text
stringlengths
10
2.72M
package com.nisira.view.Activity; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.support.design.widget.TextInputEditText; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.transition.Slide; import android.transition.TransitionInflater; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.getbase.floatingactionbutton.FloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import com.google.gson.Gson; import com.nisira.core.dao.DordenservicioclienteDao; import com.nisira.core.dao.Personal_servicioDao; import com.nisira.core.entity.Clieprov; import com.nisira.core.entity.DatosClieProvFree; import com.nisira.core.entity.Dordenserviciocliente; import com.nisira.core.entity.EstructClieProvFree; import com.nisira.core.entity.Ordenserviciocliente; import com.nisira.core.entity.Personal_servicio; import com.nisira.core.interfaces.FragmentNisira; import com.nisira.core.service.ConsumerService; import com.nisira.gcalderon.policesecurity.R; import com.nisira.view.Adapter.Adapter_edt_DOrdenServicio; import com.nisira.view.Adapter.Adapter_edt_DOrdenServicio_vehiculo; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; public class edt_OrdenServicio_Fragment extends FragmentNisira { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String OPCION = "param1"; private static final String ANTERIOR = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private TextInputEditText txt_documento; private TextInputEditText txt_cliente; private TextInputEditText txt_nromanual; private TextInputEditText txt_nrocont; private TextInputEditText txt_nroprecinto; private TextInputEditText txt_nroservicio; private TextView txt_fecha; private TextView txt_estado; private FloatingActionsMenu multiple_fab; private FloatingActionButton fab_modificar; List<Dordenserviciocliente> lstordenserviciocliente = new ArrayList<>(); DordenservicioclienteDao DordenservicioclienteDao; public int item_tabla_syncrodoc; private RecyclerView recyclerView; private RecyclerView.Adapter adapter; private RecyclerView.LayoutManager lManager; private Ordenserviciocliente ordenserviciocliente; public edt_OrdenServicio_Fragment() { // Required empty public constructor } // TODO: Rename and change types and number of parameters public static edt_OrdenServicio_Fragment newInstance(String param1, String param2) { edt_OrdenServicio_Fragment fragment = new edt_OrdenServicio_Fragment(); Bundle args = new Bundle(); args.putString(OPCION, param1); args.putString(ANTERIOR, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(OPCION); mParam2 = getArguments().getString(ANTERIOR); ordenserviciocliente = (Ordenserviciocliente) getArguments().getSerializable("OrdenServicio"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_edt__dorden_servicio, container, false); animacionEntrada(); txt_documento = (TextInputEditText)view.findViewById(R.id.txt_documento); txt_cliente = (TextInputEditText)view.findViewById(R.id.txt_ordenservicio); txt_nrocont = (TextInputEditText)view.findViewById(R.id.txt_nrocont); txt_nromanual = (TextInputEditText)view.findViewById(R.id.txt_nromanual); txt_nroprecinto = (TextInputEditText)view.findViewById(R.id.txt_nroprecinto); txt_nroservicio = (TextInputEditText)view.findViewById(R.id.txt_nroservicio); txt_fecha = (TextView)view.findViewById(R.id.txt_fecha); txt_estado = (TextView)view.findViewById(R.id.txt_estado); recyclerView = (RecyclerView)view.findViewById(R.id.recycler_os); multiple_fab = (FloatingActionsMenu) view.findViewById(R.id.multiple_fab); fab_modificar = (FloatingActionButton)view.findViewById(R.id.fab_modificar); LlenarCampos(); Listeners(); return view; } public void animacionEntrada(){ Slide slide = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { slide = (Slide) TransitionInflater.from(getContext()).inflateTransition(R.transition.activity_slide); setExitTransition(slide); setEnterTransition(slide); } } public void LlenarCampos(){ TextView view = (TextView) getActivity().findViewById(R.id.campo_titulo2); view.setText(getString(R.string.edt_OrdenServicio)); txt_nrocont.setText(ordenserviciocliente.getNrocontenedor()); txt_nromanual.setText(ordenserviciocliente.getNromanual()); txt_nroprecinto.setText(ordenserviciocliente.getNroprecinto()); txt_nroservicio.setText(ordenserviciocliente.getNro_oservicio()); txt_documento.setText(ordenserviciocliente.getIddocumento()+"-"+ ordenserviciocliente.getSerie()+ "-"+ ordenserviciocliente.getNumero()); txt_documento.setHint("Documento: "); //txt_cliente.setText(ordenserviciocliente.getCliente()); txt_cliente.setText(ordenserviciocliente.getRazonsocial()); txt_cliente.setHint("Cliente:"); SimpleDateFormat sm = new SimpleDateFormat("dd-MM-yyyy"); String strDate = sm.format(ordenserviciocliente.getFecha()); txt_fecha.setText(strDate); String estado = ordenserviciocliente.getIdestado(); if(estado.equals("PE")){ txt_estado.setText("Pendiente"); } recyclerView.setHasFixedSize(true); lManager = new LinearLayoutManager(getContext()); recyclerView.setLayoutManager(lManager); DordenservicioclienteDao = new DordenservicioclienteDao(); try { lstordenserviciocliente = DordenservicioclienteDao.ListarxOrdenServicio(ordenserviciocliente); switch (mParam1){ case "Asignacion Personal": case "Registro Hora": adapter = new Adapter_edt_DOrdenServicio(mParam1,lstordenserviciocliente,getFragmentManager(),ordenserviciocliente); recyclerView.setAdapter(adapter); multiple_fab.setVisibility(View.GONE); break; case "Registro Vehiculo": // adapter = new Adapter_edt_DOrdenServicio_vehiculo(mParam1,lstordenserviciocliente,getFragmentManager(),ordenserviciocliente); adapter = new Adapter_edt_DOrdenServicio(mParam1,lstordenserviciocliente,getFragmentManager(),ordenserviciocliente); recyclerView.setAdapter(adapter); multiple_fab.setVisibility(View.VISIBLE); break; } } catch (Exception e) { e.printStackTrace(); } } public void Listeners(){ fab_modificar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (int i = 0; i < lstordenserviciocliente.size(); i++) { if (lstordenserviciocliente.get(i).isSeleccion()) { Personal_servicioDao daop = new Personal_servicioDao(); Personal_servicio personal_servicio = null; try { personal_servicio = daop.listarxDordenservicio(lstordenserviciocliente.get(i)).get(0); } catch (Exception e) { e.printStackTrace(); } Fragment fragment = mnt_PersonalServicio_Fragment.newInstance(OPCION, "Modificar"); Bundle bundle = fragment.getArguments(); bundle.putSerializable("OrdenServicio", ordenserviciocliente); bundle.putSerializable("DOrdenServicio",lstordenserviciocliente.get(i)); bundle.putSerializable("PersonalServicio",personal_servicio); fragment.setArguments(bundle); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.main_content, fragment, "NewFragmentTag"); ft.addToBackStack(null); ft.commit(); } } } }); } }
package com.app.upworktest.models; import java.util.List; public class QuizQuestion { public String questionText; public int correctAnswerIndex; public float timestamp; public float timecap; public List<QuizAnswer> answers; public int userAnswerIndex = -1; }
package com.dipanshu.app.observabletestproject.ui.activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import com.dipanshu.app.observabletestproject.R; import com.dipanshu.app.observabletestproject.model.Posts; import com.dipanshu.app.observabletestproject.util.Utility; import java.util.Timer; import java.util.TimerTask; /** * Created by Dipanshu on 24-12-2017. * * In this activity I am using @Timer class in the ui thread to update the spent time in every minute. */ public class PostDetailActivityThree extends AppCompatActivity { private TextView text_title; private TextView text_description; private TextView text_timing; private long postDate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_post_detail); text_title = findViewById(R.id.text_title); text_description = findViewById(R.id.text_description); text_timing = findViewById(R.id.text_timing); showPostDetails(); } private void showPostDetails() { Bundle bundle = getIntent().getExtras(); Posts posts = bundle.getParcelable("POST"); String title = posts.getTitle(); String description = posts.getDescription(); String timestamp = posts.getTimestamp(); text_title.setText(title); text_description.setText(description); postDate = Utility.timeInMillis(timestamp); text_timing.setText(Utility.getDateDifference(postDate)); } public void onResume(){ super.onResume(); try { Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { Log.e("Clock","Time Updated"); text_timing.setText(Utility.getDateDifference(postDate)); } }); } }; timer.schedule(timerTask, 30000, 30000); } catch (IllegalStateException e){ Log.i("Clock", "resume error"); } } }
package weebloog; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import static com.googlecode.objectify.ObjectifyService.ofy; public class BlogServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String title = req.getParameter("title"); String post = req.getParameter("post"); BlogPost blogpost = new BlogPost(user, title, post); ofy().save().entity(blogpost).now(); resp.sendRedirect("/"); } }
package automation.enums; public enum Browser { CHROME("77"), // FIREFOX("78"), // IE("993"), // OPERA("9.9.3"); private String version; Browser(String version) { this.version = version; } public String getVersion() { return version; } }
package gina.nikol.qnr.demo.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import gina.nikol.qnr.demo.entity.Employee; @Repository public class EmployeeDAOImpl implements EmployeeDAO { // need to inject the session factory @Autowired private SessionFactory sessionFactory; @Override @Transactional public List<Employee> getEmployees() { Session currentSession = sessionFactory.getCurrentSession(); Query<Employee> query = currentSession.createQuery("from Employee ORDER BY lastName", Employee.class); List<Employee> employees = query.getResultList(); return employees; } }
package com.esum.appframework.struts.actionform; import java.util.ArrayList; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import com.esum.appframework.common.UtilCommon; public class ListUtilForm extends BeanUtilForm { public void setValue(Object bean, String name, Object value) { } public String getValue(String name) { return null; } public void reset(ActionMapping mapping, HttpServletRequest request) { ArrayList list = new ArrayList(); String[][] result = getParameters(request); if (result == null) { System.out.println("Error : getParameters();"); } String parameter = mapping.getParameter(); int parameterNumber = 0; if (result != null) { String value = (String)result[0][1]; if (value != null && value.length() > 0) { String[] splitValue = UtilCommon.split(value, "|"); parameterNumber = splitValue.length; } } for (int number = 0; number < parameterNumber; number++) { Object obj = null; if (parameter != null && !parameter.equals("")) { obj = newInstance(parameter); } if (obj != null) { obj = setForms(number, result, obj); if (obj == null) { System.out.println("Error : setForms();"); } } list.add(number, obj); } setBean(list); } protected String[][] getParameters(HttpServletRequest request) { Enumeration enumData = request.getParameterNames(); if (enumData == null) return null; ArrayList parameterName = new ArrayList(); ArrayList parameterValue = new ArrayList(); int parameterMax = 0; int maxCount = 0; int i = 0; while(enumData.hasMoreElements()) { String name = (String)enumData.nextElement(); String value = request.getParameter(name); if (value != null && value.length() > 0) { parameterName.add(i, name); parameterValue.add(i, value); String[] splitValue = UtilCommon.split(value, "|"); int parameterNumber = splitValue.length; if (parameterNumber > parameterMax) { parameterMax = parameterNumber; maxCount = 1; } else if (parameterNumber == parameterMax) { maxCount++; } i++; } } String[][] parameters = new String[maxCount][2]; int j = 0; for (int k = 0; k < parameterName.size(); k++) { String value = (String)parameterValue.get(k); String[] splitValue = UtilCommon.split(value, "|"); if (splitValue.length == parameterMax) { parameters[j][0] = (String)parameterName.get(k); parameters[j][1] = (String)parameterValue.get(k); j++; } } return parameters; } protected Object setForms(int number, String[][] parameters, Object obj) { for (int i = 0; i < parameters.length; i++) { try { String name = (String)parameters[i][0]; String value = (String)parameters[i][1]; String[] splitValue = UtilCommon.split(value, "|"); //System.out.println("name==="+name+", value==="+value+ ", splitValue[number]==="+splitValue[number]); beanUtilsBean.setProperty(obj, name, splitValue[number]); } catch(Exception e) { //return null; } } return obj; } public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); return (errors); } }
package com.example.armstest.controller; import com.example.armstest.data.DeviceNameRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/deviceName") public class DeviceController { private DeviceNameRepo deviceNameRepo; @Autowired public DeviceController(DeviceNameRepo deviceNameRepo) { this.deviceNameRepo = deviceNameRepo; } @GetMapping public String deviceNameController(Model model){ model.addAttribute("deviceC",deviceNameRepo.findAll()); return "deviceName"; } }
package com.cbsystematics.edu.internet_shop.entity; public enum RoleEnum { USER(new Role("User")), ADMIN(new Role("Admin")), MODERATOR(new Role("Moderator")); private Role role; RoleEnum(Role role) { this.role = role; } public Role getRole() { return role; } }
package u1l; import robocode.*; import java.awt.Color; import static robocode.util.Utils.normalRelativeAngleDegrees; import robocode.RobotStatus; import java.awt.geom.Point2D; // API help : http://robocode.sourceforge.net/docs/robocode/robocode/Robot.html /** * ProtoSpencerTronV4 - a robot by Carl Adrian P. Castueras and Mary Aracelli S. Basbas * Demonstrates mode shifting */ public class ProtoSpencerTronV4 extends AdvancedRobot { private AdvancedEnemyBot enemy = new AdvancedEnemyBot(); private byte moveDirection = 1; private int wallMargin = 60; private int targetOffset = 9; private double targetTurn; private int mode; private int strafTime; private final int CLOSE_RANGE = 0; private final int BERSERK = 1; private final int CHASER = 2; /** * -----------------MODES--------------------- * CLOSE RANGE * ->designed to close-in to an enemy while moving side-to-side * ->priority is avoiding enemy shots while tracking and shooting an enemy * CHASER * ->designed to chase a faraway enemy and shoot with predictive firing * ->priority is following an enemy to get close enough while shooting */ /** * run: ProtoSpencerTronV4's default behavior */ public void run() { //default mode is close range this.mode = CLOSE_RANGE; setBodyColor(Color.green); setGunColor(Color.yellow); setRadarColor(Color.white); setBulletColor(Color.cyan); setScanColor(Color.cyan); //custom event declarations start addCustomEvent(new Condition("low_health") { public boolean test() { if(getEnergy() < 30) { return true; } else return false; } }); addCustomEvent(new Condition("long_range_enemy"){ public boolean test(){ if(enemy.getDistance() > getBattleFieldWidth()/2) { return true; } else return false; } }); addCustomEvent(new Condition("short_range_enemy"){ public boolean test(){ if(enemy.getDistance() < getBattleFieldWidth()/16) { return true; } else return false; } }); //custom event declarations start //make the radar and gun move independent of the robot's body turn setAdjustRadarForRobotTurn(true); setAdjustGunForRobotTurn(true); enemy.reset(); // Robot main loop while(true) { //keep spinning the radar to always be updated of the enemies around setTurnRadarRightRadians(Double.POSITIVE_INFINITY); doMove(); execute(); } } /** * onScannedRobot: What to do when you see another robot */ public void onScannedRobot(ScannedRobotEvent e) { if(enemy.none() || //track a closer enemy e.getDistance() < enemy.getDistance() || //continue tracking the current enemy e.getName().equals(enemy.getName()) ){ enemy.update(e,this); } switch(this.mode) { case CLOSE_RANGE: { //a gun tracking algorithm based on Track Fire double absoluteBearing = getHeading() + enemy.getBearing(); double gunTurn = normalRelativeAngleDegrees(absoluteBearing - getGunHeading()); //use an offset to make up for any change caused by body movement gunTurn -= (targetOffset*moveDirection); //turn the gun to an approximation of where the enemy is setTurnGunRight(gunTurn); //always turn 90 degrees relative to the enemy for ease of avoiding enemy shots targetTurn = enemy.getBearing() + 90; //get closer to the enemy by adding positive or negative 45 degrees to turning angle targetTurn -= (45*moveDirection); setTurnRight(targetTurn); //fire only if the gun is not hot and if the gun is relatively close to the enemy if(getGunHeat() == 0 && Math.abs(getGunTurnRemaining()) < 10) { //set firepower to change depending on how close the enemy is //farther -> lower firepower ; closer -> higher firepower setFire(Math.min(400 / enemy.getDistance(),3)); } break; }//end case CLOSE_RANGE case CHASER: { // calculate firepower based on distance double firePower = Math.min(500 / enemy.getDistance(), 3); // calculate speed of bullet double bulletSpeed = 20 - firePower * 3; // distance = rate * time, solved for time long time = (long)(enemy.getDistance() / bulletSpeed); // calculate gun turn to predicted x,y location double futureX = enemy.getFutureX(time); double futureY = enemy.getFutureY(time); double absDeg = absoluteBearing(getX(), getY(), futureX, futureY); // turn the gun to the predicted x,y location setTurnGunRight(normalizeBearing(absDeg - getGunHeading())); //chase the enemy by charging straight into it targetTurn = enemy.getBearing(); setTurnRight(targetTurn); //fire only if the gun is not hot and if the gun is relatively close to the enemy if(getGunHeat() == 0 && Math.abs(getGunTurnRemaining()) < 10) { //set firepower to change depending on how close the enemy is //farther -> lower firepower ; closer -> higher firepower setFire(Math.min(400 / enemy.getDistance(),3)); } break; } case BERSERK: { double absoluteBearing = getHeading() + enemy.getBearing(); double gunTurn = normalRelativeAngleDegrees(absoluteBearing - getGunHeading()); //use an offset to make up for any change caused by body movement gunTurn -= (targetOffset*moveDirection); //turn the gun to an approximation of where the enemy is setTurnGunRight(gunTurn); //chase the enemy by charging straight into it targetTurn = enemy.getBearing(); setTurnRight(targetTurn); break; } } } /** * onHitByBullet: What to do when you're hit by a bullet */ public void onHitByBullet(HitByBulletEvent e) { } public void onHitRobot(HitRobotEvent e){ if(this.mode == BERSERK){ } } /** * onHitWall: What to do when you hit a wall */ public void onHitWall(HitWallEvent e) { // Replace the next line with any behavior you would like moveDirection *= -1; setAhead(20 * moveDirection); } public void doMove(){ if(this.getVelocity() == 0){ //moveDirection *= -1; } if(this.mode == CLOSE_RANGE){ strafTime = 30; } else if(this.mode == CHASER){ strafTime = 1000; } else if(this.mode == BERSERK){ strafTime = 10000; } //move in one direction for 30 ticks and then switch direction (strafing) //NOTE : higher strafing time (e.g 60-90)-> better chasing but higher chance to hit walls // smaller strafing time (e.g 30-40) -> lower chance to hit walls but has bad chasing // very small strafing time (0-20) -> prone to ramming and point-blank shots if(getTime() % strafTime == 0){ moveDirection *= -1; } setAhead(100 * moveDirection); } public void onRobotDeath(RobotDeathEvent e){ if(e.getName().equals(enemy.getName())){ enemy.reset(); } } double normalizeBearing(double angle){ while(angle > 180) angle -= 360; while(angle < -180) angle += 360; return angle; } //computes the absolute bearing between two points (from http://mark.random-article.com/weber/java/robocode/lesson4.html) double absoluteBearing(double x1, double y1, double x2, double y2) { double xo = x2-x1; double yo = y2-y1; double hyp = Point2D.distance(x1, y1, x2, y2); double arcSin = Math.toDegrees(Math.asin(xo / hyp)); double bearing = 0; if (xo > 0 && yo > 0) { // both pos: lower-Left bearing = arcSin; } else if (xo < 0 && yo > 0) { // x neg, y pos: lower-right bearing = 360 + arcSin; // arcsin is negative here, actuall 360 - ang } else if (xo > 0 && yo < 0) { // x pos, y neg: upper-left bearing = 180 - arcSin; } else if (xo < 0 && yo < 0) { // both neg: upper-right bearing = 180 - arcSin; // arcsin is negative here, actually 180 + ang } return bearing; } public void onCustomEvent(CustomEvent e){ //mode shifter events start if(e.getCondition().getName().equals("low_health")) { if(mode != BERSERK) { //mode = BERSERK; //setBodyColor(Color.red); } } if(e.getCondition().getName().equals("long_range_enemy")) { if(mode != CHASER) { mode = CHASER; setBodyColor(Color.blue); } } if(e.getCondition().getName().equals("short_range_enemy")) { if(mode != CLOSE_RANGE) { mode = CLOSE_RANGE; setBodyColor(Color.green); } } //mode shifter events end } } //idea of enemy bot based on tutorial http://mark.random-article.com/weber/java/robocode/ class EnemyBot { private double bearing; private double distance; private double energy; private double heading; private double velocity; private String name; public EnemyBot() { reset(); } public void reset() { this.bearing = 0.0; this.distance = 0.0; this.energy = 0.0; this.heading = 0.0; this.velocity = 0.0; this.name = ""; } public void update(ScannedRobotEvent e) { this.bearing = e.getBearing(); this.distance = e.getDistance(); this.energy = e.getEnergy(); this.heading = e.getHeading(); this.velocity = e.getVelocity(); this.name = e.getName(); } public boolean none() { if(this.name.equals("")) return true; else return false; } //getter-setter section start public double getBearing() { return this.bearing; } public void setBearing(double newBearing) { this.bearing = newBearing; } public double getDistance() { return this.distance; } public void setDistance(double newDistance) { this.distance = newDistance; } public double getEnergy() { return this.energy; } public void setEnergy(double newEnergy) { this.energy = newEnergy; } public double getHeading() { return this.heading; } public void setHeading(double newHeading) { this.heading = newHeading; } public double getVelocity() { return this.velocity; } public void setVelocity(double newVelocity) { this.velocity = newVelocity; } public String getName() { return this.name; } public void setName(String newName) { this.name = newName; } //getter-setter section end } //Advanced EnemyBot class from http://mark.random-article.com/weber/java/ch5/lab4.html class AdvancedEnemyBot extends EnemyBot { double x; double y; public AdvancedEnemyBot() { this.reset(); } public void reset() { super.reset(); this.x = 0; this.y = 0; } public void update(ScannedRobotEvent e, Robot robot) { super.update(e); double absBearingDeg = (robot.getHeading() + e.getBearing()); if (absBearingDeg < 0) absBearingDeg += 360; // yes, you use the _sine_ to get the X value because 0 deg is North x = robot.getX() + Math.sin(Math.toRadians(absBearingDeg)) * e.getDistance(); // yes, you use the _cosine_ to get the Y value because 0 deg is North y = robot.getY() + Math.cos(Math.toRadians(absBearingDeg)) * e.getDistance(); } public double getFutureX(long when) { return x + Math.sin(Math.toRadians(getHeading())) * getVelocity() * when; } public double getFutureY(long when) { return y + Math.cos(Math.toRadians(getHeading())) * getVelocity() * when; } //getter-setter section start public double getX() { return this.x; } public double getY() { return this.y; } //getter-setter section end }
package uz.pdp.lesson5task1.payload; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class TurniketDto { private Integer companyId; private String ownerEmail; }
package com.mygdx.game; import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.annotations.Wire; import com.artemis.utils.IntBag; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.ai.steer.Limiter; import com.badlogic.gdx.ai.steer.Steerable; import com.badlogic.gdx.ai.steer.SteeringAcceleration; import com.badlogic.gdx.ai.steer.SteeringBehavior; import com.badlogic.gdx.ai.steer.behaviors.*; import com.badlogic.gdx.ai.steer.proximities.RadiusProximity; import com.badlogic.gdx.ai.steer.utils.Path; import com.badlogic.gdx.ai.steer.utils.paths.LinePath; import com.badlogic.gdx.ai.utils.Location; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.Field; import com.badlogic.gdx.utils.reflect.ReflectionException; import com.mygdx.game.components.AI; import com.mygdx.game.components.Agent; import com.mygdx.game.components.AgentLocation; import com.mygdx.game.components.Transform; /** * Created by EvilEntity on 24/02/2017. */ public class Agents extends IteratingInputSystem { private static final String TAG = Agents.class.getSimpleName(); protected ComponentMapper<Transform> mTransform; protected ComponentMapper<AI> mAI; protected ComponentMapper<Agent> mAgent; @Wire Map map; @Wire Pathfinding pf; @Wire ShapeRenderer shapes; Array<Agent> activeAgents = new Array<>(); public Agents () { super(Aspect.all(Transform.class, AI.class, Agent.class)); } @Override protected void initialize () { } boolean paused; float delta; float deltaScale = 1; @Override protected void begin () { shapes.setProjectionMatrix(camera.combined); if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){ paused = !paused; } if (paused) { delta = 0; } else { delta = world.delta * deltaScale; } } @Override protected void inserted (int entityId) { activeAgents.add(mAgent.get(entityId)); } private Vector2 v2_1 = new Vector2(); private Vector2 v2_2 = new Vector2(); private final SteeringAcceleration<Vector2> steeringOutput = new SteeringAcceleration<Vector2>(new Vector2()); @Override protected void process (int entityId) { Transform tf = mTransform.get(entityId); AI ai = mAI.get(entityId); Agent agent = mAgent.get(entityId); if (ai.steering != null) { // Calculate steering acceleration ai.steering.calculateSteering(steeringOutput); agent.getPosition().mulAdd(agent.getLinearVelocity(), delta); agent.getLinearVelocity().mulAdd(steeringOutput.linear, delta).limit(agent.getMaxLinearSpeed()); // If we haven't got any velocity, then we can do nothing. if (!agent.getLinearVelocity().isZero(agent.getZeroLinearSpeedThreshold()) && ai.path != null) { float orientation = vectorToAngle(agent.getLinearVelocity()); orientation = Step.of(orientation * MathUtils.radDeg).angle; agent.targetOrientation = orientation * MathUtils.degRad; // Gdx.app.log(TAG, "target " + (orientation)); } if (!MathUtils.isZero(agent.getAngularVelocity()) || !MathUtils.isZero(steeringOutput.angular)) { agent.setOrientation(agent.getOrientation() + (agent.getAngularVelocity() * delta)); agent.setAngularVelocity(agent.getAngularVelocity() * 0.98f + steeringOutput.angular * delta); } tf.xy(agent.getPosition().x, agent.getPosition().y); } if (agent.doorTimer > 0) { agent.doorTimer -= delta; if (agent.doorTimer < 0) agent.doorTimer = 0; } // TODO handle size shapes.begin(ShapeRenderer.ShapeType.Filled); if (ai.path != null) { LinePath<Vector2> path = (LinePath<Vector2>)ai.path; Array<LinePath.Segment<Vector2>> segments = path.getSegments(); float step = 1f /(segments.size-1); float c = 0; for (int i = 0; i < segments.size; i++) { shapes.setColor(c, c, c, 1); if (i%2 == 0) { shapes.setColor(Color.MAGENTA); } else { shapes.setColor(Color.CYAN); } LinePath.Segment<Vector2> segment = segments.get(i); shapes.rectLine(segment.getBegin().x, segment.getBegin().y, segment.getEnd().x, segment.getEnd().y, .075f); c += step; } } if (selectedId == entityId) { shapes.setColor(Color.FIREBRICK); float size = (agent.clearance)/2f-.3f; shapes.rect(tf.x - size, tf.y -size, size, size, size * 2, size * 2, 1, 1, agent.getOrientation() * MathUtils.radDeg ); } v2_1.set(0, 1).rotateRad(agent.getOrientation()).limit(.3f); v2_2.set(1, 1).rotateRad(agent.targetOrientation).limit(.5f); switch (agent.clearance) { case 1: { shapes.setColor(Color.LIGHT_GRAY); }break; case 2: { shapes.setColor(Color.DARK_GRAY); }break; case 3: { shapes.setColor(Color.BLACK); }break; } float size = (agent.clearance)/2f-.4f; shapes.rect(tf.x - size, tf.y -size, size, size, size * 2, size * 2, 1, 1, agent.getOrientation() * MathUtils.radDeg ); // shapes.setColor(Color.MAGENTA); // shapes.rectLine(tf.x, tf.y, tf.x + v2_2.x, tf.y + v2_2.y, .15f); // shapes.circle(tf.x, tf.y, size, 16); shapes.setColor(Color.DARK_GRAY); shapes.rectLine(tf.x, tf.y, tf.x + v2_1.x, tf.y + v2_1.y, .1f); shapes.end(); shapes.begin(ShapeRenderer.ShapeType.Line); shapes.setColor(Color.LIGHT_GRAY); shapes.rect(tf.gx - .5f, tf.gy - .5f, agent.width, agent.height); if (ai.steering != null) { drawDebug(tf, ai.steering); } shapes.end(); } @Override protected void removed (int entityId) { activeAgents.removeValue(mAgent.get(entityId), true); } private void drawDebug (Transform tf, SteeringBehavior<Vector2> behavior) { if (behavior instanceof MyBlendedSteering) { MyBlendedSteering blendedSteering = (MyBlendedSteering)behavior; for (int i = 0; i < blendedSteering.getCount(); i++) { drawDebug(tf, blendedSteering.get(i).getBehavior()); } } else if (behavior instanceof FollowPath) { FollowPath<Vector2, LinePath.LinePathParam> fp = (FollowPath<Vector2, LinePath.LinePathParam>)behavior; shapes.setColor(Color.CYAN); Vector2 tp = fp.getInternalTargetPosition(); shapes.circle(tp.x, tp.y, .2f, 16); } else if (behavior instanceof LookWhereYouAreGoing) { LookWhereYouAreGoing lwyag = (LookWhereYouAreGoing)behavior; } else if (behavior instanceof CollisionAvoidance) { CollisionAvoidance ca = (CollisionAvoidance)behavior; // ffs private things :/ try { Field field = ClassReflection.getDeclaredField(CollisionAvoidance.class, "firstNeighbor"); field.setAccessible(true); Steerable<Vector2> firstNeighbor = (Steerable<Vector2>)field.get(ca); field = ClassReflection.getDeclaredField(CollisionAvoidance.class, "firstMinSeparation"); field.setAccessible(true); float firstMinSeparation = (Float)field.get(ca); field = ClassReflection.getDeclaredField(CollisionAvoidance.class, "firstDistance"); field.setAccessible(true); float firstDistance = (Float)field.get(ca); field = ClassReflection.getDeclaredField(CollisionAvoidance.class, "firstRelativePosition"); field.setAccessible(true); Vector2 firstRelativePosition = (Vector2)field.get(ca); field = ClassReflection.getDeclaredField(CollisionAvoidance.class, "firstRelativeVelocity"); field.setAccessible(true); Vector2 firstRelativeVelocity = (Vector2)field.get(ca); field = ClassReflection.getDeclaredField(CollisionAvoidance.class, "relativePosition"); field.setAccessible(true); Vector2 relativePosition = (Vector2)field.get(ca); shapes.setColor(Color.RED); if (firstNeighbor != null) { Vector2 fp = firstNeighbor.getPosition(); shapes.circle(fp.x, fp.y, .3f, 16); shapes.circle(fp.x, fp.y, .35f, 16); shapes.circle(fp.x, fp.y, .36f, 16); } shapes.setColor(Color.MAGENTA); if (relativePosition != null) { v2_1.set(relativePosition).scl(.1f); shapes.line(tf.x, tf.y, tf.x + v2_1.x, tf.y + v2_1.y); } } catch (ReflectionException e) { e.printStackTrace(); } RadiusProximity proximity = (RadiusProximity)ca.getProximity(); float radius = proximity.getRadius(); shapes.setColor(Color.ORANGE); shapes.circle(tf.x, tf.y, radius, 32); } else if (behavior instanceof PriorityDoorArrive) { PriorityDoorArrive pfp = (PriorityDoorArrive)behavior; shapes.setColor(Color.GOLD); Vector2 tp = pfp.getInternalTargetPosition(); shapes.circle(tp.x, tp.y, .15f, 16); shapes.setColor(Color.MAGENTA); Vector2 ap = pfp.getArriveTargetPosition(); shapes.circle(ap.x, ap.y, .15f, 16); } else if (behavior instanceof Arrive) { Arrive arrive = (Arrive)behavior; } else if (behavior instanceof ReachOrientation) { ReachOrientation ro = (ReachOrientation)behavior; } else if (behavior instanceof MyArrive) { MyArrive arrive = (MyArrive)behavior; } else if (behavior instanceof PriorityBlendedSteering) { PriorityBlendedSteering pbs = (PriorityBlendedSteering)behavior; for (int i = 0; i < pbs.getCount(); i++) { drawDebug(tf, pbs.get(i).getBehavior()); } } else if (behavior instanceof MyPrioritySteering) { MyPrioritySteering ps = (MyPrioritySteering)behavior; for (int i = 0; i < ps.getCount(); i++) { drawDebug(tf, ps.get(i)); } } else if (behavior instanceof PrioritySteering) { PrioritySteering ps = (PrioritySteering)behavior; } else { Gdx.app.log(TAG, "Not supported behaviour type " + behavior.getClass()); } } int selectedId = -1; @Override protected void touchDownLeft (float x, float y) { selectedId = agentAt(x, y); } @Override protected void touchDownRight (float x, float y) { if (selectedId == -1) return; // go to spot? // find path Transform tf = mTransform.get(selectedId); final Agent agent = mAgent.get(selectedId); float offset = (agent.clearance-1f)/2f; pf.findPath(Map.grid(tf.gx - offset), Map.grid(tf.gy - offset), Map.grid(x - offset), Map.grid(y-offset), agent.clearance, new Pathfinding.PFCallback() { @Override public void found (Pathfinding.NodePath path) { final AI ai = mAI.get(selectedId); ai.path = convertPath(path); ai.followPath.update(ai.path, path); ai.priorityPath.update(ai.path, path); ai.steering = ai.steeringPath; } @Override public void notFound () { AI ai = mAI.get(selectedId); ai.path = null; Gdx.app.log(TAG, "path not found"); } }); // follow path } private void trySpawnAt (int x, int y, int size) { Map.Node at = map.at(x, y); if (at == null || at.type == Map.WL) return; IntBag entityIds = getEntityIds(); for (int i = 0; i < entityIds.size(); i++) { Transform tf = mTransform.get(entityIds.get(i)); if (tf.gx == x && tf.gy == y) return; } int agentId = world.create(); Transform tf = mTransform.create(agentId); tf.xy(x, y); final Agent agent = mAgent.create(agentId); agent.setMaxAngularAcceleration(360 * MathUtils.degreesToRadians); agent.setMaxAngularSpeed(90 * MathUtils.degreesToRadians); agent.setMaxLinearAcceleration(20); agent.setMaxLinearSpeed(2); agent.boundingRadius = .3f; agent.getPosition().set(tf.x, tf.y); agent.clearance = size; final AI ai = mAI.create(agentId); ai.target.getPosition().set(agent.getPosition()); ai.target.setOrientation(agent.getOrientation()); // ai.arrive = arrive; PrioritySteering<Vector2> priorityIdle = new PrioritySteering<>(agent); MyBlendedSteering steeringIdle = new MyBlendedSteering(agent); // radius must be large enough when compared to agents bounding radiys CollisionAvoidance<Vector2> avoidance = new CollisionAvoidance<>(agent, new RadiusProximity<>(agent, activeAgents, .2f)); // ai.avoidance = avoidance; priorityIdle.add(avoidance); ReachOrientation<Vector2> reachOrientation = new ReachOrientation<>(agent); reachOrientation.setTarget(ai.target); reachOrientation.setAlignTolerance(1 * MathUtils.degRad); reachOrientation.setDecelerationRadius(MathUtils.PI / 4); reachOrientation.setTimeToTarget(.15f); steeringIdle.add(reachOrientation, 1); Arrive<Vector2> arrive = new Arrive<>(agent, ai.target); arrive.setTimeToTarget(.15f); arrive.setArrivalTolerance(.01f); arrive.setDecelerationRadius(.66f); steeringIdle.add(arrive, 1); priorityIdle.add(steeringIdle); ai.steeringIdle = priorityIdle; // TODO we want custom priority steering, that will stop following path if blocked tile is encountered MyPrioritySteering<Vector2> priorityPath = new MyPrioritySteering<>(agent); PriorityBlendedSteering priorityBlendedPath = new PriorityBlendedSteering(agent); // TODO use follow path, with fairly large path offset so we are about 2 tiles ahead of actual position // if out target is at locked door, we want to arrive to previous waypoint until the door is open // hit the map to check type, store if door was hit, use agents timer for debug PriorityDoorArrive priorityDoorArrive = new PriorityDoorArrive(agent); priorityDoorArrive.setTimeToTarget(.15f); priorityDoorArrive.setArrivalTolerance(.01f); priorityDoorArrive.setDecelerationRadius(.66f); priorityDoorArrive.setPathOffset(.5f * size + .8f); priorityDoorArrive.setPredictionTime(0); priorityDoorArrive.setMap(map); priorityDoorArrive.setAlignTolerance(1 * MathUtils.degRad); priorityDoorArrive.setFaceDecelerationRadius(MathUtils.PI / 4); priorityDoorArrive.setFaceTimeToTarget(.15f); ai.priorityPath = priorityDoorArrive; priorityBlendedPath.add(priorityDoorArrive, 1); priorityPath.add(priorityBlendedPath); MyBlendedSteering blendedPath = new MyBlendedSteering(agent); blendedPath.add(avoidance, 1); LookWhereYouAreGoing<Vector2> lookWhereYouAreGoing = new LookWhereYouAreGoing<>(agent); lookWhereYouAreGoing.setAlignTolerance(1 * MathUtils.degRad); lookWhereYouAreGoing.setDecelerationRadius(MathUtils.PI / 4); lookWhereYouAreGoing.setTimeToTarget(.15f); blendedPath.add(lookWhereYouAreGoing, 1); final MyFollowPath followPath = new MyFollowPath(agent); followPath.setCallback(new MyFollowPath.Callback() { @Override public void arrived () { Gdx.app.log(TAG, "Arrived"); Location<Vector2> location = ai.target; location.getPosition().set(agent.getPosition()); location.setOrientation(agent.targetOrientation); ai.steering = ai.steeringIdle; ai.path = null; } }); followPath .setTimeToTarget(0.15f) .setPathOffset(.3f * size) .setPredictionTime(.2f) .setArrivalTolerance(0.01f) .setArriveEnabled(true) .setDecelerationRadius(.66f); ai.followPath = followPath; blendedPath.add(followPath, 1); priorityPath.add(blendedPath); ai.steeringPath = priorityPath; } private Path<Vector2, LinePath.LinePathParam> convertPath (Pathfinding.NodePath path) { float offset = (path.clearance-1)/2f; Array<Vector2> wayPoints = new Array<>(); for (int i = 0; i < path.getCount(); i++) { Map.Node node = path.get(i); wayPoints.add(new Vector2(node.x + offset, node.y + offset)); } return new LinePath<>(wayPoints, true); } private Circle c = new Circle(); int agentAt(float x, float y) { IntBag entityIds = getEntityIds(); int[] data = entityIds.getData(); for (int i = 0; i < entityIds.size(); i++) { Transform tf = mTransform.get(data[i]); c.set(tf.x, tf.y, .4f); if (c.contains(x, y)) { return data[i]; } } return -1; } @Override public boolean keyDown (int keycode) { int x = Map.grid(tmp.x); int y = Map.grid(tmp.y); switch (keycode) { case Input.Keys.Q: { trySpawnAt(x, y, 1); } break; case Input.Keys.W: { trySpawnAt(x, y, 2); }break; case Input.Keys.E: { trySpawnAt(x, y, 3); }break; case Input.Keys.MINUS: { deltaScale = Math.max(deltaScale -.1f, 0); Gdx.app.log(TAG, "ds " + deltaScale); }break; case Input.Keys.EQUALS: { deltaScale = Math.min(deltaScale +.1f, 2); Gdx.app.log(TAG, "ds " + deltaScale); }break; case Input.Keys.NUM_0: { deltaScale = 1; Gdx.app.log(TAG, "ds " + deltaScale); }break; } return false; } public static float vectorToAngle (Vector2 vector) { return (float)Math.atan2(-vector.x, vector.y); } public static Vector2 angleToVector (Vector2 outVector, float angle) { outVector.x = -(float)Math.sin(angle); outVector.y = (float)Math.cos(angle); return outVector; } public static class MyFollowPath extends FollowPath<Vector2, LinePath.LinePathParam> { private static final LinePath<Vector2> dummy = new LinePath<>(new Array<>(new Vector2[]{new Vector2(), new Vector2(0, 1)})); private Callback callback; private Pathfinding.NodePath nodes; public MyFollowPath (Steerable<Vector2> owner, Path<Vector2, LinePath.LinePathParam> path) { super(owner, path); } public MyFollowPath (Steerable<Vector2> owner, Path<Vector2, LinePath.LinePathParam> path, float pathOffset) { super(owner, path, pathOffset); } public MyFollowPath (Steerable<Vector2> owner, Path<Vector2, LinePath.LinePathParam> path, float pathOffset, float predictionTime) { super(owner, path, pathOffset, predictionTime); } public MyFollowPath (Agent agent) { super(agent, dummy); } @Override protected SteeringAcceleration<Vector2> calculateRealSteering (SteeringAcceleration<Vector2> steering) { steering = super.calculateRealSteering(steering); if (steering.isZero() && path.getEndPoint().epsilonEquals(owner.getPosition(), 0.01f)) { if (callback != null) { callback.arrived(); } } return steering; } public MyFollowPath setCallback (Callback callback) { this.callback = callback; return this; } public void update (Path<Vector2, LinePath.LinePathParam> path, Pathfinding.NodePath nodes) { this.path = path; this.nodes = nodes; } public interface Callback { void arrived(); } } public static class MyBlendedSteering extends BlendedSteering<Vector2> { /** * Creates a {@code BlendedSteering} for the specified {@code owner}, {@code maxLinearAcceleration} and * {@code maxAngularAcceleration}. * * @param owner the owner of this behavior. */ public MyBlendedSteering (Steerable<Vector2> owner) { super(owner); } public int getCount() { return list.size; } public void setWeight(SteeringBehavior behavior, float weight) { for (BehaviorAndWeight<Vector2> behaviorAndWeight : list) { if (behaviorAndWeight.getBehavior() == behavior) { behaviorAndWeight.setWeight(weight); } } } } public static class PriorityBlendedSteering extends BlendedSteering<Vector2> implements MyPrioritySteering.PriorityOverride { protected SteeringAcceleration<Vector2> steering; boolean override; public PriorityBlendedSteering (Steerable<Vector2> owner) { super(owner); this.steering = new SteeringAcceleration<Vector2>(newVector(owner)); } public int getCount() { return list.size; } @Override protected SteeringAcceleration<Vector2> calculateRealSteering (SteeringAcceleration<Vector2> blendedSteering) { blendedSteering.setZero(); override = false; // Go through all the behaviors int len = list.size; for (int i = 0; i < len; i++) { BehaviorAndWeight<Vector2> bw = list.get(i); SteeringBehavior<Vector2> behavior = bw.getBehavior(); // Calculate the behavior's steering behavior.calculateSteering(steering); // Scale and add the steering to the accumulator blendedSteering.mulAdd(steering, bw.getWeight()); if (behavior instanceof MyPrioritySteering.PriorityOverride) { override |= ((MyPrioritySteering.PriorityOverride)behavior).override(); } } Limiter actualLimiter = getActualLimiter(); // Crop the result blendedSteering.linear.limit(actualLimiter.getMaxLinearAcceleration()); if (blendedSteering.angular > actualLimiter.getMaxAngularAcceleration()) blendedSteering.angular = actualLimiter.getMaxAngularAcceleration(); return blendedSteering; } public void setWeight(SteeringBehavior behavior, float weight) { for (BehaviorAndWeight<Vector2> behaviorAndWeight : list) { if (behaviorAndWeight.getBehavior() == behavior) { behaviorAndWeight.setWeight(weight); } } } @Override public boolean override () { return override; } } public static class MyPrioritySteering<T extends Vector<T>> extends SteeringBehavior<T> { /** The threshold of the steering acceleration magnitude below which a steering behavior is considered to have given no output. */ protected float epsilon; /** The list of steering behaviors in priority order. The first item in the list is tried first, the subsequent entries are only * considered if the first one does not return a result. */ protected Array<SteeringBehavior<T>> behaviors = new Array<SteeringBehavior<T>>(); /** The index of the behavior whose acceleration has been returned by the last evaluation of this priority steering. */ protected int selectedBehaviorIndex; /** Creates a {@code PrioritySteering} behavior for the specified owner. The threshold is set to 0.001. * @param owner the owner of this behavior */ public MyPrioritySteering (Steerable<T> owner) { this(owner, 0.001f); } /** Creates a {@code PrioritySteering} behavior for the specified owner and threshold. * @param owner the owner of this behavior * @param epsilon the threshold of the steering acceleration magnitude below which a steering behavior is considered to have * given no output */ public MyPrioritySteering (Steerable<T> owner, float epsilon) { super(owner); this.epsilon = epsilon; } /** Adds the specified behavior to the priority list. * @param behavior the behavior to add * @return this behavior for chaining. */ public MyPrioritySteering<T> add (SteeringBehavior<T> behavior) { behaviors.add(behavior); return this; } @Override protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) { // We'll need epsilon squared later. float epsilonSquared = epsilon * epsilon; // Go through the behaviors until one has a large enough acceleration int n = behaviors.size; selectedBehaviorIndex = -1; for (int i = 0; i < n; i++) { selectedBehaviorIndex = i; SteeringBehavior<T> behavior = behaviors.get(i); // Calculate the behavior's steering behavior.calculateSteering(steering); // this steering will be taken into account only if override is true if (behavior instanceof PriorityOverride) { if (((PriorityOverride)behavior).override()) { return steering; } else { continue; } } // If we're above the threshold return the current steering if (steering.calculateSquareMagnitude() > epsilonSquared) return steering; } // If we get here, it means that no behavior had a large enough acceleration, // so return the small acceleration from the final behavior or zero if there are // no behaviors in the list. return n > 0 ? steering : steering.setZero(); } /** Returns the index of the behavior whose acceleration has been returned by the last evaluation of this priority steering; -1 * otherwise. */ public int getSelectedBehaviorIndex () { return selectedBehaviorIndex; } /** Returns the threshold of the steering acceleration magnitude below which a steering behavior is considered to have given no * output. */ public float getEpsilon () { return epsilon; } /** Sets the threshold of the steering acceleration magnitude below which a steering behavior is considered to have given no * output. * @param epsilon the epsilon to set * @return this behavior for chaining. */ public MyPrioritySteering<T> setEpsilon (float epsilon) { this.epsilon = epsilon; return this; } public interface PriorityOverride { boolean override(); } // // Setters overridden in order to fix the correct return type for chaining // @Override public MyPrioritySteering<T> setOwner (Steerable<T> owner) { this.owner = owner; return this; } @Override public MyPrioritySteering<T> setEnabled (boolean enabled) { this.enabled = enabled; return this; } /** Sets the limiter of this steering behavior. However, {@code PrioritySteering} needs no limiter at all as it simply returns * the first non zero steering acceleration. * @return this behavior for chaining. */ @Override public MyPrioritySteering<T> setLimiter (Limiter limiter) { this.limiter = limiter; return this; } public int getCount() { return behaviors.size; } public SteeringBehavior<T> get (int i) { return behaviors.get(i); } } public class MyArrive<T extends Vector<T>> extends SteeringBehavior<T> implements MyPrioritySteering.PriorityOverride { /** The target to arrive to. */ protected Location<T> target; /** The tolerance for arriving at the target. It lets the owner get near enough to the target without letting small errors keep * it in motion. */ protected float arrivalTolerance; /** The radius for beginning to slow down */ protected float decelerationRadius; /** The time over which to achieve target speed */ protected float timeToTarget = 0.1f; protected boolean override; /** Creates an {@code Arrive} behavior for the specified owner. * @param owner the owner of this behavior */ public MyArrive (Steerable<T> owner) { this(owner, null); } /** Creates an {@code Arrive} behavior for the specified owner and target. * @param owner the owner of this behavior * @param target the target of this behavior */ public MyArrive (Steerable<T> owner, Location<T> target) { super(owner); this.target = target; } @Override protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) { return arrive(steering, target.getPosition()); } protected SteeringAcceleration<T> arrive (SteeringAcceleration<T> steering, T targetPosition) { if (!override) { steering.setZero(); return steering; } // Get the direction and distance to the target T toTarget = steering.linear.set(targetPosition).sub(owner.getPosition()); float distance = toTarget.len(); // Check if we are there, return no steering if (distance <= arrivalTolerance) return steering.setZero(); Limiter actualLimiter = getActualLimiter(); // Go max speed float targetSpeed = actualLimiter.getMaxLinearSpeed(); // If we are inside the slow down radius calculate a scaled speed if (distance <= decelerationRadius) targetSpeed *= distance / decelerationRadius; // Target velocity combines speed and direction T targetVelocity = toTarget.scl(targetSpeed / distance); // Optimized code for: toTarget.nor().scl(targetSpeed) // Acceleration tries to get to the target velocity without exceeding max acceleration // Notice that steering.linear and targetVelocity are the same vector targetVelocity.sub(owner.getLinearVelocity()).scl(1f / timeToTarget).limit(actualLimiter.getMaxLinearAcceleration()); // No angular acceleration steering.angular = 0f; // Output the steering return steering; } /** Returns the target to arrive to. */ public Location<T> getTarget () { return target; } /** Sets the target to arrive to. * @return this behavior for chaining. */ public MyArrive<T> setTarget (Location<T> target) { this.target = target; return this; } /** Returns the tolerance for arriving at the target. It lets the owner get near enough to the target without letting small * errors keep it in motion. */ public float getArrivalTolerance () { return arrivalTolerance; } /** Sets the tolerance for arriving at the target. It lets the owner get near enough to the target without letting small errors * keep it in motion. * @return this behavior for chaining. */ public MyArrive<T> setArrivalTolerance (float arrivalTolerance) { this.arrivalTolerance = arrivalTolerance; return this; } /** Returns the radius for beginning to slow down. */ public float getDecelerationRadius () { return decelerationRadius; } /** Sets the radius for beginning to slow down. * @return this behavior for chaining. */ public MyArrive<T> setDecelerationRadius (float decelerationRadius) { this.decelerationRadius = decelerationRadius; return this; } /** Returns the time over which to achieve target speed. */ public float getTimeToTarget () { return timeToTarget; } /** Sets the time over which to achieve target speed. * @return this behavior for chaining. */ public MyArrive<T> setTimeToTarget (float timeToTarget) { this.timeToTarget = timeToTarget; return this; } // // Setters overridden in order to fix the correct return type for chaining // @Override public MyArrive<T> setOwner (Steerable<T> owner) { this.owner = owner; return this; } @Override public MyArrive<T> setEnabled (boolean enabled) { this.enabled = enabled; return this; } /** Sets the limiter of this steering behavior. The given limiter must at least take care of the maximum linear speed and * acceleration. * @return this behavior for chaining. */ @Override public MyArrive<T> setLimiter (Limiter limiter) { this.limiter = limiter; return this; } @Override public boolean override () { return override; } } public static class PriorityDoorArrive extends Arrive<Vector2> implements MyPrioritySteering.PriorityOverride { private static final LinePath<Vector2> dummy = new LinePath<>(new Array<>(new Vector2[]{new Vector2(), new Vector2(0, 1)})); /** The distance along the path to generate the target. Can be negative if the owner has to move along the reverse direction. */ protected float pathOffset; /** The current position on the path */ protected LinePath.LinePathParam pathParam; /** The flag indicating whether to use {@link Arrive} behavior to approach the end of an open path. It defaults to {@code true}. */ protected boolean arriveEnabled; /** The time in the future to predict the owner's position. Set it to 0 for non-predictive path following. */ protected float predictionTime; private Vector2 internalTargetPosition; private Vector2 arriveTargetPosition; protected boolean override; protected Map map; protected Agent owner; private LinePath<Vector2> path; protected Face<Vector2> face; protected AgentLocation faceLocation; public PriorityDoorArrive (Agent owner) { this(owner, dummy, 0); } /** Creates a non-predictive {@code FollowPath} behavior for the specified owner and path. * @param owner the owner of this behavior * @param path the path to be followed by the owner. */ public PriorityDoorArrive (Agent owner, Path<Vector2, LinePath.LinePathParam> path) { this(owner, path, 0); } /** Creates a non-predictive {@code FollowPath} behavior for the specified owner, path and path offset. * @param owner the owner of this behavior * @param path the path to be followed by the owner * @param pathOffset the distance along the path to generate the target. Can be negative if the owner is to move along the * reverse direction. */ public PriorityDoorArrive (Agent owner, Path<Vector2, LinePath.LinePathParam> path, float pathOffset) { this(owner, path, pathOffset, 0); } /** Creates a {@code FollowPath} behavior for the specified owner, path, path offset, maximum linear acceleration and prediction * time. * @param owner the owner of this behavior * @param path the path to be followed by the owner * @param pathOffset the distance along the path to generate the target. Can be negative if the owner is to move along the * reverse direction. * @param predictionTime the time in the future to predict the owner's position. Can be 0 for non-predictive path following. */ public PriorityDoorArrive (Agent owner, Path<Vector2, LinePath.LinePathParam> path, float pathOffset, float predictionTime) { super(owner); this.path = (LinePath<Vector2>)path; this.pathParam = path.createParam(); this.pathOffset = pathOffset; this.predictionTime = predictionTime; this.owner = owner; this.arriveEnabled = true; this.internalTargetPosition = newVector(owner); this.arriveTargetPosition = newVector(owner); face = new Face<>(owner); faceLocation = new AgentLocation(); face.setTarget(faceLocation); } protected int findSegmentIndex (float targetDistance) { // NOTE only open paths if (targetDistance < 0) { // Clamp target distance to the min targetDistance = 0; } else if (targetDistance > path.getLength()) { // Clamp target distance to the max targetDistance = path.getLength(); } // Walk through lines to see on which line we are Array<LinePath.Segment<Vector2>> segments = path.getSegments(); int segmentId = -1; for (int i = 0; i < segments.size; i++) { LinePath.Segment<Vector2> segment = segments.get(i); if (segment.getCumulativeLength() >= targetDistance) { return i; } } return segmentId; } int lastAt = -1; @Override protected SteeringAcceleration<Vector2> calculateRealSteering (SteeringAcceleration<Vector2> steering) { // Predictive or non-predictive behavior? Vector2 location = (predictionTime == 0) ? // Use the current position of the owner owner.getPosition() : // Calculate the predicted future position of the owner. We're reusing steering.linear here. steering.linear.set(owner.getPosition()).mulAdd(owner.getLinearVelocity(), predictionTime); // Find the distance from the start of the path float distance = path.calculateDistance(location, pathParam); // Offset it float targetDistance = distance + pathOffset; // first we find a target thats ahead far enough path.calculateTargetPosition(internalTargetPosition, pathParam, targetDistance); Map.Node at = map.at(internalTargetPosition.x, internalTargetPosition.y); if (!override) { if (lastAt != at.index) { lastAt = at.index; Gdx.app.log(TAG, "At " + Map.typeToStr(at.type)); if (at.type == Map.DR) { // if we hit a door, we find the segment that ends in the door Array<LinePath.Segment<Vector2>> segments = path.getSegments(); int segmentIndex = findSegmentIndex(targetDistance); arriveTargetPosition.set(segments.get(segmentIndex).getBegin()); faceLocation.getPosition().set(segments.get(segmentIndex).getEnd()); // NOTE request the door to open owner.doorTimer = owner.clearance * 2; override = true; } else { override = false; arriveTargetPosition.set(0, 0); } } } if (override) { // NOTE arrive at the selected target while we wait for door to open if (owner.doorTimer > 0) { // we know face only adds angular, so we will reuse steering here face.calculateSteering(steering); // we need to store it, as arrive will override it float angular = steering.angular; arrive(steering, arriveTargetPosition); steering.angular = angular; return steering; } else { override = false; } } return steering.setZero(); } /** Returns the path to follow */ public Path<Vector2, LinePath.LinePathParam> getPath () { return path; } /** Sets the path followed by this behavior. * @param path the path to set * @return this behavior for chaining. */ public PriorityDoorArrive setPath (Path<Vector2, LinePath.LinePathParam> path) { this.path = (LinePath<Vector2>)path; return this; } /** Returns the path offset. */ public float getPathOffset () { return pathOffset; } /** Returns the flag indicating whether to use {@link Arrive} behavior to approach the end of an open path. */ public boolean isArriveEnabled () { return arriveEnabled; } /** Returns the prediction time. */ public float getPredictionTime () { return predictionTime; } /** Sets the prediction time. Set it to 0 for non-predictive path following. * @param predictionTime the predictionTime to set * @return this behavior for chaining. */ public PriorityDoorArrive setPredictionTime (float predictionTime) { this.predictionTime = predictionTime; return this; } /** Sets the flag indicating whether to use {@link Arrive} behavior to approach the end of an open path. It defaults to * {@code true}. * @param arriveEnabled the flag value to set * @return this behavior for chaining. */ public PriorityDoorArrive setArriveEnabled (boolean arriveEnabled) { this.arriveEnabled = arriveEnabled; return this; } /** Sets the path offset to generate the target. Can be negative if the owner has to move along the reverse direction. * @param pathOffset the pathOffset to set * @return this behavior for chaining. */ public PriorityDoorArrive setPathOffset (float pathOffset) { this.pathOffset = pathOffset; return this; } /** Returns the current path parameter. */ public LinePath.LinePathParam getPathParam () { return pathParam; } /** Returns the current position of the internal target. This method is useful for debug purpose. */ public Vector2 getInternalTargetPosition () { return internalTargetPosition; } public Vector2 getArriveTargetPosition () { return arriveTargetPosition; } // // Setters overridden in order to fix the correct return type for chaining // @Override public PriorityDoorArrive setOwner (Steerable<Vector2> owner) { super.setOwner(owner); this.owner = (Agent)owner; return this; } @Override public PriorityDoorArrive setEnabled (boolean enabled) { this.enabled = enabled; return this; } /** Sets the limiter of this steering behavior. The given limiter must at least take care of the maximum linear speed and * acceleration. However the maximum linear speed is not required for a closed path. * @return this behavior for chaining. */ @Override public PriorityDoorArrive setLimiter (Limiter limiter) { this.limiter = limiter; return this; } @Override public PriorityDoorArrive setTarget (Location<Vector2> target) { this.target = target; return this; } @Override public PriorityDoorArrive setArrivalTolerance (float arrivalTolerance) { this.arrivalTolerance = arrivalTolerance; return this; } @Override public PriorityDoorArrive setDecelerationRadius (float decelerationRadius) { this.decelerationRadius = decelerationRadius; return this; } public PriorityDoorArrive setFaceDecelerationRadius (float decelerationRadius) { face.setDecelerationRadius(decelerationRadius); return this; } @Override public PriorityDoorArrive setTimeToTarget (float timeToTarget) { this.timeToTarget = timeToTarget; return this; } public PriorityDoorArrive setFaceTimeToTarget (float timeToTarget) { face.setTimeToTarget(timeToTarget); return this; } public void setMap (Map map) { this.map = map; } @Override public boolean override () { return override; } public void update (Path<Vector2, LinePath.LinePathParam> path, Pathfinding.NodePath nodePath) { setPath(path); } public Face<Vector2> setAlignTolerance (float alignTolerance) { return face.setAlignTolerance(alignTolerance); } } // counterclockwise, 0 east, 90 north, -90 south public enum Step {E(0), SE(-45), S(-90), SW(-135), W(180), NW(135), N(90), NE(45); public final int angle; private static Step[] cache = new Step[360]; static { Step[] values = values(); for (int i = 0; i < 360; i++) { cache[i] = W; for (Step value : values) { if (Math.abs(i - value.angle - 180) <= 22.5f){ cache[i] = value; break; } } } } Step (int angle) { this.angle = angle; } public static Step of(float angle) { return cache[((int)normalize(angle)) + 180]; } } public static float normalize(float angle) { return angle - 360f * MathUtils.floor((angle + 180) / 360f); } }
package com.gxtc.huchuan.ui.news; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.gxtc.commlibrary.base.BaseRecyclerAdapter; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.commlibrary.recyclerview.RecyclerView; import com.gxtc.commlibrary.recyclerview.wrapper.LoadMoreWrapper; import com.gxtc.commlibrary.utils.EventBusUtil; import com.gxtc.commlibrary.utils.ToastUtil; import com.gxtc.huchuan.Constant; import com.gxtc.huchuan.R; import com.gxtc.huchuan.adapter.NewsCollectAdapter; import com.gxtc.huchuan.bean.NewsBean; import com.gxtc.huchuan.bean.event.EventCollectSelectBean; 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.AllApi; import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity; import com.gxtc.huchuan.utils.DialogUtil; import com.gxtc.huchuan.utils.LoginErrorCodeUtil; import com.gxtc.huchuan.widget.DividerItemDecoration; import org.greenrobot.eventbus.Subscribe; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by sjr on 2017/3/15. * 新闻收藏列表 */ public class NewsCollectActivity extends BaseTitleActivity implements NewsCollectContract.View { @BindView(R.id.rl_news_collect) RecyclerView mRecyclerView; @BindView(R.id.sw_news_collect) SwipeRefreshLayout swNewsCollect; @BindView(R.id.headBackButton) ImageButton headBackButton; @BindView(R.id.cb_editor) CheckBox cbEditor; @BindView(R.id.tv_news_collect) TextView tvNewsCollect; private NewsCollectContract.Presenter mPresenter; private NewsCollectAdapter mAdapter; private List<NewsBean> mDatas; private List<BaseRecyclerAdapter.ViewHolder> holders; private List<String> newsIds; int count = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_news_collect); EventBusUtil.register(this); } @Override public void initData() { mDatas = new ArrayList<>(); holders = new ArrayList<>(); newsIds = new ArrayList<>(); swNewsCollect.setColorSchemeResources(R.color.refresh_color1, R.color.refresh_color2, R.color.refresh_color3, R.color.refresh_color4); initRecyCleView(); new NewsCollectPresenter(this); mPresenter.getData(false); } @OnClick({R.id.headBackButton, R.id.tv_news_collect}) public void onClick(View view) { switch (view.getId()) { case R.id.headBackButton: NewsCollectActivity.this.finish(); break; case R.id.tv_news_collect://删除操作 showDeleteDialog(); break; } } @Override public void initListener() { swNewsCollect.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mPresenter.getData(true); mRecyclerView.reLoadFinish(); } }); mRecyclerView.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() { @Override public void onLoadMoreRequested() { mPresenter.loadMrore(); } }); } Subscription subThumbsup; /** * 删除收藏文章 */ private void showDeleteDialog() { mDialog = DialogUtil.createDialog(this, "提示", "确定要删除" + count + "条收藏吗?", "取消", "确定", new DialogUtil.DialogClickListener() { @Override public void clickLeftButton(View view) { mDialog.dismiss(); } @Override public void clickRightButton(View view) { for (int i = 0; i < mAdapter.getList().size(); i++) { NewsBean bean = mAdapter.getList().get(i); if (bean.isCheck()) {//选中的时候 newsIds.add(bean.getId()); } } deleteCollect(UserManager.getInstance().getToken(), (ArrayList<String>) newsIds); mDialog.dismiss(); } }); mDialog.show(); } /** * 取消收藏 * <p> * 2017/3/30 这个方法有个问题,就是本来我是应该本地刷新的,但是莫名其妙只能删除第一个,项目赶为了避免bug删除后重新刷新数据了,后续要优化 * 2017/4/6 上述问题已解决 删除时list的数据变了 * * @param token * @param newsIds */ private void deleteCollect(String token, final ArrayList<String> newsIds) { if (newsIds.size() > 0) subThumbsup = AllApi.getInstance().getCollect(token, newsIds) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<ApiResponseBean<Object>>(new ApiCallBack() { @Override public void onSuccess(Object data) { for (int i = 0; i < mAdapter.getList().size(); i++) { NewsBean bean = mAdapter.getList().get(i); if (bean.isCheck()) {//选中的时候 mAdapter.getList().remove(bean); i--; } } mAdapter.notifyDataSetChanged(); mRecyclerView.notifyChangeData(); // mPresenter.getData(true); // for (int i = 0; i < newsIds.size(); i++) { // LogUtil.printD("aa:" + newsIds.get(i)); // // } tvNewsCollect.setVisibility(View.GONE); for (int i = 0; i < mDatas.size(); i++) { mDatas.get(i).setShow(false); } newsIds.clear(); cbEditor.setChecked(false); } @Override public void onError(String errorCode, String message) { LoginErrorCodeUtil.showHaveTokenError(NewsCollectActivity.this, errorCode, message); } })); else ToastUtil.showShort(NewsCollectActivity.this, "请选择文章"); } /** * 新闻列表 */ private void initRecyCleView() { mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL, false)); mRecyclerView.setLoadMoreView(R.layout.model_footview_loadmore); mRecyclerView.addItemDecoration(new DividerItemDecoration(NewsCollectActivity.this, LinearLayoutManager.HORIZONTAL)); } @Override public void showData(final List<NewsBean> datas) { mDatas.clear(); mDatas.addAll(datas); mAdapter = new NewsCollectAdapter(this, datas, R.layout.item_news_collect_activity); mRecyclerView.setAdapter(mAdapter); mAdapter.setOnReItemOnClickListener(new BaseRecyclerAdapter.OnReItemOnClickListener() { @Override public void onItemClick(View v, int position) { Intent intent = new Intent(NewsCollectActivity.this, NewsWebActivity.class); intent.putExtra("data", datas.get(position)); startActivity(intent); } }); setEditor(datas); } private void setEditor(final List<NewsBean> datas) { cbEditor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) {//可以编辑状态 cbEditor.setText("取消"); for (int i = 0; i < datas.size(); i++) { datas.get(i).setShow(true); } mRecyclerView.notifyChangeData(); tvNewsCollect.setVisibility(View.VISIBLE); tvNewsCollect.setText("删除(0)"); } else { cbEditor.setText("编辑"); tvNewsCollect.setVisibility(View.GONE); for (int i = 0; i < datas.size(); i++) { datas.get(i).setShow(false); datas.get(i).setCheck(false); } count = 0; mRecyclerView.notifyChangeData(); } } }); } private AlertDialog mDialog; @Override public void tokenOverdue() { Intent intent = new Intent(NewsCollectActivity.this, LoginAndRegisteActivity.class); startActivityForResult(intent, Constant.requestCode.NEWS_COLLECT); } @Override public void setPresenter(NewsCollectContract.Presenter presenter) { mPresenter = presenter; } @Override public void showLoad() { getBaseLoadingView().showLoading(); } @Override public void showLoadFinish() { swNewsCollect.setRefreshing(false); getBaseLoadingView().hideLoading(); } @Override public void showEmpty() { getBaseEmptyView().showEmptyContent(getString(R.string.empty_no_data)); } @Override public void showReLoad() { } /** * 加载更多时网络错误,直接打吐司 * * @param info */ @Override public void showError(String info) { ToastUtil.showShort(this, info); } /** * 初始网络错误,点击重新加载 */ @Override public void showNetError() { getBaseEmptyView().showNetWorkViewReload(new View.OnClickListener() { @Override public void onClick(View v) { initData(); //记得隐藏 getBaseEmptyView().hideEmptyView(); } }); } @Override public void showRefreshFinish(List<NewsBean> datas) { mRecyclerView.notifyChangeData(datas, mAdapter); // cbEditor.setChecked(false); } @Override public void showLoadMore(List<NewsBean> datas) { mRecyclerView.changeData(datas, mAdapter); } @Override public void showNoMore() { mRecyclerView.loadFinish(); } /** * 删除按钮 */ @Subscribe public void onEvent(EventCollectSelectBean bean) { for (int i = 0; i < mDatas.size(); i++) { if (i == bean.getPosition() && bean.isSelected() == true) { holders.add(bean.holder); count++; } else if (i == bean.getPosition() && bean.isSelected() == false) { count--; if (count < 0) { count = 0; } } } tvNewsCollect.setText("删除(" + count + ")"); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (Constant.requestCode.NEWS_COLLECT == requestCode && resultCode == Constant.ResponseCode.LOGINRESPONSE_CODE) { initData(); } } @Override protected void onDestroy() { super.onDestroy(); mPresenter.destroy(); if (subThumbsup != null && subThumbsup.isUnsubscribed()) { subThumbsup.unsubscribe(); } EventBusUtil.unregister(this); } }
package com.abt.middle.swipback; import android.app.Activity; import android.app.Application; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.view.View; import android.view.ViewGroup; import com.abt.middle.R; import com.abt.middle.swipback.widget.SwipBackLayout; import com.abt.middle.swipback.widget.ViewUtil; /** * @描述: @右滑删除 * @作者: @黄卫旗 * @创建时间: @2017-12-04 */ public class SwipBackManager { private static final String TAG = "SwipBackManager"; private static SwipBackConfig sSwipBackConfig; private static ActivityMgr sActivityManage; public static final void initialize(Application application, SwipBackConfig config) { if (null == sSwipBackConfig) { sSwipBackConfig = config; sActivityManage = new ActivityMgr(); application.registerActivityLifecycleCallbacks(sActivityManage); } } private SwipBackManager() { } public static final SwipBackConfig getSwipBackConfig() { return sSwipBackConfig; } /** * 把当前 * @param curActivity */ public static final void addSwipBackList(@NonNull final Activity curActivity) { final ViewGroup decorView = ViewUtil.getDecorView(curActivity); final View contentView = decorView.getChildAt(0); decorView.removeViewAt(0); View content = contentView.findViewById(android.R.id.content); if (content.getBackground() == null) { content.setBackground(decorView.getBackground()); } final Activity[] preActivity = {sActivityManage.getPreActivity()}; final View[] preContentView = {ViewUtil.getContentView(preActivity[0])}; Drawable preDecorViewDrawable = ViewUtil.getDecorViewDrawable(preActivity[0]); content = preContentView[0].findViewById(android.R.id.content); if (content.getBackground() == null) { content.setBackground(preDecorViewDrawable); } final SwipBackLayout layout = new SwipBackLayout(curActivity, contentView, preContentView[0], preDecorViewDrawable, new SwipBackLayout.OnInternalStateListener() { @Override public void onSlide(float percent) { } @Override public void onOpen() { } @Override public void onClose(Boolean finishActivity) { if (getSwipBackConfig() != null && getSwipBackConfig().isRotateScreen()) { if (finishActivity != null && finishActivity) { // remove了preContentView后布局会重新调整,这时候contentView回到原处,所以要设不可见 contentView.setVisibility(View.INVISIBLE); } /*if (preActivity[0] != null && preContentView[0].getParent() != ViewUtil.getDecorView(preActivity[0])) { preContentView[0].setX(0); ((ViewGroup) preContentView[0].getParent()).removeView(preContentView[0]); ViewUtil.getDecorView(preActivity[0]).addView(preContentView[0], 0); }*/ } if (finishActivity != null && finishActivity) { curActivity.finish(); curActivity.overridePendingTransition(0, R.anim.anim_out_none); sActivityManage.postRemoveActivity(curActivity); } else if (finishActivity == null) { sActivityManage.postRemoveActivity(curActivity); } } @Override public void onCheckPreActivity(SwipBackLayout slideBackLayout) { Activity activity = sActivityManage.getPreActivity(); } }); decorView.addView(layout); } }
package main.Controller; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.fxml.Initializable; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import main.Model.Report; import main.Util.DBConnector; import main.Util.DBQuery; import java.net.URL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; /** * @author Michael Williams - 001221520 * * This class controls and handles all processes related to the 'ReportTwo.fxml' page. */ public class ReportTwoController implements Initializable { public TableView<Report> AC_Schedule_Table; public TableColumn<Report,String> ACcontactName; public TableColumn<Report,String> ACappointmentId; public TableColumn<Report,String> ACappointmentTitle; public TableColumn<Report,String> ACappointmentDesc; public TableColumn<Report,String> ACappointmentStart; public TableColumn<Report,String> ACappointmentEnd; public TableColumn<Report,String> ACcustomerId; public TableView<Report> DG_Schedule_Table; public TableColumn<Report,String> DGcontactName; public TableColumn<Report,String> DGappointmentId; public TableColumn<Report,String> DGappointmentTitle; public TableColumn<Report,String> DGappointmentDesc; public TableColumn<Report,String> DGappointmentStart; public TableColumn<Report,String> DGappointmentEnd; public TableColumn<Report,String> DGcustomerId; public TableView<Report> LL_Schedule_Table; public TableColumn<Report,String> LLcontactName; public TableColumn<Report,String> LLappointmentId; public TableColumn<Report,String> LLappointmentTitle; public TableColumn<Report,String> LLappointmentDesc; public TableColumn<Report,String> LLappointmentStart; public TableColumn<Report,String> LLappointmentEnd; public TableColumn<Report,String> LLcustomerId; /** * This initialize method holds tbe table build methods * @param url * @param resourceBundle */ @Override public void initialize(URL url, ResourceBundle resourceBundle) { buildACScheduleReportTable(); buildDGScheduleReportTable(); buildLLScheduleReportTable(); } /** *Builds the table for Contact one */ public void buildACScheduleReportTable(){ String getStatement = "select con.Contact_Name, apt.Appointment_ID , apt.Title, apt.Description,apt.Start,apt.End, Customer_ID\n" + "from appointments apt join contacts con on apt.Contact_ID = con.Contact_ID where apt.Contact_ID = 1 order by con.Contact_ID, apt.Start;"; ObservableList<Report> reportResults = FXCollections.observableArrayList(); try { DBQuery.setPreparedStatement(DBConnector.getConnection(),getStatement); PreparedStatement ps = DBQuery.getPreparedStatement(); ps.execute(); ResultSet rs = ps.getResultSet(); if (rs != null){ while (rs.next()){ Report r = new Report( rs.getString(1), String.valueOf(rs.getInt(2)), rs.getString(3), rs.getString(4), String.valueOf(rs.getTimestamp(5)), String.valueOf(rs.getTimestamp(6)), String.valueOf(rs.getInt(7)) ); reportResults.add(r); } } }catch (SQLException s){ s.printStackTrace(); } FilteredList<Report> reportFilteredList = new FilteredList<>(reportResults); AC_Schedule_Table.setItems(reportFilteredList); ACcontactName.setCellValueFactory(new PropertyValueFactory<>("var1")); ACappointmentId.setCellValueFactory(new PropertyValueFactory<>("var2")); ACappointmentTitle.setCellValueFactory(new PropertyValueFactory<>("var3")); ACappointmentDesc.setCellValueFactory(new PropertyValueFactory<>("var4")); ACappointmentStart.setCellValueFactory(new PropertyValueFactory<>("var5")); ACappointmentEnd.setCellValueFactory(new PropertyValueFactory<>("var6")); ACcustomerId.setCellValueFactory(new PropertyValueFactory<>("var7")); } /** *Builds the table for Contact two */ public void buildDGScheduleReportTable(){ String getStatement = "select con.Contact_Name, apt.Appointment_ID , apt.Title, apt.Description,apt.Start,apt.End, Customer_ID\n" + "from appointments apt join contacts con on apt.Contact_ID = con.Contact_ID where apt.Contact_ID = 2 order by con.Contact_ID, apt.Start;"; ObservableList<Report> reportResults = FXCollections.observableArrayList(); try { DBQuery.setPreparedStatement(DBConnector.getConnection(),getStatement); PreparedStatement ps = DBQuery.getPreparedStatement(); ps.execute(); ResultSet rs = ps.getResultSet(); if (rs != null){ while (rs.next()){ Report r = new Report( rs.getString(1), String.valueOf(rs.getInt(2)), rs.getString(3), rs.getString(4), String.valueOf(rs.getTimestamp(5)), String.valueOf(rs.getTimestamp(6)), String.valueOf(rs.getInt(7)) ); reportResults.add(r); } } }catch (SQLException s){ s.printStackTrace(); } FilteredList<Report> reportFilteredList = new FilteredList<>(reportResults); DG_Schedule_Table.setItems(reportFilteredList); DGcontactName.setCellValueFactory(new PropertyValueFactory<>("var1")); DGappointmentId.setCellValueFactory(new PropertyValueFactory<>("var2")); DGappointmentTitle.setCellValueFactory(new PropertyValueFactory<>("var3")); DGappointmentDesc.setCellValueFactory(new PropertyValueFactory<>("var4")); DGappointmentStart.setCellValueFactory(new PropertyValueFactory<>("var5")); DGappointmentEnd.setCellValueFactory(new PropertyValueFactory<>("var6")); DGcustomerId.setCellValueFactory(new PropertyValueFactory<>("var7")); } /** *Builds the table for Contact three */ public void buildLLScheduleReportTable(){ String getStatement = "select con.Contact_Name, apt.Appointment_ID , apt.Title, apt.Description,apt.Start,apt.End, Customer_ID\n" + "from appointments apt join contacts con on apt.Contact_ID = con.Contact_ID where apt.Contact_ID = 3 order by con.Contact_ID, apt.Start;"; ObservableList<Report> reportResults = FXCollections.observableArrayList(); try { DBQuery.setPreparedStatement(DBConnector.getConnection(),getStatement); PreparedStatement ps = DBQuery.getPreparedStatement(); ps.execute(); ResultSet rs = ps.getResultSet(); if (rs != null){ while (rs.next()){ Report r = new Report( rs.getString(1), String.valueOf(rs.getInt(2)), rs.getString(3), rs.getString(4), String.valueOf(rs.getTimestamp(5)), String.valueOf(rs.getTimestamp(6)), String.valueOf(rs.getInt(7)) ); reportResults.add(r); } } }catch (SQLException s){ s.printStackTrace(); } FilteredList<Report> reportFilteredList = new FilteredList<>(reportResults); LL_Schedule_Table.setItems(reportFilteredList); LLcontactName.setCellValueFactory(new PropertyValueFactory<>("var1")); LLappointmentId.setCellValueFactory(new PropertyValueFactory<>("var2")); LLappointmentTitle.setCellValueFactory(new PropertyValueFactory<>("var3")); LLappointmentDesc.setCellValueFactory(new PropertyValueFactory<>("var4")); LLappointmentStart.setCellValueFactory(new PropertyValueFactory<>("var5")); LLappointmentEnd.setCellValueFactory(new PropertyValueFactory<>("var6")); LLcustomerId.setCellValueFactory(new PropertyValueFactory<>("var7")); } }
package shared.Crawler; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; public class Link implements Serializable { /** * */ private static final long serialVersionUID = 1L; URL url; String domain; public Link(String url) throws MalformedURLException, URISyntaxException { this.url = new URL(url); this.domain = calculateDomainName(url.toString()); } public static String calculateDomainName(String url) { URI uri; try { uri = new URI(url); String domain = uri.getHost(); return domain.startsWith("www.") ? domain.substring(4) : domain; } catch (URISyntaxException e) { return null; } } public String getDomainName() { return domain; } public URL getURL() { return url; } public String toString() { return url + "\t" + domain; } }
package cover; public class InfiniteRangeSet implements ISet { private final int start; private final int step; public InfiniteRangeSet(int start, int step) { this.start = start; this.step = -step; } public boolean coversAnyElement(final boolean[] array) { for (int i = start; i < array.length; i += step) { if (!array[i]) { return true; } } return false; } public int countCoveredElements(final boolean[] array) { int covered = 0; for (int i = start; i < array.length; i += step) { if (!array[i]) { covered++; } } return covered; } public int markCoveredElements(boolean[] array) { int covered = 0; for (int i = start; i < array.length; i += step) { if (!array[i]) { array[i] = true; covered++; } } return covered; } }
package be.openclinic.system; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.*; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.dom4j.DocumentHelper; import org.dom4j.Element; import SecuGen.FDxSDKPro.jni.*; public class FingerPrint { JSGFPLib sgfplib; String callId,url; long port=SGPPPortAddr.AUTO_DETECT; public static void main(String[] args) { FingerPrint fingerPrint = new FingerPrint(); if(args.length>0){ System.out.println("Command = "+args[0]); if(args[0].equalsIgnoreCase("checkReady")){ if(args.length>2){ fingerPrint.url = args[1]; fingerPrint.callId = args[2]; if(args.length>3){ fingerPrint.port=Long.parseLong(args[3]); } fingerPrint.checkReady(); } else{ System.out.println("Syntax: FingerPrint checkReady <url> <call id>"); } } else if(args[0].equalsIgnoreCase("getFingerPrint")){ if(args.length>2){ fingerPrint.url = args[1]; fingerPrint.callId = args[2]; System.out.println("url = "+fingerPrint.url); System.out.println("callId = "+fingerPrint.callId); if(args.length>3){ fingerPrint.port=Long.parseLong(args[3]); } fingerPrint.getFingerPrint(); } else{ System.out.println("Syntax: FingerPrint checkReady <url> <call id>"); } } } } public void getFingerPrint(){ try{ if(isReady()){ Element eFingerPrint = DocumentHelper.createElement("fingerprint"); eFingerPrint.addAttribute("command", "getFingerPrint"); setLedOn(true); eFingerPrint.add(read()); setLedOn(false); CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("data", eFingerPrint.asXML(), ContentType.TEXT_PLAIN); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); try { System.out.println("posting: "+url); CloseableHttpResponse response = client.execute(httpPost); System.out.println("checkReady status code: "+response.getStatusLine().getStatusCode()); System.out.println("checkReady response: "+response.getStatusLine().getReasonPhrase()); } catch (Exception e) { e.printStackTrace(); } } } catch(Exception e){ e.printStackTrace(); } finally{ closeLib(); } } public static BufferedImage toImage(byte[] data, int w, int h) { DataBuffer buffer = new DataBufferByte(data, data.length); WritableRaster raster = Raster.createInterleavedRaster(buffer, w, h, w, 1, new int[]{0}, null); ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); ColorModel cm = new ComponentColorModel(cs, false, true,Transparency.OPAQUE, DataBuffer.TYPE_BYTE); return new BufferedImage(cm, raster, false, null); } public Element read(){ Element eFingerPrintInfo = DocumentHelper.createElement("fingerPrintInfo"); eFingerPrintInfo.addAttribute("callId", callId); SGDeviceInfoParam deviceInfo = new SGDeviceInfoParam(); sgfplib.GetDeviceInfo(deviceInfo); byte[] imageBuffer = new byte[deviceInfo.imageHeight*deviceInfo.imageWidth]; System.out.println("Call GetImage()"); long err = sgfplib.GetImageEx(imageBuffer,10000,0,50); if(err == SGFDxErrorCode.SGFDX_ERROR_NONE){ System.out.println("Fingerprint captured"); int[] quality = new int[1]; int[] maxSize = new int[1]; int[] size = new int[1]; SGFingerInfo fingerInfo = new SGFingerInfo(); fingerInfo.FingerNumber = SGFingerPosition.SG_FINGPOS_LI; fingerInfo.ImageQuality = quality[0]; fingerInfo.ImpressionType = SGImpressionType.SG_IMPTYPE_LP; fingerInfo.ViewNumber = 1; /////////////////////////////////////////////// // Set Template format ISO19794 System.out.println("Call SetTemplateFormat(ISO19794)"); err = sgfplib.SetTemplateFormat(SGFDxTemplateFormat.TEMPLATE_FORMAT_ISO19794); System.out.println("SetTemplateFormat returned : [" + err + "]"); /////////////////////////////////////////////// // Get Max Template Size for ISO19794 System.out.println("Call GetMaxTemplateSize()"); err = sgfplib.GetMaxTemplateSize(maxSize); System.out.println("GetMaxTemplateSize returned : [" + err + "]"); System.out.println("Max ISO19794 Template Size is : [" + maxSize[0] + "]"); /////////////////////////////////////////////// // Create ISO19794 Template for Finger1 byte[] ISOminutiaeBuffer = new byte[maxSize[0]]; System.out.println("Call CreateTemplate()"); err = sgfplib.CreateTemplate(fingerInfo, imageBuffer, ISOminutiaeBuffer); System.out.println("CreateTemplate returned : [" + err + "]"); err = sgfplib.GetTemplateSize(ISOminutiaeBuffer, size); System.out.println("GetTemplateSize returned : [" + err + "]"); System.out.println("ISO19794 Template Size is : [" + size[0] + "]"); eFingerPrintInfo.addElement("iso").setText(org.apache.commons.codec.binary.Base64.encodeBase64String(ISOminutiaeBuffer)); eFingerPrintInfo.addElement("raw").setText(org.apache.commons.codec.binary.Base64.encodeBase64String(imageBuffer)); eFingerPrintInfo.addElement("width").setText(deviceInfo.imageWidth+""); eFingerPrintInfo.addElement("height").setText(deviceInfo.imageHeight+""); } else{ eFingerPrintInfo.addElement("iso").setText("0"); } System.out.println("Error = "+err); return eFingerPrintInfo; } public int matchISO(byte[] ISOminutiaeBuffer1, byte[] ISOminutiaeBuffer2){ int[] score = new int[1]; int[] maxSize = new int[1]; int[] size = new int[1]; boolean[] matched = new boolean[1]; System.out.println("Performing ISO match"); /////////////////////////////////////////////// // Set Template format ISO19794 System.out.println("Call SetTemplateFormat(ISO19794)"); long err = sgfplib.SetTemplateFormat(SGFDxTemplateFormat.TEMPLATE_FORMAT_ISO19794); System.out.println("SetTemplateFormat returned : [" + err + "]"); /////////////////////////////////////////////// // Get Max Template Size for ISO19794 System.out.println("Call GetMaxTemplateSize()"); err = sgfplib.GetMaxTemplateSize(maxSize); System.out.println("GetMaxTemplateSize returned : [" + err + "]"); System.out.println("Max ISO19794 Template Size is : [" + maxSize[0] + "]"); System.out.println("Call MatchIsoTemplates()"); err = sgfplib.MatchIsoTemplate(ISOminutiaeBuffer1, 0, ISOminutiaeBuffer2, 0, SGFDxSecurityLevel.SL_NORMAL, matched); System.out.println("MatchISOTemplates returned : [" + err + "]"); System.out.println("ISO-1 <> ISO-2 Match Result : [" + matched[0] + "]"); System.out.println("Call GetIsoMatchingScore()"); err = sgfplib.GetIsoMatchingScore(ISOminutiaeBuffer1, 0, ISOminutiaeBuffer2, 0, score); System.out.println("GetIsoMatchingScore returned : [" + err + "]"); System.out.println("ISO-1 <> ISO-2 Match Score : [" + score[0] + "]"); return score[0]; } public void checkReady(){ try{ if(isReady()){ Element eFingerPrint = DocumentHelper.createElement("fingerprint"); eFingerPrint.addAttribute("command", "checkReady"); eFingerPrint.add(getDeviceInfo()); CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("data", eFingerPrint.asXML(), ContentType.TEXT_PLAIN); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); try { System.out.println("posting: "+url); CloseableHttpResponse response = client.execute(httpPost); System.out.println("checkReady status code: "+response.getStatusLine().getStatusCode()); System.out.println("checkReady response: "+response.getStatusLine().getReasonPhrase()); } catch (Exception e) { e.printStackTrace(); } } } catch(Exception e){ e.printStackTrace(); } finally{ closeLib(); } } public boolean initLib(){ System.out.println("Instantiate JSGFPLib Object"); sgfplib = new JSGFPLib(); if ((sgfplib != null) && (sgfplib.jniLoadStatus != SGFDxErrorCode.SGFDX_ERROR_JNI_DLLLOAD_FAILED)) { System.out.println("jniLoadStatus="+sgfplib.jniLoadStatus); System.out.println(sgfplib); return true; } else { System.out.println("An error occurred while loading JSGFPLIB.DLL JNI Wrapper"); return false; } } public boolean initDevice(){ System.out.println("Call Init(SGFDxDeviceName.SG_DEV_AUTO)"); long err = sgfplib.Init(SGFDxDeviceName.SG_DEV_AUTO); System.out.println("Init returned : [" + err + "]"); if(err == SGFDxErrorCode.SGFDX_ERROR_NONE){ return true; } else{ return false; } } public boolean openDevice(){ System.out.println("Call OpenDevice("+port+")"); long err = sgfplib.OpenDevice(port); System.out.println("OpenDevice returned : [" + err + "]"); if(err == SGFDxErrorCode.SGFDX_ERROR_NONE){ return true; } else{ for(int n=0;n<5;n++){ err = sgfplib.OpenDevice(n); System.out.println("OpenDevice returned : [" + err + "]"); if(err == SGFDxErrorCode.SGFDX_ERROR_NONE){ port=n; return true; } } return false; } } public boolean isReady(){ if(initLib() && initDevice() && openDevice()){ return true; } else{ return false; } } public Element getDeviceInfo(){ Element eDeviceInfo = DocumentHelper.createElement("deviceInfo"); eDeviceInfo.addAttribute("callId", callId); System.out.println("Call GetDeviceInfo()"); SGDeviceInfoParam deviceInfo = new SGDeviceInfoParam(); long err = sgfplib.GetDeviceInfo(deviceInfo); if(err == SGFDxErrorCode.SGFDX_ERROR_NONE){ eDeviceInfo.addElement("DeviceSN").setText(new String(deviceInfo.deviceSN()).trim()); eDeviceInfo.addElement("ComPort").setText(deviceInfo.comPort+""); eDeviceInfo.addElement("ComSpeed").setText(deviceInfo.comSpeed+""); eDeviceInfo.addElement("DeviceID").setText(deviceInfo.deviceID+""); eDeviceInfo.addElement("FWVersion").setText(deviceInfo.FWVersion+""); } else{ eDeviceInfo.addElement("Error").setText(err+""); } return eDeviceInfo; } public void setLedOn(boolean bOn){ long err = sgfplib.SetLedOn(bOn); System.out.println("SetLedOn returned : [" + err + "]"); } public void closeLib(){ sgfplib.CloseDevice(); System.out.println("Closing JSGFPLib"); long err = sgfplib.Close(); System.out.println("Close returned : [" + err + "]"); } }
package com.sirma.itt.javacourse.chat.client.ui; import java.awt.BorderLayout; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.JPanel; import javax.swing.JTabbedPane; import org.apache.log4j.Logger; import com.sirma.itt.javacourse.chat.client.ui.componnents.ClosableTabbedPane; import com.sirma.itt.javacourse.chat.common.Message; import com.sirma.itt.javacourse.chat.common.utils.CommonUtils; import com.sirma.itt.javacourse.chat.common.utils.LanguageController; /** * The main chat panel window. * * * @author siliev * */ public class ChatsPanel extends JPanel { private static final long serialVersionUID = -3781827111159603799L; private static final Logger LOGGER = Logger.getLogger(ChatsPanel.class); private ClosableTabbedPane tabbedPane; private List<ChatWindow> tabs; /** * Constructor */ public ChatsPanel() { tabs = new ArrayList<ChatWindow>(); setUp(); } /** * Sets up the UI settings. */ private void setUp() { tabbedPane = new ClosableTabbedPane(); JPanel panel = this; tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); panel.setLayout(new BorderLayout()); panel.add(tabbedPane, BorderLayout.CENTER); } /** * Adds the new tab to the tabbed pane. * * * @param info * the information for the new tab. */ public void addNewTab(Message info) { LOGGER.info("Adding tab"); ChatWindow chatWindow = createNewPanel(info); if (chatWindow.getChatID() == 0) { tabbedPane .add(LanguageController.getWord("commonroom"), chatWindow); } else { tabbedPane.add(info.getContent(), chatWindow); } tabbedPane.invalidate(); tabs.add(chatWindow); } /** * Creates a new chat window. * * @param info * the information required for the new chat window. * @return the new chat window. */ private ChatWindow createNewPanel(Message info) { LOGGER.info("Creating new window"); ChatWindow panel = new ChatWindow(); panel.setChatID(info.getChatRoomId()); panel.setUserNames(Arrays.asList(CommonUtils.splitList(info .getContent()))); return panel; } /** * Gets the current selected chats id. * * @return the selected chat windows ID. */ public Long getChatId() { ChatWindow window = (ChatWindow) tabbedPane.getSelectedComponent(); return window.getChatID(); } /** * Send a message to be displayed in the proper tab. * * @param message * the message that is to be processed. */ public void processMessage(Message message) { for (ChatWindow tab : tabs) { if (tab.getChatID() == message.getChatRoomId()) { if (!tabbedPane.containsComponnent(tab)) { if (tab.getChatID() == 0) { tabbedPane.add( LanguageController.getWord("commonroom"), tab); } else { tabbedPane.add(tab.getUserNames().toString(), tab); } } tab.displayMessage(message); tabbedPane.shoudNotifyUser(tab); break; } } } /** * Checks if there is already a chat room with the people we have selected. * * @param list * the list of users we want to check. * @return true if there is no chat with the same user is there is then the * result is false. */ public boolean checkPanels(List<String> list) { for (ChatWindow tab : tabs) { if (tab.getUserNames().containsAll(list) && list.containsAll(tab.getUserNames())) { if (tab.getChatID() != 0) { return false; } } } return true; } /** * Returns the selected chats ID. */ public Long getSelectedChat() { ChatWindow window = (ChatWindow) tabbedPane.getSelectedComponent(); return window.getChatID(); } /** * Resets all the chats windows. */ public void resetChats() { tabs.clear(); tabbedPane.removeAll(); } /** * Shows the tab if its hidden. * * @param list * the user list to check for the tab. */ public void showTab(List<String> list) { for (ChatWindow tab : tabs) { if (tab.getUserNames().containsAll(list) && list.containsAll(tab.getUserNames())) { if (tab.getChatID() == 0) { tabbedPane.add(LanguageController.getWord("commonroom"), tab); } else { tabbedPane.add(tab.getUserNames().toString(), tab); } } } } }
package com.sinodynamic.hkgta.integration.spa.response; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "RowNum", "id", "resourceFile", "Type", "HasVariant", "IsVariant", "Name", "Description", "Duration", "Price", "PriceText", "IncludesTax", "CatalogNew", "CatalogRecommended", "VideoURL", "CanBook", "ShowPrice", "SortOrder", "CenterTaxId", "RecoveryTime", "FinalPrice" }) public class Item extends BaseResponse { private static final long serialVersionUID = 1535798639672859194L; @JsonProperty("RowNum") private Integer rowNum; @JsonProperty("id") private String id; @JsonProperty("resourceFile") private Object resourceFile; @JsonProperty("Type") private Integer type; @JsonProperty("HasVariant") private Integer hasVariant; @JsonProperty("IsVariant") private Integer isVariant; @JsonProperty("Name") private String name; @JsonProperty("Description") private String description; @JsonProperty("Duration") private Integer duration; @JsonProperty("Price") private Integer price; @JsonProperty("PriceText") private Object priceText; @JsonProperty("IncludesTax") private Integer includesTax; @JsonProperty("CatalogNew") private Integer catalogNew; @JsonProperty("CatalogRecommended") private Integer catalogRecommended; @JsonProperty("VideoURL") private Object videoURL; @JsonProperty("CanBook") private Integer canBook; @JsonProperty("ShowPrice") private Integer showPrice; @JsonProperty("SortOrder") private Integer sortOrder; @JsonProperty("CenterTaxId") private Object centerTaxId; @JsonProperty("RecoveryTime") private Integer recoveryTime; @JsonProperty("FinalPrice") private Integer finalPrice; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); public Integer getRowNum() { return rowNum; } public void setRowNum(Integer rowNum) { this.rowNum = rowNum; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Object getResourceFile() { return resourceFile; } public void setResourceFile(Object resourceFile) { this.resourceFile = resourceFile; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getHasVariant() { return hasVariant; } public void setHasVariant(Integer hasVariant) { this.hasVariant = hasVariant; } public Integer getIsVariant() { return isVariant; } public void setIsVariant(Integer isVariant) { this.isVariant = isVariant; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } public Object getPriceText() { return priceText; } public void setPriceText(Object priceText) { this.priceText = priceText; } public Integer getIncludesTax() { return includesTax; } public void setIncludesTax(Integer includesTax) { this.includesTax = includesTax; } public Integer getCatalogNew() { return catalogNew; } public void setCatalogNew(Integer catalogNew) { this.catalogNew = catalogNew; } public Integer getCatalogRecommended() { return catalogRecommended; } public void setCatalogRecommended(Integer catalogRecommended) { this.catalogRecommended = catalogRecommended; } public Object getVideoURL() { return videoURL; } public void setVideoURL(Object videoURL) { this.videoURL = videoURL; } public Integer getCanBook() { return canBook; } public void setCanBook(Integer canBook) { this.canBook = canBook; } public Integer getShowPrice() { return showPrice; } public void setShowPrice(Integer showPrice) { this.showPrice = showPrice; } public Integer getSortOrder() { return sortOrder; } public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; } public Object getCenterTaxId() { return centerTaxId; } public void setCenterTaxId(Object centerTaxId) { this.centerTaxId = centerTaxId; } public Integer getRecoveryTime() { return recoveryTime; } public void setRecoveryTime(Integer recoveryTime) { this.recoveryTime = recoveryTime; } public Integer getFinalPrice() { return finalPrice; } public void setFinalPrice(Integer finalPrice) { this.finalPrice = finalPrice; } public void setAdditionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view.rootlayout; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.Initializable; import javafx.scene.control.Button; /** * FXML Controller class * * @author Dr.Chase */ public class AboutPopUpController { /** * Initializes the controller class. */ Button OkButton; public void initialize() { // TODO } }
import com.sun.net.httpserver.HttpServer; import handlers.*; import handlers.creep.*; import handlers.mentor.MentorEditProfile; import handlers.mentor.MentorLoginPageHandler; import handlers.mentor.coincubator.*; import handlers.mentor.quests.*; import handlers.mentor.store.*; import handlers.student.*; import handlers.mentor.students.*; import java.net.InetSocketAddress; public class App { public static void main(String[] args) throws Exception { // create a server on port 8000 HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); // set routes //Login server.createContext("/login", new LoginHandler()); //logout server.createContext("/logout", new LogoutHandler()); //Mentor handler server.createContext("/mentor/homepage", new MentorLoginPageHandler()); server.createContext("/mentor/store", new StoreHandler()); server.createContext("/mentor/students-menu", new StudentMenuHandler()); server.createContext("/mentor/add-student", new AddStudentHandler()); server.createContext("/mentor/remove-student", new RemoveStudentHandler()); server.createContext("/mentor/add-quest", new AddQuestHandler()); server.createContext("/mentor/remove-quest", new RemoveQuestHandler()); server.createContext("/mentor/add-item", new AddItemHandler()); server.createContext("/mentor/remove-item", new RemoveItemHandler()); server.createContext("/mentor/students", new StudentsListHandler()); server.createContext("/mentor/edit-student", new EditStudentHandler()); server.createContext("/mentor/quest-menu", new QuestMenuHandler()); server.createContext("/mentor/quest-list", new QuestListHandler()); server.createContext("/mentor/store-menu", new StoreMenuHandler()); server.createContext("/mentor/editProfile", new MentorEditProfile()); server.createContext("/mentor/coincubators-menu", new CoincubatorMenuHandler()); server.createContext("/mentor/add-coincubator", new AddCoincubatorHandler()); server.createContext("/mentor/edit-coincubator", new EditCoincubatorHandler()); server.createContext("/mentor/remove-coincubator", new RemoveCoincubatorHandler()); server.createContext("/mentor/coincubator-list", new CoincubatorListHandler()); server.createContext("/mentor/edit-quest", new EditQuestHandler()); server.createContext("/mentor/edit-item", new EditItemHandler()); //Student handler server.createContext("/student", new StudentLoginPageHandler()); server.createContext("/student/coincubator", new StudentCoincubatorHandler()); server.createContext("/student/quests", new StudentQuestsHandler()); server.createContext("/student/store", new StudentStoreHandler()); server.createContext("/student/inventory", new StudentInventoryHandler()); server.createContext("/student/transactions", new StudentTransactionsHandler()); server.createContext("/student/editProfile", new StudentEditProfileHandler()); //CreepHandler server.createContext("/creep", new CreepLoginPageHandler()); server.createContext("/creep/showMentors", new CreepShowMentorsHandler()); server.createContext("/creep/addMentor", new CreepAddMentorHandler()); server.createContext("/creep/editMentor", new CreepEditMentorHandler()); server.createContext("/creep/removeMentor", new CreepRemoveMentorHandler()); server.createContext("/creep/editProfile", new CreepEditProfileHandler()); server.setExecutor(null); // creates a default executor // start listening server.start(); } }
package br.com.douglastuiuiu.biometricengine.exception; /** * @author douglasg * @since 10/03/2017 */ public class ServiceException extends Exception { private static final long serialVersionUID = -1766164263398361960L; public ServiceException() { super(); } public ServiceException(String message, Throwable cause) { super(message, cause); } public ServiceException(String message) { super(message); } public ServiceException(Throwable cause) { super(cause); } }
package com.itheima.mysql_day04.jdbc_demo_05; import com.itheima.mysql_day04.util.JDBCUtils; import java.sql.*; public class Demo_05 { /* 使用ResultSet获取数据 */ public static void main(String[] args) { Statement stmt = null; Connection conn = null; ResultSet rs = null; try { //1. 注册驱动 //2. 获取连接对象 conn = JDBCUtils.getConnection(); //3. 创建sql语句 String sql = "select * from account"; //4. 获取sql语句执行对象 stmt = conn.createStatement(); //5. 执行sql语句 rs = stmt.executeQuery(sql); //6. 处理结果集 while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); double balance = rs.getDouble("balance"); System.out.println(id + ", " + name + ", " + balance); } } catch (SQLException e) { e.printStackTrace(); } finally { //7. 释放资源 JDBCUtils.close(stmt, conn, rs); } } }
package pl.almestinio.countdowndays.ui.editCountdownView; import org.joda.time.DateTime; import pl.almestinio.countdowndays.model.CountdownDay; /** * Created by mesti193 on 4/1/2018. */ public interface EditCountdownContracts { interface View{ void showSnackbarSuccess(String message); void showSnackbarError(String message); void showColorPicker(String color, int id); void startMenuFragment(); } interface Presenter{ void getColor(String color, int id); void editCountdownToDatabase(CountdownDay countdownDay, String title, DateTime dateTime, String colorStroke, String colorSolid); } }
package alien4cloud.rest.topology; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.hibernate.validator.constraints.NotBlank; /** * a nodetemplate request object * * @author 'Igor Ngouagna' */ @Getter @Setter @ToString @NoArgsConstructor @SuppressWarnings("PMD.UnusedPrivateField") public class NodeTemplateRequest { /** the name of the node template */ @NotBlank private String name; /** related NodeType id */ @NotBlank private String indexedNodeTypeId; public NodeTemplateRequest(String name, String indexedNodeTypeId) { this.name = name; this.indexedNodeTypeId = indexedNodeTypeId; } }
package be.darkshark.parkshark.api.controller; import be.darkshark.parkshark.api.dto.allocation.CreateAllocationDTO; import be.darkshark.parkshark.api.dto.allocation.GetAllocationDTO; import be.darkshark.parkshark.service.AllocationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(path = "/allocations") public class AllocationController { private final AllocationService allocationService; @Autowired public AllocationController(AllocationService allocationService) { this.allocationService = allocationService; } @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<GetAllocationDTO> getAllAllocations(@RequestParam(required = false) Integer limit, @RequestParam(required = false) String status, @RequestParam(required = false) boolean desc) { return allocationService.getAllAllocations(limit, status, desc); } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.CREATED) public GetAllocationDTO createAllocation (@RequestBody CreateAllocationDTO createAllocationDTO) { return allocationService.createAllocation(createAllocationDTO); } @PutMapping(path = "/{allocationId}/{memberId}",produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public GetAllocationDTO stopAllocation (@PathVariable long allocationId, @PathVariable long memberId) { return allocationService.stopAllocation(allocationId, memberId); } }
package Array; public class L070_ClimbStairs { public static void main(String[] args) { int n = 3; int ret = new L070_ClimbStairs().climbStairs(n); System.out.print(ret); } // 2. 仅保存最后2个数字即可 public int climbStairs(int n) { if (n <= 2) return n; int f1 = 1, f2 = 2, tmp = 0; for (int i = 3; i <= n; i++) { tmp = f1 + f2; f1 = f2; f2 = tmp; } return f2; } // 1. 数组 public int climbStairs1(int n) { if (n <= 2) return n; int[] ret = new int[n]; ret[0] = 1; ret[1] = 2; for (int i = 2; i <= n - 1; i++) { ret[i] = ret[i - 2] + ret[i - 1]; } return ret[n - 1]; } }
package com.sirma.itt.javacourse.threads.test.task5; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.sirma.itt.javacourse.threads.task5.synchronizedstack.ObjectListSynchonized; /** * Test class {@link ObjectListSynchonized} * * @author Simeon Iliev */ public class TestObjectList { private ObjectListSynchonized list; /** * Set up method. * * @throws java.lang.Exception * something went wrong. */ @Before public void setUp() throws Exception { list = new ObjectListSynchonized(1); } /** * Test method for Adding elements. */ @Test public void testAddElement() { assertTrue(list.addElement(2)); } /** * Test removing element. */ @Test public void testRemoveElement() { list.addElement(2); assertTrue(list.removeElement()); } }
package Pro30.FindGreatestSumOfSubArray; /*HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。 今天测试组开完会后,他又发话了:在古老的一维模式识别中, 常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。 但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢? 例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。 你会不会被他忽悠住?(子向量的长度至少是1)*/ public class Solution { public int FindGreatestSumOfSubArray(int[] array) { if (array.length == 0) { return 0; } int sum = array[0]; for (int i = 0; i <array.length; i++) { int compareSum = 0; for (int j = i; j < array.length; j++) { compareSum += array[j]; if (compareSum > sum) { sum = compareSum; } } } return sum; } public static void main(String[] args) { Solution solution = new Solution(); int[] array = {-1, -2, -3, -10, -4, -7, -2, -5}; int resultSum = solution.FindGreatestSumOfSubArray(array); System.out.println(resultSum); } }
package nxpense.helper; import nxpense.domain.User; import nxpense.exception.UnauthenticatedException; import nxpense.repository.UserRepository; import nxpense.security.CustomUserDetails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; @Component public class SecurityPrincipalHelper { private static final Logger LOGGER = LoggerFactory.getLogger(SecurityPrincipalHelper.class); @Autowired private UserRepository userRepository; public User getCurrentUser() { User currentUser = ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser(); if (currentUser == null) { throw new UnauthenticatedException("User does not seem to be authenticated!"); } String currentUserEmail = currentUser.getEmail(); currentUser = userRepository.findOne(currentUser.getId()); if(currentUser == null) { LOGGER.warn("User with email [{}] seems is authenticated through the application but couldn't be found in database!", currentUserEmail); throw new UnauthenticatedException("User not found in database!"); } return currentUser; } }
/** * */ package conexion; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Clase que contiene la conexion a la base de datos * * @author Darwin * */ public class Conexion { // Controlador de mysql private static final String CONTROLADOR = "com.mysql.jdbc.Driver"; // Direccion de la base de datos en mysql private static final String URL = "jdbc:mysql://localhost:3306/chocolate"; // Usuario base de datos mysql private static final String USUARIO = "root"; // Contrasenia para ingresar a mysql private static final String CLAVE = "0711"; private Connection con; /** * En este bloque estatico se carga el controlador de mysql */ static { try { Class.forName(CONTROLADOR); } catch (ClassNotFoundException e) { System.out.println("Error al cargar el controlador"); e.printStackTrace(); } } /** * Metodo que efectua la conexion entre la base de datos y la aplicacion */ public Connection conectar() { Connection conexion = null; try { conexion = DriverManager.getConnection(URL, USUARIO, CLAVE); } catch (SQLException e) { System.out.println("Error en la conexionr"); e.printStackTrace(); } return conexion; } public Connection getConnection() { return con; // Retorno el objeto Connection } }
package com.formation; import java.util.stream.Collectors; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.TokenSource; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.junit.Assert; import org.junit.Test; import com.formation.model.VehicleGroup; public class FormationBuilderTest { @Test public void testFormation() { // Get our lexer // TokenSource lexer = new FormationLexer(new ANTLRInputStream("@A,1,1#BHP,1:1")); TokenSource lexer = new FormationLexer(new ANTLRInputStream("@A,F,F,F,F,[(LK,1:1#BHP@B,1:2#BHP,1#BHP,1#BHP@C,WR:5#BHP],[2:6#BHP,2#BHP@D,2#BHP,2#BHP;VR,FA):10#BHP;VH],F,F")); // Get a list of matched tokens CommonTokenStream tokens = new CommonTokenStream(lexer); // Pass the tokens to the parser FormationParser parser = new FormationParser(tokens); // Specify our entry point FormationParser.FormationContext formationContext = parser.formation(); // Walk it and attach our listener ParseTreeWalker walker = new ParseTreeWalker(); FormationListener formationBuilder = new FormationBuilder(f -> { Assert.assertEquals(f.getFormationElements().size(), 8); Assert.assertTrue(f.getFormationElements().stream().filter(e -> { if (e.getClass().equals(VehicleGroup.class)) { return true; } return false; }).collect(Collectors.toList()).size() == 2); }); walker.walk(formationBuilder, formationContext); } }
package com.fsClothes.mapper.impl; import java.util.List; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.fsClothes.mapper.CategoryMapper; import com.fsClothes.pojo.Category; import com.fsClothes.pojo.CategoryRootBean; /** * @author MrDCG * @version 创建时间:2020年3月9日 上午11:17:02 * */ //持久层 @Repository public class CategoryMapperImpl extends SqlSessionDaoSupport implements CategoryMapper { @Autowired @Override public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { super.setSqlSessionFactory(sqlSessionFactory); } @Override public void insertRoot(CategoryRootBean crb) { getSqlSession().getMapper(CategoryMapper.class).insertRoot(crb); } @Override public void insertChild(Category cate) { getSqlSession().getMapper(CategoryMapper.class).insertChild(cate); } @Override public List<Category> findAll() { return getSqlSession().getMapper(CategoryMapper.class).findAll(); } @Override public List<Category> findToTree(int categoryParentId) { return getSqlSession().getMapper(CategoryMapper.class).findToTree(categoryParentId); } @Override public void delete(int id, int categoryParentId) { getSqlSession().getMapper(CategoryMapper.class).delete(id, categoryParentId); } @Override public int findByPid(int categoryParentId) { return getSqlSession().getMapper(CategoryMapper.class).findByPid(categoryParentId); } @Override public void updateParent(int pid) { getSqlSession().getMapper(CategoryMapper.class).updateParent(pid); } @Override public Category findById(int id) { return getSqlSession().getMapper(CategoryMapper.class).findById(id); } @Override public void updateParIsLeaf(int pid) { getSqlSession().getMapper(CategoryMapper.class).updateParIsLeaf(pid); } @Override public void deleteData(int id) { getSqlSession().getMapper(CategoryMapper.class).deleteData(id); } @Override public List<Category> findByLeaf() { return getSqlSession().getMapper(CategoryMapper.class).findByLeaf(); } @Override public List<Category> findRootCategory() { return getSqlSession().getMapper(CategoryMapper.class).findRootCategory(); } @Override public List<Category> findParentCategory(int id) { return getSqlSession().getMapper(CategoryMapper.class).findParentCategory(id); } }
public class NineEasy { private long MOD = 1000000007; public int count(int N, int[] in) { boolean[][] saw = new boolean[in.length][5]; for(int i = 0; i < saw.length; ++i) { int temp = in[i]; for(int j = 0; j < saw[i].length; ++j) { if(temp%2 == 1) { saw[i][j] = true; } temp /= 2; } } int pow = 1; long[][][][][][] sum = new long[in.length + 1][9][9][9][9][9]; sum[0][0][0][0][0][0] = 1; for(int digit = 0; digit < in.length; ++digit) { for(int a = 0; a < 9; ++a) { int aMult = saw[digit][0] ? 1 : 0; for(int b = 0; b < 9; ++b) { int bMult = saw[digit][1] ? 1 : 0; for(int c = 0; c < 9; ++c) { int cMult = saw[digit][2] ? 1 : 0; for(int d = 0; d < 9; ++d) { int dMult = saw[digit][3] ? 1 : 0; for(int e = 0; e < 9; ++e) { int eMult = saw[digit][4] ? 1 : 0; if(sum[digit][a][b][c][d][e] != 0) { for(int num = 0; num <= 9; ++num) { int nextA = (a + (aMult * num))%9; int nextB = (b + (bMult * num))%9; int nextC = (c + (cMult * num))%9; int nextD = (d + (dMult * num))%9; int nextE = (e + (eMult * num))%9; sum[digit + 1][nextA][nextB][nextC][nextD][nextE] += sum[digit][a][b][c][d][e]; sum[digit + 1][nextA][nextB][nextC][nextD][nextE] %= MOD; } } } } } } } pow *= 10; pow %= 9; } return (int)sum[in.length][0][0][0][0][0]; } }
package vista.Comandas; import java.util.Vector; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.WindowConstants; import controlador.MesaView; import controlador.Restaurante; public class FormCerrarComanda extends javax.swing.JFrame { private JLabel lblMesa; private JComboBox cmbMesas; private JLabel lblTotal; private AbstractAction cerrarMesaAction; private AbstractAction calcTotalAction; private JButton btnCerrarMesa; private JButton btnTotal; private JTextField txtTotal; public FormCerrarComanda() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); this.setTitle("Cerrar Mesa"); getContentPane().setLayout(null); this.setPreferredSize(new java.awt.Dimension(400, 200)); { lblMesa = new JLabel(); getContentPane().add(lblMesa); lblMesa.setText("SELECCIONE MESA: "); lblMesa.setBounds(12, 12, 146, 14); } { Vector mesasAbiertas = getMesasAbiertas(Restaurante.getRestaurante().getMesasView()); cmbMesas = new JComboBox(mesasAbiertas); getContentPane().add(cmbMesas); cmbMesas.setBounds(170, 9, 54, 21); } { lblTotal = new JLabel(); getContentPane().add(lblTotal); lblTotal.setText("TOTAL MESA: "); lblTotal.setBounds(78, 54, 146, 14); lblTotal.setFont(new java.awt.Font("Tahoma",1,11)); lblTotal.setForeground(new java.awt.Color(0,0,255)); } { txtTotal = new JTextField(); getContentPane().add(txtTotal); txtTotal.setBounds(255, 51, 125, 21); txtTotal.setEditable(false); txtTotal.setFont(new java.awt.Font("Tahoma",1,11)); txtTotal.setForeground(new java.awt.Color(255,0,0)); } { btnTotal = new JButton(); getContentPane().add(btnTotal); btnTotal.setText("Calcular Total"); btnTotal.setBounds(255, 9, 126, 21); btnTotal.setFont(new java.awt.Font("Tahoma",1,11)); btnTotal.setAction(getCalcTotalAction()); } { btnCerrarMesa = new JButton(); getContentPane().add(btnCerrarMesa); btnCerrarMesa.setText("Cerrar Mesa"); btnCerrarMesa.setBounds(78, 100, 303, 29); btnCerrarMesa.setFont(new java.awt.Font("Tahoma",1,11)); btnCerrarMesa.setAction(getCerrarMesaAction()); } pack(); this.setSize(400, 200); } catch (Exception e) { e.printStackTrace(); } } private AbstractAction getCalcTotalAction() { if(calcTotalAction == null) { calcTotalAction = new AbstractAction("Calcular Total", null) { public void actionPerformed(ActionEvent evt) { float total = 0; try{ total = Restaurante.getRestaurante().getTotalComanda(Integer.parseInt(cmbMesas.getSelectedItem().toString())); txtTotal.setText(String.valueOf(total)); } catch (Exception e){ JOptionPane.showMessageDialog(null, "No se pudo calcular el total de la mesa seleccionada.", "Error en el calculo del total", JOptionPane.WARNING_MESSAGE); } } }; } return calcTotalAction; } private AbstractAction getCerrarMesaAction() { if(cerrarMesaAction == null) { cerrarMesaAction = new AbstractAction("Cerrar Mesa", null) { public void actionPerformed(ActionEvent evt) { try{ Restaurante.getRestaurante().cerrarMesa(Integer.parseInt(cmbMesas.getSelectedItem().toString())); JOptionPane.showMessageDialog(null, "Mesa cerrada correctamente. Se esta imprimiendo el ticket fiscal.", "Mensaje", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e){ JOptionPane.showMessageDialog(null, "No se pudo cerrar la mesa seleccionada.", "Error en el cierre de la mesa", JOptionPane.WARNING_MESSAGE); } } }; } return cerrarMesaAction; } public Vector getMesasAbiertas (Vector<MesaView> v){ Vector mv = new Vector(); for (int i= 0; i < v.size(); i++){ if (v.elementAt(i).isOcupada()) mv.add(v.elementAt(i).getNroMesa()); } return mv; } }
import java.util.ArrayList; import java.util.List; public class PascalTriangleTwo { /** * Given the rowIndex, return the corresponding row of PascalTriangle * Input: 3 Output: [1,3,3,1] */ public List<Integer> getRow(int rowIndex) { List<Integer> toreturn = new ArrayList<Integer>(); if(rowIndex<0) return toreturn; for(int j=0; j<rowIndex+1; j++){ toreturn.add(0,1); for(int i=1; i<toreturn.size()-1; i++){ toreturn.set(i, toreturn.get(i)+toreturn.get(i+1)); } } return toreturn; } /** * Same thing. */ }
/** * */ package de.fraunhofer.iese.ids.odrl.policy.library.model.enums; /** * @author Robin Brandstaedter <Robin.Brandstaedter@iese.fraunhofer.de> * */ public enum TimeUnit { //every hour HOURS("0 0 * * * ?","H"), //every day DAYS("0 0 0 * * ?","D"), //every first day of the month MONTHS("0 0 0 1 * ?", "M"), //every first of January YEARS("0 0 0 1 1 ?", "Y"); private final String mydataCron; private final String odrlXsdDuration; TimeUnit(String op1, String op2) { mydataCron = op1; odrlXsdDuration = op2; } public String getMydataCron() { return mydataCron; } public String getOdrlXsdDuration() { return odrlXsdDuration; } }
package com.mahang.weather.common; /** * Created by hasee on 2017/3/18. */ public interface PreferenceKey { String KET_LOCATION_CITY = "location_city"; }
package com.yxkj.facexradix.room.dao; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; import com.yxkj.facexradix.room.bean.IosToken; import com.yxkj.facexradix.room.bean.Record; import java.util.List; @Dao public interface IosTokenDao { /** * @ClassName: UserDao * @Desription: * @author: Dreamcoding * @date: 2018/12/6 */ @Query("SELECT * FROM IosToken") List<IosToken> listAll(); @Query("SELECT * FROM IosToken LIMIT :start OFFSET :sum") List<IosToken> list(int start, int sum); @Query("SELECT * FROM IosToken WHERE sn=:sn") IosToken listTokenBySn(String sn); @Query("SELECT COUNT(*) FROM IosToken") int count(); @Insert void insert(IosToken... iosTokens); @Update void update(IosToken... iosTokens); @Delete void delete(IosToken... iosTokens); @Query("DELETE FROM IosToken WHERE 1=1") void deleteAll(); }
import java.util.*; public class Solution5 { public static void main(String args[]) { Scanner in=new Scanner(System.in); String s=in.next(); int j=s.length(); int i=0; j--; while(i<j) { if(s.charAt(i)==s.charAt(j)) { i++; j--; } else break; } if(i>=j) System.out.println("Palindrome"); else System.out.println("Not Palindrome"); } }
package com.example.bookspace.adapters; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.bookspace.R; import com.example.bookspace.ReviewsClass; import java.util.List; public class ReviewsAdapter extends BaseAdapter { private Context mContext1; private List<ReviewsClass> mBooksList1; public ReviewsAdapter(Context mContext,List<ReviewsClass> mBooksList){ this.mContext1 = mContext; this.mBooksList1 = mBooksList; } @Override public int getCount() { return mBooksList1.size(); } @Override public Object getItem(int position) { return mBooksList1.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row1 = View.inflate(mContext1, R.layout.reviewview, null); TextView myName = row1.findViewById(R.id.textViewUsername); TextView myDate = row1.findViewById(R.id.textViewDate); TextView myReview = (TextView) row1.findViewById(R.id.textViewReview); myName.setText(mBooksList1.get(position).getName()); myDate.setText(mBooksList1.get(position).getCreated()); myReview.setText(mBooksList1.get(position).getText()); row1.setTag(mBooksList1.get(position).getId()); return row1; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.support; import java.io.IOException; import org.junit.jupiter.api.Test; import org.springframework.beans.testfixture.beans.TestBean; import org.springframework.core.testfixture.io.SerializationTestUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rod Johnson * @author Dmitriy Kopylenko * @author Chris Beams * @author Dmitriy Kopylenko */ class JdkRegexpMethodPointcutTests { private AbstractRegexpMethodPointcut rpc = new JdkRegexpMethodPointcut(); @Test void noPatternSupplied() throws Exception { noPatternSuppliedTests(rpc); } @Test void serializationWithNoPatternSupplied() throws Exception { rpc = SerializationTestUtils.serializeAndDeserialize(rpc); noPatternSuppliedTests(rpc); } private void noPatternSuppliedTests(AbstractRegexpMethodPointcut rpc) throws Exception { assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isFalse(); assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse(); assertThat(rpc.getPatterns()).isEmpty(); } @Test void exactMatch() throws Exception { rpc.setPattern("java.lang.Object.hashCode"); exactMatchTests(rpc); rpc = SerializationTestUtils.serializeAndDeserialize(rpc); exactMatchTests(rpc); } private void exactMatchTests(AbstractRegexpMethodPointcut rpc) throws Exception { // assumes rpc.setPattern("java.lang.Object.hashCode"); assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue(); assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isTrue(); assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse(); } @Test void specificMatch() throws Exception { rpc.setPattern("java.lang.String.hashCode"); assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue(); assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isFalse(); } @Test void wildcard() throws Exception { rpc.setPattern(".*Object.hashCode"); assertThat(rpc.matches(Object.class.getMethod("hashCode"), Object.class)).isTrue(); assertThat(rpc.matches(Object.class.getMethod("wait"), Object.class)).isFalse(); } @Test void wildcardForOneClass() throws Exception { rpc.setPattern("java.lang.Object.*"); assertThat(rpc.matches(Object.class.getMethod("hashCode"), String.class)).isTrue(); assertThat(rpc.matches(Object.class.getMethod("wait"), String.class)).isTrue(); } @Test void matchesObjectClass() throws Exception { rpc.setPattern("java.lang.Object.*"); assertThat(rpc.matches(Exception.class.getMethod("hashCode"), IOException.class)).isTrue(); // Doesn't match a method from Throwable assertThat(rpc.matches(Exception.class.getMethod("getMessage"), Exception.class)).isFalse(); } @Test void withExclusion() throws Exception { this.rpc.setPattern(".*get.*"); this.rpc.setExcludedPattern(".*Age.*"); assertThat(this.rpc.matches(TestBean.class.getMethod("getName"), TestBean.class)).isTrue(); assertThat(this.rpc.matches(TestBean.class.getMethod("getAge"), TestBean.class)).isFalse(); } }
package ru.ivan.leo.otgcontrol; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.hoho.android.usbserial.driver.UsbSerialPort; import org.w3c.dom.Text; import java.sql.Time; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Main2Activity extends AppCompatActivity { Button clearLog; TextView LogDisplay; String log = ""; int i = 0; UsbSerialPort sPort = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); //SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); //String dataTime = formatter.format(new Date(Long.parseLong())) String TheTime = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()); String TTime = (android.text.format.DateFormat.format("HH:mm:ss", new java.util.Date()).toString()); clearLog = (Button) findViewById(R.id.buttonMain2); LogDisplay = (TextView) findViewById(R.id.logViewMain2); LogDisplay.setMovementMethod(new ScrollingMovementMethod()); //Time(); //SystemClock.elapsedRealtime(); //LogDisplay.setText(TTime); onStarted(); // clearLog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } void onStarted(){ i = i + 1; log = getIntent().getExtras().getString("log"); log ="\n"+ "OnStart " + i + log; LogDisplay.setText(log); //******нужно заполнить логи ****// } @Override protected void onResume(){ super.onResume(); } }
package com.huang.Test; public class ServiceTest { // DoInfoBean doBean = new DoInfoBean(); // // DelFileDao fileDao = new DelFileDao(); // // private void init(String name, String path, boolean isFile, String type, String context) { // doBean.setName(name); // doBean.setPath(path); // doBean.setIsFile(isFile); // doBean.setType(type); // doBean.setContext(context); // } // // @Test // public void delFileDaoTest() { // // init("test.txt", "D:/", true, "", ""); // // assertEquals("success", fileDao.delFile(doBean)); // // init("test.txt", "D:/", true, "", ""); // // assertEquals("success", fileDao.addFile(doBean)); // // init("test.txt", "D:/", true, "", "welcome"); // // assertEquals("success", fileDao.updateFile(doBean)); // // init("test.txt", "D:/", true, "", ""); // // assertEquals("welcome", fileDao.getFileContext(doBean)); // // init("", "D:/workSpace/", true, "", ""); // // assertEquals(".metadata:.recommenders:front:service", fileDao.getFolderList(doBean)); // } }
package com.infoworks.lab.rest.breaker; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; public class HttpResponse implements AutoCloseable { private CircuitBreaker.Status status; private Integer code; private String payload; @Override public void close() throws Exception { //TODO } public HttpResponse() { this(HttpURLConnection.HTTP_NOT_FOUND); } public HttpResponse(Integer code) { this.setCode(code); } public CircuitBreaker.Status getStatus() { return status; } public void setStatus(CircuitBreaker.Status status) { this.status = status; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; this.status = (code == HttpURLConnection.HTTP_OK) ? CircuitBreaker.Status.CLOSED : CircuitBreaker.Status.OPEN; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public void setPayload(InputStream payload) { if (payload == null) return; try (BufferedReader in = new BufferedReader( new InputStreamReader(payload))){ // String inputLine; StringBuffer response = new StringBuffer(); // while ((inputLine = in.readLine()) != null) { response.append(inputLine); } setPayload(response.toString()); } catch (IOException e) { e.printStackTrace(); } } }
package testRunner; //import org.junit.runner.RunWith; import org.testng.annotations.Test; import cucumber.api.CucumberOptions; //import cucumber.api.junit.Cucumber; import cucumber.api.testng.AbstractTestNGCucumberTests; //Uncomment @RunWith if not using Junit //@RunWith(Cucumber.class) @CucumberOptions( features={"Features"}, glue={"stepDefination"}, plugin={"html:target/cucumber-html-report", "json:target/cucumber.jason", "pretty:target/cucumber-pretty,txt", "usage:target/cucumber-usage.json", "junit:target/cucumber-result.xml" } ) @Test public class Runner extends AbstractTestNGCucumberTests{ }
/** * */ package com.miaoqi.authen.core.properties; /** * @author zhailiang * */ public class SmsCodeProperties { /** * 默认配置 */ private int length = 6; private int expireIn = 60; private String url; public int getLength() { return this.length; } public void setLength(int length) { this.length = length; } public int getExpireIn() { return this.expireIn; } public void setExpireIn(int expireIn) { this.expireIn = expireIn; } public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } }
package com.gaoshin.onsalelocal.search; import org.apache.solr.handler.dataimport.Context; public class ImportOnEndListener extends ImportListener { @Override public void onEvent(Context ctx) { String name = ctx.getSolrCore().getName(); Object value = ctx.getRequestParameters().get(KEY_END_TIME); saveProperties(ctx, KEY_END_TIME, value.toString()); System.out.println(name + ": ======= import finished. Time spent: " + (System.currentTimeMillis() - Long.parseLong(value.toString())) + ". startTime for next import is " + value + ". import stats: " + ctx.getStats()); } }
package com.example.interview.operators; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Operators { @SerializedName("rechageonetimetoken") @Expose private String rechageonetimetoken; @SerializedName("all_operator") @Expose private List<AllOperator> allOperator = null; @SerializedName("response") @Expose private Integer response; @SerializedName("status") @Expose private Boolean status; @SerializedName("message") @Expose private String message; public String getRechageonetimetoken() { return rechageonetimetoken; } public void setRechageonetimetoken(String rechageonetimetoken) { this.rechageonetimetoken = rechageonetimetoken; } public List<AllOperator> getAllOperator() { return allOperator; } public void setAllOperator(List<AllOperator> allOperator) { this.allOperator = allOperator; } public Integer getResponse() { return response; } public void setResponse(Integer response) { this.response = response; } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
package com.douglaslbittencourt.comercial; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CursoAlgaworksComercialApiApplication { public static void main(String[] args) { SpringApplication.run(CursoAlgaworksComercialApiApplication.class, args); } }
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.core.util; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Random; public class UUIDMgr { /** * The singleton instance. */ private static UUIDMgr instance; /** * The random number generator. * Used for the UUID calculation. */ private Random random; /** * The IP address of this host. * Used for the UUID calculation. */ private byte[] ip; /** * Process identifier of the java process to distinguish among * concurrent processes on a single machine. * Used for the UUID calculation. */ private long processID; /** * The counter for an improved resolution of the system clock. * Used for the UUID calculation. */ private short counter; /** * The starting value for the counter. * Used for the UUID calculation. */ private short startCounter; /** * The time when the last UUID was created. * Used for the UUID calculation. */ private long lastTime; /** * The debug mode flag. * Used for the UUID calculation. */ private boolean debugMode; /** * The initial counter state for the debug mode. * Used for the UUID calculation. */ private int initialCount = 0; /** * The class initializer, creates a new instance. */ static { instance = new UUIDMgr(); } /*----------------------------------------------------- instance methods -----------------------------------------------------*/ /** * The private constructor. * */ private UUIDMgr() { // initialize the UUID generation stuff random = new Random(); // the processID is used as a unique identifier for this java process processID = System.nanoTime(); // init the time counter with a random number counter = (short) (random.nextInt() & 0xffff); startCounter = counter; lastTime = 0L; try { InetAddress host = InetAddress.getLocalHost(); ip = host.getAddress(); } catch (UnknownHostException ue) { // host address not available, just take random numbers ip = new byte[] { (byte) (random.nextInt() & 0xff), (byte) (random.nextInt() & 0xff), (byte) (random.nextInt() & 0xff), (byte) (random.nextInt() & 0xff) }; } // switch off debug mode debugMode = false; initialCount = 0; } /** * Returns the singleton instance of the UUID manager. * * @return the UUID manager object * */ public static UUIDMgr getInstance() { return instance; } /*---------------------------------------------------------------- UUID generation methods ----------------------------------------------------------------*/ /** * Creates a new UUID string that contains no type information. * * @return the new UUID string * */ public String createUUIDString() { return createUUID(0); } /** * Switches the debug mode on or off. In the debug mode, the only * variable part of the UUID's is a counter. Therefore, we will get * the same sequence of UUID's on any machine at any time. * The counter can also be set to an initial value. * * @param debug * true to switch on debug mode, false to switch it off * * @see #setInitialCount * */ public void setDebugMode(boolean debug) { debugMode = debug; } /** * Switches the debug mode on or off. In the debug mode, the UUID's are * created starting with an initial counter. * If the debug mode is switched off, the initial counter is ignored. * * @param debugMode * true to switch on debug mode * @param initialCount * the inital count for ranges of UUID's * */ public void setDebugMode(boolean debugMode, int initialCount) { setDebugMode(debugMode); setInitialCount(initialCount); } /** * Sets the initial counter for the UUID's generated in debug mode. * * @param counter * the inital count for ranges of UUID's * * @see #setDebugMode * */ public void setInitialCount(int counter) { this.initialCount = counter; } /*------------------------------------------------------ private helper methods ------------------------------------------------------*/ /** * Creates a new UUID string. The ID consists of a class type code, * an IP address and process id of this server, the current system time, * a time resolution enhancement counter and a random number. * All components are encoded using the Base64 encoding scheme. * * @param aTypeCode * the type code to be encoded * @return the new UUID string */ private String createUUID(int aTypeCode) { // byte array for the binary representation of the UUID byte[] array = new byte[18]; // higher byte of class type code byte hiCode = (byte) ((aTypeCode >> 8) & 0xff); // lower byte of class type code byte loCode = (byte) (aTypeCode & 0xff); // type code higher part (7 bits) array[8] = hiCode; // type code lower part (8 bits) array[9] = loCode; // in debug mode UUID's are machine independent and created // always in the same sequence if (debugMode) { // unused in debug mode array[2] = 0; array[3] = 0; array[4] = 0; array[5] = 0; array[6] = 0; // unused in debug mode array[7] = (byte) 'B'; array[0] = (byte) 'e'; array[1] = (byte) 'e'; array[10] = (byte) 'h'; array[11] = (byte) 'i'; array[12] = (byte) 'v'; array[13] = (byte) 'e'; // create a lock for changing the counter synchronized (this) { // in debug mode the only variable part is a 4-byte counter array[14] = (byte) ((initialCount >> 24) & 0xff); array[15] = (byte) ((initialCount >> 16) & 0xff); array[16] = (byte) ((initialCount >> 8) & 0xff); array[17] = (byte) (initialCount & 0xff); initialCount++; } } else { // IP address (32 bits) array[2] = ip[0]; array[3] = ip[1]; array[4] = ip[2]; array[5] = ip[3]; // processID number higher part array[14] = (byte) ((processID >> 8) & 0xff); // processID number lower part array[15] = (byte) (processID & 0xff); long time = 0L; short localCounter = 0; // random number (16 bits) int rand = 0; // create a lock for changing the counter synchronized (this) { // get the creation time of the UUID (48 bits) time = System.currentTimeMillis(); if (time == lastTime) { counter++; if (counter == startCounter) { // we MUST wait until the system clock changes do { // wait for 10 milliseconds try { Thread.sleep(10); } catch (InterruptedException ie) { } // now read time again time = System.currentTimeMillis(); } while (lastTime == time); lastTime = time; } } else { lastTime = time; // init the counter counter = (short) (random.nextInt() & 0xffff); startCounter = counter; } localCounter = counter; rand = random.nextInt(); } // time stamp (48 bits) array[10] = (byte) ((time >> 40) & 0xff); array[11] = (byte) ((time >> 32) & 0xff); array[16] = (byte) ((time >> 24) & 0xff); array[17] = (byte) ((time >> 16) & 0xff); array[13] = (byte) ((time >> 8) & 0xff); array[12] = (byte) (time & 0xff); // counter (16 bits) array[6] = (byte) ((localCounter >> 8) & 0xff); array[7] = (byte) (localCounter & 0xff); array[0] = (byte) ((rand >> 8) & 0xff); array[1] = (byte) (rand & 0xff); } // encode the array in Base64 return encodeUUID(array); } /** * This method encodes the UUID byte array into a Base64 like UUID * encoded string. The resulting string will have a guaranteed length * of 24 characters. * * @param array * the binary representation of the UUID * * @return the encoded string * */ private String encodeUUID(byte[] array) { return encode(array); } public final static char[] ENCRYPTION_TABLE = { // 0 1 2 3 4 5 6 7 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 1 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 2 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 3 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 4 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 5 'w', 'x', 'y', 'z', '0', '1', '2', '3', // 6 '4', '5', '6', '7', '8', '9', '.', '_' // 7 }; /** * A static array that maps ASCII code points to a 6-bit integer, * or -1 for an invalid code point. */ protected final static byte[] dec_table = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; /** * Encodes <i>data</i> as a String using base64 like encoding. L * * @param data * The bytes that have to be encoded. * * @return the encoded string. * */ public static String encode(byte[] data) { return new String(encodeAsByteArray(data)); } /** * Encodes <i>data</i> as a byte array using base64 like encoding. The characters * 'A'-'Z', 'a'-'z', '0'-'9', '#', '_', and '=' in the output are mapped to * their ASCII code points. Line breaks in the output are represented as * CR LF (codes 13 and 10). * * @param data * The bytes that have to be encoded. * * @return the encoded byte array. * * @reviewed 08/29/99 Stefan Gloy */ public static byte[] encodeAsByteArray(byte[] data) { int i = 0, j = 0; int len = data.length; int delta = len % 3; int outlen = ((len + 2) / 3) * 4 + (len == 0 ? 2 : 0); byte[] output = new byte[outlen]; byte a, b, c; for (int count = len / 3; count > 0; count--) { a = data[i++]; b = data[i++]; c = data[i++]; output[j++] = (byte) (ENCRYPTION_TABLE[(a >>> 2) & 0x3F]); output[j++] = (byte) (ENCRYPTION_TABLE[((a << 4) & 0x30) + ((b >>> 4) & 0x0F)]); output[j++] = (byte) (ENCRYPTION_TABLE[((b << 2) & 0x3C) + ((c >>> 6) & 0x03)]); output[j++] = (byte) (ENCRYPTION_TABLE[c & 0x3F]); } if (delta == 1) { a = data[i++]; output[j++] = (byte) (ENCRYPTION_TABLE[(a >>> 2) & 0x3F]); output[j++] = (byte) (ENCRYPTION_TABLE[((a << 4) & 0x30)]); output[j++] = (byte) '='; output[j++] = (byte) '='; } else if (delta == 2) { a = data[i++]; b = data[i++]; output[j++] = (byte) (ENCRYPTION_TABLE[(a >>> 2) & 0x3F]); output[j++] = (byte) (ENCRYPTION_TABLE[((a << 4) & 0x30) + ((b >>> 4) & 0x0F)]); output[j++] = (byte) (ENCRYPTION_TABLE[((b << 2) & 0x3C)]); output[j++] = (byte) '='; } if (j != outlen) { throw new InternalError("Bug in UUIDCodec.java: incorrect length calculated for base64 output"); } return output; } /** * Decodes a byte array containing UUID-encoded ASCII. Characters with * ASCII code points &lt;= 32 (this includes whitespace and newlines) are * ignored. * * @param data * The bytes that have to be decoded. * * @return the decoded data. * @exception IllegalArgumentException * if data contains invalid characters, * i.e. not codes 0-32, 'A'-'Z', 'a'-'z', '#', '_'. or '=', or is * incorrectly padded. * */ public static byte[] decode(byte[] data) { int padCount = 0; int i, len = data.length; int real_len = 0; for (i = len - 1; i >= 0; --i) { if (data[i] > ' ') real_len++; if (data[i] == 0x3D) // ASCII '=' padCount++; } if (real_len % 4 != 0) throw new IllegalArgumentException("Length not a multiple of 4"); int ret_len = (real_len / 4) * 3 - padCount; byte[] ret = new byte[ret_len]; i = 0; byte[] t = new byte[4]; int output_index = 0; int j = 0; t[0] = t[1] = t[2] = t[3] = 0x3D; // ASCII '=' while (i < len) { byte c = data[i++]; if (c > ' ') t[j++] = c; if (j == 4) { output_index += decode(ret, output_index, t[0], t[1], t[2], t[3]); j = 0; t[0] = t[1] = t[2] = t[3] = 0x3D; // ASCII '=' } } if (j > 0) decode(ret, output_index, t[0], t[1], t[2], t[3]); return ret; } /** * Decodes a UUID-encoded String. Characters with ASCII code points &lt;= 32 * (this includes whitespace and newlines) are ignored. * * @param data * The bytes that have to be decoded. * * @return the decoded data. * @exception IllegalArgumentException * if data contains invalid characters, * i.e. not codes 0-32, 'A'-'Z', 'a'-'z', '#', '_'. or '=', or is * incorrectly padded. * * @reviewed 08/29/99 Stefan Gloy */ public static byte[] decode(String msg) throws IllegalArgumentException { return decode(msg.getBytes()); } /** * Given a block of 4 encoded bytes <code>{ a, b, c, d }</code>, this method * decodes up to 3 bytes of output, and stores them starting at <code>ret[ret_offset]</code>. * * @param ret * output buffer * @param ret_off * buffer offset * @param a * encoded byte #1 * @param b * encoded byte #2 * @param c * encoded byte #3 * @param d * encoded byte #4 * * @return the number of bytes converted. * @exception IllegalArgumentException * if a, b, c or d contain invalid * characters, or are incorrectly padded. * * @reviewed 08/29/99 Stefan Gloy */ private static int decode(byte[] ret, int ret_off, byte a, byte b, byte c, byte d) { byte da = dec_table[a]; byte db = dec_table[b]; byte dc = dec_table[c]; byte dd = dec_table[d]; if (da == -1 || db == -1 || (dc == -1 && c != 0x3D) || (dd == -1 && d != 0x3D)) throw new IllegalArgumentException("Invalid character [" + (a & 0xFF) + ", " + (b & 0xFF) + ", " + (c & 0xFF) + ", " + (d & 0xFF) + "]"); ret[ret_off++] = (byte) (da << 2 | db >>> 4); if (c == 0x3D) // ASCII '=' return 1; ret[ret_off++] = (byte) (db << 4 | dc >>> 2); if (d == 0x3D) // ASCII '=' return 2; ret[ret_off++] = (byte) (dc << 6 | dd); return 3; } }
package com.bag.pin.model; /** * Created by johnny on 25/11/15. */ public class Board { }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.tags; import jakarta.servlet.jsp.JspException; import jakarta.servlet.jsp.PageContext; import jakarta.servlet.jsp.tagext.Tag; import jakarta.servlet.jsp.tagext.TagSupport; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.web.testfixture.servlet.MockBodyContent; import org.springframework.web.testfixture.servlet.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ArgumentTag} * * @author Nicholas Williams */ public class ArgumentTagTests extends AbstractTagTests { private ArgumentTag tag; private MockArgumentSupportTag parent; @BeforeEach public void setUp() throws Exception { PageContext context = createPageContext(); parent = new MockArgumentSupportTag(); tag = new ArgumentTag(); tag.setPageContext(context); tag.setParent(parent); } @Test public void argumentWithStringValue() throws JspException { tag.setValue("value1"); int action = tag.doEndTag(); assertThat(action).isEqualTo(Tag.EVAL_PAGE); assertThat(parent.getArgument()).isEqualTo("value1"); } @Test public void argumentWithImplicitNullValue() throws JspException { int action = tag.doEndTag(); assertThat(action).isEqualTo(Tag.EVAL_PAGE); assertThat(parent.getArgument()).isNull(); } @Test public void argumentWithExplicitNullValue() throws JspException { tag.setValue(null); int action = tag.doEndTag(); assertThat(action).isEqualTo(Tag.EVAL_PAGE); assertThat(parent.getArgument()).isNull(); } @Test public void argumentWithBodyValue() throws JspException { tag.setBodyContent(new MockBodyContent("value2", new MockHttpServletResponse())); int action = tag.doEndTag(); assertThat(action).isEqualTo(Tag.EVAL_PAGE); assertThat(parent.getArgument()).isEqualTo("value2"); } @Test public void argumentWithValueThenReleaseThenBodyValue() throws JspException { tag.setValue("value3"); int action = tag.doEndTag(); assertThat(action).isEqualTo(Tag.EVAL_PAGE); assertThat(parent.getArgument()).isEqualTo("value3"); tag.release(); parent = new MockArgumentSupportTag(); tag.setPageContext(createPageContext()); tag.setParent(parent); tag.setBodyContent(new MockBodyContent("value4", new MockHttpServletResponse())); action = tag.doEndTag(); assertThat(action).isEqualTo(Tag.EVAL_PAGE); assertThat(parent.getArgument()).isEqualTo("value4"); } @SuppressWarnings("serial") private class MockArgumentSupportTag extends TagSupport implements ArgumentAware { Object argument; @Override public void addArgument(Object argument) { this.argument = argument; } private Object getArgument() { return argument; } } }
package com.cipher.c0753362_mad3125_midterm.activities; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import androidx.annotation.Nullable; import com.cipher.c0753362_mad3125_midterm.BaseActivity; import com.cipher.c0753362_mad3125_midterm.R; import com.cipher.c0753362_mad3125_midterm.SatelliteSharedPref; import com.cipher.c0753362_mad3125_midterm.pojoUsers.Users; import com.cipher.c0753362_mad3125_midterm.utils.Utility; import com.cipher.c0753362_mad3125_midterm.utils.Verifications; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class LoginActivity extends BaseActivity { BaseActivity mActivity = LoginActivity.this; private static final String TAG = "LoginActivity"; EditText etEmail; EditText etPassword; String userFile; private ArrayList<Users> usersArrayList = new ArrayList<>(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); init(); try { userFile = readUsers("users"); }catch (Exception e){ e.printStackTrace(); } readFromString(); } private void readFromString() { try { JSONArray userJsonArray = new JSONArray(userFile); for (int i =0 ; i<userJsonArray.length() ;i++){ Users users = new Users(); JSONObject userObject = userJsonArray.getJSONObject(i); users.setUserID(userObject.getInt("userID")); users.setUserName(userObject.getString("userEmail")); users.setPassword(userObject.getString("userPassword")); usersArrayList.add(users); } }catch (Exception e){ e.printStackTrace(); } } public String readUsers(String fileName) throws IOException { BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader(getAssets().open(fileName), "UTF-8")); String content = ""; String line; while ((line = reader.readLine()) != null) { content = content + line; } return content; } @Override public void init() { etEmail = findViewById(R.id.etEmail); etPassword = findViewById(R.id.etPassword); } @Override public void onClick(View v) { if (v.getId()==R.id.btnLogin){ if (isValid()){ if (checkFromList(etEmail.getText().toString(),etPassword.getText().toString())){ SatelliteSharedPref.writeString(mActivity,SatelliteSharedPref.isLogin,"true"); SatelliteSharedPref.writeString(mActivity,SatelliteSharedPref.emailId,etEmail.getText().toString()); startActivity(new Intent(mActivity , HomeActivity.class)); }else { Utility.showAlertDialog(mActivity,getString(R.string.wrongCredentialsEntered)); } } } } private boolean checkFromList(String email, String password) { for (int i =0 ; i<usersArrayList.size(); i++){ if (usersArrayList.get(i).getUserName().equalsIgnoreCase(email)){ Log.e(TAG, "email found: " ); if (usersArrayList.get(i).getPassword().equalsIgnoreCase(password)){ Log.e(TAG, "password found: "); return true; } } } return false; } private boolean isValid() { if(!Verifications.isValidEmail(etEmail.getText().toString())){ Utility.showAlertDialog(mActivity,getString(R.string.pleaseEnterValidEmail)); return false; // etEmail.setError(getString(R.string.pleaseEnterValidEmail)); }else if (!Verifications.isValidPassword(etPassword.getText().toString())){ Utility.showAlertDialog(mActivity,getString(R.string.pleaseEnterValidPassword)); return false; // etPassword.setError(getString(R.string.pleaseEnterValidPassword)); } return true; } }
package at.ac.tuwien.sepm.groupphase.backend.endpoint.dto; import at.ac.tuwien.sepm.groupphase.backend.entity.Permissions; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.Objects; public class OperatorDto { private Long id; @NotNull(message = "Name darf nicht null sein") @NotBlank(message = "Name darf nicht leer sein") @Size(max = 255, message = "Name darf nicht länger als 255 Zeichen sein") private String name; @NotNull(message = "LoginName darf nicht null sein") @NotBlank(message = "LoginName darf nicht leer sein") @Size(max = 128, message = "LoginName darf nicht länger als 128 Zeichen sein") private String loginName; @NotNull(message = "Passwort darf nicht null sein") @NotBlank(message = "Passwort darf nicht leer sein") private String password; @NotNull(message = "E-Mail darf nicht null sein") @NotBlank(message = "E-Mail darf nicht leer sein") @Email(message = "Ungültiges E-Mail-Format") private String email; @NotNull(message = "Berechtigungslevel darf nicht null sein") @Enumerated(EnumType.STRING) private Permissions permissions; public OperatorDto(){} public OperatorDto(Long id, String name, String loginName, String password, String email, Permissions permissions) { this.id = id; this.name = name; this.loginName = loginName; this.password = password; this.email = email; this.permissions = permissions; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getLoginName() { return this.loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Permissions getPermissions() { return this.permissions; } public void setPermissions(Permissions permissions) { this.permissions = permissions; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof OperatorDto)) { return false; } OperatorDto operatorLoginDto = (OperatorDto) o; return Objects.equals(id, operatorLoginDto.id) && Objects.equals(name, operatorLoginDto.name) && Objects.equals(loginName, operatorLoginDto.loginName) && Objects.equals(email, operatorLoginDto.email) && Objects.equals(password, operatorLoginDto.password) && Objects.equals(permissions, operatorLoginDto.permissions); } @Override public int hashCode() { return Objects.hash(id, name, loginName, email, password, permissions); } @Override public String toString() { return "OperatorDto{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", login_name='" + loginName + '\'' + ", email='" + email + '\'' + ", password='" + password + '\'' + ", permissions='" + permissions + '\'' + '}'; } }
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.trackselection; import static com.google.android.exoplayer2.util.Assertions.checkNotNull; import android.content.Context; import android.graphics.Point; import android.os.Looper; import android.os.Parcel; import android.os.Parcelable; import android.view.accessibility.CaptioningManager; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.util.Util; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.Locale; /** Constraint parameters for track selection. */ public class TrackSelectionParameters implements Parcelable { /** * A builder for {@link TrackSelectionParameters}. See the {@link TrackSelectionParameters} * documentation for explanations of the parameters that can be configured using this builder. */ public static class Builder { // Video private int maxVideoWidth; private int maxVideoHeight; private int maxVideoFrameRate; private int maxVideoBitrate; private int minVideoWidth; private int minVideoHeight; private int minVideoFrameRate; private int minVideoBitrate; private int viewportWidth; private int viewportHeight; private boolean viewportOrientationMayChange; private ImmutableList<String> preferredVideoMimeTypes; // Audio private ImmutableList<String> preferredAudioLanguages; @C.RoleFlags private int preferredAudioRoleFlags; private int maxAudioChannelCount; private int maxAudioBitrate; private ImmutableList<String> preferredAudioMimeTypes; // Text private ImmutableList<String> preferredTextLanguages; @C.RoleFlags private int preferredTextRoleFlags; private boolean selectUndeterminedTextLanguage; // General private boolean forceLowestBitrate; private boolean forceHighestSupportedBitrate; /** * @deprecated {@link Context} constraints will not be set using this constructor. Use {@link * #Builder(Context)} instead. */ @Deprecated public Builder() { // Video maxVideoWidth = Integer.MAX_VALUE; maxVideoHeight = Integer.MAX_VALUE; maxVideoFrameRate = Integer.MAX_VALUE; maxVideoBitrate = Integer.MAX_VALUE; viewportWidth = Integer.MAX_VALUE; viewportHeight = Integer.MAX_VALUE; viewportOrientationMayChange = true; preferredVideoMimeTypes = ImmutableList.of(); // Audio preferredAudioLanguages = ImmutableList.of(); preferredAudioRoleFlags = 0; maxAudioChannelCount = Integer.MAX_VALUE; maxAudioBitrate = Integer.MAX_VALUE; preferredAudioMimeTypes = ImmutableList.of(); // Text preferredTextLanguages = ImmutableList.of(); preferredTextRoleFlags = 0; selectUndeterminedTextLanguage = false; // General forceLowestBitrate = false; forceHighestSupportedBitrate = false; } /** * Creates a builder with default initial values. * * @param context Any context. */ @SuppressWarnings({"deprecation", "method.invocation"}) // Methods invoked are setter only. public Builder(Context context) { this(); setPreferredTextLanguageAndRoleFlagsToCaptioningManagerSettings(context); setViewportSizeToPhysicalDisplaySize(context, /* viewportOrientationMayChange= */ true); } /** * @param initialValues The {@link TrackSelectionParameters} from which the initial values of * the builder are obtained. */ protected Builder(TrackSelectionParameters initialValues) { // Video maxVideoWidth = initialValues.maxVideoWidth; maxVideoHeight = initialValues.maxVideoHeight; maxVideoFrameRate = initialValues.maxVideoFrameRate; maxVideoBitrate = initialValues.maxVideoBitrate; minVideoWidth = initialValues.minVideoWidth; minVideoHeight = initialValues.minVideoHeight; minVideoFrameRate = initialValues.minVideoFrameRate; minVideoBitrate = initialValues.minVideoBitrate; viewportWidth = initialValues.viewportWidth; viewportHeight = initialValues.viewportHeight; viewportOrientationMayChange = initialValues.viewportOrientationMayChange; preferredVideoMimeTypes = initialValues.preferredVideoMimeTypes; // Audio preferredAudioLanguages = initialValues.preferredAudioLanguages; preferredAudioRoleFlags = initialValues.preferredAudioRoleFlags; maxAudioChannelCount = initialValues.maxAudioChannelCount; maxAudioBitrate = initialValues.maxAudioBitrate; preferredAudioMimeTypes = initialValues.preferredAudioMimeTypes; // Text preferredTextLanguages = initialValues.preferredTextLanguages; preferredTextRoleFlags = initialValues.preferredTextRoleFlags; selectUndeterminedTextLanguage = initialValues.selectUndeterminedTextLanguage; // General forceLowestBitrate = initialValues.forceLowestBitrate; forceHighestSupportedBitrate = initialValues.forceHighestSupportedBitrate; } // Video /** * Equivalent to {@link #setMaxVideoSize setMaxVideoSize(1279, 719)}. * * @return This builder. */ public Builder setMaxVideoSizeSd() { return setMaxVideoSize(1279, 719); } /** * Equivalent to {@link #setMaxVideoSize setMaxVideoSize(Integer.MAX_VALUE, Integer.MAX_VALUE)}. * * @return This builder. */ public Builder clearVideoSizeConstraints() { return setMaxVideoSize(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Sets the maximum allowed video width and height. * * @param maxVideoWidth Maximum allowed video width in pixels. * @param maxVideoHeight Maximum allowed video height in pixels. * @return This builder. */ public Builder setMaxVideoSize(int maxVideoWidth, int maxVideoHeight) { this.maxVideoWidth = maxVideoWidth; this.maxVideoHeight = maxVideoHeight; return this; } /** * Sets the maximum allowed video frame rate. * * @param maxVideoFrameRate Maximum allowed video frame rate in hertz. * @return This builder. */ public Builder setMaxVideoFrameRate(int maxVideoFrameRate) { this.maxVideoFrameRate = maxVideoFrameRate; return this; } /** * Sets the maximum allowed video bitrate. * * @param maxVideoBitrate Maximum allowed video bitrate in bits per second. * @return This builder. */ public Builder setMaxVideoBitrate(int maxVideoBitrate) { this.maxVideoBitrate = maxVideoBitrate; return this; } /** * Sets the minimum allowed video width and height. * * @param minVideoWidth Minimum allowed video width in pixels. * @param minVideoHeight Minimum allowed video height in pixels. * @return This builder. */ public Builder setMinVideoSize(int minVideoWidth, int minVideoHeight) { this.minVideoWidth = minVideoWidth; this.minVideoHeight = minVideoHeight; return this; } /** * Sets the minimum allowed video frame rate. * * @param minVideoFrameRate Minimum allowed video frame rate in hertz. * @return This builder. */ public Builder setMinVideoFrameRate(int minVideoFrameRate) { this.minVideoFrameRate = minVideoFrameRate; return this; } /** * Sets the minimum allowed video bitrate. * * @param minVideoBitrate Minimum allowed video bitrate in bits per second. * @return This builder. */ public Builder setMinVideoBitrate(int minVideoBitrate) { this.minVideoBitrate = minVideoBitrate; return this; } /** * Equivalent to calling {@link #setViewportSize(int, int, boolean)} with the viewport size * obtained from {@link Util#getCurrentDisplayModeSize(Context)}. * * @param context Any context. * @param viewportOrientationMayChange Whether the viewport orientation may change during * playback. * @return This builder. */ public Builder setViewportSizeToPhysicalDisplaySize( Context context, boolean viewportOrientationMayChange) { // Assume the viewport is fullscreen. Point viewportSize = Util.getCurrentDisplayModeSize(context); return setViewportSize(viewportSize.x, viewportSize.y, viewportOrientationMayChange); } /** * Equivalent to {@link #setViewportSize setViewportSize(Integer.MAX_VALUE, Integer.MAX_VALUE, * true)}. * * @return This builder. */ public Builder clearViewportSizeConstraints() { return setViewportSize(Integer.MAX_VALUE, Integer.MAX_VALUE, true); } /** * Sets the viewport size to constrain adaptive video selections so that only tracks suitable * for the viewport are selected. * * @param viewportWidth Viewport width in pixels. * @param viewportHeight Viewport height in pixels. * @param viewportOrientationMayChange Whether the viewport orientation may change during * playback. * @return This builder. */ public Builder setViewportSize( int viewportWidth, int viewportHeight, boolean viewportOrientationMayChange) { this.viewportWidth = viewportWidth; this.viewportHeight = viewportHeight; this.viewportOrientationMayChange = viewportOrientationMayChange; return this; } /** * Sets the preferred sample MIME type for video tracks. * * @param mimeType The preferred MIME type for video tracks, or {@code null} to clear a * previously set preference. * @return This builder. */ public Builder setPreferredVideoMimeType(@Nullable String mimeType) { return mimeType == null ? setPreferredVideoMimeTypes() : setPreferredVideoMimeTypes(mimeType); } /** * Sets the preferred sample MIME types for video tracks. * * @param mimeTypes The preferred MIME types for video tracks in order of preference, or an * empty list for no preference. * @return This builder. */ public Builder setPreferredVideoMimeTypes(String... mimeTypes) { preferredVideoMimeTypes = ImmutableList.copyOf(mimeTypes); return this; } // Audio /** * Sets the preferred language for audio and forced text tracks. * * @param preferredAudioLanguage Preferred audio language as an IETF BCP 47 conformant tag, or * {@code null} to select the default track, or the first track if there's no default. * @return This builder. */ public Builder setPreferredAudioLanguage(@Nullable String preferredAudioLanguage) { return preferredAudioLanguage == null ? setPreferredAudioLanguages() : setPreferredAudioLanguages(preferredAudioLanguage); } /** * Sets the preferred languages for audio and forced text tracks. * * @param preferredAudioLanguages Preferred audio languages as IETF BCP 47 conformant tags in * order of preference, or an empty array to select the default track, or the first track if * there's no default. * @return This builder. */ public Builder setPreferredAudioLanguages(String... preferredAudioLanguages) { ImmutableList.Builder<String> listBuilder = ImmutableList.builder(); for (String language : checkNotNull(preferredAudioLanguages)) { listBuilder.add(Util.normalizeLanguageCode(checkNotNull(language))); } this.preferredAudioLanguages = listBuilder.build(); return this; } /** * Sets the preferred {@link C.RoleFlags} for audio tracks. * * @param preferredAudioRoleFlags Preferred audio role flags. * @return This builder. */ public Builder setPreferredAudioRoleFlags(@C.RoleFlags int preferredAudioRoleFlags) { this.preferredAudioRoleFlags = preferredAudioRoleFlags; return this; } /** * Sets the maximum allowed audio channel count. * * @param maxAudioChannelCount Maximum allowed audio channel count. * @return This builder. */ public Builder setMaxAudioChannelCount(int maxAudioChannelCount) { this.maxAudioChannelCount = maxAudioChannelCount; return this; } /** * Sets the maximum allowed audio bitrate. * * @param maxAudioBitrate Maximum allowed audio bitrate in bits per second. * @return This builder. */ public Builder setMaxAudioBitrate(int maxAudioBitrate) { this.maxAudioBitrate = maxAudioBitrate; return this; } /** * Sets the preferred sample MIME type for audio tracks. * * @param mimeType The preferred MIME type for audio tracks, or {@code null} to clear a * previously set preference. * @return This builder. */ public Builder setPreferredAudioMimeType(@Nullable String mimeType) { return mimeType == null ? setPreferredAudioMimeTypes() : setPreferredAudioMimeTypes(mimeType); } /** * Sets the preferred sample MIME types for audio tracks. * * @param mimeTypes The preferred MIME types for audio tracks in order of preference, or an * empty list for no preference. * @return This builder. */ public Builder setPreferredAudioMimeTypes(String... mimeTypes) { preferredAudioMimeTypes = ImmutableList.copyOf(mimeTypes); return this; } // Text /** * Sets the preferred language and role flags for text tracks based on the accessibility * settings of {@link CaptioningManager}. * * <p>Does nothing for API levels &lt; 19 or when the {@link CaptioningManager} is disabled. * * @param context A {@link Context}. * @return This builder. */ public Builder setPreferredTextLanguageAndRoleFlagsToCaptioningManagerSettings( Context context) { if (Util.SDK_INT >= 19) { setPreferredTextLanguageAndRoleFlagsToCaptioningManagerSettingsV19(context); } return this; } /** * Sets the preferred language for text tracks. * * @param preferredTextLanguage Preferred text language as an IETF BCP 47 conformant tag, or * {@code null} to select the default track if there is one, or no track otherwise. * @return This builder. */ public Builder setPreferredTextLanguage(@Nullable String preferredTextLanguage) { return preferredTextLanguage == null ? setPreferredTextLanguages() : setPreferredTextLanguages(preferredTextLanguage); } /** * Sets the preferred languages for text tracks. * * @param preferredTextLanguages Preferred text languages as IETF BCP 47 conformant tags in * order of preference, or an empty array to select the default track if there is one, or no * track otherwise. * @return This builder. */ public Builder setPreferredTextLanguages(String... preferredTextLanguages) { ImmutableList.Builder<String> listBuilder = ImmutableList.builder(); for (String language : checkNotNull(preferredTextLanguages)) { listBuilder.add(Util.normalizeLanguageCode(checkNotNull(language))); } this.preferredTextLanguages = listBuilder.build(); return this; } /** * Sets the preferred {@link C.RoleFlags} for text tracks. * * @param preferredTextRoleFlags Preferred text role flags. * @return This builder. */ public Builder setPreferredTextRoleFlags(@C.RoleFlags int preferredTextRoleFlags) { this.preferredTextRoleFlags = preferredTextRoleFlags; return this; } /** * Sets whether a text track with undetermined language should be selected if no track with * {@link #setPreferredTextLanguages(String...) a preferred language} is available, or if the * preferred language is unset. * * @param selectUndeterminedTextLanguage Whether a text track with undetermined language should * be selected if no preferred language track is available. * @return This builder. */ public Builder setSelectUndeterminedTextLanguage(boolean selectUndeterminedTextLanguage) { this.selectUndeterminedTextLanguage = selectUndeterminedTextLanguage; return this; } // General /** * Sets whether to force selection of the single lowest bitrate audio and video tracks that * comply with all other constraints. * * @param forceLowestBitrate Whether to force selection of the single lowest bitrate audio and * video tracks. * @return This builder. */ public Builder setForceLowestBitrate(boolean forceLowestBitrate) { this.forceLowestBitrate = forceLowestBitrate; return this; } /** * Sets whether to force selection of the highest bitrate audio and video tracks that comply * with all other constraints. * * @param forceHighestSupportedBitrate Whether to force selection of the highest bitrate audio * and video tracks. * @return This builder. */ public Builder setForceHighestSupportedBitrate(boolean forceHighestSupportedBitrate) { this.forceHighestSupportedBitrate = forceHighestSupportedBitrate; return this; } /** Builds a {@link TrackSelectionParameters} instance with the selected values. */ public TrackSelectionParameters build() { return new TrackSelectionParameters(this); } @RequiresApi(19) private void setPreferredTextLanguageAndRoleFlagsToCaptioningManagerSettingsV19( Context context) { if (Util.SDK_INT < 23 && Looper.myLooper() == null) { // Android platform bug (pre-Marshmallow) that causes RuntimeExceptions when // CaptioningService is instantiated from a non-Looper thread. See [internal: b/143779904]. return; } CaptioningManager captioningManager = (CaptioningManager) context.getSystemService(Context.CAPTIONING_SERVICE); if (captioningManager == null || !captioningManager.isEnabled()) { return; } preferredTextRoleFlags = C.ROLE_FLAG_CAPTION | C.ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND; Locale preferredLocale = captioningManager.getLocale(); if (preferredLocale != null) { preferredTextLanguages = ImmutableList.of(Util.getLocaleLanguageTag(preferredLocale)); } } } /** * An instance with default values, except those obtained from the {@link Context}. * * <p>If possible, use {@link #getDefaults(Context)} instead. * * <p>This instance will not have the following settings: * * <ul> * <li>{@link Builder#setViewportSizeToPhysicalDisplaySize(Context, boolean) Viewport * constraints} configured for the primary display. * <li>{@link Builder#setPreferredTextLanguageAndRoleFlagsToCaptioningManagerSettings(Context) * Preferred text language and role flags} configured to the accessibility settings of * {@link CaptioningManager}. * </ul> */ @SuppressWarnings("deprecation") public static final TrackSelectionParameters DEFAULT_WITHOUT_CONTEXT = new Builder().build(); /** * @deprecated This instance is not configured using {@link Context} constraints. Use {@link * #getDefaults(Context)} instead. */ @Deprecated public static final TrackSelectionParameters DEFAULT = DEFAULT_WITHOUT_CONTEXT; public static final Creator<TrackSelectionParameters> CREATOR = new Creator<TrackSelectionParameters>() { @Override public TrackSelectionParameters createFromParcel(Parcel in) { return new TrackSelectionParameters(in); } @Override public TrackSelectionParameters[] newArray(int size) { return new TrackSelectionParameters[size]; } }; /** Returns an instance configured with default values. */ public static TrackSelectionParameters getDefaults(Context context) { return new Builder(context).build(); } // Video /** * Maximum allowed video width in pixels. The default value is {@link Integer#MAX_VALUE} (i.e. no * constraint). * * <p>To constrain adaptive video track selections to be suitable for a given viewport (the region * of the display within which video will be played), use ({@link #viewportWidth}, {@link * #viewportHeight} and {@link #viewportOrientationMayChange}) instead. */ public final int maxVideoWidth; /** * Maximum allowed video height in pixels. The default value is {@link Integer#MAX_VALUE} (i.e. no * constraint). * * <p>To constrain adaptive video track selections to be suitable for a given viewport (the region * of the display within which video will be played), use ({@link #viewportWidth}, {@link * #viewportHeight} and {@link #viewportOrientationMayChange}) instead. */ public final int maxVideoHeight; /** * Maximum allowed video frame rate in hertz. The default value is {@link Integer#MAX_VALUE} (i.e. * no constraint). */ public final int maxVideoFrameRate; /** * Maximum allowed video bitrate in bits per second. The default value is {@link * Integer#MAX_VALUE} (i.e. no constraint). */ public final int maxVideoBitrate; /** Minimum allowed video width in pixels. The default value is 0 (i.e. no constraint). */ public final int minVideoWidth; /** Minimum allowed video height in pixels. The default value is 0 (i.e. no constraint). */ public final int minVideoHeight; /** Minimum allowed video frame rate in hertz. The default value is 0 (i.e. no constraint). */ public final int minVideoFrameRate; /** * Minimum allowed video bitrate in bits per second. The default value is 0 (i.e. no constraint). */ public final int minVideoBitrate; /** * Viewport width in pixels. Constrains video track selections for adaptive content so that only * tracks suitable for the viewport are selected. The default value is the physical width of the * primary display, in pixels. */ public final int viewportWidth; /** * Viewport height in pixels. Constrains video track selections for adaptive content so that only * tracks suitable for the viewport are selected. The default value is the physical height of the * primary display, in pixels. */ public final int viewportHeight; /** * Whether the viewport orientation may change during playback. Constrains video track selections * for adaptive content so that only tracks suitable for the viewport are selected. The default * value is {@code true}. */ public final boolean viewportOrientationMayChange; /** * The preferred sample MIME types for video tracks in order of preference, or an empty list for * no preference. The default is an empty list. */ public final ImmutableList<String> preferredVideoMimeTypes; // Audio /** * The preferred languages for audio and forced text tracks as IETF BCP 47 conformant tags in * order of preference. An empty list selects the default track, or the first track if there's no * default. The default value is an empty list. */ public final ImmutableList<String> preferredAudioLanguages; /** * The preferred {@link C.RoleFlags} for audio tracks. {@code 0} selects the default track if * there is one, or the first track if there's no default. The default value is {@code 0}. */ @C.RoleFlags public final int preferredAudioRoleFlags; /** * Maximum allowed audio channel count. The default value is {@link Integer#MAX_VALUE} (i.e. no * constraint). */ public final int maxAudioChannelCount; /** * Maximum allowed audio bitrate in bits per second. The default value is {@link * Integer#MAX_VALUE} (i.e. no constraint). */ public final int maxAudioBitrate; /** * The preferred sample MIME types for audio tracks in order of preference, or an empty list for * no preference. The default is an empty list. */ public final ImmutableList<String> preferredAudioMimeTypes; // Text /** * The preferred languages for text tracks as IETF BCP 47 conformant tags in order of preference. * An empty list selects the default track if there is one, or no track otherwise. The default * value is an empty list, or the language of the accessibility {@link CaptioningManager} if * enabled. */ public final ImmutableList<String> preferredTextLanguages; /** * The preferred {@link C.RoleFlags} for text tracks. {@code 0} selects the default track if there * is one, or no track otherwise. The default value is {@code 0}, or {@link C#ROLE_FLAG_SUBTITLE} * | {@link C#ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND} if the accessibility {@link CaptioningManager} * is enabled. */ @C.RoleFlags public final int preferredTextRoleFlags; /** * Whether a text track with undetermined language should be selected if no track with {@link * #preferredTextLanguages} is available, or if {@link #preferredTextLanguages} is unset. The * default value is {@code false}. */ public final boolean selectUndeterminedTextLanguage; // General /** * Whether to force selection of the single lowest bitrate audio and video tracks that comply with * all other constraints. The default value is {@code false}. */ public final boolean forceLowestBitrate; /** * Whether to force selection of the highest bitrate audio and video tracks that comply with all * other constraints. The default value is {@code false}. */ public final boolean forceHighestSupportedBitrate; protected TrackSelectionParameters(Builder builder) { // Video this.maxVideoWidth = builder.maxVideoWidth; this.maxVideoHeight = builder.maxVideoHeight; this.maxVideoFrameRate = builder.maxVideoFrameRate; this.maxVideoBitrate = builder.maxVideoBitrate; this.minVideoWidth = builder.minVideoWidth; this.minVideoHeight = builder.minVideoHeight; this.minVideoFrameRate = builder.minVideoFrameRate; this.minVideoBitrate = builder.minVideoBitrate; this.viewportWidth = builder.viewportWidth; this.viewportHeight = builder.viewportHeight; this.viewportOrientationMayChange = builder.viewportOrientationMayChange; this.preferredVideoMimeTypes = builder.preferredVideoMimeTypes; // Audio this.preferredAudioLanguages = builder.preferredAudioLanguages; this.preferredAudioRoleFlags = builder.preferredAudioRoleFlags; this.maxAudioChannelCount = builder.maxAudioChannelCount; this.maxAudioBitrate = builder.maxAudioBitrate; this.preferredAudioMimeTypes = builder.preferredAudioMimeTypes; // Text this.preferredTextLanguages = builder.preferredTextLanguages; this.preferredTextRoleFlags = builder.preferredTextRoleFlags; this.selectUndeterminedTextLanguage = builder.selectUndeterminedTextLanguage; // General this.forceLowestBitrate = builder.forceLowestBitrate; this.forceHighestSupportedBitrate = builder.forceHighestSupportedBitrate; } /* package */ TrackSelectionParameters(Parcel in) { ArrayList<String> preferredAudioLanguages = new ArrayList<>(); in.readList(preferredAudioLanguages, /* loader= */ null); this.preferredAudioLanguages = ImmutableList.copyOf(preferredAudioLanguages); this.preferredAudioRoleFlags = in.readInt(); ArrayList<String> preferredTextLanguages1 = new ArrayList<>(); in.readList(preferredTextLanguages1, /* loader= */ null); this.preferredTextLanguages = ImmutableList.copyOf(preferredTextLanguages1); this.preferredTextRoleFlags = in.readInt(); this.selectUndeterminedTextLanguage = Util.readBoolean(in); // Video this.maxVideoWidth = in.readInt(); this.maxVideoHeight = in.readInt(); this.maxVideoFrameRate = in.readInt(); this.maxVideoBitrate = in.readInt(); this.minVideoWidth = in.readInt(); this.minVideoHeight = in.readInt(); this.minVideoFrameRate = in.readInt(); this.minVideoBitrate = in.readInt(); this.viewportWidth = in.readInt(); this.viewportHeight = in.readInt(); this.viewportOrientationMayChange = Util.readBoolean(in); ArrayList<String> preferredVideoMimeTypes = new ArrayList<>(); in.readList(preferredVideoMimeTypes, /* loader= */ null); this.preferredVideoMimeTypes = ImmutableList.copyOf(preferredVideoMimeTypes); // Audio this.maxAudioChannelCount = in.readInt(); this.maxAudioBitrate = in.readInt(); ArrayList<String> preferredAudioMimeTypes = new ArrayList<>(); in.readList(preferredAudioMimeTypes, /* loader= */ null); this.preferredAudioMimeTypes = ImmutableList.copyOf(preferredAudioMimeTypes); // General this.forceLowestBitrate = Util.readBoolean(in); this.forceHighestSupportedBitrate = Util.readBoolean(in); } /** Creates a new {@link Builder}, copying the initial values from this instance. */ public Builder buildUpon() { return new Builder(this); } @Override @SuppressWarnings("EqualsGetClass") public boolean equals(@Nullable Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } TrackSelectionParameters other = (TrackSelectionParameters) obj; // Video return maxVideoWidth == other.maxVideoWidth && maxVideoHeight == other.maxVideoHeight && maxVideoFrameRate == other.maxVideoFrameRate && maxVideoBitrate == other.maxVideoBitrate && minVideoWidth == other.minVideoWidth && minVideoHeight == other.minVideoHeight && minVideoFrameRate == other.minVideoFrameRate && minVideoBitrate == other.minVideoBitrate && viewportOrientationMayChange == other.viewportOrientationMayChange && viewportWidth == other.viewportWidth && viewportHeight == other.viewportHeight && preferredVideoMimeTypes.equals(other.preferredVideoMimeTypes) // Audio && preferredAudioLanguages.equals(other.preferredAudioLanguages) && preferredAudioRoleFlags == other.preferredAudioRoleFlags && maxAudioChannelCount == other.maxAudioChannelCount && maxAudioBitrate == other.maxAudioBitrate && preferredAudioMimeTypes.equals(other.preferredAudioMimeTypes) && preferredTextLanguages.equals(other.preferredTextLanguages) && preferredTextRoleFlags == other.preferredTextRoleFlags && selectUndeterminedTextLanguage == other.selectUndeterminedTextLanguage // General && forceLowestBitrate == other.forceLowestBitrate && forceHighestSupportedBitrate == other.forceHighestSupportedBitrate; } @Override public int hashCode() { int result = 1; // Video result = 31 * result + maxVideoWidth; result = 31 * result + maxVideoHeight; result = 31 * result + maxVideoFrameRate; result = 31 * result + maxVideoBitrate; result = 31 * result + minVideoWidth; result = 31 * result + minVideoHeight; result = 31 * result + minVideoFrameRate; result = 31 * result + minVideoBitrate; result = 31 * result + (viewportOrientationMayChange ? 1 : 0); result = 31 * result + viewportWidth; result = 31 * result + viewportHeight; result = 31 * result + preferredVideoMimeTypes.hashCode(); // Audio result = 31 * result + preferredAudioLanguages.hashCode(); result = 31 * result + preferredAudioRoleFlags; result = 31 * result + maxAudioChannelCount; result = 31 * result + maxAudioBitrate; result = 31 * result + preferredAudioMimeTypes.hashCode(); // Text result = 31 * result + preferredTextLanguages.hashCode(); result = 31 * result + preferredTextRoleFlags; result = 31 * result + (selectUndeterminedTextLanguage ? 1 : 0); // General result = 31 * result + (forceLowestBitrate ? 1 : 0); result = 31 * result + (forceHighestSupportedBitrate ? 1 : 0); return result; } // Parcelable implementation. @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeList(preferredAudioLanguages); dest.writeInt(preferredAudioRoleFlags); dest.writeList(preferredTextLanguages); dest.writeInt(preferredTextRoleFlags); Util.writeBoolean(dest, selectUndeterminedTextLanguage); // Video dest.writeInt(maxVideoWidth); dest.writeInt(maxVideoHeight); dest.writeInt(maxVideoFrameRate); dest.writeInt(maxVideoBitrate); dest.writeInt(minVideoWidth); dest.writeInt(minVideoHeight); dest.writeInt(minVideoFrameRate); dest.writeInt(minVideoBitrate); dest.writeInt(viewportWidth); dest.writeInt(viewportHeight); Util.writeBoolean(dest, viewportOrientationMayChange); dest.writeList(preferredVideoMimeTypes); // Audio dest.writeInt(maxAudioChannelCount); dest.writeInt(maxAudioBitrate); dest.writeList(preferredAudioMimeTypes); // General Util.writeBoolean(dest, forceLowestBitrate); Util.writeBoolean(dest, forceHighestSupportedBitrate); } }
package com.drugstore.pdp.product.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="PRODUCT_INFO") public class ProductInfo { @Id @GeneratedValue private long id; @Column(name="PRODUCTNAME") private String productName; @Column(name="COST_PRICE") private float costPrice; @Column(name="SELLING_PRICE") private float sellingPrice; @Column(name="PRODUCT_CATEGORY_NAME") private String productCategoryName; @Column(name="COMPANY_NAME") private String companyName; @Column(name="MFG_DATE") private Date mfgDate; @Column(name="EXP_DATE") private Date expDate; @Column(name="PACKAGING") private String packaging; @Column(name="QUANTITY") private long quantity; @Column private String batchNO; private String deals; @Column(name="LASTUPDATED_DATE") Date lastUpdatedDate; @Column(name="LASTUPDATED_BY") String lastUpdatedBy; @Column(name="CREATION_DATE") Date creationDate; @Column(name="CREATED_BY") String createdBy; @Column(name="INVALID_FLAG") char invalidFlag; @Column(name="DELETE_FLAG") char deleteFlag; private String searchKeyOfProduct; public void setSearchKeyOfProduct(String searchKeyOfProduct) { this.searchKeyOfProduct = searchKeyOfProduct; } public String getSearchKeyOfProduct() { return searchKeyOfProduct; } public ProductInfo() { // TODO Auto-generated constructor stub } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public float getCostPrice() { return costPrice; } public void setCostPrice(float costPrice) { this.costPrice = costPrice; } public float getSellingPrice() { return sellingPrice; } public void setSellingPrice(float sellingPrice) { this.sellingPrice = sellingPrice; } public String getProductCategoryName() { return productCategoryName; } public void setProductCategoryName(String productCategoryName) { this.productCategoryName = productCategoryName; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public Date getMfgDate() { return mfgDate; } public void setMfgDate(Date mfgDate) { this.mfgDate = mfgDate; } public Date getExpDate() { return expDate; } public void setExpDate(Date expDate) { this.expDate = expDate; } public String getPackaging() { return packaging; } public void setPackaging(String packaging) { this.packaging = packaging; } public long getQuantity() { return quantity; } public void setQuantity(long quantity) { this.quantity = quantity; } public Date getLastUpdatedDate() { return lastUpdatedDate; } public void setLastUpdatedDate(Date lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; } public String getLastUpdatedBy() { return lastUpdatedBy; } public void setLastUpdatedBy(String lastUpdatedBy) { this.lastUpdatedBy = lastUpdatedBy; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public char getInvalidFlag() { return invalidFlag; } public void setInvalidFlag(char invalidFlag) { this.invalidFlag = invalidFlag; } public char getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(char deleteFlag) { this.deleteFlag = deleteFlag; } public void setBatchNO(String batchNO) { this.batchNO = batchNO; } public String getBatchNO() { return batchNO; } public void setDeals(String deals) { this.deals = deals; } public String getDeals() { return deals; } }
public class HelloTopia { public static void main(String[] args) { System.out.println("Hello Topia"); } }
package com.ctgu.lan.manage.controller; import com.ctgu.lan.manage.utils.MD5Util; import org.springframework.http.HttpRequest; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @Description TODO * @auther lan_wh * @create 2019-05-25 16:45 * @ClassName adminLoginController * @Version 1.0.0 */ @RestController @RequestMapping("/admin") public class adminLoginController { @RequestMapping("/login") public void adminLogin(@RequestParam("phoneNumber")String phoneNumber , @RequestParam("passWord")String passWord, Model model){ String cryptPassWord = MD5Util.crypt(passWord); System.out.println(cryptPassWord); model.addAttribute("loginErrorMsg","密码错误"); } }
package com.springbootreactapi.api.controller; import com.springbootreactapi.api.model.User; import com.springbootreactapi.api.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; //@CrossOrigin(origins = "http://localhost:3023") test comment @RestController @RequestMapping("api/") public class UserController { @Autowired private UserRepository userRepository; @GetMapping("users") public List<User> getUsers () { return this.userRepository.findAll(); } @PostMapping("users") public String addUser(@RequestBody User user) { User userToSave = new User(user.getFirstName(), user.getLastName(), user.getEmail()); userRepository.save(userToSave); return "redirect:"; } }
package com.rankytank.client.gui; import com.google.gwt.user.client.ui.Button; /** * */ public class AddPlayerButton extends Button { public AddPlayerButton() { setStyleName("colorbutton3"); } }
package dev.nowalk.repositories; import java.util.List; import dev.nowalk.models.Movie; public interface MovieRepo { // The primary functionality that we would like our Repository (DAO, data access object) Layer to achieve is the //CRUD operation on our Data. //some common Retrieve/Read methods public Movie getMovie(int id); public List<Movie> getAllMovies(); //Create method public Movie addMovie(Movie m); //Update method public Movie updateMovie(Movie change); //Delete method public Movie deleteMovie(int id); }
package idv.emp.dao; import java.util.List; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import idv.emp.model.Emp2; //@RunWith(SpringRunner.class) //@SpringBootTest public class YlParamRepositoryTest { // @Autowired // private EmpVODao empVODao;DEEEE // // @Ignore // @Test // public void testFindAll() { // List<EmpVO> list = empVODao.findAll(); // for (EmpVO aEmp : list) { // System.out.print(aEmp.getId().getEmpNo() + ","); // System.out.print(aEmp.getEname() + ","); // System.out.print(aEmp.getJob() + ","); // System.out.print(aEmp.getHiredate() + ","); // System.out.print(aEmp.getSal() + ","); // System.out.print(aEmp.getComm() + ","); // System.out.print(aEmp.getDeptno()); // System.out.println(); // } // } }
package com.codingchili.social.configuration; import com.codingchili.social.model.*; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; import java.util.ArrayList; import java.util.List; import com.codingchili.core.context.CoreContext; import com.codingchili.core.context.SystemContext; import com.codingchili.core.files.Configurations; import com.codingchili.core.protocol.Serializer; import com.codingchili.core.security.Token; import com.codingchili.core.security.TokenFactory; import com.codingchili.core.storage.StorageLoader; /** * @author Robin Duda * <p> * Context wrapper for the social service. */ public class SocialContext extends SystemContext { private static final String FRIENDS = "friends"; private OnlineDB online; private AsyncFriendStore friends; private TokenFactory factory; private PartyEngine party; protected SocialContext() { } private SocialContext(CoreContext core) { super(core); this.factory = new TokenFactory(core, settings().getClientSecret()); this.online = new OnlineDB(this); this.party = new PartyEngine(this); } /** * Creates the social context and asynchronously sets up databases. * * @param core the core context to create the social context on. * @return future. */ public static Future<SocialContext> create(CoreContext core) { Future<SocialContext> future = Future.future(); SocialContext context = new SocialContext(core); new StorageLoader<FriendList>(core) .withPlugin(context.settings().getStorage()) .withValue(FriendList.class) .withDB(FRIENDS) .build(storage -> { if (storage.succeeded()) { context.setFriends(new FriendsDB(storage.result(), context.online())); future.complete(context); } else { future.fail(storage.cause()); } }); return future; } private void setFriends(AsyncFriendStore db) { this.friends = db; } /** * @return database used to store friend relations. */ public AsyncFriendStore friends() { return friends; } /** * @return in-memory database for tracking online accounts. */ public OnlineDB online() { return online; } /** * @return the party manager. */ public PartyEngine party() { return party; } /** * @param token a client token to verify the signature of. * @return future. */ public Future<Void> verify(Token token) { return factory.verify(token); } /** * @return the settings for this social service. */ public SocialSettings settings() { return Configurations.get(SocialSettings.PATH, SocialSettings.class); } /** * Sends a client message to all realms. * * @param target the receiver account id of the message. * @param message the message to send. * @return future completed on request completion. */ public CompositeFuture send(String target, Object message) { List<Future> futures = new ArrayList<>(); for (String realm : online.realms(target)) { Future<Void> future = Future.future(); futures.add(future); bus().request(realm, Serializer.json(message), done -> { if (done.succeeded()) { future.complete(); } else { future.fail(done.cause()); } }); } return CompositeFuture.all(futures); } }
package io.flyingmongoose.brave.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.app.FragmentManager; import io.flyingmongoose.brave.fragment.FragGroupsNewOld; import io.flyingmongoose.brave.fragment.FragGroupsPrivate; import io.flyingmongoose.brave.fragment.FragGroupsPublicOld; /** * Created by IC on 5/24/2015. */ public class VPAdaptGroups extends FragmentStatePagerAdapter { CharSequence titles[]; int numberOfTabs; public VPAdaptGroups(FragmentManager fragMang, CharSequence titles[], int numberOfTabs) { super(fragMang); this.titles = titles; this.numberOfTabs = numberOfTabs; } @Override public Fragment getItem(int position) { switch (position) { case 0: FragGroupsPublicOld fragGroupPublic = new FragGroupsPublicOld(); return fragGroupPublic; case 1: FragGroupsPrivate fragGroupPrivate = new FragGroupsPrivate(); return fragGroupPrivate; case 2: FragGroupsNewOld fragGroupNew = new FragGroupsNewOld(); return fragGroupNew; default: FragGroupsPublicOld fragGroupPublicDefault = new FragGroupsPublicOld(); return fragGroupPublicDefault; } } @Override public CharSequence getPageTitle(int position) { return titles[position]; } @Override public int getCount() { return numberOfTabs; } }
package edu.gyaneshm.ebay_product_search.shared; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.Locale; import edu.gyaneshm.ebay_product_search.EbayProductSearchApplication; import edu.gyaneshm.ebay_product_search.R; public class Utils { public static String formatPriceToString(Double number) { if (number == null) { return ""; } if (Math.floor(number) == number) { return String.format(Locale.getDefault(), "%.1f", number); } else { return String.format(Locale.getDefault(), "%.2f", number); } } public static String truncateString(String str, int len) { if (str.length() > len) { str = str.substring(0, len) + getString(R.string.horizontal_ellipsis); } return str; } public static String getString(int id) { return EbayProductSearchApplication.getInstance().getApplicationContext().getString(id); } public static void showToast(int id) { showToast(getString(id)); } public static void showToast(String... messages) { StringBuilder str = new StringBuilder(); for (String s : messages) { str.append(s); str.append(" "); } showToast(str.toString().trim()); } public static void showToast(String message) { Toast.makeText( EbayProductSearchApplication.getInstance(), message, Toast.LENGTH_SHORT ).show(); } public static String doubleToString(Double n) { return String.valueOf((int) Math.round(Math.floor(n))); } public static int doubleToInt(Double n) { return (int) Math.round(Math.floor(n)); } public static String optString(JSONObject json, String key) { if (json.isNull(key)) return null; else return json.optString(key, null); } public static Double optDouble(JSONObject json, String key) { if (json.isNull(key)) return null; else return json.optDouble(key); } public static Boolean optBoolean(JSONObject json, String key) { if (json.isNull(key)) return false; else return json.optBoolean(key, false); } public static JSONArray optJSONArray(JSONObject json, String key) { if (json.isNull(key)) return new JSONArray(); else return json.optJSONArray(key); } public static String capitalizeFirstCharacter(String str) { if (str == null) { return null; } return str.substring(0, 1).toUpperCase() + str.substring(1); } }
package com.cdapplications.until; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.widget.DatePicker; import java.util.Calendar; /** * Created by Colin on 2015-09-06. */ public class PickDateFragment extends DialogFragment { public static PickDateFragment newInstance(){ return new PickDateFragment(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState){ Calendar calendar = Calendar.getInstance(); super.onCreateDialog(savedInstanceState); AlertDialog dateDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { UntilHomeActivity activity = ((UntilHomeActivity) getActivity()); activity.storeDate(year, monthOfYear, dayOfMonth); activity.updatePreview(); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); return dateDialog; } }
package com.javatunes.domain; import java.io.Serializable; import javax.inject.Named; @Named public class Transaction implements Serializable { private static final long serialVersionUID = 1L; private long id; private String userName; private double subTotal; private double tax; private double total; private Cart cart; public Transaction() { } public Transaction(final long id, final String userName, final double tax, final double total, final double subTotal) { super(); this.id = id; this.userName = userName; this.tax = tax; this.total = total; this.subTotal = subTotal; this.cart = null; } public Transaction(final String id) { this.userName = id; } public Cart getCart() { return this.cart; } public long getId() { return this.id; } public double getSubTotal() { return this.subTotal; } /** * @return the tax */ public double getTax() { return this.tax; } /** * @return the total */ public double getTotal() { return this.total; } /** * @return the userName */ public String getUserName() { return this.userName; } public void setCart(final Cart cart) { this.cart = cart; } public void setId(final long id) { this.id = id; } public void setSubTotal(final double subTotal) { this.subTotal = subTotal; } /** * @param tax the tax to set */ public void setTax(final double tax) { this.tax = tax; } /** * @param total the total to set */ public void setTotal(final double total) { this.total = total; } /** * @param userName the userName to set */ public void setUserName(final String userName) { this.userName = userName; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Transaction [userName=" + this.userName + ", subTotal=" + this.subTotal + ", tax=" + this.tax + ", total=" + this.total + ", cart=" + this.cart + "]"; } }
package com.sise.bishe; import com.sise.bishe.dao.UserMapper; import com.sise.bishe.entity.User; import com.sise.bishe.service.UserService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.xml.ws.Action; import java.util.List; @SpringBootTest class BisheApplicationTests { @Autowired UserMapper userMapper; @Autowired UserService userService; @Test void contextLoads() { User mlz = userMapper.findUserByUsernameAndPwd("mlz", "$apr1$mlz$.9DYx7szmYqBJrdepYGC11"); System.out.println(mlz); } }
package com.mediafire.sdk; import com.mediafire.sdk.response_models.MediaFireApiResponse; public interface MediaFireApiResponseParser { /** * parses a response as a byte[] to an ApiResponse of the type passed * @param response * @param classOfT * @param <T> * @return null if the response could not be parsed */ <T extends MediaFireApiResponse> T parseResponse(MediaFireHttpResponse response, Class<T> classOfT) throws MediaFireException; /** * response format (json or xml) * @return */ String getResponseFormat(); }
import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentCatalog; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont; import org.apache.pdfbox.pdmodel.font.PDType0Font; import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm; import org.apache.pdfbox.pdmodel.interactive.form.PDField; import org.apache.pdfbox.pdmodel.interactive.form.PDTextField; import org.apache.pdfbox.pdmodel.interactive.form.PDVariableText; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class main { public static void main(String[] args) throws IOException { //Loading an existing document File file = new File("E:\\Utils\\BMBNHS_PRO_KH giao.pdf"); PDDocument document = PDDocument.load(file); PDFont formFont = PDType0Font.load(document, new FileInputStream("E:\\Utils\\src\\main\\resources\\timesbd.ttf"), false); // check that the font has what you need; ARIALUNI.TTF is good but huge PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); PDResources res = acroForm.getDefaultResources(); // could be null, if so, then create it with the setter String fontName = res.add(formFont).getName(); String defaultAppearanceString = "/" + fontName + " 0 Tf 0 g"; // adjust to replace existing font name PDTextField textField = (PDTextField) acroForm.getField("cus_full_name"); textField.setDefaultAppearance(defaultAppearanceString); textField.setValue("ĐÀO MẠNH"); document.save("E:\\Utils\\456.pdf"); //Closing the document document.close(); } }
package apptsched.bootstrap; import apptsched.common.DateHelper; import apptsched.domain.Appointment; import apptsched.domain.Client; import apptsched.domain.Employee; import apptsched.services.AppointmentService; import apptsched.services.ClientService; import apptsched.services.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by Logan.Moen on 7/24/2017. */ @Component public class SeedData implements ApplicationListener<ContextRefreshedEvent>{ private final EmployeeService employeeService; private final ClientService clientService; private final AppointmentService appointmentService; @Autowired public SeedData(EmployeeService employeeService, ClientService clientService, AppointmentService appointmentService){ this.appointmentService = appointmentService; this.clientService = clientService; this.employeeService = employeeService; } @Override public void onApplicationEvent(ContextRefreshedEvent event){ // method1(); // Pageable p = new PageRequest(0, 1, Sort.Direction.DESC, "emailAddress"); // Sort email = new Sort(Sort.Direction.ASC, "emailAddress"); // for(Employee e : employeeService.findAll(p)) // System.out.println(e.getFirstName() + " " + e.getLastName() + ": " + e.getEmailAddress()); } private void method1(){ // appointmentService.deleteAll(); // employeeService.deleteAll(); // clientService.deleteAll(); List<Date> e1PTO = new ArrayList<>(); e1PTO.add(DateHelper.dateConstructor(1995, 1, 1, false)); e1PTO.add(DateHelper.dateConstructor(1995, 1, 2, false)); List<Date> e2PTO = new ArrayList<>(); e1PTO.add(DateHelper.dateConstructor(1996, 1, 1, false)); e1PTO.add(DateHelper.dateConstructor(1996, 1, 2, false)); Employee employee1 = new Employee("Logan", "Moen", "Robert", "lrmoen@astontech.com", "952-929-2233", (DateHelper.dateConstructor(1992, 1, 1, false)), "Doctor"); Employee employee2 = new Employee("Jay", "Moen", "Andrew", "jamoen@astontech.com", "952-929-2133", (DateHelper.dateConstructor(1997, 1, 1, false)), "Lawyer"); Client client1 = new Client("Andrew", "Warnke", "Christopher", "acwarnke@gmail.com", "952-929-2234", (DateHelper.dateConstructor(1992, 3, 3, false))); Client client2 = new Client("Chris", "Warnke", "Rodney", "crwarnke@gmail.com", "952-929-2264", (DateHelper.dateConstructor(1996, 3, 3, false))); employee1.setPto(e1PTO); employee1.setPto(e2PTO); employeeService.save(employee1); employeeService.save(employee2); clientService.save(client1); clientService.save(client2); List<Appointment> e1Appt = new ArrayList<>(); Appointment appt1 = new Appointment("Meeting", (DateHelper.dateConstructor(2000, 1, 1, false).toString()), "F204", employeeService.findOne(1), clientService.findOne(3)); Appointment appt2 = new Appointment("Check-Up", (DateHelper.dateConstructor(2004, 1, 1, false).toString()), "F209", employeeService.findOne(2), clientService.findOne(3)); Appointment appt4 = new Appointment("Review", (DateHelper.dateConstructor(2004, 1, 6, false).toString()), "F209", employeeService.findOne(1), clientService.findOne(3)); appt1.setCompleted(true); appt2.setCompleted(true); e1Appt.add(appt1); e1Appt.add(appt2); e1Appt.add(appt4); appointmentService.save(e1Appt); Appointment apt = new Appointment("Consulting", new Date().toString(), "F449", employeeService.findOne(1), clientService.findOne(4)); appointmentService.save(apt); } }
package com.example.entity.base; /** * Created by ZYB on 2017-03-10. */ public class Result<T> { public int code; public String msg; public T data; public int getCode() { return code; } public String getMsg() { return msg; } public T getData() { return data; } public void setCode(int code) { this.code = code; } public void setMsg(String msg) { this.msg = msg; } public void setData(T data) { this.data = data; } @Override public String toString() { return "Result{" + "code=" + code + ", msg='" + msg + '\'' + ", data=" + data + '}'; } public boolean isSuccess() { return this.code == 200; } }
package com.bobo.portal.user.servlet; import com.bobo.bean.User; import com.bobo.common.BaseServlet; import com.bobo.portal.user.dao.impl.UserDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; /** * @Author: bobobo * @Date: 2019/8/8 9:21 * @Version:1.0 */ @WebServlet({"/userServlet.do"}) public class UserServlet extends BaseServlet{ private static final long serialVersionUID = 1L; private UserDao userDao = null; @Override public void init() throws ServletException { super.init(); userDao = (UserDao) applicationContext.getBean("userDao"); } /*注册方法*/ //该方法的url是 http://www.zc.com/userServlet.do?method=regUser public String regUser(HttpServletRequest request, HttpServletResponse response) { try { request.setCharacterEncoding("GBK"); String loginacct = request.getParameter("loginacct"); String userpswd = request.getParameter("userpswd"); String email = request.getParameter("email"); String username = request.getParameter("username"); String name = new String(username.getBytes("iso-8859-1"),"UTF-8"); String userType = request.getParameter("userType"); User user = new User(loginacct,userpswd,username,email); int num =userDao.addUser(user); if(num>=1) { return "index.html"; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return "error.html"; } /*登陆方法*/ public String dologin(HttpServletRequest request, HttpServletResponse response){ PrintWriter out = null; try { out = response.getWriter(); String loginacct = request.getParameter("loginacct"); String userpswd = request.getParameter("userpswd"); User user = new User(loginacct, userpswd, null, null); User loguser = userDao.loginUser(user); if (loguser == null){ out.print("error"); //表示状态 纯文本 }else { out.print("ok"); } } catch (IOException e) { e.printStackTrace(); return "error.html"; } return null; } }
package com.shopping.webScoket;
public class LastWordLength { public int lengthOfLastWord(String s) { int length = 0; String[] result = s.trim().split(" "); return result[result.length - 1].length(); } } class LastWordLengthTest { public static void main(String[] args) { System.out.println(new LastWordLength().lengthOfLastWord(" afd b ")); } }
package com.codepath.instagram.fragments; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.codepath.instagram.R; import com.codepath.instagram.core.MainApplication; import com.codepath.instagram.helpers.EndlessScrollListener; import com.codepath.instagram.helpers.Utils; import com.codepath.instagram.helpers.adapters.InstagramPostsAdapter; import com.codepath.instagram.models.InstagramPost; import com.codepath.instagram.models.InstagramPosts; import com.codepath.instagram.networking.NetworkService; import com.codepath.instagram.persistence.InstagramClientDatabase; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONObject; import java.util.List; import cz.msebera.android.httpclient.Header; /** * Created by araiff on 11/1/15. */ public class PostsFragment extends Fragment { private Context mContext; private View mLayout; private String mSrc; private String mNextSrc; private RecyclerView rvPosts; private SwipeRefreshLayout swipeContainer; private InstagramPostsAdapter adapter; private LinearLayoutManager layoutManager; private JsonHttpResponseHandler handler = new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { List<InstagramPost> posts = Utils.decodePostsFromJsonResponse(response); mNextSrc = Utils.getNextSrc(response); /*InstagramClientDatabase db = InstagramClientDatabase.getInstance(mContext); db.emptyAllTables(); db.addInstagramPosts(posts);*/ loadUI(posts); } @Override public void onFailure(int statusCode, Header[] headers, String res, Throwable t) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) Log.d("ATOM", "failed request!!!"); } }; private JsonHttpResponseHandler infiniteHandler = new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { List<InstagramPost> posts = Utils.decodePostsFromJsonResponse(response); appendToList(posts); mNextSrc = Utils.getNextSrc(response); } }; @Override public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { mLayout = inflater.inflate(R.layout.fragment_posts, container, false); mContext = container.getContext(); initUI(); if (MainApplication.getRestClient().isNetworkAvailable(mContext)) { MainApplication.getRestClient().getPostsFromSource(mSrc, handler); } else { /*InstagramClientDatabase db = InstagramClientDatabase.getInstance(mContext); List<InstagramPost> posts = db.getAllInstagramPosts(); loadUI(posts);*/ } return mLayout; } public void setPostSource(String src) { mSrc = src; } private void initUI() { layoutManager = new LinearLayoutManager(mLayout.getContext()); rvPosts = (RecyclerView) mLayout.findViewById(R.id.rvPosts); swipeContainer = (SwipeRefreshLayout) mLayout.findViewById(R.id.swipeContainer); swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getActivity().startService(new Intent(getActivity(), NetworkService.class)); //MainApplication.getRestClient().getHomeTimeline(handler); } }); rvPosts.setOnScrollListener(new EndlessScrollListener(layoutManager) { @Override public boolean onLoadMore(int page) { if (!mNextSrc.isEmpty()) { MainApplication.getRestClient().getPostsFromSource(mNextSrc, infiniteHandler); return true; } else { return false; } } }); } private void loadUI(List<InstagramPost> posts) { // Lookup the recyclerview in activity layout // Root JSON in response is an dictionary i.e { "data : [ ... ] } // Handle resulting parsed JSON response here // Create adapter passing in the sample user data adapter = new InstagramPostsAdapter(posts); // Attach the adapter to the recyclerview to populate items rvPosts.setAdapter(adapter); // Set layout manager to position the items rvPosts.setLayoutManager(layoutManager); swipeContainer.setRefreshing(false); } private void appendToList(List<InstagramPost> posts) { int newItemIdx = adapter.getItemCount(); adapter.addAll(posts); adapter.notifyItemRangeInserted(newItemIdx, posts.size()); } @Override public void onPause() { super.onPause(); LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(postsReceiver); } @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(NetworkService.ACTION); LocalBroadcastManager.getInstance(getActivity()).registerReceiver(postsReceiver, filter); } private BroadcastReceiver postsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { InstagramPosts posts = (InstagramPosts) intent.getSerializableExtra("posts"); loadUI(posts.posts); } }; }
package Program_Examples; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class convert_InputStream_to_String { public static void main(String[] args) throws IOException { InputStreamReader isr = null; BufferedReader br = null; InputStream is = new ByteArrayInputStream("This is the content of my file".getBytes()); StringBuilder sb = new StringBuilder(); String content; try { isr = new InputStreamReader(is); br = new BufferedReader(isr); while ((content = br.readLine()) != null) { sb.append(content); } } catch (IOException ioe) { System.out.println("IO Exception occurred"); ioe.printStackTrace(); } finally { isr.close(); br.close(); } String mystring = sb.toString(); System.out.println(mystring); } }
package LC414ThirdMaximumNumber; import java.util.TreeSet; //Time Complexity O(nlogn) not O(n) //Inserting in heap is logN. // So insertion og N elements will take nlogn changing the overall complexity of algo to nlogn public class TreeSetSolu { public int thirdMax(int[] nums) { TreeSet<Integer> treeSet = new TreeSet<>(); for (int num : nums) { treeSet.add(num); if (treeSet.size() > 3) { treeSet.remove(treeSet.first()); } } if (treeSet.size() == 3) { return treeSet.first(); } return treeSet.last(); } }
package com.huawei.account.mapper; import com.huawei.account.domain.Account; import com.huawei.account.domain.Bill; import com.huawei.account.domain.Bill_Code; import com.huawei.account.domain.Services; import com.huawei.base.utils.PageBean; import java.util.List; /** * Created by dllo on 17/11/16. */ public interface AccountMapper { List<Account> findAllAccount(PageBean pageBean); int findAccountCount(Account account); int setState(Account account); int deleteAccount(Account account); int findSingle(String re_idcard); int addAccount(Account account); int findServiceCount(); List<Services> findAllService(PageBean<Services> pageBean); int findBillCount(); List<Bill> findAllBill(PageBean<Bill> pageBean); Account findAccountById(int account_id); int findBill_CodeCount(); List<Bill_Code> findAllBill_Code(PageBean<Bill_Code> pageBean); void deleteAcc_Ser(Account account); }
package mb.tianxundai.com.toptoken.secondphase.allInterface; import java.util.HashMap; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import mb.tianxundai.com.toptoken.R; import mb.tianxundai.com.toptoken.aty.SplashShouAty; import mb.tianxundai.com.toptoken.base.BaseListener; import mb.tianxundai.com.toptoken.bean.MallMainUpdataBean; import mb.tianxundai.com.toptoken.net.RetrofitClient; import android.content.Context; import android.util.Log; import mb.tianxundai.com.toptoken.secondphase.bean.DueTimeBean; import mb.tianxundai.com.toptoken.secondphase.bean.HistoryBean; import mb.tianxundai.com.toptoken.uitl.Config; import mb.tianxundai.com.toptoken.uitl.PreferencesUtils; public class SecondInteractor { private Context context; public SecondInteractor(Context context) { this.context = context; } interface OnSuccessListener extends BaseListener { void getDueTimeSuccess(List<DueTimeBean.DataBean> dueTimeBean); void commitOrderSuccess(List<DueTimeBean.DataBean> dueTimeBean); void getHistoryListSuccess(HistoryBean historyBean); void onFailure(String message); } //获取到期时间 public void getDueTime(final OnSuccessListener onSuccessListener){ Observable<DueTimeBean> expiremlist = RetrofitClient.getHttpUtilsInstance().apiClient.getDueTime(SplashShouAty.LANGUAGE); expiremlist.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).safeSubscribe(new Observer<DueTimeBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(DueTimeBean dueTimeBean) { Log.i("dueTimeBean---", dueTimeBean.toString()); if (dueTimeBean.getStatus() == 200) { onSuccessListener.getDueTimeSuccess(dueTimeBean.getData()); }else { onSuccessListener.onFailure(dueTimeBean.getMsg()); } } @Override public void onError(Throwable e) { Log.i("dueTimeBean---", e.toString()); onSuccessListener.onFailure(context.getString(R.string.inter_error)); onSuccessListener.hideProgress(); } @Override public void onComplete() { onSuccessListener.hideProgress(); } }); } //提交订单 public void commitOrder(final OnSuccessListener onSuccessListener, String bizhong, int id, String moneySum, String name, String pass, String type){ String token = PreferencesUtils.getString(context, Config.TOKEN); Map<String, Object> map = new HashMap<>(); map.put("coinName", bizhong); map.put("id", id); map.put("moneySum", moneySum); map.put("name", name); map.put("pass", pass); map.put("type", type); Observable<DueTimeBean> submissionOrder = RetrofitClient.getHttpUtilsInstance().apiClient.submissionOrder(SplashShouAty.LANGUAGE,token,map); submissionOrder.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).safeSubscribe(new Observer<DueTimeBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(DueTimeBean dueTimeBean) { if (dueTimeBean.getStatus() == 200) { onSuccessListener.commitOrderSuccess(dueTimeBean.getData()); }else { onSuccessListener.onFailure(dueTimeBean.getMsg()); } } @Override public void onError(Throwable e) { onSuccessListener.onFailure(context.getString(R.string.inter_error)); onSuccessListener.hideProgress(); } @Override public void onComplete() { onSuccessListener.hideProgress(); } }); } //获取历史明细列表 public void getHistoryList(final OnSuccessListener onSuccessListener){ String token = PreferencesUtils.getString(context, Config.TOKEN); Observable<HistoryBean> expiremlist = RetrofitClient.getHttpUtilsInstance().apiClient.getHistoryList(SplashShouAty.LANGUAGE,token); expiremlist.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).safeSubscribe(new Observer<HistoryBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(HistoryBean historyBean) { // if (historyBean.getStatus() == 200) { // onSuccessListener.getDueTimeSuccess(historyBean.getData()); // // }else { // onSuccessListener.onFailure(historyBean.getMsg()); // } } @Override public void onError(Throwable e) { Log.i("HistoryBean---", e.toString()); onSuccessListener.onFailure(context.getString(R.string.inter_error)); onSuccessListener.hideProgress(); } @Override public void onComplete() { onSuccessListener.hideProgress(); } }); } }
package pl.dkiszka.bank.account.controllers; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import pl.dkiszka.bank.account.dto.BaseResponse; import pl.dkiszka.bank.account.services.AccountService; /** * @author Dominik Kiszka {dominikk19} * @project bank-application * @date 26.04.2021 */ @RestController @RequestMapping(path = "/api/v1/accounts") @RequiredArgsConstructor class CloseAccountController { private final AccountService accountService; @DeleteMapping(path = "/{id}") ResponseEntity<BaseResponse> closeAccount(@PathVariable String id) { return ResponseEntity.ok(accountService.closeAccount(id)); } }
package com.game.web.rest; import com.game.biz.model.DemarrageLastWeekReport; import com.game.service.DemarrageLastWeekReportService; import com.game.web.rest.errors.BadRequestAlertException; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing {@link DemarrageLastWeekReport}. */ @RestController @RequestMapping("/api") public class DemarrageLastWeekReportResource { private final Logger log = LoggerFactory.getLogger(DemarrageLastWeekReportResource.class); private static final String ENTITY_NAME = "demarrageLastWeekReport"; @Value("${jhipster.clientApp.name}") private String applicationName; private final DemarrageLastWeekReportService demarrageLastWeekReportService; public DemarrageLastWeekReportResource(DemarrageLastWeekReportService demarrageLastWeekReportService) { this.demarrageLastWeekReportService = demarrageLastWeekReportService; } /** * {@code POST /demarrage-last-week-reports} : Create a new demarrageLastWeekReport. * * @param demarrageLastWeekReport the demarrageLastWeekReport to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new demarrageLastWeekReport, or with status {@code 400 (Bad Request)} if the demarrageLastWeekReport has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/demarrage-last-week-reports") public ResponseEntity<DemarrageLastWeekReport> createDemarrageLastWeekReport(@RequestBody DemarrageLastWeekReport demarrageLastWeekReport) throws URISyntaxException { log.debug("REST request to save DemarrageLastWeekReport : {}", demarrageLastWeekReport); if (demarrageLastWeekReport.getId() != null) { throw new BadRequestAlertException("A new demarrageLastWeekReport cannot already have an ID", ENTITY_NAME, "idexists"); } DemarrageLastWeekReport result = demarrageLastWeekReportService.save(demarrageLastWeekReport); return ResponseEntity.created(new URI("/api/demarrage-last-week-reports/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /demarrage-last-week-reports} : Updates an existing demarrageLastWeekReport. * * @param demarrageLastWeekReport the demarrageLastWeekReport to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated demarrageLastWeekReport, * or with status {@code 400 (Bad Request)} if the demarrageLastWeekReport is not valid, * or with status {@code 500 (Internal Server Error)} if the demarrageLastWeekReport couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/demarrage-last-week-reports") public ResponseEntity<DemarrageLastWeekReport> updateDemarrageLastWeekReport(@RequestBody DemarrageLastWeekReport demarrageLastWeekReport) throws URISyntaxException { log.debug("REST request to update DemarrageLastWeekReport : {}", demarrageLastWeekReport); if (demarrageLastWeekReport.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } DemarrageLastWeekReport result = demarrageLastWeekReportService.save(demarrageLastWeekReport); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, demarrageLastWeekReport.getId().toString())) .body(result); } /** * {@code GET /demarrage-last-week-reports} : get all the demarrageLastWeekReports. * * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of demarrageLastWeekReports in body. */ @GetMapping("/demarrage-last-week-reports") public List<DemarrageLastWeekReport> getAllDemarrageLastWeekReports() { log.debug("REST request to get all DemarrageLastWeekReports"); return demarrageLastWeekReportService.findAll(); } /** * {@code GET /demarrage-last-week-reports/:id} : get the "id" demarrageLastWeekReport. * * @param id the id of the demarrageLastWeekReport to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the demarrageLastWeekReport, or with status {@code 404 (Not Found)}. */ @GetMapping("/demarrage-last-week-reports/{id}") public ResponseEntity<DemarrageLastWeekReport> getDemarrageLastWeekReport(@PathVariable Long id) { log.debug("REST request to get DemarrageLastWeekReport : {}", id); Optional<DemarrageLastWeekReport> demarrageLastWeekReport = demarrageLastWeekReportService.findOne(id); return ResponseUtil.wrapOrNotFound(demarrageLastWeekReport); } /** * {@code DELETE /demarrage-last-week-reports/:id} : delete the "id" demarrageLastWeekReport. * * @param id the id of the demarrageLastWeekReport to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/demarrage-last-week-reports/{id}") public ResponseEntity<Void> deleteDemarrageLastWeekReport(@PathVariable Long id) { log.debug("REST request to delete DemarrageLastWeekReport : {}", id); demarrageLastWeekReportService.delete(id); return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); } }
package linkedList; import java.util.LinkedList; public class C206 { public static void main(String[] args) { ListNode next2 = new ListNode(3); ListNode next1 = new ListNode(2, next2); ListNode head = new ListNode(1, next1); Solution_1 solution = new Solution_1(); System.out.println(solution.reverseList(head)); } /** * 206. 反转链表 反转一个单链表。 */ static class Solution_1 { public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode cur = head; while (cur != null) { ListNode tmp = cur.next; cur.next = prev; prev = cur; cur = tmp; } return prev; } } }
package com.worldchip.bbpaw.bootsetting.receiver; import com.worldchip.bbpaw.bootsetting.util.Common; import com.worldchip.bbpaw.bootsetting.util.LogUtil; import com.worldchip.bbpaw.bootsetting.util.Utils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BootBroadcaseReceiver extends BroadcastReceiver { private static final String TAG = BootBroadcaseReceiver.class.getSimpleName(); private static final String ACTION = "android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context arg0, Intent arg1) { if (arg1.getAction().equals(ACTION)) { /*String isFirst = Common.getPreferenceValue(Utils.IS_FIRST_START_KEY, "true"); boolean first = isFirst.equals("true") ? true :false; LogUtil.e(TAG, "isFirst == "+isFirst); if (!first) { return; }*/ String startCount = Common.getPreferenceValue(Utils.IS_FIRST_START_KEY, "0"); LogUtil.e(TAG, "startCount == "+startCount); if (startCount.equals("3")) { return; } Intent intent = new Intent(); intent.setClassName("com.worldchip.bbpaw.bootsetting", "com.worldchip.bbpaw.bootsetting.activity.MainActivity"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); arg0.startActivity(intent); } } }
import static org.junit.Assert.assertEquals; import image.Image; import image.Pixel; import model.ColorTransformation; import model.Filter; import model.ImageProcessingModel; import model.ImageUtils; import model.PPM; import model.SimpleImageProcessingModel; import java.util.ArrayList; import java.util.List; import org.junit.Test; /** * Test class for the simple image processing model. */ public class SimpleImageProcessingModelTest { private final ImageProcessingModel model = new SimpleImageProcessingModel(); // tests getCurrentImage() @Test public void getCurrentImage() { model.makeCheckerBoard(3); List<List<Pixel>> expectedPixels = new ArrayList<>(); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.get(0).add(new Pixel(0,0,0)); expectedPixels.get(0).add(new Pixel(255,255,255)); expectedPixels.get(0).add(new Pixel(0,0,0)); expectedPixels.get(1).add(new Pixel(255,255,255)); expectedPixels.get(1).add(new Pixel(0,0,0)); expectedPixels.get(1).add(new Pixel(255,255,255)); expectedPixels.get(2).add(new Pixel(0,0,0)); expectedPixels.get(2).add(new Pixel(255,255,255)); expectedPixels.get(2).add(new Pixel(0,0,0)); Image expectedImage = new Image(expectedPixels, 3, 3); assertEquals(model.exportImage(),expectedImage); } // tests makeCheckerBoard() @Test public void testMakeCheckerBoard() { model.makeCheckerBoard(3); Image im = model.exportImage(); List<List<Pixel>> expectedPixels = new ArrayList<>(); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.get(0).add(new Pixel(0,0,0)); expectedPixels.get(0).add(new Pixel(255,255,255)); expectedPixels.get(0).add(new Pixel(0,0,0)); expectedPixels.get(1).add(new Pixel(255,255,255)); expectedPixels.get(1).add(new Pixel(0,0,0)); expectedPixels.get(1).add(new Pixel(255,255,255)); expectedPixels.get(2).add(new Pixel(0,0,0)); expectedPixels.get(2).add(new Pixel(255,255,255)); expectedPixels.get(2).add(new Pixel(0,0,0)); Image expectedImage = new Image(expectedPixels, 3, 3); assertEquals(im, expectedImage); } // tests makeCheckerBoard() with invalid length @Test(expected = IllegalArgumentException.class) public void testMakeCheckerBoardInvalidLength() { model.makeCheckerBoard(-1); } // tests the blur image filter @Test public void testImageFilterBlur() { model.makeCheckerBoard(3); model.imageFilter(Filter.BLUR); Image im = model.exportImage(); List<List<Pixel>> expectedPixels = new ArrayList<>(); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.get(0).add(new Pixel(64, 64, 64)); expectedPixels.get(0).add(new Pixel(96, 96, 96)); expectedPixels.get(0).add(new Pixel(64, 64, 64)); expectedPixels.get(1).add(new Pixel(96, 96, 96)); expectedPixels.get(1).add(new Pixel(128, 128, 128)); expectedPixels.get(1).add(new Pixel(96, 96, 96)); expectedPixels.get(2).add(new Pixel(64, 64, 64)); expectedPixels.get(2).add(new Pixel(96, 96, 96)); expectedPixels.get(2).add(new Pixel(64, 64, 64)); Image expectedImage = new Image(expectedPixels, 3, 3); assertEquals(im, expectedImage); } // tests the sharpen image filter @Test public void testImageFilterSharpen() { model.makeCheckerBoard(3); model.imageFilter(Filter.SHARPEN); Image im = model.exportImage(); List<List<Pixel>> expectedPixels = new ArrayList<>(); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.get(0).add(new Pixel(64, 64, 64)); expectedPixels.get(0).add(new Pixel(255, 255, 255)); expectedPixels.get(0).add(new Pixel(64, 64, 64)); expectedPixels.get(1).add(new Pixel(255, 255, 255)); expectedPixels.get(1).add(new Pixel(255, 255, 255)); expectedPixels.get(1).add(new Pixel(255, 255, 255)); expectedPixels.get(2).add(new Pixel(64, 64, 64)); expectedPixels.get(2).add(new Pixel(255, 255, 255)); expectedPixels.get(2).add(new Pixel(64, 64, 64)); Image expectedImage = new Image(expectedPixels, 3, 3); assertEquals(im, expectedImage); } // tests imageFilter with null filter @Test(expected = IllegalArgumentException.class) public void testImageFilterNullFilter() { model.makeCheckerBoard(3); model.imageFilter(null); } // tests the sepia color transformation @Test public void testColorTransformationSepia() { model.makeCheckerBoard(3); model.colorTransformation(ColorTransformation.SEPIA); Image im = model.exportImage(); List<List<Pixel>> expectedPixels = new ArrayList<>(); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.get(0).add(new Pixel(0,0,0)); expectedPixels.get(0).add(new Pixel(255, 255, 239)); expectedPixels.get(0).add(new Pixel(0,0,0)); expectedPixels.get(1).add(new Pixel(255, 255, 239)); expectedPixels.get(1).add(new Pixel(0,0,0)); expectedPixels.get(1).add(new Pixel(255, 255, 239)); expectedPixels.get(2).add(new Pixel(0,0,0)); expectedPixels.get(2).add(new Pixel(255, 255, 239)); expectedPixels.get(2).add(new Pixel(0,0,0)); Image expectedImage = new Image(expectedPixels, 3, 3); assertEquals(im, expectedImage); } // tests the greyscale color transformation @Test public void testColorTransformationGreyScale() { model.makeCheckerBoard(3); model.colorTransformation(ColorTransformation.GREYSCALE); Image im = model.exportImage(); List<List<Pixel>> expectedPixels = new ArrayList<>(); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.get(0).add(new Pixel(0,0,0)); expectedPixels.get(0).add(new Pixel(255,255,255)); expectedPixels.get(0).add(new Pixel(0,0,0)); expectedPixels.get(1).add(new Pixel(255,255,255)); expectedPixels.get(1).add(new Pixel(0,0,0)); expectedPixels.get(1).add(new Pixel(255,255,255)); expectedPixels.get(2).add(new Pixel(0,0,0)); expectedPixels.get(2).add(new Pixel(255,255,255)); expectedPixels.get(2).add(new Pixel(0,0,0)); Image expectedImage = new Image(expectedPixels, 3, 3); assertEquals(im, expectedImage); } // tests colorTransformation with null color transformation @Test(expected = IllegalArgumentException.class) public void testColorTransformationNullCT() { model.makeCheckerBoard(3); model.colorTransformation(null); } // tests importImage @Test public void testImportImage() { Image im = ImageUtils.readFile("checkerboardBLUR.ppm",new PPM()); model.importImage(im); List<List<Pixel>> expectedPixels = new ArrayList<>(); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.get(0).add(new Pixel(64, 64, 64)); expectedPixels.get(0).add(new Pixel(96, 96, 96)); expectedPixels.get(0).add(new Pixel(64, 64, 64)); expectedPixels.get(1).add(new Pixel(96, 96, 96)); expectedPixels.get(1).add(new Pixel(128, 128, 128)); expectedPixels.get(1).add(new Pixel(96, 96, 96)); expectedPixels.get(2).add(new Pixel(64, 64, 64)); expectedPixels.get(2).add(new Pixel(96, 96, 96)); expectedPixels.get(2).add(new Pixel(64, 64, 64)); Image expectedImage = new Image(expectedPixels, 3, 3); assertEquals(model.exportImage(),expectedImage); } // tests exportImage @Test public void testExportImage() { model.makeCheckerBoard(3); Image im = model.exportImage(); List<List<Pixel>> expectedPixels = new ArrayList<>(); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.add(new ArrayList<>()); expectedPixels.get(0).add(new Pixel(0,0,0)); expectedPixels.get(0).add(new Pixel(255,255,255)); expectedPixels.get(0).add(new Pixel(0,0,0)); expectedPixels.get(1).add(new Pixel(255,255,255)); expectedPixels.get(1).add(new Pixel(0,0,0)); expectedPixels.get(1).add(new Pixel(255,255,255)); expectedPixels.get(2).add(new Pixel(0,0,0)); expectedPixels.get(2).add(new Pixel(255,255,255)); expectedPixels.get(2).add(new Pixel(0,0,0)); Image expectedImage = new Image(expectedPixels, 3, 3); assertEquals(im,expectedImage); } // tests exportImage when there are no images to export @Test(expected = IllegalStateException.class) public void testExportImageNoImagesToExport() { model.exportImage(); } // tests than an exception is thrown when imageFilter is called when there is no image @Test(expected = IllegalStateException.class) public void testImageFilterNoImage() { model.imageFilter(Filter.BLUR); } //tests than an exception is thrown when colorTransformation is called when there is no image @Test(expected = IllegalStateException.class) public void testColorTransformationNoImage() { model.colorTransformation(ColorTransformation.GREYSCALE); } }
package com.melodygram.broadcastReceivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import com.melodygram.activity.ChatActivity; /** * Created by LALIT on 27-07-2016. */ public class NetworkBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getExtras() != null) { NetworkInfo ni = (NetworkInfo) intent.getExtras().get( ConnectivityManager.EXTRA_NETWORK_INFO); if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) { Intent intentResponse = new Intent(); intentResponse.setAction(ChatActivity.ChatBroadcastReceiver.ACTION); intentResponse.addCategory(Intent.CATEGORY_DEFAULT); intentResponse.putExtra("type", "Connected"); context.sendBroadcast(intentResponse); } if (intent.getExtras().getBoolean( ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) { } } } }
package br.com.vl; import lombok.Getter; import lombok.Setter; import javax.faces.bean.ManagedBean; import java.util.ArrayList; import java.util.List; /** * Created by leo on 12/12/16. */ @ManagedBean @Getter @Setter public class TesteBean { private List<ModeloDiploma> modelos; public TesteBean() { modelos = new ArrayList<>(); modelos.add(new ModeloDiploma(10020, "Modelo de Teste", "Diploma de candidato eleito")); modelos.add(new ModeloDiploma(10000, "Modelo Eleições Municipais", "Diploma de candidato eleito")); modelos.add(new ModeloDiploma(10001, "Modelo Eleições Gerais", "Diploma de candidato eleito")); } }
package com.example.ahmed.bakingapp; import com.example.ahmed.bakingapp.data.Ingredient; import com.example.ahmed.bakingapp.data.Step; import java.io.Serializable; import java.util.ArrayList; public class AbstractModel implements Serializable { private String title; private ArrayList<Ingredient> ingredients; private ArrayList<Step> step; public AbstractModel(String title, ArrayList<Ingredient> ingredients, ArrayList<Step> steps) { this.title = title; this.ingredients = ingredients; this.step = steps; } public AbstractModel() { } public ArrayList<Ingredient> getIngredients() { return ingredients; } public void setIngredients(ArrayList<Ingredient> ingredients) { this.ingredients = ingredients; } public ArrayList<Step> getSteps() { return step; } public void setSteps(ArrayList<Step> step) { this.step = step; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
package com.zxt.compplatform.workflow.service.impl; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.zxt.compplatform.form.entity.Form; import com.zxt.compplatform.form.service.IFormService; import com.zxt.compplatform.formengine.constant.Constant; import com.zxt.compplatform.formengine.entity.view.EditColumn; import com.zxt.compplatform.formengine.entity.view.EditPage; import com.zxt.compplatform.formengine.entity.view.TextColumn; import com.zxt.compplatform.workflow.dao.ChuangjianWorkFlowDao; import com.zxt.compplatform.workflow.dao.PidaidWorkFlowDao; import com.zxt.compplatform.workflow.dao.WorkFlowFrameDao; import com.zxt.compplatform.workflow.dao.impl.LiuchengdianWorkFlowDaoImpl; import com.zxt.compplatform.workflow.entity.ActivityDef; import com.zxt.compplatform.workflow.entity.TaskFormNodeEntity; import com.zxt.compplatform.workflow.service.WorkFlowFrameService; public class WorkFlowFrameServiceImpl implements WorkFlowFrameService { private WorkFlowFrameDao workFlowFrameDao; private PidaidWorkFlowDao pwfdi; private ChuangjianWorkFlowDao chuangjianWorkFlowDao; private IFormService formService; private LiuchengdianWorkFlowDaoImpl workflowModelNodeDao; public WorkFlowFrameDao getWorkFlowFrameDao() { return workFlowFrameDao; } public void setFormService(IFormService formService) { this.formService = formService; } public void setWorkFlowFrameDao(WorkFlowFrameDao workFlowFrameDao) { this.workFlowFrameDao = workFlowFrameDao; } public PidaidWorkFlowDao getPwfdi() { return pwfdi; } public void setPwfdi(PidaidWorkFlowDao pwfdi) { this.pwfdi = pwfdi; } public TaskFormNodeEntity findById(String taskFormId) { return workFlowFrameDao.findById(taskFormId); } public List findTaskFormNodeEntity() { // TODO Auto-generated method stub try { List taskFormNodeEntityList = workFlowFrameDao .findTaskFormNodeEntity(); for (int i = 0; i < taskFormNodeEntityList.size(); i++) { TaskFormNodeEntity tfne = (TaskFormNodeEntity) taskFormNodeEntityList .get(i); int processInstanceID = Integer.parseInt(tfne .getProcessInstanceID()); int taskNodeID = Integer.parseInt(tfne.getTaskNodeID()); List nodeList = null; nodeList = workflowModelNodeDao .activityDefList(processInstanceID + ""); Form form = formService.findById(tfne.getFormID()); List pwfdlist = pwfdi.pidaidfindfn(processInstanceID, taskNodeID); if (pwfdlist != null && pwfdlist.size() > 1) { tfne.setProcessInstanceName(pwfdlist.get(0).toString()); // /tfne.setTaskNodeName(pwfdlist.get(1).toString()); // tfne.setTaskNodeName(nodeList.size()+""); } tfne.setTaskNodeName(processInstanceID + ""); /* * if(form != null) tfne.setFormName("<a * >hello"+form.getFormName()+"</a>"); */ tfne .setFormName("<a href=\"javascript: onclick=wfFormconfigEdit(" + processInstanceID + ",'" + tfne.getTaskFormID() + "')\">配置</a>"); } return taskFormNodeEntityList; } catch (Exception e) { e.printStackTrace(); } return null; } public List getWorkflowModelNodeListByPId(String processInstanceID) { // TODO Auto-generated method stub List nodeList = null; nodeList = workflowModelNodeDao.activityDefListNew(processInstanceID); List resultList = new ArrayList(); if (nodeList != null) for (int i = 0; i < nodeList.size(); i++) { ActivityDef activityDef = (ActivityDef) nodeList.get(i); int id = activityDef.getActivityDefId(); String name = activityDef.getName(); List list = workFlowFrameDao.findTaskFormByNode(id, processInstanceID); for (int j = 0; j < list.size(); j++) { TaskFormNodeEntity tfne = (TaskFormNodeEntity) list.get(j); if (tfne == null) { tfne = new TaskFormNodeEntity(); tfne .setTaskNodeName(name + "<br/><a href=\"javascript: onclick=wf_formconfig_edit_add('" + id + "')\">新增表单</a>"); tfne.setTaskNodeID(id + ""); } else { tfne .setTaskNodeName(name + "<br/><a href=\"javascript: onclick=wf_formconfig_edit_add('" + id + "')\">新增表单</a>"); tfne.setTaskNodeID(id + ""); } resultList.add(tfne); } if (list.size() == 0) { TaskFormNodeEntity tfne = new TaskFormNodeEntity(); tfne .setTaskNodeName(name + "<br/><a href=\"javascript: onclick=wf_formconfig_edit_add('" + id + "')\">新增表单</a>"); tfne.setTaskNodeID(id + ""); resultList.add(tfne); } } return resultList; } public List getWFModelNodeListByPId(String processInstanceID) { try { return workflowModelNodeDao.activityDefListNew(processInstanceID); } catch (Exception e) { e.printStackTrace(); } return null; } public List getWorkFlowTabPage() { return workFlowFrameDao.getWorkFlowTabPage(); } /** * formId获取流程ID */ public TaskFormNodeEntity findTaskFormNodeEntity(String formID) { // TODO Auto-generated method stub return workFlowFrameDao.findTaskFormNodeEntity(formID); } /** * 启动新的流程实例 */ public void startProcessInstance(TaskFormNodeEntity taskFormNodeEntity, HttpServletRequest request) { // TODO Auto-generated method stub int userId = Integer.parseInt(request.getSession().getAttribute( "userId").toString()); String parmer[][] = new String[3][2]; parmer[0][0] = "APP_ID"; parmer[0][1] = request.getParameter("APP_ID"); // parmer[1][0] = "userId"; // parmer[1][1] = userId+""; parmer[1][0] = "con_param";// 启动时不传参数 if ((request.getParameter("con_param") != null) && (!"".equals(request.getParameter("con_param")))) { parmer[1][1] = request.getParameter("con_param"); } else { parmer[1][1] = "-1"; } parmer[2][0] = "REC_ID"; parmer[2][1] = request.getParameter("REC_ID"); String processInstanceID = ""; if (request.getParameter(Constant.CUSTOM_PROCESSDEFID_ID) != null && !"".equals(request .getParameter(Constant.CUSTOM_PROCESSDEFID_ID))) { processInstanceID = request .getParameter(Constant.CUSTOM_PROCESSDEFID_ID); } else { processInstanceID = taskFormNodeEntity.getProcessInstanceID(); } chuangjianWorkFlowDao.chuangjian(processInstanceID, userId, parmer); } public void startProcessInstance(TaskFormNodeEntity taskFormNodeEntity, HttpServletRequest request,EditPage editPage) { // TODO Auto-generated method stub int userId = Integer.parseInt(request.getSession().getAttribute( "userId").toString()); String parmer[][] = new String[3][2]; parmer[0][0] = "APP_ID"; parmer[0][1] = request.getParameter("APP_ID"); // parmer[1][0] = "userId"; // parmer[1][1] = userId+""; parmer[1][0] = "con_param";// 启动时不传参数 if ((request.getParameter("con_param") != null) && (!"".equals(request.getParameter("con_param")))) { parmer[1][1] = request.getParameter("con_param"); } else { parmer[1][1] = "-1"; } parmer[2][0] = "REC_ID"; String REC_ID = ""; List list = editPage.getEditColumn(); for(int i = 0;i<list.size();i++){ EditColumn editColumn = (EditColumn)list.get(i); TextColumn textColumn = editColumn.getTextColumn(); if("true".equals(textColumn.getIsworkflow())){ REC_ID = request.getParameter(editColumn.getName()); break; } } //parmer[2][1] = request.getParameter("REC_ID"); parmer[2][1] = REC_ID; String processInstanceID = ""; if (request.getParameter(Constant.CUSTOM_PROCESSDEFID_ID) != null && !"".equals(request .getParameter(Constant.CUSTOM_PROCESSDEFID_ID))) { processInstanceID = request .getParameter(Constant.CUSTOM_PROCESSDEFID_ID); } else { processInstanceID = taskFormNodeEntity.getProcessInstanceID(); } chuangjianWorkFlowDao.chuangjian(processInstanceID, userId, parmer); } public boolean insertTaskFormNodeEntity(TaskFormNodeEntity tfne) { return workFlowFrameDao.insertTaskFormNodeEntity(tfne); } public boolean updateTaskFormNodeEntity(TaskFormNodeEntity tfne) { return workFlowFrameDao.updateTaskFormNodeEntity(tfne); } public boolean updateTaskFormNodeEntityT(TaskFormNodeEntity tfne) { return workFlowFrameDao.updateTaskFormNodeEntityT(tfne); } public boolean deleteTaskFormNodeEntity(String tf_id) { return workFlowFrameDao.deleteTaskFormNodeEntity(tf_id); } public int findTotalRows() { return workFlowFrameDao.findTotalRows(); } public ChuangjianWorkFlowDao getChuangjianWorkFlowDao() { return chuangjianWorkFlowDao; } public void setChuangjianWorkFlowDao( ChuangjianWorkFlowDao chuangjianWorkFlowDao) { this.chuangjianWorkFlowDao = chuangjianWorkFlowDao; } public LiuchengdianWorkFlowDaoImpl getWorkflowModelNodeDao() { return workflowModelNodeDao; } public void setWorkflowModelNodeDao( LiuchengdianWorkFlowDaoImpl workflowModelNodeDao) { this.workflowModelNodeDao = workflowModelNodeDao; } /* * 拼装字符串 */ public String getWorkflowModelNodeStringByPId(String processInstanceID) { int nodeTotal = 0; List nodeList = workflowModelNodeDao .activityDefListNew(processInstanceID); if (nodeList != null && nodeList.size() > 0) { nodeTotal = nodeList.size(); } StringBuffer sb = new StringBuffer(nodeTotal + ""); sb.append(":"); if (nodeList != null) { for (int i = 0; i < nodeList.size(); i++) { ActivityDef activityDef = (ActivityDef) nodeList.get(i); int id = activityDef.getActivityDefId(); String name = activityDef.getName(); List list = workFlowFrameDao.findTaskFormByNode(id, processInstanceID); sb.append(name); sb.append("("); sb.append(list == null ? 0 : list.size()); sb.append(")、"); } } return sb.toString().substring(0, sb.toString().lastIndexOf("、")); } }
package com.classroom.services.infrastructure.persistence.hibernate; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.joda.time.LocalDateTime; import org.springframework.stereotype.Repository; import com.classroom.services.domain.model.Exams; import com.classroom.services.domain.model.Homework; import com.classroom.services.domain.model.repositories.IBaseRepository; import com.classroom.services.domain.model.repositories.IExamMarksRepository; import com.classroom.services.domain.model.repositories.IExamResultsRepository; import com.classroom.services.domain.model.repositories.criteria.BaseSearchCriteria; import com.classroom.services.domain.model.repositories.criteria.ExamResultsSearchCriteria; @Repository public class ExamMarksRepository extends BaseRepository<Exams, BaseSearchCriteria> implements IExamMarksRepository{ public List<Exams> getExamMarks(Integer examId) { System.out.println("query !! "+examId); List<Exams> examMarks = null; CriteriaQuery<Exams> query = getCriteriaBuilder().createQuery( Exams.class); Root<Exams> from = query.from(Exams.class); Predicate[] predicates = new Predicate[1]; predicates[0] = getCriteriaBuilder().equal(from.get("examGroupId"), examId); query.where(predicates); query.select(from); System.out.println("query !! "+query); examMarks = getResultList(query); List<Exams> getExamMarks = new ArrayList<Exams>(); if (examMarks.size() >= 1) { for (Integer i = 0; i < examMarks.size(); i++) { getExamMarks.add(examMarks.get(i)); } } return getExamMarks; } }
package com.aidigame.hisun.imengstar.ui; import java.io.File; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import org.jivesoftware.smack.util.Base64.InputStream; import org.simple.eventbus.EventBus; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Html; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.aidigame.hisun.imengstar.PetApplication; import com.aidigame.hisun.imengstar.adapter.StringAdapter; import com.aidigame.hisun.imengstar.constant.Constants; import com.aidigame.hisun.imengstar.http.HttpUtil; import com.aidigame.hisun.imengstar.service.DownLoadApkService; import com.aidigame.hisun.imengstar.util.HandleHttpConnectionException; import com.aidigame.hisun.imengstar.util.LogUtil; import com.aidigame.hisun.imengstar.util.StringUtil; import com.aidigame.hisun.imengstar.util.UiUtil; import com.aidigame.hisun.imengstar.R; /** * 更新软件 弹出窗 * @author admin * */ public class UpdateAPKActivity extends BaseActivity { TextView titleTv,cancelTv,sureTv; int mode;//1,摇一摇;2,捣捣乱; LinearLayout noteLayout; // TextView infoTv; Handler handler; boolean isSending=false; // ScrollView scrollview; RelativeLayout progress_view_layout,progressLayout; View progressView; StringAdapter adapter; ArrayList<String> list; ListView listView; public int currentLength=0; public Handler progressHandler=new Handler(){ public void handleMessage(android.os.Message msg) { switch (msg.what) { case 1: //进行中 long length=msg.arg1; currentLength+=length; int w=progress_view_layout.getMeasuredWidth(); int width=(int) (length*1f/Constants.apk_size*w); RelativeLayout.LayoutParams param=(RelativeLayout.LayoutParams)progressView.getLayoutParams(); if(param==null){ param=new RelativeLayout.LayoutParams(width,RelativeLayout.LayoutParams.WRAP_CONTENT); } param.width=width; progressView.setLayoutParams(param); break; case 2: //完成 String path=Constants.Picture_Root_Path+File.separator+"pet.apk"; Intent intent=new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive"); UpdateAPKActivity.this.startActivity(intent); break; case 3: //失败 Toast.makeText(UpdateAPKActivity.this, "更新失败", Toast.LENGTH_LONG).show(); break; } }; }; public static UpdateAPKActivity updateAPKActivity; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); updateAPKActivity=this; setContentView(R.layout.activity_update_apk); mode=getIntent().getIntExtra("mode", 1); handler=HandleHttpConnectionException.getInstance().getHandler(this); noteLayout=(LinearLayout)findViewById(R.id.note_layout); // infoTv=(TextView)findViewById(R.id.info_tv); progress_view_layout=(RelativeLayout)findViewById(R.id.progress_view_layout); progressLayout=(RelativeLayout)findViewById(R.id.progress_layout); progressView=findViewById(R.id.progress_view); // scrollview=(ScrollView)findViewById(R.id.listview); listView=(ListView)findViewById(R.id.listview); list=new ArrayList<String>(); // list.add("1."); // list.add("2."); // list.add("3."); // list.add("4."); adapter=new StringAdapter(this, list); listView.setAdapter(adapter); initView(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub final String info=HttpUtil.updateVersionInfo(handler, Constants.VERSION, UpdateAPKActivity.this); runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if(!StringUtil.isEmpty(info)){ String[] strs=info.split("&"); LogUtil.i("mi", "info="+info); // infoTv.setText(info); if(strs!=null){ for(int i=0;i<strs.length;i++){ list.add(strs[i]); } runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub adapter.update(list); adapter.notifyDataSetChanged(); } }); } } } }); } }).start(); } private void initView() { titleTv=(TextView)findViewById(R.id.textView1); cancelTv=(TextView)findViewById(R.id.cancel_tv); sureTv=(TextView)findViewById(R.id.sure_tv); /* * 强制更新,只显示 更新按钮 * * 非强制,显示两个按钮 */ // if(Constants.VERSION!=null&&StringUtil.canUpdate(this, Constants.VERSION)){ cancelTv.setVisibility(View.GONE); noteLayout.setVisibility(View.VISIBLE); } cancelTv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub /* * 是否强制更新 * 否,关掉对话框,回到应用 * 是 弹框提示必须更新,如果不更新则程序关闭 */ finish(); System.gc(); } }); sureTv.setOnClickListener(new OnClickListener() { boolean isloading=false; @Override public void onClick(View v) { // TODO Auto-generated method stub if(isloading){ return; } isloading=true; Intent intent=new Intent(UpdateAPKActivity.this,DownLoadApkService.class); UpdateAPKActivity.this.startService(intent); // new MultiThreadDownload().start(); if(Constants.VERSION!=null&&StringUtil.canUpdate(UpdateAPKActivity.this, Constants.VERSION)){ listView.setVisibility(View.INVISIBLE); progressLayout.setVisibility(View.VISIBLE); isFinish=false; }else{ finish(); } } }); } boolean isFinish=false; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub // return super.onKeyDown(keyCode, event); EventBus.getDefault().post("", "finish"); return true; } class MultiThreadDownload extends Thread { /** * 多线程下载 * 1:使用RandomAccessFile在任意的位置写入数据。 * 2:需要计算第一个线程下载的数据量,可以平均分配。如果不够平均时, * 则直接最后一个线程处理相对较少的数据 * 3:必须要在下载之前准备好相同大小的文件,通过文件头获取 */ @Override public void run() { // TODO Auto-generated method stub super.run(); //1:声明文件名和下载的地址 try { String fileName = "imengstar.apk"; // String urlStr = ""+Constants.android_url; String urlStr="http://home4pet.aidigame.com/pet_beta_1.0.15.apk"; // String urlStr="http://apk.hiapk.com/appdown/com.ss.android.article.news?webparams=sviptodoc291cmNlPTkz"; //2:声明Url URL url = new URL(urlStr/*+"/"+fileName*/); //3:获取连接 HttpURLConnection con = (HttpURLConnection) url.openConnection(); //4:设置请求方式 con.setRequestMethod("GET"); //5:获取请求头,即文件的长度 int length = con.getContentLength();//获取下载文件的长度,以计算每个线程应该下载的数据量。 length=13006589; //6:在指定的目录下,创建一个同等大小的文件 RandomAccessFile file = new RandomAccessFile(Constants.Picture_Root_Path+File.separator+fileName, "rw");//创建一个相同大小的文件。 //7:设置文件大小,占位 file.setLength(length);//设置文件大小。 file.close(); //8:定义线程个数 int size = 3; //9:计算每一个线程应该下载多少字节的数据,如果正好整除则最好,否则加1 int block = length/size==0?length/size:length/size+1;//计算每个线程应该下载的数据量。 System.err.println("每个线程应该下载:"+block); //10:运行三个线程并计算从哪个字节开始到哪一个字节结束 for(int i=0;i<size;i++){ int start = i*block; int end = start+(block-1);//计算每一个线程的开始和结束字节。 System.err.println(i+"="+start+","+end); new MyDownThread(fileName, start, end,url).start(); } } catch (Exception e) { // TODO: handle exception } } } class MyDownThread extends Thread{ //定义文件名 private String fileName; //定义从何地开始下载 private int start; //定义下载到哪一个字节 private int end; private URL url; public MyDownThread(String fileName,int start,int end,URL url){ this.fileName=fileName; this.start=start; this.end=end; this.url=url; } @Override public void run() { try{ //11:开始下载 HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); //12:设置分段下载的请求头 con.setRequestProperty("Range","bytes="+start+"-"+end);//设置从服务器上读取的文件块。 //13:开始下载,需要判断206 if(con.getResponseCode()==206){//访问成功,则返回的状态码为206。 InputStream in = (InputStream) con.getInputStream(); //14:声明随机写文件对象,注意rwd是指即时将数据写到文件中,而不使用缓存区 RandomAccessFile out = new RandomAccessFile(Constants.Picture_Root_Path+File.separator+fileName,"rwd"); out.seek(start);//设置从文件的某个位置开始写数据。 byte[] b=new byte[1024]; int len = 0; while((len=in.read(b))!=-1){ out.write(b,0,len); Message msg=handler.obtainMessage(); msg.what=1; msg.arg1=len; handler.sendMessage(msg); } out.close(); in.close(); } System.err.println(this.getName()+"执行完成"); }catch(Exception e){ throw new RuntimeException(e); } } } }
package Utilities; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.imageio.ImageIO; import javax.servlet.ServletContext; public class SizeImage { private static final int IMG_WIDTH = 100; private static final int IMG_HEIGHT = 100; public void writeFile() throws IOException, URISyntaxException { FacesContext facesContext = FacesContext.getCurrentInstance(); URL url = facesContext.getClass().getResource("resources/images/photos_original/iPhone11.png"); ExternalContext externalContext = facesContext.getExternalContext(); Path path = Paths.get(((ServletContext) externalContext.getContext()) .getRealPath("/resources/images/photos-resized/iPhone11.png")); BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); externalContext.responseReset(); externalContext.setResponseContentType("image/png"); externalContext.setResponseContentLength((int) attrs.size()); externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + "iPhone11.png" + "\""); InputStream inStream = externalContext. getResourceAsStream("/resources/images/photos/iPhone.png"); BufferedImage originalImage = ImageIO.read( inStream); int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizeImageHintJpg = resizeImageWithHint(originalImage, type); try (OutputStream os = externalContext.getResponseOutputStream()) { ImageIO.write(resizeImageHintJpg, "jpg", os); } facesContext.responseComplete(); } public void read( ) { try { InputStream is = this.getClass().getResourceAsStream("/resources/photos_riginal/iPhone.png"); BufferedImage originalImage = ImageIO.read( is ); int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizeImageHintJpg = resizeImageWithHint(originalImage, type); ImageIO.write(resizeImageHintJpg, "jpg", new File("c:\\image\\mkyong_hint_jpg.jpg")); BufferedImage resizeImageHintPng = resizeImageWithHint(originalImage, type); ImageIO.write(resizeImageHintPng, "png", new File("c:\\image\\mkyong_hint_png.jpg")); } catch (IOException e) { System.out.println(e.getMessage()); } } private static BufferedImage resizeImageWithHint(BufferedImage originalImage, int type) { BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null); g.dispose(); g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); return resizedImage; } }
package org.jbehave.demo.steps; import org.jbehave.core.annotations.Given; import org.jbehave.core.annotations.Then; import org.jbehave.core.annotations.When; import org.jbehave.demo.builders.FlightBuilder; import org.jbehave.demo.builders.FopBuilder; import org.jbehave.demo.builders.PassengerBuilder; import org.jbehave.demo.builders.PnrBuilder; import org.jbehave.demo.domain.Flight; import org.jbehave.demo.domain.Fop; import org.jbehave.demo.domain.Passenger; import org.jbehave.demo.pages.ConfirmationPage; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class BookPnrSteps { private final FopBuilder fopBuilder; private FlightBuilder flightBuilder; private PassengerBuilder passengerBuilder; private PnrBuilder pnrBuilder; private ConfirmationPage confirmationPage; private List<Passenger> passengers = new ArrayList<Passenger>(); public BookPnrSteps(ConfirmationPage confirmationPage) { this.confirmationPage = confirmationPage; this.flightBuilder = new FlightBuilder(); this.passengerBuilder = new PassengerBuilder(); this.fopBuilder = new FopBuilder(); this.pnrBuilder = new PnrBuilder(flightBuilder, passengerBuilder, fopBuilder); } @Given("there are 8 passengers") public void eightPassengers(){ passengerBuilder.withPassenger(8); } @Given("I am a deaf passenger") public void deafPassenger(){ passengerBuilder.withDeafPassenger(); } @When("I book a flight") public void bookFlight(){ Flight flight = flightBuilder.build(); passengers.addAll(passengerBuilder.build()); Fop fop = fopBuilder.build(); pnrBuilder.build(flight, passengers, fop); } @Then("I receive a PNR indicating my special service") public void verifyDeaf(){ assertTrue(confirmationPage.hasSsr("deaf")); } @Then("I receive a PNR") public void verifyConfirmedPnr(){ assertTrue(confirmationPage.hasSuccessfulPnr()); assertThat(confirmationPage.passengerName(), is(passengers.get(0).name())); } }
package nxpense.helper; import nxpense.builder.ExpenseDtoBuilder; import nxpense.domain.CreditExpense; import nxpense.domain.DebitExpense; import nxpense.domain.Expense; import nxpense.domain.Tag; import nxpense.dto.ExpenseDTO; import nxpense.dto.ExpenseResponseDTO; import nxpense.dto.ExpenseSource; import nxpense.dto.PageDTO; import org.joda.time.LocalDate; import org.junit.Test; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * */ public class ExpenseConverterTest { private static final String EXPENSE_DESCRIPTION = "Test groceries"; private static final BigDecimal EXPENSE_AMOUNT = BigDecimal.valueOf(49.95); private static final LocalDate EXPENSE_DATE = new LocalDate(2015, 3, 1); private static final int EXPENSE_POSITION = 15; private static final String TAG_NAME_1 = "Bill"; private static final String TAG_NAME_2 = "Mobile phone"; private static final Tag TAG1 = createTag(TAG_NAME_1); private static final Tag TAG2 = createTag(TAG_NAME_2); private static Tag createTag(String name) { Tag tag = new Tag(); tag.setName(name); return tag; } @Test public void testDtoToEntity_DebitExpense() { ExpenseDTO expenseDTO = new ExpenseDtoBuilder() .setDate(EXPENSE_DATE) .setAmount(EXPENSE_AMOUNT) .setDescription(EXPENSE_DESCRIPTION) .setSource(ExpenseSource.DEBIT_CARD) .setPosition(EXPENSE_POSITION) .build(); Expense expense = ExpenseConverter.dtoToEntity(expenseDTO); assertThat(expense).isNotNull().isInstanceOf(DebitExpense.class); assertThat(expense.getDate()).isEqualTo(EXPENSE_DATE.toDate()); assertThat(expense.getAmount()).isEqualTo(EXPENSE_AMOUNT); assertThat(expense.getDescription()).isEqualTo(EXPENSE_DESCRIPTION); assertThat(expense.getPosition()).isEqualTo(EXPENSE_POSITION); } @Test public void testDtoToEntity_CreditExpense() { ExpenseDTO expenseDTO = new ExpenseDtoBuilder() .setDate(EXPENSE_DATE) .setAmount(EXPENSE_AMOUNT) .setDescription(EXPENSE_DESCRIPTION) .setSource(ExpenseSource.CREDIT_CARD) .setPosition(EXPENSE_POSITION) .build(); Expense expense = ExpenseConverter.dtoToEntity(expenseDTO); assertThat(expense).isNotNull().isInstanceOf(CreditExpense.class); assertThat(expense.getDate()).isEqualTo(EXPENSE_DATE.toDate()); assertThat(expense.getAmount()).isEqualTo(EXPENSE_AMOUNT); assertThat(expense.getDescription()).isEqualTo(EXPENSE_DESCRIPTION); assertThat(expense.getPosition()).isEqualTo(EXPENSE_POSITION); } @Test(expected = IllegalArgumentException.class) public void testDtoToEntity_NullExpenseSource() { ExpenseDTO expenseDTO = new ExpenseDtoBuilder() .setDate(EXPENSE_DATE) .setAmount(EXPENSE_AMOUNT) .setDescription(EXPENSE_DESCRIPTION) .build(); ExpenseConverter.dtoToEntity(expenseDTO); } @Test public void testEntityToResponseDto_creditExpense() { Expense expense = new CreditExpense() { @Override public Integer getId() { return 5; } }; expense.setDate(EXPENSE_DATE.toDate()); expense.setAmount(EXPENSE_AMOUNT); expense.setDescription(EXPENSE_DESCRIPTION); expense.addTag(TAG1); expense.addTag(TAG2); ExpenseResponseDTO expenseDto = ExpenseConverter.entityToResponseDto(expense); assertThat(expenseDto.getId()).isEqualTo(5); assertThat(expenseDto.getAmount()).isEqualTo(EXPENSE_AMOUNT); assertThat(expenseDto.getSource()).isEqualTo(ExpenseSource.CREDIT_CARD); assertThat(expenseDto.getTags()).hasSize(2); assertThat(expenseDto.getTags().get(0).getName()).isEqualTo(TAG_NAME_1); assertThat(expenseDto.getTags().get(1).getName()).isEqualTo(TAG_NAME_2); } @Test public void testEntityToResponseDto_debitExpense() { Expense expense = new DebitExpense() { @Override public Integer getId() { return 5; } }; expense.setDate(EXPENSE_DATE.toDate()); expense.setAmount(EXPENSE_AMOUNT); expense.setDescription(EXPENSE_DESCRIPTION); ExpenseResponseDTO expenseDto = ExpenseConverter.entityToResponseDto(expense); assertThat(expenseDto.getId()).isEqualTo(5); assertThat(expenseDto.getAmount()).isEqualTo(EXPENSE_AMOUNT); assertThat(expenseDto.getSource()).isEqualTo(ExpenseSource.DEBIT_CARD); } @Test public void testExpensePageToExpensePageDto() { List<Expense> expenses = new ArrayList<Expense>(); Expense expense = new DebitExpense() { @Override public Integer getId() { return 5; } }; expense.setDate(EXPENSE_DATE.toDate()); expense.setAmount(EXPENSE_AMOUNT); expense.setDescription(EXPENSE_DESCRIPTION); expenses.add(expense); int totalNumberOfResult = 100; int page = 5; int pageSize = 25; Sort.Direction direction = Sort.Direction.ASC; String [] props = {"amount"}; PageRequest pageRequest = new PageRequest(page, pageSize, direction, props); Page<Expense> expensePage = new PageImpl<Expense>(expenses, pageRequest, totalNumberOfResult); PageDTO<ExpenseResponseDTO> expensePageDto = ExpenseConverter.expensePageToExpensePageDto(expensePage); assertThat(expensePageDto.getNumberOfItems()).isEqualTo(expenses.size()); assertThat(expensePageDto.getPageNumber()).isEqualTo(page); assertThat(expensePageDto.getPageSize()).isEqualTo(pageSize); assertThat(expensePageDto.getSortDirection()).isEqualTo(direction); assertThat(expensePageDto.getSortProperty()).isEqualTo("amount"); assertThat(expensePageDto.getItems().get(0).getId()).isEqualTo(5); } }
package com.test.base; /** * Given two non-negative integers num1 and num2 represented as strings, * return the product of num1 and num2, also represented as a string. * * 给定两个非负数,求乘积 * * Example 1: * Input: num1 = "2", num2 = "3" * Output: "6" * * Example 2: * Input: num1 = "123", num2 = "456" * Output: "56088" * * Note: * The length of both num1 and num2 is < 110. 长度小于110 * Both num1 and num2 contain only digits 0-9. 只包含0-9的数字 * Both num1 and num2 do not contain any leading zero, except the number 0 itself. 头部不包含0,除非本身为0 * You must not use any built-in BigInteger library or convert the inputs to integer directly. 不准使用大数计算等辅助库 * * @author YLine * * 2016年12月25日 下午2:30:35 */ public interface Solution { public String multiply(String num1, String num2); }
package com.example.riccardo.chat_rev.db; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.example.riccardo.chat_rev.chat.Const; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.sql.SQLException; import java.util.ArrayList; /** * Created by riccardo on 04/12/15. */ public class DbAdapter { //variabili private ricorrenti private Context context; private SQLiteDatabase db; private DbHelper dbHelper; private SharedPreferences sp; public DbAdapter (Context context){ this.context = context; this.sp = context.getSharedPreferences(Const.SP_NAME, Context.MODE_PRIVATE); } /* Funzioni per la gestione del db */ public void open() throws SQLException{ if (this.dbHelper==null) this.dbHelper = new DbHelper(context); db = dbHelper.getWritableDatabase(); } public void close(){ dbHelper.close(); } /* Funzioni per le chat */ public long createChat(int id, String name, long timestamp) throws SQLException{ this.open(); ContentValues cv = createChatCV(id, name, timestamp); return db.insertOrThrow(DbHelper.T_CHAT, null, cv); } public long getLastChatTimestamp(int id) throws SQLException{ this.open(); Cursor c = db.query(DbHelper.T_CHAT, new String[]{DbHelper.K_CHAT_TIMESTAMP}, DbHelper.K_CHAT_ID + "=" + id, null, null, null, null); c.moveToFirst(); Log.e("Get lst tmsp-->", "id: " + id + "tmsp: " + c.getLong(c.getColumnIndex(DbHelper.K_CHAT_TIMESTAMP))); return c.getLong(c.getColumnIndex(DbHelper.K_CHAT_TIMESTAMP)); } public JSONArray getAllChats() throws SQLException, JSONException { this.open(); Cursor c = db.query(DbHelper.T_CHAT, new String[]{DbHelper.K_CHAT_ID, DbHelper.K_CHAT_NAME}, DbHelper.K_CHAT_DELETED + " = " + 0, null, null, null, null); JSONArray a = new JSONArray(); while (c.moveToNext()) { JSONObject j = new JSONObject(); j.put(Const.API_CHAT_ID, c.getInt(c.getColumnIndex(DbHelper.K_CHAT_ID))); j.put(Const.API_CHAT_NAME, c.getString(c.getColumnIndex(DbHelper.K_CHAT_NAME))); a.put(j); } return a; } public boolean chatExists(int chatId) throws SQLException{ this.open(); Cursor c = db.rawQuery("SELECT COUNT(*) FROM " + dbHelper.T_CHAT + " WHERE " + dbHelper.K_CHAT_ID + "=" + chatId + ";", null); if (c != null) { c.moveToFirst(); if (c.getInt(0) > 0) { c.close(); return true; } } c.close(); return false; } private int updateChatTimeStamp(int id, long t) throws SQLException{ this.open(); //aggiorno il timestamp dell'ultima lettura ContentValues cv = new ContentValues(); cv.put(DbHelper.K_CHAT_TIMESTAMP, t); return db.update(DbHelper.T_CHAT, cv, dbHelper.K_CHAT_ID + "=" + id, null); } /* Funzioni per i messaggi */ public String getFileFromQueue(int idMsg) throws SQLException, JSONException{ this.open(); Cursor c = db.query(DbHelper.T_QUEUE, new String[]{DbHelper.K_JSON_STRING}, DbHelper.K_ID_QUEUE + "=" + idMsg, null, null, null, null); c.moveToFirst(); JSONObject j = new JSONObject(c.getString(c.getColumnIndex(DbHelper.K_JSON_STRING))); return j.getString(Const.API_FILE); } public String getFileMsg(int idMsg) throws SQLException,JSONException{ this.open(); Cursor c = db.query(DbHelper.T_MESSAGES, new String[] {DbHelper.K_MESSAGE_SRC_FILE}, DbHelper.K_MESSAGE_ID + "=" + idMsg, null, null, null, null); c.moveToFirst(); return c.getString(c.getColumnIndex(DbHelper.K_MESSAGE_SRC_FILE)); } public long createMediaMessage(int id, String sender, long timestamp, String text, int chat,String srcFile,int type) throws SQLException{ this.open(); System.out.println("createMediaMessage Timestamp: " + timestamp); ContentValues cv = createMediaMessageCV(id, sender, timestamp, text, chat,type,srcFile); return db.insertOrThrow(DbHelper.T_MESSAGES, null, cv); } public long createMessage(int id, String sender, long timestamp, String text, int chat) throws SQLException{ this.open(); System.out.println("createMessage Timestamp: " + timestamp); ContentValues cv = createMessageCV(id, sender, timestamp, text, chat); db.execSQL("UPDATE " +DbHelper.T_CHAT+ " SET " +DbHelper.K_CHAT_DELETED + "=" + 0 + " WHERE " +DbHelper.K_CHAT_ID+ "=" + chat); return db.insertOrThrow(DbHelper.T_MESSAGES, null, cv); } public void deleteMsg(int id){ ContentValues cv = new ContentValues(); cv.put(DbHelper.K_MESSAGE_DELETED,1); db.update(DbHelper.T_MESSAGES,cv,DbHelper.K_MESSAGE_ID + "=" + id,null); } public void deleteChat(int idChat){ db.execSQL("UPDATE " + DbHelper.T_CHAT + " SET " + DbHelper.K_CHAT_DELETED + "=" + 1 + " WHERE " + DbHelper.K_CHAT_ID + "=" + idChat); db.execSQL("UPDATE " + DbHelper.T_MESSAGES + " SET " + DbHelper.K_MESSAGE_DELETED + "=" + 1 + " WHERE " + DbHelper.K_MESSAGE_CHAT + "=" + idChat); /*ContentValues cv = new ContentValues(); cv.put(DbHelper.K_CHAT_DELETED,1); db.update(DbHelper.T_CHAT, cv, DbHelper.K_CHAT_DELETED + "=" + idChat, null); cv.clear(); cv.put(DbHelper.K_MESSAGE_DELETED, 1); db.update(DbHelper.T_MESSAGES, cv, DbHelper.K_MESSAGE_CHAT + "=" + idChat, null);*/ } public JSONArray getConversation(int id) throws JSONException, SQLException { this.open(); //prendo i messaggi della chat Cursor c = db.query(DbHelper.T_MESSAGES, new String[] {DbHelper.K_MESSAGE_ID, DbHelper.K_MESSAGE_SENDER, DbHelper.K_MESSAGE_TIMESTAMP, DbHelper.K_MESSAGE_TEXT,DbHelper.K_MESSAGE_SRC_FILE,DbHelper.K_MESSAGE_TYPE}, DbHelper.K_MESSAGE_CHAT + "=" + id + " AND " + DbHelper.K_MESSAGE_DELETED + "=" + 0, null, null, null, null); JSONArray a = new JSONArray(); //riempo l'array da restituire JSONObject j=new JSONObject(); while (c.moveToNext()) { j= new JSONObject(); j.put(Const.API_MESSAGE_ID, c.getInt(c.getColumnIndex(DbHelper.K_MESSAGE_ID))); if (sp.getString(Const.SP_USER, "").equals(c.getString(c.getColumnIndex(DbHelper.K_MESSAGE_SENDER)))) j.put(Const.API_MESSAGE_IN, 0); else j.put(Const.API_MESSAGE_IN, 1); j.put(Const.API_MESSAGE_TIMESTAMP, c.getLong(c.getColumnIndex(DbHelper.K_MESSAGE_TIMESTAMP))); j.put(Const.API_TYPE, c.getInt(c.getColumnIndex(DbHelper.K_MESSAGE_TYPE))); if(c.getInt(c.getColumnIndex(DbHelper.K_MESSAGE_TYPE))==Const.MSG_TYPE_TEXT) j.put(Const.API_MESSAGE_TEXT, c.getString(c.getColumnIndex(DbHelper.K_MESSAGE_TEXT))); else j.put(Const.API_FILE, c.getString(c.getColumnIndex(DbHelper.K_MESSAGE_SRC_FILE))); a.put(j); } if (updateChatTimeStamp(id,j.getLong(Const.API_MESSAGE_TIMESTAMP)+1) <= 0) return null; return a; } public JSONArray getConversationUpdates(int id) throws JSONException, SQLException { this.open(); String user = sp.getString(Const.SP_USER, ""); long timestamp = getLastChatTimestamp(id); Log.e("Get conv update time-->", timestamp + ""); Cursor c = db.query(DbHelper.T_MESSAGES, new String[]{DbHelper.K_MESSAGE_ID, DbHelper.K_MESSAGE_SENDER, DbHelper.K_MESSAGE_TIMESTAMP, DbHelper.K_MESSAGE_TEXT,DbHelper.K_MESSAGE_TYPE,DbHelper.K_MESSAGE_SRC_FILE}, DbHelper.K_MESSAGE_CHAT + "=" + id +" " + "AND "+dbHelper.K_MESSAGE_TIMESTAMP+">"+timestamp+ " AND " +DbHelper.K_MESSAGE_SENDER+" <> '"+user+"'", null, null, null, null); JSONArray a = new JSONArray(); //riempo l'array da restituire JSONObject j= new JSONObject(); while (c.moveToNext()) { j= new JSONObject(); j.put(Const.API_MESSAGE_ID, c.getInt(c.getColumnIndex(DbHelper.K_MESSAGE_ID))); if (sp.getString(Const.SP_USER, "").equals(c.getString(c.getColumnIndex(DbHelper.K_MESSAGE_SENDER)))) j.put(Const.API_MESSAGE_IN, 0); else j.put(Const.API_MESSAGE_IN, 1); j.put(Const.API_MESSAGE_TIMESTAMP, c.getLong(c.getColumnIndex(DbHelper.K_MESSAGE_TIMESTAMP))); j.put(Const.API_TYPE, c.getInt(c.getColumnIndex(DbHelper.K_MESSAGE_TYPE))); if(c.getInt(c.getColumnIndex(DbHelper.K_MESSAGE_TYPE))==Const.MSG_TYPE_TEXT) j.put(Const.API_MESSAGE_TEXT, c.getString(c.getColumnIndex(DbHelper.K_MESSAGE_TEXT))); else j.put(Const.API_FILE, c.getString(c.getColumnIndex(DbHelper.K_MESSAGE_SRC_FILE))); a.put(j); } if (updateChatTimeStamp(id,j.getLong(Const.API_MESSAGE_TIMESTAMP)+1) <= 0) return null; return a; } /* funzioni per i contatti */ public long createContact(String name) throws SQLException{ this.open(); ContentValues cv = new ContentValues(); cv.put(DbHelper.K_CONTACT_NAME, name); return db.insertOrThrow(DbHelper.T_CONTACTS, null, cv); } public JSONArray getContacts()throws SQLException,JSONException{ this.open(); //prendo i messaggi della chat String sql="SELECT * FROM "+dbHelper.T_CONTACTS+";"; Cursor c = db.rawQuery(sql,null); JSONArray jsonArray = new JSONArray(); //riempo l'array da restituire while (c.moveToNext()) { JSONObject j = new JSONObject(); j.put(Const.API_USER, c.getString(c.getColumnIndex(DbHelper.K_CONTACT_NAME))); jsonArray.put(j); } return jsonArray; } /* funzioni msg uscita */ public long queueMsg(String jsonString) throws SQLException { this.open(); ContentValues cv = createMsgQueueCV(jsonString); return db.insertOrThrow(DbHelper.T_QUEUE, null, cv); } public boolean dequeueMsg(int id) throws SQLException{ this.open(); return db.delete(DbHelper.T_QUEUE, DbHelper.K_ID_QUEUE + "=" + id, null) > 0; } public ArrayList<ContentValues> getOutMessagesQueue() throws SQLException{ this.open(); Cursor c = db.query(DbHelper.T_QUEUE, new String[] { DbHelper.K_ID_QUEUE,DbHelper.K_JSON_STRING }, null, null, null, null, null); ArrayList<ContentValues> l = new ArrayList<ContentValues>(); if (c == null) return l; while (c.moveToNext()) { ContentValues contentValues = new ContentValues(); contentValues.put( DbHelper.K_ID_QUEUE,c.getInt(c.getColumnIndex(DbHelper.K_ID_QUEUE))); contentValues.put(DbHelper.K_JSON_STRING, c.getString(c.getColumnIndex(DbHelper.K_JSON_STRING))); l.add(contentValues); } return l; } /* Utils */ private ContentValues createMsgQueueCV(String jsonString) { ContentValues cv = new ContentValues(); cv.put(DbHelper.K_JSON_STRING, jsonString); return cv; } private ContentValues createChatCV(int id, String name, long ts) { ContentValues cv = new ContentValues(); cv.put(DbHelper.K_CHAT_ID, id); cv.put(DbHelper.K_CHAT_NAME, name); cv.put(DbHelper.K_CHAT_TIMESTAMP, ts); Log.d("LOG CONTENT VALUES-->", id + " " + name + " " + ts + " "); return cv; } private ContentValues createMessageCV(int id, String s, long ts, String t, int c) { System.out.println("Content value message txt-->"+ts); ContentValues cv = new ContentValues(); cv.put(DbHelper.K_MESSAGE_ID, id); cv.put(DbHelper.K_MESSAGE_SENDER, s); cv.put(DbHelper.K_MESSAGE_TIMESTAMP, ts); cv.put(DbHelper.K_MESSAGE_TEXT, t); cv.put(DbHelper.K_MESSAGE_CHAT, c); return cv; } private ContentValues createMediaMessageCV(int id, String s, long ts, String t, int c,int type,String srcFile) { System.out.println("Content value message txt-->"+ts); ContentValues cv = new ContentValues(); cv.put(DbHelper.K_MESSAGE_ID, id); cv.put(DbHelper.K_MESSAGE_SENDER, s); cv.put(DbHelper.K_MESSAGE_TIMESTAMP, ts); cv.put(DbHelper.K_MESSAGE_TEXT, t); cv.put(DbHelper.K_MESSAGE_CHAT, c); cv.put(DbHelper.K_MESSAGE_SRC_FILE, srcFile); cv.put(DbHelper.K_MESSAGE_TYPE, type); return cv; } public boolean isOpened(){ if(db!=null)return true; else return false; } }
// ChatClient.java // // Modified 1/30/2000 by Alan Frindell // Last modified 2/18/2003 by Ting Zhang // Last modified : Priyank Patel <pkpatel@cs.stanford.edu> // // Chat Client starter application. package Chat; // AWT/Swing import java.awt.*; import java.awt.event.*; import javax.swing.*; // Java import java.io.*; // socket import java.net.*; // Crypto import java.security.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.concurrent.TimeUnit; public class ChatClient extends Thread { public static final int SUCCESS = 0; public static final int CONNECTION_REFUSED = 1; public static final int BAD_HOST = 2; public static final int ERROR = 3; String _loginName; ChatClientThread _thread; ChatLoginPanel _loginPanel; ChatRoomPanel _chatPanel; PrintWriter _out = null; BufferedReader _in = null; CardLayout _layout; JFrame _appFrame; String kAB; Socket _socket = null; SecureRandom secureRandom; KeyStore clientKeyStore; KeyStore caKeyStore; private ServerSocket _serverSocket; private JDialog waitDialog; private HashMap<Integer, String> clientTable; public ChatClient() { super("ChatClientListenThread"); clientTable = new HashMap<Integer, String>(); clientTable.put( 5001, "clienta"); clientTable.put( 5002, "clientb"); _loginName = null; try { initComponents(); } catch (Exception e) { System.out.println("ChatClient error: " + e.getMessage()); e.printStackTrace(); } _layout.show(_appFrame.getContentPane(), "Login"); } public void show() { _appFrame.pack(); _appFrame.setVisible(true); } //This method shows a "pls wait" dialog public void run() { waitDialog = new JDialog((JFrame) SwingUtilities.getWindowAncestor(_loginPanel), "...waiting a participant...", Dialog.ModalityType.DOCUMENT_MODAL); waitDialog.add( new JLabel( "...waiting a participant...")); waitDialog.setLayout( new GridBagLayout()); waitDialog.setSize(300,100); waitDialog.setLocationRelativeTo((JFrame) SwingUtilities.getWindowAncestor(_loginPanel)); waitDialog.setVisible(true); } // Construct the app inside a frame, in the center of the screen public static void main(String[] args) { ChatClient app = new ChatClient(); app.show(); } // initComponents // // Component initialization private void initComponents() throws Exception { _appFrame = new JFrame("WutsApp"); _layout = new CardLayout(); _appFrame.getContentPane().setLayout(_layout); _loginPanel = new ChatLoginPanel(this); _chatPanel = new ChatRoomPanel(this); _appFrame.getContentPane().add(_loginPanel, "Login"); _appFrame.getContentPane().add(_chatPanel, "ChatRoom"); _appFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { quit(); } }); } // quit // // Called when the application is about to quit. public void quit() { try { _socket.shutdownOutput(); _thread.join(); _socket.close(); } catch (Exception err) { System.out.println("ChatClient error: " + err.getMessage()); err.printStackTrace(); } System.exit(0); } // Called from the login panel when the user clicks the "connect" // button. public int connect(String loginName, char[] password, String keyStoreName, char[] keyStorePassword, int portToListen, int portToConnect, int asPort, int tgsPort) { boolean listen = false; boolean connected = false; try { _loginName = loginName; String kA = Utils.getKey(keyStoreName, String.valueOf( keyStorePassword), loginName, String.valueOf(password)); _socket = new Socket(Constants.HOST, portToConnect); _out = new PrintWriter(_socket.getOutputStream(), true); _in = new BufferedReader(new InputStreamReader( _socket.getInputStream())); //COMMUNICATION WITH AS connected = true; Socket asSocket = new Socket( Constants.HOST, asPort); PrintWriter asOut = new PrintWriter(asSocket.getOutputStream(), true); BufferedReader asIn = new BufferedReader(new InputStreamReader( asSocket.getInputStream())); asOut.println( loginName + " " + Utils.hash( kA)); String msg = asIn.readLine(); msg = msg.trim(); String session = msg.split(" ")[0]; String sA = Utils.decrypt_aes( kA, Constants.IV, session); String tgt = msg.split( " ")[1]; asSocket.close(); //COMMUNICATION WITH TGS Socket tgsSocket = new Socket( Constants.HOST, tgsPort); PrintWriter tgsOut = new PrintWriter(tgsSocket.getOutputStream(), true); BufferedReader tgsIn = new BufferedReader(new InputStreamReader( tgsSocket.getInputStream())); String idA = loginName; String idB = clientTable.get( portToConnect); String timestamp = Utils.encrypt_aes( sA, Constants.IV, Utils.getCurrentTimestamp()); tgsOut.println( idA + " " + idB + " " + tgt + " " + timestamp); msg = tgsIn.readLine().trim(); String[] msgInput = Utils.decrypt_aes(sA, Constants.IV, msg).split( " "); kAB = msgInput[1]; String ticket = msgInput[2]; tgsSocket.close(); String current = Utils.getCurrentTimestamp(); //COMMUNICATION INITIALIZATION _out.println( idA + " " + ticket + " " + Utils.encrypt_aes( kAB, Constants.IV, current)); msg = _in.readLine().trim(); String receivedTimestamp = Utils.decrypt_aes( kAB, Constants.IV, msg); SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); Date receivedTime = dateFormat.parse( receivedTimestamp); Date currentTime = dateFormat.parse( current); long diffInMillies = receivedTime.getTime() - currentTime.getTime(); TimeUnit timeUnit = TimeUnit.SECONDS; long diff = timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS); if( diff != 1) { System.out.println( "Timestamp check failed"); return ERROR; } _layout.show(_appFrame.getContentPane(), "ChatRoom"); _thread = new ChatClientThread(this); _thread.start(); return SUCCESS; } catch (UnknownHostException e) { System.err.println("Don't know about the serverHost: " + Constants.HOST); System.exit(1); } catch (IOException e) { if( !connected) listen = true; else { System.err.println("Couldn't get I/O for " + "the connection to the serverHost: " + Constants.HOST); e.printStackTrace(); } } catch (AccessControlException e) { return BAD_HOST; } catch (Exception e) { System.out.println("ChatClient err: " + e.getMessage()); e.printStackTrace(); } //This block runs if a client start its program before other side of communication, so it becomes a listener if( listen) { try { _serverSocket = new ServerSocket(portToListen); this.start(); _socket = _serverSocket.accept(); _out = new PrintWriter(_socket.getOutputStream(), true); _in = new BufferedReader(new InputStreamReader( _socket.getInputStream())); String msg = _in.readLine().trim(); String[] msgInput = msg.split( " "); String kB = Utils.getKey( keyStoreName, String.valueOf( keyStorePassword), loginName, String.valueOf( password)); String idA = msgInput[0]; String ticket = Utils.decrypt_aes( kB, Constants.IV, msgInput[1]); String idADec = ticket.split( " ")[0]; kAB = ticket.split( " ")[1]; String timestamp = Utils.decrypt_aes( kAB, Constants.IV, msgInput[2]); if( !idA.equals( idADec)) return ERROR; if( !Utils.checkTimestamp(timestamp)) return ERROR; String timestampRespond = ""; SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); Date receivedTime = null; try { receivedTime = dateFormat.parse( timestamp); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); // creates calendar cal.setTime(receivedTime); // sets calendar time/date cal.add(Calendar.SECOND, 1); //Add one second Date d = cal.getTime(); timestampRespond = dateFormat.format(d); _out.println( Utils.encrypt_aes( kAB, Constants.IV, timestampRespond)); waitDialog.setVisible(false); waitDialog.dispatchEvent(new WindowEvent( waitDialog, WindowEvent.WINDOW_CLOSING)); _layout.show(_appFrame.getContentPane(), "ChatRoom"); _thread = new ChatClientThread(this); _thread.start(); return SUCCESS; } catch (IOException e) { System.err.println("Could not listen on port: " + portToListen); System.exit(-1); } } return ERROR; } // sendMessage // // Called from the ChatPanel when the user types a carrige return. public void sendMessage(String msg) { try { msg = _loginName + "> " + msg; String mac = Utils.generateMAC( msg, kAB); getOutputArea().append(msg + "\n"); msg = Utils.encrypt_aes( kAB, Constants.IV, msg); _out.println(msg + " " + mac); } catch (Exception e) { System.out.println("ChatClient err: " + e.getMessage()); e.printStackTrace(); } } public Socket getSocket() { return _socket; } public JTextArea getOutputArea() { return _chatPanel.getOutputArea(); } public String getKAB() { return kAB; } }
package com.pikai.app.activity; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.pikai.app.R; import com.pikai.app.properties.ServerProperties; import com.pikai.app.utils.HttpUtils; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * Created by Methew on 2016/2/15. * 登陆页面 */ public class LoginActivity extends Activity { private Button loginButton = null; private Button registerButton = null; private TextView textView = null; private EditText userNameEditText; private EditText userPassEditText; @Override protected void onCreate(Bundle savedInstanceState) { Log.i("message", "--------------登陆页面初始化--------------------"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); loginButton = (Button) findViewById(R.id.main_button_login); registerButton = (Button) findViewById(R.id.main_button_register); userNameEditText = (EditText) findViewById(R.id.main_editTxt_userName); userPassEditText = (EditText) findViewById(R.id.main_editTxt_userPass); //设置监听事件 registerButton.setOnClickListener(new MyButtonListener()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void changeButtonColor(View view) { // 获取点击控件的id int id = view.getId(); // 根据id进行判断进行怎么样的处理 // switch (id) { // // 登陆事件的处理 // case R.id.btn_login: // // 获取用户名 // final String userName = et_name.getText().toString(); // // 获取用户密码 // final String userPass = et_pass.getText().toString(); // if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(userPass)) { // Toast.makeText(this, "用户名或者密码不能为空", Toast.LENGTH_LONG).show(); // } else { // // 开启子线程 // new Thread() { // public void run() { // loginByPost(userName, userPass); // 调用loginByPost方法 // } // // ; // }.start(); // } // break; // } Log.i("message", "---------------get--------------------"); loginButton.setBackgroundColor(getResources().getColor(R.color.red)); } public void login(View view) { Log.i("message", "login 登陆操作"); Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle data = msg.getData(); String val = data.getString("value"); Log.i("mylog", "请求结果-->" + val); } }; Runnable runnable = new Runnable() { @Override public void run() { Message msg = new Message(); Bundle data = new Bundle(); data.putString("value", "请求结果"); msg.setData(data); String userName = userNameEditText.getText().toString(); String userPass = userPassEditText.getText().toString(); // 传递的数据 String postData = null; try { postData = "username=" + URLEncoder.encode(userName, "UTF-8") + "&userpass=" + URLEncoder.encode(userPass, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.out.println("--------------- 异常-------------------"); } HttpUtils.doPost(ServerProperties.BASE_URL, postData); // handler.sendMessage(msg); } }; new Thread(runnable).start(); loginButton.setBackgroundColor(getResources().getColor(R.color.green)); } //OnClickListener 事件监听处理 class MyButtonListener implements View.OnClickListener { public void onClick(View v) { System.out.println("---------------post--------------------"); registerButton.setBackgroundColor(getResources().getColor(R.color.blue)); } } }