text
stringlengths
10
2.72M
package zuoshen.Tree; import java.util.Stack; public class 后序非递归 { public void postOrder(treeNode head){ if(head==null){ return; } postOrder(head.left); postOrder(head.right); System.out.print(head.value+" "); } public void postOrderNo(treeNode head){ if(head==null){ return; } Stack<treeNode>s1=new Stack<>(); Stack<treeNode>s2=new Stack<>(); s1.push(head); while (!s1.empty()){ head=s1.pop(); s2.push(head); if(head.left!=null){ s1.push(head.left); } if(head.right!=null){ s1.push(head.right); } } while (!s2.empty()){ System.out.println(s2.pop().value); } } }
package com.example.ocenika.service; import com.example.ocenika.model.Comment; import com.example.ocenika.model.Professor; import com.example.ocenika.model.University; import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; public interface APIService { @GET("api/universities/") Call<List<University>> getUniversities(); @GET("api/professors/") Call<List<Professor>> getProfessors(); @GET("api/professors/") Call<List<Professor>> getProfessorsByUniversity(@Query("universities") int universityId); @GET("api/professors/{id}") Call<Professor> getProfessorById(@Path("id") int professorId); @POST("api/ratings/") Call<Comment> addComment(@Body Comment comment, @Header("authorization") String token); }
package com.tencent.mm.plugin.setting.ui.setting; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; class EditSignatureUI$2 implements OnMenuItemClickListener { final /* synthetic */ EditSignatureUI mPP; EditSignatureUI$2(EditSignatureUI editSignatureUI) { this.mPP = editSignatureUI; } public final boolean onMenuItemClick(MenuItem menuItem) { this.mPP.YC(); this.mPP.finish(); return true; } }
package self.learning.isudoku; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * * @author hshrishrimal */ public class Sudoku { private int NUM_OF_ROWS = 9; private int NUM_OF_COLUMNS = 9; private int SUB_MATRIX_SIZE = 3; private SudokuCell[][] sudoku; public SudokuCell[][] getSudoku() { return sudoku; } public Sudoku(SudokuCell[][] initialSudoko) { this.sudoku = initialSudoko; this.NUM_OF_ROWS = initialSudoko.length; this.NUM_OF_COLUMNS = this.NUM_OF_ROWS; this.SUB_MATRIX_SIZE = (int) Math.sqrt(NUM_OF_ROWS); } public Sudoku(int[][] initialSudoko) { SudokuCell[][] sudoku = new SudokuCell[initialSudoko.length][initialSudoko[0].length]; for (int row = 0; row < initialSudoko.length; row++) { for (int col = 0; col < initialSudoko[0].length; col++) { if(initialSudoko[row][col] != 0) { sudoku[row][col] = new SudokuCell(SudokuCellColor.BLACK, new Pair<Integer,Integer>(row,col), initialSudoko[row][col]); } else { sudoku[row][col] = new SudokuCell(SudokuCellColor.GREEN, new Pair<Integer,Integer>(row,col), initialSudoko[row][col]); } } } this.NUM_OF_ROWS = initialSudoko.length; this.NUM_OF_COLUMNS = this.NUM_OF_ROWS; this.SUB_MATRIX_SIZE = (int) Math.sqrt(NUM_OF_ROWS); this.sudoku = sudoku; } public int getNUM_OF_ROWS() { return NUM_OF_ROWS; } public int getNUM_OF_COLUMNS() { return NUM_OF_COLUMNS; } public int getSUB_MATRIX_SIZE() { return SUB_MATRIX_SIZE; } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int heightOfBus = scanner.nextInt(); int numberOfBridges = scanner.nextInt(); int heightOfBridges; int counter = 0; while (scanner.hasNext()) { heightOfBridges = scanner.nextInt(); counter++; if (heightOfBus >= heightOfBridges) { System.out.println("Will crash on bridge " + counter); break; } if (counter == numberOfBridges) { System.out.println("Will not crash"); break; } } } }
import java.io.*; class Control4 { public static void main(String[]args) { int s=Integer.parseInt(args[0]); int r,t=0; while(s>0){ r=s%10; t=t+r; s=s/10; } System.out.println("the sum of the digits of s is:"+t); } }
package com.wb.cloud.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; /** * @ClassName : ApplicationContextConfig * @Author : 王斌 * @Date : 2020-11-18 19:35 * @Description * @Version */ @Configuration public class ApplicationContextConfig { @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } }
package pro.roquelaure.leapyears; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class LeapYearsTest { @Test public void leapYears_return_true_if_the_parameter_is_divisible_by_400() { int num = 400; boolean isDivisibleByNum = LeapYears.calculate(num); assertTrue(isDivisibleByNum); } @Test public void leapYears_return_false_if_the_parameter_is_not_divisible_by_400() { int num = 69; boolean isDivisibleByNum = LeapYears.calculate(num); assertFalse(isDivisibleByNum); } @Test public void leapYears_return_false_if_the_parameter_is_divisible_by_100_but_not_400() { int num = 100; boolean isDivisibleByNum = LeapYears.calculate(num); assertFalse(isDivisibleByNum); } @Test public void leapYears_return_true_if_the_parameter_is_divisible_by_4_but_not_by_100() { int num = 2012; boolean isDivisibleByNum = LeapYears.calculate(num); assertTrue(isDivisibleByNum); } @Test public void leapYears_return_false_if_the_parameter_is_not_divisible_by_4() { int num = 2; boolean isDivisibleByNum = LeapYears.calculate(num); assertFalse(isDivisibleByNum); } }
package com.libedi.demo.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.libedi.demo.domain.TestEntity; /** * TestRepository * * @author Sang-jun, Park (libedi@linecorp.com) * @since 2019. 04. 02 */ public interface TestRepository extends JpaRepository<TestEntity, Long> { }
package com.project.backend.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.project.backend.entità.CaratteristicheQualitativeSt; public interface CaratteristicheQualitativeStRepository extends JpaRepository<CaratteristicheQualitativeSt, String> { }
package design_method.策略模式; public class Context { CalPrice calPrice; public void method(double price){ calPrice.calPrice(price); } }
package com.blog.system.action; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.blog.system.Dao.DailyDao; import com.blog.system.Dao.PhotoDao; import com.blog.system.Dto.DailyBean; import com.blog.system.Dto.PhotoBean; public class PhotoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String param = request.getParameter("param"); if (param == null) { param = "view"; } if (param == "view" || param.equals("view")) { getPhoto(request, response); } else if (param == "del" || param.equals("del")) { try { String photoid = request.getParameter("photoid"); PhotoDao pd = new PhotoDao(); pd.delPhoto(photoid); } catch (Exception e) { e.printStackTrace(); } getPhoto(request, response); } else if (param == "singlephoto" || param.equals("singlephoto")) { String photoid = request.getParameter("photoid"); PhotoDao pd = new PhotoDao(); PhotoBean pb = pd.getSinglePhoto(photoid); request.setAttribute("singlephoto", pb); RequestDispatcher requestDispatcher = request .getRequestDispatcher("/system/singlephoto.jsp"); requestDispatcher.forward(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void getPhoto(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { int page; if (request.getParameter("page") != null) { page = Integer.parseInt(request.getParameter("page")); } else { page = 1; } int size = 10; try { List<PhotoBean> ret = new ArrayList<PhotoBean>(); PhotoDao pd = new PhotoDao(); ret = pd.getSystemPhoto(page, size); long count = pd.getPhotoCount(); request.setAttribute("count", count); request.setAttribute("page", page); request.setAttribute("size", size); request.setAttribute("photo", ret); RequestDispatcher requestDispatcher = request .getRequestDispatcher("/system/systemphoto.jsp"); requestDispatcher.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } }
/** * */ package fl.sabal.source.interfacePC.Windows; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import fl.sabal.source.interfacePC.Codes.Event.lettersToUppsercase; import fl.sabal.source.interfacePC.Codes.Event.notDigit; import fl.sabal.source.interfacePC.Codes.Event.notLetters; import fl.sabal.source.interfacePC.Codes.ControllerMatter; import fl.sabal.source.interfacePC.Codes.DataBases.MySQL; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JComboBox; import javax.swing.JButton; import java.awt.Font; import javax.swing.SwingConstants; /** * @author FL-AndruAnnohomy * */ @SuppressWarnings("serial") public class WindowMatter extends JFrame { private JPanel contentPane; public JTextField matterField; public JTextField hoursField; @SuppressWarnings("rawtypes") public JComboBox laboratoryBox; private JButton btnCancel; public JButton btnAccept; public MySQL mysql; /** * Create the frame. */ @SuppressWarnings("rawtypes") public WindowMatter(MySQL mysql) { this.mysql = mysql; setBounds(100, 100, 285, 170); setResizable(false); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblMatter = new JLabel("Materia :"); lblMatter.setHorizontalAlignment(SwingConstants.CENTER); lblMatter.setFont(new Font("Arial", Font.BOLD, 14)); lblMatter.setBounds(10, 17, 95, 14); contentPane.add(lblMatter); matterField = new JTextField(); matterField.setFont(new Font("Arial", Font.BOLD, 14)); matterField.setBounds(109, 11, 155, 23); contentPane.add(matterField); matterField.setColumns(10); JLabel lblHours = new JLabel("Horas :"); lblHours.setHorizontalAlignment(SwingConstants.CENTER); lblHours.setFont(new Font("Arial", Font.BOLD, 14)); lblHours.setBounds(10, 45, 95, 14); contentPane.add(lblHours); hoursField = new JTextField(); hoursField.setFont(new Font("Arial", Font.BOLD, 14)); hoursField.setBounds(109, 39, 155, 23); contentPane.add(hoursField); JLabel lblLaboratory = new JLabel("Laboratorio :"); lblLaboratory.setHorizontalAlignment(SwingConstants.CENTER); lblLaboratory.setFont(new Font("Arial", Font.BOLD, 14)); lblLaboratory.setBounds(10, 76, 95, 14); contentPane.add(lblLaboratory); laboratoryBox = new JComboBox(); laboratoryBox.setFont(new Font("Arial", Font.BOLD, 14)); laboratoryBox.setBounds(109, 70, 155, 23); contentPane.add(laboratoryBox); btnAccept = new JButton("Aceptar"); btnAccept.setFont(new Font("Arial", Font.BOLD, 14)); btnAccept.setBounds(141, 101, 95, 23); contentPane.add(btnAccept); btnCancel = new JButton("Cancelar"); btnCancel.setFont(new Font("Arial", Font.BOLD, 14)); btnCancel.setBounds(42, 101, 95, 23); contentPane.add(btnCancel); } /** * @param event */ public void controller(ControllerMatter event) { btnCancel.addActionListener(event); btnCancel.setActionCommand("DISPOSE"); btnAccept.addActionListener(event); btnAccept.setActionCommand("ACCEPT"); matterField.addKeyListener(new lettersToUppsercase()); matterField.addKeyListener(new notDigit()); hoursField.addKeyListener(new notLetters()); } }
package com.komdosh.yandextestapp.request; import com.komdosh.yandextestapp.data.dto.DictionaryDto; import retrofit2.Call; import retrofit2.http.POST; import retrofit2.http.Query; /** * @author Komdosh * @since 19.03.2017 */ public interface DictionaryAPI { @POST("lookup") Call<DictionaryDto> translate(@Query("key") String key, @Query("text") String text, @Query("lang") String lang); }
// Sun Certified Java Programmer // Chapter 7, P627_2 // Generics and Collections public class CreatingGenericMethods { public static void main(String[] args) { // } }
package pl.finsys.propertyPlaceholder; public class Robot { private String hi; private String bye; public String getHi() { return hi; } public void setHi(String hi) { this.hi = hi; } public String getBye() { return bye; } public void setBye(String bye) { this.bye = bye; } public String sayHello(){ return hi + ", Human!"; } public String sayGoodbye(){ return bye + ", Human!"; } }
package com.chuxin.family.utils; import com.chuxin.family.app.CxApplication; import android.content.Context; public class ScreenUtil { // dp转换成pix public static int dip2px(Context context, float dipValue){ final float scale = CxApplication.getInstance().getResources().getDisplayMetrics().density; return (int)(dipValue * scale + 0.5f); } public static int px2dip(Context context, float dipValue){ final float scale = CxApplication.getInstance().getResources().getDisplayMetrics().density; return (int)(dipValue / scale + 0.5f); } public static int getScreenType(Context context){ float height = CxApplication.getInstance().getResources().getDisplayMetrics().heightPixels; if(height>=800){ return 1; }else{ return 0; } } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.cmsitems.populators; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.cms2.model.contents.CMSItemModel; import de.hybris.platform.cms2.model.pages.AbstractPageModel; import de.hybris.platform.cms2.servicelayer.services.AttributeDescriptorModelHelperService; import de.hybris.platform.cmsfacades.data.ComponentTypeAttributeData; import de.hybris.platform.cmsfacades.data.ComponentTypeData; import de.hybris.platform.cmsfacades.types.populator.CMSItemDropdownComponentTypeAttributePopulator; import de.hybris.platform.cmsfacades.types.populator.I18nComponentTypePopulator; import de.hybris.platform.core.model.type.AttributeDescriptorModel; import de.hybris.platform.core.model.type.ComposedTypeModel; import de.hybris.platform.servicelayer.type.TypeService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.beans.factory.ObjectFactory; import java.util.Arrays; import java.util.Collections; @UnitTest @RunWith(MockitoJUnitRunner.class) public class CMSItemDropdownComponentTypeAttributePopulatorTest { @InjectMocks private CMSItemDropdownComponentTypeAttributePopulator populator; @Mock private AttributeDescriptorModel sourceAttributeDescriptor; @Mock private ComponentTypeAttributeData targetComponentTypeAttributeData; @Mock private AttributeDescriptorModelHelperService attributeDescriptorModelHelperService; @Mock private I18nComponentTypePopulator i18nComponentTypePopulator; @Mock private TypeService typeService; @Mock private ObjectFactory<ComponentTypeData> componentTypeDataFactory; @Mock private ComposedTypeModel abstractPageSubTypeComponentModel; @Mock private ComposedTypeModel subTypeOfCMSItemComponentModel; @Mock private ComposedTypeModel subTypeLevel2ComponentModel; private static final String ID_ATTRIBUTE = "uuid"; private static final String LABEL_ATTRIBUTE_NAME = "name"; private static final String LABEL_ATTRIBUTE_UID = "uid"; private final String TYPE_CODE = "typeCode"; private static final String CMS_ITEM_DROPDOWN = "CMSItemDropdown"; private abstract class SubTypeOfAbstractPageModel extends AbstractPageModel { }; private class SubTypeOfCMSItemModel extends CMSItemModel { }; @Before public void setUp() { doReturn(new ComponentTypeData()).when(componentTypeDataFactory).getObject(); doReturn(true).when(abstractPageSubTypeComponentModel).getAbstract(); doReturn(abstractPageSubTypeComponentModel).when(typeService).getComposedTypeForClass(SubTypeOfAbstractPageModel.class); doReturn(Arrays.asList(subTypeLevel2ComponentModel)).when(abstractPageSubTypeComponentModel).getAllSubTypes(); doReturn("SubTypeOfAbstractPageModel").when(abstractPageSubTypeComponentModel).getCode(); doReturn(false).when(subTypeOfCMSItemComponentModel).getAbstract(); doReturn(subTypeOfCMSItemComponentModel).when(typeService).getComposedTypeForClass(SubTypeOfCMSItemModel.class); doReturn(Arrays.asList(subTypeLevel2ComponentModel)).when(subTypeOfCMSItemComponentModel).getAllSubTypes(); doReturn("SubTypeOfCMSItemModel").when(subTypeOfCMSItemComponentModel).getCode(); doReturn("SubTypeOfAbstractPageModelLevel2").when(subTypeLevel2ComponentModel).getCode(); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { Object[] args = invocationOnMock.getArguments(); ComponentTypeData componentTypeData = (ComponentTypeData)args[1]; componentTypeData.setI18nKey(((ComposedTypeModel)args[0]).getCode() + "Key"); return null; } }).when(i18nComponentTypePopulator).populate(Matchers.any(), Matchers.any(ComponentTypeData.class)); } @Test public void testPopulateShouldSetItemDropdownAttributesAlongWithSearchParamsForAttributesOfTypeAbstractPageModel() { // GIVEN targetComponentTypeAttributeData = new ComponentTypeAttributeData(); doReturn(SubTypeOfAbstractPageModel.class).when(attributeDescriptorModelHelperService) .getAttributeClass(sourceAttributeDescriptor); // WHEN populator.populate(sourceAttributeDescriptor, targetComponentTypeAttributeData); // THEN assertThat(targetComponentTypeAttributeData.getCmsStructureType(), is(CMS_ITEM_DROPDOWN)); assertThat(targetComponentTypeAttributeData.getIdAttribute(), is(ID_ATTRIBUTE)); assertThat(targetComponentTypeAttributeData.getLabelAttributes(), contains(LABEL_ATTRIBUTE_NAME, LABEL_ATTRIBUTE_UID)); assertThat(targetComponentTypeAttributeData.getParams(), hasEntry(TYPE_CODE, "SubTypeOfAbstractPage")); assertThat(targetComponentTypeAttributeData.getParams(), hasEntry("itemSearchParams", "pageStatus:active")); assertThat(targetComponentTypeAttributeData.getSubTypes(), hasEntry("SubTypeOfAbstractPageModelLevel2", "SubTypeOfAbstractPageModelLevel2Key")); assertThat(targetComponentTypeAttributeData.getSubTypes().size(), is(1)); } @Test public void testPopulateShouldSetItemDropdownAttributesWithoutSearchParamsForAttributesNotOfTypeAbstractPageModel() { // GIVEN targetComponentTypeAttributeData = new ComponentTypeAttributeData(); doReturn(SubTypeOfCMSItemModel.class).when(attributeDescriptorModelHelperService) .getAttributeClass(sourceAttributeDescriptor); // WHEN populator.populate(sourceAttributeDescriptor, targetComponentTypeAttributeData); // THEN assertThat(targetComponentTypeAttributeData.getCmsStructureType(), is(CMS_ITEM_DROPDOWN)); assertThat(targetComponentTypeAttributeData.getIdAttribute(), is(ID_ATTRIBUTE)); assertThat(targetComponentTypeAttributeData.getLabelAttributes(), contains(LABEL_ATTRIBUTE_NAME, LABEL_ATTRIBUTE_UID)); assertThat(targetComponentTypeAttributeData.getParams(), hasEntry(TYPE_CODE, "SubTypeOfCMSItem")); assertThat(targetComponentTypeAttributeData.getParams(), not(hasEntry("itemSearchParams", "pageStatus:active"))); assertThat(targetComponentTypeAttributeData.getSubTypes(), hasEntry("SubTypeOfAbstractPageModelLevel2", "SubTypeOfAbstractPageModelLevel2Key")); assertThat(targetComponentTypeAttributeData.getSubTypes(), hasEntry("SubTypeOfCMSItemModel", "SubTypeOfCMSItemModelKey")); assertThat(targetComponentTypeAttributeData.getSubTypes().size(), is(2)); } @Test public void givenNoSupportedSubTypeAndTypeIsAbstract_populate_shouldReturnAnEmptyList() { // GIVEN targetComponentTypeAttributeData = new ComponentTypeAttributeData(); doReturn(SubTypeOfAbstractPageModel.class).when(attributeDescriptorModelHelperService) .getAttributeClass(sourceAttributeDescriptor); doReturn(Collections.emptyList()).when(abstractPageSubTypeComponentModel).getAllSubTypes(); // WHEN populator.populate(sourceAttributeDescriptor, targetComponentTypeAttributeData); // THEN assertThat(targetComponentTypeAttributeData.getSubTypes().size(), is(0)); } }
package com.example.day02.contract; import com.example.day02.bean.BannerBean; import com.example.day02.bean.ListBean; import com.example.day02.bean.ProjectBean; import com.example.day02.util.net.INteCallBack; public class MainContract { public interface MainView { void getBanner(BannerBean bannerBean); void getData(ProjectBean projectBean); void getList(ListBean listBean); void getResult(String result); } public interface MainModel { <T> void getMod(String url, INteCallBack<T> callBack); } public interface MainPersenter { void per(); void per1(); void per2(); } }
/* * 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 pe.edu.upeu.control; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import pe.edu.upeu.model.Diagnostico; import pe.edu.upeu.model.Paciente; import pe.edu.upeu.service.DiagnosticoServis; import pe.edu.upeu.service.DoctorServis; import pe.edu.upeu.service.PacienteServis; /** * * @author Alumnos */ @Controller @RequestMapping("/diagnostico") public class DiagnosticoCController { @Autowired DiagnosticoServis service; @Autowired DoctorServis serviceDoc; @Autowired PacienteServis servicePa; @Autowired MessageSource messageSource; @RequestMapping(value = {"/", "/list"}, method = RequestMethod.GET) public ModelAndView listDiagnostico(ModelMap model) { List<Diagnostico> lista = service.listarEntidad(); Map<String, Object> modelo = new HashMap<String, Object>(); modelo.put("ListaDiagnostico", lista); modelo.put("mensaje", "Reporte de Diagnostico"); modelo.put("mensaje", "Reporte de Diagnostico"); return new ModelAndView("diagnostico/mainDiagnostico", modelo); } @RequestMapping(value = "buscarDiagnostico", method = RequestMethod.POST) public ModelAndView buscarDiagnostico(HttpServletRequest r) { String dato = r.getParameter("dato") == null ? "" : r.getParameter("dato"); List<Diagnostico> lista = service.listarPorNombre(dato); Map<String, Object> modelo = new HashMap<String, Object>(); modelo.put("ListaDiagnostico", lista); return new ModelAndView("diagnostico/mainDiagnostico", modelo); } @RequestMapping(value = "eliminarDiagnostico", method = RequestMethod.GET) public ModelAndView eliminarDiagnostico(HttpServletRequest r) { int idEntidad = Integer.parseInt(r.getParameter("id")); service.eliminarEntidadId(idEntidad); System.out.println("si llego al metodo"); return new ModelAndView(new RedirectView("diagnostico/list")); } @RequestMapping(value = "formDiagnostico", method = RequestMethod.GET) public ModelAndView irFormulario(@ModelAttribute("modeloDiagnostico") Diagnostico entidad, BindingResult result) { Map<String, Object> modelo = new HashMap<String, Object>(); modelo.put("listaTemporada", "Holasssssssssss"); modelo.put("listaTemporadaX", service.listarEntidad()); modelo.put("listaTemporada2", ""); modelo.put("listaTemporada3", ""); modelo.put("ListDoctor", serviceDoc.listarEntidad()); modelo.put("ListPaciente", servicePa.listarEntidad()); return new ModelAndView("diagnostico/formDiagnostico", modelo); } @RequestMapping(value = "guardarDiagnostico", method = RequestMethod.POST) public ModelAndView guardarDiagnosticoXX(@ModelAttribute Diagnostico entidad, BindingResult result) { entidad.setFecha(new Date()); //methodo para devolver una persona por ID // o puedes guardar directamente ID Diagnostico diagnostico = new Diagnostico(); diagnostico.setEstado(""); service.guardarEntidad(entidad); return new ModelAndView(new RedirectView("list")); } @RequestMapping(value = "modificarDiagnostico", method = RequestMethod.GET) public ModelAndView modificarDiagnostico(HttpServletRequest r) { int id = Integer.parseInt(r.getParameter("id")); Diagnostico entidad = null; entidad = service.buscarEntidadId(id); return new ModelAndView("diagnostico/formUDiagnostico", "ModeloDiagnostico", entidad); } @RequestMapping(value = "modificarDiagnosticoX", method = RequestMethod.GET) public String modificarDiagnosticoX(HttpServletRequest r, Model model) { int id = Integer.parseInt(r.getParameter("id")); Diagnostico diagnostico = null; diagnostico = service.buscarEntidadId(id); model.addAttribute("ModeloDiagnostico", diagnostico); return "diagnostico/formUDiagnostico"; } @RequestMapping(value = "actualizarDiagnostico", method = RequestMethod.POST) public ModelAndView gactualizarDiagnosticoXX(@ModelAttribute("ModeloDiagnostico") Diagnostico entidad, BindingResult result) { service.modificarEntidadId(entidad); return new ModelAndView(new RedirectView("list")); } }
package com.hk.movie; /** * @author huangkai * @date 2018-6-3 17:39 */ public @interface ExcludeFromComponentScan { }
package uz.kassa.test.domain.entity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.stereotype.Service; import uz.kassa.test.domain.entity.base.BaseEntity; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import javax.persistence.Table; import java.util.Objects; @Entity @Table(name = "employees") @Getter @Setter @NoArgsConstructor public class Employee extends BaseEntity { private String username; private String password; private String emailConfirmToken; private Boolean confirmed; @ManyToOne(fetch = FetchType.LAZY) public Company company; public Employee(String username, String password, String emailConfirmToken) { this(username, password); this.emailConfirmToken = emailConfirmToken; this.confirmed = false; } public Employee(String username, String password) { this.username = username; this.password = password; } public Boolean isConfirmed() { return this.confirmed; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Employee employee = (Employee) o; return Objects.equals(username, employee.username); } @Override public int hashCode() { return Objects.hash(super.hashCode(), username); } }
package net.plazmix.core.api.service.group; import lombok.Getter; import net.plazmix.core.api.Core; @Getter public enum Group { PLAYER("&7", "", "&7Игрок", false), METEOR("&e", "", "&e&lMeteor", false), COMET("&d", "", "&d&lComet", false), STAR("&6", "", "&6&lStar", false), GALAXY("&5", "", "&5&lGalaxy", false), COSMO("&1", "", "&1&lCosmo", false), CHAT_MODER("&2&lCHAT MODER &2", "", "&2&lCHAT MODER", true), MODER("&9&lMODER &9", "", "&9&lMODER", true), TRUE_MODER("&3&lMODER+ &3", "", "&3&lMODER+", true), MANAGER("&9&lMANAGER &9", "", "&9&lMANAGER", true), CURATOR("&c&lCURATOR &c", "", "&c&lCURATOR", true), DEV("&9&lDEV &9", "", "&9&lDEV", true), ADMIN("&4&lADMIN &4", "", "&4&lADMIN", true); private final String prefix, suffix, displayName; private final boolean staff; Group(String prefix, String suffix, String displayName, boolean staff) { this.prefix = Core.getApi().colorize(prefix); this.suffix = Core.getApi().colorize(suffix); this.displayName = Core.getApi().colorize(displayName); this.staff = staff; } }
/* * Copyright (c) 2011, 2020, Frank Jiang and/or its affiliates. All rights * reserved. AbstractParameter.java is PROPRIETARY/CONFIDENTIAL built in 2013. * Use is subject to license terms. */ package com.frank.svm.config; import java.io.PrintStream; import libsvm.svm_parameter; import libsvm.svm_print_interface; /** * The abstract LIBSVM parameter configuration. * <p> * </p> * * @author <a href="mailto:jiangfan0576@gmail.com">Frank Jiang</a> * @version 1.0.0 */ public abstract class AbstractParameter { /** * The support vector machine type. This value should be initialized in the * constructors of the sub-classes. * * @see svm_parameter#LINEAR * @see svm_parameter#POLY * @see svm_parameter#RBF * @see svm_parameter#SIGMOID * @see svm_parameter#PRECOMPUTED */ protected int svmType; /** * The cache size of SVM in MB (default 100). */ protected double cacheSize = 100.0; /** * The tolerance of termination criterion (default 0.001) for training. */ protected double tolerance = 0.001; /** * The flag for whether shrinking technology is used (default <tt>true</tt> * ). */ protected boolean useShrinking = true; /** * The flag for whether the model supports probability estimates (default * <tt>false</tt> ). */ protected boolean useProbabilityEstimates = false; /** * The flag for whether the training and others action is do in quiet mode * (default <tt>true</tt>). A quiet mode means the SVM will run without any * console output; in opposite, some information will be print in the * console. */ protected boolean isQuietMode; /** * The SVM printer. It is mapped with the quiet mode. */ protected svm_print_interface printer; /** * The kernel type of the SVM. */ protected Kernel kernel = new KernelRBF(); /** * Configure the specified LIBSVM parameter with current parameter settings. * * @param param * the LIBSVM parameter to set */ protected void configParameter(svm_parameter param) { param.svm_type = svmType; param.cache_size = cacheSize; param.eps = tolerance; param.shrinking = useShrinking ? 1 : 0; param.probability = useProbabilityEstimates ? 1 : 0; printer = new svm_print_interface() { @Override public void print(String s) { // quiet printer, do nothing } }; kernel.configure(param); param.nr_weight = 0; param.weight = new double[0]; param.weight_label = new int[0]; } /** * Returns the LIBSVM parameter instance with the configuration of current * parameters. * * @return the parameters */ public svm_parameter getParameter() { svm_parameter param = new svm_parameter(); configParameter(param); return param; } /** * Getter for cache size in MB of the current SVM. * * @return the cache size */ public double getCacheSize() { return cacheSize; } /** * Set the cache size in MB of the current SVM (default 100). * * @param cacheSize * the value of cache size */ public void setCacheSize(double cacheSize) { if (cacheSize <= 0) throw new IllegalArgumentException(String.format( "The cache size %.4f must be positive.", cacheSize)); this.cacheSize = cacheSize; } /** * Get the tolerance of termination criterion. * * @return the tolerance */ public double getTolerance() { return tolerance; } /** * Set the tolerance of termination criterion (default 0.001). * * @param tolerance * the value of tolerance */ public void setTolerance(double tolerance) { if (tolerance <= 0) throw new IllegalArgumentException(String.format( "The tolerance %g must be positive.", tolerance)); this.tolerance = tolerance; } /** * Returns <tt>true</tt> if shrinking technology is used, otherwise * <tt>false</tt>. * * @return <tt>true</tt> if shrinking technology is used, otherwise * <tt>false</tt> */ public boolean isUseShrinking() { return useShrinking; } /** * Set whether the shrinking technology is used. * * @param useShrinking * <tt>true</tt> for using shrinking */ public void setUseShrinking(boolean useShrinking) { this.useShrinking = useShrinking; } /** * Returns <tt>true</tt> if the current SVM support probability estimates * * @return <tt>true</tt> if the current SVM support probability estimates */ public boolean isUseProbabilityEstimates() { return useProbabilityEstimates; } /** * Set whether the current SVM support probability estimates. * * @param useProbabilityEstimates * <tt>true</tt> for using probability estimates */ public void setUseProbabilityEstimates(boolean useProbabilityEstimates) { if (useProbabilityEstimates && svmType == svm_parameter.ONE_CLASS) throw new IllegalArgumentException( "One-class SVM does not support probability estimates."); this.useProbabilityEstimates = useProbabilityEstimates; } /** * Returns the kernel type. * * @return the kernel type */ public Kernel getKernel() { return kernel; } /** * Set the kernel type. * * @param kernel * the value of kernel */ public void setKernel(Kernel kernel) { this.kernel = kernel; } /** * Getter for printer. * * @return the printer */ public svm_print_interface getPrinter() { return printer; } /** * Setter for printer. If need quiet mode, just use <tt>null</tt> for the * parameter {@code printer}. * * @param printer * the value of printer */ public void setPrinter(final PrintStream printer) { if (printer != null) { isQuietMode = false; this.printer = new svm_print_interface() { @Override public void print(String s) { printer.print(s); printer.flush(); } }; } else { isQuietMode = true; this.printer = new svm_print_interface() { @Override public void print(String s) { // quiet printer, do nothing } }; } } /** * Returns the support vector machine type. * * @return the support vector machine type */ public int getSvmType() { return svmType; } /** * Set the support vector machine type. * * @param svmType * the support vector machine type */ public void setSvmType(int svmType) { this.svmType = svmType; } }
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.springframework.sync; import org.junit.jupiter.api.Test; import org.springframework.sync.operations.PatchOperation; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class DiffTest { @Test void noChanges() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); Patch diff = Diff.diff(original, modified); assertEquals(0, diff.size()); } @Test void nullPropertyToNonNullProperty() { Todo original = new Todo(null, "A", false); Todo modified = new Todo(1L, "A", false); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/id", op.getPath()); assertNull(op.getValue()); } @Test void singleBooleanPropertyChangeOnObject() { Todo original = new Todo(1L, "A", false); Todo modified = new Todo(1L, "A", true); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/complete", op.getPath()); assertFalse((Boolean) op.getValue()); op = ops.get(1); assertEquals("replace", op.getOp()); assertEquals("/complete", op.getPath()); assertTrue((Boolean) op.getValue()); } @Test void singleStringPropertyChangeOnObject() { Todo original = new Todo(1L, "A", false); Todo modified = new Todo(1L, "B", false); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/description", op.getPath()); assertEquals("A", op.getValue()); op = ops.get(1); assertEquals("replace", op.getOp()); assertEquals("/description", op.getPath()); assertEquals("B", op.getValue()); } @Test void singleNumericPropertyChangeOnObject() { Todo original = new Todo(1L, "A", false); Todo modified = new Todo(2L, "A", false); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/id", op.getPath()); assertEquals(1L, op.getValue()); op = ops.get(1); assertEquals("replace", op.getOp()); assertEquals("/id", op.getPath()); assertEquals(2L, op.getValue()); } @Test void changeTwoPropertiesOnObject() { Todo original = new Todo(1L, "A", false); Todo modified = new Todo(1L, "B", true); Patch diff = Diff.diff(original, modified); assertEquals(4, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/description", op.getPath()); assertEquals("A", op.getValue()); op = ops.get(1); assertEquals("replace", op.getOp()); assertEquals("/description", op.getPath()); assertEquals("B", op.getValue()); op = ops.get(2); assertEquals("test", op.getOp()); assertEquals("/complete", op.getPath()); assertEquals(false, op.getValue()); op = ops.get(3); assertEquals("replace", op.getOp()); assertEquals("/complete", op.getPath()); assertEquals(true, op.getValue()); } @Test void singleBooleanPropertyChangeOnItemInList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.get(1).setComplete(true); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/1/complete", op.getPath()); assertEquals(false, op.getValue()); op = ops.get(1); assertEquals("replace", op.getOp()); assertEquals("/1/complete", op.getPath()); assertEquals(true, op.getValue()); } @Test void singleStringPropertyChangeOnItemInList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.get(1).setDescription("BBB"); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/1/description", op.getPath()); assertEquals("B", op.getValue()); op = ops.get(1); assertEquals("replace", op.getOp()); assertEquals("/1/description", op.getPath()); assertEquals("BBB", op.getValue()); } @Test void singleMultiplePropertyChangeOnItemInList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.get(1).setComplete(true); modified.get(1).setDescription("BBB"); Patch diff = Diff.diff(original, modified); assertEquals(4, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/1/description", op.getPath()); assertEquals("B", op.getValue()); op = ops.get(1); assertEquals("replace", op.getOp()); assertEquals("/1/description", op.getPath()); assertEquals("BBB", op.getValue()); op = ops.get(2); assertEquals("test", op.getOp()); assertEquals("/1/complete", op.getPath()); assertEquals(false, op.getValue()); op = ops.get(3); assertEquals("replace", op.getOp()); assertEquals("/1/complete", op.getPath()); assertEquals(true, op.getValue()); } @Test void propertyChangeOnTwoItemsInList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.get(0).setDescription("AAA"); modified.get(1).setComplete(true); Patch diff = Diff.diff(original, modified); assertEquals(4, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/0/description", op.getPath()); assertEquals("A", op.getValue()); op = ops.get(1); assertEquals("replace", op.getOp()); assertEquals("/0/description", op.getPath()); assertEquals("AAA", op.getValue()); op = ops.get(2); assertEquals("test", op.getOp()); assertEquals("/1/complete", op.getPath()); assertEquals(false, op.getValue()); op = ops.get(3); assertEquals("replace", op.getOp()); assertEquals("/1/complete", op.getPath()); assertEquals(true, op.getValue()); } @Test void insertItemAtBeginningOfList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.add(0, new Todo(0L, "Z", false)); Patch diff = Diff.diff(original, modified); assertEquals(1, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("add", op.getOp()); assertEquals("/0", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(0L, value.getId().longValue()); assertEquals("Z", value.getDescription()); assertFalse(value.isComplete()); } @Test void insertTwoItemsAtBeginningOfList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.add(0, new Todo(25L, "Y", false)); modified.add(0, new Todo(26L, "Z", true)); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("add", op.getOp()); assertEquals("/0", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(26L, value.getId().longValue()); assertEquals("Z", value.getDescription()); assertTrue(value.isComplete()); op = ops.get(1); assertEquals("add", op.getOp()); assertEquals("/1", op.getPath()); value = (Todo) op.getValue(); assertEquals(25L, value.getId().longValue()); assertEquals("Y", value.getDescription()); assertFalse(value.isComplete()); } @Test void insertItemAtMiddleOfList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.add(2, new Todo(0L, "Z", false)); Patch diff = Diff.diff(original, modified); assertEquals(1, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("add", op.getOp()); assertEquals("/2", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(0L, value.getId().longValue()); assertEquals("Z", value.getDescription()); assertFalse(value.isComplete()); } @Test void insertTwoItemsAtMiddleOfList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.add(2, new Todo(25L, "Y", false)); modified.add(2, new Todo(26L, "Z", true)); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("add", op.getOp()); assertEquals("/2", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(26L, value.getId().longValue()); assertEquals("Z", value.getDescription()); assertTrue(value.isComplete()); op = ops.get(1); assertEquals("add", op.getOp()); assertEquals("/3", op.getPath()); value = (Todo) op.getValue(); assertEquals(25L, value.getId().longValue()); assertEquals("Y", value.getDescription()); assertFalse(value.isComplete()); } @Test void insertItemAtEndOfList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.add(3, new Todo(0L, "Z", false)); Patch diff = Diff.diff(original, modified); assertEquals(1, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("add", op.getOp()); assertEquals("/3", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(0L, value.getId().longValue()); assertEquals("Z", value.getDescription()); assertFalse(value.isComplete()); } @Test void insertTwoItemsAtEndOfList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.add(3, new Todo(25L, "Y", false)); modified.add(4, new Todo(26L, "Z", true)); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("add", op.getOp()); assertEquals("/3", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(25L, value.getId().longValue()); assertEquals("Y", value.getDescription()); assertFalse(value.isComplete()); op = ops.get(1); assertEquals("add", op.getOp()); assertEquals("/4", op.getPath()); value = (Todo) op.getValue(); assertEquals(26L, value.getId().longValue()); assertEquals("Z", value.getDescription()); assertTrue(value.isComplete()); } @Test void insertItemsAtBeginningAndEndOfList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.add(0, new Todo(25L, "Y", false)); modified.add(4, new Todo(26L, "Z", true)); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("add", op.getOp()); assertEquals("/0", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(25L, value.getId().longValue()); assertEquals("Y", value.getDescription()); assertFalse(value.isComplete()); op = ops.get(1); assertEquals("add", op.getOp()); assertEquals("/4", op.getPath()); value = (Todo) op.getValue(); assertEquals(26L, value.getId().longValue()); assertEquals("Z", value.getDescription()); assertTrue(value.isComplete()); } @Test void removeItemFromBeginningOfList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.remove(0); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/0", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(1L, value.getId().longValue()); assertEquals("A", value.getDescription()); assertFalse(value.isComplete()); op = ops.get(1); assertEquals("remove", op.getOp()); assertEquals("/0", op.getPath()); } @Test void removeItemFromMiddleOfList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.remove(1); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/1", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(2L, value.getId().longValue()); assertEquals("B", value.getDescription()); assertFalse(value.isComplete()); op = ops.get(1); assertEquals("remove", op.getOp()); assertEquals("/1", op.getPath()); } @Test void removeItemFromEndOfList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.remove(2); Patch diff = Diff.diff(original, modified); assertEquals(2, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/2", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(3L, value.getId().longValue()); assertEquals("C", value.getDescription()); assertFalse(value.isComplete()); op = ops.get(1); assertEquals("remove", op.getOp()); assertEquals("/2", op.getPath()); } @Test void removeAllItemsFromList() { List<Todo> original = buildTodoList(); List<Todo> modified = buildTodoList(); modified.remove(0); modified.remove(0); modified.remove(0); Patch diff = Diff.diff(original, modified); assertEquals(6, diff.size()); List<PatchOperation> ops = diff.getOperations(); PatchOperation op = ops.get(0); assertEquals("test", op.getOp()); assertEquals("/0", op.getPath()); Todo value = (Todo) op.getValue(); assertEquals(1L, value.getId().longValue()); assertEquals("A", value.getDescription()); assertFalse(value.isComplete()); op = ops.get(1); assertEquals("remove", op.getOp()); assertEquals("/0", op.getPath()); op = ops.get(2); assertEquals("test", op.getOp()); assertEquals("/0", op.getPath()); value = (Todo) op.getValue(); assertEquals(2L, value.getId().longValue()); assertEquals("B", value.getDescription()); assertFalse(value.isComplete()); op = ops.get(3); assertEquals("remove", op.getOp()); assertEquals("/0", op.getPath()); op = ops.get(4); assertEquals("test", op.getOp()); assertEquals("/0", op.getPath()); value = (Todo) op.getValue(); assertEquals(3L, value.getId().longValue()); assertEquals("C", value.getDescription()); assertFalse(value.isComplete()); op = ops.get(5); assertEquals("remove", op.getOp()); assertEquals("/0", op.getPath()); } @Test void addEntryToListProperty() { ArrayList<Todo> todos = new ArrayList<>(); todos.add(new Todo(1L, "A", false)); todos.add(new Todo(2L, "B", false)); todos.add(new Todo(3L, "C", false)); TodoList before = new TodoList(); before.setTodos(todos); todos = new ArrayList<>(); todos.add(new Todo(1L, "A", false)); todos.add(new Todo(2L, "B", false)); todos.add(new Todo(3L, "C", false)); todos.add(new Todo(4L, "D", false)); TodoList after = new TodoList(); after.setTodos(todos); Patch diff = Diff.diff(before, after); List<PatchOperation> operations = diff.getOperations(); assertEquals(1, diff.size()); assertEquals("add", operations.get(0).getOp()); assertEquals("/todos/3", operations.get(0).getPath()); assertEquals(new Todo(4L, "D", false), operations.get(0).getValue()); } @Test void removeEntryFromListProperty() { ArrayList<Todo> todos = new ArrayList<>(); todos.add(new Todo(1L, "A", false)); todos.add(new Todo(2L, "B", false)); todos.add(new Todo(3L, "C", false)); TodoList before = new TodoList(); before.setTodos(todos); todos = new ArrayList<>(); todos.add(new Todo(1L, "A", false)); todos.add(new Todo(3L, "C", false)); TodoList after = new TodoList(); after.setTodos(todos); Patch diff = Diff.diff(before, after); List<PatchOperation> operations = diff.getOperations(); assertEquals(2, diff.size()); assertEquals("test", operations.get(0).getOp()); assertEquals("/todos/1", operations.get(0).getPath()); assertEquals(new Todo(2L, "B", false), operations.get(0).getValue()); assertEquals("remove", operations.get(1).getOp()); assertEquals("/todos/1", operations.get(1).getPath()); } @Test void editEntryInListProperty() { ArrayList<Todo> todos = new ArrayList<>(); todos.add(new Todo(1L, "A", false)); todos.add(new Todo(2L, "B", false)); todos.add(new Todo(3L, "C", false)); TodoList before = new TodoList(); before.setTodos(todos); todos = new ArrayList<>(); todos.add(new Todo(1L, "A", false)); todos.add(new Todo(2L, "BBB", true)); todos.add(new Todo(3L, "C", false)); TodoList after = new TodoList(); after.setTodos(todos); Patch diff = Diff.diff(before, after); List<PatchOperation> operations = diff.getOperations(); assertEquals(4, diff.size()); assertEquals("test", operations.get(0).getOp()); assertEquals("/todos/1/description", operations.get(0).getPath()); assertEquals("B", operations.get(0).getValue()); assertEquals("replace", operations.get(1).getOp()); assertEquals("/todos/1/description", operations.get(1).getPath()); assertEquals("BBB", operations.get(1).getValue()); assertEquals("test", operations.get(2).getOp()); assertEquals("/todos/1/complete", operations.get(2).getPath()); assertEquals(false, operations.get(2).getValue()); assertEquals("replace", operations.get(3).getOp()); assertEquals("/todos/1/complete", operations.get(3).getPath()); assertEquals(true, operations.get(3).getValue()); } @Test void addEntryToArrayProperty() { Todo[] todos = new Todo[3]; todos[0] = new Todo(1L, "A", false); todos[1] = new Todo(2L, "B", false); todos[2] = new Todo(3L, "C", false); TodoList before = new TodoList(); before.setTodoArray(todos); todos = new Todo[4]; todos[0] = new Todo(1L, "A", false); todos[1] = new Todo(2L, "B", false); todos[2] = new Todo(3L, "C", false); todos[3] = new Todo(4L, "D", false); TodoList after = new TodoList(); after.setTodoArray(todos); Patch diff = Diff.diff(before, after); List<PatchOperation> operations = diff.getOperations(); assertEquals(1, diff.size()); assertEquals("add", operations.get(0).getOp()); assertEquals("/todoArray/3", operations.get(0).getPath()); assertEquals(new Todo(4L, "D", false), operations.get(0).getValue()); } @Test void removeEntryFromArrayProperty() { Todo[] todos = new Todo[3]; todos[0] = new Todo(1L, "A", false); todos[1] = new Todo(2L, "B", false); todos[2] = new Todo(3L, "C", false); TodoList before = new TodoList(); before.setTodoArray(todos); todos = new Todo[2]; todos[0] = new Todo(1L, "A", false); todos[1] = new Todo(3L, "C", false); TodoList after = new TodoList(); after.setTodoArray(todos); Patch diff = Diff.diff(before, after); List<PatchOperation> operations = diff.getOperations(); assertEquals(2, diff.size()); assertEquals("test", operations.get(0).getOp()); assertEquals("/todoArray/1", operations.get(0).getPath()); assertEquals(new Todo(2L, "B", false), operations.get(0).getValue()); assertEquals("remove", operations.get(1).getOp()); assertEquals("/todoArray/1", operations.get(1).getPath()); } @Test void editEntryInArrayProperty() { Todo[] todos = new Todo[3]; todos[0] = new Todo(1L, "A", false); todos[1] = new Todo(2L, "B", false); todos[2] = new Todo(3L, "C", false); TodoList before = new TodoList(); before.setTodoArray(todos); todos = new Todo[3]; todos[0] = new Todo(1L, "A", false); todos[1] = new Todo(2L, "BBB", true); todos[2] = new Todo(3L, "C", false); TodoList after = new TodoList(); after.setTodoArray(todos); Patch diff = Diff.diff(before, after); List<PatchOperation> operations = diff.getOperations(); assertEquals(4, diff.size()); assertEquals("test", operations.get(0).getOp()); assertEquals("/todoArray/1/description", operations.get(0).getPath()); assertEquals("B", operations.get(0).getValue()); assertEquals("replace", operations.get(1).getOp()); assertEquals("/todoArray/1/description", operations.get(1).getPath()); assertEquals("BBB", operations.get(1).getValue()); assertEquals("test", operations.get(2).getOp()); assertEquals("/todoArray/1/complete", operations.get(2).getPath()); assertEquals(false, operations.get(2).getValue()); assertEquals("replace", operations.get(3).getOp()); assertEquals("/todoArray/1/complete", operations.get(3).getPath()); assertEquals(true, operations.get(3).getValue()); } private List<Todo> buildTodoList() { List<Todo> original = new ArrayList<>(); original.add(new Todo(1L, "A", false)); original.add(new Todo(2L, "B", false)); original.add(new Todo(3L, "C", false)); return original; } }
package io.zipcoder.pets; /** * Created by joseph on 2/2/16. */ public class App { public static void main(String[] args) { PetQuery pq = new PetQuery(); pq.showPets(); } }
package com.example.user.myapplication.main.activity.fragment; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.example.user.myapplication.R; import com.example.user.myapplication.domain.Product; import com.example.user.myapplication.lockscreen.task.GetTotalTask; import com.example.user.myapplication.lockscreen.task.ProductsTask; import com.example.user.myapplication.main.activity.Tab2DetailActivity; import com.example.user.myapplication.main.activity.adapter.Tab2BaseAdapter; import java.util.concurrent.ExecutionException; @SuppressLint("ValidFragment") public class Tab2 extends Fragment { private ListView listView; Product[] products; public int MAX; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_tab2, container,false); listView = (ListView)view.findViewById(R.id.productlistview); setAdapter(); // listview경계 listView.setDivider(new ColorDrawable(Color.BLACK)); listView.setDividerHeight(3); //Click listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(getActivity(),Tab2DetailActivity.class); i.putExtra("product", products[position]); startActivity(i); } }); return view; } private void setAdapter(){ Integer[] productPoint; Integer[] productImage; try{ products = new ProductsTask().execute().get(); MAX = new GetTotalTask().execute().get(); productPoint = new Integer[MAX]; for(int i=0;i<MAX;i++){ productPoint[i] = products[i].getPoint(); } productImage = productPoint; Tab2BaseAdapter listViewAdapter = new Tab2BaseAdapter(getActivity(),R.layout.tab2_list_view_item_layout,R.id.product_icon,productImage); listView.setAdapter(listViewAdapter); }catch(InterruptedException e){ }catch (ExecutionException e){ } } }
package com.tingke.admin.controller; import com.tingke.admin.entity.AclEvent; import com.tingke.admin.model.R; import com.tingke.admin.service.AclEventService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.text.ParseException; /** * <p> * 前端控制器 * </p> * * @author zhx * @since 2020-05-19 */ @Api(value="后台管理“事件”管理接口",description = "后台管理“事件”管理,增删改查") @RestController @RequestMapping("/admin/acl-event") @CrossOrigin public class AclEventController { @Autowired private AclEventService aclEventService; @ApiOperation("添加事件") @GetMapping("/addEvent/{event}") @ApiImplicitParam(name="event",value = "内容",required=true,paramType="path") public R addEvent(@PathVariable("event")String content){ R responseResult = aclEventService.addEvent(content); return responseResult; } @ApiOperation("修改事件") @PostMapping("/editEvent") public R editEvent(@RequestBody AclEvent aclEvent){ R responseResult = aclEventService.editEvent(aclEvent); return responseResult; } @ApiOperation("完成事件") @GetMapping("/completeEvent/{id}") @ApiImplicitParam(name="id",value = "主键",required=true,paramType="path") public R completeEvent(@PathVariable("id")String id){ R responseResult = aclEventService.completeEvent(id); return responseResult; } @ApiOperation("遍历返回事件") @PostMapping("/selectEvent") public R selectEvent(){ R responseResult = aclEventService.selectEvent(); return responseResult; } @ApiOperation("通过id查询") @PostMapping("/selectOneEvent/{id}") @ApiImplicitParam(name="id",value = "主键",required=true,paramType="path") public R selectOneEvent(@PathVariable("id")String id){ R responseResult = aclEventService.selectOneEvent(id); return responseResult; } @ApiOperation("根据日期查询事件") @GetMapping("/selectEventByDate/{date}") @ApiImplicitParam(name="date",value = "日期",required=true,paramType="path") public R selectEventByDate(@PathVariable("date")String date) throws ParseException { R responseResult = aclEventService.selectEventByDate(date); return responseResult; } @ApiOperation("根据ids删除事件") @GetMapping("/deleteEventByIds/{ids}") @ApiImplicitParam(name="ids",value = "日期",required=true,paramType="path") public R deleteEventByIds(@PathVariable("ids") String ids) throws ParseException { R responseResult = aclEventService.deleteEventByIds(ids); return responseResult; } }
/* * #%L * OpenEHR - Java Model Stack * %% * Copyright (C) 2016 - 2017 Cognitive Medical Systems, Inc (http://www.cognitivemedicine.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. * #L% * Author: Claude Nanjo */ package org.openehr.utils.message; public class GlobalMessageLoggingLevel { /** * At this level and above, list entries are included in `as_string' and any other output function */ private static Integer globalLoggingLevel = MessageSeverityTypes.ERROR_TYPE_WARNING; public static Integer getGlobalLoggingLevel() { return globalLoggingLevel; } public static void setGlobalLoggingLevel(Integer globalLoggingLevel) { if(MessageSeverityTypes.isValidErrorType(globalLoggingLevel)) { GlobalMessageLoggingLevel.globalLoggingLevel = globalLoggingLevel; } else { throw new IllegalArgumentException("Invalid global error reporting level " + globalLoggingLevel); } } }
package polydungeons.item.charms; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.Vec3d; import polydungeons.entity.PolyDungeonsEntities; import polydungeons.entity.charms.AnchorEntity; import polydungeons.entity.charms.SubstituteEntity; public class SubstituteCharmItem extends CharmItem { @Override boolean createEntity(PlayerEntity creator, Vec3d pos) { SubstituteEntity newEntity = new SubstituteEntity(PolyDungeonsEntities.SUBSTITUTE, creator.getEntityWorld()); newEntity.updatePosition(pos.x, pos.y + 1.5, pos.z); creator.getEntityWorld().spawnEntity(newEntity); return true; } }
package renderer; import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import java.util.List; import renderer.sub.TextElement; public class TextRenderer implements Renderable{ private static List<TextElement> toRender = new ArrayList<>(); private Graphics g; public void setG(Graphics g) { this.g = g; } public static void text(String text, int x, int y, Color c, int size){ toRender.add(new TextElement(text, x, y, c, size)); } public void render(Graphics g){ for(TextElement e : new ArrayList<>(toRender)){ e.render(g); } toRender.clear(); } }
/** * Javassonne * http://code.google.com/p/javassonne/ * * @author [Add Name Here] * @date Feb 12, 2009 * * Copyright 2009 Javassonne Team * 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.javassonne.model; import java.util.ArrayList; import java.util.HashMap; public class TileFeatureBindings { HashMap<String, ArrayList<String>> bindings_ = new HashMap<String, ArrayList<String>>(); HashMap<String, String> completionMultipliers_ = new HashMap<String, String>(); public TileFeatureBindings() { } public Integer completionMultiplierForFeature(String identifier) { return Integer.parseInt(completionMultipliers_.get(identifier)); } public void addCompletionMultiplierForFeature(String identifier, String multiplier) { completionMultipliers_.put(identifier, multiplier); } public void addCompletionMultipliers(TileFeatureBindings other) { completionMultipliers_.putAll(other.completionMultipliers_); } public Boolean featuresBind(String identifier1, String identifier2) { if (bindings_.containsKey(identifier1)) return bindings_.get(identifier1).contains(identifier2); else return false; } public Boolean featuresBind(TileFeature feature1, TileFeature feature2) { if (feature1 == null && feature2 == null) return true; else if (feature1 == null || feature2 == null) return false; else if (bindings_.containsKey(feature1.identifier)) return bindings_.get(feature1.identifier).contains( feature2.identifier); else return false; } public void addFeatureBinding(String identifier1, String identifier2) { if (bindings_.containsKey(identifier1) == false) bindings_.put(identifier1, new ArrayList<String>()); if (bindings_.containsKey(identifier2) == false) bindings_.put(identifier2, new ArrayList<String>()); bindings_.get(identifier1).add(identifier2); if (identifier1.equals(identifier2) == false) bindings_.get(identifier2).add(identifier1); } public void addFeatureBindings(TileFeatureBindings other) { bindings_.putAll(other.bindings_); } }
package com.jenmaarai.sidekick.swing; import java.util.ArrayList; import java.util.List; import javax.swing.Icon; import javax.swing.JCheckBox; /** * A kind of check box that can work as part of a complex group of checkboxes. * This component maintains a list of <tt>JCheckBox</tt>es refered to as * <em>constraints</em> that dictate wether or not the checkbox is enabled * based on the current state of the constraints. */ public class LinkedCheckBox extends JCheckBox { private List<CheckBoxConstraint> constraints; /** * Creates an unconstrained check box. */ public LinkedCheckBox() { this(null, null, false); } /** * Creates an unconstrained check box with given text. */ public LinkedCheckBox(String text) { this(text, null, false); } /** * Creates an unconstrained check box with given text. * If <tt>selected</tt> the check box will be ticked. */ public LinkedCheckBox(String text, boolean selected) { this(text, null, selected); } /** * Creates an unconstrained check box with a specific icon. */ public LinkedCheckBox(Icon icon) { this(null, icon, false); } /** * Creates an unconstrained check box with a specific icon. * If <tt>selected</tt> the check box will be ticked. */ public LinkedCheckBox(Icon icon, boolean selected) { this(null, icon, selected); } /** * Creates an unconstrained check box with a specific text and icon. */ public LinkedCheckBox(String text, Icon icon) { this(text, icon, false); } /** * Creates an unconstrained check box with a specific text and icon. * If <tt>selected</tt> the check box will be ticked. */ public LinkedCheckBox(String text, Icon icon, boolean selected) { super(text, icon, selected); constraints = new ArrayList<>(); } /** * Adds a constraining checkbox to this one. * For this checkbox to become enabled, every constraining checkbox must be * in the specified select state. In other words, the following expression * must be true for every constraint: <tt>box.isSelected() == state</tt> */ public void requires(JCheckBox box, boolean state) { if (box == null) { throw new IllegalArgumentException("box is null"); } constraints.add(new CheckBoxConstraint(box, state)); // Check whenever the constraint is selected or deselected box.addActionListener((evt) -> checkConstraints()); // Check whenever the constraint is enabled or disabled box.addPropertyChangeListener("enabled", (evt) -> checkConstraints()); // Check immediately checkConstraints(); } /** * Sets the enabled state of this checkbox. * If this box is constrained, changing its enabled state will do nothing. */ @Override public void setEnabled(boolean b) { if (constraints.isEmpty()) { super.setEnabled(b); } } /** * Check all checkboxes constraints and enables this checkbox if they are * met. For this checkbox to become enabled, every constraining checkbox * must be in the state specified during the call to <tt>requires()</tt> */ protected void checkConstraints() { boolean enabled = true; for (CheckBoxConstraint c : constraints) { enabled &= (c.checkBox.isSelected() == c.targetState); } super.setEnabled(enabled); } /** * Simple structure to store a constraining checkbox. */ private class CheckBoxConstraint { private JCheckBox checkBox; private boolean targetState; private CheckBoxConstraint(JCheckBox checkBox, boolean targetState) { this.checkBox = checkBox; this.targetState = targetState; } } }
package com.espendwise.manta.service; import com.espendwise.manta.model.data.BusEntityData; import com.espendwise.manta.model.data.StoreMessageData; import com.espendwise.manta.model.entity.StoreMessageEntity; import com.espendwise.manta.model.entity.StoreMessageListEntity; import com.espendwise.manta.model.view.EntityHeaderView; import com.espendwise.manta.model.view.StoreMessageListView; import com.espendwise.manta.util.StoreMessageUpdateRequest; import com.espendwise.manta.util.UpdateRequest; import com.espendwise.manta.util.criteria.StoreMessageDataCriteria; import com.espendwise.manta.util.criteria.StoreMsgAccountConfigCriteria; import com.espendwise.manta.util.validation.ValidationException; import java.util.List; public interface StoreMessageService { public StoreMessageEntity saveMessageData(StoreMessageUpdateRequest updateRequest) throws ValidationException; public StoreMessageData findStoreMessage(Long storeId, Long storeMessageId); public List<StoreMessageListView> findMessagesByCriteria(StoreMessageDataCriteria criteria); public List<BusEntityData> findConfiguratedAccounts(StoreMsgAccountConfigCriteria criteria); public void configureAllAccounts(Long storeId, Long storeMessageId, Boolean activeOnly); public void configureAccounts(Long storeId, Long storeMessageId, UpdateRequest<Long> configurationRequest); public EntityHeaderView findStoreMessageHeader(Long storeMessageId); public StoreMessageEntity findStoreMessages(Long storeMessageId); public void deleteTranslation(Long storeMessageId, Long storeMessageDetailId); }
public class Game{ public String namaHero; public Game(String namaHero){ this.namaHero = namaHero; } public void showNamaHero(){ System.out.println(namaHero); } }
package SvgPac; import java.awt.Color; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.Serializable; public abstract class SvgShape extends SvgObject { private static final long serialVersionUID = -6257433982022624430L; public final class Style extends SvgLineStyle implements Serializable { private static final long serialVersionUID = 2165229794287610906L; public boolean fill = true; public Color fill_color = Color.yellow; public Style() { super(); } public final void read(BufferedReader br) throws IOException { System.out.print("\tfill="); String str = br.readLine(); if (str.equals("none") || str.isEmpty()) { fill = false; } else { try { String[] rgb = str.split(","); fill_color = new Color( Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2])); } catch (Exception e) { fill = false; } } super.read(br); } @Override public void save(DataOutputStream stream) throws IOException { stream.writeBoolean(fill); SvgHelper.writeColor(stream, fill_color); super.save(stream); } @Override public void load(DataInputStream stream) throws IOException { fill = stream.readBoolean(); fill_color = SvgHelper.readColor(stream); super.load(stream); } @Override public String toString() { return String.format("fill=\"%s\" stroke=\"%s\" stroke-width=\"%s\" opacity=\"%s\"", fill ? SvgHelper.colorToString(fill_color) : "none", stroke ? SvgHelper.colorToString(stroke_color) : "none", SvgHelper.floatToString(stroke_width), SvgHelper.floatToString(opacity)); } public final Color fillWithAlpha() { return new Color( fill_color.getRed(), fill_color.getGreen(), fill_color.getBlue(), Math.round(255 * opacity)); } } protected Style style = new Style(); public SvgShape() { super(); } public Style getStyle() { return style; } }
package com.bozhong.lhdataaccess.domain; import java.util.Date; /** * User: 李志坚 * Date: 2018/11/5 * 医生处方的Model对象 */ public class DoctorPrescriptionDO { private Long id; private String doctorPrescriptionNumber; private String patientId; private String organizStructureCode; private String drugName; private String doctorPrescriptionClassific; private Date lastEditedTime; private String validFlag; private Long createId; private Date createTime; private Long updateId; private Date updateTime; private int count; public void setCount(int count) { this.count = count; } public Date getLastEditedTime() { return lastEditedTime; } public void setLastEditedTime(Date lastEditedTime) { this.lastEditedTime = lastEditedTime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDoctorPrescriptionNumber() { return doctorPrescriptionNumber; } public void setDoctorPrescriptionNumber(String doctorPrescriptionNumber) { this.doctorPrescriptionNumber = doctorPrescriptionNumber == null ? null : doctorPrescriptionNumber.trim(); } public String getPatientId() { return patientId; } public void setPatientId(String patientId) { this.patientId = patientId == null ? null : patientId.trim(); } public String getOrganizStructureCode() { return organizStructureCode; } public void setOrganizStructureCode(String organizStructureCode) { this.organizStructureCode = organizStructureCode == null ? null : organizStructureCode.trim(); } public String getDrugName() { return drugName; } public void setDrugName(String drugName) { this.drugName = drugName; } public String getDoctorPrescriptionClassific() { return doctorPrescriptionClassific; } public void setDoctorPrescriptionClassific(String doctorPrescriptionClassific) { this.doctorPrescriptionClassific = doctorPrescriptionClassific == null ? null : doctorPrescriptionClassific.trim(); } public String getValidFlag() { return validFlag; } public void setValidFlag(String validFlag) { this.validFlag = validFlag; } public Long getCreateId() { return createId; } public void setCreateId(Long createId) { this.createId = createId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getUpdateId() { return updateId; } public void setUpdateId(Long updateId) { this.updateId = updateId; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
package kyle.game.besiege.party; //package kyle.game.besiege.playerPartyPanel; // //import com.badlogic.gdx.utils.Array; //import static kyle.game.besiege.playerPartyPanel.Weapon.*; // //public enum UnitType { // BANDITS(new Weapon[]{MILITARY_FORK, HATCHET, CLUB, SPEAR, MACE, SHORTBOW, RECURVE, LONGBOW}), // PEASANTS(new Weapon[]{PITCHFORK, MILITARY_FORK, HATCHET, CLUB, SHORTBOW}), // FARMERS(new Weapon[]{PITCHFORK, MILITARY_FORK, HATCHET}), // // POLEAXE_BAD(new Weapon[]{SPEAR}), // POLEAXE_MED(new Weapon[]{PIKE, HALBERD}), // POLEAXE_BEST(new Weapon[]{VOULGE, GUISARME}), // // MOUNTED_MED(new Weapon[]{CAVALRY_AXE, CAVALRY_SPEAR, CAVALRY_PICK}), // KNIGHT(new Weapon[]{LANCE, FLAIL, ARMING_SWORD}), // // RANGED_BAD(new Weapon[]{SHORTBOW}), // RANGED_MED(new Weapon[]{SHORTBOW, CROSSBOW, LONGBOW, RECURVE}), // RANGED_GOOD(new Weapon[]{ADV_CROSSBOW, ADV_LONGBOW, ADV_RECURVE}), // // LIGHT_BAD(new Weapon[]{CLUB, HATCHET}), // LIGHT_MED(new Weapon[]{SHORTSWORD, MACE, WAR_HAMMER}), // LIGHT_GOOD(new Weapon[]{MORNINGSTAR, FALCHION}), // // HEAVY_MED(new Weapon[]{LONGSWORD, BATTLE_AXE}), // HEAVY_GOOD(new Weapon[]{GREATSWORD, MAUL, GLAIVE}), // // INFANTRY_BAD(new Weapon[]{CLUB, HATCHET, SPEAR}), // INFANTRY_MED(new Weapon[]{PIKE, HALBERD, SHORTSWORD, MACE, WAR_HAMMER, LONGSWORD, BATTLE_AXE}), // INFANTRY_GOOD(new Weapon[]{VOULGE, GUISARME, MORNINGSTAR, FALCHION, GREATSWORD, MAUL, GLAIVE}); // // private Array<Weapon> types; // // private UnitType(Weapon[] weapons) { // this.types = new Array<Weapon>(weapons); // } // // public Weapon random() { // return types.random(); // } //}
package com.pingcap.tools.cdb.binlog.instance.core; import com.pingcap.tools.cdb.binlog.common.CDBLifeCycle; import com.pingcap.tools.cdb.binlog.listener.CDBEventListener; /** * Created by iamxy on 2017/2/16. */ public interface CDBInstance extends CDBLifeCycle { String getDestination(); CDBEventListener getEventListener(); }
package rt.intersectables; import javax.vecmath.*; import rt.BoundingBox; import rt.HitRecord; import rt.Intersectable; import rt.Ray; /** * Defines a triangle by referring back to a {@link Mesh} * and its vertex and index arrays. */ public class MeshTriangle implements Intersectable { private Mesh mesh; private int index; /** * Make a triangle. * * @param mesh the mesh storing the vertex and index arrays * @param index the index of the triangle in the mesh */ public MeshTriangle(Mesh mesh, int index) { this.mesh = mesh; this.index = index; } public HitRecord intersect(Ray r) { HitRecord hr = new HitRecord(); hr.intersectable = mesh; hr.material = mesh.material; hr.w = new Vector3f(r.direction); hr.w.negate(); hr.w.normalize(); float vertices[] = mesh.vertices; float normals[] = mesh.normals; // Access the triangle vertices as follows (same for the normals): // 1. Get three vertex indices for triangle int v0 = mesh.indices[index*3]; int v1 = mesh.indices[index*3+1]; int v2 = mesh.indices[index*3+2]; // 2. Access x,y,z coordinates for each vertex float x0 = vertices[v0*3]; float x1 = vertices[v1*3]; float x2 = vertices[v2*3]; float y0 = vertices[v0*3+1]; float y1 = vertices[v1*3+1]; float y2 = vertices[v2*3+1]; float z0 = vertices[v0*3+2]; float z1 = vertices[v1*3+2]; float z2 = vertices[v2*3+2]; // 2. Access x,y,z coordinates for each normal float nx0 = normals[v0*3]; float nx1 = normals[v1*3]; float nx2 = normals[v2*3]; float ny0 = normals[v0*3+1]; float ny1 = normals[v1*3+1]; float ny2 = normals[v2*3+1]; float nz0 = normals[v0*3+2]; float nz1 = normals[v1*3+2]; float nz2 = normals[v2*3+2]; Matrix3f mat = new Matrix3f(x0 - x1, x0 - x2, r.direction.x, y0 - y1, y0 - y2, r.direction.y, z0 - z1, z0 - z2, r.direction.z); try{ mat.invert(); }catch(SingularMatrixException e) { return null; } Vector3f v = new Vector3f(x0 - r.origin.x, y0 - r.origin.y, z0 - r.origin.z); mat.transform(v); float beta = v.x; float gamma = v.y; float alpha = 1 - beta - gamma; hr.t = v.z; if(beta < 0 || gamma < 0 || beta + gamma > 1 || hr.t < 0) // no hit { return null; } hr.position = new Vector3f(r.origin.x + r.direction.x*hr.t, r.origin.y + r.direction.y*hr.t, r.origin.z + r.direction.z*hr.t); hr.normal = new Vector3f(alpha*nx0 + beta*nx1 + gamma*nx2, alpha*ny0 + beta*ny1 + gamma*ny2, alpha*nz0 + beta*nz1 + gamma*nz2); hr.normal.normalize(); hr.t1 = new Vector3f(x1 - x0, y1 - y0, z1 - z0); hr.t1.normalize(); hr.t2 = new Vector3f(); hr.t2.cross(hr.normal, hr.t1); return hr; } @Override public BoundingBox getBoundingBox() { float vertices[] = mesh.vertices; // Access the triangle vertices as follows (same for the normals): // 1. Get three vertex indices for triangle int v0 = mesh.indices[index*3]; int v1 = mesh.indices[index*3+1]; int v2 = mesh.indices[index*3+2]; // 2. Access x,y,z coordinates for each vertex float x0 = vertices[v0*3]; float x1 = vertices[v1*3]; float x2 = vertices[v2*3]; float y0 = vertices[v0*3+1]; float y1 = vertices[v1*3+1]; float y2 = vertices[v2*3+1]; float z0 = vertices[v0*3+2]; float z1 = vertices[v1*3+2]; float z2 = vertices[v2*3+2]; return new BoundingBox(min(x0,x1,x2),max(x0,x1,x2),min(y0,y1,y2),max(y0,y1,y2),min(z0,z1,z2),max(z0,z1,z2)); } private float min(float a, float b, float c) { return (a<b)?((a<c)?(a):(c)):((b<c)?(b):(c)); } private float max(float a, float b, float c) { return (a>b)?((a>c)?(a):(c)):((b>c)?(b):(c)); } }
package zm.gov.moh.core.repository.database.entity.domain; import androidx.room.*; import zm.gov.moh.core.repository.database.entity.SynchronizableEntity; import com.squareup.moshi.Json; import org.threeten.bp.LocalDateTime; @Entity(tableName = "person_name") public class PersonName extends SynchronizableEntity { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "person_name_id") @Json(name = "person_name_id") private long personNameId; @ColumnInfo(name = "preferred") @Json(name = "preferred") private short preferred; @ColumnInfo(name = "person_id") @Json(name = "person_id") private long personId; @ColumnInfo(name = "prefix") @Json(name = "prefix") private String prefix; @ColumnInfo(name = "given_name") @Json(name = "given_name") private String givenName; @ColumnInfo(name = "middle_name") @Json(name = "middle_name") private String middleName; @ColumnInfo(name = "family_name_prefix") @Json(name = "family_name_prefix") private String familyNamePrefix; @ColumnInfo(name = "family_name") @Json(name = "family_name") private String familyName; @ColumnInfo(name = "family_name2") @Json(name = "family_name2") private String familyName2; @ColumnInfo(name = "family_name_suffix") @Json(name = "family_name_suffix") private String familyNameSuffix; @ColumnInfo(name = "degree") @Json(name = "degree") private String degree; @ColumnInfo(name = "creator") @Json(name = "creator") private long creator; @ColumnInfo(name = "date_created") @Json(name = "date_created") private LocalDateTime dateCreated; @ColumnInfo(name = "voided") @Json(name = "voided") private short voided; @ColumnInfo(name = "voided_by") @Json(name = "voided_by") private Long voidedBy; @ColumnInfo(name = "date_voided") @Json(name = "date_voided") private LocalDateTime dateVoided; @ColumnInfo(name = "void_reason") @Json(name = "void_reason") private String voidReason; @ColumnInfo(name = "changed_by") @Json(name = "changed_by") private Long changedBy; @ColumnInfo(name = "date_changed") @Json(name = "date_changed") private LocalDateTime dateChanged; @ColumnInfo(name = "uuid") @Json(name = "uuid") private String uuid; public PersonName(long personId, String givenName, String familyName, short preferred){ this.personId = personId; this.givenName = givenName; this.familyName = familyName; this.preferred = preferred; } @Ignore public PersonName(long personNameId, long personId, String givenName, String familyName, short preferred,LocalDateTime dateCreated){ this.personNameId = personNameId; this.personId = personId; this.givenName = givenName; this.familyName = familyName; this.preferred = preferred; this.dateCreated = dateCreated; this.dateChanged = dateCreated; } public long getPersonNameId() { return personNameId; } public void setPersonNameId(long personNameId) { this.personNameId = personNameId; } public short getPreferred() { return preferred; } public void setPreferred(short preferred) { this.preferred = preferred; } @Override public long getId() { return personNameId; } public long getPersonId() { return personId; } public void setPersonId(long personId) { this.personId = personId; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getGivenName() { return givenName; } public void setGivenName(String givenName) { this.givenName = givenName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getFamilyNamePrefix() { return familyNamePrefix; } public void setFamilyNamePrefix(String familyNamePrefix) { this.familyNamePrefix = familyNamePrefix; } public String getFamilyName() { return familyName; } public void setFamilyName(String familyName) { this.familyName = familyName; } public String getFamilyName2() { return familyName2; } public void setFamilyName2(String familyName2) { this.familyName2 = familyName2; } public String getFamilyNameSuffix() { return familyNameSuffix; } public void setFamilyNameSuffix(String familyNameSuffix) { this.familyNameSuffix = familyNameSuffix; } public String getDegree() { return degree; } public void setDegree(String degree) { this.degree = degree; } public long getCreator() { return creator; } public void setCreator(long creator) { this.creator = creator; } public LocalDateTime getDateCreated() { return dateCreated; } public void setDateCreated(LocalDateTime dateCreated) { this.dateCreated = dateCreated; } public short getVoided() { return voided; } public void setVoided(short voided) { this.voided = voided; } public Long getVoidedBy() { return voidedBy; } public void setVoidedBy(Long voidedBy) { this.voidedBy = voidedBy; } public LocalDateTime getDateVoided() { return dateVoided; } public void setDateVoided(LocalDateTime dateVoided) { this.dateVoided = dateVoided; } public String getVoidReason() { return voidReason; } public void setVoidReason(String voidReason) { this.voidReason = voidReason; } public Long getChangedBy() { return changedBy; } public void setChangedBy(Long changedBy) { this.changedBy = changedBy; } public LocalDateTime getDateChanged() { return dateChanged; } public void setDateChanged(LocalDateTime dateChanged) { this.dateChanged = dateChanged; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
package com.supconit.kqfx.web.fxzf.notify.services; import hc.base.domains.Pageable; import hc.orm.BasicOrmService; import com.supconit.kqfx.web.fxzf.notify.entities.Notify; public interface NotifyService extends BasicOrmService<Notify,String> { /** * 分页查询信息列表 * @param pager * @param condition * @return */ Pageable<Notify> findByPager(Pageable<Notify> pager, Notify condition); }
/* * 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 Interfaces2; /** * * @author Brayan Castellanos */ public class Operar implements Calcular { @Override public void calcularNum(int num1, int num2) { if(num1 > num2){ System.out.println("el numero "+num1+ " es mayor que"+num2); }else{ System.out.println("el numero "+num2+ " es mayor que"+num1); } if(num1 % 2 == 0){ System.out.println("el numero "+num1+" es par "); }else{ System.out.println("el numero "+num1+" es impar "); } if(num2 % 2 == 0){ System.out.println("el numero "+num2+" es par "); }else{ System.out.println("el numero "+num2+" es impar "); } } }
package ui; import game.UIController; import javax.swing.*; class MainMenuView extends JComponent { private final UIController game; MainMenuView(UIController game) { this.game = game; // draw menu options here, hooking their events to // method calls on `game` } }
package com.ece496; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.orm.SugarContext; public class MainActivity extends AppCompatActivity { final Fragment fragment1 = new MonthViewFragment(); final Fragment fragment2 = new DashboardFragment(); final Fragment fragment3 = new NotificationsFragment(); final Fragment fragment4 = new SettingsFragment(); final WeekViewFragment frag_weekview = new WeekViewFragment(); final FragmentManager fm = getSupportFragmentManager(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SugarContext.init(getApplicationContext()); setContentView(R.layout.activity_main); BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); fm.beginTransaction().add(R.id.main_container, fragment4, "4").hide(fragment4).commit(); fm.beginTransaction().add(R.id.main_container, fragment3, "3").hide(fragment3).commit(); fm.beginTransaction().add(R.id.main_container, fragment2, "2").hide(fragment2).commit(); // fm.beginTransaction().add(R.id.main_container, fragment1, "1").commit(); fm.beginTransaction().add(R.id.main_container, frag_weekview, "1").commit(); } private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: fm.beginTransaction().replace(R.id.main_container, frag_weekview).show(frag_weekview).commit(); return true; case R.id.navigation_dashboard: fm.beginTransaction().replace(R.id.main_container, fragment2).show(fragment2).commit(); return true; case R.id.navigation_notifications: fm.beginTransaction().replace(R.id.main_container, fragment3).show(fragment3).commit(); return true; case R.id.navigation_settings: fm.beginTransaction().replace(R.id.main_container, fragment4).show(fragment4).commit(); return true; } return false; } }; }
package com.libedi.demo.util; import java.util.Objects; import java.util.function.Function; /** * FunctionWithException functional interface * * @author Sang-jun, Park * @since 2019. 02. 13 */ @FunctionalInterface public interface FunctionWithException<T, R, E extends Exception> { R apply(T t) throws E; default Function<T, R> wrapper() { return t -> { try { return apply(t); } catch (Exception e) { throw new RuntimeException(e); } }; } static <T, R> Function<T, R> wrapper(final FunctionWithException<T, R, ?> function) { return Objects.requireNonNull(function).wrapper(); } }
package com.github.jerrysearch.tns.server.util; import java.text.SimpleDateFormat; public final class DateUtil { public static final SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd"); public static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); public static final SimpleDateFormat timeFormat = new SimpleDateFormat( "HH:mm:ss"); public static final SimpleDateFormat hourFormat = new SimpleDateFormat( "HH"); }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.common.predicate; import java.util.Objects; import java.util.function.Predicate; import org.apache.commons.lang3.StringUtils; /** * Predicate to test if a given string is parsable into an Integer and that it matches lower and upper boundaries when * set */ public class ValidIntegerPredicate implements Predicate<String> { private Integer min; private Integer max; @Override public boolean test(final String target) { boolean result = false; if (StringUtils.isNotBlank(target)) { try { final int num = Integer.parseInt(target); if (isGreaterOrEqualToMin(num) || isLessOrEqualToMax(num) || areMinAndMaxNull()) { result = true; } } catch (final NumberFormatException e) { result = false; } } return result; } /** * If min is not null, determine if num is greater or equal to min */ protected boolean isGreaterOrEqualToMin(final int num) { return Objects.nonNull(getMin()) && num >= getMin(); } /** * If max is not null, determine if num is less or equal to max */ protected boolean isLessOrEqualToMax(final int num) { return Objects.nonNull(getMax()) && num <= getMax(); } /** * Determine if both min and max are null */ protected boolean areMinAndMaxNull() { return Objects.isNull(getMin()) && Objects.isNull(getMax()); } protected Integer getMin() { return min; } public void setMin(final Integer min) { this.min = min; } protected Integer getMax() { return max; } public void setMax(final Integer max) { this.max = max; } }
package com.tencent.mm.plugin.subapp.ui.friend; import android.content.Intent; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import com.tencent.mm.plugin.account.bind.ui.BindMContactIntroUI; import com.tencent.mm.plugin.account.bind.ui.MobileFriendUI; import com.tencent.mm.plugin.account.friend.a.l; import com.tencent.mm.plugin.account.friend.a.l.a; import com.tencent.mm.ui.MMWizardActivity; class FMessageConversationUI$6 implements OnItemClickListener { final /* synthetic */ FMessageConversationUI ose; FMessageConversationUI$6(FMessageConversationUI fMessageConversationUI) { this.ose = fMessageConversationUI; } public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) { if (i != 0) { return; } if (l.XC() != a.eKt) { Intent intent = new Intent(this.ose.mController.tml, BindMContactIntroUI.class); intent.putExtra("key_upload_scene", 5); MMWizardActivity.D(this.ose.mController.tml, intent); return; } this.ose.startActivity(new Intent(this.ose.mController.tml, MobileFriendUI.class)); } }
package select; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; public class Test { public static void main(String[] args) { } public static Connection getConnection() throws ClassNotFoundException, SQLException, IOException { InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); //读取四个基本信息 String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); //加载驱动 Class.forName(driverClass); //获取连接 Connection conn = DriverManager.getConnection(url, user, password); return conn; } public void closeResource(Connection conn, PreparedStatement ps) throws SQLException { ps.execute(); ps.close(); conn.close(); } }
package ru.rchol.springgo.modelwork; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import ru.rchol.springgo.model.Visitors; import java.util.List; /** * Created by User on 012 12.06.18. */ @Component @Transactional public class VisitorsService { @Autowired private VisitorsDAOImpl visitorsDAO; public void addVisitor(Visitors visitors){ visitorsDAO.addVisitor(visitors); } public List<Visitors> getAllVisitors(){ return visitorsDAO.getAllVisitors(); } }
package com.abc.labEx; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public class BookAuthor { public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("CAP-DB"); EntityManager entityManager = factory.createEntityManager(); Book book1=new Book(); book1.setISBN(100); book1.setPrice(1000); book1.setTitle("Beloved"); Book book2=new Book(); book2.setISBN(101); book2.setPrice(1500); book2.setTitle("Things Fall Apart"); Author author1=new Author(); author1.setId(1); author1.setName("Toni Morrison"); author1.addBook(book1); author1.addBook(book2); EntityTransaction txn = entityManager.getTransaction(); txn.begin(); entityManager.persist(author1); System.out.println("Added author along with book details to database."); txn.commit(); entityManager.close(); factory.close(); } }
package com.eiv; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class JdbcTemplate { private Connection conn; public JdbcTemplate(Connection conn) { this.setConnection(conn); } public void setConnection(Connection conn) { this.conn = conn; } public <T> List<T> query(String sql, RowMapper<T> rowMapper) { List<T> resultados = new ArrayList<>(); try (PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery()) { while (rs.next()) { T t = rowMapper.mapRow(rs, rs.getRow()); resultados.add(t); } } catch (SQLException e) { System.out.println(e.getMessage()); System.out.println(e.getStackTrace()); throw new RuntimeException(e.getMessage(), e); } return resultados; } }
package interfaz; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import logica.Controlador; import otros.DAOException; import presentacion.Carta; import presentacion.Jugador; import presentacion.Partida; public class PanelHipotesis extends JFrame { /** * */ private static final long serialVersionUID = 1L; private String[] arma, habitacion, persona; private JPanel contentPane; private byte posArma, posHabitacion, posPersona = 0; private JLabel panelArma, panelPersona, panelHabitacion; private boolean esSolucion; private Controlador control; // public static void main(String[] args) { // EventQueue.invokeLater(new Runnable() { // public void run() { // try { // PanelHipotesis frame = new PanelHipotesis("COMEDOR"); // frame.setVisible(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } /** * Create the frame. */ public PanelHipotesis(String hab) { try { control= new Controlador(); } catch (DAOException e) { // TODO Auto-generated catch block e.printStackTrace(); } esSolucion=false; arma = new String[] {"ATRAS","CANDELABRO","CUCHILLO","CUERDA","LLAVEINGLESA","PISTOLA","VENENO"}; persona = new String[] {"ATRAS","MRGREEN","MRMUSTARD","PEACOCK","SCARLET","PLUM","WHITE"}; habitacion = new String[] {"ATRAS","COMEDOR","COCINA","SALON","ESTUDIO","BIBLIOTECA","SALONJUEGOS","CONSERVATORIO","AUDITORIO","RECIBIDOR"}; //C�digo por defecto para crear la ventana. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(0, 150, 766, 450); contentPane = new JPanel(); setContentPane(contentPane); // FIN C�digo por defecto contentPane.setBackground(Color.LIGHT_GRAY); //CAMBIAR LUEGO //Definimos el tama�o contentPane.setMaximumSize(new Dimension(766, 450)); contentPane.setMinimumSize(new Dimension(766, 450)); setUndecorated(true); //Ventana sin marco contentPane.setLayout(null); //Layout absoluto //Creacion de los t�tulos //Creamos los labels JLabel labelArma = new JLabel("ARMA"); JLabel labelPersona = new JLabel("PERSONA"); JLabel labelHabitacion = new JLabel("HABITACIÓN"); //Les cambiamos la fuente labelArma.setFont(new Font("TimesRoman", Font.BOLD, 25)); labelPersona.setFont(new Font("TimesRoman", Font.BOLD, 25)); labelHabitacion.setFont(new Font("TimesRoman", Font.BOLD, 25)); //Indicamos en que punto se crean y con que tama�o labelArma.setBounds(90, 50, 166, 50); labelPersona.setBounds(320, 50, 166, 50); labelHabitacion.setBounds(550, 50, 166, 50); //A�adimos los labels al panel principal contentPane.add(labelArma); contentPane.add(labelPersona); contentPane.add(labelHabitacion); // #### -> Creamos los botones para seleccionar arma JButton armaAtras = new JButton(); //Creamos boton para seleccionar arma anterior armaAtras.setText("<"); //Ponemos el texto del boton armaAtras.setBounds(25, 177, 50, 50); //Posicion y tama�o del boton armaAtras.setFocusable(false); //Para que no se quede seleccionado contentPane.add(armaAtras); //A�adimos boton JButton armaAlante = new JButton(); //Creamos boton para seleccionar el arma siguiente armaAlante.setText(">"); //Ponemos texto al boton armaAlante.setBounds(191, 177, 50, 50); //Posicion y tam�o del boton armaAlante.setFocusable(false); //Para que no se quede seleccionado contentPane.add(armaAlante); //A�adimos el boton // #### -> Creamos los botones para seleccionar la persona JButton personaAtras = new JButton(); //Creamos boton para seleccionar arma anterior personaAtras.setText("<"); //Ponemos el texto del boton personaAtras.setBounds(275, 177, 50, 50); //Posicion y tama�o del boton personaAtras.setFocusable(false); //Para que no se quede seleccionado contentPane.add(personaAtras); //A�adimos boton JButton personaAlante = new JButton(); //Creamos boton para seleccionar el arma siguiente personaAlante.setText(">"); //Ponemos texto al boton personaAlante.setBounds(441, 177, 50, 50); //Posicion y tama�o del boton personaAlante.setFocusable(false); //Para que no se quede seleccionado contentPane.add(personaAlante); // #### -> Creamos los botones para seleccionar la habitaci�n JButton habitacionAtras = new JButton(); habitacionAtras.setText("<"); habitacionAtras.setBounds(525, 177, 50, 50); habitacionAtras.setFocusable(false); JButton habitacionAlante = new JButton(); habitacionAlante.setText(">"); habitacionAlante.setBounds(691, 177, 50, 50); habitacionAlante.setFocusable(false); //Comprobamos si tiene que ser una soluci�n o una hipotesis while(!hab.equals(habitacion[posHabitacion])){ posHabitacion++; } if(posHabitacion == 0){ //Estamos ante una Solucion esSolucion=true; contentPane.add(habitacionAtras); contentPane.add(habitacionAlante); } //Creacion de otro espacio para las cartas (PERSONA) panelPersona = new JLabel(); //Creamos el panel para elegir a una Persona panelPersona.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/ATRAS.png")));// Establecer el fondo panelPersona.setBounds(300, 100, 166, 204); //Ponemos la posici�n y el tama�o contentPane.add(panelPersona); //A�adimos el panel al panel principal. //Creacion del ultimo esp�cio (HABITACI�N) panelHabitacion = new JLabel(); //Creamos el panel de la habitaci�n panelHabitacion.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/"+ habitacion[posHabitacion] + ".png"))); //Establecer fondo panelHabitacion.setBounds(550, 100, 166, 204); //Posicion y tama�o contentPane.add(panelHabitacion); //A�adimos al panel principal //Creacion del ultimo esp�cio (ARMA) panelArma = new JLabel(""); panelArma.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/ATRAS.png")));// Establecer el fondo panelArma.setBounds(56, 100, 160, 204); contentPane.add(panelArma); //Creamos el boton Aceptar para confirmar la hipotesis JButton confirmar = new JButton(); confirmar.setText("ACEPTAR"); confirmar.setBounds(280, 350, 200, 50); confirmar.setFocusable(false); contentPane.add(confirmar); // EVENTO DE LOS BOTONES // #### Arma anterior armaAtras.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { cambiarArma(false); } }); // #### Arma siguiente armaAlante.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { cambiarArma(true); } }); // #### Persona anterior personaAtras.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { cambiarPersonaje(false); } }); // #### Persona siguiente personaAlante.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { cambiarPersonaje(true); } }); // #### Habitacion anterior habitacionAtras.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { cambiarHabitacion(false); } }); // #### Habitacion siguiente habitacionAlante.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { cambiarHabitacion(true); } }); // #### Accion del boton Aceptar confirmar.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { boolean correct = true; finalizar(); Carta[] hipoAux = Partida.getRespuesta(); for(int i=0; i<hipoAux.length; i++){ if(hipoAux[i].getNombre().equals("atras")){ correct=false; } } if(correct){ if(esSolucion){ if(comprobarSolucion()){ int idPartida= PanelPartida.getPartida().getIdpartida(); String ganador= PanelPartida.getPartida().getJugadorlocal().getNombre(); control.cambiarEstadoSolucion(idPartida,1,ganador); PanelSolucion ps = new PanelSolucion(PanelPartida.getPartida()); ps.setVisible(true); ps.setAlwaysOnTop(true); control.aumentarPuntuacion(PanelPartida.getPartida().getJugadorlocal().getID()); dispose(); }else{ dispose(); JOptionPane.showMessageDialog(null,"¡Ups, que mala suerte! La solución no es correcta. Has perdido la partida."); PanelPartida.getPanel().abandonar(); } }else{ //PanelJugador.girarDado(); guardarAcusacion(); Jugador.hipotesisHecha(); PanelPartida.habilitar(true); dispose(); //Cierra esta ventana, no la aplicacion entera. //PanelPartida.getPanel().comprobarCarta2(); } }else{ JOptionPane.showMessageDialog(contentPane, "Acusación incompleta, faltan uno o más tipos de cartas por elegir."); } } }); } private boolean comprobarSolucion() { Carta[] solucionPartida= PanelPartida.getPartida().getSolucion(); Carta [] respuesta = PanelPartida.getPartida().getRespuesta(); boolean res=true; for(int i=0;i<3 && res ;i++){ if(!solucionPartida[i].getNombre().equals(respuesta[i].getNombre()))res=false; } return res; } //METODO DE MOVIMIENTO EN LOS ARRAYS private void cambiarArma(boolean movimiento){ if (movimiento){ //Si hay que avanzar a la imagen siguiente if (posArma == 6) //Si esta al final del array posArma = 1; //Vuelve al principio del arrya else //Si no esta al principio posArma++; //Pasa a la siguiente imagen }else{ //Si hay que pasar a la imagen anterior if (posArma < 2) //Si esta al principio del array posArma = 6; //Pasa al final else //Si no esta al principio posArma--; //Pasa a la imagen anterior } //Asignamos la imagen al panel correspondiente panelArma.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/" + arma[posArma] + ".png"))); } private void cambiarPersonaje(boolean movimiento){ if (movimiento){ //Si hay que avanzar a la siguiente imagen if (posPersona == 6) //Si esta al final del array posPersona = 1; //Vuelve al principio else //Si no esta al final posPersona++; //Se selecciona la siguiente persona }else{ //Si no se avanza, se selecciona la imagen anterior if (posPersona < 2) //Si esta al principio del array posPersona = 6; //Se vuelve al final else //Si no esta al principio posPersona--; //Se selecciona la imagen anterior } //Asignamos la imagen al panel correspondiente panelPersona.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/" + persona[posPersona] + ".png"))); } private void cambiarHabitacion(boolean movimiento){ if(movimiento){ //Si hay que avanzar a la siguiente imagen if (posHabitacion == 9) //Comprobamos si esta al fnal del array posHabitacion = 1; //Si lo esta volvemos al principio else //Si no esta al final del array posHabitacion++; //Pasamos a la siguiente imagen }else{ //Si no hay que avanzar retrocedemos a la imagen anterior if (posHabitacion < 2) //Comprobamos si esta al principio del array posHabitacion = 9; //Si esta al principio volvemos al final else //Si no esta al principio posHabitacion--; //Pasamos a la imagen anterior } //Asignamos la imagen al panel correspondiente panelHabitacion.setIcon(new ImageIcon(this.getClass().getResource("/imagenes/" + habitacion[posHabitacion] + ".png"))); } //METODO DE ENVIO AL PRINCIPAL private void finalizar (){ Carta[] res = new Carta[] {new Carta(arma[posArma].substring(0), (ImageIcon)panelArma.getIcon(), "arma"), new Carta(persona[posPersona].substring(0), (ImageIcon)panelPersona.getIcon(),"personaje"), new Carta(habitacion[posHabitacion].substring(0), (ImageIcon)panelHabitacion.getIcon(),"habitacion")}; PanelPartida.getPartida().setRespuesta(res); } private void guardarAcusacion(){ int idPartida=PanelPartida.getPartida().getIdpartida(); Carta[] res = Partida.getRespuesta(); Partida.setRespuesta(res); String[] cartasAcusacion = new String[3]; cartasAcusacion[0] = res[0].getNombre(); System.out.println(cartasAcusacion[0]); cartasAcusacion[1] = res[1].getNombre(); System.out.println(cartasAcusacion[1]); cartasAcusacion[2] = res[2].getNombre(); System.out.println(cartasAcusacion[2]); String nombreJugador = PanelPartida.getPartida().getJugadorlocal().getNombre(); control.guardarAcusacion(cartasAcusacion, idPartida,nombreJugador ); control.acusacionRealizada(idPartida); establecerTurnoAcusacion(); } public void establecerTurnoAcusacion(){ //poner turnoAcusacion = turnoPartida+1 int idPartida=PanelPartida.getPartida().getIdpartida(); int auxTurno = control.getTurnoPartida(idPartida)+1; PanelPartida.getPartida().recalcularJugadores(idPartida); if(auxTurno==PanelPartida.getPartida().getNumjugadores()){ //control.setTurnoAcusacion(idPartida, 0); control.setTurnoAcusacion(idPartida, 0); }else{ control.setTurnoAcusacion(idPartida, auxTurno); } PanelPartida.getPartida().ejecutarTimer(idPartida);//al hacer la acusacion volvemos a ejecutar el timer } }
package com.bytedance.sandboxapp.b.b; import android.text.TextUtils; import com.bytedance.sandboxapp.b.a.b.b; import d.f.b.l; import org.json.JSONException; import org.json.JSONObject; public final class a { public JSONObject a; private final String b; public a() { this.b = "SandboxJsonObject"; this.a = new JSONObject(); } public a(String paramString) { JSONObject jSONObject; this.b = "SandboxJsonObject"; try { if (TextUtils.isEmpty(paramString)) { jSONObject = new JSONObject(); } else { jSONObject = new JSONObject((String)jSONObject); } } catch (JSONException jSONException) { b.b.e(this.b, new Object[] { jSONException }); jSONObject = new JSONObject(); } this.a = jSONObject; } public a(JSONObject paramJSONObject) { this.b = "SandboxJsonObject"; JSONObject jSONObject = paramJSONObject; if (paramJSONObject == null) jSONObject = new JSONObject(); this.a = jSONObject; } public final a a(String paramString, Object paramObject) { l.b(paramString, "key"); try { this.a.put(paramString, paramObject); return this; } catch (JSONException jSONException) { b.b.e(this.b, new Object[] { jSONException }); return this; } } public final String toString() { String str = this.a.toString(); l.a(str, "toJson().toString()"); return str; } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\sandboxapp\b\b\a.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package org.nishkarma.petclinic.model; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.bind.annotation.XmlElement; import org.springframework.beans.support.MutableSortDefinition; import org.springframework.beans.support.PropertyComparator; public class Vets { /** * This field was generated by MyBatis Generator. This field corresponds to * the database column vets.id * * @mbggenerated Thu Aug 01 15:43:11 KST 2013 */ private Integer id; /** * This field was generated by MyBatis Generator. This field corresponds to * the database column vets.first_name * * @mbggenerated Thu Aug 01 15:43:11 KST 2013 */ private String firstName; /** * This field was generated by MyBatis Generator. This field corresponds to * the database column vets.last_name * * @mbggenerated Thu Aug 01 15:43:11 KST 2013 */ private String lastName; /** * This method was generated by MyBatis Generator. This method returns the * value of the database column vets.id * * @return the value of vets.id * * @mbggenerated Thu Aug 01 15:43:11 KST 2013 */ private Set<Specialties> specialties; public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. This method sets the * value of the database column vets.id * * @param id * the value for vets.id * * @mbggenerated Thu Aug 01 15:43:11 KST 2013 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. This method returns the * value of the database column vets.first_name * * @return the value of vets.first_name * * @mbggenerated Thu Aug 01 15:43:11 KST 2013 */ public String getFirstName() { return firstName; } /** * This method was generated by MyBatis Generator. This method sets the * value of the database column vets.first_name * * @param firstName * the value for vets.first_name * * @mbggenerated Thu Aug 01 15:43:11 KST 2013 */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * This method was generated by MyBatis Generator. This method returns the * value of the database column vets.last_name * * @return the value of vets.last_name * * @mbggenerated Thu Aug 01 15:43:11 KST 2013 */ public String getLastName() { return lastName; } /** * This method was generated by MyBatis Generator. This method sets the * value of the database column vets.last_name * * @param lastName * the value for vets.last_name * * @mbggenerated Thu Aug 01 15:43:11 KST 2013 */ public void setLastName(String lastName) { this.lastName = lastName; } protected void setSpecialtiesInternal(Set<Specialties> specialties) { this.specialties = specialties; } protected Set<Specialties> getSpecialtiesInternal() { if (this.specialties == null) { this.specialties = new HashSet<Specialties>(); } return this.specialties; } @XmlElement public List<Specialties> getSpecialties() { List<Specialties> sortedSpecs = new ArrayList<Specialties>( getSpecialtiesInternal()); PropertyComparator.sort(sortedSpecs, new MutableSortDefinition("name", true, true)); return Collections.unmodifiableList(sortedSpecs); } public int getNrOfSpecialties() { return getSpecialtiesInternal().size(); } public void addSpecialty(Specialties specialty) { getSpecialtiesInternal().add(specialty); } }
package com.cyberdust.automation.utils; import com.cyberdust.automation.application.Logging; import io.appium.java_client.AppiumDriver; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.service.local.AppiumDriverLocalService; import io.appium.java_client.service.local.AppiumServiceBuilder; import io.appium.java_client.service.local.flags.GeneralServerFlag; import org.junit.BeforeClass; import org.openqa.selenium.SessionNotCreatedException; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.UnreachableBrowserException; import java.io.File; import java.io.IOException; public class Drivers extends ActionHelper { private static AppiumDriverLocalService service = AppiumDriverLocalService.buildDefaultService(); private static DesiredCapabilities capabilities = new DesiredCapabilities(); private static AppiumDriver <WebElement> driver; private static String appiumServerAddress = "127.0.0.1"; private static String appiumServerPort = "4723"; private static boolean IOSSimulator; private static boolean IOSSetup = false; private static boolean ranSetup = false; @BeforeClass public static void setUp() throws Exception { if (!ranSetup) { initialSetup(); } } public static void initialSetup() throws Exception { IOSSimulator = false; setRanSetup(true); resetCapabilities(); if (!IOSSetup && System.getProperty("os.name").toLowerCase().contains("mac")) { IOSSetup = true; new DeviceReader().checkDevice(); new AppPath().findApp(); } System.out.println("\n------ Starting Appium Server ------"); service = AppiumDriverLocalService.buildService(new AppiumServiceBuilder() .withAppiumJS(new File("/usr/local/lib/node_modules/appium/build/lib/main.js")) .withArgument(GeneralServerFlag.LOG_NO_COLORS) .withArgument(GeneralServerFlag.LOG_LEVEL, "debug") .withArgument(GeneralServerFlag.PRE_LAUNCH) .withIPAddress(appiumServerAddress) .usingPort(Integer.parseInt(appiumServerPort))); service.start(); try { if (DeviceReader.isRunningIOSSimulator()) { IOSSimulator = true; capabilities.setCapability("platformName", "IOS"); capabilities.setCapability("platformVersion", ""); capabilities.setCapability("deviceName", "=iPhone 6 ("); capabilities.setCapability("noReset", true); capabilities.setCapability("nativeInstrumentsLib", true); capabilities.setCapability("bundleId", Constants.IOS_BUNDLE_ID); capabilities.setCapability("app", AppPath.localAppPath); driver = new IOSDriver<>(service.getUrl(), capabilities); } if (DeviceReader.isRunningIOSDevice()) { capabilities.setCapability("platformName", "IOS"); capabilities.setCapability("platformVersion", ""); capabilities.setCapability("deviceName", "iPhone"); capabilities.setCapability("noReset", true); capabilities.setCapability("nativeInstrumentsLib", true); capabilities.setCapability("bundleId", Constants.IOS_BUNDLE_ID); capabilities.setCapability("udid", DeviceReader.getIOSUdid()); driver = new IOSDriver<>(service.getUrl(), capabilities); } if (DeviceReader.isRunningAndroidDevice()) { capabilities.setCapability("platformName", "Android"); capabilities.setCapability("platformVersion", ""); capabilities.setCapability("deviceName", "Android"); capabilities.setCapability("noReset", true); capabilities.setCapability("appPackage", Constants.ANDROID_BUNDLE_ID); capabilities.setCapability("appActivity", Constants.ANDROID_APP_ACTIVITY); driver = new AndroidDriver<>(service.getUrl(), capabilities); } } catch (UnreachableBrowserException e) { System.out.println("Browser unreachable, restarting server..."); setUp(); } catch (SessionNotCreatedException e) { appiumServerPort = String.valueOf(Integer.parseInt(appiumServerPort) + 1); System.out.println("[Appium] Server already running, trying port "+appiumServerPort+"\n"); setUp(); } catch (Exception e) { e.printStackTrace(); } } public static void tearDown() { if (driver != null) { driver.quit(); } if (service != null) { service.stop(); } } private static void resetCapabilities() { capabilities.setCapability("platformName", ""); capabilities.setCapability("platformVersion",""); capabilities.setCapability("deviceName",""); capabilities.setCapability("bundleId",""); capabilities.setCapability("udid",""); capabilities.setCapability("app",""); if (capabilities.getCapability("appPackage") != null) { capabilities.setCapability("appPackage", ""); capabilities.setCapability("appActivity", ""); } } // Prints text to console and to a log file in the project/test logs folder public void log(String text) { try { new Logging(text, getClass()); } catch (IOException e) { e.printStackTrace(); } } public void log(Exception e) { log("[Fail] got exception " + e); } public boolean isAndroid() { return capabilities.getCapability("platformName").equals("Android"); } public boolean isIOS() { return capabilities.getCapability("platformName").equals("IOS"); } public boolean isIOSSimulator() { return IOSSimulator; } public static String getAppiumServerAddress() { return appiumServerAddress; } public static String getAppiumServerPort() { return appiumServerPort; } public static AppiumDriver<WebElement> getDriver() { return driver; } public static void setAppiumServerAddress(String appiumServerAddress) { Drivers.appiumServerAddress = appiumServerAddress; } public static void setAppiumServerPort(String appiumServerPort) { Drivers.appiumServerPort = appiumServerPort; } public static void setRanSetup(boolean ranSetup) { Drivers.ranSetup = ranSetup; } }
package com.sourceallies.filter; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import javax.servlet.http.HttpServletResponse; import org.junit.Test; public class ResponseLoggerFactoryTest { @Test public void testCreate(){ HttpServletResponse response = mock(HttpServletResponse.class); ResponseLoggerFactory factory = new ResponseLoggerFactory(); ResponseLogger responseLogger = factory.create(response); assertNotNull(responseLogger); assertSame(response, responseLogger.getResponse()); } }
package com.bloomberg.server.arithmeticservice.businesslogic; import com.bloomberg.server.arithmeticservice.businesslogic.exceptions.ExpressionBuildException; import com.bloomberg.server.arithmeticservice.businesslogic.interfaces.IExpressionBuilder; import com.bloomberg.server.arithmeticservice.models.Expression; import org.springframework.stereotype.Service; @Service public class ExpressionBuilder implements IExpressionBuilder { @Override public String build(Expression expression) throws ExpressionBuildException { if(expression == null || expression.getNumbers() == null || expression.getOperation() == null) throw new ExpressionBuildException("Null expression"); var quantityOfNumbers = expression.getNumbers().size(); var expressionStr = new StringBuilder(); for (int i = 0; i < quantityOfNumbers; i++) { var number = expression.getNumbers().get(i); expressionStr.append(number); if(i < quantityOfNumbers - 1) expressionStr.append(expression.getOperation()); } return expressionStr.toString(); } }
package com.chuxin.family.widgets; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.chuxin.family.R; /** * * @author shichao.wang 2013.04.08 * */ public class CalendarNiceSelector extends ListView { private static final String TAG = "CalendarNiceSelector"; private String[] mValues = null; private String[] mTexts = null; private boolean mMultiSelection = false; private boolean mMustSelectOne = true; protected List<Integer> mSelectedList = new ArrayList<Integer>(); private onUpdateListener mOnUpdateListener = null; private int calculatePixelForDip(int dip) { Resources r = getResources(); float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, r.getDisplayMetrics()); return (int)px; } public String[] getSelection() { if (mSelectedList.size() == 0) { return null; } String[] results = new String[mSelectedList.size()]; for(int i = 0; i < results.length; i++) { results[i] = mValues[mSelectedList.get(i)]; } return results; } public void setSelection(String[] values) { if ((values == null) || (values.length == 0)) return; mSelectedList.clear(); for(int i = 0; i < values.length; i++) { for(int j = 0; j < mValues.length; j++) { if (values[i].equals(mValues[j])) { clickItem(Integer.valueOf(j), true); } } } } public CalendarNiceSelector(Context context, AttributeSet attrs) { super(context, attrs); setFooterDividersEnabled(false); setBackgroundResource(R.drawable.cx_fa_bg_white_corner_rect_with_grey_border); setDivider(getResources().getDrawable(R.drawable.cx_fa_bg_grey_divider_line)); setDividerHeight(calculatePixelForDip(1)); setSelector(R.color.cx_fa_co_transparent); setCacheColorHint(0x0); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.cx_fa_decl_niceselector_attrs); int textsResId = typedArray.getResourceId(R.styleable.cx_fa_decl_niceselector_attrs_texts, 0); Log.d(TAG, "textsResId = " + textsResId); if (textsResId == 0) { Log.e(TAG, "Error: no valid texts resource set!"); assert(false); } mTexts = getResources().getStringArray(textsResId); int valuesResId = typedArray.getResourceId(R.styleable.cx_fa_decl_niceselector_attrs_values, 0); if (valuesResId == 0) { Log.e(TAG, "Error: no valid values resource set!"); assert(false); } Log.d(TAG, "valuesResId = " + valuesResId); mValues = getResources().getStringArray(valuesResId); mMultiSelection = typedArray.getBoolean(R.styleable.cx_fa_decl_niceselector_attrs_multiSelection, false); mMustSelectOne = typedArray.getBoolean(R.styleable.cx_fa_decl_niceselector_attrs_mustSelectOne, true); typedArray.recycle(); setAdapter(new BaseAdapter() { @Override public int getCount() { return mValues.length; } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup root) { Log.d(TAG, "redraw child view " + position); View view = null; if (convertView != null) { view = convertView; } else { view = LayoutInflater.from(root.getContext()) .inflate(R.layout.cx_fa_widget_nice_selector_row, root, false); } ImageView image = (ImageView)view.findViewById(R.id.cx_fa_widget_niceselector_image); TextView text = (TextView)view.findViewById(R.id.cx_fa_widget_niceselector_text); Integer positionWrapper = Integer.valueOf(position); if (mSelectedList.contains(positionWrapper)) { image.setVisibility(VISIBLE); } else { image.setVisibility(GONE); } text.setText(mTexts[position]); return view; } }); setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int position, long id) { clickItem(Integer.valueOf(position), false); } }); } private void updateChildAt(Integer position) { View view = getChildAt(position); if (view == null) { // this view may have not been seen. return; } ImageView image = (ImageView)view.findViewById(R.id.cx_fa_widget_niceselector_image); if (mSelectedList.contains(position)) { image.setVisibility(VISIBLE); } else { image.setVisibility(GONE); } //this.setVisibility(View.INVISIBLE); } void clickItem(Integer position, boolean isShow) { int deselected = -1; if (mSelectedList.contains(position)) { // this item has already bee selected boolean allowRemove = false; if (mSelectedList.size() > 1) { allowRemove = true; } else if (!mMustSelectOne) { allowRemove = true; } else { // the item cannot be removed, so no change will happen. return; } if (allowRemove) mSelectedList.remove(position); } else { // this item has not been selected yet. if (!mMultiSelection) { // check if allow to do multi-selection if (mSelectedList.size() > 0) { deselected = mSelectedList.get(0); mSelectedList.clear(); } } mSelectedList.add(position); } if (deselected != -1) updateChildAt(Integer.valueOf(deselected)); updateChildAt(position); if(isShow){ this.setVisibility(View.VISIBLE); } else { this.setVisibility(View.GONE); onDismissListener.onDismiss(); } mOnUpdateListener.onUpdateData(); } public interface onUpdateListener{ public void onUpdateData(); } public void setOnUpdateListener(onUpdateListener onUpdateListener){ this.mOnUpdateListener = onUpdateListener; } public interface OnDismissListener{ public void onDismiss(); } private OnDismissListener onDismissListener; public void setOnDismissListener(OnDismissListener listener){ this.onDismissListener=listener; } }
package org.sourceit.entities; import org.sourceit.properties.Gender; public class Person { protected String name; protected int age; protected Gender gender; protected final String properties = "Name,Age,Gender"; public Person() { this.name = "Your name"; this.age = 25; this.gender = Gender.M; } public Person(String name, int age, Gender gender) { this.name = name; this.age = age; this.gender = gender; } public String getProperties() { return properties; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } @Override public String toString() { return "" + this.name + "," + this.age + "," + this.gender; } }
package com.elvarg.world.entity.combat.magic; import java.util.Arrays; import java.util.Optional; import com.elvarg.engine.task.impl.CombatPoisonEffect.PoisonType; import com.elvarg.world.content.PrayerHandler; import com.elvarg.world.entity.combat.CombatFactory; import com.elvarg.world.entity.impl.Character; import com.elvarg.world.entity.impl.player.Player; import com.elvarg.world.model.Animation; import com.elvarg.world.model.EffectTimer; import com.elvarg.world.model.Graphic; import com.elvarg.world.model.GraphicHeight; import com.elvarg.world.model.Item; import com.elvarg.world.model.MagicSpellbook; import com.elvarg.world.model.Projectile; import com.elvarg.world.model.Skill; public enum CombatSpells { WIND_STRIKE(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 91, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(92, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 2; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(90, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 5; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556), new Item(558) }); } @Override public int levelRequired() { return 1; } @Override public int spellId() { return 1152; } }), CONFUSE(new CombatEffectSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(716)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 103, 44, 3, 43, 31, 0)); } @Override public void spellEffect(Character cast, Character castOn) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (player.getSkillManager().getCurrentLevel(Skill.ATTACK) < player.getSkillManager().getMaxLevel(Skill.ATTACK)) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the player has already been weakened."); } return; } int decrease = (int) (0.05 * (player.getSkillManager().getCurrentLevel(Skill.ATTACK))); player.getSkillManager().setCurrentLevel(Skill.ATTACK, player.getSkillManager().getCurrentLevel(Skill.ATTACK) - decrease); player.getSkillManager().updateSkill(Skill.ATTACK); player.getPacketSender().sendMessage( "You feel slightly weakened."); } /*else if (castOn.isNpc()) { NPC npc = (NPC) castOn; if (npc.getDefenceWeakened()[0] || npc.getStrengthWeakened()[0]) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the NPC has already been weakened."); } return; } npc.getDefenceWeakened()[0] = true; }*/ } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(104, GraphicHeight.HIGH)); } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(102, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 13; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 3), new Item(557, 2), new Item(559) }); } @Override public int levelRequired() { return 3; } @Override public int spellId() { return 1153; } }), WATER_STRIKE(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 94, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(95, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 4; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(93, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 7; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555), new Item(556), new Item(558) }); } @Override public int levelRequired() { return 5; } @Override public int spellId() { return 1154; } }), EARTH_STRIKE(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 97, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(98, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 6; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(96, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 9; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 1), new Item(558, 1), new Item(557, 2) }); } @Override public int levelRequired() { return 9; } @Override public int spellId() { return 1156; } }), WEAKEN(new CombatEffectSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(716)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 106, 44, 3, 43, 31, 0)); } @Override public void spellEffect(Character cast, Character castOn) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (player.getSkillManager().getCurrentLevel(Skill.STRENGTH) < player.getSkillManager().getMaxLevel(Skill.STRENGTH)) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the player has already been weakened."); } return; } int decrease = (int) (0.05 * (player.getSkillManager().getCurrentLevel(Skill.STRENGTH))); player.getSkillManager().setCurrentLevel(Skill.STRENGTH, player.getSkillManager().getCurrentLevel(Skill.STRENGTH) - decrease); player.getSkillManager().updateSkill(Skill.STRENGTH); player.getPacketSender().sendMessage( "You feel slightly weakened."); } /*else if (castOn.isNpc()) { NPC npc = (NPC) castOn; if (npc.getDefenceWeakened()[1] || npc.getStrengthWeakened()[1]) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the NPC has already been weakened."); } return; } npc.getDefenceWeakened()[1] = true; }*/ } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(107, GraphicHeight.HIGH)); } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(105, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 21; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 3), new Item(557, 2), new Item(559, 1) }); } @Override public int levelRequired() { return 11; } @Override public int spellId() { return 1157; } @Override public MagicSpellbook getSpellbook() { return null; } }), FIRE_STRIKE(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 100, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(101, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 8; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(99, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 11; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 1), new Item(558, 1), new Item(554, 3) }); } @Override public int levelRequired() { return 13; } @Override public int spellId() { return 1158; } }), WIND_BOLT(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 118, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(119, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 9; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(117, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 13; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 2), new Item(562, 1) }); } @Override public int levelRequired() { return 17; } @Override public int spellId() { return 1160; } }), CURSE(new CombatEffectSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(710)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 109, 44, 3, 43, 31, 0)); } @Override public void spellEffect(Character cast, Character castOn) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (player.getSkillManager().getCurrentLevel(Skill.DEFENCE) < player.getSkillManager().getMaxLevel(Skill.DEFENCE)) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the player has already been weakened."); } return; } int decrease = (int) (0.05 * (player.getSkillManager().getCurrentLevel(Skill.DEFENCE))); player.getSkillManager().setCurrentLevel(Skill.DEFENCE, player.getSkillManager().getCurrentLevel(Skill.DEFENCE) - decrease); player.getSkillManager().updateSkill(Skill.DEFENCE); player.getPacketSender().sendMessage( "You feel slightly weakened."); }/* else if (castOn.isNpc()) { NPC npc = (NPC) castOn; if (npc.getDefenceWeakened()[2] || npc.getStrengthWeakened()[2]) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the NPC has already been weakened."); } return; } npc.getDefenceWeakened()[2] = true; }*/ } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(110, GraphicHeight.HIGH)); } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(108, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 29; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 2), new Item(557, 3), new Item(559, 1) }); } @Override public int levelRequired() { return 19; } @Override public int spellId() { return 1161; } }), BIND(new CombatEffectSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(710)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 178, 44, 3, 43, 31, 0)); } @Override public void spellEffect(Character cast, Character castOn) { if (!castOn.getCombat().getFreezeTimer().finished()) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because they are already frozen."); } return; } CombatFactory.freeze(castOn, 5); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(181, GraphicHeight.HIGH)); } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(177, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 30; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 3), new Item(557, 3), new Item(561, 2) }); } @Override public int levelRequired() { return 20; } @Override public int spellId() { return 1572; } }), WATER_BOLT(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 121, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(122, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 10; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(120, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 16; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 2), new Item(562, 1), new Item(555, 2) }); } @Override public int levelRequired() { return 23; } @Override public int spellId() { return 1163; } }), EARTH_BOLT(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 124, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(125, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 11; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(123, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 19; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 2), new Item(562, 1), new Item(557, 3) }); } @Override public int levelRequired() { return 29; } @Override public int spellId() { return 1166; } }), FIRE_BOLT(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 127, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(128, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 12; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(126, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 22; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 3), new Item(562, 1), new Item(554, 4) }); } @Override public int levelRequired() { return 35; } @Override public int spellId() { return 1169; } }), CRUMBLE_UNDEAD(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(724)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 146, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(147)); } @Override public int maximumHit() { return 15; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(145, 6553600)); } @Override public int baseExperience() { return 24; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 2), new Item(562, 1), new Item(557, 2) }); } @Override public int levelRequired() { return 39; } @Override public int spellId() { return 1171; } }), WIND_BLAST(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 133, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(134, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 13; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(132, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 25; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 3), new Item(560, 1) }); } @Override public int levelRequired() { return 41; } @Override public int spellId() { return 1172; } }), WATER_BLAST(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 136, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(137, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 14; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(135, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 28; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 3), new Item(556, 3), new Item(560, 1) }); } @Override public int levelRequired() { return 47; } @Override public int spellId() { return 1175; } }), IBAN_BLAST(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(708)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 88, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(89)); } @Override public int maximumHit() { return 25; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(87, 6553600)); } @Override public int baseExperience() { return 30; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.of(new Item[] { new Item(1409) }); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(560, 1), new Item(554, 5) }); } @Override public int levelRequired() { return 50; } @Override public int spellId() { return 1539; } }), SNARE(new CombatEffectSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(710)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 178, 44, 3, 43, 31, 0)); } @Override public void spellEffect(Character cast, Character castOn) { if (!castOn.getCombat().getFreezeTimer().finished()) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because they are already frozen."); } return; } CombatFactory.freeze(castOn, 10); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(180, GraphicHeight.HIGH)); } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(177, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 60; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 3), new Item(557, 4), new Item(561, 3) }); } @Override public int levelRequired() { return 50; } @Override public int spellId() { return 1582; } }), MAGIC_DART(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1576)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 328, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(329)); } @Override public int maximumHit() { return 19; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(327, 6553600)); } @Override public int baseExperience() { return 30; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.of(new Item[] { new Item(4170) }); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(558, 4), new Item(560, 1) }); } @Override public int levelRequired() { return 50; } @Override public int spellId() { return 12037; } }), EARTH_BLAST(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 139, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(140, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 15; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(138, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 31; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 3), new Item(560, 1), new Item(557, 4) }); } @Override public int levelRequired() { return 53; } @Override public int spellId() { return 1177; } }), FIRE_BLAST(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 130, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(131, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 16; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(129, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 34; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 4), new Item(560, 1), new Item(554, 5) }); } @Override public int levelRequired() { return 59; } @Override public int spellId() { return 1181; } }), SARADOMIN_STRIKE(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(811)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(76)); } @Override public int maximumHit() { return 20; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 35; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.of(new Item[] { new Item(2415) }); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 4), new Item(565, 2), new Item(554, 2) }); } @Override public int levelRequired() { return 60; } @Override public int spellId() { return 1190; } }), CLAWS_OF_GUTHIX(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(811)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(77)); } @Override public int maximumHit() { return 20; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 35; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.of(new Item[] { new Item(2416) }); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 4), new Item(565, 2), new Item(554, 2) }); } @Override public int levelRequired() { return 60; } @Override public int spellId() { return 1191; } }), FLAMES_OF_ZAMORAK(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(811)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(78)); } @Override public int maximumHit() { return 20; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 35; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.of(new Item[] { new Item(2417) }); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 4), new Item(565, 2), new Item(554, 2) }); } @Override public int levelRequired() { return 60; } @Override public int spellId() { return 1192; } }), WIND_WAVE(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 159, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(160, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 17; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(158, GraphicHeight.MIDDLE)); } @Override public int baseExperience() { return 36; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 5), new Item(565, 1) }); } @Override public int levelRequired() { return 62; } @Override public int spellId() { return 1183; } }), WATER_WAVE(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 162, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(163, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 18; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(161, GraphicHeight.MIDDLE)); } @Override public int baseExperience() { return 37; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 5), new Item(565, 1), new Item(555, 7) }); } @Override public int levelRequired() { return 65; } @Override public int spellId() { return 1185; } }), VULNERABILITY(new CombatEffectSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(729)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 168, 44, 3, 43, 31, 0)); } @Override public void spellEffect(Character cast, Character castOn) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (player.getSkillManager().getCurrentLevel(Skill.DEFENCE) < player.getSkillManager().getMaxLevel(Skill.DEFENCE)) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the player is already weakened."); } return; } int decrease = (int) (0.10 * (player.getSkillManager().getCurrentLevel(Skill.DEFENCE))); player.getSkillManager().setCurrentLevel(Skill.DEFENCE, player.getSkillManager().getCurrentLevel(Skill.DEFENCE) - decrease); player.getSkillManager().updateSkill(Skill.DEFENCE); player.getPacketSender().sendMessage( "You feel slightly weakened."); }/* else if (castOn.isNpc()) { NPC npc = (NPC) castOn; if (npc.getDefenceWeakened()[2] || npc.getStrengthWeakened()[2]) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the NPC is already weakened."); } return; } npc.getStrengthWeakened()[2] = true; }*/ } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(169)); } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(167, 6553600)); } @Override public int baseExperience() { return 76; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(557, 5), new Item(555, 5), new Item(566, 1) }); } @Override public int levelRequired() { return 66; } @Override public int spellId() { return 1542; } }), EARTH_WAVE(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 165, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(166, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 19; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(164, GraphicHeight.MIDDLE)); } @Override public int baseExperience() { return 40; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 5), new Item(565, 1), new Item(557, 7) }); } @Override public int levelRequired() { return 70; } @Override public int spellId() { return 1188; } }), ENFEEBLE(new CombatEffectSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(729)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 171, 44, 3, 43, 31, 0)); } @Override public void spellEffect(Character cast, Character castOn) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (player.getSkillManager().getCurrentLevel(Skill.STRENGTH) < player.getSkillManager().getMaxLevel(Skill.STRENGTH)) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the player is already weakened."); } return; } int decrease = (int) (0.10 * (player.getSkillManager().getCurrentLevel(Skill.STRENGTH))); player.getSkillManager().setCurrentLevel(Skill.STRENGTH, player.getSkillManager().getCurrentLevel(Skill.STRENGTH) - decrease); player.getSkillManager().updateSkill(Skill.STRENGTH); player.getPacketSender().sendMessage( "You feel slightly weakened."); } /*else if (castOn.isNpc()) { NPC npc = (NPC) castOn; if (npc.getDefenceWeakened()[1] || npc.getStrengthWeakened()[1]) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the NPC is already weakened."); } return; } npc.getStrengthWeakened()[1] = true; }*/ } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(172)); } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(170, 6553600)); } @Override public int baseExperience() { return 83; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(557, 8), new Item(555, 8), new Item(566, 1) }); } @Override public int levelRequired() { return 73; } @Override public int spellId() { return 1543; } }), FIRE_WAVE(new CombatNormalSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(711)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 156, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(157, GraphicHeight.HIGH)); } @Override public int maximumHit() { return 20; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(155, GraphicHeight.MIDDLE)); } @Override public int baseExperience() { return 42; } @Override public Optional<Item[]> equipmentRequired(Player player) { return Optional.empty(); } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 5), new Item(565, 1), new Item(554, 7) }); } @Override public int levelRequired() { return 75; } @Override public int spellId() { return 1189; } }), ENTANGLE(new CombatEffectSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(710)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 178, 44, 3, 43, 31, 0)); } @Override public void spellEffect(Character cast, Character castOn) { if (!castOn.getCombat().getFreezeTimer().finished()) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because they are already frozen."); } return; } CombatFactory.freeze(castOn, 15); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(179, GraphicHeight.HIGH)); } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(177, GraphicHeight.HIGH)); } @Override public int baseExperience() { return 91; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 5), new Item(557, 5), new Item(561, 4) }); } @Override public int levelRequired() { return 79; } @Override public int spellId() { return 1592; } }), STUN(new CombatEffectSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(729)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 174, 44, 3, 43, 31, 0)); } @Override public void spellEffect(Character cast, Character castOn) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (player.getSkillManager().getCurrentLevel(Skill.ATTACK) < player.getSkillManager().getMaxLevel(Skill.ATTACK)) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the player is already weakened."); } return; } int decrease = (int) (0.10 * (player.getSkillManager().getCurrentLevel(Skill.ATTACK))); player.getSkillManager().setCurrentLevel(Skill.ATTACK, player.getSkillManager().getCurrentLevel(Skill.ATTACK) - decrease); player.getSkillManager().updateSkill(Skill.ATTACK); player.getPacketSender().sendMessage( "You feel slightly weakened."); }/* else if (castOn.isNpc()) { NPC npc = (NPC) castOn; if (npc.getDefenceWeakened()[0] || npc.getStrengthWeakened()[0]) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the NPC is already weakened."); } return; } npc.getStrengthWeakened()[0] = true; }*/ } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(107)); } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(173, 6553600)); } @Override public int baseExperience() { return 90; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(557, 12), new Item(555, 12), new Item(556, 1) }); } @Override public int levelRequired() { return 80; } @Override public int spellId() { return 1562; } }), TELEBLOCK(new CombatEffectSpell() { @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1819)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 344, 44, 3, 43, 31, 0)); } @Override public void spellEffect(Character cast, Character castOn) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (!player.getCombat().getTeleBlockTimer().finished()) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "The spell has no effect because the player is already teleblocked."); } return; } final int seconds = player.getPrayerActive()[PrayerHandler.PROTECT_FROM_MAGIC] ? 300 : 600; player.getCombat().getTeleBlockTimer().start(seconds); player.getPacketSender().sendEffectTimer(seconds, EffectTimer.TELE_BLOCK) .sendMessage("You have just been teleblocked!"); } else if (castOn.isNpc()) { if (cast.isPlayer()) { ((Player) cast).getPacketSender().sendMessage( "Your spell has no effect on this target."); } } } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(345)); } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 65; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(563, 1), new Item(562, 1), new Item(560, 1) }); } @Override public int levelRequired() { return 85; } @Override public int spellId() { return 12445; } }), SMOKE_RUSH(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { CombatFactory.poisonEntity(castOn, PoisonType.MILD); } @Override public int spellRadius() { return 0; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1978)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 384, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(385)); } @Override public int maximumHit() { return 13; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 30; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 1), new Item(554, 1), new Item(562, 2), new Item(560, 2) }); } @Override public int levelRequired() { return 50; } @Override public int spellId() { return 12939; } }), SHADOW_RUSH(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (player.getSkillManager().getCurrentLevel(Skill.ATTACK) < player.getSkillManager().getMaxLevel(Skill.ATTACK)) { return; } int decrease = (int) (0.1 * (player.getSkillManager().getCurrentLevel(Skill.ATTACK))); player.getSkillManager().setCurrentLevel(Skill.ATTACK, player.getSkillManager().getCurrentLevel(Skill.ATTACK) - decrease); player.getSkillManager().updateSkill(Skill.ATTACK); } } @Override public int spellRadius() { return 0; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1978)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 378, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(379)); } @Override public int maximumHit() { return 14; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 31; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 1), new Item(566, 1), new Item(562, 2), new Item(560, 2) }); } @Override public int levelRequired() { return 52; } @Override public int spellId() { return 12987; } }), BLOOD_RUSH(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { cast.heal((int) (damage * 0.10)); } @Override public int spellRadius() { return 0; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1978)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 372, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(373)); } @Override public int maximumHit() { return 15; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 33; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(565, 1), new Item(562, 2), new Item(560, 2) }); } @Override public int levelRequired() { return 56; } @Override public int spellId() { return 12901; } }), ICE_RUSH(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { CombatFactory.freeze(castOn, 5); } @Override public int spellRadius() { return 0; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1978)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 360, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(361)); } @Override public int maximumHit() { return 18; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 34; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 2), new Item(562, 2), new Item(560, 2) }); } @Override public int levelRequired() { return 58; } @Override public int spellId() { return 12861; } }), SMOKE_BURST(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { CombatFactory.poisonEntity(castOn, PoisonType.MILD); } @Override public int spellRadius() { return 1; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1979)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(389)); } @Override public int maximumHit() { return 13; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 36; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 2), new Item(554, 2), new Item(562, 4), new Item(560, 2) }); } @Override public int levelRequired() { return 62; } @Override public int spellId() { return 12963; } }), SHADOW_BURST(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (player.getSkillManager().getCurrentLevel(Skill.ATTACK) < player.getSkillManager().getMaxLevel(Skill.ATTACK)) { return; } int decrease = (int) (0.1 * (player.getSkillManager().getCurrentLevel(Skill.ATTACK))); player.getSkillManager().setCurrentLevel(Skill.ATTACK, player.getSkillManager().getCurrentLevel(Skill.ATTACK) - decrease); player.getSkillManager().updateSkill(Skill.ATTACK); } } @Override public int spellRadius() { return 1; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1979)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(382)); } @Override public int maximumHit() { return 18; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 37; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 1), new Item(566, 2), new Item(562, 4), new Item(560, 2) }); } @Override public int levelRequired() { return 64; } @Override public int spellId() { return 13011; } }), BLOOD_BURST(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { cast.heal((int) (damage * 0.15)); } @Override public int spellRadius() { return 1; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1979)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(376)); } @Override public int maximumHit() { return 21; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 39; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(565, 2), new Item(562, 4), new Item(560, 2) }); } @Override public int levelRequired() { return 68; } @Override public int spellId() { return 12919; } }), ICE_BURST(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { CombatFactory.freeze(castOn, 10); } @Override public int spellRadius() { return 1; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1979)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(363)); } @Override public int maximumHit() { return 22; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 40; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 4), new Item(562, 4), new Item(560, 2) }); } @Override public int levelRequired() { return 70; } @Override public int spellId() { return 12881; } }), SMOKE_BLITZ(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { CombatFactory.poisonEntity(castOn, PoisonType.EXTRA); } @Override public int spellRadius() { return 0; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1978)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 386, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(387)); } @Override public int maximumHit() { return 23; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 42; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 2), new Item(554, 2), new Item(565, 2), new Item(560, 2) }); } @Override public int levelRequired() { return 74; } @Override public int spellId() { return 12951; } }), SHADOW_BLITZ(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (player.getSkillManager().getCurrentLevel(Skill.ATTACK) < player.getSkillManager().getMaxLevel(Skill.ATTACK)) { return; } int decrease = (int) (0.15 * (player.getSkillManager().getCurrentLevel(Skill.ATTACK))); player.getSkillManager().setCurrentLevel(Skill.ATTACK, player.getSkillManager().getCurrentLevel(Skill.ATTACK) - decrease); player.getSkillManager().updateSkill(Skill.ATTACK); } } @Override public int spellRadius() { return 0; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1978)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 380, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(381)); } @Override public int maximumHit() { return 24; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 43; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 2), new Item(566, 2), new Item(565, 2), new Item(560, 2) }); } @Override public int levelRequired() { return 76; } @Override public int spellId() { return 12999; } }), BLOOD_BLITZ(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { cast.heal((int) (damage * 0.20)); } @Override public int spellRadius() { return 0; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1978)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.of(new Projectile(cast, castOn, 374, 44, 3, 43, 31, 0)); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(375)); } @Override public int maximumHit() { return 25; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 45; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(565, 4), new Item(560, 2) }); } @Override public int levelRequired() { return 80; } @Override public int spellId() { return 12911; } }), ICE_BLITZ(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { CombatFactory.freeze(castOn, 15); } @Override public int spellRadius() { return 0; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1978)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(367)); } @Override public int maximumHit() { return 26; } @Override public Optional<Graphic> startGraphic() { return Optional.of(new Graphic(366, 6553600)); } @Override public int baseExperience() { return 46; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 3), new Item(565, 2), new Item(560, 2) }); } @Override public int levelRequired() { return 82; } @Override public int spellId() { return 12871; } }), SMOKE_BARRAGE(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { CombatFactory.poisonEntity(castOn, PoisonType.SUPER); } @Override public int spellRadius() { return 1; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1979)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(391)); } @Override public int maximumHit() { return 27; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 48; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 4), new Item(554, 4), new Item(565, 2), new Item(560, 4) }); } @Override public int levelRequired() { return 86; } @Override public int spellId() { return 12975; } }), SHADOW_BARRAGE(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { if (castOn.isPlayer()) { Player player = (Player) castOn; if (player.getSkillManager().getCurrentLevel(Skill.ATTACK) < player.getSkillManager().getMaxLevel(Skill.ATTACK)) { return; } int decrease = (int) (0.15 * (player.getSkillManager().getCurrentLevel(Skill.ATTACK))); player.getSkillManager().setCurrentLevel(Skill.ATTACK, player.getSkillManager().getCurrentLevel(Skill.ATTACK) - decrease); player.getSkillManager().updateSkill(Skill.ATTACK); } } @Override public int spellRadius() { return 1; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1979)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(383)); } @Override public int maximumHit() { return 28; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 49; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(556, 4), new Item(566, 3), new Item(565, 2), new Item(560, 4) }); } @Override public int levelRequired() { return 88; } @Override public int spellId() { return 13023; } }), BLOOD_BARRAGE(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { cast.heal((int) (damage * 0.20)); } @Override public int spellRadius() { return 1; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1979)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(377)); } @Override public int maximumHit() { return 29; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 51; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(560, 4), new Item(566, 1), new Item(565, 4) }); } @Override public int levelRequired() { return 92; } @Override public int spellId() { return 12929; } }), ICE_BARRAGE(new CombatAncientSpell() { @Override public void spellEffect(Character cast, Character castOn, int damage) { CombatFactory.freeze(castOn, 20); } @Override public int spellRadius() { return 1; } @Override public Optional<Animation> castAnimation() { return Optional.of(new Animation(1979)); } @Override public Optional<Projectile> castProjectile(Character cast, Character castOn) { return Optional.empty(); } @Override public Optional<Graphic> endGraphic() { return Optional.of(new Graphic(369)); } @Override public int maximumHit() { return 30; } @Override public Optional<Graphic> startGraphic() { return Optional.empty(); } @Override public int baseExperience() { return 52; } @Override public Optional<Item[]> itemsRequired(Player player) { return Optional.of(new Item[] { new Item(555, 6), new Item(565, 2), new Item(560, 4) }); } @Override public int levelRequired() { return 94; } @Override public int spellId() { return 12891; } }); /** * The spell attached to this element. */ private final CombatSpell spell; /** * Creates a new {@link CombatSpells}. * * @param spell * the spell attached to this element. */ private CombatSpells(CombatSpell spell) { this.spell = spell; } /** * Gets the spell attached to this element. * * @return the spell. */ public final CombatSpell getSpell() { return spell; } /** * Gets the spell with a {@link CombatSpell#spellId()} of {@code id}. * * @param id * the identification of the combat spell. * @return the combat spell with that identification. */ public static Optional<CombatSpells> getCombatSpells(int id) { return Arrays.stream(CombatSpells.values()).filter(s -> s != null && s.getSpell().spellId() == id).findFirst(); } public static CombatSpell getCombatSpell(int spellId) { Optional<CombatSpells> spell = getCombatSpells(spellId); if(spell.isPresent()) { return spell.get().getSpell(); } return null; } }
package com.todo.persistence.model; import java.util.UUID; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import lombok.Data; @Data @Entity public class Task { @Id @GeneratedValue private UUID id; private String description; private Status status; }
package com.example.meetgo; /** * Constant values reused in this sample. */ final class Constants { static final int SUCCESS_RESULT = 0; static final int FAILURE_RESULT = 1; private static final String PACKAGE_NAME = "com.example.mapwithmarker"; static final String RECEIVER = PACKAGE_NAME + ".RECEIVER"; static final String RESULT_ADDRESS = PACKAGE_NAME + ".RESULT_ADDRESS"; static final String RESULT_ZIPCODE = PACKAGE_NAME + ".RESULT_ZIPCODE"; static final String LOCATION_DATA_EXTRA = PACKAGE_NAME + ".LOCATION_DATA_EXTRA"; public static final int LOCATION_INTERVAL = 10000; public static final int FASTEST_LOCATION_INTERVAL = 5000; }
package top.kylewang.bos; import org.junit.Test; /** * @author Kyle.Wang * 2018/1/16 0016 13:50 */ public class TestDemo { @Test public void test() { System.out.println(inverseString("abcde")); } public String inverseString(String source) { StringBuilder stringBuilder = new StringBuilder(); char[] chars = source.toCharArray(); for (int i = chars.length - 1; i >= 0; i--) { stringBuilder.append(chars[i]); } return stringBuilder.toString(); } } class SingleClass { private SingleClass(){ } private static final SingleClass singleClass= new SingleClass(); public static SingleClass getSingleClass() { return singleClass; } }
package jdichiera.platformer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; public class PlatformView extends SurfaceView implements Runnable{ private boolean debugging = true; private volatile boolean running; private Thread gameThread = null; // Objects for drawing private Paint paint; // Canvas could initially be local // Later we will use it outside of draw(); private Canvas canvas; private SurfaceHolder ourHolder; Context context; long startFrameTime; long timeThisFrame; long fps; // New engine classes private LevelManager lm; private Viewport vp; InputController ic; SoundManager sm; private PlayerState ps; PlatformView(Context context, int screenWidth, int screenHeight){ super(context); this.context = context; // Initialize drawing objects ourHolder = getHolder(); paint = new Paint(); // Initialize the viewport vp = new Viewport(screenWidth, screenHeight); // Initialize the sound manager sm = new SoundManager(); sm.loadSound(context); ps = new PlayerState(); // Load the first level loadLevel("LevelCave", 15, 2); } public void loadLevel(String level, float px, float py){ lm = null; // Create a new LevelManager // Pass in a Context, screen details, level name // and player location lm = new LevelManager(context, vp.getPixelsPerMeterX(), vp.getScreenWidth(), ic, level, px, py); ic = new InputController(vp.getScreenWidth(), vp.getScreenHeight()); PointF location = new PointF(px, py); ps.saveLocation(location); // Set the player location as the world center vp.setWorldCenter(lm.gameObjects.get(lm.playerIndex) .getWorldLocation().x, lm.gameObjects.get(lm.playerIndex) .getWorldLocation().y); } @Override public void run(){ while(running){ startFrameTime = System.currentTimeMillis(); update(); draw(); // Calculate the FPS this frame // We will use this result to time animations and movement timeThisFrame = System.currentTimeMillis() - startFrameTime; if(timeThisFrame >= 1){ fps = 1000 / timeThisFrame; } } } private void update() { // Loop through GameObjects to see if any need to be clipped for(GameObject go : lm.gameObjects){ if(go.isActive()){ // If the gameObject is on the current screen and not being clipped // set the visible flag to true. If it is not on the screen set the // visible flag to false so we do not draw them if(!vp.clipObjects(go.getWorldLocation().x, go.getWorldLocation().y, go.getWidth(), go.getHeight())){ go.setVisible(true); // Check collisions with player int hit = lm.player.checkCollisions(go.getHitbox()); if(hit > 0){ switch(go.getType()){ case 'c': sm.playSound("coin_pickup"); go.setActive(false); go.setVisible(false); ps.gotCredit(); // Now restore state that was // removed by collision detection if (hit != 2) {// Any hit except feet lm.player.restorePreviousVelocity(); } break; case 'u': sm.playSound("gun_upgrade"); go.setActive(false); go.setVisible(false); lm.player.gun.upgradeRateOfFire(); ps.increaseFireRate(); if (hit != 2) {// Any hit except feet lm.player.restorePreviousVelocity(); } break; case 'e': //extralife go.setActive(false); go.setVisible(false); sm.playSound("extra_life"); ps.addLife(); if (hit != 2) { lm.player.restorePreviousVelocity(); } break; default: if(hit == 1){ lm.player.setxVelocity(0); lm.player.setPressingRight(false); } if(hit == 2){ lm.player.isFalling = false; } break; } } if (lm.isPlaying()) { // Run any un-clipped updates go.update(fps, lm.gravity); } } else { go.setVisible(false); } } } if(lm.isPlaying()){ // reset the player location as the center of the viewport vp.setWorldCenter(lm.gameObjects.get(lm.playerIndex).getWorldLocation().x, lm.gameObjects.get(lm.playerIndex).getWorldLocation().y); } } private void draw(){ if(ourHolder.getSurface().isValid()){ // Lock the area of memory that we are drawing to canvas = ourHolder.lockCanvas(); // Clear the last frame with a blank color paint.setColor(Color.argb(255, 0, 0, 255)); canvas.drawColor(Color.argb(255, 0, 0, 255)); // Draw all GameObjects Rect toScreen2d = new Rect(); // Draw a layer at a time for (int layer = -1; layer <= 1; layer++){ for(GameObject go : lm.gameObjects){ // Only draw if the gameObject is visible and belongs to this layer if(go.isVisible() && go.getWorldLocation().z == layer){ toScreen2d.set(vp.worldToScreen(go.getWorldLocation().x, go.getWorldLocation().y, go.getWidth(), go.getHeight())); // If the bitmap is animated if(go.isAnimated()){ // Get the next frame of the bitmap and rotate if necessary if(go.getFacing() == 1){ // Rotate Matrix flipper = new Matrix(); flipper.preScale(-1, 1); Rect r = go.getRectToDraw(System.currentTimeMillis()); Bitmap b = Bitmap.createBitmap( lm.bitmapsArray[lm.getBitmapIndex(go.getType())], r.left, r.top, r.width(), r.height(), flipper, true); canvas.drawBitmap(b, toScreen2d.left, toScreen2d.top, paint); } else{ canvas.drawBitmap( lm.bitmapsArray[lm.getBitmapIndex(go.getType())], go.getRectToDraw(System.currentTimeMillis()), toScreen2d, paint); } } else { canvas.drawBitmap(lm.bitmapsArray[lm.getBitmapIndex(go.getType())], toScreen2d.left, toScreen2d.top, paint); } } } } //draw the bullets paint.setColor(Color.argb(255, 255, 255, 255)); for (int i = 0; i < lm.player.gun.getNumBullets(); i++) { // Pass in the x and y coords as usual // then .25 and .05 for the bullet width and height toScreen2d.set(vp.worldToScreen (lm.player.gun.getBulletX(i), lm.player.gun.getBulletY(i), .25f, .05f)); canvas.drawRect(toScreen2d, paint); } // Debug text if (debugging) { paint.setTextSize(16); paint.setTextAlign(Paint.Align.LEFT); paint.setColor(Color.argb(255, 255, 255, 255)); canvas.drawText("fps:" + fps, 10, 60, paint); canvas.drawText("num objects: " + lm.gameObjects.size(), 10, 80, paint); canvas.drawText("num clipped: " + vp.getNumClipped(), 10, 100, paint); canvas.drawText("playerX: "+lm.gameObjects.get(lm.playerIndex).getWorldLocation().x, 10, 120, paint); canvas.drawText("playerY: "+lm.gameObjects.get(lm.playerIndex).getWorldLocation().y, 10, 140, paint); canvas.drawText("Gravity: " + lm.gravity, 10, 160, paint); canvas.drawText("X velocity: " + lm.gameObjects.get(lm.playerIndex).getxVelocity(), 10, 180, paint); canvas.drawText("Y velocity: " + lm.gameObjects.get(lm.playerIndex).getyVelocity(), 10, 200, paint); canvas.drawText("isJumping: " + lm.player.isJumping, 10, 220, paint); canvas.drawText("isFalling: " + lm.player.isFalling, 10, 240, paint); // Reset the number of clipped objects each frame vp.resetNumClipped(); } // Draw the buttons paint.setColor(Color.argb(80, 255, 255, 255)); ArrayList<Rect> buttonsToDraw; buttonsToDraw = ic.getButtons(); for(Rect rect : buttonsToDraw){ RectF rf = new RectF(rect.left, rect.top, rect.right, rect.bottom); canvas.drawRoundRect(rf, 15f, 15f, paint); } // Draw paused message if game is paused if (!this.lm.isPlaying()) { paint.setTextAlign(Paint.Align.CENTER); paint.setColor(Color.argb(255, 255, 255, 255)); paint.setTextSize(120); canvas.drawText("Paused", vp.getScreenWidth() / 2, vp.getScreenHeight() / 2, paint); } // Unlock the frame and draw the scene ourHolder.unlockCanvasAndPost(canvas); } } // Clean up thread if the game is interrupted public void pause(){ running = false; try { gameThread.join(); } catch (InterruptedException e){ Log.e("Error", "Failed to pause thread"); } } // Make a new thread and start it // Execution moves to our run method public void resume(){ running = true; gameThread = new Thread(this); gameThread.start(); } @Override public boolean onTouchEvent(MotionEvent motionEvent) { if(lm != null) { ic.handleInput(motionEvent, lm, sm, vp); } return true; } }
/** * */ package uk.gov.hmcts.befta.util; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; /** * @author korneleehenry * */ class MapVerificationResultTest { /** * Test method for {@link uk.gov.hmcts.befta.util.MapVerificationResult#minimalUnverifiedResult(java.lang.String, int, int)}. */ @Test void testMinimalUnverifiedResult() { String field = "field"; int currentDepth = 1; int maxMessageDepth = 2; MapVerificationResult actual = MapVerificationResult.minimalUnverifiedResult(field, currentDepth, maxMessageDepth); assertNotNull(actual); assertFalse(actual.isVerified()); } /** * Test method for {@link java.lang.Object#equals(java.lang.Object)}. */ @Test void testEqualsObject() { String field = "field"; int currentDepth = 1; int maxMessageDepth = 2; MapVerificationResult actual = new MapVerificationResult(field, false, "Summary",currentDepth, maxMessageDepth); MapVerificationResult expected = new MapVerificationResult(field, false, "Summary",currentDepth, maxMessageDepth); assertEquals(expected,actual); assertEquals(expected.hashCode(), actual.hashCode()); } /** * Test method for {@link java.lang.Object#toString()}. */ @Test void testToString() { String field = "field"; int currentDepth = 1; int maxMessageDepth = 2; String summary = "summary"; MapVerificationResult actual = new MapVerificationResult(field, false, "Summary",currentDepth, maxMessageDepth); MapVerificationResult expected = new MapVerificationResult(field, false, "",currentDepth, maxMessageDepth); expected.setCurrentDepth(currentDepth); expected.setVerified(true); expected.setMaxMessageDepth(maxMessageDepth); expected.setSummary(summary); expected.setField(field); assertNotEquals(expected,actual); assertNotNull(actual.toString()); } }
package interviewTasks_Saim; public class RecursionString { public static void main(String[] args) { permutationString("ABC"); } public static void permutationString(String word){ permutationString("",word); } private static void permutationString(String perm, String word){ if(word.length()==0){ System.out.println(perm); }else{ for (int i = 0; i < word.length(); i++) { permutationString(perm+word.charAt(i), word.substring(0,i)+word.substring(i+1,word.length())); } } } }
package com.example.l03.projektpaszport; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class EdytujWazneInformacjeActivity extends AppCompatActivity { private EditText etprzyjmowanie_jedzenia; private EditText etprzyjmowanie_plynów; private EditText etmoje_bezpieczenstwo; private EditText etkorzystanie_z_toalety; private EditText etopieka_osobista; private EditText etsen; private EditText etalergie; private DatabaseHelper db; private WazneInformacje wazneInformacje; private Button bEdytuj; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { finish(); startActivity(new Intent(getApplicationContext(),OMnieActivity.class)); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edytuj_wazne_informacje); etprzyjmowanie_jedzenia = (EditText) findViewById(R.id.etprzyjmowanie_jedzenia); etprzyjmowanie_plynów= (EditText) findViewById(R.id.etprzyjmowanie_plynów); etmoje_bezpieczenstwo= (EditText) findViewById(R.id.etmoje_bezpieczenstwo); etkorzystanie_z_toalety= (EditText) findViewById(R.id.etkorzystanie_z_toalety); etopieka_osobista= (EditText) findViewById(R.id.etopieka_osobista); etsen= (EditText) findViewById(R.id.etsen); etalergie= (EditText) findViewById(R.id.etalergie); bEdytuj = (Button) findViewById(R.id.bEdytuj); db = new DatabaseHelper(getApplicationContext()); if(!db.checkWazneInformacjeDatabase()) { db.createWazneInformacje("brak informacji", "brak informacji", "brak informacji", "brak informacji", "brak informacji", "brak informacji", "brak informacji"); } wazneInformacje = db.getWazneInformacje(); Log.e("ilosc w wazne", wazneInformacje.getKorzystanie_z_toalety()); etprzyjmowanie_jedzenia.setText(wazneInformacje.getPrzyjmowanie_jedzenia()); etprzyjmowanie_plynów.setText(wazneInformacje.getPrzyjmowanie_plynów()); etmoje_bezpieczenstwo.setText(wazneInformacje.getMoje_bezpieczenstwo()); etkorzystanie_z_toalety.setText(wazneInformacje.getKorzystanie_z_toalety()); etopieka_osobista.setText(wazneInformacje.getOpieka_osobista()); etsen.setText(wazneInformacje.getSen()); etalergie.setText(wazneInformacje.getAlergie()); bEdytuj.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { wazneInformacje.setPrzyjmowanie_jedzenia(etprzyjmowanie_jedzenia.getText().toString()); wazneInformacje.setPrzyjmowanie_plynów(etprzyjmowanie_plynów.getText().toString()); wazneInformacje.setMoje_bezpieczenstwo(etmoje_bezpieczenstwo.getText().toString()); wazneInformacje.setKorzystanie_z_toalety(etkorzystanie_z_toalety.getText().toString()); wazneInformacje.setOpieka_osobista(etopieka_osobista.getText().toString()); wazneInformacje.setSen(etsen.getText().toString()); wazneInformacje.setAlergie(etalergie.getText().toString()); db.updateWazneInformacje(wazneInformacje); finish(); startActivity(new Intent(getApplicationContext(),OMnieActivity.class)); } }); } }
package com.team5.dl; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public enum MockFile { SAMPLE_RESPONSE( MockFileLocation.JSON, "sampleResponse.json" ), ; private String fileLocation; private String fileName; private MockFile(MockFileLocation fileLocation, String fileName) { this.fileLocation = fileLocation.fileLocation(); this.fileName = fileName; } public String load() { String contents = FileMocker.mock(fileLocation, fileName); assert contents != null; return contents; } public String fileLocation() { return fileLocation; } public String fileName() { return fileName; } } enum MockFileLocation { JSON("src/test/resources/json"), ; private String fileLocation; private MockFileLocation(String fileLocation) { this.fileLocation = fileLocation; } public String fileLocation() { return fileLocation; } } class FileMocker { private String contents; public FileMocker(String directoryPath, String fileName) { this.contents = mock(directoryPath, fileName); } public String getContents() { return this.contents; } public static String mock(String directoryPath, String fileName) { return read(formatDirectoryPath(directoryPath) + fileName); } private static String formatDirectoryPath(String directoryPath) { if (!directoryPath.endsWith("/")) { directoryPath = directoryPath + "/"; } return directoryPath; } private static String read(String filename) { try { return tryToRead(filename); } catch (Exception var2) { return handleException(filename); } } private static String handleException(String filename) { return null; } private static String tryToRead(String filename) throws FileNotFoundException, IOException { File file = new File(filename); char[] responseData = new char[(int)file.length()]; FileReader fileReader = new FileReader(file); fileReader.read(responseData); fileReader.close(); return new String(responseData); } }
package com.spbsu.benchmark.flink.index.ops; import com.spbsu.benchmark.flink.index.Result; import com.spbsu.flamestream.example.bl.index.model.WordIndexAdd; import com.spbsu.flamestream.example.bl.index.utils.IndexItemInLong; import com.spbsu.flamestream.runtime.utils.tracing.Tracing; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.functions.ProcessFunction; import org.apache.flink.util.Collector; import java.util.ArrayList; import java.util.Collection; import java.util.NavigableMap; import java.util.TreeMap; public class TotalOrderEnforcer extends ProcessFunction<Result, Result> { private transient NavigableMap<Long, Collection<Result>> buffer; //private transient Tracing.Tracer inputTracer; //private transient Tracing.Tracer outputTracer; @Override public void open(Configuration parameters) throws Exception { super.open(parameters); buffer = new TreeMap<>(); //inputTracer = Tracing.TRACING.forEvent("tot-enforcer-receive"); //outputTracer = Tracing.TRACING.forEvent("tot-enforcer-send"); } @Override public void processElement(Result value, Context ctx, Collector<Result> out) { //inputTracer.log(WordIndexAdd.hash( // value.wordIndexAdd().word(), // IndexItemInLong.pageId(value.wordIndexAdd().positions()[0]) //)); buffer.putIfAbsent(ctx.timestamp(), new ArrayList<>()); buffer.get(ctx.timestamp()).add(value); ctx.timerService().registerEventTimeTimer(ctx.timestamp()); } @Override public void onTimer(long timestamp, OnTimerContext ctx, Collector<Result> out) { final NavigableMap<Long, Collection<Result>> head = buffer.headMap(timestamp, true); head.forEach((ts, value) -> value.stream() //.peek(result -> outputTracer.log(WordIndexAdd.hash( // result.wordIndexAdd().word(), // IndexItemInLong.pageId(result.wordIndexAdd().positions()[0]) //))) .forEach(out::collect)); head.clear(); } }
package kh.cocoa.service; import kh.cocoa.dao.PositionDAO; import kh.cocoa.dto.PositionDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class PositionService implements PositionDAO { @Autowired PositionDAO pdao; // 소형 관리자 사용자관리 @Override public List<PositionDTO> getAllPosList(){ return pdao.getAllPosList(); } @Override public List<PositionDTO> getPositionList() { return pdao.getPositionList(); } @Override public int updatePosList(List<PositionDTO> list){ return pdao.updatePosList(list); } }
package naruter.com.outsourcing.dao.impl; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import lombok.extern.slf4j.Slf4j; import naruter.com.outsourcing.dao.ClientAnFreeDAO; import naruter.com.outsourcing.vo.AdditionalFreeInfo; import naruter.com.outsourcing.vo.ClientInfo; import naruter.com.outsourcing.vo.FreelancerInfo; @Slf4j @Repository public class ClientAnFreeDAOImpl implements ClientAnFreeDAO { @Autowired private SqlSession ss; @Override public Integer clientInsert(ClientInfo ci) { // TODO Auto-generated method stub return ss.insert("SQL.CLIENTANFREE.inClient", ci); } @Override public Integer freeInsert(FreelancerInfo fi) { // TODO Auto-generated method stub return ss.insert("SQL.CLIENTANFREE.inFree", fi); } @Override public Integer freeEduInsertList(List<AdditionalFreeInfo> eduList) { // TODO Auto-generated method stub int hap=0; for(AdditionalFreeInfo edu : eduList) { hap += ss.insert("SQL.CLIENTANFREE.inEdu",edu); } return hap; } @Override public Integer freeEduInsert(AdditionalFreeInfo edu) { // TODO Auto-generated method stub return ss.insert("SQL.CLIENTANFREE.inEdu",edu); } @Override public Integer clientUpdate(ClientInfo ci) { // TODO Auto-generated method stub return ss.update("SQL.CLIENTANFREE.upClient", ci); } @Override public Integer freeUpdate(FreelancerInfo fi) { // TODO Auto-generated method stub return ss.update("SQL.CLIENTANFREE.upFree", fi); } @Override public Integer freeEduUpdate(AdditionalFreeInfo edu) { // TODO Auto-generated method stub return ss.update("SQL.CLIENTANFREE.upEdu", edu); } @Override public ClientInfo clientSelect(Integer memberNum) { // TODO Auto-generated method stub return ss.selectOne("SQL.CLIENTANFREE.selClient", memberNum); } @Override public FreelancerInfo freeSelect(Integer memberNum) { // TODO Auto-generated method stub return ss.selectOne("SQL.CLIENTANFREE.selFree", memberNum); } @Override public List<AdditionalFreeInfo> freeEduSelect(Integer memberNum) { // TODO Auto-generated method stub return ss.selectList("SQL.CLIENTANFREE.selEdu", memberNum); } @Override public Integer additionalDel(AdditionalFreeInfo addinfo) { // TODO Auto-generated method stub return ss.delete("SQL.CLIENTANFREE.delEdu", addinfo); } @Override public Character getMemType(Integer memberNum) { String type = ss.selectOne("SQL.CLIENTANFREE.getType", memberNum); return type.charAt(0); } @Override public Integer chSkill(Integer skillNum) { // TODO Auto-generated method stub return ss.selectOne("SQL.CLIENTANFREE.chSkill", skillNum); } }
package ejercicios.nonacces.estaticos; public class MainPersona { public static void main(String[] args) { // TODO Auto-generated method stub Paciente paciente1 = new Paciente(); paciente1.setNombre("Juan"); paciente1.setEdad(25); paciente1.registrar(paciente1.getNombre()); // utilizar variable estatica Paciente.consultarNacionalidadStatica(); } }
package com.tencent.tencentmap.mapsdk.a; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import com.tencent.map.lib.gl.model.GLIcon; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.OutputStream; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; public class kq$a implements jg { private final WeakReference<kq> a; private byte[] b = null; public kq$a(kq kqVar) { this.a = new WeakReference(kqVar); } public byte[] a(String str) { Closeable closeable; Throwable th; HttpURLConnection httpURLConnection; if (this.a == null || this.a.get() == null) { return null; } if (!kq.a((kq) this.a.get()).a(str)) { return null; } if (str != null) { str = str.replace("/mvd_map", jy.b()).replace("/mobile_newmap", jy.b()); } String a = jy.a(str); int i = (a.contains("styleid") && a.contains("scene") && a.contains("version")) ? 1 : 0; if (i == 0) { String str2; if (a.endsWith(".jpg") || a.startsWith("http://closedroadvector.map.qq.com") || a.startsWith("http://p0.map.gtimg.com/scenic/")) { str2 = a; } else { str2 = a + kh.c(kq.b((kq) this.a.get())); } try { po a2 = pn.a().a(str2, "androidsdk"); if (a2 == null) { return null; } if (!a.contains("qt=rtt")) { kq.a((kq) this.a.get()).b(a); } if (a.startsWith("http://p0.map.gtimg.com/scenic/") && a2.a != null && a2.a.length == 0) { if (this.b == null) { Bitmap createBitmap = Bitmap.createBitmap(GLIcon.TOP, GLIcon.TOP, Config.ARGB_8888); new Canvas(createBitmap).drawARGB(0, 255, 255, 255); OutputStream byteArrayOutputStream = new ByteArrayOutputStream(); createBitmap.compress(CompressFormat.PNG, 100, byteArrayOutputStream); this.b = byteArrayOutputStream.toByteArray(); } a2.a = this.b; } return a2.a; } catch (Exception e) { return null; } } HttpURLConnection httpURLConnection2; Closeable inputStream; try { httpURLConnection2 = (HttpURLConnection) new URL(a).openConnection(); try { httpURLConnection2.addRequestProperty("User-Agent", "androidsdk"); httpURLConnection2.setConnectTimeout(10000); if (httpURLConnection2.getResponseCode() == 200) { inputStream = httpURLConnection2.getInputStream(); try { byte[] a3 = q.a(inputStream); if (!a.contains("qt=rtt")) { kq.a((kq) this.a.get()).b(a); } if (httpURLConnection2 != null) { httpURLConnection2.disconnect(); } if (inputStream != null) { q.a(inputStream); } return a3; } catch (Throwable th2) { th = th2; httpURLConnection = httpURLConnection2; if (httpURLConnection != null) { httpURLConnection.disconnect(); } if (inputStream != null) { q.a(inputStream); } throw th; } } if (httpURLConnection2 != null) { httpURLConnection2.disconnect(); } return null; } catch (Throwable th3) { th = th3; inputStream = null; httpURLConnection = httpURLConnection2; if (httpURLConnection != null) { httpURLConnection.disconnect(); } if (inputStream != null) { q.a(inputStream); } throw th; } } catch (Throwable th4) { th = th4; inputStream = null; httpURLConnection = null; if (httpURLConnection != null) { httpURLConnection.disconnect(); } if (inputStream != null) { q.a(inputStream); } throw th; } } }
package com.diozero.devices.sandpit.motor; /*- * #%L * Organisation: diozero * Project: diozero - Core * Filename: SilentStepStick.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import com.diozero.api.RuntimeIOException; import com.diozero.devices.sandpit.motor.ChopperStepperController.FrequencyMultiplierChopperController; /** * Represents a class of bipolar stepper motor drivers using 3 inputs: enable, direction, and "speed" (PWM frequency). * <p> * Originally developed for a <a href="https://learn.watterott.com/silentstepstick/">Watterott SilentStepStick</a>, * this should be compatible with the Pololu A4988 drivers and other compatible ADI Tinamic drivers. * <p> * The micro-step capabilities of the driver chip are configured externally to this driver. This does <b>NOT</b> use * the UART interface. * <p> * The "enable" pin turns the motor driver on and off. In most cases, if the driver is <b>disabled</b>, power * is not supplied to the motor and the shaft can be moved manually. * * @author Greg Flurry, E. A. Graham Jr. */ public class SilentStepStick extends AbstractChopperStepperMotor { public static final int DEFAULT_STEPS = 200; /** * Constructs a new stepper motor instance with default 200 steps per rotation. * * @param driver the driver */ public SilentStepStick(ChopperStepperController.FrequencyMultiplierChopperController driver) { this(driver, DEFAULT_STEPS); } /** * Constructs a new stepper motor instance. * * @param driver the driver * @param stepsPerRevolution steps (not counting micro-stepping) */ public SilentStepStick(FrequencyMultiplierChopperController driver, int stepsPerRevolution) { super(stepsPerRevolution, driver); } /** * Whether the driver is currently enabled or not. * * @return {@code true} if enabled */ public boolean isEnabled() { return myDriver().isEnabled(); } /** * Enables or disables the stepper driver. * <p> * When disabled, typically the driver does not power the motor, and thus there is no torque applied. It can be * turned manually. * * @param enabled {@code true} to enable */ public void setEnabled(boolean enabled) { myDriver().setEnabled(enabled); } @Override protected void run(Direction direction, float speed) { ChopperStepperController.FrequencyMultiplierChopperController driver = myDriver(); if (!driver.isEnabled()) throw new RuntimeIOException("Driver is not enabled"); driver.setDirection(direction); var frequencyFactor = stepsPerRotation / 60f; var multiplier = driver.getResolution().multiplier(); var frequency = Math.round(speed * frequencyFactor * multiplier); driver.setFrequency(frequency); driver.run(); } private FrequencyMultiplierChopperController myDriver() { return ((ChopperStepperController.FrequencyMultiplierChopperController)getController()); } }
package com.zitrojjdev.sampleapp1; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; public class WebViewActvity extends AppCompatActivity { private static final String TAG = "onWebViewActivity"; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_view_actvity); // receiving the url from previous intent Intent intent = getIntent(); String url =""; try { url= intent.getStringExtra("url"); } catch (NullPointerException e){ Log.d(TAG, "onCreate: No url from intent"); } // initWidget webView = findViewById(R.id.webView); // para evitar que se abra con el navegador webView.setWebViewClient(new WebViewClient()); // open javascripts for websites to work webView.getSettings().setJavaScriptEnabled(true); // load url webView.loadUrl(url); } // Como navegamos dentro de nuestra app, el boton de go back de android puede navegar atrás dentro del webView // o puede navegar atrás en nuestra APP y sacarnos del webView. Por eso sobreescribimos el método @Override public void onBackPressed() { // si podemos navegar atrás dentro del webView, if (webView.canGoBack()){ webView.goBack(); } else { // Si no podemos ir atras en el webView, vamos atras en la APP super.onBackPressed(); } } }
package br.com.pcmaker.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import br.com.pcmaker.common.util.StringUtils; import br.com.pcmaker.dao.UsuarioDAO; import br.com.pcmaker.entity.Usuario; import br.com.pcmaker.enums.StatusRegistro; @Repository public class UsuarioDaoImpl extends CrudDAOImpl<Usuario> implements UsuarioDAO{ @SuppressWarnings("unchecked") @Override public Usuario get(String login) { DetachedCriteria criteria = DetachedCriteria.forClass(Usuario.class); criteria.add(Restrictions.eq("login", login)); criteria.add(Restrictions.eq("statusRegistro", StatusRegistro.ATIVO.getCodigo())); List<Usuario> usuarios = (List<Usuario>) template.findByCriteria(criteria); return !usuarios.isEmpty() ? (Usuario) usuarios.get(0) : null; } @SuppressWarnings("unchecked") @Override public List<Usuario> query(String nome, String login) { DetachedCriteria criteria = DetachedCriteria.forClass(Usuario.class); if(StringUtils.isNotBlank(nome)){ criteria.add(Restrictions.like("nome", nome, MatchMode.ANYWHERE)); } if(StringUtils.isNotBlank(login)){ criteria.add(Restrictions.like("login", login, MatchMode.ANYWHERE)); } criteria.addOrder(Order.asc("nome")); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return (List<Usuario>) template.findByCriteria(criteria); } }
package engine.util.math; public class Vector2 { private double x; private double y; public Vector2() { x = 0; y = 0; } public Vector2(double x, double y) { this.x = x; this.y = y; } public Vector2(Vector2 vec) { x = vec.getX(); y = vec.getY(); } public double getX() { return x; } public double getY() { return y; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public void incrementX(double x) { this.x += x; } public void incrementY(double y) { this.y += y; } public void decrementX(double x) { this.x -= x; } public void decrementY(double y) { this.y -= y; } public void increment(Vector2 vec) { x += vec.getX(); y += vec.getY(); } public void decrement(Vector2 vec) { x -= vec.getX(); y -= vec.getY(); } public void copy(Vector2 vec) { x = vec.getX(); y = vec.getY(); } public void setMagnitude(double magnitude) { if(getMagnitude() == 0) { setX(1); setY(1); } Vector2 unitVector = getUnitVector(); setX(unitVector.getX() * magnitude); setY(unitVector.getY() * magnitude); } public double getMagnitude() { return Math.sqrt( (x * x) + (y * y)); } public Vector2 getUnitVector() { if (getMagnitude() > 0) { return new Vector2(x / getMagnitude(), y / getMagnitude()); } else { return new Vector2(0, 0); } } }
package com.fanniemae.www.messaging.services; import java.sql.SQLException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.JSONException; import org.json.JSONObject; import com.fanniemae.www.messaging.messageDAO.IMessageDAO; import com.fanniemae.www.messaging.messageDAO.MessageDAO; import com.fanniemae.www.messaging.messageDTO.MessageDTO; @Path("/messages") public class MessageService { @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public MessageDTO create(MessageDTO message) throws ClassNotFoundException, SQLException { IMessageDAO MessageDAO = new MessageDAO(); return MessageDAO.create(message); } @GET @Path("/{messageID}") @Produces(MediaType.APPLICATION_JSON) public MessageDTO read(@PathParam("messageID") long messageID) throws SQLException, ClassNotFoundException { IMessageDAO MessageDAO = new MessageDAO(); return MessageDAO.read(messageID); } @PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public MessageDTO update(MessageDTO message) throws ClassNotFoundException, SQLException { IMessageDAO messageDAO = new MessageDAO(); return messageDAO.update(message); } @DELETE @Path("{messageID}") @Produces(MediaType.APPLICATION_JSON) public Response delete(@PathParam("messageID") long messageID) throws ClassNotFoundException, SQLException, JSONException { IMessageDAO MessageDAO = new MessageDAO(); String message = MessageDAO.delete(messageID); JSONObject jsonObject = new JSONObject(); jsonObject.put("message", message); return Response.status(200).entity(jsonObject.toString()).build(); } }
package cn.nam.ssm.seckill.web; import cn.nam.ssm.seckill.dto.Exposer; import cn.nam.ssm.seckill.dto.SeckillExecution; import cn.nam.ssm.seckill.dto.SeckillResult; import cn.nam.ssm.seckill.entiy.Seckill; import cn.nam.ssm.seckill.enums.SeckillStateEnum; import cn.nam.ssm.seckill.exception.RepeatKillException; import cn.nam.ssm.seckill.exception.SeckillCloseException; import cn.nam.ssm.seckill.service.SeckillService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.Date; import java.util.List; /** * 前端页面操作控制模块 * 使用restul风格的url模块/资源/{}/细分 * * @author Nanrong Zeng * @version 1.0 */ @Component("SeckillController") @RequestMapping("/seckill") public class SeckillController { @Autowired private SeckillService seckillService; /** * 获取秒杀商品列表页 * * @param model * @return */ @RequestMapping(value = "/list", method = RequestMethod.GET) public String list(Model model) { List<Seckill> list = seckillService.getSeckillList(); model.addAttribute("list", list); // 访问的是/WEB-INF/jps/list.jsp return "list"; } /** * 获取某一商品的秒杀详情页 * * @param seckillId * @param model * @return */ @RequestMapping(value = "/{seckillId}/detail", method = RequestMethod.GET) public String detail(@PathVariable("seckillId") Long seckillId, Model model) { if (seckillId == null) { // 当没有点击具体某一秒杀商品详情时,重新返回list页面 return "redirect:/seckill/list"; } Seckill seckill = seckillService.getById(seckillId); if (seckill == null) { // id无效,重新返回list页面 return "redirect:/seckill/list"; } model.addAttribute("seckill", seckill); return "detail"; } /** * 获取商品秒杀操作详情地址(md5) * * @param seckillId * @return 秒杀开始,返回秒杀操作入口;秒杀未开始,返回系统时间和秒杀时间 */ @RequestMapping(value = "/{seckillId}/exposer", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"}) @ResponseBody public SeckillResult<Exposer> exposer(@PathVariable("seckillId") Long seckillId) { SeckillResult<Exposer> result; try { Exposer exposer = seckillService.exportSeckillUrl(seckillId); result = new SeckillResult<>(true, exposer); } catch (Exception e) { e.printStackTrace(); result = new SeckillResult<>(false, e.getMessage()); } return result; } /** * 执行秒杀 * * @param seckillId * @param md5 md5加密的秒杀地址段 * @param userPhone * @return 秒杀成功,返回包含秒杀明细对象的SeckillResult; 否则,返回错误信息 */ @RequestMapping(value = "/{seckillId}/{md5}/execution", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) @ResponseBody public SeckillResult<SeckillExecution> execute( @PathVariable("seckillId") Long seckillId, @PathVariable("md5") String md5, @CookieValue(value = "userPhone", required = false) Long userPhone) { if (userPhone == null) { return new SeckillResult<>(false, "未注册"); } try { SeckillExecution successExecution = seckillService.executeSeckill(seckillId, userPhone, md5); return new SeckillResult<>(true, successExecution); } catch (RepeatKillException e1) { SeckillExecution repeatExecution = new SeckillExecution(seckillId, SeckillStateEnum.REPEAT_KILL); return new SeckillResult<>(true, repeatExecution); } catch (SeckillCloseException e2) { SeckillExecution endExecution = new SeckillExecution(seckillId, SeckillStateEnum.END); return new SeckillResult<>(true, endExecution); } catch (Exception e) { SeckillExecution innerErrorExecution = new SeckillExecution(seckillId, SeckillStateEnum.INNER_ERROR); return new SeckillResult<>(true, innerErrorExecution); } } /** * 获取系统当前时间 * * @return */ @RequestMapping(value = "/time/now", method = RequestMethod.GET) @ResponseBody public SeckillResult<Long> getCurrentTime() { Date now = new Date(); return new SeckillResult<>(true, now.getTime()); } }
package com.test.demo; import java.util.List; public interface IStudentService { public void save(List<Student> students); }
package org.alienideology.jcord.event.handler; import org.alienideology.jcord.JCord; import org.alienideology.jcord.event.guild.GuildCreateEvent; import org.alienideology.jcord.internal.object.IdentityImpl; import org.alienideology.jcord.internal.object.guild.Guild; import org.alienideology.jcord.internal.object.user.User; import org.json.JSONArray; import org.json.JSONObject; /** * @author AlienIdeology */ public class GuildCreateEventHandler extends EventHandler { public GuildCreateEventHandler(IdentityImpl identity) { super(identity); } @Override public void dispatchEvent(JSONObject json, int sequence) { Guild guild = (Guild) identity.getGuild(json.getString("id")); if (json.has("presences")) { JSONArray presences = json.getJSONArray("presences"); for (int i = 0; i < presences.length(); i++) { JSONObject presence = presences.getJSONObject(i); builder.buildPresence(presence, (User) identity.getUser(presence.getJSONObject("user").getString("id"))); // Presences are set automatically } } // Ignore initial guild create event if (guild == null) { guild = builder.buildGuild(json); dispatchEvent(new GuildCreateEvent(identity, sequence, guild)); } // Request guild members after the guild is built long memberCount = json.getLong("member_count"); if (memberCount > JCord.GUILD_MEMBERS_LARGE_THRESHOLD) { // Need to request guild members identity.getGateway().sendRequestMembers(json.getString("id")); } } }
package com.locadoraveiculosweb.mappers; import java.util.List; import javax.enterprise.inject.Model; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import com.locadoraveiculosweb.modelo.Carro; import com.locadoraveiculosweb.modelo.dtos.CarroDto; @Model @Mapper(componentModel = "cdi", uses = { AcessorioMapper.class, ModeloCarroMapper.class }) public interface CarroMapper { @Mapping(target="alugueis", ignore = true) Carro toCarro(CarroDto dto); @Mapping(target="alugueis", ignore = true) CarroDto toCarroDto(Carro entity); List<Carro> toCarro(List<CarroDto> dto); List<CarroDto> toCarroDto(List<Carro> entity); }
package com.x.service; import java.util.Date; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import com.x.model.weixin.WeixinSearchParams; import com.x.model.weixin.message.resp.TextMessage; import com.x.utils.StringUtil; import com.x.utils.weixin.MessageUtil; /** * @ClassName: CoreService.java * @Description: TODO * * @author Kenmy * @version V1.0 * @Date 2014-1-11下午02:41:36 */ public class WeixinCoreService { private static Logger log = Logger.getLogger(WeixinCoreService.class); /** * 处理微信发来的请求 * * @param request * @return: String * @author: Kenmy * @Date: 2014-1-11 下午02:18:14 */ public String processRequest(HttpServletRequest request) { String respMessage = null; try { // 默认返回的文本消息内容 String respContent = "您好,您问的问题我还在学习中/:P-("; // xml请求解析 Map<String, String> requestMap = MessageUtil.paraseXml(request); // 消息类型 String msgType = requestMap.get("MsgType"); // 文本消息 if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) { // 指令消息内容 String order = StringUtil.ToDBC(requestMap.get("Content")); if (order.equals("?")) { // 获取住菜单帮助信息 // respContent = WeixinOrderGroupInit.menu; respContent = "获得菜单帮助信息"; } else if (isQqFace(order)) { // 判断用户发送的是否是单个QQ表情,是则返回该表情 respContent = order; } else { // String type = WeixinOrderGroupInit.get(order); // if (type.equals("text")) { // respContent = // textService.getContext(StringUtil.toInt(order)).getContent(); // } else if (type.equals("news")) { // return new NewsCoreService().processRequest(requestMap); // } } } else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) { respContent = "您发送的是图片消息!"; } else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) { respContent = "您发送的是地理位置消息!"; } else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) { respContent = "您发送的是链接消息!"; } else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) { respContent = "您发送的是音频消息!"; } else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) { // 事件推送 // 事件类型 String eventType = requestMap.get("Event"); // 订阅 if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) { // respContent = // "感谢您对勤快柳儿的喜爱\n".concat(WeixinOrderGroupInit.menu); } else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) { // 取消订阅 // TODO: 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息 } else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) { // TODO: 自定义菜单权没有开放,暂不处理该类信息 } } respMessage = messageText(requestMap, respContent); } catch (Exception e) { log.error(e); } return respMessage; } /** * 回复文本消息 * * @param requestMap * @return */ public String messageText(Map<String, String> requestMap, String respContent) { // 发送帐号(open_id) String fromUserName = requestMap.get("FromUserName"); // 公众帐号 String toUserName = requestMap.get("ToUserName"); // 回复文本消息 TextMessage textMessage = new TextMessage(); textMessage.setToUserName(fromUserName); textMessage.setFromUserName(toUserName); textMessage.setCreateTime(new Date().getTime()); textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT); textMessage.setFuncFlag(0); textMessage.setContent(respContent); return MessageUtil.textMessageToXml(textMessage); } /** * 判断是否是QQ表情 * * @param content * @return boolean */ public static boolean isQqFace(String content) { boolean result = false; String qqfaceRegex = "/::\\)|/::~|/::B|/::\\||/:8-\\)|/::<|/::$|/::X|/::Z|/::'\\(|/::-\\||/::@|/::P|/::D|/::O|/::\\(|/::\\+|/:--b|/::Q|/::T|/:,@P|/:,@-D|/::d|/:,@o|/::g|/:\\|-\\)|/::!|/::L|/::>|/::,@|/:,@f|/::-S|/:\\?|/:,@x|/:,@@|/::8|/:,@!|/:!!!|/:xx|/:bye|/:wipe|/:dig|/:handclap|/:&-\\(|/:B-\\)|/:<@|/:@>|/::-O|/:>-\\||/:P-\\(|/::'\\||/:X-\\)|/::\\*|/:@x|/:8\\*|/:pd|/:<W>|/:beer|/:basketb|/:oo|/:coffee|/:eat|/:pig|/:rose|/:fade|/:showlove|/:heart|/:break|/:cake|/:li|/:bome|/:kn|/:footb|/:ladybug|/:shit|/:moon|/:sun|/:gift|/:hug|/:strong|/:weak|/:share|/:v|/:@\\)|/:jj|/:@@|/:bad|/:lvu|/:no|/:ok|/:love|/:<L>|/:jump|/:shake|/:<O>|/:circle|/:kotow|/:turn|/:skip|/:oY|/:#-0|/:hiphot|/:kiss|/:<&|/:&>"; Pattern p = Pattern.compile(qqfaceRegex); Matcher m = p.matcher(content); if (m.matches()) { result = true; } return result; } /** * 菜单点击处理 * * @param respContent * @param eventKey * @return */ private String menuClick(Map<String, String> requestMap, String respContent, String eventKey, WeixinSearchParams params) { String respMessage = null; int key = StringUtil.toInt(eventKey); switch (key) { case 11: // 游戏介绍 params.setMenuId(11); break; case 12: // 最新资讯 params.setMenuId(12); break; case 13: // 加入QQ群 params.setMenuId(13); break; case 21: // 最新活动 params.setMenuId(21); break; case 22: // 获奖名单 params.setMenuId(22); break; case 23: // 刮刮卡 params.setMenuId(23); break; case 24: // 绑定角色 params.setMenuId(24); break; case 31: // 客服电话被点击 params.setMenuId(31); break; case 32: // 游戏帮助FAQ params.setMenuId(32); break; case 33: // 问题反馈 params.setMenuId(33); break; case 34: // 调戏蛋挞妹 params.setMenuId(34); break; case 35: // 听蛋挞唱歌 params.setMenuId(35); break; } if (respMessage == null) { // respMessage = new // WeixinMessageCoreService().processRequest(requestMap, params); } return respMessage; } }
package com.lfd.day0000_01_tools.utils; import java.io.File; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.os.Environment; import android.os.StatFs; import android.text.format.Formatter; public class StorageUtils { /** * * @param file * @return long[] size 2 total,available */ @SuppressLint("NewApi") @SuppressWarnings("deprecation") public static long[] getStorageSize(File file){ long availableBlocks; long blockCount; long blockSize; StatFs fs = new StatFs(file.getPath()); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ availableBlocks = fs.getAvailableBlocksLong(); blockCount = fs.getBlockCountLong(); blockSize = fs.getBlockSizeLong(); }else{ availableBlocks = fs.getAvailableBlocks(); blockCount = fs.getBlockCount(); blockSize = fs.getBlockSize(); } return new long[]{blockSize*blockCount,blockSize*availableBlocks}; } /** * 格式化-存储大小 * @param context * @param file * @return */ public static String[] getStorageFormatterSize(Context context,File file){ long[] ls = getStorageSize(file); return new String[]{Formatter.formatFileSize(context, ls[0]),Formatter.formatFileSize(context, ls[1])}; } /** * @param relfile 文件相对路径-相对sdcard * @return 绝对路径 */ public static File getSdcardFile(File relfile){ if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){ if(!relfile.isAbsolute()){ return new File(Environment.getExternalStorageDirectory(),relfile.getParent()); }else{ return relfile; } }else{ return null; } } }
/* * Copyright 2019 GcsSloop * * 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. * * Last modified 2019-05-09 02:16:23 * * GitHub: https://github.com/GcsSloop * WeiBo: http://weibo.com/GcsSloop * WebSite: http://www.gcssloop.com */ package com.gcssloop.pagelayoutmanager; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; /** * Created by louisgeek on 2018/9/21. */ public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder> implements IDataAccess<T> { protected List<T> mDataList = new ArrayList<>(); protected abstract int setupItemLayoutId(); @NonNull @Override public BaseRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(setupItemLayoutId(), parent, false); return new BaseRecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull final BaseRecyclerViewHolder holder, final int position) { //抽象方法 this.findBindView(position, holder); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(v, position); } } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mOnItemClickListener != null) { return mOnItemClickListener.onItemLongClick(v, position); } return false; } }); } @Override public int getItemCount() { return mDataList.size(); } protected abstract void findBindView(int position, BaseRecyclerViewHolder baseViewHolder); //clickable private OnItemClickListener mOnItemClickListener; public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.mOnItemClickListener = onItemClickListener; } @Override public List<T> getDataList() { return mDataList; } @Override public T getData(int position) { return mDataList.get(position); } @Override public void refreshDataList(List<T> dataList) { if (dataList == null) { return; } mDataList.clear(); mDataList.addAll(dataList); notifyDataSetChanged(); } @Override public void clearDataList() { mDataList.clear(); notifyDataSetChanged(); } @Override public boolean addDataListAtStart(List<T> dataList) { if (dataList == null) { return false; } mDataList.addAll(0, dataList); notifyItemRangeInserted(0, dataList.size()); return true; } @Override public boolean addDataListAtEnd(List<T> dataList) { if (dataList == null) { return false; } int positionStart = mDataList.size(); mDataList.addAll(dataList); notifyItemRangeInserted(positionStart, dataList.size()); return true; } @Override public boolean addData(int position, T data) { if (data == null) { return false; } mDataList.add(data); notifyItemInserted(position); return true; } @Override public boolean addDataAtStart(T data) { if (data == null) { return false; } mDataList.add(0, data); notifyItemInserted(0); return true; } @Override public boolean addDataAtEnd(T data) { if (data == null) { return false; } int positionStart = mDataList.size(); mDataList.add(data); notifyItemInserted(positionStart); return true; } @Override public boolean removeData(int position) { boolean result = false; T d = mDataList.remove(position); if (d != null) { result = true; notifyItemRemoved(position); } return result; } @Override public boolean removeData(T data) { if (data == null) { return false; } boolean result = false; int index = mDataList.indexOf(data); if (index > 0) { result = this.removeData(index); } return result; } @Override public boolean replaceData(int locationPos, T data) { if (data == null) { return false; } boolean result = false; T d = mDataList.set(locationPos, data); if (d != null) { result = true; notifyItemChanged(locationPos); } return result; } @Override public boolean replaceData(T oldData, T data) { if (oldData == null || data == null) { return false; } boolean result = false; int index = mDataList.indexOf(oldData); if (index > 0) { result = this.replaceData(index, data); } return result; } }
package cn.edu.hebtu.software.sharemate.Adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import cn.edu.hebtu.software.sharemate.Bean.Comment; import cn.edu.hebtu.software.sharemate.Bean.CommentBean; import cn.edu.hebtu.software.sharemate.Bean.NoteBean; import cn.edu.hebtu.software.sharemate.R; public class CustomAdapter extends BaseAdapter implements View.OnClickListener{ private Context context; private int itemLaout; private Callback mCallback; private List<NoteBean> notes =new ArrayList<>(); public CustomAdapter(Context context, int itemLaout, Callback mCallback, List<NoteBean> notes) { this.context = context; this.itemLaout = itemLaout; this.mCallback = mCallback; this.notes = notes; } @Override public int getCount() { return notes.size(); } @Override public Object getItem(int position) { return notes.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView==null){ viewHolder = new ViewHolder(); LayoutInflater layoutInflater=LayoutInflater.from(context); convertView=layoutInflater.inflate(itemLaout,null); viewHolder.userIcon=convertView.findViewById(R.id.user_icon); viewHolder.userName=convertView.findViewById(R.id.user_name); viewHolder.guanZhu = convertView.findViewById(R.id.guannzhu); viewHolder.ivPhoto=convertView.findViewById(R.id.iv_photo); viewHolder.noteDetail=convertView.findViewById(R.id.note_alltext); viewHolder.noteTitle=convertView.findViewById(R.id.title); viewHolder.noteZan = convertView.findViewById(R.id.dianzan); viewHolder.zanCount=convertView.findViewById(R.id.z_count); viewHolder.noteShoucang = convertView.findViewById(R.id.shoucang); viewHolder.shouCount=convertView.findViewById(R.id.c_count); viewHolder.noteComment= convertView.findViewById(R.id.pinglun); viewHolder.Comment2= convertView.findViewById(R.id.pinglun2); viewHolder.commentCount=convertView.findViewById(R.id.p_count); viewHolder.Comment=convertView.findViewById(R.id.pinglun1); viewHolder.Allcount=convertView.findViewById(R.id.all_count); viewHolder.contentUserIcon=convertView.findViewById(R.id.user_icon2); viewHolder.addComment=convertView.findViewById(R.id.fb); viewHolder.sendComment=convertView.findViewById(R.id.fabu); viewHolder.noteTime = convertView.findViewById(R.id.time); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder)convertView.getTag(); } //设置显示的图片和文字 if(notes.get(position).isIslike()==1){ notes.get(position).setZan(R.drawable.xihuan2); }else {notes.get(position).setZan(R.drawable.xin);} if(notes.get(position).getIscollect()==1){ notes.get(position).setCol(R.drawable.xingxing2); }else {notes.get(position).setCol(R.drawable.xingxing);} if(notes.get(position).getIsfollow()==1){ viewHolder.guanZhu.setBackgroundResource(R.drawable.cancelfollowedbutton_style); viewHolder.guanZhu.setText("已关注"); viewHolder.guanZhu.setTextColor(convertView.getResources().getColor(R.color.deepGray)); }else{ viewHolder.guanZhu.setBackgroundResource(R.drawable.followbutton_style); viewHolder.guanZhu.setText("关注"); viewHolder.guanZhu.setTextColor(convertView.getResources().getColor(R.color.brightRed)); } viewHolder.noteZan.setBackgroundResource(notes.get(position).getZan()); viewHolder.ivPhoto.setImageBitmap(notes.get(position).getNoteImage1()); viewHolder.noteDetail.setText(notes.get(position).getNoteDetail()); viewHolder.noteTitle.setText(notes.get(position).getNoteTitle()); viewHolder.noteTime.setText(notes.get(position).getNoteTime()); viewHolder.userName.setText(notes.get(position).getUser().getUserName()); viewHolder.Comment.setText(notes.get(position).getCommentBean().getUser().getUserName()+":"+ notes.get(position).getCommentBean().getCommentDetail()); viewHolder.Comment2.setText(notes.get(position).getCommentDetail()); viewHolder.Allcount.setText("共"+notes.get(position).getPingluncount()+"条评论"); viewHolder.userIcon.setImageBitmap(notes.get(position).getUser().getUserImage()); viewHolder.contentUserIcon.setImageBitmap(notes.get(position).getUserContent().getUserImage()); viewHolder.zanCount.setText(notes.get(position).getZancount1()+""); viewHolder.shouCount.setText(notes.get(position).getCollectcount()+""); viewHolder.commentCount.setText(notes.get(position).getPingluncount()+""); viewHolder.noteShoucang.setBackgroundResource(notes.get(position).getCol()); viewHolder.userIcon.setTag(position); viewHolder.guanZhu.setTag(position); viewHolder.noteZan.setTag(position); viewHolder.sendComment.setTag(position); viewHolder.noteShoucang.setTag(position); viewHolder.noteComment.setTag(position); viewHolder.addComment.setTag(position); viewHolder.userIcon.setOnClickListener(this); viewHolder.guanZhu.setOnClickListener(this); viewHolder.noteZan.setOnClickListener(this); viewHolder.noteShoucang.setOnClickListener(this); viewHolder.noteComment.setOnClickListener(this); viewHolder.sendComment.setOnClickListener(this); viewHolder.addComment.setOnClickListener(this); final ViewHolder finalViewHolder = viewHolder; //final ViewHolder finalViewHolder2 = viewHolder; viewHolder.addComment.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ }else { int p = (int) v.getTag(); String c = ""+finalViewHolder.addComment.getText(); if(!c.equals("")){ notes.get(p).setCommentDetail(c); } Log.e("comment",c); } } }); return convertView; } class ViewHolder { ImageView userIcon; TextView userName; Button guanZhu; ImageView ivPhoto; TextView noteDetail; TextView noteTitle; Button noteZan;TextView zanCount; Button noteShoucang;TextView shouCount; Button noteComment;TextView commentCount; TextView Comment;TextView Allcount;TextView Comment2; ImageView contentUserIcon; EditText addComment; Button sendComment; TextView noteTime; } @Override public void onClick(View view) { mCallback.click(view); } /** * 回调接口. */ public interface Callback { void click(View v); } }
package com.example.ecommerce.Model; public class Deliverers { private String name, phone, password, sid, address,email,balance,totalearning,totaldelivery,currentpick; public Deliverers() { } public Deliverers(String name, String phone, String password, String sid, String address, String email, String balance, String totalearning, String totaldelivery, String currentpick) { this.name = name; this.phone = phone; this.password = password; this.sid = sid; this.address = address; this.email = email; this.balance = balance; this.totalearning = totalearning; this.totaldelivery = totaldelivery; this.currentpick = currentpick; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBalance() { return balance; } public void setBalance(String balance) { this.balance = balance; } public String getTotalearning() { return totalearning; } public void setTotalearning(String totalearning) { this.totalearning = totalearning; } public String getTotaldelivery() { return totaldelivery; } public void setTotaldelivery(String totaldelivery) { this.totaldelivery = totaldelivery; } public String getCurrentpick() { return currentpick; } public void setCurrentpick(String currentpick) { this.currentpick = currentpick; } }
import java.io.IOException; import java.rmi.RemoteException; import java.util.*; public class SubjectManager implements ISubjectManager { private List<Subject> subjectList; private int listSize; // Default Constructor public SubjectManager() { } // Alternative constructor public SubjectManager(List<Subject> subjectList) { this.subjectList = subjectList; this.listSize = subjectList.size(); } // Loads subjects to the Manager public void loadSubjects (List<Subject> new_subjects) { this.subjectList = new ArrayList<Subject>(); this.subjectList = new_subjects; this.listSize = new_subjects.size(); } // Returns all subjects as a list public List<Subject> getAll() { return subjectList; } // Returns desired subject by code, or null if not found public Subject getSubjectByCode(String code) { for (Subject subject : subjectList) { if (subject.getCode().equals(code)) { return subject; } } return null; } // Changes desired subject's comment if subject is found, according to the received code public int changeComment(String code, String new_comment, User professor) { // Runs through list for (Subject subject : subjectList) { // Looks for code match if (subject.getCode().equals(code)) { // Checks if the subject's professor is the current user if ( !subject.getProfessor().equals(professor.getName()) ) { System.out.println("Professor logado não é o docente desse disciplina."); return 1; } else { // Changes comment subject.setComment(new_comment); // Updates the subjects' file through a DataCreation object DataCreation data_update = new DataCreation(); data_update.setSubjectsList(this.subjectList); try { data_update.writeSubjects(); } catch (IOException e) { System.out.println("Exceção na atualização do arquivo de disciplinas."); e.printStackTrace(); return 3; } return 0; } } } return 2; } }
package com.tencent.tencentmap.mapsdk.a; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class sy { private static sy b = null; private SharedPreferences a; private sy() { } public static sy a() { if (b == null) { synchronized (sy.class) { b = new sy(); } } return b; } public final String a(String str) { return this.a == null ? null : this.a.getString(str, null); } public final void a(Context context) { Context applicationContext = context.getApplicationContext(); this.a = applicationContext.getSharedPreferences(applicationContext.getPackageName(), 0); } public final boolean a(String str, int i) { return this.a == null ? false : this.a.edit().putInt(str, i).commit(); } public final boolean a(String str, String str2) { return this.a == null ? false : this.a.edit().putString(str, str2).commit(); } public final boolean a(String str, boolean z) { return this.a == null ? false : this.a.edit().putBoolean(str, z).commit(); } public final boolean a(String[] strArr) { int i = 0; if (this.a == null) { return false; } Editor edit = this.a.edit(); int length = strArr.length; while (i < length) { edit.remove(strArr[i]); i++; } return edit.commit(); } public final int b(String str) { return this.a == null ? -1 : this.a.getInt(str, -1); } public final boolean c(String str) { return this.a == null ? false : this.a.getBoolean(str, false); } }
/* * 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.apache.clerezza; /** * Represents a language as expressed by the RDF 4646 language tag * * @author reto */ public class Language { private String id; /** * Constructs the language tag defined by RDF 4646, normalized to lowercase. * * @param id as defined by RDF 4646, normalized to lowercase. */ public Language(String id) { if ((id == null) || (id.equals(""))) { throw new IllegalArgumentException("A language id may not be null or empty"); } this.id = id.toLowerCase(); } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other instanceof Language) { return id.equals(((Language) other).id); } else { return false; } } @Override public int hashCode() { return id.hashCode(); } @Override public String toString() { return id; } }
package com.tencent.mm.plugin.fingerprint; import com.tencent.mm.bt.h.d; import com.tencent.mm.model.ar; import com.tencent.mm.model.p; import com.tencent.mm.plugin.fingerprint.b.b; import com.tencent.mm.plugin.fingerprint.b.c; import com.tencent.mm.plugin.fingerprint.b.f; import com.tencent.mm.plugin.fingerprint.b.g; import com.tencent.mm.plugin.fingerprint.b.i; import com.tencent.mm.plugin.fingerprint.b.j; import com.tencent.mm.plugin.fingerprint.b.n; import com.tencent.mm.pluginsdk.k; import com.tencent.mm.sdk.platformtools.x; import java.util.HashMap; public class a implements ar { private n jgf = new n(); private i jgg = new i(); private j jgh = new j(); private b jgi = new b(); private f jgj = new f(); private g jgk = new g(); private c jgl; static { com.tencent.mm.wallet_core.a.i("FingerprintAuth", com.tencent.mm.plugin.fingerprint.ui.a.class); } public static a aMW() { return (a) p.v(a.class); } public final HashMap<Integer, d> Ci() { return null; } public final void gi(int i) { } public final void bn(boolean z) { x.i("MicroMsg.SubCoreFingerPrint", "alvinluo SoterWrapperApi isInit: %b in SubCoreFingerprint initTA", new Object[]{Boolean.valueOf(com.tencent.d.b.b.a.cFO().isInit())}); if (com.tencent.d.b.b.a.cFO().isInit()) { aMY(); } else { x.i("MicroMsg.SubCoreFingerPrint", "alvinluo soter is not initialized, do init"); com.tencent.mm.kernel.g.a(k.class, new com.tencent.mm.plugin.fingerprint.b.d()); com.tencent.mm.kernel.g.Em().h(new 1(this), 1500); } com.tencent.mm.sdk.b.a.sFg.b(this.jgf); com.tencent.mm.sdk.b.a.sFg.b(this.jgg); com.tencent.mm.sdk.b.a.sFg.b(this.jgh); com.tencent.mm.sdk.b.a.sFg.b(this.jgi); com.tencent.mm.sdk.b.a.sFg.b(this.jgj); com.tencent.mm.sdk.b.a.sFg.b(this.jgk); } public final void bo(boolean z) { } public final void onAccountRelease() { com.tencent.mm.sdk.b.a.sFg.c(this.jgf); this.jgg.release(); com.tencent.mm.sdk.b.a.sFg.c(this.jgg); com.tencent.mm.sdk.b.a.sFg.c(this.jgh); com.tencent.mm.sdk.b.a.sFg.c(this.jgi); com.tencent.mm.sdk.b.a.sFg.c(this.jgj); if (this.jgl != null) { c.abort(); c.release(); this.jgl = null; } com.tencent.mm.sdk.b.a.sFg.c(this.jgk); } public static c aMX() { com.tencent.mm.kernel.g.Eg().Ds(); if (aMW().jgl == null) { aMW().jgl = new c(); } return aMW().jgl; } private static void aMY() { k kVar; if (com.tencent.d.b.a.cFN()) { kVar = new com.tencent.mm.plugin.fingerprint.b.k(); } else { kVar = new com.tencent.mm.plugin.fingerprint.b.d(); } kVar.aNj(); com.tencent.mm.kernel.g.a(k.class, kVar); } }
package org.luna.board.mapper; import org.luna.board.domain.BoardVO; public interface BoardMapper { //게시글 전체 조회 BoardVO selectAll(BoardVO board); //bno로 게시글 하나 조회 BoardVO selectOne(Integer bno); //게시글 등록 void register(BoardVO board); //게시글 삭제 void remove(Integer bno); //게시글 수정 void modify(BoardVO board); }
package com.eCommerce.eComApp.model; import lombok.Data; import org.springframework.data.mongodb.core.mapping.Document; import java.util.List; @Document("categories") public @Data class Categorie { private String id; private String name; private List<Item> items; private String description; }
package game.app.dtos.response; import java.util.Date; import lombok.Data; @Data public class GameResponse { private String title; private String description; private Date release; private Double price; public GameResponse() { } }
package com.dayuanit.shop.domain; import java.util.Date; public class OrderDetail { private Integer id; private Integer orderId; private Integer goodsId; private String price; private Integer goodsAccount; private String goodsTotalPrice; private String goodsName; private Date createTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } public Integer getGoodsId() { return goodsId; } public void setGoodsId(Integer goodsId) { this.goodsId = goodsId; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Integer getGoodsAccount() { return goodsAccount; } public void setGoodsAccount(Integer goodsAccount) { this.goodsAccount = goodsAccount; } public String getGoodsTotalPrice() { return goodsTotalPrice; } public void setGoodsTotalPrice(String goodsTotalPrice) { this.goodsTotalPrice = goodsTotalPrice; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getGoodsName() { return goodsName; } public void setGoodsName(String goodsName) { this.goodsName = goodsName; } }
package acs.logic; import java.util.List; import acs.boundary.UserBoundary; public interface ExtendedUserService extends UserService{ public List<UserBoundary> getAllUsers(String adminDomain, String adminEmail, int size, int page); }
package com.website.tools.navigation; import com.website.views.WebPages; /** * The session manager.</br> * * @author Jérémy Pansier */ public class SessionManager { /** The user cookie name. */ private static final String USER_KEY = "user"; /** * The private constructor to hide the implicit empty public one. */ private SessionManager() {} /** * Gets the session user name stored in the JSESSIONID cookie.</br> * Redirects to the connection web page if its null. * * @return the session user name or null if there is no session user name stored in the JSESSIONID cookie */ public static String getSessionUserNameOrRedirect() { final String username = getSessionUserName(); if (null == username) { Redirector.redirect(WebPages.CONNECTION.createJsfUrl(), true, "Connexion requise"); return null; } return username; } /** * Gets the session user name stored in the JSESSIONID cookie.</br> * * @return the session user name or null if there is no session user name stored in the JSESSIONID cookie */ public static String getSessionUserName() { final Object attribute = ContextManager.getRequest().getSession().getAttribute(USER_KEY); return attribute == null ? null : attribute.toString(); } /** * Tracks the specified user with a parameter stored in the JSESSIONID cookie.</br> * The cookie will persist in the session until browser shutdown. * * @param username the user name to store */ public static void trackUser(final String username) { ContextManager.getRequest().getSession().setAttribute(USER_KEY, username); } /** * Releases the browser current user.</br> * Invalidates the session and by the way destroy the JSESSIONID cookie. */ public static void releaseUser() { ContextManager.getRequest().getSession().invalidate(); } }
package vista; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; public class Menu2 extends JDialog { private final JPanel contentPanel = new JPanel(); public JButton prov; public JButton emp; public JButton vent; /** * Launch the application. */ public static void main(String[] args) { try { Menu2 dialog = new Menu2(); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } /** * Create the dialog. */ public Menu2() { setBounds(100, 100, 603, 369); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); JButton inv = new JButton("Almacen"); inv.setBounds(26, 64, 180, 101); inv.setHorizontalTextPosition(SwingConstants.CENTER); inv.setVerticalTextPosition(SwingConstants.BOTTOM); ImageIcon inven = new ImageIcon(Menu2.class.getResource("/img/box.png")); ImageIcon iconoI = new ImageIcon(inven.getImage().getScaledInstance(100, 70, Image.SCALE_SMOOTH)); inv.setIcon(iconoI); inv.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { almacenes alm = new almacenes(); alm.setVisible(true); dispose(); } }); contentPanel.setLayout(null); inv.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 19)); contentPanel.add(inv); JButton emp = new JButton("Empleados"); emp.setBounds(217, 64, 180, 101); emp.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 19)); emp.setHorizontalTextPosition(SwingConstants.CENTER); emp.setVerticalTextPosition(SwingConstants.BOTTOM); ImageIcon dd = new ImageIcon(Menu2.class.getResource("/img/usuario.png")); ImageIcon icono2 = new ImageIcon(dd.getImage().getScaledInstance(100, 70, Image.SCALE_SMOOTH)); emp.setIcon(icono2); emp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Empleado emp = new Empleado(); emp.setVisible(true); dispose(); } }); contentPanel.add(emp); JButton prov = new JButton("Proveedores"); prov.setBounds(26, 186, 180, 106); prov.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 19)); prov.setVerticalTextPosition(SwingConstants.BOTTOM); prov.setHorizontalTextPosition(SwingConstants.CENTER); ImageIcon prove = new ImageIcon(Menu2.class.getResource("/img/frontal-truck.png")); ImageIcon iconoP = new ImageIcon(prove.getImage().getScaledInstance(100, 70, Image.SCALE_SMOOTH)); prov.setIcon(iconoP); prov.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Proveedor prov =new Proveedor(); prov.setVisible(true); dispose(); } }); contentPanel.add(prov); JButton vent = new JButton("Ventas"); vent.setBounds(217, 189, 180, 101); vent.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 19)); vent.setVerticalTextPosition(SwingConstants.BOTTOM); vent.setHorizontalTextPosition(SwingConstants.CENTER); ImageIcon venta = new ImageIcon(Menu2.class.getResource("/img/ventas.png")); ImageIcon iconoV = new ImageIcon(venta.getImage().getScaledInstance(100, 70, Image.SCALE_SMOOTH)); vent.setIcon(iconoV); vent.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Ventas venta = new Ventas(); venta.setVisible(true); dispose(); } }); contentPanel.add(vent); JLabel lblNewLabel = new JLabel("Elija una Operacion"); lblNewLabel.setBounds(167, 11, 244, 42); lblNewLabel.setFont(new Font("Goudy Old Style", Font.PLAIN, 29)); contentPanel.add(lblNewLabel); JButton clientes = new JButton("Clientes"); clientes.setBounds(407, 64, 160, 101); clientes.setHorizontalTextPosition(SwingConstants.CENTER); clientes.setVerticalTextPosition(SwingConstants.BOTTOM); clientes.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 19)); ImageIcon cliente = new ImageIcon(Menu2.class.getResource("/img/clientes.png")); ImageIcon iconoC = new ImageIcon(cliente.getImage().getScaledInstance(100, 70, Image.SCALE_SMOOTH)); clientes.setIcon(iconoC); clientes.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Cliente client = new Cliente(); client.setVisible(true); dispose(); } }); contentPanel.add(clientes); JButton btnProduccion = new JButton("Produccion"); btnProduccion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Produccion produc = new Produccion(); produc.setVisible(true); dispose(); } }); btnProduccion.setVerticalTextPosition(SwingConstants.BOTTOM); btnProduccion.setHorizontalTextPosition(SwingConstants.CENTER); btnProduccion.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 19)); ImageIcon produccion = new ImageIcon(Menu2.class.getResource("/img/production.png")); ImageIcon iconoProd = new ImageIcon(cliente.getImage().getScaledInstance(100, 70, Image.SCALE_SMOOTH)); btnProduccion.setBounds(407, 186, 160, 101); btnProduccion.setIcon(iconoProd); contentPanel.add(btnProduccion); } }