blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
02dc3fd90544cd199b13323e733e1f42a43533e5
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_3e04525d2f7953ba3e27a5d9e155aa91b0d76a40/MultiArrowEntityListener/2_3e04525d2f7953ba3e27a5d9e155aa91b0d76a40_MultiArrowEntityListener_s.java
UTF-8
5,801
2.625
3
[]
no_license
package com.ayan4m1.multiarrow; import java.util.List; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityListener; import org.bukkit.event.entity.ProjectileHitEvent; import com.ayan4m1.multiarrow.arrows.ArrowType; import com.ayan4m1.multiarrow.arrows.ArrowEffect; import com.ayan4m1.multiarrow.arrows.TimedArrowEffect; import com.iConomy.iConomy; import com.iConomy.system.Holdings; /** * Listens for entity events and raises arrow effect events * @author ayan4m1 */ public class MultiArrowEntityListener extends EntityListener { private MultiArrow plugin; public MultiArrowEntityListener(MultiArrow instance) { plugin = instance; } public boolean chargeFee(Player player, ArrowType type) { Double arrowFee = plugin.config.getArrowFee(type); if (plugin.iconomy != null && player.hasPermission("multiarrow.free-fees") && arrowFee > 0D) { try { if (iConomy.hasAccount(player.getName())) { Holdings balance = iConomy.getAccount(player.getName()).getHoldings(); if (balance.hasEnough(arrowFee)) { balance.subtract(arrowFee); if ((Boolean)plugin.config.getOptionValue("send-balance-on-fee") == true) { player.sendMessage("Balance is now " + iConomy.format(balance.balance()) + ""); } } else { player.sendMessage("You need " + iConomy.format(arrowFee) + ", but only have " + iConomy.format(balance.balance())); return false; } } else { player.sendMessage("Couldn't find your iConomy holdings, cannot pay fee of " + iConomy.format(arrowFee)); return false; } } catch (Exception e) { plugin.log.warning("Exception when trying to charge " + player.getName() + " " + iConomy.format(arrowFee)); } return true; } else return true; } public void onProjectileHit(ProjectileHitEvent event) { if (!(event.getEntity() instanceof Arrow)) { return; } Arrow arrow = (Arrow)event.getEntity(); if (!(arrow.getShooter() instanceof Player)) { return; } ArrowType arrowType = plugin.activeArrowType.get(((Player)arrow.getShooter()).getName()); //We should ignore this event if there is a targetable entity within one block List<Entity> entities = arrow.getNearbyEntities(1D, 1D, 1D); int entCount = entities.size(); for(Entity ent : entities) { if ((ent instanceof Arrow) || (ent instanceof Item) || (ent == arrow.getShooter())) { entCount--; } } //Only raise the onGroundHitEvent if there are no valid entities nearby if (entCount == 0) { if (arrowType != ArrowType.NORMAL) { if (this.chargeFee((Player)arrow.getShooter(), arrowType)) { ArrowEffect arrowEffect = null; String className = plugin.toProperCase(arrowType.toString()) + "ArrowEffect"; try { arrowEffect = (ArrowEffect)Class.forName("com.ayan4m1.multiarrow.arrows." + className).newInstance(); } catch (ClassNotFoundException e) { plugin.log.warning("Failed to find class " + className); } catch (InstantiationException e) { plugin.log.warning("Could not instantiate class " + className); } catch (IllegalAccessException e) { plugin.log.warning("Could not access class " + className); } arrowEffect.onGroundHitEvent(arrow); if (plugin.config.getArrowRemove(arrowType)) { arrow.remove(); } if (arrowEffect instanceof TimedArrowEffect) { TimedArrowEffect timedArrowEffect = (TimedArrowEffect)arrowEffect; plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, timedArrowEffect.getDelayTriggerRunnable(arrow), timedArrowEffect.getDelayTicks()); } } } } } public void onEntityDamage(EntityDamageEvent event) { if (event.getCause() != EntityDamageEvent.DamageCause.PROJECTILE) { return; } if (!(event instanceof EntityDamageByEntityEvent)) { return; } EntityDamageByEntityEvent ebe = (EntityDamageByEntityEvent)event; if (!(ebe.getDamager() instanceof Arrow)) { return; } Arrow arrow = (Arrow)ebe.getDamager(); if (!(arrow.getShooter() instanceof Player)) { return; } ArrowType arrowType = plugin.activeArrowType.get(((Player)arrow.getShooter()).getName()); if (arrowType != ArrowType.NORMAL) { event.setCancelled(true); if (this.chargeFee((Player)arrow.getShooter(), arrowType)) { ArrowEffect arrowEffect = null; String className = plugin.toProperCase(arrowType.toString()) + "ArrowEffect"; try { arrowEffect = (ArrowEffect)Class.forName("com.ayan4m1.multiarrow.arrows." + className).newInstance(); } catch (ClassNotFoundException e) { plugin.log.warning("Failed to find class " + className); } catch (InstantiationException e) { plugin.log.warning("Could not instantiate class " + className); } catch (IllegalAccessException e) { plugin.log.warning("Could not access class " + className); } arrowEffect.onEntityHitEvent(arrow, event.getEntity()); if (plugin.config.getArrowRemove(arrowType)) { arrow.remove(); } if (arrowEffect instanceof TimedArrowEffect) { TimedArrowEffect timedArrowEffect = (TimedArrowEffect)arrowEffect; plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, timedArrowEffect.getDelayTriggerRunnable(arrow), timedArrowEffect.getDelayTicks()); } } } } }
true
a13b4d46212d00e77810ab8d39562115e7ebfedf
Java
cesperil/Agrotente
/src/main/java/es/grapecheck/plataforma/webaction/bean/GestionEconomicaBean.java
UTF-8
5,916
1.679688
2
[]
no_license
package es.grapecheck.plataforma.webaction.bean; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import org.jfree.util.Log; import es.grapecheck.plataforma.negocio.service.MovimientoEconomicoService; import es.grapecheck.plataforma.negocio.service.ParcelasService; import es.grapecheck.plataforma.persistencia.exception.PersistenciaException; import es.grapecheck.plataforma.persistencia.vo.MovimientoEconomicoVO; import es.grapecheck.plataforma.persistencia.vo.ParcelasVO; import es.grapecheck.plataforma.persistencia.vo.UsuarioVO; import es.grapecheck.plataforma.utiles.Constantes; import es.grapecheck.plataforma.utiles.FacesUtils; import es.grapecheck.plataforma.utiles.FlashContext; import es.grapecheck.plataforma.utiles.TipoBean; import es.grapecheck.plataforma.utiles.TratamientoDeDatos; import es.grapecheck.plataforma.utiles.TratamientoFechas; import es.grapecheck.plataforma.webaction.form.BotoneraPrimefacesForm; @ManagedBean @ViewScoped public class GestionEconomicaBean extends BotoneraPrimefacesForm<MovimientoEconomicoVO>{ private static final long serialVersionUID = -1479162331630831185L; private List<ParcelasVO> listaParcelas; public List<ParcelasVO> getListaParcelas() { return listaParcelas; } public void setListaParcelas(List<ParcelasVO> listaParcelas) { this.listaParcelas = listaParcelas; } private MovimientoEconomicoVO movimientoEconomicoVO; public MovimientoEconomicoVO getMovimientoEconomicoVO() { return movimientoEconomicoVO; } public void setMovimientoEconomicoVO(MovimientoEconomicoVO movimientoEconomicoVO) { this.movimientoEconomicoVO = movimientoEconomicoVO; } @EJB private MovimientoEconomicoService movimientoEconomicoService; public MovimientoEconomicoService getMovimientoEconomicoService() { return movimientoEconomicoService; } public void setMovimientoEconomicoService( MovimientoEconomicoService movimientoEconomicoService) { this.movimientoEconomicoService = movimientoEconomicoService; } @EJB private ParcelasService parcelasService; public ParcelasService getParcelasService() { return parcelasService; } public void setParcelasService(ParcelasService parcelasService) { this.parcelasService = parcelasService; } @PostConstruct private void init() { try { this.getBotonAyuda().setOnclick("PF('modalAyuda').show()"); this.setRutaAyuda("../ayudas/ayudaSinAyuda.xhtml"); this.montarBotoneraMantenimientoComun(TipoBean.ALTA); this.getBotonImprimir().setDisabled(true); String accionSalirPorDefecto = "#{gestionEconomicaBean.goVolver}"; this.meterAccionBoton(this.getBotonSalir(), accionSalirPorDefecto); setMovimientoEconomicoVO(new MovimientoEconomicoVO()); setListaParcelas(this.getParcelasService().getParcelasByUsuario((UsuarioVO)FacesUtils.getSessionParameter(Constantes.USUARIO_LOGIN))); } catch (Exception e) { mostrarConfirmGenericoSinCancelar(FacesUtils.getValueMensajesProperties("etiqueta.mensaje.exception"),FacesUtils.getValueMensajesProperties("etiqueta.cabecera.exception"),Constantes.SEVERITY_ALERT,this.getActionListenerCancelarConfirmGenerico()); } } public void add() { MovimientoEconomicoVO movimientoEconomicoVO = this.getMapper().map(this.getMovimientoEconomicoVO(),MovimientoEconomicoVO.class); try { //Guardar Log.info("Guardar Movimiento Economico"); if(TratamientoDeDatos.esNullCeroVacio(movimientoEconomicoVO.getId())){ String textoFecha = movimientoEconomicoVO.getTextoFecha(); movimientoEconomicoVO.setFecha(TratamientoFechas.stringToDate(textoFecha, TratamientoFechas.formatoEspanol)); movimientoEconomicoVO.setConcepto(movimientoEconomicoVO.getConcepto().toUpperCase()); //el usuario es el de login de momento. movimientoEconomicoVO.setFkIdeUsuario((UsuarioVO)FacesUtils.getSessionParameter(Constantes.USUARIO_LOGIN)); if(!TratamientoDeDatos.esNullCeroVacio(movimientoEconomicoVO.getTextoParcela())){ ParcelasVO parcela = getParcelaByNombre(movimientoEconomicoVO.getTextoParcela()); movimientoEconomicoVO.setFkIdeParcela(parcela); } this.getMovimientoEconomicoService().addMovimiento(movimientoEconomicoVO); } setMovimientoEconomicoVO(new MovimientoEconomicoVO()); //UtilidadesContingencia.setBusquedaAutomatica(true); //MensajeGenericoNavegando(FacesUtils.getValueMensajesProperties("etiqueta.cabecera.informacion"), FacesUtils.getValueMensajesProperties("etiqueta.mensaje.usuarioguardado"), Constantes.SEVERITY_INFO); mostrarConfirmGenericoSinCancelar("Guardado correctamente", Constantes.SEVERITY_INFO, ""); //cesperilla 27-10-2015 seteo para que busque automáticamente al volver a consulta } catch (PersistenciaException e) { e.printStackTrace(); mostrarConfirmGenericoSinCancelar(FacesUtils.getValueMensajesProperties("etiqueta.mensaje.exception"),FacesUtils.getValueMensajesProperties("etiqueta.cabecera.exception"),Constantes.SEVERITY_ALERT,this.getActionListenerCancelarConfirmGenerico()); } } /** * * @param query * @return */ public List<String> completeText(String query) { List<String> results = new ArrayList<String>(); for(int i = 0; i < getListaParcelas().size(); i++) { ParcelasVO parcela = getListaParcelas().get(i); if(parcela.getNombre().contains(query)){ results.add(parcela.getNombre()); } } return results; } public ParcelasVO getParcelaByNombre(String textoParcela){ for(int i=0; i<getListaParcelas().size(); i++){ ParcelasVO parcela = getListaParcelas().get(i); if(parcela.getNombre().equals(textoParcela)){ return parcela; } } return null; } }
true
5617c94f59a088aaac1f9b2c3fbe93aae39bf73a
Java
LeslieCao/JavaLearn
/src/com/imooc/interfaceLearn/IPlayGame.java
UTF-8
96
1.992188
2
[]
no_license
package com.imooc.interfaceLearn; public interface IPlayGame { public void playGame(); }
true
4dde8dfbe77014fe077c0dc380adbfb0beb7d885
Java
TribuneX/talk_automated_testing
/demo-II-database-mock/src/test/java/de/itemis/databasemock/unittest/ContactTestRepository.java
UTF-8
1,389
2.390625
2
[]
no_license
package de.itemis.databasemock.unittest; import de.itemis.databasemock.Contact; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Random; public class ContactTestRepository<S> implements de.itemis.databasemock.ContactRepository { private List<Contact> repository = new ArrayList<>(); @Override public <S extends Contact> S save(final S s) { s.setId(new Random().nextLong()); repository.add(s); return s; } @Override public <S extends Contact> Iterable<S> saveAll(final Iterable<S> iterable) { return null; } @Override public Optional<Contact> findById(final Long aLong) { return Optional.of(repository.get(0)); } @Override public boolean existsById(final Long aLong) { return false; } @Override public Iterable<Contact> findAll() { return null; } @Override public Iterable<Contact> findAllById(final Iterable<Long> iterable) { return null; } @Override public long count() { return 0; } @Override public void deleteById(final Long aLong) { } @Override public void delete(final Contact contact) { } @Override public void deleteAll(final Iterable<? extends Contact> iterable) { } @Override public void deleteAll() { } }
true
bb7726dd08fc5400313acc132d60eab252823729
Java
opaeum/opaeum
/runtime/opaeum-runtime-core/opaeum-runtime-hibernate/src/main/java/org/opaeum/hibernate/domain/AbstractEnumResolver.java
UTF-8
2,257
2.328125
2
[]
no_license
package org.opaeum.hibernate.domain; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import org.hibernate.HibernateException; import org.hibernate.engine.SessionImplementor; import org.hibernate.usertype.UserType; import org.opaeum.runtime.domain.EnumResolver; import org.opaeum.runtime.domain.IEnum; public abstract class AbstractEnumResolver implements EnumResolver,UserType{ @Override public int[] sqlTypes(){ return new int[]{ Types.BIGINT }; } public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor arg2, Object arg3) throws HibernateException, SQLException { long object = rs.getLong(names[0]); if(rs.wasNull()){ return null; }else{ return fromOpaeumId(object); } } public void nullSafeSet(PreparedStatement st,Object value,int index, SessionImplementor si) throws HibernateException,SQLException{ if(value == null){ st.setNull(index, Types.BIGINT); }else{ st.setLong(index, toOpaeumId((IEnum) value)); } } public Object nullSafeGet(ResultSet rs,String[] names,Object owner) throws HibernateException,SQLException{ long object = rs.getLong(names[0]); if(rs.wasNull()){ return null; }else{ return fromOpaeumId(object); } } public void nullSafeSet(PreparedStatement st,Object value,int index) throws HibernateException,SQLException{ if(value == null){ st.setNull(index, Types.BIGINT); }else{ st.setLong(index, toOpaeumId((IEnum) value)); } } @Override public boolean equals(Object x,Object y) throws HibernateException{ return x==y; } @Override public int hashCode(Object x) throws HibernateException{ return x.hashCode(); } @Override public Object deepCopy(Object value) throws HibernateException{ return value; } @Override public boolean isMutable(){ return false; } @Override public Serializable disassemble(Object value) throws HibernateException{ return (Serializable) value; } @Override public Object assemble(Serializable cached,Object owner) throws HibernateException{ return cached; } @Override public Object replace(Object original,Object target,Object owner) throws HibernateException{ return original; } }
true
d378276642049841997f0466c6142afd5e45d3e3
Java
lfcanals/simple-virtual
/src/main/java/com/lfcanals/testing/virtualizer/util/SessionRecorder.java
UTF-8
1,964
2.734375
3
[ "Apache-2.0" ]
permissive
package com.lfcanals.testing.virtualizer.util; import org.netcrusher.core.reactor.*; import org.netcrusher.core.filter.*; import org.netcrusher.tcp.*; /** * Main class that starts a proxy to save session. * */ public final class SessionRecorder { private static String localIp, targetIp; private static int localPort, targetPort; /** * @param args * @throws Exception * @throws InterruptedException */ public static void main(String[] args) throws Exception { final NioReactor reactor = new NioReactor(); final TcpCrusher crusher = TcpCrusherBuilder.builder() .withReactor(reactor) .withBindAddress(localIp, localPort) .withConnectAddress(targetIp, targetPort) .withIncomingTransformFilterFactory((addr) -> new LoggingFilter(addr, "incoming", LoggingFilter.Level.INFO)) .withOutgoingTransformFilterFactory((addr) -> new LoggingFilter(addr, "outgoing", LoggingFilter.Level.INFO)) .buildAndOpen(); //crusher.close(); //reactor.close(); } // Ok ok, fast and dirty, no complications public static void parseParams(final String args[]) { try { localIp = args[1].split(":")[0]; localPort = Integer.parseInt(args[1].split(":")[1]); targetIp = args[2].split(":")[0]; targetPort = Integer.parseInt(args[2].split(":")[1]); if(args[0].equals("TCP")) { } else if(args[0].equals("UDP")) { } else { throw new Exception("Protocol can be only TCP or UDP"); } } catch(Exception e) { System.err.println("Try calling with: TCP|UDP " + "<localIp>:<port> <targetIp>:<port>"); System.exit(1); } } }
true
2cf4100b1b886bbf52d3a20cc8487599b860e599
Java
TsymbalenkoOleksandr/MerakiApp
/src/main/java/com/meraki/controller/EventController.java
UTF-8
3,143
2.265625
2
[]
no_license
package com.meraki.controller; import com.meraki.entity.Event; import com.meraki.entity.Router; import com.meraki.service.EventService; import com.meraki.service.RouterService; import org.jboss.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.HashSet; import java.util.List; import java.util.Set; @Controller public class EventController { private static final Logger logger = Logger.getLogger(EventController.class); @Autowired private EventService eventService; @Autowired private RouterService routerService; @RequestMapping("getAllEventLists") public ModelAndView getAllEmployees() { List<Event> eventList = eventService.getAllEvents(); logger.info("get all event" + eventList); return new ModelAndView("eventList", "eventList", eventList); } @RequestMapping("createEvent") public ModelAndView createEvent(@ModelAttribute Event event) { logger.info("create event " + event); return new ModelAndView("eventForm"); } @RequestMapping("editEvent") public ModelAndView editEvent(@RequestParam long id, @ModelAttribute Event event) { event = eventService.getEvent(id); logger.info("edit event " + event); return new ModelAndView("eventForm", "eventObject", event); } @RequestMapping("saveEvent") public ModelAndView saveEvent(@ModelAttribute Event event, HttpServletRequest request) { logger.info("save event " + event); int id = Integer.parseInt(request.getParameter("idr")); /// сделать коментарии а то пиздец // System.out.println(event.getDateFrom() + event.getDateTo().toString()); Router router = routerService.getRouter(id); // router.setEvent(event); Set<Router> routerSet = new HashSet<>(); routerSet.add(router); event.setRouters(routerSet); // routerService.updateRouter(router); if (event.getId() == 0) { eventService.createEvent(event); } else { eventService.updateEvent(event); // routerService.updateRouter(router); } logger.info("save event " + event); return new ModelAndView("redirect:getAllEventLists"); } @RequestMapping("deleteEvent") public ModelAndView deleteEvent(@RequestParam long id) { eventService.deleteEvent(id); logger.info("delete event " + id); return new ModelAndView("redirect:getAllEventLists"); } @RequestMapping("searchEvent") public ModelAndView search(@RequestParam("searchName") String searchName) { List<Event> eventList = eventService.getAllEvents(searchName); return new ModelAndView("eventList", "eventList", eventList); } }
true
9ba52090e335ce7af092e16c1becd34ea9bde484
Java
mrzeng/krqsteward2.0
/order-center/src/main/java/com/ejushang/steward/ordercenter/vo/ApportionPersonVo.java
UTF-8
1,034
2.03125
2
[]
no_license
package com.ejushang.steward.ordercenter.vo; /** * User:moon * Date: 14-8-13 * Time: 上午9:56 */ public class ApportionPersonVo { //用户id private Integer employeeId; //用户名 private String username; //真实姓名 private String employeeName; //分配数量 private Integer apportionCount; public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public Integer getApportionCount() { return apportionCount; } public void setApportionCount(Integer apportionCount) { this.apportionCount = apportionCount; } }
true
125fa14400abe43a7c5e951a421e5d1edf586048
Java
GitRavindra/CarSellingWebsite
/PickMyCar/src/project/Specification.java
UTF-8
5,057
2.546875
3
[]
no_license
package project; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/Specification") public class Specification extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw=response.getWriter(); /*response.setContentType("text/html"); pw.println("<html>"); pw.println("<body>"); pw.println("<script type='text\\javascript'>"); pw.println("document.getElementById('l2').innerHTML="+model+";"); pw.println("document.getElementById('t1').value='hellos';"); pw.println("</script>"); pw.println(" <form name='f1'>"); pw.println("<input type=\"text\" id=\"t1\">"); pw.println("<label id=\"l2\">kk</label>"); pw.println("</form"); pw.println("</body>"); pw.println("</html>");*/ Connection con=null; PreparedStatement st=null; ResultSet rs=null; try {con=Connect.getConnect(); String model=request.getParameter("t1"); String brand=request.getParameter("s") ; pw.println(model+brand); String sql="select ENGINE_TYPE,ENGINE_DISPLACEMENT,FUEL_TYPE,POWER, TORQUE ,SPEED_TRANSMISSION ,NO_OF_CYLINDER ,SUSPENSION ,NO_OF_GEARS ,FUEL_CAPACITY from car where brand=? and model_name=?"; st=con.prepareStatement(sql); st.setString(1,brand); st.setString(2,model); rs=st.executeQuery(); response.setContentType("text/html"); pw.println("<html>"); pw.println("<head>"); pw.println("<title>Specification</title>"); pw.println("<link rel=\"stylesheet\" href=\"specification.css\">"); pw.println("<script type=\"text/javascript\" src=\"Login.js\">"); pw.println("</script>"); pw.println("</head>"); pw.println("<body>"); pw.println(" <form class =\"form-wrap\" name='f1'>"); pw.println("<center> <h1>Specification </h1> </center>\r\n" + " Engine type: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp; &ensp;\r\n" + " <input type=\"text\" id=\"textbox1\" disabled><br>\r\n" + " Engine displacement: &nbsp;\r\n" + " <input type=\"text\" id=\"textbox2\" disabled><br>\r\n" + " Fuel Type: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &ensp;\r\n" + " <input type=\"text\" id=\"textbox3\" disabled><br>\r\n" + " Power: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &ensp;\r\n" + " <input type=\"text\" id=\"textbox4\" disabled><br>\r\n" + " Torque: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp;\r\n" + " <input type=\"text\" id=\"textbox5\" disabled><br>\r\n" + " Speed Transmission: &ensp;\r\n" + " <input type=\"text\" id=\"textbox6\" disabled></br>\r\n" + " No. of Cylinders: &nbsp &nbsp &nbsp &nbsp;\r\n" + " <input type=\"text\" id=\"textbox7\" disabled></br>\r\n" + " Suspension Front: &nbsp &nbsp &ensp;\r\n" + " <input type=\"text\" id=\"textbox8\" disabled></br>\r\n" + " No. of Gear: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp;\r\n" + " <input type=\"text\" id=\"textbox9\" disabled></br>\r\n" + " Fuel Capacity: &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp;\r\n" + " <input type=\"text\" id=\"textbox10\" disabled><br>"); pw.println("<input type=\"buttton\" onclick=\"goBack()\" value=\"Back\" name=\"b1\" >\r\n" + " <input type=\"submit\" value=\"Buy Now\" name=\"b2\"> <br>"); pw.println("<select name=\"s\"> "); if(rs.next()) { for(int i=1;i<=10;i++) { pw.println("<option"); pw.println("value='"+rs.getString(i)+"'"); pw.println(">"); pw.println(rs.getString(i)); pw.println("</option>"); } } pw.println("</select> <br>"); pw.println("<script>"); pw.println("specification();"); pw.println("</script>"); pw.println("</form"); pw.println("</body>"); pw.println("</html>"); } catch (Exception e) { e.printStackTrace(); pw.println(e); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true
cd1ae3f74b176eea76afbc0cfa12c28763785789
Java
smalam119/route_planner_revisited
/app/src/main/java/com/thyme/smalam119/routeplannerapplication/Map/NotificationMap/NotificationMapActivity.java
UTF-8
949
1.851563
2
[]
no_license
package com.thyme.smalam119.routeplannerapplication.Map.NotificationMap; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.google.android.gms.maps.SupportMapFragment; import com.thyme.smalam119.routeplannerapplication.R; public class NotificationMapActivity extends AppCompatActivity { private RpaOnNotificationMapReadyCallBack mRpaOnNotificationMapReadyCallBack; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification_map); prepareView(); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(mRpaOnNotificationMapReadyCallBack); } private void prepareView() { mRpaOnNotificationMapReadyCallBack = new RpaOnNotificationMapReadyCallBack(this); } }
true
97186411bd6edc86e2753049e3243fd165dbd4c0
Java
fukudasatomi/nucalgen
/nucalgen/src/main/java/jp/satomichan/nucalgen/CellStylePool.java
UTF-8
851
2.546875
3
[]
no_license
package jp.satomichan.nucalgen; import java.util.HashMap; import java.util.Map; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFDataFormat; public class CellStylePool { private Workbook workbook; CellStylePool(Workbook workbook){ this.workbook = workbook; } private Map<String, CellStyle> cellStyleMap = new HashMap<String, CellStyle>(); CellStyle getCellStyle(String format) { if(this.cellStyleMap.containsKey(format)) { return this.cellStyleMap.get(format); }else { CellStyle cs = this.workbook.createCellStyle(); XSSFDataFormat xssfFormat = (XSSFDataFormat) this.workbook.createDataFormat(); cs.setDataFormat(xssfFormat.getFormat(format)); this.cellStyleMap.put(format, cs); return this.cellStyleMap.get(format); } } }
true
fde1d41790bcc2ac734a08c3ba7f6565014ce198
Java
devansh-amazon/amazon-neptune-tools
/neptune-export/src/main/java/com/amazonaws/services/neptune/profiles/neptune_ml/v2/parsing/ParseLabelsV2.java
UTF-8
4,179
2.109375
2
[ "Apache-2.0" ]
permissive
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://www.apache.org/licenses/LICENSE-2.0 or in the "license" file accompanying this file. This file 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.amazonaws.services.neptune.profiles.neptune_ml.v2.parsing; import com.amazonaws.services.neptune.profiles.neptune_ml.common.config.Separator; import com.amazonaws.services.neptune.profiles.neptune_ml.common.parsing.*; import com.amazonaws.services.neptune.profiles.neptune_ml.v2.config.EdgeLabelTypeV2; import com.amazonaws.services.neptune.profiles.neptune_ml.v2.config.LabelConfigV2; import com.amazonaws.services.neptune.profiles.neptune_ml.v2.config.NodeLabelTypeV2; import com.amazonaws.services.neptune.propertygraph.Label; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.Collection; public class ParseLabelsV2 { private final Collection<JsonNode> config; private final Collection<Double> defaultSplitRates; public ParseLabelsV2(Collection<JsonNode> config, Collection<Double> defaultSplitRates) { this.config = config; this.defaultSplitRates = defaultSplitRates; } public Collection<LabelConfigV2> parseNodeClassLabels() { Collection<LabelConfigV2> nodeClassLabels = new ArrayList<>(); for (JsonNode json : config) { if (isNodeClass(json)) { ParsingContext context = new ParsingContext("node label"); Label nodeType = new ParseNodeType(json, context).parseNodeType(); String property = new ParseProperty(json, context.withLabel(nodeType)).parseSingleProperty(); ParsingContext propertyContext = context.withLabel(nodeType).withProperty(property); NodeLabelTypeV2 labelType = new ParseNodeLabelTypeV2(json, propertyContext).parseLabel(); Separator separator = new ParseSeparator(json).parseSeparator(); Collection<Double> splitRates = new ParseSplitRate(json, defaultSplitRates, propertyContext).parseSplitRates(); nodeClassLabels.add(new LabelConfigV2(nodeType, labelType.name(), property, splitRates, separator)); } } return nodeClassLabels; } private boolean isNodeClass(JsonNode json) { return json.has("node"); } private boolean isEdgeClass(JsonNode json) { return json.has("edge"); } public void validate() { for (JsonNode json : config) { if (!isNodeClass(json) && !isEdgeClass(json)) { throw new IllegalArgumentException("Illegal label element. Expected 'node' or 'edge' field."); } } } public Collection<LabelConfigV2> parseEdgeClassLabels() { Collection<LabelConfigV2> edgeClassLabels = new ArrayList<>(); for (JsonNode json : config) { if (isEdgeClass(json)) { ParsingContext context = new ParsingContext("edge label"); Label edgeType = new ParseEdgeType(json, context).parseEdgeType(); String property = new ParseProperty(json, context.withLabel(edgeType)).parseNullableSingleProperty(); ParsingContext propertyContext = context.withLabel(edgeType).withProperty(property); EdgeLabelTypeV2 labelType = new ParseEdgeLabelTypeV2(json, propertyContext).parseLabel(); labelType.validate(property, edgeType); Separator separator = new ParseSeparator(json).parseSeparator(); Collection<Double> splitRates = new ParseSplitRate(json, defaultSplitRates, propertyContext).parseSplitRates(); edgeClassLabels.add(new LabelConfigV2(edgeType, labelType.name(), property, splitRates, separator)); } } return edgeClassLabels; } }
true
c57a6285d14c1c2c0138c0b7d4e0d4b7c57fc3a7
Java
adamfisk/littleshoot-downloader
/src/main/java/org/lastbamboo/common/download/RangeDownloadListener.java
UTF-8
1,005
2.59375
3
[]
no_license
package org.lastbamboo.common.download; /** * Listens for connection events. */ public interface RangeDownloadListener { /** * Called when a give downloader has established a connection. * * @param downloader The connected downloader. */ void onConnect(RangeDownloader downloader); /** * Called when the download has begun. * * @param downloader The downloader. */ void onDownloadStarted(RangeDownloader downloader); /** * Notification that the download has finished. * * @param downloader The downloader. */ void onDownloadFinished(RangeDownloader downloader); /** * Called when the download has failed. * * @param downloader The downloader. */ void onFail(RangeDownloader downloader); /** * Called when a set of bytes are read for a given range. * * @param downloader The downloader. */ void onBytesRead(RangeDownloader downloader); }
true
8e7b53df00fb18e3bb817b7c63614c37984c740b
Java
emmurphy1/optaplanner
/core/optaplanner-core-impl/src/test/java/org/optaplanner/core/api/score/constraint/ConstraintMatchTest.java
UTF-8
2,064
2.15625
2
[ "Apache-2.0" ]
permissive
package org.optaplanner.core.api.score.constraint; import static org.optaplanner.core.api.score.buildin.simple.SimpleScore.ONE; import static org.optaplanner.core.api.score.buildin.simple.SimpleScore.ZERO; import java.util.List; import org.junit.jupiter.api.Test; import org.optaplanner.core.api.score.buildin.simple.SimpleScore; import org.optaplanner.core.impl.testdata.util.PlannerAssert; class ConstraintMatchTest { @Test void equalsAndHashCode() { // No CM should equal any other. ConstraintMatch<SimpleScore> constraintMatch = new ConstraintMatch<>("a.b", "c", List.of("e1"), ZERO); PlannerAssert.assertObjectsAreEqual(constraintMatch, constraintMatch); ConstraintMatch<SimpleScore> constraintMatch2 = new ConstraintMatch<>("a.b", "c", List.of("e1"), ZERO); // Cast do avoid Comparable checks. PlannerAssert.assertObjectsAreNotEqual(constraintMatch, (Object) constraintMatch2); } @Test void compareTo() { PlannerAssert.assertCompareToOrder( new ConstraintMatch<>("a.b", "a", List.of("a"), ZERO), new ConstraintMatch<>("a.b", "a", List.of("a", "aa"), ZERO), new ConstraintMatch<>("a.b", "a", List.of("a", "ab"), ZERO), new ConstraintMatch<>("a.b", "a", List.of("a", "c"), ZERO), new ConstraintMatch<>("a.b", "a", List.of("a", "aa", "a"), ZERO), new ConstraintMatch<>("a.b", "a", List.of("a", "aa", "b"), ZERO), new ConstraintMatch<>("a.b", "a", List.of("a", "aa"), ONE), new ConstraintMatch<>("a.b", "b", List.of("a", "aa"), ZERO), new ConstraintMatch<>("a.b", "b", List.of("a", "ab"), ZERO), new ConstraintMatch<>("a.b", "b", List.of("a", "c"), ZERO), new ConstraintMatch<>("a.c", "a", List.of("a", "aa"), ZERO), new ConstraintMatch<>("a.c", "a", List.of("a", "ab"), ZERO), new ConstraintMatch<>("a.c", "a", List.of("a", "c"), ZERO)); } }
true
22fab950486e69e084389cea68c2822a90699a41
Java
FrederikMeincke/NordicMotorhome
/src/main/java/com/nordicmotorhome/Repository/CountryRepo.java
UTF-8
964
2.53125
3
[]
no_license
package com.nordicmotorhome.Repository; import com.nordicmotorhome.Model.Country; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; @Repository public class CountryRepo { @Autowired JdbcTemplate jdbcTemplate; /** * This method fetches all countries in the DB and adds it to the rowMapper * @author Kasper N. Jensen * @return list of countries */ public List<Country> fetchAllCountries(){ String sqlUse = "USE NMR;"; String sqlZip = "SELECT * FROM NMR.countries;"; RowMapper<Country> rowMapper = new BeanPropertyRowMapper<>(Country.class); jdbcTemplate.update(sqlUse); return jdbcTemplate.query(sqlZip,rowMapper); } }
true
d69a34d90a39e4f518b453ef1bffbc9c67b7fe4c
Java
agreenwalrus/Review-Assistant
/src/main/java/resources/TableMaker/Convetrters/StudentConverter.java
UTF-8
1,122
2.5
2
[]
no_license
package resources.TableMaker.Convetrters; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import data.Student; import data.mark.LabMark; import java.lang.reflect.Type; public class StudentConverter implements JsonSerializer<Student> { private boolean info_cell_editable; private boolean addLink; public StudentConverter( boolean addLink, boolean info_cell_editable) { this.addLink = addLink; this.info_cell_editable = info_cell_editable; } @Override public JsonElement serialize(Student src, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); object.addProperty("cell-class", "cell-ui" + (info_cell_editable ? " info-cell-editable" : "")); object.addProperty("value", src.getFulName()); object.addProperty("type", "student"); object.addProperty("id", src.getId().toString()); if (addLink) object.addProperty("link", src.getGitURL()); return object; } }
true
fe420d7efe82dd7980d6ed48596da09e043c9f38
Java
IanLee1521/server
/src/main/java/gov/osti/entity/DOECodeMetadata.java
UTF-8
15,687
1.960938
2
[]
no_license
package gov.osti.entity; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import java.io.Reader; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Table; import java.io.IOException; import java.io.Serializable; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.OneToMany; import javax.persistence.Temporal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Entity @Table(name="metadata") @JsonIgnoreProperties (ignoreUnknown = true) public class DOECodeMetadata implements Serializable { /** * */ private static final long serialVersionUID = -909574677603914304L; private static final Logger log = LoggerFactory.getLogger(DOECodeMetadata.class.getName()); // Status values public enum Status { Saved, Published, Submitted } // Attributes private Long codeId; private String siteOwnershipCode = null; private Boolean openSource = null; private String repositoryLink = null; private String landingPage = null; private String accessibility = null; private String doiStatus = null; // set of Access Limitations (Strings) private List<String> accessLimitations = new ArrayList<>(); // Child tables -- persons private List<Developer> developers = new ArrayList<>(); private List<Contributor> contributors = new ArrayList<>(); // Child tables -- organizations private List<SponsoringOrganization> sponsoringOrganizations = new ArrayList<>(); private List<ContributingOrganization> contributingOrganizations = new ArrayList<>(); private List<ResearchOrganization> researchOrganizations = new ArrayList<>(); // Child table -- identifiers private List<RelatedIdentifier> relatedIdentifiers = new ArrayList<>(); private Date releaseDate = null; private String softwareTitle = null; private String acronym = null; private String doi = null; private String description = null; private String countryOfOrigin = null; private String keywords = null; private String disclaimers = null; private List<String> licenses = new ArrayList<>(); private String recipientName = null; private String recipientEmail = null; private String recipientPhone = null; private String recipientOrg = null; private String siteAccessionNumber = null; private String otherSpecialRequirements = null; private String owner = null; private Status workflowStatus = null; // Jackson object mapper private static final ObjectMapper mapper = new ObjectMapper() .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) .setSerializationInclusion(Include.NON_NULL); //for Gson public DOECodeMetadata() { } /** * getJson - Serializes the Metadata Object into a JSON. * @return A JsonElement representing the metadata's internal state in JSON */ public JsonNode toJson() { return mapper.valueToTree(this); } /** * Parses JSON in the request body of the reader into a DOECodemetadata object. * @param reader - A request reader containing JSON in the request body. * @return A DOECodeMetadata object representing the data of the JSON in the request body. * @throws IOException on JSON parsing errors (IO errors) */ public static DOECodeMetadata parseJson(Reader reader) throws IOException { return mapper.readValue(reader, DOECodeMetadata.class); } /** * Primary key for Metadata, the unique identifier value. * * @return the unique ID value for this record */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column (name = "CODE_ID") public Long getCodeId() { return codeId; } public void setCodeId(Long codeId) { this.codeId = codeId; } @Column (name="SITE_OWNERSHIP_CODE") public String getSiteOwnershipCode() { return siteOwnershipCode; } public void setSiteOwnershipCode(String siteOwnershipCode) { this.siteOwnershipCode = siteOwnershipCode; } @Column (name="OPEN_SOURCE") public Boolean getOpenSource() { return (null==openSource) ? false : openSource; } public void setOpenSource(Boolean openSource) { this.openSource = openSource; } @Column (name="REPOSITORY_LINK") public String getRepositoryLink() { return repositoryLink; } public void setRepositoryLink(String repositoryLink) { this.repositoryLink = repositoryLink; } /** * Obtain the set of Access Limitation values for this record. * @return a List of Access Limitation values */ @ElementCollection @CollectionTable( name = "ACCESS_LIMITATIONS", joinColumns=@JoinColumn(name="CODE_ID") ) @Column (name="ACCESS_LIMITATION") public List<String> getAccessLimitations() { return this.accessLimitations; } /** * Set the Access Limitations for this record. * @param limitations a set of Access Limitations to store */ public void setAccessLimitations(List<String> limitations) { this.accessLimitations = limitations; } /** * Get all the Contributors for this Metadata. * @return the Contributor List */ @OneToMany (cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn (name="OWNER_ID", referencedColumnName = "CODE_ID") public List<Contributor> getContributors() { return this.contributors; } /** * Get all the Sponsoring Organizations for this Metadata * @return a List of Sponsoring Organizations */ @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn (name ="OWNER_ID", referencedColumnName = "CODE_ID") public List<SponsoringOrganization> getSponsoringOrganizations() { return this.sponsoringOrganizations; } /** * Get all the Contributing Organizations * @return the List of Contributing Organizations */ @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn (name = "OWNER_ID", referencedColumnName = "CODE_ID") public List<ContributingOrganization> getContributingOrganizations() { return this.contributingOrganizations; } /** * Get all the Research Organizations * @return a List of Research Organizations */ @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn (name="OWNER_ID", referencedColumnName = "CODE_ID") public List<ResearchOrganization> getResearchOrganizations() { return this.researchOrganizations; } @Column (name = "SOFTWARE_TITLE", length = 1000) public String getSoftwareTitle() { return softwareTitle; } public void setSoftwareTitle(String softwareTitle) { this.softwareTitle = softwareTitle; } public String getAcronym() { return acronym; } public void setAcronym(String acronym) { this.acronym = acronym; } public String getDoi() { return doi; } public void setDoi(String doi) { this.doi = doi; } @Column (length = 4000, name = "description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setRelatedIdentifiers(List<RelatedIdentifier> identifiers) { this.relatedIdentifiers = identifiers; } @ElementCollection @CollectionTable( name="RELATED_IDENTIFIERS", joinColumns=@JoinColumn(name="CODE_ID") ) public List<RelatedIdentifier> getRelatedIdentifiers() { return this.relatedIdentifiers; } @Column (name = "COUNTRY_OF_ORIGIN") public String getCountryOfOrigin() { return countryOfOrigin; } public void setCountryOfOrigin(String countryOfOrigin) { this.countryOfOrigin = countryOfOrigin; } @Column (length = 500) public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } @Column (length = 1000) public String getDisclaimers() { return disclaimers; } public void setDisclaimers(String disclaimers) { this.disclaimers = disclaimers; } @ElementCollection @CollectionTable( name = "LICENSES", joinColumns=@JoinColumn(name="CODE_ID") ) @Column (name = "LICENSE") public List<String> getLicenses() { return licenses; } public void setLicenses(List<String> licenses) { this.licenses = licenses; } /** * Get all the Developers for this Metadata * @return the List of Developers */ @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn (name="OWNER_ID", referencedColumnName = "CODE_ID") public List<Developer> getDevelopers() { return developers; } /** * Add a single Developer to the in-memory items; if place is not set, * set it to the end of the current list. * * @param d the Developer to add * @return the Object we just added */ public Developer add(Developer d) { if (0==d.getPlace()) d.setPlace(developers.size()+1); developers.add(d); return d; } public ResearchOrganization add(ResearchOrganization o) { if (0==o.getPlace()) o.setPlace(researchOrganizations.size()+1); researchOrganizations.add(o); return o; } public SponsoringOrganization add(SponsoringOrganization o) { if (0==o.getPlace()) o.setPlace(sponsoringOrganizations.size()+1); sponsoringOrganizations.add(o); return o; } public ContributingOrganization add(ContributingOrganization o) { if (0==o.getPlace()) o.setPlace(contributingOrganizations.size()+1); contributingOrganizations.add(o); return o; } public Contributor add(Contributor c) { if (0==c.getPlace()) c.setPlace(contributors.size()+1); contributors.add(c); return c; } public void setContributingOrganizations(List<ContributingOrganization> list) { Integer place = 0; for ( ContributingOrganization o : list ) { if (0==o.getPlace()) o.setPlace(++place); } this.contributingOrganizations = list; } public void setResearchOrganizations(List<ResearchOrganization> list) { Integer place = 0; for ( ResearchOrganization o : list ) { if (0==o.getPlace()) o.setPlace(++place); } this.researchOrganizations = list; } public void setSponsoringOrganizations(List<SponsoringOrganization> list) { Integer place = 0; for ( SponsoringOrganization o : list ) { if (0==o.getPlace()) o.setPlace(++place); } this.sponsoringOrganizations = list; } public void setContributors(List<Contributor> list) { Integer place = 0; for ( Contributor c : list ) { if (0==c.getPlace()) c.setPlace(++place); } this.contributors = list; } /** * Add entire List at once; make sure to keep Place up to date properly. * * @param devlist a List of Developers to set */ public void setDevelopers(List<Developer> devlist) { // ensure that place is tracked appropriately Integer place = 0; for ( Developer d : devlist ) { if (0==d.getPlace()) d.setPlace(++place); } this.developers = devlist; } @Column (name = "RECIPIENT_NAME") public String getRecipientName() { return recipientName; } public void setRecipientName(String recipientName) { this.recipientName = recipientName; } @Column (name="RECIPIENT_EMAIL") public String getRecipientEmail() { return recipientEmail; } public void setRecipientEmail(String recipientEmail) { this.recipientEmail = recipientEmail; } @Column (name="RECIPIENT_PHONE") public String getRecipientPhone() { return recipientPhone; } public void setRecipientPhone(String recipientPhone) { this.recipientPhone = recipientPhone; } @Column (name = "RECIPIENT_ORGANIZATION") public String getRecipientOrg() { return recipientOrg; } public void setRecipientOrg(String recipientOrg) { this.recipientOrg = recipientOrg; } @Column (name="SITE_ACCESSION_NUMBER") public String getSiteAccessionNumber() { return siteAccessionNumber; } public void setSiteAccessionNumber(String siteAccessionNumber) { this.siteAccessionNumber = siteAccessionNumber; } @Column (name="OTHER_SPECIAL_REQUIREMENTS") public String getOtherSpecialRequirements() { return otherSpecialRequirements; } public void setOtherSpecialRequirements(String otherSpecialRequirements) { this.otherSpecialRequirements = otherSpecialRequirements; } /** * Obtain the WORKFLOW STATUS on this record (initially New, then Saved; after * a record is Published or Submitted, it may no longer be Saved.) * * @return the Status value for this record */ @Enumerated (EnumType.STRING) @Column (name="WORKFLOW_STATUS") public Status getWorkflowStatus() { return workflowStatus; } /** * Set the WORKFLOW STATUS on this record. * @param status the Status value to set */ public void setWorkflowStatus(Status status) { workflowStatus = status; } public void setReleaseDate(Date date) { this.releaseDate = date; } @Column (name="release_date") @Temporal(javax.persistence.TemporalType.DATE) @JsonFormat (shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "EST") public Date getReleaseDate() { return this.releaseDate; } @Column (name="LANDING_PAGE") public String getLandingPage() { return landingPage; } public void setLandingPage(String landingPage) { this.landingPage = landingPage; } @Column (name="DOI_STATUS") public String getDoiStatus() { return doiStatus; } public void setDoiStatus(String doiStatus) { this.doiStatus = doiStatus; } public String getAccessibility() { return accessibility; } public void setAccessibility(String accessibility) { this.accessibility = accessibility; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } }
true
d9963899eae42e31859969f917b9aca32c814b57
Java
skuarch/neo
/src/java/model/wrappers/WrapperObjectInterchange.java
UTF-8
2,125
2.765625
3
[]
no_license
package model.wrappers; import java.io.IOException; import model.beans.Configuration; import model.dao.DAO; import model.net.ObjectInterchange; /** * wrapper for the class ObjectInterchange * * @author skuarch */ public class WrapperObjectInterchange { private ObjectInterchange objectInterchange = null; private Configuration configuration = null; //========================================================================== /** * create a instance */ public WrapperObjectInterchange() { objectInterchange = new ObjectInterchange(); } // end WrapperObjectInterchange //========================================================================== /** * send and receive object, this warpper open the connection send the * object, receive a object and close the conenction * * @param object Object serializable * @return Object * @throws IOException * @throws ClassNotFoundException * @throws NullPointerException * @throws Exception */ public Object sendReceive(Object object) throws IOException, ClassNotFoundException, NullPointerException, Exception { if (object == null) { throw new NullPointerException("object is null"); } Object objectReturned = null; try { configuration = (Configuration) new DAO().get(1, Configuration.class); objectInterchange.setHost(configuration.getRemoteServer()); objectInterchange.setPort(configuration.getRemoteServerPort()); objectInterchange.setTimeout(configuration.getTimeWaitMessage()); objectInterchange.connect(); objectInterchange.sendObject(object); objectReturned = objectInterchange.receiveObject(); } catch (IOException ioe) { throw ioe; } catch (ClassNotFoundException cnfe) { throw cnfe; } catch (Exception e) { throw e; } finally { objectInterchange.closeConnection(); } return objectReturned; } // end sendReceive } // end class
true
92e2fc82a1900cff5aff0607b6ee48544f70414a
Java
ksh564/toilet
/app/src/main/java/org/androidtown/findrest/other/map_poi.java
UTF-8
599
2.203125
2
[]
no_license
package org.androidtown.findrest.other; /** * Created by 김승훈 on 2017-03-21. */ public class map_poi{ static double xpoi,ypoi; public map_poi(){ } public map_poi(double xpoi,double ypoi){ map_poi.xpoi=xpoi; map_poi.ypoi=ypoi; } public static double getXpoi() { return xpoi; } public static void setXpoi(double xpoi) { map_poi.xpoi = xpoi; } public static double getYpoi() { return ypoi; } public static void setYpoi(double ypoi) { map_poi.ypoi = ypoi; } }
true
09d9d41417130425495d82db05297304db78d7b9
Java
devlynnsingley/G153_JavaProgramming
/Project5/src/p7_13/p7_13.java
UTF-8
1,676
3.828125
4
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package p7_13; import java.util.Scanner; /** * * @author C02122472 */ public class p7_13 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner in = new Scanner(System.in); String player = " X "; TicTacToe game = new TicTacToe(); boolean done = false; // TODO code application logic here while (!done) { System.out.print(game.toString()); System.out.print("Row for " + player + " (0 to exit): "); int row = in.nextInt() - 1; /* * This checks if the players want to quit. */ if (row < 0) done = true; else { System.out.print("Column for " + player + ": "); int column = in.nextInt() - 1; game.set(row, column, player); /* * This loop will run a check to see if there are any winners. */ if (game.getWinner(player) == player) { System.out.println("The winner is" + player + "!!!"); done = true; } /* * This loop determines which player should be next. */ if (player.equals(" X ")) player = " O "; else player = " X "; } } } }
true
f8644a5e51675830d0cce3f9b01908bdc0683d46
Java
hybrid1969/evenova-Java-api
/src/main/java/com/tlabs/eve/ccp/EveRSSResponse.java
UTF-8
1,132
2.359375
2
[]
no_license
package com.tlabs.eve.ccp; import com.tlabs.eve.EveResponse; import java.util.ArrayList; import java.util.List; public final class EveRSSResponse extends EveResponse { private List<EveRSSEntry> rssEntries = new ArrayList<>(); private String title; private String link; private long dateUpdated; public EveRSSResponse() { super(); } public final List<EveRSSEntry> getEntries() { return this.rssEntries; } public final void addEntry(final EveRSSEntry entry) { //limit it if (this.rssEntries.size() < 50) { this.rssEntries.add(entry); } } public long getDateUpdated() { return dateUpdated; } public void setDateUpdated(long dateUpdated) { this.dateUpdated = dateUpdated; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } }
true
667fda239eefa8c9da108b59e13b1c6ae223fce6
Java
wangwilliams/design
/src/com/company/contribute/Singleton/SingletonMain.java
UTF-8
343
2.65625
3
[]
no_license
package com.company.contribute.Singleton; public class SingletonMain { public static void main(String[] args) { President president = President.getInstance(); President president1 = President.getInstance(); System.out.println(president.equals(president1)); System.out.println(president.getName()); } }
true
edae419ecb6e3cc80128a613b921371ea981eb0b
Java
BrayWyatt/Hotelbeds-Suppliers-Integrations-Developer-TEST
/Register_User/src/com/hotelbeds/supplierintegrations/hackertest/detector/HackerDetection.java
UTF-8
1,909
2.5625
3
[]
no_license
package com.hotelbeds.supplierintegrations.hackertest.detector; import com.sun.org.apache.xpath.internal.operations.Equals; import java.io.FileNotFoundException; import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; import java.util.Scanner; public class HackerDetection implements HackerDetector { @Override public String parseLine(String line) { //"80.238.9.179,133612947,SIGNIN_SUCCESS,Will.Smith" Scanner myReader = null; try { myReader = new Scanner(LogTools.logFile); } catch (FileNotFoundException e) { e.printStackTrace(); } int aparicionesFallidas = 0; while (myReader.hasNextLine()) { String logLine = myReader.nextLine(); if (!logLine.equals("")) { Calendar cal = Calendar.getInstance(); // creates calendar cal.setTime(new Date(Long.valueOf(logLine.split(",")[1]))); // sets calendar time/date cal.add(Calendar.MINUTE, 5); // adds one hour cal.getTime(); // returns new date object plus one hour if (cal.getTime().compareTo(new Date()) > 0) { if ((logLine.split(",")[0]).equals(line.split(",")[0]) && (logLine.split(",")[2]).equals(LogStatus.SIGNIN_FAILURE.toString())) { aparicionesFallidas++; } } } } myReader.close(); if(aparicionesFallidas >= 5) { return line.split(",")[0]; } return null; } }
true
2b67e8fa600c589e9657034e13eef518e5acb806
Java
cloudsoft/enstratius-client
/enstratius-java-client/src/main/java/io/cloudsoft/enstratius/api/requests/network/GetFirewall.java
UTF-8
1,628
2.171875
2
[ "Apache-2.0" ]
permissive
package io.cloudsoft.enstratius.api.requests.network; import io.cloudsoft.enstratius.api.HttpMethod; import io.cloudsoft.enstratius.api.client.AbstractRequest; import io.cloudsoft.enstratius.api.client.Request; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.util.ArrayList; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; public class GetFirewall extends AbstractRequest implements Request { private final static String API_CALL = "network/Firewall/%s"; private final String firewallId; private final String accountId; private final String regionId; public GetFirewall(String firewallId) { this(checkNotNull(firewallId, "firewallId"), null, null); } public GetFirewall(String firewallId, String accountId, String regionId) { this.firewallId = checkNotNull(firewallId, "firewallId"); this.accountId = accountId; this.regionId = regionId; } @Override public String getURI() { return String.format(resolveUri(API_CALL), firewallId); } @Override public HttpMethod getRestMethodName() { return HttpMethod.GET; } @Override public List<NameValuePair> getQueryParameters() { List<NameValuePair> queryParams = new ArrayList<NameValuePair>(); if (accountId != null) queryParams.add(new BasicNameValuePair("accountId", accountId)); if (regionId != null) queryParams.add(new BasicNameValuePair("regionId", regionId)); return queryParams; } @Override public String getPathToResult() { return "firewalls"; } }
true
1f5205135dd9f656b06a5627ab459a69158938e1
Java
George-E/MyWaterlooCCCSolutions
/SolutionsInJava/2013j4/src/Main.java
UTF-8
474
2.84375
3
[]
no_license
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int time = in.nextInt(); int chores = in.nextInt(); int choreTime[] = new int[chores]; for (int i = 0; i < chores; i++) { choreTime[i] = in.nextInt(); } Arrays.sort(choreTime); for (int i = 0; i < chores; i++) { time -= choreTime[i]; if (time < 0) { System.out.println(i); break; } } } }
true
bf0687a45b97a61684e69e6ff0fa42dd2fa68033
Java
mauricioccasani/plsql
/src/main/java/com/example/demo/controller/CustomerController.java
UTF-8
3,064
2.234375
2
[]
no_license
package com.example.demo.controller; import com.example.demo.client.CustomerClientImpl; import com.example.demo.client.CustomerFeignClient; import com.example.demo.model.Customer; import com.example.demo.model.Usuario; import com.example.demo.model.UsuarioResponse; import com.example.demo.service.UsuarioService; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.WebExchangeBindException; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import javax.validation.Valid; import java.net.URI; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; @RestController @Log4j2 @RequestMapping("/api") public class CustomerController { /* @Autowired private CustomerClientImpl customerClient; @Autowired private CustomerFeignClient client; @GetMapping("/{id}") public Customer setCustomerClient(@PathVariable String id) { return this.customerClient.findById(id); } */ @Autowired private UsuarioService usuarioService; @PostMapping public Mono<Usuario>save( @RequestBody Usuario monoUsuario) { log.info("Usuario creado: {}",monoUsuario); return this.usuarioService.add(monoUsuario); /* Map<String, Object> respuesta = new HashMap<String, Object>(); return monoUsuario.flatMap(usuario -> { return usuarioService.add(usuario).map(usu -> { respuesta.put("usuario", usu); respuesta.put("mensaje", "Usuario creado con éxito"); respuesta.put("timestamp", new Date()); return ResponseEntity .created(URI.create("/api/".concat(usu.getId()))) .contentType(MediaType.APPLICATION_JSON) .body(respuesta); }); });.onErrorResume(t -> { return Mono.just(t).cast(WebExchangeBindException.class) .flatMap(e -> Mono.just(e.getFieldErrors())) .flatMapMany(Flux::fromIterable) .map(fieldError -> "El campo " + fieldError.getField() + " " + fieldError.getDefaultMessage()) .collectList() .flatMap(list -> { respuesta.put("errors", list); respuesta.put("timestamp", new Date()); respuesta.put("status", HttpStatus.BAD_REQUEST.value()); return Mono.just(ResponseEntity.badRequest().body(respuesta)); }); });*/ } @GetMapping public Flux<Usuario>getALL(){ log.info("Usuario lista : {}",this.usuarioService.get()); return this.usuarioService.get(); } }
true
6b273f126a8189d3424d25620c77f6103f7ed132
Java
apache/netbeans
/java/debugger.jpda/src/org/netbeans/modules/debugger/jpda/models/ThreadsCache.java
UTF-8
28,607
1.648438
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.debugger.jpda.models; import com.sun.jdi.ObjectCollectedException; import com.sun.jdi.ThreadGroupReference; import com.sun.jdi.ThreadReference; import com.sun.jdi.VMDisconnectedException; import com.sun.jdi.VirtualMachine; import com.sun.jdi.event.Event; import com.sun.jdi.event.ThreadDeathEvent; import com.sun.jdi.event.ThreadStartEvent; import com.sun.jdi.request.EventRequest; import com.sun.jdi.request.ThreadDeathRequest; import com.sun.jdi.request.ThreadStartRequest; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.modules.debugger.jpda.JPDADebuggerImpl; import org.netbeans.modules.debugger.jpda.jdi.IllegalThreadStateExceptionWrapper; import org.netbeans.modules.debugger.jpda.jdi.InternalExceptionWrapper; import org.netbeans.modules.debugger.jpda.jdi.InvalidRequestStateExceptionWrapper; import org.netbeans.modules.debugger.jpda.jdi.ObjectCollectedExceptionWrapper; import org.netbeans.modules.debugger.jpda.jdi.ObjectReferenceWrapper; import org.netbeans.modules.debugger.jpda.jdi.ThreadGroupReferenceWrapper; import org.netbeans.modules.debugger.jpda.jdi.ThreadReferenceWrapper; import org.netbeans.modules.debugger.jpda.jdi.VMDisconnectedExceptionWrapper; import org.netbeans.modules.debugger.jpda.jdi.VMOutOfMemoryExceptionWrapper; import org.netbeans.modules.debugger.jpda.jdi.VirtualMachineWrapper; import org.netbeans.modules.debugger.jpda.jdi.event.ThreadDeathEventWrapper; import org.netbeans.modules.debugger.jpda.jdi.event.ThreadStartEventWrapper; import org.netbeans.modules.debugger.jpda.jdi.request.EventRequestManagerWrapper; import org.netbeans.modules.debugger.jpda.jdi.request.EventRequestWrapper; import org.netbeans.modules.debugger.jpda.util.Executor; import org.openide.util.Exceptions; /** * * @author martin */ public class ThreadsCache implements Executor { public static final String PROP_THREAD_STARTED = "threadStarted"; // NOI18N public static final String PROP_THREAD_DIED = "threadDied"; // NOI18N public static final String PROP_GROUP_ADDED = "groupAdded"; // NOI18N /** Threads containing this pattern in their names are filtered out (private threads, see visual debugger). */ public static final String THREAD_NAME_FILTER_PATTERN = "org.netbeans.modules.debugger.jpda"; // NOI18N private static final Logger logger = Logger.getLogger(ThreadsCache.class.getName()); private VirtualMachine vm; private JPDADebuggerImpl debugger; // Map of thread groups. Null when not initialized, otherwise contains // list of sub-groups for a group key. // uninitializedGroupList values for unknown sub-groups private Map<ThreadGroupReference, List<ThreadGroupReference>> groupMap; private final List<ThreadGroupReference> uninitializedGroupList = Collections.emptyList(); // Map of threads hierarchy - list of threads for group keys. // Null when not initialized. private Map<ThreadGroupReference, List<ThreadReference>> threadMap; private List<ThreadReference> allThreads; private PropertyChangeSupport pcs = new PropertyChangeSupport(this); private final boolean[] canFireChanges = new boolean[] { false }; public ThreadsCache(JPDADebuggerImpl debugger) { this.debugger = debugger; //groupMap = new HashMap<ThreadGroupReference, List<ThreadGroupReference>>(); //threadMap = new HashMap<ThreadGroupReference, List<ThreadReference>>(); allThreads = new ArrayList<ThreadReference>(); VirtualMachine vm = debugger.getVirtualMachine(); if (vm != null) { setVirtualMachine(vm); } } public void setVirtualMachine(VirtualMachine vm) { List<ThreadReference> _allThreads; List<ThreadGroupReference> _allGroups; synchronized (this) { if (this.vm == vm) return ; try { this.vm = vm; ThreadStartRequest tsr = EventRequestManagerWrapper.createThreadStartRequest( VirtualMachineWrapper.eventRequestManager(vm)); ThreadDeathRequest tdr = EventRequestManagerWrapper.createThreadDeathRequest( VirtualMachineWrapper.eventRequestManager(vm)); EventRequestWrapper.setSuspendPolicy(tsr, ThreadStartRequest.SUSPEND_NONE); EventRequestWrapper.setSuspendPolicy(tdr, ThreadStartRequest.SUSPEND_NONE); debugger.getOperator().register(tsr, this); debugger.getOperator().register(tdr, this); EventRequestWrapper.enable(tsr); EventRequestWrapper.enable(tdr); init(); } catch (VMDisconnectedExceptionWrapper e) { this.vm = null; } catch (InternalExceptionWrapper e) { this.vm = null; } catch (ObjectCollectedExceptionWrapper e) { this.vm = null; } catch (InvalidRequestStateExceptionWrapper irse) { Exceptions.printStackTrace(irse); this.vm = null; } _allThreads = new ArrayList<ThreadReference>(allThreads); if (groupMap != null) { _allGroups = getAllGroups(); } else { _allGroups = Collections.emptyList(); } } for (ThreadReference t : _allThreads) { pcs.firePropertyChange(PROP_THREAD_STARTED, null, t); } for (ThreadGroupReference g : _allGroups) { pcs.firePropertyChange(PROP_GROUP_ADDED, null, g); } synchronized (canFireChanges) { canFireChanges[0] = true; canFireChanges.notifyAll(); } } private synchronized void init() throws VMDisconnectedExceptionWrapper, InternalExceptionWrapper { allThreads = new ArrayList<ThreadReference>(VirtualMachineWrapper.allThreads(vm)); } private void initGroups(ThreadGroupReference group) { try { List<ThreadGroupReference> groups = new ArrayList<>(ThreadGroupReferenceWrapper.threadGroups0(group)); List<ThreadReference> threads = new ArrayList<>(ThreadGroupReferenceWrapper.threads0(group)); groupMap.put(group, groups); threadMap.put(group, threads); for (ThreadGroupReference g : groups) { initGroups(g); } } catch (ObjectCollectedException e) { } } private synchronized void initThreadGroups() throws VMDisconnectedExceptionWrapper, VMOutOfMemoryExceptionWrapper { threadMap = new HashMap<ThreadGroupReference, List<ThreadReference>>(); if (groupMap == null) { groupMap = new HashMap<ThreadGroupReference, List<ThreadGroupReference>>(); } else { // Remove unknown groups: Set<ThreadGroupReference> groups = new HashSet<ThreadGroupReference>(groupMap.keySet()); for (ThreadGroupReference g : groups) { if (groupMap.get(g) == uninitializedGroupList) { groupMap.remove(g); } } } List<ThreadGroupReference> groups; groups = groupMap.get(null); if (groups == null) { try { groups = new ArrayList<>(VirtualMachineWrapper.topLevelThreadGroups(vm)); } catch (InternalExceptionWrapper ex) { return ; } groupMap.put(null, groups); } for (ThreadGroupReference group : groups) { initGroups(group); } List<ThreadReference> mainThreads = new ArrayList<>(); threadMap.put(null, mainThreads); for (ThreadReference thread : allThreads) { try { if (ThreadReferenceWrapper.threadGroup(thread) == null) { mainThreads.add(thread); } } catch (ObjectCollectedExceptionWrapper e) { } catch (IllegalThreadStateExceptionWrapper e) { } catch (InternalExceptionWrapper e) { } } } public synchronized List<ThreadReference> getAllThreads() { return Collections.<List<ThreadReference>>unmodifiableList(new ArrayList(allThreads)); } public synchronized List<ThreadGroupReference> getTopLevelThreadGroups() { boolean uninitialized; if (groupMap == null) { groupMap = new HashMap<ThreadGroupReference, List<ThreadGroupReference>>(); uninitialized = true; } else { uninitialized = false; } List<ThreadGroupReference> topGroups = groupMap.get(null); if (topGroups == null) { if (vm == null) { return Collections.emptyList(); } topGroups = new ArrayList<>(VirtualMachineWrapper.topLevelThreadGroups0(vm)); groupMap.put(null, topGroups); if (uninitialized) { for (ThreadGroupReference g : topGroups) { groupMap.put(g, uninitializedGroupList); } } } return Collections.<List<ThreadReference>>unmodifiableList(new ArrayList(topGroups)); } public synchronized List<ThreadReference> getThreads(ThreadGroupReference group) { if (threadMap == null) { try { initThreadGroups(); } catch (VMDisconnectedExceptionWrapper ex) { return Collections.emptyList(); } catch (VMOutOfMemoryExceptionWrapper ex) { return Collections.emptyList(); } } List<ThreadReference> threads = threadMap.get(group); if (threads == null) { threads = Collections.<ThreadReference>emptyList(); } else { threads = Collections.<List<ThreadReference>>unmodifiableList(new ArrayList(threads)); } return threads; } public synchronized List<ThreadGroupReference> getGroups(ThreadGroupReference group) { if (groupMap == null) { try { initThreadGroups(); } catch (VMDisconnectedExceptionWrapper ex) { return Collections.emptyList(); } catch (VMOutOfMemoryExceptionWrapper ex) { return Collections.emptyList(); } } List<ThreadGroupReference> groups = groupMap.get(group); if (groups == uninitializedGroupList) { groups = new ArrayList<>(ThreadGroupReferenceWrapper.threadGroups0(group)); groupMap.put(group, groups); } if (groups == null) { groups = Collections.<ThreadGroupReference>emptyList(); } else { groups = Collections.<List<ThreadReference>>unmodifiableList(new ArrayList(groups)); } return groups; } private synchronized List<ThreadGroupReference> getAllGroups() { if (groupMap == null) { try { initThreadGroups(); } catch (VMDisconnectedExceptionWrapper ex) { return Collections.emptyList(); } catch (VMOutOfMemoryExceptionWrapper ex) { return Collections.emptyList(); } } List<ThreadGroupReference> groups = new ArrayList<ThreadGroupReference>(); fillAllGroups(groups, null); return groups; } private void fillAllGroups(List<ThreadGroupReference> groups, ThreadGroupReference g) { List<ThreadGroupReference> gs = groupMap.get(g); if (gs != null) { if (gs == uninitializedGroupList) { gs = new ArrayList<>(ThreadGroupReferenceWrapper.threadGroups0(g)); groupMap.put(g, gs); } groups.addAll(gs); for (ThreadGroupReference gg : gs) { fillAllGroups(groups, gg); } } } private List<ThreadGroupReference> addGroups(ThreadGroupReference group) throws ObjectCollectedExceptionWrapper { if (threadMap != null && !threadMap.containsKey(group)) { List<ThreadReference> threads = new ArrayList<>(); threadMap.put(group, threads); } if (groupMap == null) { return Collections.emptyList(); } List<ThreadGroupReference> addedGroups = new ArrayList<ThreadGroupReference>(); ThreadGroupReference parent; try { parent = ThreadGroupReferenceWrapper.parent(group); } catch (InternalExceptionWrapper ex) { return Collections.emptyList(); } catch (VMDisconnectedExceptionWrapper ex) { return Collections.emptyList(); } if (groupMap.get(parent) == null) { if (parent != null) { addedGroups.addAll(addGroups(parent)); } else { List<ThreadGroupReference> topGroups = new ArrayList<>(VirtualMachineWrapper.topLevelThreadGroups0(vm)); groupMap.put(null, topGroups); addedGroups.addAll(topGroups); } } List<ThreadGroupReference> parentsGroups = groupMap.get(parent); if (parentsGroups != null && !parentsGroups.contains(group)) { if (parentsGroups == uninitializedGroupList) { parentsGroups = new ArrayList<>(ThreadGroupReferenceWrapper.threadGroups0(parent)); groupMap.put(parent, parentsGroups); addedGroups.addAll(parentsGroups); } else { parentsGroups.add(group); addedGroups.add(group); } List<ThreadGroupReference> groups = new ArrayList<>(); groupMap.put(group, groups); } return addedGroups; } public boolean exec(Event event) { if (event instanceof ThreadStartEvent) { ThreadReference thread; boolean handleGroups = debugger.isInterestedInThreadGroups(); ThreadGroupReference group = null; try { thread = ThreadStartEventWrapper.thread((ThreadStartEvent) event); String name = ThreadReferenceWrapper.name(thread); if (name.contains(THREAD_NAME_FILTER_PATTERN)) { // Filtered return true; } if (handleGroups) { group = ThreadReferenceWrapper.threadGroup(thread); } } catch (InternalExceptionWrapper ex) { return true; } catch (VMDisconnectedExceptionWrapper ex) { return true; } catch (VMOutOfMemoryExceptionWrapper ex) { return true; } catch (IllegalThreadStateExceptionWrapper ex) { return true; } catch (ObjectCollectedExceptionWrapper ocex) { return true; } List<ThreadGroupReference> addedGroups = null; if (logger.isLoggable(Level.FINE)) { try { logger.fine("ThreadStartEvent: "+thread+", group = "+group+", handleGroups = "+handleGroups); } catch (Exception ex) { logger.log(Level.FINE, ex.getLocalizedMessage(), ex); } } synchronized (this) { if (group != null) { try { addedGroups = addGroups(group); } catch (ObjectCollectedExceptionWrapper ex) { try { if (ObjectReferenceWrapper.isCollected(thread)) { return true; } } catch (InternalExceptionWrapper ex1) { return true; } catch (VMDisconnectedExceptionWrapper ex1) { return true; } catch (ObjectCollectedExceptionWrapper ex1) { return true; } } } if (!handleGroups) { groupMap = null; threadMap = null; } else { if (threadMap != null) { List<ThreadReference> threads = threadMap.get(group); if (threads != null && !threads.contains(thread)) { // could be added by init() threads.add(thread); } } } if (!allThreads.contains(thread)) { // could be added by init() allThreads.add(thread); } } synchronized (canFireChanges) { if (!canFireChanges[0]) { try { canFireChanges.wait(); } catch (InterruptedException ex) {} } } if (addedGroups != null) { for (ThreadGroupReference g : addedGroups) { pcs.firePropertyChange(PROP_GROUP_ADDED, null, g); } } pcs.firePropertyChange(PROP_THREAD_STARTED, null, thread); } if (event instanceof ThreadDeathEvent) { ThreadReference thread; ThreadGroupReference group; try { thread = ThreadDeathEventWrapper.thread((ThreadDeathEvent) event); } catch (InternalExceptionWrapper ex) { return true; } catch (VMDisconnectedExceptionWrapper ex) { return true; } boolean getGroup; synchronized (this) { getGroup = groupMap != null || threadMap != null; } if (getGroup) { try { group = ThreadReferenceWrapper.threadGroup(thread); } catch (InternalExceptionWrapper ex) { group = null; } catch (VMDisconnectedExceptionWrapper ex) { return true; } catch (VMOutOfMemoryExceptionWrapper ex) { return true; } catch (IllegalThreadStateExceptionWrapper ex) { group = null; } catch (ObjectCollectedExceptionWrapper ocex) { group = null; } } else { group = null; } if (logger.isLoggable(Level.FINE)) { try { logger.fine("ThreadDeathEvent: "+thread+", group = "+group+", groupMap = "+groupMap); } catch (Exception ex) { logger.log(Level.FINE, ex.getLocalizedMessage(), ex); } } boolean removed = false; synchronized (this) { if (threadMap != null) { List<ThreadReference> threads; if (group != null) { threads = threadMap.get(group); } else { threads = null; for (List<ThreadReference> testThreads : threadMap.values()) { if (testThreads.contains(thread)) { threads = testThreads; } } } if (threads != null) { threads.remove(thread); } } removed = allThreads.remove(thread); } if (removed) { synchronized (canFireChanges) { if (!canFireChanges[0]) { try { canFireChanges.wait(); } catch (InterruptedException ex) {} } } pcs.firePropertyChange(PROP_THREAD_DIED, thread, null); } } return true; } public void removed(EventRequest eventRequest) { } /** * Check if the given thread is in the threads cache and add it if it's not. * This should be called when we have a suspicion that we did not receive * some events or that thread IDs changed (see e.g.: http://bugs.sun.com/view_bug.do?bug_id=6862295). */ public void assureThreadIsCached(ThreadReference tref) { boolean contains; synchronized (this) { contains = allThreads.contains(tref); } if (!contains) { String tname; try { tname = tref.toString(); if (tname.contains(THREAD_NAME_FILTER_PATTERN)) { return ; } } catch (Exception ex) { tname = ex.getLocalizedMessage(); } logger.info("Must SYNCHRONIZE ThreadsCache, did not found "+tname); sync(); } } /** * Synchronize the cached threads with VM threads. * This should be called when we have a suspicion that we did not receive * some events or that thread IDs changed (see e.g.: http://bugs.sun.com/view_bug.do?bug_id=6862295). */ private void sync() { List<ThreadReference> newThreads; List<ThreadReference> oldThreads; List<ThreadGroupReference> addedGroups = null; synchronized (this) { // Synchronize soon so that we do not add back threads removed from events, // or remove threads added from events List<ThreadReference> allThreadsNew; try { allThreadsNew = new ArrayList<ThreadReference>(VirtualMachineWrapper.allThreads(vm)); } catch (InternalExceptionWrapper iex) { return ; } catch (VMDisconnectedExceptionWrapper vmdex) { return ; } newThreads = new ArrayList<ThreadReference>(allThreadsNew); newThreads.removeAll(allThreads); oldThreads = new ArrayList<ThreadReference>(allThreads); oldThreads.removeAll(allThreadsNew); // Add new threads: for (ThreadReference thread : newThreads) { ThreadGroupReference group; try { group = ThreadReferenceWrapper.threadGroup(thread); } catch (InternalExceptionWrapper ex) { continue; } catch (VMDisconnectedExceptionWrapper ex) { return ; } catch (VMOutOfMemoryExceptionWrapper ex) { return ; } catch (IllegalThreadStateExceptionWrapper ex) { continue; } catch (ObjectCollectedExceptionWrapper ocex) { continue; } if (group != null) { try { if (addedGroups == null) { addedGroups = addGroups(group); } else { addedGroups.addAll(addGroups(group)); } } catch (ObjectCollectedExceptionWrapper occex) { try { if (ObjectReferenceWrapper.isCollected(thread)) { continue; } } catch (InternalExceptionWrapper ex1) { continue; } catch (VMDisconnectedExceptionWrapper ex1) { return ; } catch (ObjectCollectedExceptionWrapper ex1) { continue; } } } if (threadMap != null) { List<ThreadReference> threads = threadMap.get(group); if (threads != null && !threads.contains(thread)) { // could be added by init() threads.add(thread); } } } allThreads.addAll(newThreads); // Remove old threads: if (threadMap != null) { for (ThreadReference thread : oldThreads) { ThreadGroupReference group; try { group = ThreadReferenceWrapper.threadGroup(thread); } catch (InternalExceptionWrapper ex) { group = null; } catch (VMDisconnectedExceptionWrapper ex) { return ; } catch (VMOutOfMemoryExceptionWrapper ex) { return ; } catch (IllegalThreadStateExceptionWrapper ex) { group = null; } catch (ObjectCollectedExceptionWrapper ocex) { group = null; } List<ThreadReference> threads; if (group != null) { threads = threadMap.get(group); } else { threads = null; for (List<ThreadReference> testThreads : threadMap.values()) { if (testThreads.contains(thread)) { threads = testThreads; } } } if (threads != null) { threads.remove(thread); } } } allThreads.removeAll(oldThreads); } // End synchronized synchronized (canFireChanges) { if (!canFireChanges[0]) { try { canFireChanges.wait(); } catch (InterruptedException ex) {} } } if (logger.isLoggable(Level.CONFIG)) { logger.config("SYNCHRONIZE of ThreadsCache discovered new threads: "+threadsListing(newThreads)); logger.config(" and removed obsolete threads: "+threadsListing(oldThreads)); } if (addedGroups != null) { for (ThreadGroupReference g : addedGroups) { pcs.firePropertyChange(PROP_GROUP_ADDED, null, g); } } for (ThreadReference thread : newThreads) { pcs.firePropertyChange(PROP_THREAD_STARTED, null, thread); } for (ThreadReference thread : oldThreads) { pcs.firePropertyChange(PROP_THREAD_DIED, thread, null); } } private static String threadsListing(List<ThreadReference> threads) { StringBuilder nt = new StringBuilder("[\n"); for (ThreadReference t : threads) { String s; try { s = t.toString(); } catch (Exception ex) { s = ex.toString(); } nt.append(s); nt.append(",\n"); } int l = nt.length(); if (l > 1) { nt.delete(l - 2, l); } nt.append(']'); return nt.toString(); } public void addPropertyChangeListener(PropertyChangeListener l) { pcs.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener(l); } }
true
57bdc249a3bfc4526b6eac8dae6eb3495a07dc9f
Java
Softtanck/MultiTypeRecycleView
/Cheweishi/app/src/main/java/com/cheweishi/android/activity/HomeMoreActivity.java
UTF-8
9,389
1.882813
2
[]
no_license
package com.cheweishi.android.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.TextView; import com.cheweishi.android.R; import com.cheweishi.android.adapter.MainGridViewAdapter; import com.cheweishi.android.config.Constant; import com.cheweishi.android.config.NetInterface; import com.cheweishi.android.dialog.ProgrosDialog; import com.cheweishi.android.entity.LoginResponse; import com.cheweishi.android.entity.MainGridInfoNative; import com.cheweishi.android.utils.ButtonUtils; import com.cheweishi.android.utils.GsonUtil; import com.cheweishi.android.widget.UnslidingGridView; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.lidroid.xutils.view.annotation.event.OnClick; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by tangce on 7/25/2016. */ public class HomeMoreActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener { private String[] name = {"买车险", "洗车", "紧急救援", "保养", "找加油站", "美容", "车辆数据", "违章查询", "找车位", "资讯"}; private int[] icon = {R.drawable.xian, R.drawable.xiche, R.drawable.jinjijiuyuan, R.drawable.baoyang, R.drawable.jiayouzhan, R.drawable.meirong, R.drawable.dongtai, R.drawable.weizhang, R.drawable.chewei, R.drawable.home_more}; // 列表 @ViewInject(R.id.gv_more_service) private UnslidingGridView gv_more_service; //左边按钮 @ViewInject(R.id.left_action) private Button left_action; //标题 @ViewInject(R.id.title) private TextView title; //列表适配器 private MainGridViewAdapter gridViewAdapter; private Intent intent = new Intent(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_more); ViewUtils.inject(this); init(); } private void init() { title.setText(getResources().getString(R.string.more_car)); left_action.setText(getResources().getString(R.string.back)); List<MainGridInfoNative> gridInfos = new ArrayList<MainGridInfoNative>(); for (int i = 0; i < 10; i++) { MainGridInfoNative gridInfo = new MainGridInfoNative(); gridInfo.setName(name[i]); gridInfo.setImgId(icon[i]); // gridInfo.setImgUrl("asdasdas");// TODO:暂无可配图片地址 gridInfos.add(gridInfo); } gridViewAdapter = new MainGridViewAdapter(baseContext, gridInfos, false); gv_more_service.setAdapter(gridViewAdapter); gv_more_service.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /** * 快速点击忽略处理 */ if (ButtonUtils.isFastClick()) { return; } switch (position) { case 0:// 买车险 Intent intent = new Intent(baseContext, WebActivity.class); intent.putExtra("url", NetInterface.INSURANCE); startActivity(intent); break; case 1:// 洗车 isLogin(WashcarListActivity.class); break; case 2:// 紧急救援 Intent sos = new Intent(baseContext, SoSActivity.class); startActivity(sos); break; case 3:// 保养 isLogin(MaintainListActivity_new.class); break; case 4:// 找加油站 isLogin(GasStationActivity.class); break; case 5:// 美容 isLogin(BeautyListActivity_new.class); break; case 6:// 车辆数据 updateCache("CAR_DETECTION"); break; case 7:// 违章代办 updateCache("PESSANY"); break; case 8:// 找车位 isLogin(FindParkingSpaceActivity.class); break; case 9:// 资讯 Intent home = new Intent(baseContext, MainNewActivity.class); home.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); home.putExtra(getResources().getString(R.string.newnotify), true); startActivity(home); finish(); break; } } @Override public void error(String errorMsg) { ProgrosDialog.closeProgrosDialog(); showToast(R.string.server_link_fault); } @Override public void receive(String TAG, String data) { ProgrosDialog.closeProgrosDialog(); switch (TAG) { case "SOS": // 紧急救援 ProgrosDialog.closeProgrosDialog(); LoginResponse sos = (LoginResponse) GsonUtil.getInstance().convertJsonStringToObject(data, LoginResponse.class); loginResponse = sos; BaseActivity.loginResponse = loginResponse; // LoginMessageUtils.saveloginmsg(baseContext, sos); isLoginOrHasCar(SoSActivity.class); break; case "CAR_DYNAMIC":// 车辆动态 ProgrosDialog.closeProgrosDialog(); LoginResponse carDynamic = (LoginResponse) GsonUtil.getInstance().convertJsonStringToObject(data, LoginResponse.class); loginResponse = carDynamic; BaseActivity.loginResponse = loginResponse; // LoginMessageUtils.saveloginmsg(baseContext, carDynamic); isLoginOrHasCar(CarDynamicActivity.class); break; case "CAR_DETECTION":// 一键检测 ProgrosDialog.closeProgrosDialog(); LoginResponse carDetection = (LoginResponse) GsonUtil.getInstance().convertJsonStringToObject(data, LoginResponse.class); loginResponse = carDetection; BaseActivity.loginResponse = loginResponse; // LoginMessageUtils.saveloginmsg(baseContext, carDetection); isLoginOrHasCar(CarDetectionActivity.class); break; case "PESSANY":// 违章查询 ProgrosDialog.closeProgrosDialog(); LoginResponse pessany = (LoginResponse) GsonUtil.getInstance().convertJsonStringToObject(data, LoginResponse.class); loginResponse = pessany; BaseActivity.loginResponse = loginResponse; // LoginMessageUtils.saveloginmsg(baseContext, pessany); isLoginOrHasCar_New(PessanySearchActivity.class); break; } } /** * 对是否登陆和是否有车处理 * * @param cls */ private void isLoginOrHasCar(Class<?> cls) { if (!isLogined()) { intent.setClass(baseContext, LoginActivity.class); startActivity(intent); overridePendingTransition(R.anim.score_business_query_enter, R.anim.score_business_query_exit); } else if (!hasCar()) { showCustomDialog("你还没有添加车辆", "添加车辆", 0); return; } else if (!hasDevice()) { showCustomDialog(getString(R.string.home_no_device), "前往绑定", 1); return; } else { intent.setClass(baseContext, cls); startActivity(intent); } } /** * 是否有车新判断 * * @param cls */ private void isLoginOrHasCar_New(Class<?> cls) { if (!isLogined()) { intent.setClass(baseContext, LoginActivity.class); startActivity(intent); overridePendingTransition(R.anim.score_business_query_enter, R.anim.score_business_query_exit); } else if (!hasCar()) { showCustomDialog("你还没有添加车辆", "添加车辆", 0); return; } else { intent.setClass(baseContext, cls); startActivity(intent); } } /** * 登陆才能跳转 * * @param cls */ private void isLogin(Class<?> cls) { if (!isLogined()) { intent.setClass(baseContext, LoginActivity.class); startActivity(intent); overridePendingTransition(R.anim.score_business_query_enter, R.anim.score_business_query_exit); } else { intent.setClass(baseContext, cls); startActivity(intent); } } private void updateCache(String tag) { if (isLogined()) { ProgrosDialog.openDialog(baseContext); String url = NetInterface.HEADER_ALL + NetInterface.UPDATE_CACHE + NetInterface.SUFFIX; Map<String, Object> param = new HashMap<>(); param.put("userId", loginResponse.getDesc()); param.put("token", loginResponse.getToken()); param.put(Constant.PARAMETER_TAG, tag); netWorkHelper.PostJson(url, param, this); } } @OnClick(R.id.left_action) @Override public void onClick(View v) { finish(); } }
true
280eecf8a0304c5cb40ab793a8a21d6bd3396977
Java
enzoappi/ProjetoDeSistemas2.Java.FEMASS
/PadraoTemplate.AgenciaDeViagem.N2_Questao03/src/model/entities/AgenciaDeViagem.java
UTF-8
1,111
3
3
[ "MIT" ]
permissive
/* * 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 model.entities; import javax.swing.JOptionPane; /** * * @author enzoappi */ public class AgenciaDeViagem { public void organizar_viagem() { int resposta = 0; resposta = Integer.parseInt(JOptionPane.showInputDialog(null, "Qual o tipo de viagem desejada?\n" + "\n[1] - Campestre" + "\n[2] - Praia" + "\n[3] - Histórica")); switch(resposta) { case 1: new ViagemCampestre().itinerarioViagem(); break; case 2: new ViagemPraia().itinerarioViagem(); break; case 3: new ViagemHistorica().itinerarioViagem(); break; default: JOptionPane.showMessageDialog(null, "Por favor selecione um valor correto!"); organizar_viagem(); } } }
true
dd14b2929912a467fda26fd2b4934b4076e7524d
Java
iswu2013/pret
/pret-open/src/main/java/com/pret/open/repository/PretCurrencyRepository.java
UTF-8
396
1.59375
2
[]
no_license
package com.pret.open.repository; import com.pret.common.repository.BaseRepository; import com.pret.open.entity.PretCurrency; /** * <p>Description: [pretRepository]</p> * Created on 2019年09月15日 * @author <a href="mailto: 1037216275@qq.com">wujinsong</a> * @version 1.0 * Copyright (c) 2019年 极客城堡 */ public interface PretCurrencyRepository extends BaseRepository<PretCurrency>{ }
true
eb216e052d7d48e199c8574a108bcd9db1ac6efe
Java
prymetheus/Struts2
/Struts2_Study/src/main/java/com/qf/web/interceptor/MyInterceptor.java
UTF-8
1,360
2.3125
2
[]
no_license
package com.qf.web.interceptor; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.qf.web.action.ParamAction1; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 自定义拦截器 * */ public class MyInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation actionInvocation) throws Exception { System.out.println("自定义拦截器正在执行......................"); /*获取行为对象*/ /* Action action = (Action)actionInvocation.getAction();*/ System.out.println("预处理"); // HttpServletRequest request = ServletActionContext.getRequest(); if (actionInvocation.getAction() instanceof ParamAction1) { ParamAction1 action = (ParamAction1) actionInvocation.getAction(); System.out.println("用户名:"+action.getUsername()+"........."); action.setUsername("拦截器"); } //执行对应的方法 String invoke = actionInvocation.invoke(); HttpServletResponse response = ServletActionContext.getResponse(); System.out.println("后处理"); return invoke; } }
true
a7c1d601e9388b386586f010be594cc36159d398
Java
Under-estimate/Answer
/com/zjs/ui/MyButton.java
UTF-8
2,256
3.21875
3
[]
no_license
package com.zjs.ui; import com.zjs.R; import javax.swing.*; import javax.swing.border.LineBorder; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * 一个好看的按钮。 * @author zjs * */ public class MyButton extends JPanel { private JLabel label; private final String text; private ActionListener listener; public MyButton(String text){ super(); this.text=text; setBackground(Color.BLACK); setBorder(new LineBorder(Color.LIGHT_GRAY)); setLayout(new BorderLayout()); initComponents(); } /** * 初始化组件 * @author zjs * */ private void initComponents(){ label=new JLabel(text,JLabel.CENTER); label.setFont(R.F.deriveFont(30f)); label.setForeground(Color.WHITE); add(label,BorderLayout.CENTER); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { setBackground(Color.LIGHT_GRAY); label.setForeground(Color.BLACK); } @Override public void mouseReleased(MouseEvent e) { setBackground(Color.BLACK); label.setForeground(Color.WHITE); //在这里执行按钮被点击的效果,因为如果在mouseClicked中执行点击效果的话,当鼠标按下和释放的位置有细微差别时mouseClicked不会被调用。 listener.actionPerformed(null); } @Override public void mouseEntered(MouseEvent e) { setBackground(Color.DARK_GRAY); } @Override public void mouseExited(MouseEvent e) { setBackground(Color.BLACK); } }); } /** * 设置该按钮的事件监听器。当鼠标点击按钮时调用 。 * 传入的actionEvent为null。 * @author zjs * */ public void setActionListener(ActionListener l){ this.listener=l; } /** * 设置该按钮的文本。 * @author zjs * */ public void setText(String text){ label.setText(text); } }
true
b2b17f7685381ab9292d5652ec6aa882a7f595f8
Java
junnae/spsak
/saksbehandling/behandlingslager/domene/src/main/java/no/nav/foreldrepenger/behandlingslager/behandling/inntektarbeidytelse/grunnlag/Inntektspost.java
UTF-8
1,042
2.265625
2
[ "MIT" ]
permissive
package no.nav.foreldrepenger.behandlingslager.behandling.inntektarbeidytelse.grunnlag; import java.time.LocalDate; import no.nav.foreldrepenger.behandlingslager.behandling.inntektarbeidytelse.YtelseType; import no.nav.foreldrepenger.behandlingslager.behandling.inntektarbeidytelse.kodeverk.InntektspostType; import no.nav.foreldrepenger.domene.typer.Beløp; public interface Inntektspost { /** * Underkategori av utbetaling * <p> * F.eks * <ul> * <li>Lønn</li> * <li>Ytelse</li> * <li>Næringsinntekt</li> * </ul> * * @return {@link InntektspostType} */ InntektspostType getInntektspostType(); /** * Periode start * * @return første dag i perioden */ LocalDate getFraOgMed(); /** * Periode slutt * * @return siste dag i perioden */ LocalDate getTilOgMed(); /** * Beløpet som har blitt utbetalt i perioden * * @return Beløpet */ Beløp getBeløp(); YtelseType getYtelseType(); }
true
61e3e820c9b134b4e292086f8edb68df74af7818
Java
nisheeth84/prjs_sample
/aio-service/src/main/java/com/viettel/coms/bo/manufacturingVTBO.java
UTF-8
3,900
1.78125
2
[]
no_license
package com.viettel.coms.bo; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import com.viettel.coms.dto.manufacturingVT_DTO; import com.viettel.service.base.model.BaseFWModelImpl; @Entity @Table(name = "GOODS_PLAN") public class manufacturingVTBO extends BaseFWModelImpl{ // @Override // public BaseFWDTOImpl toDTO() { // // TODO Auto-generated method stub // return null; // } private Long createdUserId; private Date updatedDate; private Long updatedUserId; private Date createdDate; private Long status; private String baseContent; private String performContent; private Long goodsPlanId; private String code; private String name; private Long signState; @Id @GeneratedValue(generator = "sequence") @GenericGenerator(name = "sequence", strategy = "sequence", parameters = { @Parameter(name = "sequence", value = "GOODS_PLAN_SEQ")}) @Column(name = "GOODS_PLAN_ID", length = 22) public Long getGoodsPlanId() { return goodsPlanId; } public void setGoodsPlanId(Long goodsPlanId) { this.goodsPlanId = goodsPlanId; } @Column(name = "CREATED_DATE", length = 22) public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } @Column(name = "STATUS", length = 22) public Long getStatus() { return status; } public void setStatus(Long status) { this.status = status; } @Column(name = "BASE_CONTENT", length = 22) public String getBaseContent() { return baseContent; } public void setBaseContent(String baseContent) { this.baseContent = baseContent; } @Column(name = "PERFORM_CONTENT", length = 22) public String getPerformContent() { return performContent; } public void setPerformContent(String performContent) { this.performContent = performContent; } @Column(name = "CREATED_USER_ID", length = 22) public Long getCreatedUserId() { return createdUserId; } public void setCreatedUserId(Long createdUserId) { this.createdUserId = createdUserId; } @Column(name = "UPDATED_DATE", length = 22) public Date getUpdatedDate() { return updatedDate; } public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } @Column(name = "UPDATED_USER_ID", length = 22) public Long getUpdatedUserId() { return updatedUserId; } public void setUpdatedUserId(Long updatedUserId) { this.updatedUserId = updatedUserId; } @Column(name = "CODE", length = 22) public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Column(name = "NAME", length = 22) public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name = "SIGN_STATE", length = 22) public Long getSignState() { return signState; } public void setSignState(Long signState) { this.signState = signState; } @Override public manufacturingVT_DTO toDTO() { manufacturingVT_DTO manufacturingvt_DTO = new manufacturingVT_DTO(); // set cac gia tri manufacturingvt_DTO.setGoodsPlanId(this.goodsPlanId); manufacturingvt_DTO.setCode(this.code); manufacturingvt_DTO.setName(this.name); manufacturingvt_DTO.setSignState(this.signState); manufacturingvt_DTO.setStatus(this.status); manufacturingvt_DTO.setBaseContent(this.baseContent); manufacturingvt_DTO.setPerformContent(this.performContent); manufacturingvt_DTO.setCreatedUserId(this.createdUserId); manufacturingvt_DTO.setUpdatedDate(this.updatedDate); manufacturingvt_DTO.setUpdatedUserId(this.updatedUserId); return manufacturingvt_DTO; } }
true
759094360aad2959fd08c0bd6c085db2cef0c45c
Java
wanghai328/AndroidBaseTest
/app/src/main/java/com/test/mytest/broadcast/BroadcastActivity.java
UTF-8
1,596
2.078125
2
[]
no_license
package com.test.mytest.broadcast; import android.app.Activity; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.annotation.Nullable; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.test.mytest.R; public class BroadcastActivity extends Activity implements View.OnClickListener { private final String NORMAL_ACTION = "com.test.wh"; Button btn; LocalBroadcastManager lm; MyReceiver receiver; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_broadcast); btn = findViewById(R.id.send_broadcast); initReceiver(); btn.setOnClickListener(this); } private void initReceiver() { receiver = new MyReceiver(); IntentFilter intentFilter = new IntentFilter(NORMAL_ACTION); lm = LocalBroadcastManager.getInstance(this); lm.registerReceiver(receiver, intentFilter); // registerReceiver(receiver, intentFilter); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.send_broadcast: Intent intent = new Intent(NORMAL_ACTION); intent.putExtra("config", "123"); lm.sendBroadcast(intent); break; } } @Override protected void onDestroy() { super.onDestroy(); lm.unregisterReceiver(receiver); } }
true
44c5714157d323967a6b93a9fac6fd4aea11a5c6
Java
bellmit/novbank-store
/src/main/java/com/novbank/store/util/CollectionUtils.java
UTF-8
2,643
2.6875
3
[ "Apache-2.0" ]
permissive
package com.novbank.store.util; import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Created by CaoKe on 2015/4/18. */ public class CollectionUtils { public static <K,V> void removeEmptyValueEntry(final Map<K,V> map){ Set<K> keyToDelete = new HashSet<>(); if(map == null) return; for(K key : map.keySet()) if(map.get(key) == null) keyToDelete.add(key); for(K key:keyToDelete) map.remove(key); } public static <K,V> Map<K,V> copyMapExcludeKeys(Map<K,V> map, Set<K> excludeKeys){ Map<K,V> copy = Maps.newHashMap(); if(map == null) return copy; for(K key:map.keySet()){ if(!excludeKeys.contains(key)) copy.put(key,map.get(key)); } return copy; } public static <K,V1,V2> double calculateSimilarity(Map<K,V1> left, Map<K,V2> right, Set<K> ignoreKeys, boolean strict, boolean ignoreNull, double leftMoreFactor, double rightMoreFactor, double conflictFactor){ MapDifference<K,?> difference = Maps.difference(left, right); double conflict = 0; double leftMore = 0; double rightMore = 0; double ignores = 0; double match = 0; for(K key: difference.entriesDiffering().keySet()){ if(ignoreKeys.contains(key)){ ignores++;continue; } if(ignoreNull && left.get(key)==null){ match++; continue; } if(ignoreNull && right.get(key) == null){ leftMore++;continue; } conflict++; } for(K key : difference.entriesOnlyOnLeft().keySet()){ if(ignoreKeys.contains(key)){ ignores++;continue; } if(ignoreNull && left.get(key) == null){ }else leftMore++; } for(K key : difference.entriesOnlyOnRight().keySet()){ if(ignoreKeys.contains(key)){ ignores++;continue; } if(ignoreNull && right.get(key) == null){ }else rightMore++; } match += difference.entriesInCommon().size(); if(conflict>0 && strict) return Double.MIN_VALUE; return 1 - (leftMore * leftMoreFactor + rightMore * rightMoreFactor + conflict* conflictFactor) / (1 + ignores + match + leftMore + rightMore + conflict); } }
true
c1570d3d08b63104c2ba90ac395c7e5135e2036b
Java
RelaxBin/rabbitmq_learn
/springcloudstream-rabbitmq/springcloudstream-producer/src/main/java/com/zempty/Barista.java
UTF-8
397
1.789063
2
[]
no_license
package com.zempty; import org.springframework.cloud.stream.annotation.Output; import org.springframework.messaging.MessageChannel; /** * @author zempty * @ClassName Barista.java * @Description TODO * @createTime 2020年04月05日 15:17:00 */ public interface Barista { String OUTPUT_CHANNEL = "output_channel"; @Output(Barista.OUTPUT_CHANNEL) MessageChannel logoutput(); }
true
a70aa95296961812b471c31b6f3005d5b807630b
Java
baddrug/projeto2
/src/projetointegrador/view/TelaCadProd.java
UTF-8
76,389
2.359375
2
[]
no_license
/* * 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 projetointegrador.view; import java.awt.Color; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import projetointegrador.Controller.FornecedorController; import projetointegrador.Controller.ProdutoController; /** * * @author carlo */ public class TelaCadProd extends javax.swing.JFrame { String modoTela = "Criar"; /** * Creates new form TelaCadProd */ public TelaCadProd() { initComponents(); DesabilitarFormulario(); CarregarTabela(); setLocationRelativeTo(null); } public void HabilitarFormulario(){ this.jtNome.setEnabled(true); this.jfValor.setEnabled(true); this.jtQuanti.setEnabled(true); this.jcFornecedor.setEnabled(true); this.btnSalvarProd.setEnabled(true); this.btnCancelar.setEnabled(true); this.jtNomeForn.setEnabled(true); this.jfCNPJ.setEnabled(true); this.jtBairro.setEnabled(true); this.jfCEP.setEnabled(true); this.jtCidade.setEnabled(true); this.jtEndereco.setEnabled(true); this.jfTelefone.setEnabled(true); this.jtUF.setEnabled(true); this.bntSalvar.setEnabled(true); this.bntCancelar.setEnabled(true); } public void DesabilitarFormulario(){ this.jtNome.setEnabled(false); this.jfValor.setEnabled(false); this.jtQuanti.setEnabled(false); this.jcFornecedor.setEnabled(false); this.btnSalvarProd.setEnabled(false); this.btnCancelar.setEnabled(false); this.jtNomeForn.setEnabled(false); this.jfCNPJ.setEnabled(false); this.jtBairro.setEnabled(false); this.jfCEP.setEnabled(false); this.jtCidade.setEnabled(false); this.jtEndereco.setEnabled(false); this.jfTelefone.setEnabled(false); this.jtUF.setEnabled(false); this.bntSalvar.setEnabled(false); this.bntCancelar.setEnabled(false); } public void LimparFormulario(){ this.jblIDP.setText(""); this.jtNome.setText(""); this.jfValor.setText(""); this.jtQuanti.setText(""); this.jtQuanti.setText(""); this.jblIDF.setText(""); this.jtNomeForn.setText(""); this.jfCNPJ.setText(""); this.jtBairro.setText(""); this.jfCEP.setText(""); this.jtCidade.setText(""); this.jtEndereco.setText(""); this.jfTelefone.setText(""); this.jtUF.setText(""); this.jblCampNome.setText(""); } public void CarregarTabela(){ //Peço ao controller resgatar os clientes do banco de dados ArrayList<String[]> linhasProduto = ProdutoController.consultarProduto(); ArrayList<String[]> linhasFornecedor = FornecedorController.consultarFornecedor(); //Opção 1 - Crio manualmente um modelo para a tabela e defino as colunas DefaultTableModel tmProduto = new DefaultTableModel(); tmProduto.addColumn("ID"); tmProduto.addColumn("Nome"); tmProduto.addColumn("Valor"); tmProduto.addColumn("Quantidade"); tmProduto.addColumn("Fornecedor"); jTable1.setModel(tmProduto); //Removo a coluna da View (JTable) mas mantenho na model para armazenar o ID jTable1.removeColumn(jTable1.getColumnModel().getColumn(0)); //Para cada cliente resgatado do banco de dados, atualizo a tabela for(String[] p:linhasProduto) { tmProduto.addRow(p); } //Defino o tamanho para cada coluna jTable1.getColumnModel().getColumn(0).setPreferredWidth(300); jTable1.getColumnModel().getColumn(1).setPreferredWidth(100); //Opção 1 - Crio manualmente um modelo para a tabela e defino as colunas DefaultTableModel tmFornecedor = new DefaultTableModel(); tmFornecedor.addColumn("ID"); tmFornecedor.addColumn("Nome"); tmFornecedor.addColumn("CNPJ"); tmFornecedor.addColumn("Telefone"); tmFornecedor.addColumn("Endereço"); tmFornecedor.addColumn("Bairro"); tmFornecedor.addColumn("CEP"); tmFornecedor.addColumn("UF"); jTable2.setModel(tmFornecedor); //Removo a coluna da View (JTable) mas mantenho na model para armazenar o ID jTable2.removeColumn(jTable2.getColumnModel().getColumn(0)); //Para cada cliente resgatado do banco de dados, atualizo a tabela for(String[] f:linhasFornecedor) { tmFornecedor.addRow(f); } //Defino o tamanho para cada coluna jTable2.getColumnModel().getColumn(0).setPreferredWidth(300); jTable2.getColumnModel().getColumn(1).setPreferredWidth(100); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jfValor = new javax.swing.JFormattedTextField(); jtNome = new javax.swing.JTextField(); jblValor = new javax.swing.JLabel(); jblFornecedor = new javax.swing.JLabel(); jblID = new javax.swing.JLabel(); jblNome = new javax.swing.JLabel(); jtQuanti = new javax.swing.JTextField(); jblQuant = new javax.swing.JLabel(); btnSalvarProd = new javax.swing.JButton(); btnCancelar = new javax.swing.JButton(); jblIDP = new javax.swing.JLabel(); jcFornecedor = new javax.swing.JComboBox<>(); jPanel3 = new javax.swing.JPanel(); jsTabela = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); btnRemover = new javax.swing.JButton(); jtPesquisar = new javax.swing.JTextField(); btnEditar = new javax.swing.JButton(); btnNovo = new javax.swing.JButton(); btnPesquisar = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jblBairro = new javax.swing.JLabel(); jblCidade = new javax.swing.JLabel(); jblUF = new javax.swing.JLabel(); jtBairro = new javax.swing.JTextField(); jblEndereco = new javax.swing.JLabel(); jtNomeForn = new javax.swing.JTextField(); jfCEP = new javax.swing.JFormattedTextField(); jtCidade = new javax.swing.JTextField(); jblNomeForn = new javax.swing.JLabel(); jfTelefone = new javax.swing.JFormattedTextField(); jblTel = new javax.swing.JLabel(); bntSalvar = new javax.swing.JButton(); jtUF = new javax.swing.JTextField(); jtEndereco = new javax.swing.JTextField(); jblCEP = new javax.swing.JLabel(); jblID1 = new javax.swing.JLabel(); bntCancelar = new javax.swing.JButton(); jblIDF = new javax.swing.JLabel(); jblCNPJ = new javax.swing.JLabel(); jfCNPJ = new javax.swing.JFormattedTextField(); jblCampBairro = new javax.swing.JLabel(); jblCampCidade = new javax.swing.JLabel(); jblCampUF = new javax.swing.JLabel(); jblCampCEP = new javax.swing.JLabel(); jblCampEndereco = new javax.swing.JLabel(); jblCampTel = new javax.swing.JLabel(); jblCampCNPJ = new javax.swing.JLabel(); jblCampNome = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); bntNovo = new javax.swing.JButton(); bntEditar = new javax.swing.JButton(); jtPesquisar1 = new javax.swing.JTextField(); bntPesquisar = new javax.swing.JButton(); bntRemover = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jPanel2.setBackground(new java.awt.Color(255, 153, 51)); jPanel1.setBackground(new java.awt.Color(204, 204, 204)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); try { jfValor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##,##"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jtNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jtNomeActionPerformed(evt); } }); jblValor.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblValor.setText("*Valor:"); jblFornecedor.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblFornecedor.setText("*Fornecedor:"); jblID.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblID.setText("ID:"); jblNome.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblNome.setText("*Nome:"); jblQuant.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblQuant.setText("*Quant. Estoque:"); btnSalvarProd.setBackground(new java.awt.Color(153, 153, 153)); btnSalvarProd.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnSalvarProd.setForeground(new java.awt.Color(255, 255, 255)); btnSalvarProd.setText("Salvar"); btnSalvarProd.setBorderPainted(false); btnSalvarProd.setFocusPainted(false); btnSalvarProd.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { btnSalvarProdMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { btnSalvarProdMouseExited(evt); } }); btnSalvarProd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalvarProdActionPerformed(evt); } }); btnCancelar.setBackground(new java.awt.Color(153, 153, 153)); btnCancelar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnCancelar.setForeground(new java.awt.Color(255, 255, 255)); btnCancelar.setText("Cancelar"); btnCancelar.setBorderPainted(false); btnCancelar.setFocusPainted(false); btnCancelar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { btnCancelarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { btnCancelarMouseExited(evt); } }); jcFornecedor.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Selecione" })); jcFornecedor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcFornecedorActionPerformed(evt); } }); jPanel3.setBackground(new java.awt.Color(204, 204, 204)); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "Nome", "Valor", "Quantidade" } )); jsTabela.setViewportView(jTable1); btnRemover.setBackground(new java.awt.Color(153, 153, 153)); btnRemover.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnRemover.setForeground(new java.awt.Color(255, 255, 255)); btnRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/remove.png"))); // NOI18N btnRemover.setText("Remover"); btnRemover.setBorderPainted(false); btnRemover.setFocusPainted(false); btnRemover.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { btnRemoverMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { btnRemoverMouseExited(evt); } }); btnRemover.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoverActionPerformed(evt); } }); jtPesquisar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jtPesquisarActionPerformed(evt); } }); btnEditar.setBackground(new java.awt.Color(153, 153, 153)); btnEditar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnEditar.setForeground(new java.awt.Color(255, 255, 255)); btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/editt.png"))); // NOI18N btnEditar.setText("Editar"); btnEditar.setBorderPainted(false); btnEditar.setFocusPainted(false); btnEditar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { btnEditarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { btnEditarMouseExited(evt); } }); btnEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditarActionPerformed(evt); } }); btnNovo.setBackground(new java.awt.Color(153, 153, 153)); btnNovo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnNovo.setForeground(new java.awt.Color(255, 255, 255)); btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/add.png"))); // NOI18N btnNovo.setText("Novo"); btnNovo.setBorderPainted(false); btnNovo.setFocusPainted(false); btnNovo.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { btnNovoMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { btnNovoMouseExited(evt); } }); btnNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNovoActionPerformed(evt); } }); btnPesquisar.setBackground(new java.awt.Color(153, 153, 153)); btnPesquisar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnPesquisar.setForeground(new java.awt.Color(255, 255, 255)); btnPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/pesquisar.png"))); // NOI18N btnPesquisar.setText("Pesquisar"); btnPesquisar.setBorderPainted(false); btnPesquisar.setFocusPainted(false); btnPesquisar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { btnPesquisarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { btnPesquisarMouseExited(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jsTabela, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtPesquisar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRemover, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) .addComponent(btnPesquisar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jsTabela, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnRemover, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jblFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 890, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jblIDP, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jblID, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jblNome) .addGap(0, 414, Short.MAX_VALUE)) .addComponent(jtNome)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jblValor) .addComponent(jfValor, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jblQuant) .addComponent(jtQuanti, javax.swing.GroupLayout.PREFERRED_SIZE, 396, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jcFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnSalvarProd, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jblID) .addComponent(jblNome) .addComponent(jblValor) .addComponent(jblQuant, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jfValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtQuanti, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jblIDP, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jblFornecedor) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSalvarProd, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jcFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 98, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jTabbedPane1.addTab("Cadastro de Produto", jPanel1); jPanel5.setBackground(new java.awt.Color(204, 204, 204)); jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jblBairro.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblBairro.setText("*Bairro:"); jblCidade.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblCidade.setText("*Cidade:"); jblUF.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblUF.setText("*UF:"); jblEndereco.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblEndereco.setText("*Endereço:"); try { jfCEP.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####-###"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jblNomeForn.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblNomeForn.setText("*Nome:"); try { jfTelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####-####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jblTel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblTel.setText("*Telefone:"); bntSalvar.setBackground(new java.awt.Color(153, 153, 153)); bntSalvar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bntSalvar.setForeground(new java.awt.Color(255, 255, 255)); bntSalvar.setText("Salvar"); bntSalvar.setBorderPainted(false); bntSalvar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); bntSalvar.setFocusPainted(false); bntSalvar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { bntSalvarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { bntSalvarMouseExited(evt); } }); bntSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bntSalvarActionPerformed(evt); } }); jblCEP.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblCEP.setText("*CEP:"); jblID1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblID1.setText("ID:"); bntCancelar.setBackground(new java.awt.Color(153, 153, 153)); bntCancelar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bntCancelar.setForeground(new java.awt.Color(255, 255, 255)); bntCancelar.setText("Cancelar"); bntCancelar.setBorderPainted(false); bntCancelar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); bntCancelar.setFocusPainted(false); bntCancelar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { bntCancelarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { bntCancelarMouseExited(evt); } }); bntCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bntCancelarActionPerformed(evt); } }); jblCNPJ.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jblCNPJ.setText("*CNPJ"); try { jfCNPJ.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.###.###/####-##"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jblCampBairro.setForeground(new java.awt.Color(255, 0, 0)); jblCampBairro.setText("*Campo Obrigatório"); jblCampCidade.setForeground(new java.awt.Color(255, 0, 0)); jblCampCidade.setText("*Campo Obrigatório"); jblCampUF.setForeground(new java.awt.Color(255, 0, 0)); jblCampUF.setText("*Campo Obrigatório"); jblCampCEP.setForeground(new java.awt.Color(255, 0, 0)); jblCampCEP.setText("*Campo Obrigatório"); jblCampEndereco.setForeground(new java.awt.Color(255, 0, 0)); jblCampEndereco.setText("*Campo Obrigatório"); jblCampTel.setForeground(new java.awt.Color(255, 0, 0)); jblCampTel.setText("*Campo Obrigatório"); jblCampCNPJ.setForeground(new java.awt.Color(255, 0, 0)); jblCampCNPJ.setText("*Campo Obrigatório"); jblCampNome.setForeground(new java.awt.Color(255, 0, 0)); jblCampNome.setText("*Campo Obrigatório"); jPanel6.setBackground(new java.awt.Color(204, 204, 204)); bntNovo.setBackground(new java.awt.Color(153, 153, 153)); bntNovo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bntNovo.setForeground(new java.awt.Color(255, 255, 255)); bntNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/add.png"))); // NOI18N bntNovo.setText("Novo"); bntNovo.setBorderPainted(false); bntNovo.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); bntNovo.setFocusPainted(false); bntNovo.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { bntNovoMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { bntNovoMouseExited(evt); } }); bntNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bntNovoActionPerformed(evt); } }); bntEditar.setBackground(new java.awt.Color(153, 153, 153)); bntEditar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bntEditar.setForeground(new java.awt.Color(255, 255, 255)); bntEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/editt.png"))); // NOI18N bntEditar.setText("Editar"); bntEditar.setBorderPainted(false); bntEditar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); bntEditar.setFocusPainted(false); bntEditar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { bntEditarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { bntEditarMouseExited(evt); } }); bntEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bntEditarActionPerformed(evt); } }); bntPesquisar.setBackground(new java.awt.Color(153, 153, 153)); bntPesquisar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bntPesquisar.setForeground(new java.awt.Color(255, 255, 255)); bntPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/pesquisar.png"))); // NOI18N bntPesquisar.setText("Pesquisar"); bntPesquisar.setBorderPainted(false); bntPesquisar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); bntPesquisar.setFocusPainted(false); bntPesquisar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { bntPesquisarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { bntPesquisarMouseExited(evt); } }); bntRemover.setBackground(new java.awt.Color(153, 153, 153)); bntRemover.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N bntRemover.setForeground(new java.awt.Color(255, 255, 255)); bntRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/remove.png"))); // NOI18N bntRemover.setText("Remover"); bntRemover.setBorderPainted(false); bntRemover.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); bntRemover.setFocusPainted(false); bntRemover.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { bntRemoverMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { bntRemoverMouseExited(evt); } }); bntRemover.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bntRemoverActionPerformed(evt); } }); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); jScrollPane1.setViewportView(jTable2); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtPesquisar1) .addComponent(jScrollPane1)) .addGap(18, 18, 18) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(bntRemover, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bntEditar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bntNovo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bntPesquisar)) .addContainerGap()) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addGap(11, 11, 11) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bntPesquisar) .addComponent(jtPesquisar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addGap(43, 43, 43) .addComponent(bntNovo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bntEditar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bntRemover)) .addGroup(jPanel6Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jblID1) .addComponent(jblIDF, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jblNomeForn) .addComponent(jtNomeForn, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jblCampNome))) .addComponent(jblBairro)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jblCNPJ) .addGap(71, 71, 71) .addComponent(jblTel)) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jfCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jblCidade)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jfTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(8, 8, 8)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jblCampCNPJ) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jblCampTel))) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(jblEndereco) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel5Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jblCampEndereco) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jtEndereco))))) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 426, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jblCampBairro)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jblCampCidade)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jblCampUF) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jblCampCEP)) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(33, 33, 33) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtUF, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jblUF)) .addGap(22, 22, 22) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jblCEP) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jfCEP)))))) .addContainerGap()) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bntSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(bntCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(33, 33, 33)) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jblID1) .addComponent(jblNomeForn) .addComponent(jblCNPJ) .addComponent(jblEndereco) .addComponent(jblTel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jblIDF, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtNomeForn, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jfCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jfTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jblCampCNPJ) .addComponent(jblCampNome)) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jblCampTel) .addComponent(jblCampEndereco))) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jblCidade) .addComponent(jblUF) .addComponent(jblCEP))) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jblBairro))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtUF, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jfCEP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel5Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jblCampCidade) .addComponent(jblCampBairro)) .addGap(57, 57, 57)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jblCampUF) .addComponent(jblCampCEP)) .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bntSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bntCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jTabbedPane1.addTab("Cadastro de Fornecedor", jPanel5); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jTabbedPane1) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 26, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void bntRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntRemoverActionPerformed // TODO add your handling code here: if(jTable1.getRowCount()>0) { //Resgato o número da linha pelo JTable int numeroLinha = jTable1.getSelectedRow(); //Resgato o ID (oculto) do cliente pelo JTableModel int IDfornecedor = Integer.parseInt(jTable1.getModel().getValueAt(numeroLinha, 0).toString()); //Realizo a exclusão do cliente pelo ID if(FornecedorController.excluirFornecedor(IDfornecedor)) { //Recarrego a tabela, consultando diretamente do banco de dados this.CarregarTabela(); JOptionPane.showMessageDialog(this,"Forncedor excluído da base de dados"); }else{ JOptionPane.showMessageDialog(this,"Falha ao excluir o fornecedor!"); } } else { JOptionPane.showMessageDialog(this,"Não há fornecedor para excluir!"); } this.DesabilitarFormulario(); this.LimparFormulario(); }//GEN-LAST:event_bntRemoverActionPerformed private void bntRemoverMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntRemoverMouseExited // TODO add your handling code here: bntRemover.setBackground(new Color(153,153,153)); bntRemover.setForeground(Color.WHITE); }//GEN-LAST:event_bntRemoverMouseExited private void bntRemoverMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntRemoverMouseEntered // TODO add your handling code here: bntRemover.setBackground(new Color(235,235,235)); bntRemover.setForeground(new Color(153,153,153)); }//GEN-LAST:event_bntRemoverMouseEntered private void bntPesquisarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntPesquisarMouseExited // TODO add your handling code here: bntPesquisar.setBackground(new Color(153,153,153)); bntPesquisar.setForeground(Color.WHITE); }//GEN-LAST:event_bntPesquisarMouseExited private void bntPesquisarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntPesquisarMouseEntered // TODO add your handling code here: bntPesquisar.setBackground(new Color(235,235,235)); bntPesquisar.setForeground(new Color(153,153,153)); }//GEN-LAST:event_bntPesquisarMouseEntered private void bntEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntEditarActionPerformed // TODO add your handling code here: modoTela = "Editar"; //Verifico se há linhas para poder editar if(jTable1.getRowCount()>0) { //Verifico se o usuário selecionou alguma linha (Primeira linha = 0) | Nada selecionado = -1) if(jTable1.getSelectedRow()>=0) { HabilitarFormulario(); //Variável acessória para identifcar se o formulário está em modo de edição ou alteração modoTela = "Editar"; //Atribuo os valores que estão na linha selecionada para a tabela jblIDF.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 0).toString()); jtNome.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 1).toString()); jfCNPJ.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 2).toString()); jtBairro.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 3).toString()); jfCEP.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 4).toString()); jtCidade.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 5).toString()); jtEndereco.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 6).toString()); jfTelefone.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 7).toString()); jtUF.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 8).toString()); } else { JOptionPane.showMessageDialog(this,"Selecione um cliente para editar!"); } } else { JOptionPane.showMessageDialog(this,"Não há cliente para editar!"); } }//GEN-LAST:event_bntEditarActionPerformed private void bntEditarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntEditarMouseExited // TODO add your handling code here: bntEditar.setBackground(new Color(153,153,153)); bntEditar.setForeground(Color.WHITE); }//GEN-LAST:event_bntEditarMouseExited private void bntEditarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntEditarMouseEntered // TODO add your handling code here: bntEditar.setBackground(new Color(235,235,235)); bntEditar.setForeground(new Color(153,153,153)); }//GEN-LAST:event_bntEditarMouseEntered private void bntNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntNovoActionPerformed // TODO add your handling code here: modoTela = "Criar"; HabilitarFormulario(); }//GEN-LAST:event_bntNovoActionPerformed private void bntNovoMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntNovoMouseExited // TODO add your handling code here: bntNovo.setBackground(new Color(153,153,153)); bntNovo.setForeground(Color.WHITE); }//GEN-LAST:event_bntNovoMouseExited private void bntNovoMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntNovoMouseEntered // TODO add your handling code here: bntNovo.setBackground(new Color(235,235,235)); bntNovo.setForeground(new Color(153,153,153)); }//GEN-LAST:event_bntNovoMouseEntered private void bntCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntCancelarActionPerformed // TODO add your handling code here: this.DesabilitarFormulario(); this.LimparFormulario(); }//GEN-LAST:event_bntCancelarActionPerformed private void bntCancelarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntCancelarMouseExited // TODO add your handling code here: bntCancelar.setBackground(new Color(153,153,153)); bntCancelar.setForeground(Color.WHITE); }//GEN-LAST:event_bntCancelarMouseExited private void bntCancelarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntCancelarMouseEntered // TODO add your handling code here: bntCancelar.setBackground(new Color(235,235,235)); bntCancelar.setForeground(new Color(153,153,153)); }//GEN-LAST:event_bntCancelarMouseEntered private void bntSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntSalvarActionPerformed // TODO add your handling code here: if (jtNomeForn.getText().length() > 0) { jblCampNome.setVisible(false); } else { jblCampNome.setVisible(true); } if (jfCNPJ.getText().length() > 4) { jblCampCNPJ.setVisible(false); } else { jblCNPJ.setVisible(true); } if (jfTelefone.getText().length() > 0) { jblCampTel.setVisible(false); } else { jblCampTel.setVisible(true); }if (jtEndereco.getText().length() > 0) { jblCampEndereco.setVisible(false); } else { jblCampEndereco.setVisible(true); }if (jtBairro.getText().length() > 0) { jblCampBairro.setVisible(false); } else { jblCampBairro.setVisible(true); }if (jtCidade.getText().length() > 0) { jblCampCidade.setVisible(false); } else { jblCampCidade.setVisible(true); }if (jtUF.getText().length() > 0) { jblCampUF.setVisible(false); } else { jblCampUF.setVisible(true); }if (jfCEP.getText().length() > 0) { jblCampCEP.setVisible(false); } else { jblCampCEP.setVisible(true); } if ((jtNomeForn.getText().length()>0) &&(jfCNPJ.getText().length()> 0) && (jfTelefone.getText().length() > 0) && (jfCEP.getText().length() > 0 && jtBairro.getText().length() > 0) && (jtCidade.getText().length() > 0) && (jtEndereco.getText().length() > 0 && (jtUF.getText().length() > 0))) { JOptionPane.showMessageDialog(null, "Dados Validados aqui deve ser efetuada a operação!!"); } else { JOptionPane.showMessageDialog(null, "Confira os campos Obrigatórios!!"); } if(modoTela.equals("Criar")) { //Passo ao controller a entrada do usuário e peço para salvar no banco de dados if(FornecedorController.salvarFornecedor(jtNomeForn.getText(),jfCNPJ.getText(), jtBairro.getText(),jfCEP.getText(), jtCidade.getText(), jtEndereco.getText(), jfTelefone.getText(), jtUF.getText())) { //Recarrego a tabela com os dados resgatados do banco de dados this.CarregarTabela(); JOptionPane.showMessageDialog(null,"Fornecedor cadastrado com sucesso!"); LimparFormulario(); }else{ JOptionPane.showMessageDialog(null,"Falha ao cadastrar Forncedor!"); } }else { //Passo ao controller a entrada do usuário e peço para atualizar o banco de dados if(FornecedorController.atualizarFornecedor(Integer.parseInt(jblIDF.getText()), jtNomeForn.getText(),jfCNPJ.getText(), jtBairro.getText(),jfCEP.getText(), jtCidade.getText(), jtEndereco.getText(), jfTelefone.getText(), jtUF.getText())) { //Recarrego a tabela com os dados resgatados do banco de dados this.CarregarTabela(); JOptionPane.showMessageDialog(this,"Fornecedor atualizado com sucesso!"); }else{ JOptionPane.showMessageDialog(this,"Falha ao atualizar dados do Fornecedor!"); } } LimparFormulario(); DesabilitarFormulario(); }//GEN-LAST:event_bntSalvarActionPerformed private void bntSalvarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntSalvarMouseExited // TODO add your handling code here: bntSalvar.setBackground(new Color(153,153,153)); bntSalvar.setForeground(Color.WHITE); }//GEN-LAST:event_bntSalvarMouseExited private void bntSalvarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntSalvarMouseEntered // TODO add your handling code here: bntSalvar.setBackground(new Color(235,235,235)); bntSalvar.setForeground(new Color(153,153,153)); }//GEN-LAST:event_bntSalvarMouseEntered private void btnPesquisarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnPesquisarMouseExited // TODO add your handling code here: btnPesquisar.setBackground(new Color(153,153,153)); btnPesquisar.setForeground(Color.WHITE); }//GEN-LAST:event_btnPesquisarMouseExited private void btnPesquisarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnPesquisarMouseEntered // TODO add your handling code here: btnPesquisar.setBackground(new Color(235,235,235)); btnPesquisar.setForeground(new Color(153,153,153)); }//GEN-LAST:event_btnPesquisarMouseEntered private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed // TODO add your handling code here: modoTela = "Criar"; HabilitarFormulario(); }//GEN-LAST:event_btnNovoActionPerformed private void btnNovoMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNovoMouseExited // TODO add your handling code here: btnNovo.setBackground(new Color(153,153,153)); btnNovo.setForeground(Color.WHITE); }//GEN-LAST:event_btnNovoMouseExited private void btnNovoMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNovoMouseEntered // TODO add your handling code here: btnNovo.setBackground(new Color(235,235,235)); btnNovo.setForeground(new Color(153,153,153)); }//GEN-LAST:event_btnNovoMouseEntered private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed // TODO add your handling code here: modoTela = "Editar"; //Verifico se há linhas para poder editar if(jTable1.getRowCount()>0) { //Verifico se o usuário selecionou alguma linha (Primeira linha = 0) | Nada selecionado = -1) if(jTable1.getSelectedRow()>=0) { HabilitarFormulario(); //Variável acessória para identifcar se o formulário está em modo de edição ou alteração modoTela = "Editar"; //Atribuo os valores que estão na linha selecionada para a tabela jblIDP.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 0).toString()); jtNome.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 1).toString()); jfValor.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 2).toString()); jtQuanti.setText(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 3).toString()); jcFornecedor.setName(jTable1.getModel().getValueAt(jTable1.getSelectedRow(), 4).toString()); } else { JOptionPane.showMessageDialog(this,"Selecione um cliente para editar!"); } } else { JOptionPane.showMessageDialog(this,"Não há cliente para editar!"); } }//GEN-LAST:event_btnEditarActionPerformed private void btnEditarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEditarMouseExited // TODO add your handling code here: btnEditar.setBackground(new Color(153,153,153)); btnEditar.setForeground(Color.WHITE); }//GEN-LAST:event_btnEditarMouseExited private void btnEditarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEditarMouseEntered // TODO add your handling code here: btnEditar.setBackground(new Color(235,235,235)); btnEditar.setForeground(new Color(153,153,153)); }//GEN-LAST:event_btnEditarMouseEntered private void jtPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtPesquisarActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jtPesquisarActionPerformed private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed // TODO add your handling code here: if(jTable1.getRowCount()>0) { //Resgato o número da linha pelo JTable int numeroLinha = jTable1.getSelectedRow(); //Resgato o ID (oculto) do cliente pelo JTableModel int IDproduto = Integer.parseInt(jTable1.getModel().getValueAt(numeroLinha, 0).toString()); //Realizo a exclusão do cliente pelo ID if(ProdutoController.excluirProduto(IDproduto)) { //Recarrego a tabela, consultando diretamente do banco de dados this.CarregarTabela(); JOptionPane.showMessageDialog(this,"Produto excluído da base de dados"); }else{ JOptionPane.showMessageDialog(this,"Falha ao excluir o produto!"); } } else { JOptionPane.showMessageDialog(this,"Não há produto para excluir!"); } this.DesabilitarFormulario(); this.LimparFormulario(); }//GEN-LAST:event_btnRemoverActionPerformed private void btnRemoverMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnRemoverMouseExited // TODO add your handling code here: btnRemover.setBackground(new Color(153,153,153)); btnRemover.setForeground(Color.WHITE); }//GEN-LAST:event_btnRemoverMouseExited private void btnRemoverMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnRemoverMouseEntered // TODO add your handling code here: btnRemover.setBackground(new Color(235,235,235)); btnRemover.setForeground(new Color(153,153,153)); }//GEN-LAST:event_btnRemoverMouseEntered private void btnCancelarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelarMouseExited // TODO add your handling code here: btnCancelar.setBackground(new Color(153,153,153)); btnCancelar.setForeground(Color.WHITE); }//GEN-LAST:event_btnCancelarMouseExited private void btnCancelarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelarMouseEntered // TODO add your handling code here: btnCancelar.setBackground(new Color(235,235,235)); btnCancelar.setForeground(new Color(153,153,153)); }//GEN-LAST:event_btnCancelarMouseEntered private void btnSalvarProdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarProdActionPerformed // TODO add your handling code here: if(modoTela.equals("Criar")) { //Passo ao controller a entrada do usuário e peço para salvar no banco de dados if(ProdutoController.salvarProduto(jtNome.getText(),jfValor.getText(), jtQuanti.getText(), jcFornecedor.getName())) { //Recarrego a tabela com os dados resgatados do banco de dados this.CarregarTabela(); JOptionPane.showMessageDialog(null,"Produto cadastrado com sucesso!"); LimparFormulario(); }else{ JOptionPane.showMessageDialog(null,"Falha ao cadastrar Produto!"); } }else { //Passo ao controller a entrada do usuário e peço para atualizar o banco de dados if(ProdutoController.atualizarProduto(Integer.parseInt(jblIDP.getText()), jtNome.getText(),jfValor.getText(), jtQuanti.getText(), jcFornecedor.getName())) { //Recarrego a tabela com os dados resgatados do banco de dados this.CarregarTabela(); JOptionPane.showMessageDialog(this,"Produto atualizado com sucesso!"); }else{ JOptionPane.showMessageDialog(this,"Falha ao atualizar dados do Produto!"); } } LimparFormulario(); DesabilitarFormulario(); }//GEN-LAST:event_btnSalvarProdActionPerformed private void btnSalvarProdMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSalvarProdMouseExited // TODO add your handling code here: btnSalvarProd.setBackground(new Color(153,153,153)); btnSalvarProd.setForeground(Color.WHITE); }//GEN-LAST:event_btnSalvarProdMouseExited private void btnSalvarProdMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSalvarProdMouseEntered // TODO add your handling code here: btnSalvarProd.setBackground(new Color(235,235,235)); btnSalvarProd.setForeground(new Color(153,153,153)); }//GEN-LAST:event_btnSalvarProdMouseEntered private void jtNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtNomeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jtNomeActionPerformed private void jcFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcFornecedorActionPerformed // TODO add your handling code here: jtNomeForn.getText(); }//GEN-LAST:event_jcFornecedorActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (javax.swing.UnsupportedLookAndFeelException ex) { } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaCadProd().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bntCancelar; private javax.swing.JButton bntEditar; private javax.swing.JButton bntNovo; private javax.swing.JButton bntPesquisar; private javax.swing.JButton bntRemover; private javax.swing.JButton bntSalvar; private javax.swing.JButton btnCancelar; private javax.swing.JButton btnEditar; private javax.swing.JButton btnNovo; private javax.swing.JButton btnPesquisar; private javax.swing.JButton btnRemover; private javax.swing.JButton btnSalvarProd; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTable jTable1; private javax.swing.JTable jTable2; private javax.swing.JLabel jblBairro; private javax.swing.JLabel jblCEP; private javax.swing.JLabel jblCNPJ; private javax.swing.JLabel jblCampBairro; private javax.swing.JLabel jblCampCEP; private javax.swing.JLabel jblCampCNPJ; private javax.swing.JLabel jblCampCidade; private javax.swing.JLabel jblCampEndereco; private javax.swing.JLabel jblCampNome; private javax.swing.JLabel jblCampTel; private javax.swing.JLabel jblCampUF; private javax.swing.JLabel jblCidade; private javax.swing.JLabel jblEndereco; private javax.swing.JLabel jblFornecedor; private javax.swing.JLabel jblID; private javax.swing.JLabel jblID1; private javax.swing.JLabel jblIDF; private javax.swing.JLabel jblIDP; private javax.swing.JLabel jblNome; private javax.swing.JLabel jblNomeForn; private javax.swing.JLabel jblQuant; private javax.swing.JLabel jblTel; private javax.swing.JLabel jblUF; private javax.swing.JLabel jblValor; private javax.swing.JComboBox<String> jcFornecedor; private javax.swing.JFormattedTextField jfCEP; private javax.swing.JFormattedTextField jfCNPJ; private javax.swing.JFormattedTextField jfTelefone; private javax.swing.JFormattedTextField jfValor; private javax.swing.JScrollPane jsTabela; private javax.swing.JTextField jtBairro; private javax.swing.JTextField jtCidade; private javax.swing.JTextField jtEndereco; private javax.swing.JTextField jtNome; private javax.swing.JTextField jtNomeForn; private javax.swing.JTextField jtPesquisar; private javax.swing.JTextField jtPesquisar1; private javax.swing.JTextField jtQuanti; private javax.swing.JTextField jtUF; // End of variables declaration//GEN-END:variables }
true
d7d750261eab71293cb4499074cff2c8b53cd4be
Java
KevynSM/BankSystem
/src/D3/models/Documents.java
UTF-8
996
3.15625
3
[]
no_license
package D3.models; /** Represents a Document of a Client in a Bank. * @author Diurno - Grupo 3. * @author Daniel Almeida. * @author João Conduto. * @author Kevyn Marins. * @author Tiago Leitão. */ public class Documents { private char typeDocument; private String numberDocument; /** Creates a document object with the given parameters. * * @param typeDocument A letter that represents the type of the document * @param numberDocument The number of the document. */ Documents(char typeDocument, String numberDocument) { this.typeDocument = typeDocument; this.numberDocument = numberDocument; } /** Returns the type of the document. * * @return the type of the document. */ public char getTypeDocument() { return this.typeDocument; } /** Returns the number of the document. * * @return the number of the document. */ public String getNumberDocument() { return this.numberDocument; } }
true
2fa34f561cb729cc6ed756768d0a2562ac9b6450
Java
GoogleCloudPlatform/gcp-token-broker
/code/client/client-lib/src/main/java/com/google/cloud/broker/client/utils/OAuthUtils.java
UTF-8
1,961
2.171875
2
[ "Apache-2.0" ]
permissive
// Copyright 2020 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.cloud.broker.client.utils; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.IdTokenCredentials; import com.google.auth.oauth2.IdTokenProvider; import java.io.IOException; public class OAuthUtils { public static GoogleCredentials getApplicationDefaultCredentials() { GoogleCredentials credentials; try { credentials = GoogleCredentials.getApplicationDefault(); if (!(credentials instanceof IdTokenProvider)) { throw new IllegalArgumentException("Credentials are not an instance of IdTokenProvider."); } return credentials; } catch (IOException e) { throw new RuntimeException(e); } } public static com.google.auth.oauth2.AccessToken getApplicationDefaultIdToken(String audience) { try { GoogleCredentials credentials = getApplicationDefaultCredentials(); if (!(credentials instanceof IdTokenProvider)) { throw new IllegalArgumentException("Credentials are not an instance of IdTokenProvider."); } IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder() .setIdTokenProvider((IdTokenProvider) credentials) .setTargetAudience(audience) .build(); return tokenCredential.refreshAccessToken(); } catch (IOException e) { throw new RuntimeException(e); } } }
true
e986ac14847e64f15afaa6209582bd0e86835de9
Java
motxx/AOJ
/repository/0001.java
UTF-8
426
3.03125
3
[]
no_license
import java.util.*; class aoj0001 { public void solve() { int[] list = new int[10]; Scanner sc = new Scanner(System.in); for(int i=0; i<10; i++) list[i] = sc.nextInt(); Arrays.sort(list); for(int i=0; i<3; i++) System.out.println(list[9-i]); } } class Main { public static void main(String...args) { new aoj0001().solve(); } }
true
d01cebb01a726c25208b22ad2b2552698eb8d7b4
Java
CTreffOS/codingchaos-2016_1_beginner
/aufgabe02/mwild/Rueckgeld.java
UTF-8
613
3.078125
3
[]
no_license
import AlgoTools.IO; public class Rueckgeld { public static void main(String[] argv) { double[] geld = {500.0, 200.0, 100.0, 50.0, 20.0, 10.0, 5.0, 2.0, 1.0, 0.5, 0.2, 0.1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01}; double[] amounts = IO.readDoubles(); int[] rueckgabe = new int[geld.length]; for(int i = 0; i < amounts.length; i++) { for(int j = 0; j < geld.length; j++) { while(amounts[i] >= geld[j]) { rueckgabe[j]++; amounts[i] -= geld[j]; } } for(int j = 0; j < geld.length; j++) { IO.print(rueckgabe[geld.length - 1 - j]); IO.print(" "); } IO.println(); } } }
true
1924edac2b9c0bc047773ce3d1f91daf1b656684
Java
bryan-brancotte/projetgl-2008
/iGo/src/ihm/smartPhone/statePanels/SplashScreenPanel.java
UTF-8
5,366
2.765625
3
[]
no_license
package ihm.smartPhone.statePanels; import ihm.smartPhone.component.LowerBar; import ihm.smartPhone.component.UpperBar; import ihm.smartPhone.libPT.PanelDoubleBufferingSoftwear; import ihm.smartPhone.tools.ImageLoader; import ihm.smartPhone.tools.SizeAdapteur.FontSizeKind; import java.awt.Graphics; import java.awt.Image; public class SplashScreenPanel extends PanelState { private static final long serialVersionUID = 1L; protected int maxStepInSplashScreen = -1; protected int stepInSplashScreen = 0; protected Image logo = null; /** * L'unique constructeur de cette classe. On a besoin l'ihm qui l'heberge afin d'afficher les bonnes couleurs via le * getSkin() et les bonnes tailles via le getSizeAdapteur(). * * @param ihm * l'ihm réceptrice * @param upperBar * la barre supérieur * @param lowerBar * la barre inférieur */ public SplashScreenPanel(IhmReceivingPanelState ihm, UpperBar upperBar, LowerBar lowerBar) { super(ihm, upperBar, lowerBar); } /** * Surdéfinition de la fonction de redessinement de l'objet. */ public void paint(Graphics g) { // System.out.println("SplashScreenPanel.paint(...)"); // Si le buffer n'existe pas, ou s'il n'est pas adapté à la taille du panel, on ne redéfinit if (currentQuality != PanelDoubleBufferingSoftwear.getQuality()) { currentQuality=PanelDoubleBufferingSoftwear.getQuality(); buffer = null; } if ((buffer == null) || (image.getWidth(null) != getWidth()) || (image.getHeight(null) != getHeight())) { image = createImage(getWidth(), getHeight()); buffer = image.getGraphics(); graphicsTunning(buffer); // on charge aussi le logo en fonction de la taille du panel. logo = ImageLoader.getImageIcone(getClass().getResource("/images/iGo.256.png"), (int) (this.getWidth() * 0.8), (int) (this.getHeight() * 0.8)).getImage(); buffer.setColor(father.getSkin().getColorOutside()); buffer.drawImage(logo, this.getWidth() - logo.getWidth(null) >> 1, (this.getHeight() - logo.getHeight(null)) >> 1 - father.getSizeAdapteur().getSizeSmallFont(), null); } // si le logo n'est pas définit on le charge en mémoire. On n'a besoin de le charger que si la taille // destination à changé. if (logo == null) { logo = ImageLoader.getImageIcone(getClass().getResource("/images/iGo.png"), (int) (this.getWidth() * 0.8), (int) (this.getHeight() * 0.8)).getImage(); } // on l'efface buffer.setColor(father.getSkin().getColorInside());buffer.fillRect(0, 0, getWidth(), getHeight()); buffer.drawImage(logo, this.getWidth() - logo.getWidth(null) >> 1, (this.getHeight() - logo.getHeight(null) >> 1) - father.getSizeAdapteur().getSizeSmallFont(), null); // On affiche ensuite la barre de progression if (maxStepInSplashScreen >= 0) { buffer.drawRoundRect((this.getWidth() - logo.getWidth(null) >>1) - 2, (this.getHeight() + logo.getHeight(null) >>1) - 2, 4 + logo.getWidth(null), 4 + father.getSizeAdapteur() .getSizeSmallFont(), 6, 6); int progression; if (stepInSplashScreen < maxStepInSplashScreen) progression = (int) (logo.getWidth(null) * ((float) stepInSplashScreen / maxStepInSplashScreen)); else progression = logo.getWidth(null); buffer.fillPolygon(new int[] { this.getWidth() - logo.getWidth(null) >>1, (this.getWidth() - logo.getWidth(null) >>1) + progression+1, (this.getWidth() - logo.getWidth(null) >>1) + progression+1, this.getWidth() - logo.getWidth(null) >>1}, new int[] { this.getHeight() + logo.getHeight(null) >>1, this.getHeight() + logo.getHeight(null) >>1, (this.getHeight() + logo.getHeight(null) >>1) + father.getSizeAdapteur().getSizeSmallFont() + 1, (this.getHeight() + logo.getHeight(null) >>1) + father.getSizeAdapteur().getSizeSmallFont() + 1 }, 4); } g.drawImage(image, 0, 0, this); } /** * getteur du maximume de pas dans l'écran de chargement/ * * @return le nombre maximume de pas. */ public int getMaxStepInSplashScreen() { return maxStepInSplashScreen; } /** * setteur du maximume de pas dans l'écran de chargement. Un valeur négative aura pour effet de masquer la barre de * chargement * * @param maxStepInSplashScreen * le nombre maximume de pas. */ public void setMaxStepInSplashScreen(int maxStepInSplashScreen) { this.maxStepInSplashScreen = maxStepInSplashScreen; this.repaint(); } /** * * @return */ public int getStepInSplashScreen() { return stepInSplashScreen; } /** * * @param stepInSplashScreen */ public void setStepInSplashScreen(int stepInSplashScreen) { this.stepInSplashScreen = stepInSplashScreen; this.repaint(); } /** * */ public void incrementStepInSplashScreen() { this.stepInSplashScreen++; if (stepInSplashScreen > maxStepInSplashScreen) return; this.repaint(); } @Override public void giveControle() { upperBar.clearMessage(); upperBar.setMainTitle(father.lg("SplashScreenUpperTitle"), FontSizeKind.INTERMEDIATE); upperBar.repaint(); lowerBar.clearMessage(); lowerBar.setRightTitle(father.lg("iGoVersion")); lowerBar.repaint(); } }
true
6b01115e510d893c168f830f96f4ddb4f089f930
Java
ece1778-2021/Dynasway_Concussion
/app/src/main/java/com/example/dynaswayconcussion/ui/tests/StaticTestSelectionFragment.java
UTF-8
2,847
1.96875
2
[]
no_license
package com.example.dynaswayconcussion.ui.tests; import android.content.Intent; import android.media.AudioManager; import android.media.ToneGenerator; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.dynaswayconcussion.R; public class StaticTestSelectionFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_static_test_selection, container, false); view.findViewById(R.id.cardViewStaticTestRegular).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity().getApplicationContext(), TestInstructionsActivity.class); intent.putExtra("test_type", R.string.static_test_regular_constant); intent.putExtra("test_type_name", R.string.static_test_regular); startActivity(intent); } }); view.findViewById(R.id.cardViewStaticTestTandem).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity().getApplicationContext(), TestInstructionsActivity.class); intent.putExtra("test_type", R.string.static_test_tandem_constant); intent.putExtra("test_type_name", R.string.static_test_tandem); startActivity(intent); } }); view.findViewById(R.id.cardViewStaticTestRegularDual).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity().getApplicationContext(), TestInstructionsActivity.class); intent.putExtra("test_type", R.string.static_test_regular_dual_task_constant); intent.putExtra("test_type_name", R.string.static_test_regular_dual_task); startActivity(intent); } }); view.findViewById(R.id.cardViewStaticTestTandemDual).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity().getApplicationContext(), TestInstructionsActivity.class); intent.putExtra("test_type", R.string.static_test_tandem_dual_task_constant); intent.putExtra("test_type_name", R.string.static_test_tandem_dual_task); startActivity(intent); } }); return view; } }
true
806cc0480527c94305e39d4a287221a5914b7aca
Java
uttaransarkar/Spring-Concepts
/hibernate-one-to-many-demo/src/com/uttaran/hibernate/demo/EagerLazyDemo.java
UTF-8
1,864
3.140625
3
[]
no_license
package com.uttaran.hibernate.demo; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.uttaran.hibernate.demo.entity.Course; import com.uttaran.hibernate.demo.entity.Instructor; import com.uttaran.hibernate.demo.entity.InstructorDetail; import com.uttaran.hibernate.demo.entity.Student; public class EagerLazyDemo { public static void main(String[] args) { // create session factory for the two classes SessionFactory factory = new Configuration().configure("hibernate.cfg.xml") .addAnnotatedClass(Instructor.class).addAnnotatedClass(InstructorDetail.class) .addAnnotatedClass(Course.class).buildSessionFactory(); // create session Session session = factory.getCurrentSession(); try { //begin transaction session.beginTransaction(); //getting instructor from DB int insId = 1; Instructor instructor = session.get(Instructor.class, insId); System.out.println("uttaran: Instructor details: " + instructor); //retrieving data List<Course> insCourses = instructor.getCourses(); System.out.println("uttaran: The courses are: " + insCourses); //committing transaction session.getTransaction().commit(); //closing the session session.close(); //retrieving the courses for this instructor, this would now usually throw an error //because lazy loading requires the session to be open at all times // List<Course> insCourses = instructor.getCourses(); // System.out.println("uttaran: The courses are: " + insCourses); //solution 1: call getter method while session is open System.out.println("uttaran: The courses are: " + insCourses); //data loaded while session is open so works } finally { session.close(); factory.close(); } } }
true
58409e5bd04446efd76b6b37933ec956c3a6d5cc
Java
muhd7rosli/desmoj
/src/desmoj/core/simulator/ModelParameterManager.java
UTF-8
3,331
2.796875
3
[ "Apache-2.0" ]
permissive
package desmoj.core.simulator; import java.util.Collection; /** * Interface to restrict the functionalities of a parameter-manager * to manage model-parameters. This Interface should be used as return- * type of the Model's methods which return the parameter- * manager. * * @author Tim Janz * * 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. */ public interface ModelParameterManager { /** * Method to declare a experiment-parameter. The experiment-parameter's * declarations are part of the simulation-model. The experiment- * parameter's assignments are in contrast part of an experiment. * * @param type * the experiment-parameter's type * @param name * the experiment-parameter's name */ public void declareExperimentParameter(Class<?> type, String name); /** * Method to declare a experiment-parameter. The experiment-parameter's * declarations are part of the simulation-model. The experiment- * parameter's assignments are in contrast part of an experiment. * The default value is used, if an experiment dosen't assign a * value to this parameter. * * @param type * the experiment-parameter's type * @param name * the experiment-parameter's name * @param defaultValue * the experiment-parameter's default value */ public void declareExperimentParameter(Class<?> type, String name, Object defaultValue); /** * Method to declare a model-parameter. * * @param type * the model-parameter's type * @param name * the model-parameter's name */ public void declareModelParameter(Class<?> type, String name); /** * Method to initialize (declare and assign) a model-parameter. * * @param type * the model-parameter's type * @param name * the model-parameter's name * @param value * the model-parameter's value */ public void initializeModelParameter(Class<?> type, String name, Object value); /** * Method to assign a value to a model-parameter declared previously. * * @param name * the model-parameter's name * @param value * the model-parameter's value */ public void assignModelParameter(String name, Object value); /** * Returns the value of an experiment- or model-parameter. Experiment- * and model-parameters are accessible through the model, to be able * to use the parameter's values at design-time. * * @param name * the parameter's name * @return * the parameter's value */ public Object getParameterValue(String name); /** * Returns all declared parameters. * * @return * the parameters */ public Collection<Parameter> getParameters(); }
true
7a9438d82287f5aaf5f509a44bafdc03b13cabd4
Java
aayushraizada16/FriendsList-app
/freindlist/src/main/java/com/example/freindlist/entity/Graph.java
UTF-8
893
2.640625
3
[]
no_license
package com.example.freindlist.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.ArrayList; @Entity public class Graph { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private Integer src; private Integer dest; public Graph() { } //Constructor public Graph(Integer src, Integer dest) { this.src = src; this.dest = dest; } //Getter and Setter public Integer getId() { return id; } public Integer getSrc() { return src; } public void setSrc(Integer src) { this.src = src; } public Integer getDest() { return dest; } public void setDest(Integer dest) { this.dest = dest; } }
true
c86b1911037908d02bb1013c7caf9060b2f26c6c
Java
17010322/KnowYourFacts
/app/src/main/java/sg/edu/rp/webservices/knowyourfacts/Frag1.java
UTF-8
1,045
2.140625
2
[]
no_license
package sg.edu.rp.webservices.knowyourfacts; import android.graphics.Color; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import java.util.Random; /** * A simple {@link Fragment} subclass. */ public class Frag1 extends Fragment { public Frag1() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Button button = (Button) getView().findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Random r = new Random(); v.setBackgroundColor(Color.rgb(r.nextInt(256),r.nextInt(256),r.nextInt(256))); } }); return inflater.inflate(R.layout.fragment_frag1, container, false); } }
true
54075ad53dc1121ffd8e8e1f5c499254e4b67f29
Java
magefree/mage
/Mage.Sets/src/mage/cards/c/CavesOfChaosAdventurer.java
UTF-8
3,548
2.515625
3
[ "MIT" ]
permissive
package mage.cards.c; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.AttacksTriggeredAbility; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.condition.common.CompletedDungeonCondition; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.TakeTheInitiativeEffect; import mage.abilities.effects.common.asthought.PlayFromNotOwnHandZoneTargetEffect; import mage.abilities.keyword.TrampleAbility; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.game.Game; import mage.players.Player; import mage.target.targetpointer.FixedTarget; import mage.util.CardUtil; import mage.watchers.common.CompletedDungeonWatcher; import java.util.UUID; /** * @author TheElk801 */ public final class CavesOfChaosAdventurer extends CardImpl { public CavesOfChaosAdventurer(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{R}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.BARBARIAN); this.power = new MageInt(5); this.toughness = new MageInt(3); // Trample this.addAbility(TrampleAbility.getInstance()); // When Caves of Chaos Adventurer enters the battlefield, you take the initiative. this.addAbility(new EntersBattlefieldTriggeredAbility(new TakeTheInitiativeEffect())); // Whenever Caves of Chaos Adventurer attacks, exile the top card of your library. If you've completed a dungeon, you may play that card this turn without paying its mana cost. Otherwise, you may play this card this turn. this.addAbility(new AttacksTriggeredAbility(new CavesOfChaosAdventurerEffect()) .addHint(CompletedDungeonCondition.getHint()), new CompletedDungeonWatcher()); } private CavesOfChaosAdventurer(final CavesOfChaosAdventurer card) { super(card); } @Override public CavesOfChaosAdventurer copy() { return new CavesOfChaosAdventurer(this); } } class CavesOfChaosAdventurerEffect extends OneShotEffect { CavesOfChaosAdventurerEffect() { super(Outcome.Benefit); staticText = "exile the top card of your library. If you've completed a dungeon, " + "you may play that card this turn without paying its mana cost. " + "Otherwise, you may play that card this turn"; } private CavesOfChaosAdventurerEffect(final CavesOfChaosAdventurerEffect effect) { super(effect); } @Override public CavesOfChaosAdventurerEffect copy() { return new CavesOfChaosAdventurerEffect(this); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getControllerId()); if (player == null) { return false; } Card card = player.getLibrary().getFromTop(game); if (card == null) { return false; } player.moveCards(card, Zone.EXILED, source, game); if (CompletedDungeonWatcher.checkPlayer(source.getControllerId(), game)) { game.addEffect(new PlayFromNotOwnHandZoneTargetEffect( Zone.EXILED, TargetController.YOU, Duration.EndOfTurn, true ).setTargetPointer(new FixedTarget(card, game)), source); } else { CardUtil.makeCardPlayable(game, source, card, Duration.EndOfTurn, false); } return true; } }
true
a0d457c914ae5c9aae6c2ec586f161523dec807c
Java
ErnestoPelayo/InformaTec
/app/src/main/java/com/example/macbook/informatec/ui/ActivityConferences.java
UTF-8
2,012
2.03125
2
[]
no_license
package com.example.macbook.informatec.ui; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.example.macbook.informatec.Domain.Adapters.MyAdapter; import com.example.macbook.informatec.Domain.ConferencesRepositoryImplement; import com.example.macbook.informatec.Domain.ContestRepositoryImplement; import com.example.macbook.informatec.EventsView; import com.example.macbook.informatec.Presentador.ConferencesPresenterImplement; import com.example.macbook.informatec.Presentador.ContestPresenterImplement; import com.example.macbook.informatec.Presentador.EventsPresenter; import com.example.macbook.informatec.R; import com.example.macbook.informatec.Domain.model.Events; import com.google.firebase.database.DatabaseReference; import java.util.ArrayList; import java.util.List; public class ActivityConferences extends AppCompatActivity implements EventsView { RecyclerView recyclerView; ArrayList<Events> list; MyAdapter adapter; EventsPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_concursos); recyclerView =findViewById(R.id.myRecyclerView3); recyclerView.setLayoutManager(new LinearLayoutManager(this)); list = new ArrayList<Events>(); adapter = new MyAdapter(); recyclerView.setAdapter(adapter); recyclerView.setHasFixedSize(true); LinearLayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); // Create a Presenter instance presenter = new ConferencesPresenterImplement( this, new ConferencesRepositoryImplement()); presenter.getEventsList(); } @Override public void fillAdapter(List<Events> eventsList) { adapter.addEvents(eventsList); } }
true
cf3321e78dd3ba24d05e7afd876e1ddce044e767
Java
HuyVDSE/lms-mock-project
/enamra-master/src/main/java/com/app/service/impl/ResultServiceImpl.java
UTF-8
615
1.9375
2
[]
no_license
package com.app.service.impl; import com.app.model.Result; import com.app.repository.ResultRepo; import com.app.service.ResultService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ResultServiceImpl implements ResultService { @Autowired private ResultRepo resultRepo; @Override public void saveResult(Result result) { resultRepo.save(result); } @Override public List<Result> findAllByMarkId(int markId) { return resultRepo.findAllByMarkId(markId); } }
true
2c690895d2894cb3cd83efb98ef016b41da89077
Java
JMCC-123/geogebra
/common/src/geogebra/common/kernel/kernelND/ParametricFunction.java
UTF-8
206
1.515625
2
[]
no_license
package geogebra.common.kernel.kernelND; import geogebra.common.kernel.Matrix.Coords; public interface ParametricFunction { public Coords sample(double[] parameters); public double[] getDomain(); }
true
34f0f3a423209fb40cdffbd572bce6b691c32f5a
Java
brunoyui/fruitProject
/src/main/java/com/frutare/web/rest/mapper/PagamentoMapper.java
UTF-8
1,210
2.078125
2
[]
no_license
package com.frutare.web.rest.mapper; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import com.frutare.domain.FormaPagamento; import com.frutare.domain.conta.Pagamento; import com.frutare.domain.conta.Conta; import com.frutare.web.rest.dto.PagamentoDTO; import com.frutare.web.rest.dto.FormaPagamentoDTO; /** * Mapper for the entity Cliente and its DTO ClienteDTO. */ @Mapper(componentModel = "spring", uses = {PedidoMapper.class, CreditoMapper.class}) public interface PagamentoMapper { @Mapping(source = "conta.id", target = "contaId") @Mapping(source = "formaPagamento", target = "formaPagamento") PagamentoDTO pagamentoToPagamentoDTO(Pagamento pagamento); @Mapping(target = "entradas", ignore = true) @Mapping(source = "contaId", target = "conta") @Mapping(source = "formaPagamento", target = "formaPagamento") Pagamento pagamentoDTOToPagamento(PagamentoDTO pagamento); default FormaPagamento formaPagamentoToInt(Long fPagamento) { FormaPagamento formaPagamento = new FormaPagamento(); formaPagamento.setId(fPagamento); return formaPagamento; } default Long formaPagamentoToFormaPagamentoDTO(FormaPagamento formaPagamento){ return formaPagamento.getId(); } }
true
37237e82487cbf0d00333df6f3048cfc196714fb
Java
laric158/ymsd
/ymkx-cms/src/cn/itsource/cms/controller/HelloController.java
UTF-8
702
2.0625
2
[]
no_license
package cn.itsource.cms.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import cn.itsource.cms.model.Student; import cn.itsource.cms.service.StudentService; @Controller public class HelloController { @Autowired private StudentService studentService; @RequestMapping("/hello") public ModelAndView hello() { List<Student> list = studentService.findAll(); ModelAndView mav = new ModelAndView(); mav.addObject("list", list); mav.setViewName("hello"); return mav; } }
true
e95a0b557174ca02d6edd28b6693ccf2d3de53b5
Java
pwkpwk/androbind
/app/src/main/java/com/ambientbytes/contentpresenter/viewmodels/IViewModel.java
UTF-8
372
1.679688
2
[]
no_license
package com.ambientbytes.contentpresenter.viewmodels; import org.jetbrains.annotations.NotNull; public interface IViewModel { void Presenting(@NotNull IViewModelPresenter presenter); void Presented(@NotNull IViewModelPresenter presenter); void Dismissing(@NotNull IViewModelPresenter presenter); void Dismissed(@NotNull IViewModelPresenter presenter); }
true
35b8229da37f7e72d3d6201a20d2a539f11559e6
Java
Hoda-Msw/Chess.InformedSearchStrategies
/src/chess/dataStructure/State.java
UTF-8
1,223
3.15625
3
[]
no_license
/* * 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 chess.dataStructure; /** * * @author Hoda_msw */ public class State { public int[][] board; public State(int n, int m) { board = new int[n][m]; } public boolean isEqual(State s) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { if (this.board[i][j] != s.board[i][j]) { return false; } } } return true; } public void set(State s) { for (int i = 0; i < board.length; i++) { System.arraycopy(s.board[i], 0, board[i], 0, board[i].length); } } public int HeuristicFunction() { int sum = 0; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { if (board[i][j] != CreateStates.getGoal().board[i][j]) { sum++; } } } return sum; } }
true
c0027bb68260776261eb77d0146bfb0ea1bed9cf
Java
vijaydhang/cachesynch
/CacheSynch/src/main/java/com/cachesynch/repository/PersonRepository.java
UTF-8
704
2.203125
2
[]
no_license
package com.cachesynch.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.cachesynch.entity.PersonEntity; /** * Repository class to * handle DB operation related to PERSON table * @author Vijay Dhang * */ @Repository public interface PersonRepository extends JpaRepository<PersonEntity, Long> { //Return list of rows which matches the status passed as an argument List<PersonEntity> findByStatus(String status); //Return list of rows which the status is not equal to the //status passed as an argument List<PersonEntity> findByStatusNot(String status); }
true
38e2f5f656dd521e3a508cfdd6e036376f273522
Java
shashank17sahu/MyProject
/Ebanking/src/com/ebanking/scripts/Basic_Scripts.java
UTF-8
5,757
2.515625
3
[]
no_license
package com.ebanking.scripts; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; public class Basic_Scripts { public static void main(String[] args) throws InterruptedException { String Expval="Ranford Bank"; WebDriver driver=new FirefoxDriver(); driver.get("http://183.82.100.55/ranford2"); driver.manage().window().maximize(); String Actval=driver.findElement(By.xpath("/html/body/form/table/tbody/tr/td/table/tbody/tr[4]/td/table/tbody/tr[1]/td[4]/p/span")).getText(); System.out.println(driver.getTitle()); if(Expval.equalsIgnoreCase(Actval)) { System.out.println("Ranford Application Launched"); } else { System.out.println("Ranford Application not Launched"); } //Home Page driver.findElement(By.xpath("//*[@id=\"txtuId\"]")).sendKeys("Admin"); driver.findElement(By.xpath("//*[@id=\"txtPword\"]")).sendKeys("M1ndq"); driver.findElement(By.xpath("//*[@id=\"login\"]")).click(); Thread.sleep(5000); Expval="Welcome to Admin"; if(Expval.equalsIgnoreCase(Actval)) { System.out.println("Admin Login Successfully"); } else { System.out.println("Admin Login Fial"); } //Branch Page driver.findElement(By.xpath("//img[@src='images/Branches_but.jpg']")).click(); Thread.sleep(2000); //New Branch Creation driver.findElement(By.id("BtnNewBR")).click(); Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"txtbName\"]")).sendKeys("medical"); driver.findElement(By.xpath("//*[@id=\"txtAdd1\"]")).sendKeys("Medical Chowk"); driver.findElement(By.xpath("//*[@id=\"txtZip\"]")).sendKeys("44000"); Select Ctry=new Select(driver.findElement(By.id("lst_counrtyU"))); Ctry.selectByVisibleText("INDIA"); Select state=new Select(driver.findElement(By.id("lst_stateI"))); state.selectByVisibleText("MAHARASTRA"); Select city=new Select(driver.findElement(By.id("lst_cityI"))); city.selectByVisibleText("MUMBAI"); driver.findElement(By.xpath("//*[@id=\"btn_insert\"]")).click(); Thread.sleep(2000); Actval=driver.switchTo().alert().getText(); driver.switchTo().alert().accept(); if(Actval.contains(Expval)) { System.out.println("Branch Created"); } else { System.out.println("Branch not Created"); } Thread.sleep(2000); //Home Button driver.findElement(By.xpath("//img[@src='images/admin_but_01.jpg']")).click(); Thread.sleep(5000); //Role Button driver.findElement(By.xpath("//img[@src='images/Roles_but.jpg']")).click(); Thread.sleep(2000); //New Role Creation driver.findElement(By.xpath("//*[@id=\"btnRoles\"]")).click(); Thread.sleep(2000); //Filling Details driver.findElement(By.xpath("//*[@id=\"txtRname\"]")).sendKeys("medicalchowk"); driver.findElement(By.xpath("//*[@id=\"txtRDesc\"]")).sendKeys("medical chowk"); driver.findElement(By.xpath("/html/body/div/form/div/table[1]/tbody/tr[4]/td[2]/select/option[2]")).click(); driver.findElement(By.xpath("//*[@id=\"btninsert\"]")).click(); Thread.sleep(2000); String alert=driver.switchTo().alert().getText(); System.out.println(alert); Actval=driver.switchTo().alert().getText(); driver.switchTo().alert().accept(); if(Actval.contains(Expval)) { System.out.println("Role Created"); } else { System.out.println("Role Altready Existed"); } Thread.sleep(2000); driver.findElement(By.xpath("//img[@src='images/admin_but_01.jpg']")).click(); Thread.sleep(2000); //Employee driver.findElement(By.xpath("//img[@src='images/emp_btn.jpg']")).click(); //New Employee driver.findElement(By.xpath("//*[@id=\"BtnNew\"]")).click(); //filling details in employee driver.findElement(By.xpath("//*[@id=\"txtUname\"]")).sendKeys("medical"); driver.findElement(By.xpath("//*[@id=\"txtLpwd\"]")).sendKeys("medical"); Select role=new Select(driver.findElement(By.id("lst_Roles"))); role.selectByVisibleText("medicalchowk"); Select branch=new Select(driver.findElement(By.id("lst_Branch"))); branch.selectByVisibleText("medical"); driver.findElement(By.xpath("//*[@id=\"BtnSubmit\"]")).click(); Thread.sleep(2000); Actval=driver.switchTo().alert().getText(); driver.switchTo().alert().accept(); if(Actval.contains(Expval)) { System.out.println("Employee Created"); } else { System.out.println("Employee Already Existed"); } Thread.sleep(2000); driver.findElement(By.xpath("//img[@src='images/admin_but_01.jpg']")).click(); Thread.sleep(5000); /*//User driver.findElement(By.xpath("//img[@src='images/Users_but.jpg']")).click(); //new User creation driver.findElement(By.xpath("//*[@id=\"Btnuser\"]")).click(); //Filling user details Select role1=new Select(driver.findElement(By.id("lst_Roles"))); role1.selectByVisibleText("medicalchowk"); Select branch1=new Select(driver.findElement(By.id("lst_Branch"))); branch1.selectByVisibleText("medical"); Select cid=new Select(driver.findElement(By.id("DrCName"))); cid.selectByVisibleText("medical"); driver.findElement(By.xpath("//*[@id=\"txtUname\"]")).sendKeys("medical"); driver.findElement(By.xpath("//*[@id=\"txtLpwd\"]")).sendKeys("medical"); driver.findElement(By.xpath("//*[@id=\"txtTpwd\"]")).sendKeys("medical"); driver.findElement(By.xpath("//*[@id=\"BtnSubmit\"]")).click(); Thread.sleep(2000); Actval=driver.switchTo().alert().getText(); driver.switchTo().alert().accept(); if(Actval.contains(Expval)) { System.out.println("User Created"); } else { System.out.println("User Already Existed"); } Thread.sleep(2000); driver.findElement(By.xpath("//img[@src='images/admin_but_03.jpg']")).click(); */ driver.close(); } }
true
d49ff9693f157e495b863a8871479ce337391f97
Java
bellmit/Codeshelf
/src/main/java/com/codeshelf/flyweight/controller/TcpServerInterface.java
UTF-8
7,093
2.28125
2
[]
no_license
/******************************************************************************* * CodeShelf * Copyright (c) 2005-2012, Jeffrey B. Williams, All rights reserved * $Id: TcpServerInterface.java,v 1.6 2013/03/17 19:19:13 jeffw Exp $ *******************************************************************************/ package com.codeshelf.flyweight.controller; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.LinkedBlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author jeffw * */ public class TcpServerInterface extends SerialInterfaceABC { public static final int PORT_NUM = 45000; public static final int READ_WAIT_MILLIS = 10; public static final int OPEN_WAIT_MILLIS = 25; private static final Logger LOGGER = LoggerFactory.getLogger(TcpServerInterface.class); private ServerSocket mServerSocket; private LinkedBlockingQueue<Remote> mRemotes = new LinkedBlockingQueue<Remote>(); private class Remote { public Socket clientSocket; public InputStream inputStream; public OutputStream outputStream; } /** * */ public TcpServerInterface() { } // -------------------------------------------------------------------------- /* (non-Javadoc) * @see com.codeshelf.flyweight.controller.SerialInterfaceABC#doSetupConnection() */ @Override protected final boolean doSetupConnection() { boolean result = true; try { mServerSocket = new ServerSocket(PORT_NUM); } catch (java.net.BindException e) { LOGGER.error("Address/port number in use during doSetupConnection", e); result = false; } catch (IOException e) { LOGGER.error("", e); result = false; } return result; } // -------------------------------------------------------------------------- /* (non-Javadoc) * @see com.codeshelf.flyweight.controller.SerialInterfaceABC#doStartInterface() */ @Override protected final void doStartInterface() { Thread interfaceStarterThread = new Thread(new Runnable() { public void run() { while (mServerSocket != null) { // while running Socket clientSocket = null; try { if(mServerSocket.isClosed()) { // do not spin throwing a thousand SocketExceptions per second if the socket is closed Thread.sleep(OPEN_WAIT_MILLIS); } else { clientSocket = mServerSocket.accept(); LOGGER.info("Client opened: " + clientSocket.toString()); Remote remote = new Remote(); remote.clientSocket = clientSocket; remote.inputStream = clientSocket.getInputStream(); remote.outputStream = clientSocket.getOutputStream(); // byte[] putInCharMode = { (byte) 255, (byte) 251, (byte) 1, (byte) 255, (byte) 251, (byte) 3, (byte) 255, (byte) 252, (byte) 34 }; // remote.outputStream.write(putInCharMode); mRemotes.add(remote); } } catch (IOException e) { System.err.println("Accept failed."); System.err.println(e); //System.exit(1); } catch (InterruptedException e) { LOGGER.error("OPEN_WAIT interrupted", e); } } } }, "SocketListener"); interfaceStarterThread.start(); } // -------------------------------------------------------------------------- /* (non-Javadoc) * @see com.codeshelf.flyweight.controller.SerialInterfaceABC#doResetInterface() */ @Override protected final void doResetInterface() { try { mServerSocket.close(); doSetupConnection(); } catch (IOException e1) { LOGGER.error("", e1); } for (Remote remote : mRemotes) { try { remote.clientSocket.close(); } catch (IOException e) { LOGGER.error("", e); } } mRemotes.clear(); } // -------------------------------------------------------------------------- /* (non-Javadoc) * @see com.codeshelf.flyweight.controller.SerialInterfaceABC#doStopInterface() */ @Override protected void doStopInterface() { try { // see a NPE here on tearing down integration test. Example IntegrationTest1.java if (mServerSocket != null) mServerSocket.close(); mServerSocket = null; //doSetupConnection(); } catch (IOException e1) { LOGGER.error("", e1); } for (Remote remote : mRemotes) { try { remote.clientSocket.close(); } catch (IOException e) { LOGGER.error("", e); } } mRemotes.clear(); } // -------------------------------------------------------------------------- /* (non-Javadoc) * @see com.codeshelf.flyweight.controller.SerialInterfaceABC#setRTS() */ @Override protected void setRTS() { // TODO Auto-generated method stub } // -------------------------------------------------------------------------- /* (non-Javadoc) * @see com.codeshelf.flyweight.controller.SerialInterfaceABC#clrRTS() */ @Override protected void clrRTS() { // TODO Auto-generated method stub } // -------------------------------------------------------------------------- /* (non-Javadoc) * @see com.codeshelf.flyweight.controller.SerialInterfaceABC#readByte() */ @Override protected final byte readByte() { while (this.shouldRun()) { for (Remote remote : mRemotes) { if (remote.clientSocket.isConnected()) { try { if (remote.inputStream.available() > 0) { return (byte) remote.inputStream.read(); } } catch (IOException e) { LOGGER.error("", e); } } } try { Thread.sleep(READ_WAIT_MILLIS); } catch (InterruptedException e) { LOGGER.error("", e); } } return 0; } // -------------------------------------------------------------------------- /* (non-Javadoc) * @see com.codeshelf.flyweight.controller.SerialInterfaceABC#readBytes(byte[]) */ @Override protected final int readBytes(byte[] inBuffer) { for (Remote remote : mRemotes) { if (remote.clientSocket.isConnected()) { try { if (remote.inputStream.available() > 0) { return remote.inputStream.read(inBuffer); } } catch (IOException e) { LOGGER.error("", e); doResetInterface(); } } } return 0; } // -------------------------------------------------------------------------- /* (non-Javadoc) * @see com.codeshelf.flyweight.controller.SerialInterfaceABC#writeByte(byte) */ @Override protected void writeByte(byte inByte) { for (Remote remote : mRemotes) { if (remote.clientSocket.isConnected()) { try { remote.outputStream.write(inByte); } catch (IOException e) { LOGGER.error("", e); doResetInterface(); } } } } // -------------------------------------------------------------------------- /* (non-Javadoc) * @see com.codeshelf.flyweight.controller.SerialInterfaceABC#writeBytes(byte[], int) */ @Override protected void writeBytes(byte[] inBytes, int inLength) { for (Remote remote : mRemotes) { if (remote.clientSocket.isConnected()) { try { remote.outputStream.write(inBytes, 0, inLength); } catch (IOException e) { LOGGER.error("", e); doResetInterface(); } } } } }
true
40cd00f25a6241d29faeed85b3eaade64578334c
Java
AndyTQ/The-Mars-Platform
/GameCentre/app/src/main/java/fall2018/csc2017/gamecentre/games/game2048/Game2048WinningActivity.java
UTF-8
1,943
2.578125
3
[ "Apache-2.0" ]
permissive
package fall2018.csc2017.gamecentre.games.game2048; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import fall2018.csc2017.gamecentre.MainActivity; import fall2018.csc2017.gamecentre.R; /** * A activity class that is excluded from the tests since it contains minimal amount of logic. * * The activity when the game 2048 wins */ public class Game2048WinningActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game2048_winning); Integer int_score = getIntent().getIntExtra("game_2048_score", 0); String scoreText = int_score.toString(); TextView scoreDisplay = findViewById(R.id.game2048_winning_score); scoreDisplay.setText(scoreText); findViewById(R.id.game2048_winning_quit).setOnClickListener(this); findViewById(R.id.game2048_winning_return_to_menu).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.game2048_winning_quit: Intent intentBackToCentre = new Intent(Game2048WinningActivity.this, MainActivity.class); intentBackToCentre.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivityIfNeeded(intentBackToCentre, 0); break; case R.id.game2048_winning_return_to_menu: Intent intentBackToGameMenu = new Intent(Game2048WinningActivity.this, Game2048StartingActivity.class); intentBackToGameMenu.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivityIfNeeded(intentBackToGameMenu, 0); break; } } }
true
bb9cddaf77c6f248b5c7a476b4ab51786146a2e4
Java
Sergey-Gusarov/pyramaker
/src/main/java/org/svoyt/pyramaker/engine/Rectangle.java
UTF-8
1,607
3.03125
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2012 Sergey Voyteshonok info@svoyt.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.svoyt.pyramaker.engine; /** * Rectangle */ public class Rectangle { /** * Left rectangle border (x coordinate) */ public double left; /** * Top rectangle border (y coordinate) */ public double top; /** * Right rectangle border (x coordinate) */ public double right; /** * Bottom rectangle border (y coordinate) */ public double bottom; /** * Default constructor */ public Rectangle(){ } /** * Constructor */ public Rectangle(double left, double top, double right, double bottom){ this.left = left; this.top = top; this.right = right; this.bottom = bottom; } /** * Rectangle width (right-left) * * @return width */ public double getWidth(){ return right - left; } /** * Rectangle height (bottom-top) * * @return height */ public double getHeight(){ return bottom - top; } }
true
0a2ec51403733fdb77afe5b3d097c0d7814da92b
Java
karlfel/Game
/src/Main.java
UTF-8
1,241
3.171875
3
[]
no_license
import javax.swing.*; import java.lang.Boolean; // TODO: Buttons toggle, if button is clicked action should be performed // TODO: At the bottom of the window should be displayed rolled dices and next roll // TODO: User should be able to choose from rolled dices, which to keep and which to discard // TODO: Three rolls logic -> After that should implement user choice, which points to take and how much is their sum // TODO: Update score // TODO: Buttons alignment and design, maybe instead of text put pictures on buttons // TODO: Window scaling - if window size is changed then buttons size should also be automatically changed // TODO: public class Main { public static void main(String args[]) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new MainFrame("Yahtzee"); frame.setSize(500, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); // Whole game loop /*for (int i = 0; i < 10; i++) { // Here are three rolls for (int j = 0; j < 3; j++) { } } }*/ } }
true
dc6bea4f30e3951ea7b1e4c654bf3537ea2575dc
Java
bbbnam/object-book
/object4/src/Client.java
UTF-8
578
2.578125
3
[]
no_license
public abstract class Client implements Paper { private Library library = new Library("vueJS"); private Language language = new Language("kotlinJS"); private Programmer programmer; public Library getLibrary() { return library; } public void setLibrary(Library library) { this.library = library; } public Language getLanguage() { return language; } public void setLanguage(Language language) { this.language = language; } public Programmer getProgrammer() { return programmer; } }
true
65f92ad6fd581be3b1a68d18d25e4a59ebbe4c9c
Java
rcoolboy/guilvN
/app/src/main/java/com/p118pd/sdk/AbstractC6339ill.java
UTF-8
1,394
1.8125
2
[]
no_license
package com.p118pd.sdk; /* renamed from: com.pd.sdk.ill丨 reason: invalid class name and case insensitive filesystem */ public abstract class AbstractC6339ill { public static final char OooO00o = 'Z'; public static final char OooO0O0 = 'I'; public static final char OooO0OO = 'L'; public static final char OooO0Oo = 'U'; public static final char OooO0o0 = 'R'; /* renamed from: OooO00o reason: collision with other field name */ public int f18082OooO00o; /* renamed from: OooO0O0 reason: collision with other field name */ public int f18083OooO0O0; public int OooO00o() { return this.f18083OooO0O0; } public abstract L1LL111 OooO00o(L1LL111 l1ll111); /* renamed from: OooO00o reason: collision with other method in class */ public abstract AbstractC6339ill m17400OooO00o(); public abstract AbstractC6339ill OooO00o(C6051i1lli i1lli); public abstract AbstractC6339ill OooO00o(AbstractC6339ill v); /* renamed from: OooO00o reason: collision with other method in class */ public abstract boolean m17401OooO00o(); /* renamed from: OooO00o reason: collision with other method in class */ public abstract byte[] m17402OooO00o(); public int OooO0O0() { return this.f18082OooO00o; } public abstract L1LL111 OooO0O0(L1LL111 l1ll111); public abstract String toString(); }
true
742a0f28292e9aa0bd6a2728658ab0a9ef0a1f1a
Java
mkubiak164/UserProfileAndRanking
/src/main/java/com/capgemini/user/profile/and/ranking/ranking/RankingService.java
UTF-8
2,229
2.421875
2
[]
no_license
package com.capgemini.user.profile.and.ranking.ranking; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.capgemini.user.profile.and.ranking.profile.ProfileService; @Service public class RankingService { private ProfileService profileService; private RankingDAO rankingDAO; private RankingMapper rankingMapper; @Autowired public RankingService(ProfileService profileService, RankingDAO rankingDAO, RankingMapper rankingMapper) { this.profileService = profileService; this.rankingDAO = rankingDAO; this.rankingMapper = rankingMapper; } public List<RankingDTO> findGameRanking(long gameID) { List<RankingEntity> rankingEntities = rankingDAO.findGameRanking(gameID); List<RankingDTO> rankingDTOs = new ArrayList<>(); rankingEntities.stream().forEach(r -> { rankingDTOs.add(rankingMapper.from(r)); }); return rankingDTOs; } public List<RankingDTO> findAllUserGames(long userID) { List<RankingEntity> rankingEntities = rankingDAO.findUserGamesHistory(userID); List<RankingDTO> rankingDTOs = new ArrayList<>(); rankingEntities.stream().forEach(r -> { rankingDTOs.add(rankingMapper.from(r)); }); return rankingDTOs; } public int userRankingPosition(long userID, long gameID) { List<RankingDTO> gameRanking = findGameRanking(gameID); HashMap<Long, Integer> userPoints = new HashMap<>(); profileService.findAllUsers().forEach(user -> { int currentPoints = 0; for(RankingDTO ranking : gameRanking) { if(ranking.getWinnerID() == userID){ currentPoints++; } } userPoints.put(userID, currentPoints); }); int userGamePoints = userPoints.get(Long.valueOf(userID)); int rankingPosition = 1; // przypisujemy na starcie 1 pozycje w rankingu for(Map.Entry<Long, Integer> entry : userPoints.entrySet()) { if(entry.getValue() > userGamePoints) { rankingPosition++; } } // porównujemy po kolei ilośc punktów innych userów, // jeżeli ktoś ma więcej wygranych, to pozycja usera w rankingu się zwiększa o 1 return rankingPosition; } }
true
99a93d1f57b6d100b8c24b724b369992817d2276
Java
Wonwoo2/BasicJava
/T13_JavaFxTest/src/kr/or/ddit/exam3/dao/ZipDaoImpl.java
UTF-8
997
2.234375
2
[]
no_license
package kr.or.ddit.exam3.dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.ibatis.sqlmap.client.SqlMapClient; import kr.or.ddit.exam3.util.DBUtil; import kr.or.ddit.exam3.vo.ZipVO; public class ZipDaoImpl implements IZipDao{ private static IZipDao dao; private SqlMapClient smc; private List<ZipVO> zipList; public ZipDaoImpl() { smc = DBUtil.readXML("sqlMapConfig.xml"); zipList = new ArrayList<>(); } public static IZipDao getInstance() { if(dao == null) { dao = new ZipDaoImpl(); } return dao; } @Override public List<ZipVO> getDongZipList(String dong) { try { zipList = smc.queryForList("zip.getDongZipList", dong); } catch (SQLException e) { e.printStackTrace(); } return zipList; } @Override public List<ZipVO> getZipCodeList(String zipCode) { try { zipList = smc.queryForList("zip.getZipCodeList", zipCode); } catch (SQLException e) { e.printStackTrace(); } return zipList; } }
true
0c789b601557e38b9db51bd335cf3d75f008c59a
Java
s3valkov/cooking4love
/src/main/java/org/s3valkov/cooking4love/service/CategoryService.java
UTF-8
428
1.96875
2
[]
no_license
package org.s3valkov.cooking4love.service; import org.s3valkov.cooking4love.domain.models.service.CategoryServiceModel; import java.util.List; public interface CategoryService { CategoryServiceModel createCategory(CategoryServiceModel categoryServiceModel); CategoryServiceModel findByName(String name); List<CategoryServiceModel> findAllCategories(); CategoryServiceModel findCategoryById(String id); }
true
60f6547acc90c27236dc70173aa2ada5fa469b5b
Java
LiuGuoqingBeyond/JavaBaseTest
/app/src/main/java/com/uppayplugin/unionpay/javabasetest/utils/device/ByteUtils.java
UTF-8
2,248
2.96875
3
[]
no_license
package com.uppayplugin.unionpay.javabasetest.utils.device; /** * @project:xzfpos * @author:- Richard on 2017/11/28 16:01 * @email:zhangh@qtopay.cn */ public class ByteUtils { /** * 十六进制转二进制字符串 * * @param bArray 十六进制字节数组 * @return */ public static String bytes2BinaryStr(byte[] bArray) { String[] binaryArray = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; StringBuilder outStr = new StringBuilder(); int pos = 0; for (byte b : bArray) { //高四位 pos = (b & 0xF0) >> 4; outStr.append(binaryArray[pos]); //低四位 pos = b & 0x0F; outStr.append(binaryArray[pos]); } return outStr.toString(); } public static byte[] str2bytes(String src) { if (src == null || src.length() == 0 || src.length() % 2 != 0) { return null; } int nSrcLen = src.length(); byte byteArrayResult[] = new byte[nSrcLen / 2]; StringBuffer strBufTemp = new StringBuffer(src); String strTemp; int i = 0; while (i < strBufTemp.length() - 1) { strTemp = src.substring(i, i + 2); byteArrayResult[i / 2] = (byte) Integer.parseInt(strTemp, 16); i += 2; } return byteArrayResult; } public static String convertHexToString(String hex) { StringBuilder sb = new StringBuilder(); StringBuilder temp = new StringBuilder(); // 49204c6f7665204a617661 // split into two // characters 49, 20, 4c... for (int i = 0; i < hex.length() - 1; i += 2) { // grab the hex in pairs String output = hex.substring(i, (i + 2)); if ("00".equals(output)) { return sb.toString(); } // convert hex to decimal int decimal = Integer.parseInt(output, 16); // convert the decimal to character sb.append((char) decimal); temp.append(decimal); } return sb.toString(); } }
true
5f6d5b98c4c2fe870c6ea3cd8c8a2f75a899c92f
Java
jackmead515/2d_game_engine
/src/main/java/com/engine/jsm/util/DrawUtil.java
UTF-8
225
2.34375
2
[]
no_license
package com.engine.jsm.util; import java.awt.*; public class DrawUtil { public static void drawRect(Graphics2D g2, double[] rect) { g2.drawRect((int)rect[0], (int)rect[1], (int)rect[2], (int)rect[3]); } }
true
1454f2019db6d00f9fc14231f0ccd0affd54e2cf
Java
menonpatrick/Masters-Projects
/FCFS/src/fcfs.java
UTF-8
6,015
3.09375
3
[]
no_license
public class fcfs { public static int process_id [] = new int [4]; // indicates the process number public static double arrival_time [] = new double [4]; // indicates the arrival time of the respective processes public static double burst_time [] = new double [4]; //indicates the burst time of the respective processes public static double trt [] = new double [4]; // indicates the turnaround time of the respective processes public static double wt [] = new double [4]; // indicates the waiting time of the respective processes public static double ct [] = new double [4]; // indicates the completion time of the respective processes public static int[] pcb = new int [4]; // array of pcb for storing the entries of the processes public static int[] ready_queue = new int [4]; // indicates the ready queue public static int cpu_state = 0; // indicates the state of the cpu; || 0 = free || 1 = busy || public static int pcb_state = 0; // indicates the state of the pcb; || 0 = idle || 1 = running || // arrival function public static void arrival(int p, double a, double b) { double avg = 0; // avg variable declared to find the average of turnaround time int k = 0; // variable for managing the pcb entry pcb[k] = p; // creating a PCB entry into the pcb array System.out.println("PCB entry created for Process "+p); // checking if the state of cpu is free if(cpu_state == 0) { System.out.println("** CPU is free **"); // indicating that the cpu is free cpu_state = 1; // making the state of cpu from idle to busy pcb_state = 1; // making the pcb state from idle to running // calculating completion time and turnaround time for(int i=1;i<=3;i++) { ct[i] = ct[i-1] + burst_time[i]; trt[i] = ct[i] - arrival_time[i]; } // for ends // calculating average turnaround time //double avg = 0; for(int u=1;u<=3;u++) { avg = avg + trt[u]; } // for ends avg = avg/3; //System.out.println("Average Turnaround Time : "+avg); // calculating waiting time wt[p] = trt[p] - burst_time[p]; k++; } // if cpu_state ends // if the state of cpu is not free else { System.out.println("** CPU is NOT free **"); // indicating that the cpu is not free pcb_state = 0; // pcb state changed to ready ready_queue[p] = p; // updating ready queue }// else ends completion(process_id[p]); // completion function call if(p == 3) System.out.println("Average Turnaround Time : "+avg); } // arrival function ends // completion function public static void completion(int p) { for(int x=1;x<=3;x++) if(pcb[x] == p) // searching for the pcb entry pcb[x] = 0; // pcb entry destroyed System.out.println("PCB entry destroyed for Process "+p); System.out.println("** CPU is made free **"); cpu_state = 0; // making the cpu state from busy to idle pcb_state = 0; // making the pcb state from running to idle for(int x=1;x<=3;x++) { if(ready_queue[1] != 0) { // checking if the ready queue is not empty completion(process_id[1]); // calling completion function pcb_state = 1; // indicates that the pcb state is running } // if ends else { // if the ready queue is empty cpu_state = 0; // making the state of cpu as free } // else ends } // for ends } // completion function ends // display1 function // displays the arrival time and the burst time public static void display1() { System.out.println("Initial Information -->"); System.out.println("Process \t Arrival Time \t Burst Time"); for(int i=1;i<=3;i++) System.out.println(process_id[i]+"\t\t\t"+arrival_time[i]+"\t\t"+burst_time[i]); System.out.println(); System.out.println(); } // display1 function ends // display2 function // displays the waiting time and the turnaround time public static void display2() { System.out.println("Your Information is as follows -->"); System.out.println("Process \t Waiting Time \t Turnaround Time"); for(int i=1;i<=3;i++) System.out.println(process_id[i]+"\t\t\t"+wt[i]+"\t\t"+trt[i]); System.out.println(); System.out.println(); for(int i=1;i<=3;i++) { System.out.println(); System.out.println("Process "+process_id[i]+" arrived at "+arrival_time[i]+" & completed at "+ct[i]); } // for ends } // display2 function ends // display the processes in the form of a gantt chart public static void display3() { System.out.println(); System.out.println("Gantt Chart:"); for(int i=1;i<=3;i++) { System.out.print("|\tP" +process_id[i]); } // for ends System.out.print("|"); System.out.println(); for(int i=0;i<=3;i++) { System.out.print(ct[i]+" \t"); } // for ends } // display3 function ends public static void main (String z[]) { System.out.println("First Come First Serve (5.3):"); System.out.println(); int i; // storing the values of the processes process_id [1] = 1; // process 1 process_id [2] = 2; // process 2 process_id [3] = 3; // process 3 // storing the arrival time of the processes arrival_time [1] = 0.0; // arrival time of process 1 arrival_time [2] = 0.4; // arrival time of process 2 arrival_time [3] = 1.0; // arrival time of process 3 // storing the burst time of the processes burst_time [1] = 8; // burst time of process 1 burst_time [2] = 4; // burst time of process 2 burst_time [3] = 1; // burst time of process 3 for(i=1;i<=3;i++) { arrival(process_id[i],arrival_time[i],burst_time[i]); // arrival function call //completion(process_id[i],arrival_time[i],burst_time[i]); // completion fumction call } // for ends display1(); // display1 function called display2(); // display2 function called display3(); // display3 function called } // main method ends } // class ends
true
614a05f989e27b3d6dacab832092c3adf3f90aec
Java
Pen53/RedisDistributeLock
/pen.common/src/main/java/com/mepeng/cn/pen/common/util/pinyin4j/format/ChinesePinyinVCharType.java
UTF-8
1,766
2.84375
3
[]
no_license
/** * */ package com.mepeng.cn.pen.common.util.pinyin4j.format; /** * Define the output format of character 'ü' * * <p> * 'ü' is a special character of Hanyu Pinyin, which can not be simply * represented by English letters. In Hanyu Pinyin, such characters include 'ü', * 'üe', 'üan', and 'ün'. * * <p> * This class provides several options for output of 'ü', which are listed * below. * * <table> * <tr> * <th>Options</th> * <th>Output</th> * </tr> * <tr> * <td>WITH_U_AND_COLON</td> * <td align = "center">u:</td> * </tr> * <tr> * <td>WITH_V</td> * <td align = "center">v</td> * </tr> * <tr> * <td>WITH_U_UNICODE</td> * <td align = "center">ü</td> * </tr> * </table> * * @author Li Min (xmlerlimin@gmail.com) * */ public class ChinesePinyinVCharType { /** * The option indicates that the output of 'ü' is "u:" */ public static final ChinesePinyinVCharType WITH_U_AND_COLON = new ChinesePinyinVCharType("WITH_U_AND_COLON"); /** * The option indicates that the output of 'ü' is "v" */ public static final ChinesePinyinVCharType WITH_V = new ChinesePinyinVCharType("WITH_V"); /** * The option indicates that the output of 'ü' is "ü" in Unicode form */ public static final ChinesePinyinVCharType WITH_U_UNICODE = new ChinesePinyinVCharType("WITH_U_UNICODE"); /** * @return Returns the name. */ public String getName() { return name; } /** * @param name * The name to set. */ protected void setName(String name) { this.name = name; } /** * Constructor */ protected ChinesePinyinVCharType(String name) { setName(name); } protected String name; }
true
5a4d3e4e85935f1e44505607e868ecaa66fa1fbf
Java
anddrews/InternalTraining
/xml/src/model/Place.java
UTF-8
951
3
3
[]
no_license
package model; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Place { private String name; private Date date; public Place() { this.name = ""; this.date = null; } public Place(String name, Date date) { this.name = name; this.date = date; } public Place(String name) { this.name = name; this.date = null; } public Place(String name, String date) throws ParseException { SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); this.name = name; this.date=format.parse(date); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public String toString() { return "[name=" + name + ", date=" + date + "]"; } }
true
6d32a42a45d1ad0405546b17ce9683f5b7179c63
Java
aayusharyan/bakingapp
/app/src/main/java/com/aayushsinha/android/bakingapp/stepDetailActivity.java
UTF-8
11,350
1.5625
2
[]
no_license
package com.aayushsinha.android.bakingapp; import android.app.Dialog; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewCompat; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.PlaybackParameters; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.source.ExtractorMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelection; import com.google.android.exoplayer2.trackselection.TrackSelectionArray; import com.google.android.exoplayer2.trackselection.TrackSelector; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import com.google.android.exoplayer2.ui.PlayerView; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.util.Util; import java.util.Objects; import butterknife.BindView; import butterknife.ButterKnife; public class stepDetailActivity extends AppCompatActivity { @BindView(R.id.detail_toolbar) Toolbar toolbar; @BindView(R.id.step_media_video) PlayerView playerView; @BindView(R.id.videoBufferingPB) ProgressBar videoBufferingPB; @BindView(R.id.exo_controller_fullscreen) ImageView fullScreenBtn; @BindView(R.id.exo_controller) LinearLayout playbackControlView; @BindView(R.id.toolbar_layout) CollapsingToolbarLayout toolbarLayout; @BindView(R.id.app_bar) AppBarLayout appBar; @BindView(R.id.step_detail_container) NestedScrollView stepDetailContainer; private Dialog mFullScreenDialog; private boolean isFullScreen; private boolean isZoomed; private SimpleExoPlayer player; private String videoURL; private long position; public static String SELECTED_POSITION = "exo_player_time_position"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_step_detail); ButterKnife.bind(this); setSupportActionBar(toolbar); if(getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } if (savedInstanceState == null) { Bundle arguments = new Bundle(); arguments.putString(stepListActivity.STEP_ID_KEY, getIntent().getStringExtra(stepListActivity.STEP_ID_KEY)); arguments.putString(stepListActivity.SHORT_DESC_KEY, getIntent().getStringExtra(stepListActivity.SHORT_DESC_KEY)); arguments.putString(stepListActivity.DESC_KEY, getIntent().getStringExtra(stepListActivity.DESC_KEY)); arguments.putString(stepListActivity.THUMBNAIL_URL_KEY, getIntent().getStringExtra(stepListActivity.THUMBNAIL_URL_KEY)); stepDetailFragment fragment = new stepDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction().add(R.id.step_detail_container, fragment).commit(); } else { position = savedInstanceState.getLong(SELECTED_POSITION, 0); } isFullScreen = false; videoURL = getIntent().getStringExtra(stepListActivity.VIDEO_URL_KEY); if(Objects.equals(videoURL, "")) { toolbarLayout.removeView(playerView); appBar.setExpanded(false, false); appBar.setActivated(false); appBar.setMinimumHeight(toolbar.getHeight()); ViewCompat.setNestedScrollingEnabled(stepDetailContainer,false); CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appBar.getLayoutParams(); if(lp != null) { AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) lp.getBehavior(); if (behavior != null) { behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() { @Override public boolean canDrag(@NonNull AppBarLayout appBarLayout) { return false; } }); lp.setBehavior(behavior); appBar.setLayoutParams(lp); } } } else { initPlayer(); } } private void initPlayer() { DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(); TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter); TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory); player = ExoPlayerFactory.newSimpleInstance(this, trackSelector); if (position != 0) { player.seekTo(position); } playerView.setPlayer(player); DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, getString(R.string.app_name)), bandwidthMeter); final MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(videoURL)); player.prepare(videoSource); player.setPlayWhenReady(true); player.addListener(new Player.EventListener() { @Override public void onTimelineChanged(Timeline timeline, Object manifest, int reason) { } @Override public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { } @Override public void onLoadingChanged(boolean isLoading) { } @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { if(playbackState == Player.STATE_BUFFERING) { videoBufferingPB.setVisibility(View.VISIBLE); } else { videoBufferingPB.setVisibility(View.GONE); } } @Override public void onRepeatModeChanged(int repeatMode) { } @Override public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) { } @Override public void onPlayerError(ExoPlaybackException error) { } @Override public void onPositionDiscontinuity(int reason) { } @Override public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { } @Override public void onSeekProcessed() { } }); initFullscreenDialog(); } private void initFullscreenDialog() { mFullScreenDialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen) { @Override public void onBackPressed() { closeFullscreenDialog(); super.onBackPressed(); } }; } private void openFullscreenDialog() { ((ViewGroup) playerView.getParent()).removeView(playerView); mFullScreenDialog.addContentView(playerView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); isFullScreen = true; if(isZoomed) { playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM); } else { playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT); } mFullScreenDialog.show(); } private void closeFullscreenDialog() { ((ViewGroup) playerView.getParent()).removeView(playerView); toolbarLayout.addView(playerView, 0); isFullScreen = false; if(isZoomed) { playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM); } else { playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT); } ((ImageView)playerView.findViewById(R.id.exo_controller_fullscreen)).setImageDrawable(getDrawable(R.drawable.ic_fullscreen)); mFullScreenDialog.dismiss(); } public void toggleFullScreen(View view) { if (isFullScreen) { closeFullscreenDialog(); ((ImageView)view).setImageDrawable(ContextCompat.getDrawable(stepDetailActivity.this, R.drawable.ic_fullscreen)); } else { openFullscreenDialog(); ((ImageView)view).setImageDrawable(ContextCompat.getDrawable(stepDetailActivity.this, R.drawable.ic_fullscreen_exit)); } } public void toggleZoom(View view) { if(isZoomed) { playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT); isZoomed = false; ((ImageView)view).setImageDrawable(ContextCompat.getDrawable(stepDetailActivity.this, R.drawable.ic_zoom_in)); } else { playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM); isZoomed = true; ((ImageView)view).setImageDrawable(ContextCompat.getDrawable(stepDetailActivity.this, R.drawable.ic_zoom_out)); } } @Override public void onPause() { super.onPause(); if(player != null) { position = player.getCurrentPosition(); player.release(); } } @Override public void onStop() { super.onStop(); if(player != null) { position = player.getCurrentPosition(); player.release(); } } @Override protected void onSaveInstanceState(Bundle outState) { outState.putLong(SELECTED_POSITION, position); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); position = savedInstanceState.getLong(SELECTED_POSITION, 0); if(player != null) { player.seekTo(position); player.setPlayWhenReady(true); } } }
true
0b1b4ab3556e1b14d5add9e4ce6377c7f2d51d99
Java
matheuscosantos/zup-bootcamp
/src/test/java/com/zup/mcos/nossobancodigital/controller/ClienteControllerTest.java
UTF-8
7,220
2.34375
2
[]
no_license
package com.zup.mcos.nossobancodigital.controller; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.net.URI; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class ClienteControllerTest { @Autowired private MockMvc mockMvc; @Test public void deveCriarUmCliente() throws Exception { URI uri = new URI("/api/v1/cliente"); String json = " {\n" + " \"cnh\": \"5555555555\",\n" + " \"dataDeNascimento\": \"2019-02-02\",\n" + " \"email\": \"oliveiramatheus666@gmail.com\",\n" + " \"nome\": \"Matheus\",\n" + " \"sobrenome\": \"Oliveira\"\n" + " }"; mockMvc.perform(MockMvcRequestBuilders.post(uri) .content(json) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers .status().isOk()); } @Test public void deveAdicionarEnderecoAoCadastroDeClienteComCadastroBasico() throws Exception{ URI uri = new URI("/api/v1/cliente/1/endereco"); String json = "{\n" + " \"cep\":\"12630-000\",\n" + " \"rua\":\"Travessa joao dias\",\n" + " \"bairro\":\"Centro\",\n" + " \"complemento\":\"Casa\",\n" + " \"cidade\": \"São José dos Campos\",\n" + " \"estado\": \"SP\"\n" + "}"; mockMvc.perform(MockMvcRequestBuilders.put(uri) .content(json) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers .status().isOk()); } @Test public void naoDeveAdicionarEnderecoAoCadastroDeClienteQueNaoEstejaComEstadoComCadastroBasico() throws Exception{ URI uri = new URI("/api/v1/cliente/2/endereco"); String json = "{\n" + " \"cep\":\"12630-000\",\n" + " \"rua\":\"Travessa joao dias\",\n" + " \"bairro\":\"Centro\",\n" + " \"complemento\":\"Casa\",\n" + " \"cidade\": \"São José dos Campos\",\n" + " \"estado\": \"SP\"\n" + "}"; mockMvc.perform(MockMvcRequestBuilders.put(uri) .content(json) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers .status().isBadRequest()); } @Test public void buscaClientePorId() throws Exception{ URI uri = new URI("/api/v1/cliente/1"); mockMvc.perform(MockMvcRequestBuilders.get(uri)) .andExpect(MockMvcResultMatchers.status() .isOk()); } @Test public void buscaClientePorIdQueNaoExiste() throws Exception{ URI uri = new URI("/api/v1/cliente/10"); mockMvc.perform(MockMvcRequestBuilders.get(uri)) .andExpect(MockMvcResultMatchers.status() .isNotFound()); } @Test public void buscaClientePorIdComFormatoErrado() throws Exception{ URI uri = new URI("/api/v1/cliente/10m"); mockMvc.perform(MockMvcRequestBuilders.get(uri)) .andExpect(MockMvcResultMatchers.status() .isBadRequest()); } @Test public void aprovaDadosDoCadastroEAlteraOStatusParaAceite() throws Exception{ URI uri = new URI("/api/v1/cliente/3/aprovacao"); String json = " {\n" + " \"estado\":\"ACEITE\"\n" + " }"; mockMvc.perform(MockMvcRequestBuilders.post(uri) .content(json) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers .status().isOk()); } @Test public void aprovaDadosDoCadastroEAlteraOStatusParaNaoAceite() throws Exception{ URI uri = new URI("/api/v1/cliente/3/aprovacao"); String json = "{\n" + " \"estado\":\"NAO_ACEITE\"\n" + "}"; mockMvc.perform(MockMvcRequestBuilders.post(uri) .content(json) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers .status().isOk()); } @Test public void realizaTransferenciaEntreDuasContasDoMesmoBanco() throws Exception{ URI uri = new URI("/api/v1/conta-corrente/transferencia-interna"); String json = "{\n" + " \"agenciaDeDestino\": 9711,\n" + " \"numeroDaContaDeDestino\": 12044205,\n" + " \"agenciaDaContaDeOrigem\": 9711,\n" + " \"numeroDaContaDeOrigem\": 22252525,\n" + " \"valor\": 500\n" + "}"; mockMvc.perform(MockMvcRequestBuilders.post(uri) .content(json) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers .status().isOk()); } @Test public void realizaSolicitacaoDeTransferenciaParaUmaContaDeOutroBanco() throws Exception{ URI uri = new URI("/api/v1/conta-corrente/transferencia-externa"); String json = "{\n" + " \"agenciaDeOrigem\": \"9711\",\n" + " \"contaDeOrigem\": \"22252525\",\n" + " \"agenciaDeDestino\": \"7777\",\n" + " \"codigoDoBancoDeDestino\": \"01\",\n" + " \"contaDeDestino\": \"77777777\",\n" + " \"dataDaSolicitacao\": \"2020-12-10\",\n" + " \"descricao\": \"Descrição\",\n" + " \"documento\": \"44.547.893-1\",\n" + " \"favoritado\": true,\n" + " \"nomeDoBancoDeDestino\": \"Banco do Brasil\",\n" + " \"nomeDoFavorecido\": \"Viviane\",\n" + " \"tipoDeConta\": \"CORRENTE\",\n" + " \"valor\": 300\n" + "}"; mockMvc.perform(MockMvcRequestBuilders.post(uri) .content(json) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers .status().isOk()); } }
true
41968320e65fe4de9cea2ca1ab83f544fbb8567f
Java
anabelgrau/additionalHigherGrade
/test/main/java/se/anabelandrola/saleProcess/integration/ItemDTOTest.java
UTF-8
1,948
2.96875
3
[]
no_license
package main.java.se.anabelandrola.saleProcess.integration; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ItemDTOTest { private ItemDTO itemMilk; @BeforeEach void setUp() throws Exception { itemMilk = new ItemDTO(43560294, "Milk", 10, 6, 2); } @AfterEach void tearDown() throws Exception { itemMilk = null; } @Test void testEqual() { ItemDTO itemOther = new ItemDTO(43560294, "Milk", 10, 6, 2); boolean expectedResult = true; boolean result = itemMilk.equals(itemOther); assertEquals(expectedResult, result, "Items are not equal"); } @Test void testNotEqual() { ItemDTO itemOther = new ItemDTO(43560897, "Coca cola", 2, 6, 7); boolean expectedResult = false; boolean result = itemMilk.equals(itemOther); assertEquals(expectedResult, result, "Items with different values are equal"); } @Test void testEqualIsNullItem() { ItemDTO itemOther = null; boolean expectedResult = false; boolean result = itemMilk.equals(itemOther); assertEquals(expectedResult, result, "Items equals to null"); } @Test void testEqualJavaLangObject() { Object itemOther = new Object(); boolean expectedResult = false; boolean result = itemMilk.equals(itemOther); assertEquals(expectedResult, result, "Item is equal in the java.lang.Object instance"); } @Test void testToString() { String idItem = Integer.toString(43560294); String description = "Milk"; String price = Double.toString(10.0); String vat = Integer.toString(6); String quantity = Integer.toString(2); String expectedResult = "idItem: " + idItem + ", " + "description: " + description + ", " + "price: " + price + ", " + "VAT: " + vat + ", " + "quantitySold: " + quantity + ", "; String result = itemMilk.toString(); assertEquals(expectedResult, result, "Wrong string returned by toString"); } }
true
2be6fe4b31582e0e75fc3785c03e22c93cbdc33b
Java
NCIP/stats-application-commons
/src/gov/nih/nci/caintegrator/application/workspace/WorkspaceList.java
UTF-8
1,014
2.078125
2
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
/*L * Copyright SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/stats-application-commons/LICENSE.txt for details. */ package gov.nih.nci.caintegrator.application.workspace; import gov.nih.nci.caintegrator.application.lists.UserList; import java.util.List; import java.util.ArrayList; import java.lang.Iterable; import java.util.Iterator; /** * @author prakasht * This model is used for managing the workspace during Import/Export */ public class WorkspaceList extends UserList implements Iterable { private List<UserList> folderList = new ArrayList<UserList>(); public WorkspaceList() { super(); } public WorkspaceList( String name ) { super(); setName( name ); } public void addLeaf( UserList list ) { folderList.add( list ); } public List<UserList> getFolderList() { return folderList; } public Iterator<UserList> iterator() { return folderList.iterator(); } }
true
9e6c32130c85c09e049ac98798a1a08af1a5d07d
Java
lhzheng880828/VOIPCall
/doc/libjitisi/sources/net/sf/fmj/ejmf/toolkit/util/SourcedTimerListener.java
UTF-8
195
1.75
2
[ "Apache-2.0" ]
permissive
package net.sf.fmj.ejmf.toolkit.util; import java.util.EventListener; public interface SourcedTimerListener extends EventListener { void timerUpdate(SourcedTimerEvent sourcedTimerEvent); }
true
8795ca71b648e9eac940996fc607917ef9369fd0
Java
anishp22/SOFE3650-Assignment2
/Exercise1/src/Display.java
UTF-8
120
2.625
3
[]
no_license
public class Display { public void displayItem(String itemInfo){ System.out.println(itemInfo); } }
true
cdddb40f3111c47d01522a7d8e15557c041d4e8d
Java
henriquerferrer/POOP
/Sistema.java
UTF-8
12,259
2.640625
3
[]
no_license
package poop; import java.util.ArrayList; import java.util.Collections; /** * Classe de Sistema que gere a lógica da plataforma * @author JoaquimFerrer Henrique Ferrer */ public class Sistema { private ArrayList<Inscricao> inscricoes; private ArrayList<Local> locais; private ArrayList<Pessoa> pessoas; private GestorBaseDados gestorBD; private final int percentagemGuestList = 10; private final double discontoEstExposicao = 0.1; private final int numeroMaximoInscricoes = 5; /** * */ @SuppressWarnings("unchecked") public Sistema() { this.gestorBD = new GestorBaseDados(); this.inscricoes = gestorBD.loadInscricoes(); this.locais = gestorBD.loadLocais(); this.pessoas = gestorBD.loadPessoas(); //Faz sort por ID (Data de criaçao) Collections.sort(inscricoes); } //TODO //CONFIRM THAT YOU ARE NOT CREATING THE SAME PEOPLE OR LOCAL TWICE /** *Cria um professor * @param tipoProfessor Tipo de professor. * @param nome Nome. * @param numCc Número de cartão de cidadão. * @param password Password para a plataforma. * @param perfil Perfil. */ public boolean criarProfessor(TipoProfessor tipoProfessor, String nome, String numCc, String password, Perfil perfil) { if(getPessoaByCC(numCc) == null) { Professor p = new Professor(tipoProfessor, nome, numCc, password, perfil); pessoas.add(p); gestorBD.savePessoa(p); return true; } else { return false; } } /** * Cria um Funcionário * @param tipoFuncionario Tipo de funcionário. * @param nome Nome. * @param numCc Número de cartão de cidadão. * @param password Password usada para a plataforma * @param perfil Perdil. */ public boolean criarFuncionario(TipoFuncionario tipoFuncionario, String nome, String numCc, String password, Perfil perfil) { if(getPessoaByCC(numCc) == null) { Funcionario f = new Funcionario( tipoFuncionario, nome, numCc, password, perfil); pessoas.add(f); gestorBD.savePessoa(f); return true; } else { return false; } } /** * Cria um Estudante * @param curso Curso do estudante. * @param nome Nome. * @param numCc Número de cartão de cidadão. * @param password Password usada para a plataforma. * @param perfil Perfil. */ public boolean criarEstudante(CursoDei curso , String nome, String numCc, String password, Perfil perfil) { if(getPessoaByCC(numCc) == null) { Estudante e = new Estudante( curso , nome, numCc, password, perfil); pessoas.add(e); gestorBD.savePessoa(e); return true; } else { return false; } } /** * Cria um Bar * @param coordenadas Coordenadas do Local. * @param lotacao Lotaçao máxima do bar. * @param consumoMinimo Consumo mínimo para entrar no bar. */ public void criarBar(String coordenadas, int lotacao, double consumoMinimo) { Bar b = new Bar( coordenadas, lotacao, consumoMinimo); locais.add(b); gestorBD.saveLocal(b); } /** * Cria uma exposição. * @param coordenadas Coordenadas do local. * @param formaArtistica Forma artística da exposição. * @param custoBilhete Custo de cada builhete para a exposição. */ public void criarExposicao(String coordenadas, String formaArtistica, double custoBilhete) { Exposicao e = new Exposicao(coordenadas, formaArtistica, custoBilhete); locais.add(e); gestorBD.saveLocal(e); } /** * Cria um Jardim. * @param coordenadas Coordenadas do Local. * @param area �rea do jardim. */ public void criarJardim(String coordenadas, double area) { Jardim j = new Jardim(coordenadas, area); locais.add(j); gestorBD.saveLocal(j); } /** * Cria uma área desportiva * @param coordenadas Coordenadas do Local. * @param desportos Desportos que se praticam na área desportiva. */ public void criarAreaDesportiva(String coordenadas, ArrayList<String> desportos) { AreaDesportiva a = new AreaDesportiva(coordenadas, desportos); locais.add(a); gestorBD.saveLocal(a); } /** * Retorna os locais possiveis * @return Locais */ public ArrayList<Local> getLocais() { return locais; } /** * Retorna a locatação máxima dum bar. * @param bar Bar. * @return */ public int getLotacaoDeBar(Bar bar) { return bar.getLotacao(); } /** * Retorna pessoas inscritas no local. A ordem é não é especificada. * @param local Local. * @return Pessoas inscritas no local. */ public ArrayList<Pessoa> getIncritosEmLocal(Local local){ ArrayList<Pessoa> helper = new ArrayList<Pessoa>(); for(int i = 0; i < inscricoes.size(); i++) { if (inscricoes.get(i).getLocal().equals(local)) { helper.add(inscricoes.get(i).getPessoa()); } } return helper; } /** * Cria uma inscrição duma pessoa num local. Verifica se a pessoa já tem 5 inscrições, se já tem uma inscrição nesse Local, ou se o sítio onde se vai inscrever está cheio. * @param pessoa Pessoa que se está a inscrever. * @param local Local onde se vai inscrever. * @return Se a inscrição foi bem sucedida. */ public boolean increverPessoa(Pessoa pessoa, Local local) { int numInscricoes = 0; for(int i = 0; i < inscricoes.size(); i++) { if(inscricoes.get(i).getPessoa().equals(pessoa)) { if(numInscricoes + 1 > numeroMaximoInscricoes) { return false; //Quer dizer que ja te inscreveste em 5 locais e nao podes inscrever e mais nenhum } numInscricoes++; } if(inscricoes.get(i).getPessoa().equals(pessoa) && inscricoes.get(i).getLocal().equals(local)) { return false; } } if(local.isBar() && ((Bar)local).getLotacao() < getNInscritosLocal(local)) { return false; } Inscricao i = new Inscricao(pessoa, local, inscricoes.size()); inscricoes.add(i); gestorBD.saveInscricao(i); return true; } /** * Retorna os locais ordenados por número de isncrições que têm. Utiliza um selection sort. * @return Locais ordenados. */ public ArrayList<Local> getLocaisOrdenados() { int counter = 0, max = -1; ArrayList<Local> helperLocais = new ArrayList<Local>(); ArrayList<Local> finalLocais = new ArrayList<Local>(); ArrayList<Integer> helperInscritos = new ArrayList<Integer>(); for(int i = 0; i < locais.size(); i++) { for(int p = 0; p < inscricoes.size(); p++) { if(locais.get(i).equals(inscricoes.get(p).getLocal())) { counter++; } } helperLocais.add(locais.get(i)); helperInscritos.add(counter); counter = 0; } //Ha alternativa for(Integer o: helperInscritos) { if(o > max) { max = o; } } while(finalLocais.size() < locais.size()) { for(int g = 0; g < helperInscritos.size(); g++) { if(helperInscritos.get(g) == max) { finalLocais.add(helperLocais.get(g)); } } int maxHelper = -1; for(int o = 0; o < helperInscritos.size(); o++) { if(helperInscritos.get(o) > maxHelper && helperInscritos.get(o) < max) { maxHelper = helperInscritos.get(o); } } max = maxHelper; } return finalLocais; //Alternativa 'listToSort.sort(Comparator.comparing(listWithOrder::indexOf));' } //TODO: Add polimorfism to this. Remeber to remove the discounts with students and expositions /** Obtém as receitas das inscrições feitas até à data. * @return Valor das receitas. */ public double getMinReceitas() { double finalReceitas = 0; for(int p = 0; p < inscricoes.size(); p++) { if(inscricoes.get(p).getLocal().isBar()) { finalReceitas += inscricoes.get(p).getLocal().getCustoMinimo(); } if(inscricoes.get(p).getLocal().isExposicao() && inscricoes.get(p).getPessoa().isEstudante()) { finalReceitas += inscricoes.get(p).getLocal().getCustoMinimo() * (1-discontoEstExposicao); } if(inscricoes.get(p).getLocal().isExposicao() && !(inscricoes.get(p).getPessoa().isEstudante())) { finalReceitas += inscricoes.get(p).getLocal().getCustoMinimo(); } } return finalReceitas; } /** * Obtém o tamanho da guest list dum bar. * @param bar * @return Tamanho da guest list. */ public int getGuestListSize(Bar bar) { int limiteTamanho = (int)(bar.getLotacao()*(percentagemGuestList/100.0)); return limiteTamanho; } /** * Gera a guest list dum bar. Dá prioridade a pessoas com perfil boémio e depois a pessoas que se inscreveram antes. * @param bar Bar * @return Pessoas na Guest list. */ public ArrayList<Pessoa> getGuestList(Bar bar){ ArrayList<Pessoa> finalGuestList = new ArrayList<Pessoa>(); int limiteTamanho = getGuestListSize(bar), tamanhoAtual=0; for(int p = 0; p < inscricoes.size(); p++) { if(limiteTamanho > tamanhoAtual) { if(inscricoes.get(p).getLocal().equals(bar) && inscricoes.get(p).getPessoa().getPerfil() == Perfil.BOEMIO) { finalGuestList.add(inscricoes.get(p).getPessoa()); tamanhoAtual++; } } else { break; } } for(int p = 0; p < inscricoes.size(); p++) { if(limiteTamanho > tamanhoAtual) { if(inscricoes.get(p).getLocal().equals(bar) && !(inscricoes.get(p).getPessoa().getPerfil() == Perfil.BOEMIO)){ finalGuestList.add(inscricoes.get(p).getPessoa()); System.out.println(inscricoes.get(p).getPessoa()); tamanhoAtual++; } } else { break; } } return finalGuestList; } /** * Verifica se um sítio não pode conter mais inscrições * @param place Local * @return Se não pode conter mais inscrições. */ public boolean isPlaceFull(Local place){ int counter = 0; if(place.isBar()) { for(int p = 0; p < inscricoes.size(); p++) { if(inscricoes.get(p).getLocal().equals(place)) { if(counter < ((Bar)place).getLotacao()) { counter++; } else { return true; } } } } else{ return false; } return false; } /** * Retorna o número de inscritos num local. * @param l Local * @return Número de inscritos. */ public int getNInscritosLocal(Local l) { int counter = 0; for(int i = 0; i < inscricoes.size(); i++) { if(inscricoes.get(i).getLocal().equals(l)) { counter++; } } return counter; } /** * Conta isncrições duma Pessoa * @param pessoa Pessoa * @return Número de inscrições. */ public int contarInscricoes(Pessoa pessoa) { int counter = 0; for(int p = 0; p < inscricoes.size(); p++) { if(inscricoes.get(p).getPessoa().equals(pessoa)) { counter++; } } return counter; } /** * Retorna os Locais em que uma pessoa se inscreveu. * @param pessoa Pessoa. * @return Lista de locais inscritos. */ public ArrayList<Local> getLocaisInscritos(Pessoa pessoa) { ArrayList<Local> helper = new ArrayList<Local>(); for(int i = 0; i < inscricoes.size(); i++) { if (inscricoes.get(i).getPessoa().equals(pessoa)) { helper.add(inscricoes.get(i).getLocal()); } } return helper; } /** * Descobre uma pessoa a quem pertença um numero de cartao de cidadão. Caso não exista retorna null. * @param numCC Número de cartão de cidadão. * @return Pessoa ou null se numCC não existir. */ public Pessoa getPessoaByCC(String numCC) { for(Pessoa p : pessoas) { if(p.getNumCc().equals(numCC)){ return p; } } return null; } /** * Verifica se a Pessoa associada a um número de cartão de cidadão tem a sua password igual à password passada. * @param numCC Número de cartão de cidadão. * @param password Password * @return Pessoa ou null se o número de cartão de cidadão não corresponder à password. */ public Pessoa autenticar(String numCC, String password) { Pessoa p = getPessoaByCC(numCC); if(p == null) { return null; } if(p.getPassword().equals(password)) { return p; } return null; } }
true
56e9f06f4cf6b02da35178422da7f901c9c49e8d
Java
xopheS/DrivingTony
/DrivingTony/src/main/java/ch/epfl/cs107/play/game/actor/general/Crate3.java
UTF-8
2,872
2.375
2
[]
no_license
package ch.epfl.cs107.play.game.actor.general; import java.awt.Color; import ch.epfl.cs107.play.game.actor.Actor; import ch.epfl.cs107.play.game.actor.ActorGame; import ch.epfl.cs107.play.game.actor.GameEntity; import ch.epfl.cs107.play.game.actor.ImageGraphics; import ch.epfl.cs107.play.game.actor.santa.BeeMinion; import ch.epfl.cs107.play.math.BasicContactListener; import ch.epfl.cs107.play.math.Contact; import ch.epfl.cs107.play.math.ContactListener; import ch.epfl.cs107.play.math.Part; import ch.epfl.cs107.play.math.PartBuilder; import ch.epfl.cs107.play.math.Polygon; import ch.epfl.cs107.play.math.Transform; import ch.epfl.cs107.play.math.Vector; import ch.epfl.cs107.play.window.Canvas; public class Crate3 extends GameEntity implements Actor { private ImageGraphics crateImage; private boolean hit = false; private BasicContactListener listener; private Part cratePart; private boolean spawnedByBee = false; public Crate3(ActorGame game, boolean fixed, Vector position) { super(game, fixed, position); PartBuilder partBuilder = getE().createPartBuilder(); Polygon polygon = new Polygon(new Vector(0.0f, 0.0f), new Vector(1.0f, 0.0f), new Vector(1.0f, 1.0f), new Vector(0.0f, 1.0f)); partBuilder.setShape(polygon); cratePart = partBuilder.build(); crateImage = new ImageGraphics("crate.3.png", 1, 1); crateImage.setParent(getE()); listener = new BasicContactListener(); getE().addContactListener(listener); } public Crate3(ActorGame game, boolean fixed, Vector position, BeeMinion owner) { super(game, fixed, position); spawnedByBee = true; PartBuilder partBuilder = getE().createPartBuilder(); Polygon polygon = new Polygon(new Vector(0.0f, 0.0f), new Vector(1.0f, 0.0f), new Vector(1.0f, 1.0f), new Vector(0.0f, 1.0f)); partBuilder.setShape(polygon); partBuilder.build(); crateImage = new ImageGraphics("crate.3.png", 1, 1); crateImage.setParent(getE()); getE().setPosition(new Vector(owner.getPosition().x, owner.getPosition().y)); listener = new BasicContactListener(); getE().addContactListener(listener); } public void update(float deltaTime) { int numberOfCollisions = listener.getEntities().size(); if (numberOfCollisions > 0) { hit = true; destroy(); getA().removeActor(this); } } public void draw(Canvas canvas) { crateImage.draw(canvas); } public void destroy() { // By default , actors have nothing to destroy getE().destroy(); } @Override public Vector getVelocity() { // TODO Auto-generated method stub return getE().getVelocity(); } @Override public Transform getTransform() { // TODO Auto-generated method stub return getE().getTransform(); } public Part getCratePart() { return cratePart; } public boolean getHit() { return hit; } public boolean getSpawnedByBee() { return spawnedByBee; } }
true
f66544106931c8b3100467769be0086584fd53a4
Java
smileszx/coffeebaby
/java-design-pattern/src/test/java/com/coffee/baby/pattern/ThreadTest.java
UTF-8
2,835
4.03125
4
[ "Apache-2.0" ]
permissive
package com.coffee.baby.pattern; public class ThreadTest{ public static void main(String[] args) { Singleton singleton=Singleton.getInstance(); System.out.println(singleton); } } class Singleton { private String str; private static volatile Singleton singleton;//第二层锁,volatile关键字禁止指令重排 private Singleton(){ str="hello"; } public String getStr() { return str; } //DCL public static Singleton getInstance() { if(singleton==null){//第一层检查,检查是否有引用指向对象,高并发情况下会有多个线程同时进入 synchronized (Singleton.class){//第一层锁,保证只有一个线程进入 //双重检查,防止多个线程同时进入第一层检查(因单例模式只允许存在一个对象,故在创建对象之前无引用指向对象,所有线程均可进入第一层检查) //当某一线程获得锁创建一个Singleton对象时,即已有引用指向对象,singleton不为空,从而保证只会创建一个对象 //假设没有第二层检查,那么第一个线程创建完对象释放锁后,后面进入对象也会创建对象,会产生多个对象 if(singleton==null){//第二层检查 //volatile关键字作用为禁止指令重排,保证返回Singleton对象一定在创建对象后 singleton=new Singleton(); //singleton=new Singleton语句为非原子性,实际上会执行以下内容: //(1)在堆上开辟空间;(2)属性初始化;(3)引用指向对象 //假设以上三个内容为三条单独指令,因指令重排可能会导致执行顺序为1->3->2(正常为1->2->3),当单例模式中存在普通变量需要在构造方法中进行初始化操作时, // 单线程情况下,顺序重排没有影响;但在多线程情况下,假如线程1执行singleton=new Singleton()语句时先1再3,由于系统调度线程2的原因没来得及执行步骤2, // 但此时已有引用指向对象也就是singleton!=null,故线程2在第一次检查时不满足条件直接返回singleton,此时singleton为null(即str值为null) //volatile关键字可保证singleton=new Singleton()语句执行顺序为123,因其为非原子性依旧可能存在系统调度问题(即执行步骤时被打断), // 但能确保的是只要singleton!=0,就表明一定执行了属性初始化操作;而若在步骤3之前被打断,此时singleton依旧为null,其他线程可进入第一层检查向下执行创建对象 } } } return singleton; } }
true
b1ac20498f88718fd4a7aa44ca4dd3145f2d397a
Java
backqwe/personality-server
/personality-client/src/main/java/org/olympos/cloud/client/configuration/ApiConfig.java
UTF-8
813
1.898438
2
[]
no_license
package org.olympos.cloud.client.configuration; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.util.concurrent.ConcurrentHashMap; /** * ApiConfig * * @Describe: * @Author Chanse Hao * @Date 2021-05-22 11:52 */ @PropertySource(value = {"classpath:ApiConfig.yml", "classpath:ApiConfig.yaml", "classpath:ApiConfig.properties"}, ignoreResourceNotFound = true, encoding = "utf-8", factory = ConfigurationFactory.class) @ConfigurationProperties(prefix = "api", ignoreInvalidFields = true) @Component @Data public class ApiConfig implements Cloneable { private ConcurrentHashMap<String,String> enhances; }
true
e1c14b09307edcf68add21d08035ba8fc6542972
Java
forec1/Evolutionary-Computation
/SimulatedAnnealing/src/main/java/hr/fer/zemris/optjava/dz3/tempschedule/GeometricTempSchedule.java
UTF-8
910
3.109375
3
[]
no_license
package hr.fer.zemris.optjava.dz3.tempschedule; public class GeometricTempSchedule implements ITempSchedule{ private double alpha; private double tInitial; private double tCurrent; private int innerLimit; private int outerLimit; private int innerCnt; private int outerCnt; public GeometricTempSchedule(double alpha, double tInitial, int innerLimit, int outerLimit) { this.alpha = alpha; this.tInitial = tInitial; this.innerLimit = innerLimit; this.outerLimit = outerLimit; this.tCurrent = this.tInitial; this.innerCnt = this.outerCnt = 0; } public double getNextTemperature() { innerCnt++; if(outerCnt == outerLimit) { return -100; } if(innerCnt == innerLimit) { tCurrent = alpha * tCurrent; innerCnt = 0; outerCnt++; } return tCurrent; } public int getInnerLoopCounter() { return innerCnt; } public int getOuterLoopCounter() { return outerCnt; } }
true
50fa559d1ac839e18ce4f3e3abd4adf324fcfed7
Java
Anymous526/Hera
/Operation/src/main/java/com/justinmobile/bmp/pos/mina/branch/PosManagerBrancherImpl.java
UTF-8
1,695
2.125
2
[]
no_license
package com.justinmobile.bmp.pos.mina.branch; import java.lang.reflect.Method; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.justinmobile.bmp.pos.mina.dto.PosManagerDto; import com.justinmobile.bmp.pos.mina.dto.field.Field; import com.justinmobile.bmp.pos.mina.dto.field.NumberToStriField; import com.justinmobile.bmp.pos.mina.handler.AbstractMessageHandler; import com.justinmobile.bmp.pos.mina.request.PosRequestCode; import com.justinmobile.bmp.pos.mina.request.PosRequestCodeAnnotation; import com.justinmobile.bmp.pos.mina.service.PosAppVersionPorcesser; @Service("posManagerBrancher") public class PosManagerBrancherImpl extends AbstractMessageHandler implements PosManagerBrancher{ @Autowired private PosAppVersionPorcesser posAppVersionPorcesser; @Override public PosManagerDto process(PosManagerDto message) { Map<Byte,Field> map=message.getFields(); Byte bb=0x00; String code=((NumberToStriField)map.get(bb)).getStr(); PosRequestCode requestCode=PosRequestCode.get(code); Method method = this.messageMethodMap.get(requestCode); try { return (PosManagerDto) method.invoke(this, message); } catch (Exception e) { e.printStackTrace(); return message; } } @PosRequestCodeAnnotation(PosRequestCode.APP_VERSION_RESP) public PosManagerDto appVsersionResponse(PosManagerDto message){ return posAppVersionPorcesser.appVsersionResponse(message); } @PosRequestCodeAnnotation(PosRequestCode.APP_VERSION_DOWNLOAD) public PosManagerDto appVsersionDownload(PosManagerDto message){ return posAppVersionPorcesser.appVsersionDownload(message); } }
true
61787f01cb3dd87afa442af920ef16bffbd2b37f
Java
MISAEL-HB/SoccerMatch-BackEnd
/src/main/java/com/soccermatch/SoccerMatch/repository/IMembershipsRepository.java
UTF-8
316
1.726563
2
[]
no_license
package com.soccermatch.SoccerMatch.repository; import com.soccermatch.SoccerMatch.entity.Memberships; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface IMembershipsRepository extends JpaRepository<Memberships,Integer> { }
true
de6897607d56637ba837f2e529f201e5a9971299
Java
Byron4j/CookBook
/src/main/java/org/byron4j/cookbook/netty/apidemo/serializer/SerializerAlgorithm.java
UTF-8
221
1.703125
2
[ "MIT" ]
permissive
package org.byron4j.cookbook.netty.apidemo.serializer; /** * 定义了一系列的序列化算法 */ public interface SerializerAlgorithm { /** * json 序列化标识 */ byte JSON = 1; }
true
1fdc35ff726fa6f8ed0c744a45b0ba904feafd99
Java
liran420/MultithreadedServer
/src/edu/upenn/cis/cis455/servlets/MyHttpServletRequest.java
UTF-8
13,946
2.03125
2
[]
no_license
package edu.upenn.cis.cis455.servlets; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.Socket; import java.security.Principal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TimeZone; import java.util.Vector; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; //import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ParseException; import edu.upenn.cis.cis455.webserver.HttpServerConfig; /** * This is the class implemented from HttpServletRequest for Servlets * {@inheritDoc} * @author cis555 * */ public class MyHttpServletRequest implements HttpServletRequest{ String encoding = "ISO-8859-1"; MyHttpSession session = null; private String method = null; private Properties parameters = null; private Properties attributes = null; //private String serverName = null; private String protocol = null; private int port; BufferedReader bufferedReader = null; String servletPath = null; String pathInfo = null; String requestURL = null; InetAddress address = null; String fullPath = null; Socket clientSocket = null; HttpServerConfig c = null; String QueryString; Cookie[] cookieArray = null; String sessionID = null; boolean sessionInCookie = false; boolean sessionInURL = false; MyHttpServletResponse responseObject = null; private long sessionTimeout = -1; private String queryString = ""; String contentType = "text/html"; Map<String, String> initMap; Map<String, String> headerMap; public MyHttpServletRequest(HttpServerConfig c, Socket s, Map<String, String> initMap, Map<String, String> headerMap, String queryString, long sessionTimeout) throws IOException { this.sessionTimeout = sessionTimeout * 60; // time out in minutes this.parameters = new Properties(); this.attributes = new Properties(); this.clientSocket = s; this.method = initMap.get("Type"); this.protocol = initMap.get("Protocol"); this.requestURL = initMap.get("Path"); this.fullPath = c.rootDir + requestURL; this.queryString = queryString; this.address = s.getInetAddress(); this.c = c; this.port = s.getLocalPort(); this.initMap = initMap; this.headerMap = headerMap; getCookiesFromHeader(); // for(String str : headerMap.keySet()) // System.out.println(str + ": " + headerMap.get(str)); // System.out.println("----Request End-----"); } /** * Method used in constructor to get cookies from headers in request */ private void getCookiesFromHeader(){ String cookiesString = headerMap.get("cookie"); List<Cookie> cookieList = new ArrayList<>(); if (cookiesString != null) { String[] cookiesStringList = cookiesString.split(";"); for (String cookie : cookiesStringList) { String cookiePair = cookie.trim(); // cookie pairs String[] cookieString = cookiePair.split("="); cookieList.add(new Cookie(cookieString[0], cookieString[1])); } } cookieArray = new Cookie[cookieList.size()]; for(int i = 0; i < cookieList.size(); i++) cookieArray[i] = cookieList.get(i); for(Cookie c : cookieArray){ if(c.getName().equals("SESSIONID")) { String id = c.getValue(); MyHttpSession s = ServletContainer.sessionCache.get(id); if( s == null ) continue; if(s.isValid()) { this.session = s; } // else { // ServletContainer.sessionCache.remove(id); // } } } ServletContainer.removeInvalidSessions(); // remove invalid sessions periodically } /** * Method to add Session from the cookie got in headers * @param s */ public void addSession(MyHttpSession s) { session = s; sessionID = s.getId(); } /** * {@inheritDoc} */ @Override public Object getAttribute(String key) { key = key.toLowerCase(); return attributes.get(key); } /** * {@inheritDoc} */ @Override public Enumeration getAttributeNames() { Set<Object> keys = attributes.keySet(); Vector<Object> atts = new Vector<Object>(keys); return atts.elements(); } /** * {@inheritDoc} */ @Override public String getCharacterEncoding() { return encoding; } /** * {@inheritDoc} */ @Override public int getContentLength() { if(headerMap.get("content-length") == null) return -1; else return Integer.parseInt(headerMap.get("content-length")); } /** * {@inheritDoc} */ @Override public String getContentType() { return "text/html"; } /** * {@inheritDoc} */ @Override public ServletInputStream getInputStream() throws IOException { // Implementation Not Required return null; } /** * {@inheritDoc} */ @Override public String getLocalAddr() { return c.serverIP.toString(); } /** * {@inheritDoc} */ @Override public String getLocalName() { return c.serverName; } /** * {@inheritDoc} */ @Override public int getLocalPort() { return port; } /** * {@inheritDoc} */ @Override public Locale getLocale() { if(headerMap.get("accept-language") != null) { String s = headerMap.get("accept-language"); return new Locale(s); } return Locale.US; } /** * {@inheritDoc} */ @Override public Enumeration getLocales() { // Implementation Not Required return null; } /** * {@inheritDoc} */ @Override public String getParameter(String key) { key = key.toLowerCase(); return parameters.getProperty(key); } /** * {@inheritDoc} */ @Override public Map getParameterMap() { return parameters; } /** * {@inheritDoc} */ @Override public Enumeration getParameterNames() { Set<Object> keys = parameters.keySet(); Vector<Object> atts = new Vector<Object>(keys); return atts.elements(); } /** * {@inheritDoc} */ @Override public String[] getParameterValues(String key) { key = key.toLowerCase(); List<String> temp = (List<String>)parameters.get(key); if(temp == null) { return null; } String[] res = new String[temp.size()]; for(int i = 0; i < res.length; i++) { res[i] = new String(temp.get(i)); } return res; } /** * {@inheritDoc} */ @Override public String getProtocol() { return protocol; } /** * {@inheritDoc} */ @Override public BufferedReader getReader() throws IOException { InputStreamReader reader= new InputStreamReader(clientSocket.getInputStream()); this.bufferedReader = new BufferedReader(reader); return this.bufferedReader; } /** * {@inheritDoc} */ @Override public String getRealPath(String arg0) { // TODO Auto-generated method stub return null; } /** * {@inheritDoc} */ @Override public String getRemoteAddr() { return address.toString(); } /** * {@inheritDoc} */ @Override public String getRemoteHost() { return clientSocket.toString(); } /** * {@inheritDoc} */ @Override public int getRemotePort() { return clientSocket.getPort(); } /** * {@inheritDoc} */ @Override public RequestDispatcher getRequestDispatcher(String arg0) { // Implementation Not Required return null; } /** * {@inheritDoc} */ @Override public String getScheme() { return "http"; } /** * {@inheritDoc} */ @Override public String getServerName() { return c.hostName; } /** * {@inheritDoc} */ @Override public int getServerPort() { return port; } /** * {@inheritDoc} */ @Override public boolean isSecure() { return false; } /** * {@inheritDoc} */ @Override public void removeAttribute(String key) { key = key.toLowerCase(); attributes.remove(key); } /** * {@inheritDoc} */ @Override public void setAttribute(String key, Object val) { key = key.toLowerCase(); attributes.put(key, val); } /** * {@inheritDoc} */ @Override public void setCharacterEncoding(String encoding) throws UnsupportedEncodingException { this.encoding = encoding; } /** * {@inheritDoc} */ @Override public String getAuthType() { return BASIC_AUTH; } /** * {@inheritDoc} */ @Override public String getContextPath() { return ""; } /** * {@inheritDoc} */ @Override public Cookie[] getCookies() { return cookieArray; } /** * {@inheritDoc} */ @Override public long getDateHeader(String key) { key = key.toLowerCase(); if(headerMap.get(key) == null) return -1; String date = headerMap.get(key); SimpleDateFormat f1 = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z"); SimpleDateFormat f2 = new SimpleDateFormat("EEEEE, dd-MMM-yy hh:mm:ss z"); SimpleDateFormat f3 = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy z"); f1.setTimeZone(TimeZone.getTimeZone("GMT")); f2.setTimeZone(TimeZone.getTimeZone("GMT")); f3.setTimeZone(TimeZone.getTimeZone("GMT")); Date d = null; try { if(f1.parse(date)!=null) { d = f1.parse(date); return d.getTime(); } else if(f2.parse(date)!=null) { d=f2.parse(date); return d.getTime(); } else{ d=f3.parse(date); return d.getTime(); } } catch (java.text.ParseException e) { HttpErrorLog.addError(e.getMessage() + "\n\n"); return -1; } //return -1; } /** * {@inheritDoc} */ @Override public String getHeader(String key) { key = key.toLowerCase(); return headerMap.get(key); } /** * {@inheritDoc} */ @Override public Enumeration getHeaderNames() { Set<String> keys = headerMap.keySet(); Vector<Object> atts = new Vector<Object>(keys); return atts.elements(); } /** * {@inheritDoc} */ @Override public Enumeration getHeaders(String key) { List<String> arr = new ArrayList<String>(); arr.add(headerMap.get(key)); Enumeration<String> e = Collections.enumeration(arr); return e; } /** * {@inheritDoc} */ @Override public int getIntHeader(String key) throws NumberFormatException { key = key.toLowerCase(); if(!headerMap.containsKey(key)) { return -1; } return Integer.parseInt(headerMap.get(key)); } /** * {@inheritDoc} */ @Override public String getMethod() { return method; } /** * {@inheritDoc} */ @Override public String getPathInfo() { String path = initMap.get("Path"); String res = ServletContainer.getPathInfo(path); return res; } /** * {@inheritDoc} */ @Override public String getPathTranslated() { // Deprecated return null; } /** * {@inheritDoc} */ @Override public String getQueryString() { if(initMap.get("Type").equalsIgnoreCase("GET")) return queryString; else return ""; } /** * {@inheritDoc} */ @Override public String getRemoteUser() { return null; } /** * {@inheritDoc} */ @Override public String getRequestURI() { return requestURL; } /** * {@inheritDoc} */ @Override public StringBuffer getRequestURL() { StringBuffer b = new StringBuffer(); b.append("http://"+c.hostName+":"+c.port+""+requestURL); return b; } /** * {@inheritDoc} */ @Override public String getRequestedSessionId() { return sessionID; } /** * {@inheritDoc} */ @Override public String getServletPath() { return null; } /** * This is the method to add response object into request * @param responseObject */ public void setResponseObject(MyHttpServletResponse responseObject){ this.responseObject = responseObject; } /** * {@inheritDoc} */ @Override public HttpSession getSession() { if(session==null){ session = new MyHttpSession(sessionTimeout); StringBuilder message = new StringBuilder(); Cookie c = new Cookie("SESSIONID",session.getId()); c.setMaxAge(session.getMaxInactiveInterval()); responseObject.addCookie(c); synchronized(ServletContainer.sessionCache){ ServletContainer.sessionCache.put(session.getId(),session); ServletContainer.sessionCache.notify(); } } return session; } /** * {@inheritDoc} */ @Override public HttpSession getSession(boolean toCreate) { if(session == null && toCreate) { session = new MyHttpSession(sessionTimeout); StringBuilder message = new StringBuilder(); Cookie c = new Cookie("SESSIONID",session.getId()); c.setMaxAge(session.getMaxInactiveInterval()); responseObject.addCookie(c); synchronized(ServletContainer.sessionCache){ ServletContainer.sessionCache.put(session.getId(),session); ServletContainer.sessionCache.notify(); } } return session; } /** * {@inheritDoc} */ @Override public Principal getUserPrincipal() { // Deprecated return null; } /** * {@inheritDoc} */ @Override public boolean isRequestedSessionIdFromCookie() { // TODO Auto-generated method stub return false; } /** * {@inheritDoc} */ @Override public boolean isRequestedSessionIdFromURL() { return false; } /** * {@inheritDoc} */ @Override public boolean isRequestedSessionIdFromUrl() { return false; } /** * {@inheritDoc} */ @Override public boolean isRequestedSessionIdValid() { if(session!=null) { return session.isValid(); } else { return false; } } /** * {@inheritDoc} */ @Override public boolean isUserInRole(String arg0) { // Deprecated return false; } }
true
b883d9efe2975a93a7c32aafe0a9d6b4d49332f0
Java
shalmal90/shalmal
/stringun.java
UTF-8
668
3.21875
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class stringun { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub System.out.println("Enter the string:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); char[] ch = s.toCharArray(); char[]ch1 = s.toCharArray(); for(int i=0;i<s.length();i++) { for(int j = i+1;j<s.length();j++) { if (ch[i] == ch1[j]) { if(i!=j) System.out.println("Match Found: Not a Unique String:- "+i+" and "+j); } } } } }
true
0ec1d5594c977b8998116064ad10e6bef09a191a
Java
PavelKalesnikau/JavaRushTasks
/4.JavaCollections/src/com/javarush/task/task33/task3310/Solution.java
UTF-8
1,957
3.078125
3
[]
no_license
package com.javarush.task.task33.task3310; import com.javarush.task.task33.task3310.strategy.HashMapStorageStrategy; import com.javarush.task.task33.task3310.strategy.StorageStrategy; import java.util.Date; import java.util.HashSet; import java.util.Set; public class Solution { public static void main(String[] args) { new Solution().testStrategy(new HashMapStorageStrategy(), 10000); } public static Set<Long> getIds(Shortener shortener, Set<String> strings) { Set<Long> keys = new HashSet<>(strings.size()); for (String string : strings) { keys.add(shortener.getId(string)); } return keys; } public static Set<String> getStrings(Shortener shortener, Set<Long> keys) { Set<String> strings = new HashSet<>(keys.size()); for (Long key : keys) { strings.add(shortener.getString(key)); } return strings; } public static void testStrategy(StorageStrategy strategy, long elementsNumber) { Helper.printMessage(strategy.getClass().getSimpleName()); Set<String> strings = new HashSet<>(); for (long i = 0; i < elementsNumber; i++) { String string = Helper.generateRandomString(); strings.add(string); } Shortener shortener = new Shortener(strategy); Date startTime1 = new Date(); Set<Long> keys = getIds(shortener, strings); Date endTime1 = new Date(); System.out.println(String.valueOf(endTime1.getTime() - startTime1.getTime())); Date startTime2 = new Date(); Set<String> strings_copy = getStrings(shortener, keys); Date endTime2 = new Date(); System.out.println(String.valueOf(endTime2.getTime() - startTime2.getTime())); if (strings.size() == strings_copy.size()) Helper.printMessage("Тест пройден."); else Helper.printMessage("Тест не пройден."); } }
true
78d69a9fce21bbac483a85966d19dda3a7f5063a
Java
Francoisleche/GouiranLinkProject
/app/src/main/java/com/gouiranlink/franois/gouiranlinkproject/InsciptionConnexion/SignUp.java
UTF-8
8,560
2.09375
2
[]
no_license
package com.gouiranlink.franois.gouiranlinkproject.InsciptionConnexion; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.View; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import com.gouiranlink.franois.gouiranlinkproject.R; import com.gouiranlink.franois.gouiranlinkproject.ToolsClasses.PostRequest; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SignUp extends AppCompatActivity { private String json = null; private String name = null; private String surname = null; private String email = null; private String password = null; private String passwordConfirmation = null; private String phoneNumber = null; private String codepostal = null; private PostRequest postRequest = null; private EditText surnameEditText; private EditText nameEditText; private EditText emailEditText; private EditText passwordEditText; private EditText passwordConfirmationEditText; private EditText phoneNumberEditText; private EditText codepostalEditText; private boolean isEmailValid(String email) { String EmailPattern = "[_A-Za-z0-9-\\\\+.]+@[A-Za-z0-9-]+\\.[A-Za-z]+"; final Pattern pattern = Pattern.compile(EmailPattern); final Matcher matcher = pattern.matcher(email); return (matcher.matches()); } private boolean isCodePostalValid(String codepostal) { String CodePostalPattern = "[0-9]+"; final Pattern pattern = Pattern.compile(CodePostalPattern); final Matcher matcher = pattern.matcher(codepostal); return (matcher.matches()); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); surnameEditText = (EditText) findViewById(R.id.surname); nameEditText = (EditText) findViewById(R.id.name); emailEditText = (EditText) findViewById(R.id.email_address); passwordEditText = (EditText) findViewById(R.id.password); passwordConfirmationEditText = (EditText) findViewById(R.id.password_confirmation); phoneNumberEditText = (EditText) findViewById(R.id.phone_number); codepostalEditText = (EditText) findViewById(R.id.post_code); } public void onClick(View v) { View focusView = null; Boolean cancel = false; String resp = null; surname = surnameEditText.getText().toString(); name = nameEditText.getText().toString(); email = emailEditText.getText().toString(); password = passwordEditText.getText().toString(); passwordConfirmation = passwordConfirmationEditText.getText().toString(); phoneNumber = phoneNumberEditText.getText().toString(); codepostal = codepostalEditText.getText().toString(); if (!isEmailValid(email)) { emailEditText.setError(getString(R.string.invalid_email)); focusView = emailEditText; cancel = true; focusView.requestFocus(); } if (!password.equals(passwordConfirmation)) { passwordEditText.setError(getString(R.string.non_equal_password)); focusView = passwordEditText; cancel = true; focusView.requestFocus(); } if (password == null || password.equals("")) { passwordEditText.setError(getString(R.string.necessary_field)); cancel = true; focusView = passwordEditText; focusView.requestFocus(); } if (password.length()<4) { passwordEditText.setError("Pas moins de 4 caractères"); cancel = true; focusView = passwordEditText; focusView.requestFocus(); } if (passwordConfirmation == null || passwordConfirmation.equals("")) { passwordConfirmationEditText.setError(getString(R.string.necessary_field)); cancel = true; focusView = passwordConfirmationEditText; focusView.requestFocus(); } if (name == null || name.equals("")) { nameEditText.setError(getString(R.string.necessary_field)); cancel = true; focusView = nameEditText; focusView.requestFocus(); } if (surname == null || surname.equals("")) { surnameEditText.setError(getString(R.string.necessary_field)); cancel = true; focusView = surnameEditText; focusView.requestFocus(); } if (phoneNumber == null || phoneNumber.equals("")) { phoneNumberEditText.setError(getString(R.string.necessary_field)); cancel = true; focusView = phoneNumberEditText; focusView.requestFocus(); } if (!isCodePostalValid(codepostal)){ codepostalEditText.setError("Ce code postal est invalide."); focusView = codepostalEditText; cancel = true; focusView.requestFocus(); } if (codepostal.length()!=5){ codepostalEditText.setError("Ce code postal est invalide."); focusView = codepostalEditText; cancel = true; focusView.requestFocus(); } String gender =""; RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.radioSex); int selectedId = radioSexGroup.getCheckedRadioButtonId(); RadioButton radioSexButton = (RadioButton) findViewById(selectedId); if(radioSexButton.getText().equals("Une femme")){ gender = "F"; }else{ gender = "M"; } if (!cancel) { json = "{\n" + "\"name\":\"" + name + "\",\n" + "\"surname\":\"" + surname + "\",\n" + "\"gender\":\"" + gender + "\",\n" + "\"email\":\"" + email + "\",\n" + "\"password\":\"" + password + "\",\n" + "\"mobilephone\":\""+ phoneNumber + "\"\n" + "}\n"; postRequest = new PostRequest("https://www.gouiran-beaute.com/link/api/v1/customer/", json); try { resp = postRequest.execute().get(); System.out.println("ON PASSSSSSSE PAR LA ?????"); System.out.println(resp); //Toast.makeText(this, resp, Toast.LENGTH_LONG).show(); //TODO : Vérifier retour requête 500 Internal Server Error } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.confirmation_mail_sentence).setNeutralButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(SignUp.this, LoginActivity.class); startActivity(intent); finish(); } }); AlertDialog dialog = builder.create(); dialog.show(); }else{ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Erreur, un champ n'est pas renseigné !").setNeutralButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = builder.create(); dialog.show(); } } //Retour arrière géré @Override public boolean dispatchKeyEvent(KeyEvent KEvent) { System.out.println("Pourquoijepassepasparla"); int keyaction = KEvent.getAction(); if(keyaction == KeyEvent.KEYCODE_BACK) { int keycode = KEvent.getKeyCode(); int keyunicode = KEvent.getUnicodeChar(KEvent.getMetaState() ); char character = (char) keyunicode; System.out.println("DEBUG MESSAGE KEY=" + character + " KEYCODE=" + keycode); //finish(); } return super.dispatchKeyEvent(KEvent); } }
true
026b7f6109b42ee3b938be57700605e8bc95fd9d
Java
JacksSparr0w/JWDTasks
/JWDModuleOne/src/main/java/com/katsubo/repository/Repository.java
UTF-8
635
2.265625
2
[]
no_license
package com.katsubo.repository; import com.katsubo.repository.sort.SortBy; import com.katsubo.repository.specification.Specification; import java.util.List; import java.util.Optional; public interface Repository<T> { int getMinAge(); void setMinAge(int minAge); int getMaxAge(); void setMaxAge(int maxAge); void add(T t); void delete(T t); void deleteAll(); List<T> query(Specification<T> spec); void sort(SortBy sort); List<T> getAll(); public int getAllMoney(); public void setAllMoney(int allMoney); public int getMoney(); public void setMoney(int money); }
true
002c2d8f2c33da578f7a0f20c7bab4adf4e1e3e7
Java
elambert/honeycomb
/emulator/src/java/com/sun/honeycomb/config/ClusterProperties.java
WINDOWS-1252
5,500
2.171875
2
[]
no_license
/* * Copyright 2008, Sun Microsystems, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sun.honeycomb.config; import java.util.Properties; import java.util.logging.Logger; import java.util.logging.Level; import java.io.IOException; import java.io.FileInputStream; import com.sun.honeycomb.cm.NodeMgr; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; public class ClusterProperties extends Properties { private static ClusterProperties singleton = null; public static final String CONFIG_FILE = "/config/emulator.config"; private static final Logger LOG = Logger.getLogger(ClusterProperties.class.getName()); public static synchronized ClusterProperties getInstance() { if (singleton == null) { singleton = new ClusterProperties(); try { singleton.init(); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to get the honeycomb simulator properties ["+ e.getMessage()+"]", e); singleton = null; } } return(singleton); } private ClusterProperties() { super(); } private void init() throws IOException { FileInputStream input = null; try { input = new FileInputStream(NodeMgr.getInstance().getEmulatorRoot()+CONFIG_FILE); load(input); } finally { if (input != null) { input.close(); } } } public boolean isDefined(String prop) { return(getProperty(prop) != null); } public boolean isDefaulted(String prop) { return(true); } public void setPendingProperty(String name, String value) { setProperty(name, value); } public void commitPendingChanges() { } /** * Returns the given property name, if found, as an int base type. If * the property name is not found Integer.MIN_VALUE is returned */ public int getPropertyAsInt(String name) throws NumberFormatException { return getPropertyAsInt(name, Integer.MIN_VALUE); } /** * As {@link getPropertyAsInt} except if the property is not found, the * specified defaultValue will be returned */ public int getPropertyAsInt (String name, int defaultValue) throws NumberFormatException { int num = defaultValue; String prop = getProperty (name); if (prop == null) return num; else return Integer.parseInt(prop); } /** * As {@link getPropertyAsLong} except if the property is not found, the * specified defaultValue will be returned */ public long getPropertyAsLong (String name, long defaultValue) throws NumberFormatException { long num = defaultValue; String prop = getProperty (name); if (prop == null) return num; else return Long.parseLong(prop); } /** * Returns the given properties value as a boolean. If the value is the * string "true" (ignoring case) then Boolean.TRUE will be returned, else * Boolean.FALSE will be returned */ public boolean getPropertyAsBoolean (String name) { return getPropertyAsBoolean (name, false); } /** * As {@link getPropertyAsBoolean} except if the property specificed by * the name parameter is not defined, the defaultValue parameter is * returned */ public boolean getPropertyAsBoolean (String name, boolean defaultValue) { boolean bool = defaultValue; String value = getProperty (name); if (name == null) { bool = defaultValue; } else { bool = Boolean.valueOf (value).booleanValue(); } return bool; } // No property change callbacks in the emulator, so this is a no-op public void addPropertyListener (PropertyChangeListener l) {} }
true
6b4a4f218346808323d463ee5385c9da90b9ca35
Java
saicyc/h5ds
/src/main/java/com/chinait/service/impl/TemplateServiceImpl.java
UTF-8
4,016
2.078125
2
[]
no_license
package com.chinait.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import com.chinait.dao.TemplateRepository; import com.chinait.dao.TemplateTypeRespository; import com.chinait.domain.AppSingleTemplate; import com.chinait.domain.TemplateType; import com.chinait.service.TemplateService; import com.chinait.utils.Constance; import com.chinait.utils.UserAuthentic; import com.chinait.vo.PageVO; import com.chinait.vo.SingleTemplateVO; @Service public class TemplateServiceImpl implements TemplateService{ @Autowired TemplateTypeRespository templateTypeRespository; @Autowired TemplateRepository templateRepository; @Override @Transactional public void saveSingleTemplate(String html,String qrCode,String fileUrl) { TemplateType type = templateTypeRespository.findByTypeName(Constance.TEMPLATE); AppSingleTemplate template = new AppSingleTemplate(); template.setFileUrl(fileUrl); template.setCreateTime(new Date()); template.setTemplateHtml(html); template.setSystem(false); template.setUser(UserAuthentic.getActiveUser()); template.setTemplateType(type); templateRepository.save(template); } @Override public List<AppSingleTemplate> findSimpleTemplateByType(int typeId) { TemplateType type = templateTypeRespository.findOne(typeId); if(type.isSystem()){ return templateRepository.findByTemplateTypeIdAndIsSystemTrueAndIsDeleteFalse(typeId); } return templateRepository.findByTemplateTypeIdAndIsSystemFalseAndIsDeleteFalseAndUser(typeId,UserAuthentic.getActiveUser()); } @Override public AppSingleTemplate referenceTemplate(int templateId) { return templateRepository.findByIsDeleteFalse(templateId); } @Override public Page<AppSingleTemplate> findSimpleTemplates(int simpleTemplateTypeId, PageVO<SingleTemplateVO> pageVO) { Pageable page = new PageRequest(pageVO.getCurrentPage(), pageVO.getPageSize()); return templateRepository.findByTemplateTypeIdAndIsDeleteFalseAndIsSystemTrue(simpleTemplateTypeId,page); } @Override public void findTemplates(PageVO<SingleTemplateVO> pageVO) { Pageable page = new PageRequest(pageVO.getCurrentPage(), pageVO.getPageSize()); Page<AppSingleTemplate> pages = templateRepository.findByIsSystemFalseAndIsDeleteFalse(page); List<SingleTemplateVO> list = new ArrayList<SingleTemplateVO>(); for(AppSingleTemplate template:pages.getContent()){ SingleTemplateVO temp = new SingleTemplateVO(); temp.setId(template.getId()); temp.setFileUrl(template.getFileUrl()); temp.setUserName(template.getUser().getUserName()); list.add(temp); } pageVO.setReturnList(list); pageVO.setTotalApps(pages.getTotalElements()); pageVO.setTotalPages(pages.getTotalPages()); } @Override @Transactional public void setSystemTemplates(int teplateId,int templateTypeId) { AppSingleTemplate temp = templateRepository.findByIsSystemFalseAndIsDeleteFalseAndId(teplateId); TemplateType type = templateTypeRespository.findOne(templateTypeId); AppSingleTemplate template = new AppSingleTemplate(); template.setCreateTime(new Date()); template.setDelete(false); template.setSystem(true); template.setTemplateHtml(temp.getTemplateHtml()); template.setTemplateType(type); template.setUser(UserAuthentic.getActiveUser()); template.setFileUrl(temp.getFileUrl()); templateRepository.save(template); } @Override @Transactional public void deleteTemplate(int templateId) { AppSingleTemplate template = templateRepository.findOne(templateId); template.setDelete(true); templateRepository.save(template); } @Override public List<TemplateType> findSystemTemplateType() { return templateTypeRespository.findByIsSystemTrueAndIsHideFalseAndIsDeleteFalse(); } }
true
3b7c02a62c1c7d5fd78202d7c97f5c0a015a7ad6
Java
saschaszott/hrs
/src/test/java/de/wvv/web/rest/EmployeeStyleResourceIT.java
UTF-8
8,645
2.3125
2
[]
no_license
package de.wvv.web.rest; import de.wvv.WirvsvirusApp; import de.wvv.domain.EmployeeStyle; import de.wvv.repository.EmployeeStyleRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Integration tests for the {@link EmployeeStyleResource} REST controller. */ @SpringBootTest(classes = WirvsvirusApp.class) @AutoConfigureMockMvc @WithMockUser public class EmployeeStyleResourceIT { private static final String DEFAULT_EMPLOYEE_STYLE = "AAAAAAAAAA"; private static final String UPDATED_EMPLOYEE_STYLE = "BBBBBBBBBB"; @Autowired private EmployeeStyleRepository employeeStyleRepository; @Autowired private EntityManager em; @Autowired private MockMvc restEmployeeStyleMockMvc; private EmployeeStyle employeeStyle; /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static EmployeeStyle createEntity(EntityManager em) { EmployeeStyle employeeStyle = new EmployeeStyle() .employeeStyle(DEFAULT_EMPLOYEE_STYLE); return employeeStyle; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static EmployeeStyle createUpdatedEntity(EntityManager em) { EmployeeStyle employeeStyle = new EmployeeStyle() .employeeStyle(UPDATED_EMPLOYEE_STYLE); return employeeStyle; } @BeforeEach public void initTest() { employeeStyle = createEntity(em); } @Test @Transactional public void createEmployeeStyle() throws Exception { int databaseSizeBeforeCreate = employeeStyleRepository.findAll().size(); // Create the EmployeeStyle restEmployeeStyleMockMvc.perform(post("/api/employee-styles").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeStyle))) .andExpect(status().isCreated()); // Validate the EmployeeStyle in the database List<EmployeeStyle> employeeStyleList = employeeStyleRepository.findAll(); assertThat(employeeStyleList).hasSize(databaseSizeBeforeCreate + 1); EmployeeStyle testEmployeeStyle = employeeStyleList.get(employeeStyleList.size() - 1); assertThat(testEmployeeStyle.getEmployeeStyle()).isEqualTo(DEFAULT_EMPLOYEE_STYLE); } @Test @Transactional public void createEmployeeStyleWithExistingId() throws Exception { int databaseSizeBeforeCreate = employeeStyleRepository.findAll().size(); // Create the EmployeeStyle with an existing ID employeeStyle.setId(1L); // An entity with an existing ID cannot be created, so this API call must fail restEmployeeStyleMockMvc.perform(post("/api/employee-styles").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeStyle))) .andExpect(status().isBadRequest()); // Validate the EmployeeStyle in the database List<EmployeeStyle> employeeStyleList = employeeStyleRepository.findAll(); assertThat(employeeStyleList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllEmployeeStyles() throws Exception { // Initialize the database employeeStyleRepository.saveAndFlush(employeeStyle); // Get all the employeeStyleList restEmployeeStyleMockMvc.perform(get("/api/employee-styles?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(employeeStyle.getId().intValue()))) .andExpect(jsonPath("$.[*].employeeStyle").value(hasItem(DEFAULT_EMPLOYEE_STYLE))); } @Test @Transactional public void getEmployeeStyle() throws Exception { // Initialize the database employeeStyleRepository.saveAndFlush(employeeStyle); // Get the employeeStyle restEmployeeStyleMockMvc.perform(get("/api/employee-styles/{id}", employeeStyle.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(employeeStyle.getId().intValue())) .andExpect(jsonPath("$.employeeStyle").value(DEFAULT_EMPLOYEE_STYLE)); } @Test @Transactional public void getNonExistingEmployeeStyle() throws Exception { // Get the employeeStyle restEmployeeStyleMockMvc.perform(get("/api/employee-styles/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateEmployeeStyle() throws Exception { // Initialize the database employeeStyleRepository.saveAndFlush(employeeStyle); int databaseSizeBeforeUpdate = employeeStyleRepository.findAll().size(); // Update the employeeStyle EmployeeStyle updatedEmployeeStyle = employeeStyleRepository.findById(employeeStyle.getId()).get(); // Disconnect from session so that the updates on updatedEmployeeStyle are not directly saved in db em.detach(updatedEmployeeStyle); updatedEmployeeStyle .employeeStyle(UPDATED_EMPLOYEE_STYLE); restEmployeeStyleMockMvc.perform(put("/api/employee-styles").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(updatedEmployeeStyle))) .andExpect(status().isOk()); // Validate the EmployeeStyle in the database List<EmployeeStyle> employeeStyleList = employeeStyleRepository.findAll(); assertThat(employeeStyleList).hasSize(databaseSizeBeforeUpdate); EmployeeStyle testEmployeeStyle = employeeStyleList.get(employeeStyleList.size() - 1); assertThat(testEmployeeStyle.getEmployeeStyle()).isEqualTo(UPDATED_EMPLOYEE_STYLE); } @Test @Transactional public void updateNonExistingEmployeeStyle() throws Exception { int databaseSizeBeforeUpdate = employeeStyleRepository.findAll().size(); // Create the EmployeeStyle // If the entity doesn't have an ID, it will throw BadRequestAlertException restEmployeeStyleMockMvc.perform(put("/api/employee-styles").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeStyle))) .andExpect(status().isBadRequest()); // Validate the EmployeeStyle in the database List<EmployeeStyle> employeeStyleList = employeeStyleRepository.findAll(); assertThat(employeeStyleList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional public void deleteEmployeeStyle() throws Exception { // Initialize the database employeeStyleRepository.saveAndFlush(employeeStyle); int databaseSizeBeforeDelete = employeeStyleRepository.findAll().size(); // Delete the employeeStyle restEmployeeStyleMockMvc.perform(delete("/api/employee-styles/{id}", employeeStyle.getId()).with(csrf()) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); // Validate the database contains one less item List<EmployeeStyle> employeeStyleList = employeeStyleRepository.findAll(); assertThat(employeeStyleList).hasSize(databaseSizeBeforeDelete - 1); } }
true
26bb4ad5a5be937029c41f8572d5a6cf2154b55f
Java
RaonAsa/wingko
/wingko_basic/src/main/java/com/wingko/story/domain/Ripple.java
UTF-8
3,194
2.09375
2
[]
no_license
/* * @(#)Ripple.java 2013. 8. 6. * * Copyright 2013 Wingko All rights reserved. */ package com.wingko.story.domain; /** * Reply 관리 VO * * @author yshsy * @version 1.0, 2013. 8. 6. */ public class Ripple extends Page { private int no; private int parent_no; private String parent_code; // store(상점상세정보) private int user_no; private String user_id; private String user_nickname; private String content; private String reg_date; private String reply_check; private String reqply_check_date; private String reply_order; private int level; private String search_type = ""; private String search_string = ""; public Ripple() { super(); } public Ripple(int parent_no, String parent_code) { this.parent_no = parent_no; this.parent_code = parent_code; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public int getParent_no() { return parent_no; } public void setParent_no(int parent_no) { this.parent_no = parent_no; } public String getParent_code() { return parent_code; } public void setParent_code(String parent_code) { this.parent_code = parent_code; } public int getUser_no() { return user_no; } public void setUser_no(int user_no) { this.user_no = user_no; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getUser_nickname() { return user_nickname; } public void setUser_nickname(String user_nickname) { this.user_nickname = user_nickname; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getReg_date() { return reg_date; } public void setReg_date(String reg_date) { this.reg_date = reg_date; } @Override public String toString() { return "Ripple [no=" + no + ", parent_no=" + parent_no + ", parent_code=" + parent_code + ", user_no=" + user_no + ", user_id=" + user_id + ", user_nickname=" + user_nickname + ", content=" + content + ", reg_date=" + reg_date + ", reply_order=" + reply_order + "]"; } public String getSearch_type() { return search_type; } public void setSearch_type(String search_type) { this.search_type = search_type; } public String getSearch_string() { return search_string; } public void setSearch_string(String search_string) { this.search_string = search_string; } public String getReply_check() { return reply_check; } public void setReply_check(String reply_check) { this.reply_check = reply_check; } public String getReqply_check_date() { return reqply_check_date; } public void setReqply_check_date(String reqply_check_date) { this.reqply_check_date = reqply_check_date; } public String getReply_order() { return reply_order; } public void setReply_order(String reply_order) { this.reply_order = reply_order; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } }
true
064639a059d72eef0962de3c192a59bd9b2d3432
Java
Francis-Zheng/brand-report-backend
/src/main/java/io/github/packagewjx/brandreportbackend/service/BaseService.java
UTF-8
1,731
2.6875
3
[]
no_license
package io.github.packagewjx.brandreportbackend.service; import java.util.Optional; /** * @author Junxian Wu * <p> * 实体访问服务 */ public interface BaseService<T, ID> { /** * 保存给定实体 * <p> * 若实体是新的实体,没有之前的ID,则是插入新的实体,且返回的实体中包含新的ID。 * 若实体拥有ID,则更新数据库中对应的实体。 * * @param val 新数据 * @return 若插入成功,则返回原val。否则返回null */ T save(T val); /** * 保存所有的实体 * * @param val 实体集 * @return 保存后的实体集,若ID为空则会添加ID */ Iterable<T> saveAll(Iterable<T> val); /** * 删除val * * @param val 要删除的实体 */ void delete(T val); /** * 删除ID为id的数据 * * @param id 数据Id */ void deleteById(ID id); /** * 删除ID在ids集合中的所有实体 * * @param ids 需要删除的实体的ID集合 */ void deleteAll(Iterable<T> ids); /** * 获取ID为id的数据 * * @param id 数据ID * @return 若不存在,则返回null。否则返回数据对象 */ Optional<T> getById(ID id); /** * 获取所有ID为ids集合中的id的实体 * * @param ids ID集合 * @return 所有ID在ids集合的实体 */ Iterable<T> getAllById(Iterable<ID> ids); /** * 查看是否存在 * * @param id ID * @return 若存在则为true,否则为false */ boolean existById(ID id); /** * 获取所有对象 * * @return 所有对象 */ Iterable<T> getAll(); }
true
5b34d331251ded7c616f76e5d4068a328688752c
Java
SciGaP/seagrid-rich-client
/src/main/java/nanocad/minimize/uff/opbterm.java
UTF-8
6,403
2.34375
2
[ "Apache-2.0" ]
permissive
/****************************************** *opbterm.java -- nanocad *Andrew Knox 06/25/01 *implements out of plane angle bend term ******************************************/ package nanocad.minimize.uff; import java.lang.Math; import java.util.Vector; import nanocad.atom; import nanocad.bond; import nanocad.term; public class opbterm extends term { private double k0, k1, k2; private double angle; public opbterm() {} public opbterm(atom center, atom bent, atom other1, atom other2) { myGroup = center.getGroup(); myAtoms = new atom[4]; myAtoms[1] = bent; myAtoms[0] = center; myAtoms[2] = other1; myAtoms[3] = other2; setCalculationValues(); } public void enumerate(Vector atomList, Vector termList) { for(int i = 0; i < atomList.size(); i++) { if ( ((atom)atomList.elementAt(i)).bonds.size() == 3) { atom tmp; Vector v = new Vector(); v.addElement((atom)atomList.elementAt(i)); for (int j = 0; j < 3; j++) { if (((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a1 == (atom)v.elementAt(0)) v.addElement(((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a2); else v.addElement(((bond)((atom)v.elementAt(0)).bonds.elementAt(j)).a1); } this.buildTerm(v, termList); } } } protected void buildTerm(Vector v, Vector termList) { opbterm b; for (int i = 0; i<3; i++) { b = new opbterm((atom)v.elementAt(0), (atom)v.elementAt((i%3)+1), (atom)v.elementAt(((i+1)%3)+1), (atom)v.elementAt(((i+2)%3)+1)); if (b.k0 != 0.0) { termList.addElement(b); } } } public double computeForces() { //calculate angle double pq[], rq[], qs[], normal[], dthdpq[], dthdrq[], dthdqs[]; pq = new double[3]; rq = new double[3]; qs = new double[3]; normal = new double[3]; dthdpq = new double[3]; dthdrq = new double[3]; dthdqs = new double[3]; double qsdotqs, ndotn, ndotqs, denominator, dEdth; for (int i = 0; i < 3; i++) { pq[i] = myAtoms[0].x[i] - myAtoms[3].x[i]; rq[i] = myAtoms[0].x[i] - myAtoms[2].x[i]; qs[i] = myAtoms[1].x[i] - myAtoms[0].x[i]; } normal[0] = pq[1]*rq[2] - pq[2]*rq[1]; normal[1] = pq[2]*rq[0] - pq[0]*rq[2]; normal[2] = pq[0]*rq[1] - pq[1]*rq[0]; ndotn = dotProduct(normal,normal); qsdotqs = dotProduct(qs,qs); ndotqs = dotProduct(normal,qs); if(ndotn <= 0) ndotn = uffMinimizeAlgorythm.TINY; if(qsdotqs <= 0) qsdotqs = uffMinimizeAlgorythm.TINY; double jtemp1 = ndotn * qsdotqs - ndotqs * ndotqs; if(jtemp1 <= 0) jtemp1 = uffMinimizeAlgorythm.TINY; denominator = Math.sqrt(jtemp1); double jtemp2 = ndotqs / Math.sqrt(ndotn * qsdotqs); if(jtemp2 < -1) jtemp2 = -1; if(jtemp2 > 1) jtemp2 = 1; angle = Math.PI/2 - Math.acos(jtemp2); // These are divided by 3 because we consider each // of the 3 bent atoms separately. potential = computePotential(angle) / 3; dEdth = computePotentialDerivative(angle) / 3; double RQcrossQS[] = crossProduct(rq,qs); double RQcrossNorm[] = crossProduct(rq,normal); dthdpq[0] = (-RQcrossQS[0] + RQcrossNorm[0] * ndotqs / ndotn) / denominator; dthdpq[1] = (-RQcrossQS[1] + RQcrossNorm[1] * ndotqs / ndotn) / denominator; dthdpq[2] = (-RQcrossQS[2] + RQcrossNorm[2] * ndotqs / ndotn) / denominator; double PQcrossQS[] = crossProduct(pq,qs); double PQcrossNorm[] = crossProduct(pq,normal); dthdrq[0] = (PQcrossQS[0] + PQcrossNorm[0] * ndotqs / ndotn) / denominator; dthdrq[1] = (PQcrossQS[1] + PQcrossNorm[1] * ndotqs / ndotn) / denominator; dthdrq[2] = (PQcrossQS[2] + PQcrossNorm[2] * ndotqs / ndotn) / denominator; dthdqs[0] = (normal[0] - qs[0] * ndotqs / qsdotqs) / denominator; dthdqs[1] = (normal[1] - qs[1] * ndotqs / qsdotqs) / denominator; dthdqs[2] = (normal[2] - qs[2] * ndotqs / qsdotqs) / denominator; for (int i = 0; i < 3; i++) { myAtoms[0].f[i] += dEdth * (-dthdqs[i] + dthdrq[i] + dthdpq[i]); myAtoms[1].f[i] += dEdth * dthdqs[i]; myAtoms[2].f[i] += dEdth * -dthdrq[i]; myAtoms[3].f[i] += dEdth * -dthdpq[i]; } return myAtoms[0].f[0]; //return dTheta; } public void setCalculationValues() { myGroup = myAtoms[0].getGroup(); if(myGroup.needsToGetTypes()) myGroup.setTypes(); int atomBentType = myAtoms[1].getUFFTypeNum(); int atomCenterType = myAtoms[0].getUFFTypeNum(); // Force constants for this guy came from solving 12 // linear equations in 12 unknowns for the Group V hydrides. // A three term cosine fourier expansion was used, with constants // fit to have a minimum (derivative is 0) at the natural angle, // and that minimum is set to 0. Also, at 0 degrees, the function // has a maximum of Ebarrier. // Atom Angle Ebarrier // N 107.5 5.8 // P 93.5 37 // As 91.8 40 // Sb 91.3 46 // Bi ? ? // Energies are in kilocalories per mole. Note that the angle given is // a published value for the H-X-H angle, while UFF instead uses the angle // between the IL axis and the IJK plane, for a opbterm consisting of atoms // IJKL. Values for Bismuth were unavailable, so Bi and Po are assumed // to have the same values as Sb and Te. // // Terms for carbon come directly from the literature. switch(myAtoms[0].atomicNumber()){ case 7: // Nitrogen and Oxygen case 8: k0 = 18.2169897839; k1 = -24.4237325078; k2 = 12.0067427239; break; case 15: // Phosphorus and Sulfur case 16: k0 = 22.6500766206; k1 = -7.94615918416; k2 = 22.2960825616; break; case 33: // Arsenic and Selenium case 34: k0 = 22.0248498374; k1 = -3.96032299431; k2 = 21.9354731569; break; case 51: // Antimony, Tellurium, Bismuth, and Polonium case 52: case 83: case 84: k0 = 25.1558772986; k1 = -3.25887125444; k2 = 25.1089939559; break; case 6: // Carbon, the most complicated one. if(atomBentType == 19){ // if it's bonded to O_2... k0 = 50; k1 = -50; k2 = 0; } else{ k0 = 6; k1 = -6; k2 = 0; } break; default: k0 = 0; k1 = 0; k2 = 0; } } protected double computePotential(double angle) { return k0 + k1*Math.cos(angle) + k2*Math.cos(2*angle); } protected double computePotentialDerivative(double angle) { return -k1*Math.sin(angle) - 2*k2*Math.sin(2*angle); } public String repr2() { return " OPB"; } public int termLength() { return 4; } public String name() { return "Out of Plane Bend"; } }
true
a7942b9ef840555e29533a507826ab806ac671c5
Java
mjnjust/Designmode
/src/package6/OldUser.java
UTF-8
625
2.765625
3
[]
no_license
package package6; public class OldUser implements IOldUserInfo{ private String name ; private int age ; private String address ; private int workyears ; public OldUser(String name,int age,String address,int workyears) { this.name = name ; this.age = age ; this.address =address ; this.workyears = workyears; } @Override public String getName() { return this.name; } @Override public int getAge() { return this.age; } @Override public String getAddress() { return this.address; } @Override public int getWorkYears() { return this.workyears ; } }
true
1b001946ca91d5b3de0d3811587ac88a38397da8
Java
Sensetivity/vdl
/src/main/java/com/github/engatec/vdl/model/preferences/wrapper/ConfigItemWrapper.java
UTF-8
631
2.1875
2
[]
no_license
package com.github.engatec.vdl.model.preferences.wrapper; import com.github.engatec.vdl.core.preferences.ConfigManager; import com.github.engatec.vdl.model.preferences.ConfigItem; public abstract class ConfigItemWrapper<P, V> { protected abstract ConfigItem<V> getConfigItem(); public abstract P getProperty(); public abstract V getValue(); public abstract void setValue(V v); public void restore() { V value = ConfigManager.INSTANCE.getValue(getConfigItem()); setValue(value); } public void save() { ConfigManager.INSTANCE.setValue(getConfigItem(), getValue()); } }
true
4bd5495e7a73515f6aa2aff760d26eebbccd0c6d
Java
naralycamachoacevedo/NaralyRetosG42
/RETO1/src/reto1/Reto1_PersonClass.java
UTF-8
4,069
3.453125
3
[]
no_license
/* * 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 reto1; /** * * @author naral */ public class Reto1_PersonClass { //1.Declarar las variables globales con tipo de visibilidad privada //2.Encapsulate fields, clic secundario + refactor + encapsulate fields (GET y SET) //3.Insertar método ejecutor de la clase, clic secundario + insert code + constructor //4.Creación de la función que permite consultar info de la persona (GETTER) private String nombre; private String tipo_doc; private int nro_documento; private int edad; private String estado_civil; private String ocupacion; private boolean hijos; //Los métodos utilizan la palabra reservada VOID (vacío) //Las funciones no utilizan VOID pero si el tipo de dato que retornan public Reto1_PersonClass(String nombre, String tipo_doc, int nro_documento, int edad, String estado_civil, String ocupacion, boolean hijos) { this.nombre = nombre; this.tipo_doc = tipo_doc; this.nro_documento = nro_documento; this.edad = edad; this.estado_civil = estado_civil; this.ocupacion = ocupacion; this.hijos = hijos; } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; } /** * @return the tipo_doc */ public String getTipo_doc() { return tipo_doc; } /** * @param tipo_doc the tipo_doc to set */ public void setTipo_doc(String tipo_doc) { this.tipo_doc = tipo_doc; } /** * @return the nro_documento */ public int getNro_documento() { return nro_documento; } /** * @param nro_documento the nro_documento to set */ public void setNro_documento(int nro_documento) { this.nro_documento = nro_documento; } /** * @return the edad */ public int getEdad() { return edad; } /** * @param edad the edad to set */ public void setEdad(int edad) { this.edad = edad; } /** * @return the estado_civil */ public String getEstado_civil() { return estado_civil; } /** * @param estado_civil the estado_civil to set */ public void setEstado_civil(String estado_civil) { this.estado_civil = estado_civil; } /** * @return the ocupacion */ public String getOcupacion() { return ocupacion; } /** * @param ocupacion the ocupacion to set */ public void setOcupacion(String ocupacion) { this.ocupacion = ocupacion; } /** * @return the hijos */ public boolean isHijos() { return hijos; } /** * @param hijos the hijos to set */ public void setHijos(boolean hijos) { this.hijos = hijos; } //La función debe retornar una expresión //El tipo de dato de la expresión que retorna es String public String funcion_consultar_info_P(){ return "Consulta de información de la persona\n******FORMA 1: Función******" + getNombre() + " " + getTipo_doc() + " " + getNro_documento() + " " + getEdad() + " " + getEstado_civil() + " " + getOcupacion() + " " + isHijos(); } //El método lo debemos declarar utilizando la palabra reservada VOID public void metodo_consultar_info_P(){ System.out.println("Consulta de información de la persona\n******FORMA 2: Método******" + getNombre() + " " + getTipo_doc() + " " + getNro_documento() + " " + getEdad() + " " + getEstado_civil() + " " + getOcupacion() + " " + isHijos()); } }
true