text
stringlengths
10
2.72M
package com.flavio.android.petlegal.model; public class LoginCadastro extends Login { private String confirmaSenha; public LoginCadastro(String cpf, String senha, String confirmaSenha) { setCpf(cpf); setSenha(senha); setConfirmaSenha(confirmaSenha); } public String getConfirmaSenha() { return confirmaSenha; } public void setConfirmaSenha(String confirmaSenha) { this.confirmaSenha = confirmaSenha; } }
package example_01.banking; import example_01.Developer; import example_01.ProjectManager; import example_01.ProjectTeamFactory; import example_01.Tester; public class BankingTeamFactory implements ProjectTeamFactory { @Override public Developer getDeveloper() { return new JavaDeveloper(); } @Override public Tester getTester() { return new QATester(); } @Override public ProjectManager getProjectManager() { return new BankingPM(); } }
package sample; import org.apache.ibatis.type.Alias; import cj.oshopping.common.codesupport.component.Code; import cj.oshopping.common.codesupport.mybatis.handler.AbstractCodeTypeHandler; import cj.oshopping.common.codesupport.mybatis.handler.CodeAwareEnumTypeHandler; public abstract class UserStatusTypeHandler { @Alias("UserStatusEnumTypeHandler") public static class EnumTypeHandler extends CodeAwareEnumTypeHandler<UserStatus> { } @Alias("UserStatusCodeTypeHandler") public static class CodeTypeHandler extends AbstractCodeTypeHandler<Code<UserStatus>, UserStatus> { public CodeTypeHandler() { super(UserStatus.class); } } }
package com.driva.drivaapi.controller; import com.driva.drivaapi.mapper.dto.WorkDayDTO; import com.driva.drivaapi.service.WorkDayService; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; @RestController @RequiredArgsConstructor @RequestMapping("api/workdays") public class WorkDayController { private final WorkDayService workdayService; @GetMapping @PreAuthorize("hasRole('ADMIN') or hasRole('MODERATOR')") List<WorkDayDTO> getAllWorkDays() { return workdayService.findAll(); } @GetMapping("/{id}") @PreAuthorize("hasRole('ADMIN') or hasRole('MODERATOR')") WorkDayDTO getWorkDay(@PathVariable Long id) { return workdayService.findToDTO(id); } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("hasRole('ADMIN') or hasRole('MODERATOR')") @ResponseStatus(code = HttpStatus.CREATED) WorkDayDTO createWorkDay(@RequestBody @Valid WorkDayDTO workday) { return workdayService.save(workday); } @PutMapping @PreAuthorize("hasRole('ADMIN') or hasRole('MODERATOR')") @ResponseStatus(code = HttpStatus.OK) WorkDayDTO updateWorkDay(@RequestBody @Valid WorkDayDTO workday) { return workdayService.update(workday); } @DeleteMapping("/{id}") @PreAuthorize("hasRole('ADMIN') or hasRole('MODERATOR')") @ResponseStatus(HttpStatus.NO_CONTENT) void deleteWorkDay(@PathVariable Long id) { workdayService.delete(id); } }
package cmc.vn.ejbca.RA.response; public enum ResponseStatus { DO_SERVICE_SUCCESSFUL(1000, "Success"), UNHANDLED_ERROR(1004, "Unhandled error"), OBJECT_INVALID(1005, "Object invalid"), CALL_HTTP_HAS_ERROR(1006, "The system has error, please try again later"), KEY_CONFIG_NOT_FOUND(1007, "Config Not Found"), JOB_NOT_FOUND(1008, "Job Not Found"), FIXED_DELAY_INVALID(1009, "Job not fixed delay type"), FIXED_TIME_INVALID(1010, "Job not fixed time type"), UNAUTHORIZE(401, "401 Unauthorized") ; public int code; public String message; private String messageFormat; ResponseStatus(int code, String message, String messageFormat) { this.code = code; this.message = message; this.messageFormat = messageFormat; } ResponseStatus(int code, String message) { this.code = code; this.message = message; } public ResponseStatus formatMessage(Object... str) { if (this.messageFormat != null) { this.message = String.format(this.messageFormat, str); } return this; } public ResponseStatus[] getListResponseStatus() { return ResponseStatus.values(); } public int getCode() { return this.code; } public String getMessage() { return message; } public String getMessageFormat() { return messageFormat; } }
package com.spindance.demo.data; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Class for managing list of TodoTasks. They are just stored in memory with no persistence */ public class TodoManager { private static List<TodoTask> mTodoList = new ArrayList<TodoTask>(); public static List<TodoTask> getTodoList() { return Collections.unmodifiableList(mTodoList); } public static void addItem(TodoTask t) { mTodoList.add(t); } public static TodoTask getTask(int id) { for (TodoTask t : mTodoList) { if (t.getId() == id) return t; } return null; } public static void deleteTask(int id) { for (Iterator<TodoTask> iter = mTodoList.iterator(); iter.hasNext(); ) { if (iter.next().getId() == id) { iter.remove();; return; } } } }
package dao; import java.util.List; import javax.transaction.Transactional; import org.springframework.stereotype.Repository; import model.Comentario; @Repository @Transactional public class ComentarioDAO extends GenericDAO<Comentario>{ public List<Comentario> listar(){ String hql = "Select t from classificado t"; return super.manager.createQuery(hql, Comentario.class).getResultList(); } }
package cn.ztuo.bitrade.dao; import cn.ztuo.bitrade.dao.base.BaseDao; import cn.ztuo.bitrade.entity.Member; import cn.ztuo.bitrade.entity.MemberBorrowingReturning; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; /** * @Auther:路道 * @Date:2019/6/18 * @Description:cn.ztuo.bitrade.dao * @version:1.0 */ public interface MemberBorrowingReturningDao extends BaseDao<MemberBorrowingReturning> { /** * 功能描述: 根据用户id查询出会员是否有未归还的借款信息 * @param: * @return: */ @Query(value = "SELECT COUNT(1) FROM member_borrowing_returning WHERE mid=:id AND status=0", nativeQuery = true) int borrowingRecordDetile(@Param("id") Long id); /** * 功能描述: 查看用户的欠款信息 * @param: * @return: */ @Query(value = "SELECT * FROM member_borrowing_returning WHERE mid= :id AND status=0", nativeQuery = true) MemberBorrowingReturning InformationOnArrears(@Param("id") Long id); }
package com.vietstore; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.view.UrlBasedViewResolver; import org.springframework.web.servlet.view.tiles3.TilesConfigurer; import org.springframework.web.servlet.view.tiles3.TilesView; @Configuration public class TilesConfig { @Bean("viewResolver") public ViewResolver getViewResolver() { UrlBasedViewResolver r = new UrlBasedViewResolver(); r.setViewClass(TilesView.class); return r; } @Bean("tilesConfigurer") public TilesConfigurer getTilesConfigurer() { TilesConfigurer t = new TilesConfigurer(); t.setDefinitions("/WEB-INF/tiles.xml"); return t; } }
package com.taimoor.mapstruct.mapper; import com.taimoor.mapstruct.dto.DoctorDto; import com.taimoor.mapstruct.model.Doctor; import com.taimoor.mapstruct.model.DoctorPatientSummary; import com.taimoor.mapstruct.model.Education; import com.taimoor.mapstruct.model.Patient; import org.mapstruct.AfterMapping; import org.mapstruct.BeforeMapping; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingTarget; import java.util.ArrayList; import java.util.stream.Collectors; /** * @author Taimoor Choudhary */ @Mapper(uses = {PatientMapper.class}, componentModel = "spring", imports = {ArrayList.class}) public abstract class DoctorCustomMapper { @BeforeMapping protected void validate(Doctor doctor) { if(doctor.getPatientList() == null){ doctor.setPatientList(new ArrayList<>()); } } @AfterMapping protected void updateResult(@MappingTarget DoctorDto doctorDto) { doctorDto.setName(doctorDto.getName().toUpperCase()); doctorDto.setDegree(doctorDto.getDegree().toUpperCase()); doctorDto.setSpecialization(doctorDto.getSpecialization().toUpperCase()); } @Mapping(source = "doctor.patientList", target = "patientDtoList") @Mapping(source = "doctor.specialty", target = "specialization") public abstract DoctorDto toDoctorDto(Doctor doctor); public DoctorPatientSummary toDoctorPatientSummary(Doctor doctor, Education education){ return DoctorPatientSummary.builder() .doctorId(doctor.getId()) .doctorName(doctor.getName()) .patientCount(doctor.getPatientList().size()) .patientIds(doctor.getPatientList() .stream().map(Patient::getId).collect(Collectors.toList())) .institute(education.getInstitute()) .specialization(education.getDegreeName()) .build(); } }
package org.cethos.tools.ninebatch.tasks; public class ConversionFailureException extends RuntimeException { public ConversionFailureException(Throwable throwable) { super(throwable); } }
package br.com.webstore.model; import javax.persistence.*; import javax.validation.constraints.NotEmpty; /** * Project: api-webstore * @author : Lucas Kanô de Oliveira (lucaskano) * @since : 22/04/2020 */ @Entity @Table(name = "tb_products") public class Product{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotEmpty(message = "Product name is required") private String name; @NotEmpty(message = "Product description is required") @Column(nullable = false) private String description; @NotEmpty(message = "Product price is required") private double price; @NotEmpty(message = "Product weight is required") private double weight; @NotEmpty(message = "Product quantity is required") private int quantity; private String pictureURL; public Product(){ } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getPictureURL() { return pictureURL; } public void setPictureURL(String pictureURL) { this.pictureURL = pictureURL; } public static final class Builder { private String name; private String description; private double price; private double weight; private int quantity; private String pictureURL; private Builder() { } public static Builder aProduct() { return new Builder(); } public Builder name(String name) { this.name = name; return this; } public Builder description(String description) { this.description = description; return this; } public Builder price(double price) { this.price = price; return this; } public Builder weight(double weight) { this.weight = weight; return this; } public Builder quantity(int quantity) { this.quantity = quantity; return this; } public Builder pictureURL(String pictureURL) { this.pictureURL = pictureURL; return this; } public Product build() { Product product = new Product(); product.setName(name); product.setDescription(description); product.setPrice(price); product.setWeight(weight); product.setQuantity(quantity); product.setPictureURL(pictureURL); return product; } } }
/* * Copyright (c) 2013 MercadoLibre -- All rights reserved */ package com.zauberlabs.bigdata.lambdaoa.realtime.bolts; import java.util.Date; import java.util.Map; import java.util.concurrent.Callable; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Tuple; import com.google.common.base.Objects; import com.google.common.collect.HashMultiset; import com.google.common.collect.Maps; import com.google.common.collect.Multiset; import com.zauberlabs.bigdata.lambdaoa.realtime.fragstore.FragStore; import com.zauberlabs.bigdata.lambdaoa.realtime.fragstore.NullFragStore; import com.zauberlabs.bigdata.lambdaoa.realtime.util.DatePartitionedMap; /** * Counter for fragger kills * * * @since 10/05/2013 */ public class FragCountBolt extends BaseRichBolt { /** <code>serialVersionUID</code> */ private static final long serialVersionUID = 1828794992746417016L; private DatePartitionedMap<Multiset<String>> fragsCounters; private OutputCollector collector; private FragStore fragStore; @Override @SuppressWarnings("rawtypes") public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.collector = collector; this.fragsCounters = new DatePartitionedMap<Multiset<String>>(new Callable<Multiset<String>>() { @Override public Multiset<String> call() throws Exception { return HashMultiset.create(); } }); // this.fragStore = new SploutUpdater(new SploutClient("")); setFragStore(new NullFragStore()); } @Override public void execute(Tuple tuple) { final Date timeFrame = new Date(tuple.getLong(tuple.fieldIndex("time_frame"))); if(tuple.getSourceComponent().equals("drop_to_splout_source")) { writeToStoreFrom(timeFrame); } else { final String fragger = tuple.getString(tuple.fieldIndex("fragger")); incrementFraggerForTime(timeFrame, fragger); } collector.ack(tuple); } public final void incrementFraggerForTime(final Date timeFrame, final String fragger) { fragsCounters.get(timeFrame).add(fragger); } public final void writeToStoreFrom(final Date ts) { this.fragsCounters.dropLessThan(ts); final Map<String, Long> counters = Maps.newHashMap(); for (final Multiset<String> multiset : fragsCounters.getTarget().values()) { for (String string : multiset.elementSet()) { final Long base = Objects.firstNonNull(counters.get(string), 0L); counters.put(string, base + multiset.count(string)); } } fragStore.updateFragCount(counters); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { // declarer.declare(new Fields("time_frame", "fragger", "count")); } /** Sets the fragStore. */ public void setFragStore(final FragStore fragStore) { this.fragStore = fragStore; } }
/** * 1000 이하의 소수(prime number)를 열거 * n 의 제곱근 이하의 어떤 소수로도 나누어떨어지지 않으면 n 은 소수라고 판단. * **/ public class DoIt_Q9 { public static void main(String[] args){ int counter = 0; // 곱셈과 나눗셈의 횟수 int ptr = 0; // 찾은 소수의 개수 int[] prime = new int[500]; // 소수를 저장하는 배열 (짝수는 소수가 아니므로 절반인 500) prime[ptr++] = 2; prime[ptr++] = 3; for (int n=5; n <=1000; n += 2){ // 대상은 홀수만 boolean flag = false; // counter 를 계산하기 위해 사용됨. for (int i = 1; prime[i] * prime[i] <= n; i++) { counter += 2; if (n % prime[i] == 0) { // 소수 아님 flag = true; break; } } if (!flag){ prime[ptr++] = n; counter++; } } for (int i=0; i < ptr; i++) { System.out.println(prime[i]); } System.out.println("곱셈과 나눗셈을 수행한 횟수 : " + counter); } }
package com.hjc.java_common_tools; import java.util.Arrays; public class Temp { public static void main(String[] args) { // Number[] numbers = new Integer[10]; // numbers[0] = Long.valueOf(0); // int[] c = { 3, 4, 5 }; System.out.println(c); System.out.println(c.getClass()); System.out.println(Arrays.toString(c)); } }
package kui.eureka_recommend.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kui.eureka_recommend.dao.InterestDao; import kui.eureka_recommend.entity.Interest; @Service public class InterestService { @Autowired private InterestDao interestDao; /** * 插入一条兴趣到数据库 * @param interest * @return */ public boolean insertInterest(Interest interest) { //判断该兴趣是否存在,如果存在则更新那条记录 if(interestDao.findInterestByIdN_no(interest.getId(),interest.getN_no()) != null) { //更新数据库 return interestDao.updateIterestVal(interest)>0; }else { //如果不存在,就向其添加一条记录 return interestDao.insertInterest(interest)>0; } } public List<Integer> findAllUserId() { return interestDao.findAllUserId(); } public boolean insertInterestList(List<Interest> interestList) { // TODO Auto-generated method stub return interestDao.insertInterestList(interestList) > 0; } }
public class Systemos { public static void println(String tekst){ System.out.println(tekst); } public static void println(int tekst){ System.out.println(tekst); } }
package com.sen.myshop.web.ui.interceptor; import com.sen.myshop.web.ui.constant.SystemConstant; import com.sen.myshop.web.ui.dto.TbUser; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @Auther: Sen * @Date: 2019/8/12 18:24 * @Description: */ public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { TbUser user = (TbUser) httpServletRequest.getSession().getAttribute(SystemConstant.LOGIN_USER); //未登录 if (user == null) { return true; } //已登陆 else { httpServletResponse.sendRedirect("/index"); return false; } } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
package com.engeto.example; public class HotelRoom { //když chci vytvořit nový pokoj, co o něm chci vědět //public...modifikátor přístupu = tuto třídu můžu v kódu používat kdekoli int hotelRoomId; String type; boolean hasBalcony; boolean hasView; int pricePerNight; //už Java ví, jaké informace má ukládat o každém pokoji //konstruktor: public HotelRoom (int hotelRoomId, String type, boolean hasBalcony, boolean hasView, int pricePerNight) { //když chci vytvořit pokoj, musím zadat <-) this.hotelRoomId = hotelRoomId; this.type = type; this.hasBalcony = hasBalcony; this.hasView = hasView; this.pricePerNight = pricePerNight; } //vysvětlím, co se s tím pokojem dá dělat - nový řádek - generate - getter and setter public int getHotelRoomId() {//getHotelRoomID = návratový typ = jaký je výsledek volání metody (když v main.java zavolám getHotelRoomID - dostanu číslo) return hotelRoomId; } public void setHotelRoomId(int hotelRoomId) { //set - nastaví hodnotu, ale vracet nic nebude, proto void this.hotelRoomId = hotelRoomId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isHasBalcony() { return hasBalcony; } public void setHasBalcony (boolean hasBalcony) { this.hasBalcony = hasBalcony; } public boolean isHasView() { return hasView; } public void setHasView(boolean hasView) { this.hasView = hasView; } public String getDescription() { return "Hotellroom "+hotelRoomId+": "+type+" "+pricePerNight+" CZK/night"; } }
package com.oriaxx77.javaplay.enums; import com.oriaxx77.javaplay.utility.Print; /** * Enum where the constants have a specific method. * @author BagyuraI */ public enum ConstantSpecifiedMethodEnum { /** * Return with the CLASSPATH JVM environmental setting. */ CLASSPATH { /** * Returns with the CLASSPATH JVM environmental setting. */ @Override String getInfo() { return System.getenv( "CLASSPATH" ); } }, /** * Return with the JVM version. */ VERSION { /** * Returns with the <i>java.version</i>. */ @Override String getInfo() { return System.getProperty( "java.version" ); } }; /** * Get the infor about this enum. * @return Info about this enum. */ abstract String getInfo(); /** * Static entry point of the app. It calls the {@link #getInfo()} * of all specified enum int that class and prints them to the default output. * @param args Command line arguments. They are not used atm. */ public static void main(String[] args) { for ( ConstantSpecifiedMethodEnum e : values() ) { Print.print( e + " - " + e.getInfo() ); } } }
package com.zxt.compplatform.indexgenerate.util; import java.util.HashMap; import java.util.Map; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import com.zxt.compplatform.indexset.entity.ModelPart; public class PageXmlUtil { /** * XML字符串转对象 * * @return */ public static Map xmlToPage(String xml) { XStream stream = new XStream(new DomDriver()); Map map = null; try { stream.alias("map", HashMap.class); stream.alias("key", String.class); stream.alias("model", ModelPart.class); map = (Map) stream.fromXML(xml); } catch (Exception e) { e.printStackTrace(); } return map; } /** * 对象转XML字符串 * * @param userDeskSetVo * @return */ public static String PageToxml(Map map) { XStream stream = new XStream(); try { stream.alias("map", HashMap.class); stream.alias("key", String.class); stream.alias("model", ModelPart.class); return stream.toXML(map); } catch (Exception e) { return ""; } } /** * new XML Format */ /* <map> <entry> <key>divID</key> <model id="0"> <name>jack</name> <role> </student> </entry> <entry> <key>No.1</key> <student id="1"> <name>jack</name> <email>jack@email.com</email> <address>china</address> <birthday birthday="2010-11-22"/> </student> </entry> </map> */ /** * the old XML Format */ /* * <list> <DivUnit> <region></region> <width></width> <height></height> <model> <name></name> <url></url> </model> <list> <DivUnit></DivUnit> </list> //可以有多个DivUnit,DivUnit与model不共存 </DivUnit> <DivUnit></DivUnit> </list> * */ }
package fr.ecole.eni.lokacar.bddHelper; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import fr.ecole.eni.lokacar.contract.GlobalContract; import fr.ecole.eni.lokacar.contract.ModelContract; import fr.ecole.eni.lokacar.contract.SalarieContract; public class SalarieHelper extends SQLiteOpenHelper { public SalarieHelper(Context context) { super(context, GlobalContract.DATABASE_NAME,null,GlobalContract.DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SalarieContract.SALARIES_CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SalarieContract.QUERY_DELETE_TABLE_SALARIES); onCreate(db); } }
package de.drkhannover.tests.api.auth.exceptions; public class AccessViolationException extends Exception { private static final long serialVersionUID = 7347086477709067260L; private String message; public AccessViolationException(String message) { this.message = message; } public String getMessage() { return message; } }
package com.travel.community.travel_demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; public class handler { } //@RestController //@RequestMapping("/book") //public class BookHandler { // @Autowired // private BookRepository bookRepository; // // @GetMapping("/findAll") // public List<Book> findAll(){ // return bookRepository.findAll(); // } //}
package MyServer; import javax.swing.*; import javax.swing.JTextArea; import java.io.*; import java.net.*; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class HWChatClient { private JFrame frame; private JTextArea InputArea; private JTextArea OutArea; private JButton SendButton; private Socket server; static boolean finished = false; public static void main(String[] args) throws IOException { HWChatClient window = new HWChatClient(); window.frame.setVisible(true); } public HWChatClient() throws IOException { initialize(); } private void initialize() throws IOException { server = new Socket("127.0.0.1", 1337); try { PrintWriter toServer = new PrintWriter(server.getOutputStream(), true); frame = new JFrame(); frame.setBounds(100, 100, 520, 480); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); InputArea = new JTextArea(); InputArea.setBounds(0, 0, 504, 270); frame.getContentPane().add(InputArea); OutArea = new JTextArea(); OutArea.setBounds(0, 281, 504, 118); frame.getContentPane().add(OutArea); SendButton = new JButton("Send"); SendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { toServer.println(OutArea.getText()); OutArea.setText(""); } }); SendButton.setBounds(413, 399, 91, 31); frame.getContentPane().add(SendButton); new Receiver(server); } catch (IOException e) { e.printStackTrace(); } } class Receiver implements Runnable { Socket Rserver; Receiver(Socket s){ this.Rserver = s; new Thread(this).start(); } public void run(){ try{ BufferedReader fServer = new BufferedReader(new InputStreamReader(Rserver.getInputStream())); while(!finished){ String inString = fServer.readLine(); InputArea.append("Sever: " + inString + "\n"); } } catch(IOException e){ System.err.println(e.getMessage()); } } } protected void finalize() throws IOException{ server.close(); } }
package br.com.douglastuiuiu.biometricengine.integration.creddefense.dto.request.entity.credit; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; import java.util.List; /** * @author douglas * @since 20/03/2017 */ public class CreditDTO implements Serializable { private static final long serialVersionUID = -9146702859542134482L; @JsonProperty("identifier_code") private String identifierCode; @JsonProperty("document_type") private String documentType = "2"; @JsonProperty("place_id") private String placeId; private String name; @JsonProperty("birth_date") private String birthDate; private String photo; @JsonInclude(JsonInclude.Include.NON_NULL) private List<CreditDocumentDTO> document; public CreditDTO() { } public CreditDTO(String identifierCode, String placeId, String name, String birthDate, String photo, List<CreditDocumentDTO> document) { super(); this.identifierCode = identifierCode; this.placeId = placeId; this.name = name; this.birthDate = birthDate; this.photo = photo; this.document = document; } public String getIdentifierCode() { return identifierCode; } public void setIdentifierCode(String identifierCode) { this.identifierCode = identifierCode; } public String getDocumentType() { return documentType; } public void setDocumentType(String documentType) { this.documentType = documentType; } public String getPlaceId() { return placeId; } public void setPlaceId(String placeId) { this.placeId = placeId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public List<CreditDocumentDTO> getDocument() { return document; } public void setDocument(List<CreditDocumentDTO> document) { this.document = document; } }
package com.bistel.storm.bolt.fdc; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import org.slf4j.Logger; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import com.bistel.configuration.ConfigConstants; import com.bistel.configuration.ConfigurationManager; import com.bistel.dcp.DCPMain; import com.bistel.distributed.MessagePublishLookup; import com.bistel.distributed.ZookeeperHelper; import com.bistel.fdc.FDCMain; import com.bistel.logging.util.LogUtil; import com.bistel.mq.ExchangeInfo; import com.bistel.mq.ExchangeTypeEnum; import com.bistel.mq.MessageInfo; import com.bistel.mq.Messaging; import com.bistel.mq.impl.MessagingImpl; import com.bistel.service.messaging.RabbitMQService; import com.bistel.service.messaging.RoutingHelper; import com.bistel.tracereport.convertor.ServiceMessageConvertor; import com.bistel.tracereport.model.TraceReportInfo; import com.bistel.util.CompressionUtils; import com.bistel.util.ObjectConvertorUtils; /** * The Bolt to receive stream from DCP module and further perform validation and fault detection. * It will also emit the stepId, toolId and ModuleVO objects for EsperBolt for real time analysis. * */ public class FDCBolt extends BaseRichBolt { private static final long serialVersionUID = -6992750940044800431L; private static Logger _logger = LogUtil.getLogger(FDCBolt.class); OutputCollector _collector; ConfigurationManager cm = null; private static Messaging messaging = new MessagingImpl(); private static ExchangeInfo exchange = new ExchangeInfo(); private RabbitMQService mqService=null; static Map<String,String> queueDetails = new HashMap<String,String>(); static { ZookeeperHelper.init(); exchange.setName("REALTIME_ANALYTICS"); exchange.setType(ExchangeTypeEnum.TOPIC); } /* (non-Javadoc) * @see backtype.storm.task.IBolt#prepare(java.util.Map, backtype.storm.task.TopologyContext, backtype.storm.task.OutputCollector) */ @Override public void prepare(Map conf, TopologyContext context, OutputCollector collector) { if (_logger.isDebugEnabled()) { _logger.debug("Enter prepare"); } _collector = collector; cm = ConfigurationManager.getInstance(ConfigConstants.DEFAULT_RESOURCE_NAME); // Get the instanvce of RabbitMQService mqService = RabbitMQService.getInstance(cm.getConfiguration("rabbitmq.exchange")); } /* (non-Javadoc) * @see backtype.storm.task.IBolt#execute(backtype.storm.tuple.Tuple) */ @Override public void execute(Tuple tuple) { Long previousStepEmitTime = tuple.getLong(3); if(_logger.isWarnEnabled() && (System.currentTimeMillis() - previousStepEmitTime) > 5) { _logger.warn("FDCBolt time difference in receiving the event:" + (System.currentTimeMillis() - previousStepEmitTime)); } TraceReportInfo traceReportInfo = getTraceReportInfo(tuple); // Process for FDC if(null != traceReportInfo){ if(traceReportInfo.getToolTraceInfo().getModules().values().size() > 0) { processFDC(traceReportInfo, tuple); } } _collector.ack(tuple); } private TraceReportInfo getTraceReportInfo(Tuple tuple) { byte[] tracesummaryBytes= (byte[])tuple.getValue(2); TraceReportInfo traceReportInfo = null; try { traceReportInfo = (TraceReportInfo) ObjectConvertorUtils.toObject(CompressionUtils.decompress(tracesummaryBytes)); } catch (IOException e) { _logger.error("Error while deserialising object", e); } catch (ClassNotFoundException e) { _logger.error("Error while deserialising object", e); } catch (DataFormatException e) { _logger.error("Error while deserialising object", e); } return traceReportInfo; } private void processFDC(TraceReportInfo tracereport, Tuple tuple) { long startTime = System.currentTimeMillis(); String stepId=tracereport.getToolTraceInfo().getStep(); String toolId=tracereport.getToolTraceInfo().getTool(); // Execute FDC FDCMain.execute(tracereport); if( _logger.isWarnEnabled() && (System.currentTimeMillis() - startTime) > 10 ) { _logger.warn("Time taken in FDCBOlt Process: "+ (System.currentTimeMillis() - startTime)); } // Push the trace report to Queue for persistence and summarisation pushTraceDataToQueue(tracereport); long startMessagePushTime = System.currentTimeMillis(); List<String> keyList = MessagePublishLookup.getKey(stepId+":"+toolId); if(_logger.isDebugEnabled()) _logger.debug("keyList: "+keyList); if(keyList!=null && keyList.size()>0) { StringBuffer sb = new StringBuffer(); StringBuffer routing = new StringBuffer(); int counter = 0; for(String key:keyList) { try { String moduleId = key.split(":")[2]; String paramId = key.split(":")[3]; String lotId = tracereport.getToolTraceInfo().getModules().get(moduleId).getLotId(); String substrateId = tracereport.getToolTraceInfo().getModules().get(moduleId).getSubstrateId(); String paramName = tracereport.getToolTraceInfo().getModules().get(moduleId).getParameter().getItems().get(paramId).getName(); double value = tracereport.getToolTraceInfo().getModules().get(moduleId).getParameter().getItems().get(paramId).getValue(); if(counter==0) { routing.append(stepId+":"+toolId+":"+moduleId); } else { sb.append("|"); } sb.append(paramName+","+value+","+new java.util.Date().getTime()+","+lotId+","+substrateId); counter++; } catch(Exception ex) { _logger.error("error in FDCBolt while realtime processing",ex); } } try { MessageInfo message = new MessageInfo(sb.toString(), routing.toString()); if(_logger.isDebugEnabled()) { _logger.debug("going to publish message in queue for "+routing.toString()); _logger.debug("going to publish message "+sb.toString()); } messaging.publishMessage(exchange, message); } catch(Exception ex) { _logger.error("error while publishing RA event", ex); } } long endMessagePushTime = System.currentTimeMillis(); if( _logger.isWarnEnabled() && (endMessagePushTime - startMessagePushTime) > 20 ) { _logger.warn("Time taken in FDCBOlt for RealTime Push: "+ (endMessagePushTime - startMessagePushTime)); } } /* (non-Javadoc) * @see backtype.storm.topology.IComponent#declareOutputFields(backtype.storm.topology.OutputFieldsDeclarer) */ @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("stepId", "toolId", "tracereport", "emitTime")); //declarer.declareStream("persist",new Fields("tracereport")); } /** * Push the given traceReport to the RabbitMQ. * * @param traceReport */ private void pushTraceDataToQueue(TraceReportInfo traceReport) { try { long startMessagePushTime = System.currentTimeMillis(); mqService.write(CompressionUtils.compressObject(traceReport), RoutingHelper.getRoutingKey(traceReport.getToolTraceInfo().getStep(),traceReport.getToolTraceInfo().getTool())); if( _logger.isWarnEnabled() && (System.currentTimeMillis() - startMessagePushTime) > 10 ) { _logger.warn("Time taken in FDCBOlt Push Trace Report to Queue: "+ (System.currentTimeMillis() - startMessagePushTime)); } } catch (IOException ie) { _logger.error("Exception while pushing objects to Queue ", ie); } } }
package org.zhq.box; import org.zhq.core.ReceivePacket; import java.io.ByteArrayOutputStream; public abstract class AbsByteArrayReceivePacket<Entity> extends ReceivePacket<ByteArrayOutputStream,Entity> { public AbsByteArrayReceivePacket(long len) { super(len); } @Override protected ByteArrayOutputStream createStream() { return new ByteArrayOutputStream((int) length()); } }
package patterns.behavioral.interpreter; import java.math.BigDecimal; public class SubtractExpression extends Expression { private Expression left; private Expression right; public SubtractExpression(Expression left, Expression right) { this.left = left; this.right = right; } @Override public BigDecimal interpret(Context context) { return left.interpret(context).subtract(right.interpret(context)); } }
package com.corejava.stringhandling; import java.util.Scanner; public class ReplaceCharInString { public static void main(String[] args) { Scanner scan=new Scanner(System.in); System.out.println("Enter String"); String name= scan.nextLine(); char match='s'; //char a[]=name.toCharArray(); int count=0; String b = ""; for(int i=1;i<name.length();i++) { if(name.charAt(i)==match) { count++; //2 b=b+name.substring(0,i)+count; System.out.println("b:"+b); name=name.substring(i+1); System.out.println("name:"+name); System.out.println(b); } } } } /* for(int i=0;i<a.length;i++) { if(a[i]==match) { count++; a[i]= (char) count; }} for(int i1=0;i1<a.length;i1++) { System.out.print(a[i1]); }*/ /* System.out.println(a.toString());*/
package heylichen.leetcode; /** * problem description :https://blog.csdn.net/Jas000/article/details/117399858 * leetcode no: 25 * 本题的目标非常清晰易懂,不涉及复杂的算法,但是实现过程中需要考虑的细节比较多,容易写出冗长的代码。主要考查面试者设计的能力。 * * @param <T> */ public class KReverseLinkedList<T> { private Node<T> newHead; private Node<T> previousKTail; private Node<T> kHead; private Node<T> kTail; public Node<T> kReverse(Node<T> root, int k) { if (k == 0) { return root; } Node<T> current = root; int kSize = 0; while (current != null) { if (kHead == null) { kHead = kTail = current; kSize++; Node<T> next = current.getNext(); current.setNext(null); current = next; } else if (kSize < k) { Node<T> next = current.getNext(); current.setNext(kHead); kHead = current; current = next; kSize++; } else if (kSize == k) { if (newHead == null) { newHead = kHead; } if (previousKTail != null) { previousKTail.setNext(kHead); } previousKTail = kTail; kHead = null; kTail = null; kSize = 0; } else { System.err.println("error"); } } kTail.setNext(null); if (kSize < k) { //count of last list < k, reverse again, to original order current = kHead; kHead = null; while (current != null) { Node<T> next = current.getNext(); if (kHead == null) { kHead = current; current.setNext(null); current = next; continue; } current.setNext(kHead); kHead = current; current = next; } } if (previousKTail == null) { newHead = kHead; } else { previousKTail.setNext(kHead); } return newHead; } }
package com.itheima.service; import com.itheima.entity.PageResult; import com.itheima.entity.QueryPageBean; import com.itheima.pojo.Menu; import java.util.LinkedHashSet; import java.util.List; public interface MenuService { PageResult findPage(QueryPageBean queryPageBean); void add(Menu menu); Menu findById(int id); void update(Menu menu); void delete(int id); LinkedHashSet<Menu> getMenuByRoleId(int id); /** * 获取所有菜单信息 * @return */ List<Menu> findAll(); }
package com.chinaso.behavior.entity; import java.io.Serializable; import java.util.List; /** * @author fangqian * @date 2018/8/25 10:30 */ public class Behavior implements Serializable { private static final long serialVersionUID = 1L; //行为id private int behaviorId; //行为名称 private String name; //一周行为分数 private List<BehaviorScore> behaviorScores; //创建时间 private String createtime; //更新时间 private String updatetime; public int getBehaviorId() { return behaviorId; } public void setBehaviorId(int behaviorId) { this.behaviorId = behaviorId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<BehaviorScore> getBehaviorScores() { return behaviorScores; } public void setBehaviorScores(List<BehaviorScore> behaviorScores) { this.behaviorScores = behaviorScores; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public String getUpdatetime() { return updatetime; } public void setUpdatetime(String updatetime) { this.updatetime = updatetime; } }
package com.zevzikovas.aivaras.terraria.activities.both; import android.content.Intent; import android.os.Bundle; import android.app.Activity; import android.view.View; import com.zevzikovas.aivaras.terraria.R; import com.zevzikovas.aivaras.terraria.activities.BowsActivity; import com.zevzikovas.aivaras.terraria.activities.BowsActivity; import com.zevzikovas.aivaras.terraria.activities.HBowsActivity; public class BothBowsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_both_bows); } public void BowsList (View view) { Intent intent = new Intent(getApplicationContext(), BowsActivity.class); startActivity(intent); } public void HBowsList (View view) { Intent intent = new Intent(getApplicationContext(), HBowsActivity.class); startActivity(intent); } }
import java.util.ArrayList; import java.util.List; public class PathNotFoundException extends Exception { private List<PathNode> closestPath = new ArrayList<PathNode>(); public PathNotFoundException() { super(); } public PathNotFoundException(List<PathNode> closestPath) { super(); this.closestPath = closestPath; } public List<PathNode> getClosestPath() { return closestPath; } }
package com.studygoal.jisc.Fragments; import android.app.Dialog; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.NumberPicker; import android.widget.TextView; import com.activeandroid.query.Select; import com.bumptech.glide.Glide; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.components.Description; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import com.studygoal.jisc.Adapters.GenericAdapter; import com.studygoal.jisc.Managers.DataManager; import com.studygoal.jisc.Managers.LinguisticManager; import com.studygoal.jisc.Managers.NetworkManager; import com.studygoal.jisc.Managers.SocialManager; import com.studygoal.jisc.Models.ActivityHistory; import com.studygoal.jisc.Models.Module; import com.studygoal.jisc.Models.StretchTarget; import com.studygoal.jisc.Models.Targets; import com.studygoal.jisc.R; import com.studygoal.jisc.Utils.Utils; //import com.studygoal.jisc.Utils.YFormatter; //import com.studygoal.jisc.Utils.YFormatterPercent; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; public class TargetItem extends Fragment { View mainView; public Targets target; public TargetDetails reference; public int position; PieChart mChart; LineChart lineChart; int neccesary_time; int spent_time; boolean piChart; TextView incomplete_textView; List<ActivityHistory> activityHistoryList; StretchTarget stretch_target; View.OnClickListener set_stretch_target; public TargetItem() { } public void showDialog() { final Dialog dialog = new Dialog(DataManager.getInstance().mainActivity); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.custom_spinner_layout); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); if(DataManager.getInstance().mainActivity.isLandscape) { DisplayMetrics displaymetrics = new DisplayMetrics(); DataManager.getInstance().mainActivity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int width = (int) (displaymetrics.widthPixels * 0.3); WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); params.width = width; dialog.getWindow().setAttributes(params); } ((TextView) dialog.findViewById(R.id.dialog_title)).setTypeface(DataManager.getInstance().oratorstd_typeface); ((TextView) dialog.findViewById(R.id.dialog_title)).setText(R.string.add); ArrayList<String> items = new ArrayList<>(); // items.add("Last 24 hours"); items.add(getString(R.string.report_activity)); items.add(getString(R.string.log_recent_activity)); final ListView listView = (ListView) dialog.findViewById(R.id.dialog_listview); listView.setAdapter(new GenericAdapter(DataManager.getInstance().mainActivity, "", items)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == 0) { DataManager.getInstance().fromTargetItem = true; DataManager.getInstance().mainActivity.getSupportFragmentManager().beginTransaction() .replace(R.id.main_fragment, new LogNewActivity(), "newActivity") .addToBackStack(null) .commit(); } else { DataManager.getInstance().fromTargetItem = true; LogLogActivity fragment = new LogLogActivity(); fragment.isInEditMode = false; DataManager.getInstance().mainActivity.getSupportFragmentManager().beginTransaction() .replace(R.id.main_fragment, fragment) .addToBackStack(null) .commit(); } dialog.dismiss(); } }); dialog.show(); } @Override public void onResume() { super.onResume(); DataManager.getInstance().mainActivity.setTitle(DataManager.getInstance().mainActivity.getString(R.string.target_title)); DataManager.getInstance().mainActivity.hideAllButtons(); DataManager.getInstance().mainActivity.showCertainButtons(4); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView = inflater.inflate(R.layout.target_item, container, false); mainView.findViewById(R.id.main_all_content).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { return false; } }); Module module = new Select().from(Module.class).where("module_id = ?", target.module_id).executeSingle(); TextView textView = (TextView) mainView.findViewById(R.id.target_item_text); textView.setTypeface(DataManager.getInstance().myriadpro_regular); piChart = true; Calendar c = Calendar.getInstance(); stretch_target = new Select().from(StretchTarget.class).where("target_id = ?", target.target_id).executeSingle(); try { Glide.with(DataManager.getInstance().mainActivity).load(LinguisticManager.getInstance().images.get(target.activity)).into((ImageView) mainView.findViewById(R.id.activity_icon)); } catch (Exception ignored) {} if(module != null) { activityHistoryList = new Select().from(ActivityHistory.class).where("module_id = ?", target.module_id).and("activity = ?", target.activity).execute(); } else { activityHistoryList = new Select().from(ActivityHistory.class).where("activity = ?", target.activity).execute(); } set_stretch_target = new View.OnClickListener() { @Override public void onClick(View v) { final Dialog dialog = new Dialog(DataManager.getInstance().mainActivity); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.stretchtarget_layout); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); if(DataManager.getInstance().mainActivity.isLandscape) { DisplayMetrics displaymetrics = new DisplayMetrics(); DataManager.getInstance().mainActivity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int width = (int) (displaymetrics.widthPixels * 0.3); WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); params.width = width; dialog.getWindow().setAttributes(params); } final NumberPicker hourPicker = (NumberPicker)dialog.findViewById(R.id.hour_picker); hourPicker.setMinValue(0); hourPicker.setMaxValue(10); hourPicker.setFormatter(new NumberPicker.Formatter() { @Override public String format(int value) { if (value < 10) return "0" + value; else return value + ""; } }); final NumberPicker minutePicker = (NumberPicker)dialog.findViewById(R.id.minute_picker); minutePicker.setMinValue(0); minutePicker.setMaxValue(59); minutePicker.setFormatter(new NumberPicker.Formatter() { @Override public String format(int value) { if (value < 10) return "0" + value; else return value + ""; } }); ((TextView)dialog.findViewById(R.id.timespent_save_text)).setTypeface(DataManager.getInstance().myriadpro_regular); dialog.findViewById(R.id.set_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String time = hourPicker.getValue() * 60 + minutePicker.getValue() + ""; final HashMap<String, String> map = new HashMap<>(); map.put("target_id", target.target_id); map.put("stretch_time", time); new Thread(new Runnable() { @Override public void run() { DataManager.getInstance().mainActivity.runOnUiThread(new Runnable() { @Override public void run() { DataManager.getInstance().mainActivity.showProgressBar(""); } }); if(NetworkManager.getInstance().addStretchTarget(map)) { DataManager.getInstance().mainActivity.runOnUiThread(new Runnable() { @Override public void run() { DataManager.getInstance().mainActivity.hideProgressBar(); Snackbar.make(mainView.findViewById(R.id.container), R.string.successfully_set_stretch_target, Snackbar.LENGTH_LONG).show(); mainView.findViewById(R.id.target_set_stretch_btn).setVisibility(View.GONE); // ((TextView)mainView.findViewById(R.id.target_stretch_btn_text)).setText("Edit Stretch Target"); NetworkManager.getInstance().getStretchTargets(DataManager.getInstance().user.id); // mainView.findViewById(R.id.target_set_stretch_btn).setOnClickListener(edit_stretch_target); PieChart mChart2 = (PieChart) mainView.findViewById(R.id.piechart2); mChart2.setDescription(new Description()); mChart2.setTouchEnabled(false); // radius of the center hole in percent of maximum radius mChart2.setHoleRadius(70f); mChart2.setTransparentCircleRadius(85f); mChart2.setDrawSliceText(false); mChart2.setUsePercentValues(true); Legend l2 = mChart2.getLegend(); l2.setEnabled(false); mChart2.setData(generatePieData2()); mChart2.invalidate(); dialog.dismiss(); } }); } else { DataManager.getInstance().mainActivity.runOnUiThread(new Runnable() { @Override public void run() { DataManager.getInstance().mainActivity.hideProgressBar(); Snackbar.make(mainView.findViewById(R.id.container), R.string.something_went_wrong, Snackbar.LENGTH_LONG).show(); dialog.dismiss(); } }); } } }).start(); } }); ((TextView)dialog.findViewById(R.id.dialog_title)).setTypeface(DataManager.getInstance().oratorstd_typeface); dialog.show(); } }; String current_date = c.get(Calendar.YEAR) + "-"; current_date += (c.get(Calendar.MONTH)+1)<10 ? "0" + (c.get(Calendar.MONTH)+1) + "-" : (c.get(Calendar.MONTH)+1) + "-"; current_date += c.get(Calendar.DAY_OF_MONTH)<10 ? "0" + c.get(Calendar.DAY_OF_MONTH) + " " : c.get(Calendar.DAY_OF_MONTH) + " "; current_date += c.get(Calendar.HOUR_OF_DAY)<10 ? "0" + c.get(Calendar.HOUR_OF_DAY) + ":" : c.get(Calendar.HOUR_OF_DAY) + ":"; current_date += c.get(Calendar.MINUTE)<10? "0" + c.get(Calendar.MINUTE) + ":" : c.get(Calendar.MINUTE) + ":"; current_date += c.get(Calendar.SECOND)<10? "0" + c.get(Calendar.SECOND) : c.get(Calendar.SECOND); switch (target.time_span.toLowerCase()) { case "daily": { String time = current_date.split(" ")[0]; List<ActivityHistory> tmp = new ArrayList<>(); for(int i = 0; i < activityHistoryList.size(); i++) { if(time.equals(activityHistoryList.get(i).created_date.split(" ")[0])) tmp.add(activityHistoryList.get(i)); } activityHistoryList.clear(); activityHistoryList.addAll(tmp); break; } case "weekly": { List<ActivityHistory> tmp = new ArrayList<>(); for(int i = 0; i < activityHistoryList.size(); i++) { if(Utils.isInSameWeek(activityHistoryList.get(i).created_date.split(" ")[0])) tmp.add(activityHistoryList.get(i)); } activityHistoryList.clear(); activityHistoryList.addAll(tmp); break; } case "monthly": { String time = current_date.split(" ")[0].split("-")[0] + "-" + current_date.split(" ")[0].split("-")[1]; List<ActivityHistory> tmp = new ArrayList<>(); for(int i = 0; i < activityHistoryList.size(); i++) { if(time.equals(activityHistoryList.get(i).created_date.split(" ")[0].split("-")[0] + "-" + activityHistoryList.get(i).created_date.split(" ")[0].split("-")[1])) tmp.add(activityHistoryList.get(i)); } activityHistoryList.clear(); activityHistoryList.addAll(tmp); break; } } neccesary_time = Integer.parseInt(target.total_time); spent_time = 0; for(int i=0; i < activityHistoryList.size(); i++) { spent_time += Integer.parseInt(activityHistoryList.get(i).time_spent); } if(spent_time == 0) mainView.findViewById(R.id.colorbar).setBackgroundColor(0xFFFF0000); else if(spent_time >= neccesary_time) mainView.findViewById(R.id.colorbar).setBackgroundColor(0xFF00FF00); else mainView.findViewById(R.id.colorbar).setBackgroundColor(0xFFff7400); if(spent_time == 0 || spent_time < neccesary_time) { incomplete_textView = (TextView) mainView.findViewById(R.id.target_item_incomplete_textview); incomplete_textView.setVisibility(View.VISIBLE); incomplete_textView.setTypeface(DataManager.getInstance().myriadpro_regular); incomplete_textView.setText(Utils.convertToHour(spent_time) + "/" + Utils.convertToHour(neccesary_time)); if(spent_time == 0) { View set_stretch = mainView.findViewById(R.id.target_set_stretch_btn); set_stretch.setVisibility(View.VISIBLE); ((TextView)mainView.findViewById(R.id.target_stretch_btn_text)).setText(DataManager.getInstance().mainActivity.getString(R.string.start_your_new_activity)); set_stretch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // LogNewActivity fragment = new LogNewActivity(); // DataManager.getInstance().fromTargetItem = true; // DataManager.getInstance().mainActivity.getSupportFragmentManager().beginTransaction() // .replace(R.id.main_fragment, fragment) // .addToBackStack(null) // .commit(); showDialog(); } }); } // if(stretch_target != null) { // //TODO: Edit Stretch target // View set_stretch = mainView.findViewById(R.id.target_set_stretch_btn); // set_stretch.setVisibility(View.VISIBLE); // ((TextView)mainView.findViewById(R.id.target_stretch_btn_text)).setText("Edit Stretch Target"); // set_stretch.setOnClickListener(edit_stretch_target); // // } // else { // //SET STRETCH TARGET // View set_stretch = mainView.findViewById(R.id.target_set_stretch_btn); // set_stretch.setVisibility(View.VISIBLE); // ((TextView)mainView.findViewById(R.id.target_stretch_btn_text)).setText("Set Stretch Target"); // ((TextView)mainView.findViewById(R.id.target_stretch_btn_text)).setTypeface(DataManager.getInstance().myriadpro_regular); // set_stretch.setOnClickListener(set_stretch_target); // } } else { TextView complete_textView = (TextView) mainView.findViewById(R.id.target_item_complete_textview); complete_textView.setVisibility(View.VISIBLE); complete_textView.setTypeface(DataManager.getInstance().myriadpro_regular); complete_textView.setText(Utils.convertToHour(neccesary_time) + "/" + Utils.convertToHour(neccesary_time)); if(stretch_target != null) { PieChart mChart2 = (PieChart) mainView.findViewById(R.id.piechart2); mChart2.setDescription(new Description()); mChart2.setTouchEnabled(false); // radius of the center hole in percent of maximum radius mChart2.setHoleRadius(70f); mChart2.setTransparentCircleRadius(85f); mChart2.setDrawSliceText(false); mChart2.setUsePercentValues(true); Legend l2 = mChart2.getLegend(); l2.setEnabled(false); mChart2.setData(generatePieData2()); if (spent_time < neccesary_time + Integer.parseInt(stretch_target.stretch_time)) { int time = neccesary_time + Integer.parseInt(stretch_target.stretch_time) - spent_time; TextView textView1 = (TextView) mainView.findViewById(R.id.target_reached_stretch_present); String text = LinguisticManager.getInstance().present.get(target.activity); if (text.contains(DataManager.getInstance().mainActivity.getString(R.string._for))) { text += " " + DataManager.getInstance().mainActivity.getString(R.string.another) + " "; } else { text += " " + DataManager.getInstance().mainActivity.getString(R.string.for_text) + " " + DataManager.getInstance().mainActivity.getString(R.string.another) + " "; } int hour = time / 60; int minute = time % 60; text += (hour == 1) ? "1" + " " + DataManager.getInstance().mainActivity.getString(R.string.hour) + " " : hour + " " + DataManager.getInstance().mainActivity.getString(R.string.hours) + " "; if (minute > 0) text += ((minute == 1) ? DataManager.getInstance().mainActivity.getString(R.string.and) + " 1" + " " + DataManager.getInstance().mainActivity.getString(R.string.minute) + " " : DataManager.getInstance().mainActivity.getString(R.string.and) + " " + minute + " " + DataManager.getInstance().mainActivity.getString(R.string.minutes) + " "); text += " " + DataManager.getInstance().mainActivity.getString(R.string.this_text) + " " + target.time_span.substring(0, target.time_span.length() - 2).toLowerCase() + " " + DataManager.getInstance().mainActivity.getString(R.string.to_meet_stretch_target); textView1.setText(text); textView1.setVisibility(View.VISIBLE); } } else { if(canStretchTarget()) { View set_stretch = mainView.findViewById(R.id.target_set_stretch_btn); set_stretch.setVisibility(View.VISIBLE); ((TextView) mainView.findViewById(R.id.target_stretch_btn_text)).setText(DataManager.getInstance().mainActivity.getString(R.string.set_stretch_target)); ((TextView) mainView.findViewById(R.id.target_stretch_btn_text)).setTypeface(DataManager.getInstance().myriadpro_regular); set_stretch.setOnClickListener(set_stretch_target); } } mainView.findViewById(R.id.target_item_complete_imageview).setVisibility(View.VISIBLE); mainView.findViewById(R.id.target_reached_layout).setVisibility(View.VISIBLE); } String text = ""; text += LinguisticManager.getInstance().present.get(target.activity) + " "; int hour = Integer.parseInt(target.total_time) / 60; int minute = Integer.parseInt(target.total_time) % 60; text += (hour == 1) ? "1 " + DataManager.getInstance().mainActivity.getString(R.string.hour) + " " : hour + " " + DataManager.getInstance().mainActivity.getString(R.string.hours) + " "; if(minute > 0) text += ((minute == 1) ? " " + DataManager.getInstance().mainActivity.getString(R.string.and) + " 1 " + DataManager.getInstance().mainActivity.getString(R.string.minute) + " " : " " + DataManager.getInstance().mainActivity.getString(R.string.and) + " " + minute + " " + DataManager.getInstance().mainActivity.getString(R.string.minutes) + " "); text += target.time_span.toLowerCase(); text += module == null ? "" : " " + DataManager.getInstance().mainActivity.getString(R.string.for_text) + " " + module.name; textView.setText(text); final String finalText = text; mainView.findViewById(R.id.target_reached_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SocialManager.getInstance().shareOnIntent(getActivity().getString(R.string.target_reached_2) + " " + finalText); } }); final com.daimajia.swipe.SwipeLayout swipeLayout = (com.daimajia.swipe.SwipeLayout) mainView.findViewById(R.id.swipelayout); mainView.findViewById(R.id.edit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { swipeLayout.close(true); AddTarget fragment = new AddTarget(); fragment.isInEditMode = true; fragment.item = target; DataManager.getInstance().mainActivity.getSupportFragmentManager().beginTransaction() .replace(R.id.main_fragment, fragment) .addToBackStack(null) .commit(); } }); mainView.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Dialog dialog = new Dialog(DataManager.getInstance().mainActivity); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.confirmation_dialog); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); if(DataManager.getInstance().mainActivity.isLandscape) { DisplayMetrics displaymetrics = new DisplayMetrics(); DataManager.getInstance().mainActivity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int width = (int) (displaymetrics.widthPixels * 0.45); WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); params.width = width; dialog.getWindow().setAttributes(params); } ((TextView) dialog.findViewById(R.id.dialog_title)).setTypeface(DataManager.getInstance().oratorstd_typeface); ((TextView) dialog.findViewById(R.id.dialog_title)).setText(R.string.confirmation); ((TextView) dialog.findViewById(R.id.dialog_message)).setTypeface(DataManager.getInstance().myriadpro_regular); ((TextView) dialog.findViewById(R.id.dialog_message)).setText(R.string.confirm_delete_message); ((TextView) dialog.findViewById(R.id.dialog_no_text)).setTypeface(DataManager.getInstance().myriadpro_regular); ((TextView) dialog.findViewById(R.id.dialog_no_text)).setText(R.string.no); ((TextView) dialog.findViewById(R.id.dialog_ok_text)).setTypeface(DataManager.getInstance().myriadpro_regular); ((TextView) dialog.findViewById(R.id.dialog_ok_text)).setText(R.string.yes); dialog.findViewById(R.id.dialog_ok).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); swipeLayout.close(true); reference.deleteTarget(target, position); } }); dialog.findViewById(R.id.dialog_no).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } }); //PIE Chart Data mChart = (PieChart) mainView.findViewById(R.id.piechart); mChart.setDescription(new Description()); mChart.setTouchEnabled(false); // radius of the center hole in percent of maximum radius mChart.setHoleRadius(70f); mChart.setTransparentCircleRadius(65f); mChart.setDrawSliceText(false); mChart.setUsePercentValues(true); Legend l = mChart.getLegend(); l.setEnabled(false); mChart.setData(generatePieData()); // --- // LINE Chart Data lineChart = (LineChart) mainView.findViewById(R.id.chart1); // lineChart.setViewPortOffsets(0, 20, 0, 0); // lineChart.setBackgroundColor(Color.rgb(104, 241, 175)); // no description text lineChart.setDescription(new Description()); // enable touch gestures lineChart.setTouchEnabled(false); // enable scaling and dragging lineChart.setDragEnabled(false); lineChart.setScaleEnabled(false); // if disabled, scaling can be done on x- and y-axis separately lineChart.setPinchZoom(false); lineChart.setDrawGridBackground(false); YAxis y = lineChart.getAxisLeft(); y.setTypeface(DataManager.getInstance().myriadpro_regular); if(target.time_span.toLowerCase().equals(getString(R.string.daily).toLowerCase())) { // y.setValueFormatter(new YFormatterPercent()); y.setAxisMaxValue(100); } else if(target.time_span.toLowerCase().equals(getString(R.string.Weekly).toLowerCase())) { // y.setValueFormatter(new YFormatter(2)); } else if(target.time_span.toLowerCase().equals(getString(R.string.monthly).toLowerCase())) { // y.setValueFormatter(new YFormatter(2)); } y.setAxisMinValue(0); y.setStartAtZero(true); y.setTextColor(Color.BLACK); y.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART); y.setDrawGridLines(true); y.setAxisLineColor(Color.BLACK); XAxis x = lineChart.getXAxis(); x.setTypeface(DataManager.getInstance().myriadpro_regular); x.setTextColor(Color.BLACK); x.setPosition(XAxis.XAxisPosition.BOTTOM); x.setDrawGridLines(false); x.setAxisLineColor(Color.BLACK); lineChart.getAxisRight().setEnabled(false); // add data setData(); lineChart.getLegend().setEnabled(false); // lineChart.animateXY(2000, 2000); // dont forget to refresh the drawing lineChart.invalidate(); //----- // final ImageView toggle = (ImageView) mainView.findViewById(R.id.graph_toggle); // toggle.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if(piChart) { // mainView.findViewById(R.id.linechart_rl).setVisibility(View.VISIBLE); // mainView.findViewById(R.id.piechart).setVisibility(View.INVISIBLE); // mainView.findViewById(R.id.piechart_aux).setVisibility(View.INVISIBLE); // // piChart = false; // Picasso.with(DataManager.getInstance().mainActivity).load(R.drawable.graphicon_2).into(toggle); // } // else { // mainView.findViewById(R.id.linechart_rl).setVisibility(View.INVISIBLE); // mainView.findViewById(R.id.piechart).setVisibility(View.VISIBLE); // mainView.findViewById(R.id.piechart_aux).setVisibility(View.VISIBLE); // // piChart = true; // Picasso.with(DataManager.getInstance().mainActivity).load(R.drawable.graphicon_1).into(toggle); // } // } // }); return mainView; } private boolean canStretchTarget() { boolean eligible = false; if(target.time_span.toLowerCase().equals(getString(R.string.daily).toLowerCase())) { } else if(target.time_span.toLowerCase().equals(getString(R.string.Weekly).toLowerCase())) { Calendar c = Calendar.getInstance(); if(c.get(Calendar.DAY_OF_WEEK) <= Calendar.FRIDAY) eligible = true; } else if(target.time_span.toLowerCase().equals(getString(R.string.monthly).toLowerCase())) { Calendar c = Calendar.getInstance(); if(c.getActualMaximum(Calendar.DAY_OF_MONTH) - c.get(Calendar.DAY_OF_MONTH) > 4) eligible = true; } return eligible; } private void setData() { ArrayList<String> xVals = new ArrayList<>(); ArrayList<Entry> vals1 = new ArrayList<>(); switch (target.time_span.toLowerCase()) { case "daily": { HashMap<String, Integer> time_spent = new HashMap<>(); xVals.add("00:00"); time_spent.put("00:00", 0); xVals.add("09:00"); time_spent.put("09:00", 0); xVals.add("12:00"); time_spent.put("12:00", 0); xVals.add("15:00"); time_spent.put("15:00", 0); xVals.add("18:00"); time_spent.put("18:00", 0); xVals.add("21:00"); time_spent.put("21:00", 0); xVals.add("24:00"); time_spent.put("24:00", 0); for(int i = 0; i < activityHistoryList.size(); i++) { int starttime = Integer.parseInt(activityHistoryList.get(i).created_date.split(" ")[1].split(":")[0]) * 60 + Integer.parseInt(activityHistoryList.get(i).created_date.split(" ")[1].split(":")[1]); int endtime = starttime + Integer.parseInt(activityHistoryList.get(i).time_spent); int total_time = 0; for(int j = 0; j < xVals.size(); j++) { int minutes = Integer.parseInt(xVals.get(j).split(":")[0]) * 60; if(starttime < minutes && minutes < endtime) { int tmp = time_spent.get(xVals.get(j)); time_spent.remove(xVals.get(j)); time_spent.put(xVals.get(j), tmp + minutes-starttime); total_time = tmp + minutes-starttime; } else if(minutes > endtime) { if(total_time == 0) total_time = Integer.parseInt(activityHistoryList.get(i).time_spent); time_spent.remove(xVals.get(j)); time_spent.put(xVals.get(j), total_time); } } } for (int i = 0; i < 7; i++) { float tmp = ((float)time_spent.get(xVals.get(i)) / Integer.parseInt(target.total_time)) * 100; if(tmp > 100) tmp = 100; vals1.add(new Entry(tmp, i)); } break; } case "weekly": { xVals.add("Sun"); xVals.add("Mon"); xVals.add("Tue"); xVals.add("Wed"); xVals.add("Thu"); xVals.add("Fri"); xVals.add("Sat"); HashMap<Integer, Float> values = new HashMap<>(); for(int i = 0; i < 7; i++) { values.put(i, 0f); } Calendar c = Calendar.getInstance(); for(int i = 0; i < activityHistoryList.size(); i ++) { String date = activityHistoryList.get(i).activity_date; c.set(Integer.parseInt(date.split("-")[0]), Integer.parseInt(date.split("-")[1])-1, Integer.parseInt(date.split("-")[2])); float tmp = values.get(c.get(Calendar.DAY_OF_WEEK)-1); values.remove(c.get(Calendar.DAY_OF_WEEK) - 1); values.put(c.get(Calendar.DAY_OF_WEEK) - 1, tmp + Integer.parseInt(activityHistoryList.get(i).time_spent) / 60 + (float) (Integer.parseInt(activityHistoryList.get(i).time_spent) % 60 / 60)); } for (int i = 0; i < 7; i++) { vals1.add(new Entry(values.get(i), i)); } break; } case "monthly": { //TODO: Posibila problema cand nr de zile dintr-o luna sa fie mare Calendar c = Calendar.getInstance(); HashMap<Integer, Float> values = new HashMap<>(); for(int i = 1; i <= c.get(Calendar.DAY_OF_MONTH); i++) { values.put(i, 0f); xVals.add(i + ""); for(int j = 0; j < activityHistoryList.size(); j ++) { if(Integer.parseInt(activityHistoryList.get(j).activity_date.split("-")[2]) == i) { float tmp = values.get(i); values.remove(i); values.put(i, tmp + Integer.parseInt(activityHistoryList.get(j).time_spent) / 60 + (float) (Integer.parseInt(activityHistoryList.get(j).time_spent) % 60 / 60)); } } vals1.add(new Entry(values.get(i), i-1)); } break; } } // create a dataset and give it a type LineDataSet set1 = new LineDataSet(vals1, "DataSet 1"); set1.setCubicIntensity(0.2f); set1.setDrawFilled(true); set1.setDrawCircles(false); set1.setLineWidth(1.8f); set1.setCircleSize(2f); set1.setCircleColor(Color.WHITE); set1.setColor(0xFF8864C8); set1.setFillColor(0xFF8864C8); set1.setFillAlpha(255); set1.setDrawHorizontalHighlightIndicator(false); // create a data object with the datasets LineData data = new LineData(set1); data.setValueTypeface(DataManager.getInstance().myriadpro_regular); data.setValueTextSize(12f); data.setDrawValues(false); // set data lineChart.setData(data); } protected PieData generatePieData() { ArrayList<PieEntry> entries1 = new ArrayList<>(); ArrayList<String> xVals = new ArrayList<>(); xVals.add(""); entries1.add(new PieEntry(spent_time, 0)); if(neccesary_time-spent_time > 0) { xVals.add(""); entries1.add(new PieEntry(neccesary_time - spent_time, 1)); } PieDataSet ds1 = new PieDataSet(entries1, ""); final int[] color = { Color.rgb(173, 88, 203), Color.rgb(224, 223, 224) }; ds1.setColors(color); ds1.setSliceSpace(0); ds1.setValueTextColor(Color.rgb(136, 100, 200)); ds1.setValueTextSize(12f); ds1.setDrawValues(false); PieData d = new PieData(ds1); d.setValueTypeface(DataManager.getInstance().myriadpro_regular); return d; } protected PieData generatePieData2() { ArrayList<PieEntry> entries1 = new ArrayList<>(); ArrayList<String> xVals = new ArrayList<>(); xVals.add(""); entries1.add(new PieEntry(spent_time - neccesary_time, 0)); if(stretch_target == null) stretch_target = new Select().from(StretchTarget.class).where("target_id = ?", target.target_id).executeSingle(); if(neccesary_time + Integer.parseInt(stretch_target.stretch_time) - spent_time > 0) { xVals.add(""); entries1.add(new PieEntry(neccesary_time + Integer.parseInt(stretch_target.stretch_time) - spent_time, 1)); } PieDataSet ds1 = new PieDataSet(entries1, ""); final int[] color = { Color.rgb(200, 129, 225), Color.rgb(224, 223, 224) }; ds1.setColors(color); ds1.setSliceSpace(0); ds1.setValueTextColor(Color.rgb(180, 100, 200)); ds1.setValueTextSize(12f); ds1.setDrawValues(false); PieData d = new PieData(ds1); d.setValueTypeface(DataManager.getInstance().myriadpro_regular); return d; } }
package com.junzhao.shanfen.model; import com.google.gson.annotations.Expose; import java.io.Serializable; import java.util.List; /** * Created by Administrator on 2018/3/12 0012. */ public class PHPostData implements Serializable{ @Expose public String addTime; @Expose public String evaluateNum; @Expose public String giftNum; @Expose public String goodNum; @Expose public InitialPostsBean initialPostsBean; @Expose public String isCollect; @Expose public String isFollow; @Expose public String isLikes; @Expose public String isOriginalDelete; @Expose public String isTranspond; @Expose public String postsContent; @Expose public String postsId; @Expose public String shareNum; @Expose public String shareUrl; @Expose public String topicCategoryName; @Expose public String transpondNum; @Expose public String transpondObjectId; @Expose public String userId; @Expose public String userName; @Expose public String userPhoto; @Expose public List<MediaPath> mediaPath; @Expose public List<TranspondContent> transpondContentList; public class InitialPostsBean{ @Expose public String fileType; @Expose public String initialPostsId; @Expose public String userId; @Expose public String userName; @Expose public String transpondContent; @Expose public List<MediaPath> mediaPath; } public class MediaPath{ @Expose public String originalImg; @Expose public String smallImg; @Expose public String originalVideo; @Expose public String isLandscape; @Expose public String videoImg; } /* "userId": "userName": "transpondContent": "fileType": 多媒体文件类型 "mediaPath": 多媒体文件的路径 */ public class TranspondContent{ @Expose public String userId; @Expose public String userName; @Expose public String transpondContent; @Expose public String fileType; @Expose public String mediaPath; } }
package classes; /** * Enumeration TypeEvenemrnt - écrire ici la description de l'énumération * * @author (votre nom) * @version (numéro de version ou date) */ public enum TypeEvenement { ANNIVERSSAIRE,AUTRE,MARIAGE; }
package com.learn.chapter2.mapper; import com.learn.chapter2.pojo.Role; public interface RoleMapper { Role getRole(int id ); int insertRole(Role role); }
package com.cyou.paycallback.util; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.List; import javax.servlet.http.HttpServletRequest; /** * 生成签名工具类(URL加密传输) * @author zhanghl * */ public class SignUtil { /** * 创建签名 * @param param 参数升序串 * @param isSubstr true截取8~24后返回16位子串作为签名,flase返回全部32位作为签名 * @return * @throws Exception */ public static String createSign(String param, boolean isSubstr) throws Exception { StringBuffer result = new StringBuffer(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(param.getBytes("UTF-8")); byte[] b = md5.digest(); for (int i = 0; i < b.length; ++i) { int x = b[i] & 0xFF; int h = x >>> 4; int l = x & 0x0F; result.append((char) (h + ((h < 10) ? '0' : 'a' - 10))); result.append((char) (l + ((l < 10) ? '0' : 'a' - 10))); } if (isSubstr) { return result.toString().substring(8, 24); } else { return result.toString(); } } /** * 创建参数升序串 * @param request 请求对象 * @return * @throws UnsupportedEncodingException */ public static String createParam(HttpServletRequest request) throws UnsupportedEncodingException { List<String> keyList = new ArrayList<String>(); @SuppressWarnings("unchecked") Enumeration<String> enumeration = request.getParameterNames(); while(enumeration.hasMoreElements()) { String key = enumeration.nextElement(); keyList.add(key); } Collections.sort(keyList, new Comparator<String>() { public int compare(String str1, String str2) { if(str1.compareTo(str2)>0) { return 1; } if(str1.compareTo(str2)<0) { return -1; } return 0; } }); StringBuffer param = new StringBuffer(); for(String key:keyList) { param.append(key); param.append("="); param.append(request.getParameter(key)); param.append("&"); } return param.toString().replaceAll("\n", "").replaceAll("\r", ""); } }
package stringProb; public class uniqueStrings { public static void main(String[] args){ String str="pushpak"; char ch; int count=0; while(str.length()!=0) { ch=str.charAt(0); int i=0; while(str.charAt(i)==ch) { count =count+i; i++; } str.substring(count); System.out.println(ch); System.out.println(count); } } }
package org.xaab.springmvc.model; public class LoginStatus { private final boolean success; private final boolean loggedIn; private final String username; private final String errorMessage; public LoginStatus(boolean success, boolean loggedIn, String username, String errorMessage) { this.success = success; this.loggedIn = loggedIn; this.username = username; this.errorMessage = errorMessage; } public String getErrorMessage() { return errorMessage; } public boolean isLoggedIn() { return loggedIn; } public String getUsername() { return username; } public boolean isSuccess() { return success; } }
package Recursion; import java.util.Scanner; public class SumOfArrayEle { static int sumOfEle(int[] a,int sum, int i){ if(i>a.length-1) return sum; return sumOfEle(a, sum+a[i], i+1); } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter the numberof elements: "); int n = in.nextInt(); int[] a = new int[n]; System.out.println("Enter the "+n+" elements"); for(int i=0; i<n; i++){ a[i] = in.nextInt(); } int sum = sumOfEle(a, 0, 0); System.out.println("Sum of array elements: "+sum); in.close(); } }
package com.lq.dao; import java.math.BigDecimal; import java.util.List; import javax.annotation.Resource; import com.lq.entity.Generator; import com.lq.entity.Isbn; import com.lq.entity.Rentable; import com.lq.entity.Rentablestop; import com.lq.entity.Rented; import com.lq.entity.Sale; import com.lq.other.PartRentable; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; @Repository public class RentableDaoImpl implements RentableDao{ @Resource(name="sessionFactory") private SessionFactory sessionFactory; @Override public void addRentable(Rentable rentable) { sessionFactory.getCurrentSession().save(rentable); } @Override public boolean delRentable(int index) { String hql = "delete Rentable u where u.id= ?"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, index); return (query.executeUpdate() > 0); } @SuppressWarnings("unchecked") @Override public List<Rentable> getRentables(int startlocation, int size) { String hql = "FROM Rentable order by start_time desc"; // 鏍规嵁闇�瑕佹樉绀虹殑淇℃伅涓嶅悓 灏�*鏇挎崲鎴愪笉鍚屽睘鎬э紝杩樻槸灏佽鎴愪竴涓被CommonInfo Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setMaxResults(size); query.setFirstResult(startlocation); return query.list(); } @Override public boolean updateRentable(int id, String picture){ String hql = "update Rentable u set u.picture=?where u.id=?"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setString(0, picture); query.setInteger(1, id); return (query.executeUpdate()>0); } /* * 闇�瑕佹妸rentable琛ㄤ腑鎵�鏈変笌rented閲嶅鐨勫瓧娈靛叏閮ㄥ鍒跺埌new Rented涓� */ @Override public boolean moveRentable(int index) { // TODO Auto-generated method stub String hql = "select new Rented(u.id,u.picture,u.information,u.origin_openid," + "u.start_time,u.way,u.rent_price,u.sale_price) from Rentable u where u.id=?"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, index); sessionFactory.getCurrentSession().save((Rented) query.uniqueResult()); hql = "delete Rentable u where u.id = ?"; query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, index); return (query.executeUpdate()>0); } /* * 闇�瑕佹妸rentable琛ㄤ腑鎵�鏈変笌sale閲嶅鐨勫瓧娈靛叏閮ㄥ鍒跺埌new Sale涓� */ @Override public boolean moveRentabletoSale(int bookid) { // TODO Auto-generated method stub String hql = "select new Sale(u.id,u.picture,u.information,u.origin_openid,u.start_time," + "u.way,u.rent_price,u.sale_price) from Rentable u where u.id=?"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, bookid); sessionFactory.getCurrentSession().save((Sale) query.uniqueResult()); hql = "delete Rentable u where u.id = ?"; query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, bookid); return (query.executeUpdate()>0); } @Override public boolean backRentable(int bookid,String tablename) { // TODO Auto-generated method stub String hql = "select new Rentable(u.id,u.picture,u.information,u.origin_openid,u.start_time," + "u.way,u.rent_price,u.sale_price) from "+ tablename +" u where u.id=?"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, bookid); sessionFactory.getCurrentSession().save((Rentable)query.uniqueResult()); hql = "delete "+tablename+" u where u.id = ?"; query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, bookid); return (query.executeUpdate()>0); } @Override public boolean updateRentableWay(int bookid,int way) { // TODO Auto-generated method stub String hql = "update Rentable u set u.way=? where u.id = ?"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, way); query.setInteger(1, bookid); return (query.executeUpdate()>0); } @SuppressWarnings("unchecked") @Override public List<PartRentable> getPartRentables(int startlocation, int size) { String hql = "select new PartRentable(u.id,t.picture,u.way,u.rent_price,u.sale_price,t.title) " + "FROM Rentable u,Isbn t WHERE u.information = t.isbn and u.way>0 order by u.start_time desc"; // 鏍规嵁闇�瑕佹樉绀虹殑淇℃伅涓嶅悓 灏�*鏇挎崲鎴愪笉鍚屽睘鎬э紝杩樻槸灏佽鎴愪竴涓被CommonInfo Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setMaxResults(size); query.setFirstResult(startlocation); return query.list(); } @Override public Rentable getOneRentable(int id) { String hql = "FROM Rentable u Where u.id=? "; // 鏍规嵁闇�瑕佹樉绀虹殑淇℃伅涓嶅悓 灏�*鏇挎崲鎴愪笉鍚屽睘鎬э紝杩樻槸灏佽鎴愪竴涓被CommonInfo Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, id); return (Rentable) query.uniqueResult(); } @Override public Isbn getBookInfo(String isbn) { // TODO Auto-generated method stub String hql = "FROM Isbn u Where u.isbn=? "; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setString(0, isbn); return (Isbn) query.uniqueResult(); } @Override public int getGeneratorId() { // TODO Auto-generated method stub String hql = "SELECT next_value FROM Generator WHERE name =?"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setString(0,"rentable_id"); if(query.uniqueResult() ==null ){ sessionFactory.getCurrentSession().save(new Generator("rentable_id",0)); return 0; } return (Integer)query.uniqueResult(); } @Override public boolean updateGeneratorId(int id) { // TODO Auto-generated method stub String hql = "update Generator set next_value=? WHERE name =?"; Query query =sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, id+1); query.setString(1,"rentable_id"); return(query.executeUpdate()>0); } @SuppressWarnings("unchecked") @Override public List<Rentable> getRentableWayBelowZero(String userid) { // TODO Auto-generated method stub String hql = "FROM Rentable WHERE way<0"; // 鏍规嵁闇�瑕佹樉绀虹殑淇℃伅涓嶅悓 灏�*鏇挎崲鎴愪笉鍚屽睘鎬э紝杩樻槸灏佽鎴愪竴涓被CommonInfo Query query = sessionFactory.getCurrentSession().createQuery(hql); return query.list(); } @Override public boolean moveRentabletoStop(int bookid) { // TODO Auto-generated method stub String hql = "select new Rentablestop(u.id,u.information,u.origin_openid," + "u.start_time)from Rentable u where u.id=?"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, bookid); sessionFactory.getCurrentSession().save((Rentablestop) query.uniqueResult()); hql = "delete Rentable u where u.id = ?"; query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, bookid); return (query.executeUpdate()>0); } @Override public boolean moveRentableFromStop(int bookid) { // TODO Auto-generated method stub String hql = "select new Rentable(u.id,u.information,u.origin_openid,u.start_time) from Rentablestop u" + " where u.id=?"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, bookid); sessionFactory.getCurrentSession().save((Rentable) query.uniqueResult()); hql = "delete Rentablestop u where u.id = ?"; query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, bookid); return (query.executeUpdate()>0); } @Override public boolean updateRentableInfo(int bookid, String picPath, BigDecimal rent_price, BigDecimal sale_price, int way) { // TODO Auto-generated method stub String hql = "update Rentable set picture=?,rent_price=?,sale_price=?,way=? WHERE id =?"; Query query =sessionFactory.getCurrentSession().createQuery(hql); query.setString(0,picPath); query.setBigDecimal(1, rent_price); query.setBigDecimal(2, sale_price); query.setInteger(3, way); query.setInteger(4,bookid); return(query.executeUpdate()>0); } @Override public Long getRentableLen() { // TODO Auto-generated method stub String hql = "SELECT COUNT(*) FROM Rentable"; Query query = sessionFactory.getCurrentSession().createQuery(hql); return (Long)query.uniqueResult(); } @Override public boolean updateRentableWayToMinus(int bookid) { // TODO Auto-generated method stub String hql = "select b.way from Rentable b WHERE b.id =?"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, bookid); String hql2 = "update Rentable u set u.way= ?where u.id = ?"; Query query2 = sessionFactory.getCurrentSession().createQuery(hql2); query2.setInteger(0, (Integer)query.uniqueResult()*-1); query2.setInteger(1, bookid); return (query2.executeUpdate()>0); } @Override public Rentablestop getOneRentableStop(int bookid) { // TODO Auto-generated method stub String hql = "FROM Rentablestop u Where u.id=? "; // 鏍规嵁闇�瑕佹樉绀虹殑淇℃伅涓嶅悓 灏�*鏇挎崲鎴愪笉鍚屽睘鎬э紝杩樻槸灏佽鎴愪竴涓被CommonInfo Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setInteger(0, bookid); return (Rentablestop)query.uniqueResult(); } }
package com.test; import org.springframework.util.Assert; public class isNull { public static void main(String[] args) { test(); System.out.println("111"); } private static void test() { String a=null; Assert.notNull(a, "Filter must not be null"); } }
package ca.kitamura.simpleaddressbook.screens.main; import android.util.Log; import java.io.IOException; import ca.kitamura.simpleaddressbook.models.randomuser.RandomUserResponse; import ca.kitamura.simpleaddressbook.networking.NetworkingService; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Darren on 2016-12-14. */ public class MainPresenterImpl implements MainPresenter { MainView mainView; MainPresenterImpl(MainView view) { this.mainView = view; } @Override public void getContacts() { mainView.showProgressBar(); Call<RandomUserResponse> randomUserResponseCall = NetworkingService.getRandomUserService().getRandomUsers(); randomUserResponseCall.enqueue(new Callback<RandomUserResponse>() { @Override public void onResponse(Call<RandomUserResponse> call, Response<RandomUserResponse> response) { mainView.hideProgressBar(); mainView.updateContactRecyclerView(response.body().getResults()); } @Override public void onFailure(Call<RandomUserResponse> call, Throwable t) { mainView.hideProgressBar(); if(t instanceof IOException) { mainView.showNetworkError(); } Log.e("Call Fail", t.getMessage()); } }); } @Override public void onDestroy() { mainView = null; } }
package model.personajes; import model.Unidad; import model.ataque.Ataque; import model.error.ErrorKiInsuficiente; import model.personajes.modos.GokuNormal; public class Goku extends Unidad { public Goku() { vidaMaxima = 500; vidaActual = 500; modo = new GokuNormal(); } @Override public void ataqueBasicoA(Unidad unidad) { Ataque ataqueBasico = modo.getAtaqueBasico(); unidad.recibirAtaque(ataqueBasico); } @Override public void ataqueEspecialA(Unidad unidad) throws ErrorKiInsuficiente { Ataque kamehameha = modo.getAtaqueEspecial(); unidad.recibirAtaque(kamehameha); } @Override public void recibirAtaque(Ataque ataque) { this.vidaActual -= ataque.getDano(); } }
package io.github.selchapp.api.model; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIdentityReference; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name="team") public class Team { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @ManyToMany @JoinTable(name = "team_members", joinColumns = @JoinColumn(name = "team_id"), inverseJoinColumns = @JoinColumn(name = "member_id")) @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") @JsonIdentityReference(alwaysAsId=true) private Collection<User> users; public Long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection<User> getUsers() { return users; } public void setUsers(Collection<User> users) { this.users = users; } }
import java.util.Scanner; public class Binary{ public static void main(String[] arr) { Scanner s = new Scanner(System.in); System.out.print("Enter binary number: "); long q=s.nextLong(); System.out.print("Enter decimal number : "); int p=s.nextInt(); s.close(); System.out.println("Binary to Decimal :" + bin2dec(q)); System.out.println("Decimal to binary :" + dec2bin(p)); } public static int bin2dec(long k) { int f=1,num=0; while(k!=0) { int r=(int)(k%10); num=num+r*f; k/=10; f*=2; } return num; } public static long dec2bin(int k) { int f=1; long num=0; while(k!=0) { int r=k%2; num=num+r*f; k/=2; f*=10; //System.out.printf("num %d rem %d fact %d \n",k,r,f); } return num; } }
package com.lzm.KnittingHelp.counters.components; import android.content.Context; import android.content.res.TypedArray; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.lzm.KnittingHelp.R; public class CounterCardView extends CardView { String titleHint = "Counter name"; int titleBackground; int titleColor; TextView counterCount; EditText counterTitle; LinearLayout counterHeader; Button counterIncrease; Button counterDecrease; String counterName; int currentCount = 0; Context context; public CounterCardView(Context context) { super(context); initialize(context, null); } public CounterCardView(Context context, AttributeSet attrs) { super(context, attrs); initialize(context, attrs); } public CounterCardView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(context, attrs); } private void initialize(Context context, AttributeSet attrs) { this.context = context; LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.counter_card, this, true); initializeComponents(view); initializeAttributes(context, attrs); counterName = context.getString(R.string.counter_name_placeholder); if (titleHint == null || titleHint.equals("")) { titleHint = counterName; } counterHeader.setBackgroundColor(titleBackground); counterTitle.setHint(titleHint); counterTitle.setTextColor(titleColor); counterTitle.setHintTextColor(titleColor); counterCount.setText(String.valueOf(currentCount)); } private void initializeComponents(View view) { counterCount = view.findViewById(R.id.counter_text); counterTitle = view.findViewById(R.id.counter_title); counterHeader = view.findViewById(R.id.counter_header); counterIncrease = view.findViewById(R.id.counter_increase); counterDecrease = view.findViewById(R.id.counter_decrease); counterIncrease.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { counterIncrease(); } }); counterDecrease.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { counterDecrease(); } }); } private void initializeAttributes(Context context, AttributeSet attrs) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CounterCardView, 0, 0); try { titleHint = a.getString(R.styleable.CounterCardView_titleHint); titleBackground = a.getColor(R.styleable.CounterCardView_titleBackground, ContextCompat.getColor(context, R.color.counter_header)); titleColor = a.getColor(R.styleable.CounterCardView_titleColor, ContextCompat.getColor(context, R.color.text_primary)); } finally { a.recycle(); } } void counterIncrease() { currentCount += 1; counterCount.setText(String.valueOf(currentCount)); } void counterDecrease() { if (currentCount > 0) { currentCount -= 1; counterCount.setText(String.valueOf(currentCount)); } } }
package com.mkd.adtools.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; import com.mkd.adtools.bean.AdSysUser; import com.mkd.adtools.service.AdService; import com.mkd.adtools.service.UserService; import com.mkd.adtools.utils.JwtTokenUtil; import lombok.extern.slf4j.Slf4j; @RestController @Slf4j @RequestMapping("/login") public class LoginController { @Autowired public AdService adservice ; @Autowired public UserService userService ; @RequestMapping(value = "/admlogin", method = RequestMethod.GET) public JSONObject admLogin(AdSysUser sysUser) { log.info("username:"+sysUser.getUsername()+" password:"+sysUser.getPassword()); JSONObject obj = new JSONObject(); if (StringUtils.isEmpty(sysUser.getUsername()) || StringUtils.isEmpty(sysUser.getPassword())) { obj.put("code", 1); obj.put("msg", "账户名或者密码不能为空"); return obj; } AdSysUser user = this.userService.selectSysUser(sysUser); if (user == null) { obj.put("code", 2); obj.put("msg", "账户名或者密码错误"); return obj; } String token = JwtTokenUtil.generateToken(sysUser.getUsername(), user.getId() + ""); System.out.println("token:" + token); this.userService.setSysUserToken(user.getId(), token); obj.put("msg", "登录成功"); obj.put("code", 0); JSONObject r = new JSONObject(); r.put("token", token); obj.put("data", r); return obj; } }
package lab3; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * * Classe que contém os testes de Contato * * @author Charles Bezerra de Oliveira Júnior-119110595 (Lab3) * */ class ContatoTest{ /** * Atributos do tipo contato. * */ private Contato contato1, contato2, contato3, contato4; /** * Método que inicializa e atribui objetos do tipo Contato * */ @BeforeEach void criarContatos(){ contato1 = new Contato("Charles","Bezerra", "(84) 99999-9999"); contato2 = new Contato("Pedro","Castanha", "(84) 99999-9999"); contato3 = new Contato("Charles","Bezerra", "(84) 99999-9999"); contato4 = new Contato("Matheus","Oliveira", "(84) 99999-9999"); } /** * Método que testa a função exibirContato de Contato */ @Test void testExibirContato() { assertEquals("Charles Bezerra - (84) 99999-9999", contato1.exibirContato()); assertEquals("Pedro Castanha - (84) 99999-9999", contato2.exibirContato()); assertEquals("Charles Bezerra - (84) 99999-9999", contato3.exibirContato()); assertEquals("Matheus Oliveira - (84) 99999-9999", contato4.exibirContato()); } /** * Método que testa a função toString de Contato */ @Test void testToString() { assertEquals("Charles Bezerra", contato1.toString()); assertEquals("Pedro Castanha", contato2.toString()); assertEquals("Charles Bezerra", contato3.toString()); assertEquals("Matheus Oliveira", contato4.toString()); } /** * Método que testa a função equals de Contato */ @Test void testEquals() { assertTrue(contato1.equals(contato3)); assertFalse(contato2.equals(contato3)); assertFalse(contato3.equals(contato4)); assertFalse(contato4.equals(contato1)); } }
package com.es.core.dto.input; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; public class CartItemInputDto { @NotNull(message = "Phone id should not be null") private Long phoneId; @NotNull(message = "Quantity should not be null") @Min(value = 1 , message = "Quantity should be > 0") private Long requestedQuantity; public CartItemInputDto() { } public CartItemInputDto( final Long phoneId, final Long requestedQuantity ) { this.phoneId = phoneId; this.requestedQuantity = requestedQuantity; } public Long getPhoneId() { return phoneId; } public void setPhoneId(Long phoneId) { this.phoneId = phoneId; } public Long getRequestedQuantity() { return requestedQuantity; } public void setRequestedQuantity(Long requestedQuantity) { this.requestedQuantity = requestedQuantity; } @Override public int hashCode() { int result = 42; if (phoneId != null) { result = 31 * result + phoneId.hashCode(); } if (requestedQuantity != null) { result = 31 * result + requestedQuantity.hashCode(); } return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof CartItemInputDto)) return false; final CartItemInputDto other = (CartItemInputDto) obj; boolean phoneIdEquals = (this.phoneId == null && other.phoneId == null) || (this.phoneId != null && this.phoneId.equals(other.phoneId)); boolean requestedQuantityEquals = (this.requestedQuantity == null && other.requestedQuantity == null) || (this.requestedQuantity != null && this.requestedQuantity.equals(other.requestedQuantity)); return phoneIdEquals && requestedQuantityEquals; } }
package nbi.protocols; /** * @author robert.lee * @version $Revision: 1.0 $ */ public interface Behavior { /** * Method getFilePatternString. * @return String */ String getFilePatternString(); /** * Method getRemoteFolderName. * @return String */ String getRemoteFolderName(); /** * Method getLocalFolderName. * @return String */ String getLocalFolderName(); /** * Method isBulkTransport. * @return boolean */ boolean isBulkTransport(); /** * Method isCompressPut. * @return boolean */ boolean isCompressPut(); /** * Method isPutOrGet. * @return boolean */ boolean isPutOrGet(); /** * Method getCustomLogicClassName. * @return String */ String getCustomLogicClassName(); }
/* $Id$ */ package djudge.judge.executor; import org.w3c.dom.Document; import org.w3c.dom.Element; import djudge.common.XMLSerializable; import utils.XmlTools; public class ExecutorSecurityLimits extends XMLSerializable { public final static String XMLRootElement = "security"; public ExecutorSecurityLimits(Element elem) { readXML(elem); } public ExecutorSecurityLimits() { } @Override public Document getXML() { // TODO Auto-generated method stub return XmlTools.getDocument(); } @Override public boolean readXML(Element elem) { // TODO Auto-generated method stub return true; } }
package com.pages; import org.base.LibGlobal; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class SearchHotel extends LibGlobal { public SearchHotel() { PageFactory.initElements(driver, this); } @FindBy(id = "location") private WebElement sltLocation; @FindBy(id = "hotels") private WebElement sltHotels; @FindBy(id = "room_type") private WebElement sltRoomType; @FindBy(id = "room_nos") private WebElement sltRoomNo; @FindBy(id = "adult_room") private WebElement sltAdults; @FindBy(id = "child_room") private WebElement sltChild; @FindBy(id = "Submit") private WebElement btnClick; public WebElement getSltLocation() { return sltLocation; } public WebElement getSltHotels() { return sltHotels; } public WebElement getSltRoomType() { return sltRoomType; } public WebElement getSltRoomNo() { return sltRoomNo; } public WebElement getSltAdults() { return sltAdults; } public WebElement getSltChild() { return sltChild; } public WebElement getBtnClick() { return btnClick; } public void search(String location, String hotels, String roomtype, String roomNo, String adult, String child) { selectByVisibleText(sltLocation, location); selectByVisibleText(sltHotels, hotels); selectByVisibleText(sltRoomType, roomtype); selectByVisibleText(sltRoomNo, roomNo); selectByVisibleText(sltAdults, adult); selectByVisibleText(sltChild, child); click(btnClick); } }
public abstract class Shape { private String name; public Shape(String shapeName) { name = shapeName; } public String getName() { return name; } public abstract double area(); public abstract double perimeter(); public double semiperimeter() { return perimeter()/2; } public boolean equals(Shape other) { return this.area() == other.area() && this.perimeter() == other.perimeter(); } public int compareTo(Shape other) { if(this.area() > other.area()) { return 1; } if(this.area() < other.area()) { return -1; } if(this.perimeter() < other.perimeter()) { return 1; } if(this.perimeter() > other.perimeter()) { return -1; } return 0; } public String toString() { return name + " -> area = " + area() + ", perimeter = " + perimeter(); } }
package hwl4; import java.util.Comparator; import java.util.ArrayList; public class ATM { public class Nominal implements Comparator<Nominal>, Comparable<Nominal> { private int size = 0; private int count = 0; public Nominal(int size, int count) { super(); this.size = size; this.count = count; } public int getSize() { return size; } public int getCount() { return count; } public void setDeltaCount(int delta) { if (count + delta < 0) { System.out.println("Количество купюр не может быть отрицательным"); } else count = count + delta; } @Override public int compareTo(Nominal obj) { return obj.size - this.size; } @Override public int compare(Nominal obj1, Nominal obj2) { return obj1.compareTo(obj2); } } private ArrayList<Nominal> nominals = new ArrayList<Nominal>(0); private int getSummAllMoney() { int summ = 0; for (int i = 0; i < nominals.size(); i++) { summ = summ + nominals.get(i).count * nominals.get(i).size; } return summ; } private ArrayList<ArrayList> getVariantsOfIssue(int summ) { ArrayList arr = new ArrayList<ArrayList>(0); if ((summ > 0) && (getSummAllMoney() > 0)) { for (int k = 0; k < nominals.size(); k++) { ArrayList<Nominal> var = new ArrayList<Nominal>(0); int rem = summ; boolean needNext = false; for (int i = k; i < nominals.size(); i++) { if (nominals.get(i).getCount() > 0) { int c = rem / nominals.get(i).getSize(); int trem = rem % nominals.get(i).getSize(); if (c > 0) { if (trem > 0) { for (int s = i + 1; s < nominals.size(); s++) { if (nominals.get(s).getSize() <= trem) needNext = true; } } else needNext = true; if (c <= nominals.get(i).getCount() && needNext) { rem = trem; Nominal n = new Nominal(nominals.get(i).getSize(), c); var.add(n); } needNext = false; } if (rem == 0) { arr.add(var); break; } } } } } return arr; } private int selectVaraintToIssueMoney(ArrayList<ArrayList> ar) { int selectedVariant = -1; if (ar.size() > 0) { for (int i = 0; i < ar.size(); i++) { ArrayList<Nominal> lar = ar.get(i); String V = ""; for (int j = 0; j < lar.size(); j++) { V = V + lar.get(j).getSize() + "*" + lar.get(j).getCount() + " "; } System.out.println(i + 1 + ") " + V); } System.out.println("Введите номер варианта выдачи или \"0\" для отмены выдачи"); selectedVariant = MainClassl4.gSc.nextInt() - 1; } return selectedVariant; } private void printNominals() { if (nominals.size() > 0) { String V = ""; for (int i = 0; i < nominals.size(); i++) { V = V + "\"" + nominals.get(i).getSize() + "\"" + "->" + nominals.get(i).getCount() + " "; } System.out.println(V); } } public boolean issue(int selectedVariant, ArrayList<ArrayList> variants) { boolean result = true; if (selectedVariant >= 0) { ArrayList<Nominal> ar = variants.get(selectedVariant); for (int i = 0; i < ar.size(); i++) { for (int j = 0; j < nominals.size(); j++) { if (nominals.get(j).getSize() == ar.get(i).getSize()) { nominals.get(j).setDeltaCount(ar.get(i).getCount() * -1); break; } } } } else result = false; return result; } public void addNominal(int size, int count) { Nominal n = new Nominal(size, count); nominals.add(n); nominals.sort(n); } public boolean issueMoney() { boolean result = false; System.out.println("Введите сумму для выдачи"); int summ = MainClassl4.gSc.nextInt(); ArrayList<ArrayList> variants = getVariantsOfIssue(summ); int selectedVariant = selectVaraintToIssueMoney(variants); result = issue(selectedVariant, variants); if (result == false) System.out.println("Ошибка выдачи денег или выдача была отменена"); else { System.out.println("Заберите деньги"); printSumm(); } return result; } private void printSumm() { System.out.println("Общая сумма денег в банкомате>" + this.getSummAllMoney()); } public ATM(int count100, int count50, int count20) { addNominal(100, count100); addNominal(50, count50); addNominal(20, count20); } public void printMenu() throws InterruptedException { boolean exit = false; while (exit != true) { System.out.println(" Выберите действие "); System.out.println("==============================="); System.out.println("1) Показать общую сумму денег "); System.out.println("2) Снять деньги "); System.out.println("3) Добавить купюры в банкомат"); System.out.println("4) Добавить другой номинал"); System.out.println("5) Показать номиналы купюр"); System.out.println("0) Выход"); System.out.println("==============================="); int ans = -1; while ((ans < 0) || (ans > 5)) { ans = MainClassl4.gSc.nextInt(); if ((ans < 0) || (ans > 5)) { System.out.println(" Введите корректный номер действия"); } } switch (ans) { case 1: { printSumm(); Thread.sleep(500); break; } case 2: { issueMoney(); Thread.sleep(500); break; } case 3: { int size = 0; int count = 0; boolean err = true; System.out.println("Введите номинал"); size = MainClassl4.gSc.nextInt(); System.out.println("Введите количество купюр"); count = MainClassl4.gSc.nextInt(); for (int i = 0; i < nominals.size(); i++) { if (nominals.get(i).getSize() == size) { if (count < 0) count = count * -1; nominals.get(i).setDeltaCount(count); err = false; } } if (err) System.out.println("Ошибка, не найден такой номинал"); break; } case 4: { int size = 0; int count = 0; System.out.println("Введите новый номинал"); size = MainClassl4.gSc.nextInt(); System.out.println("Введите количество купюр"); count = MainClassl4.gSc.nextInt(); addNominal(size, count); } case 5: { printNominals(); Thread.sleep(500); break; } case 0: { System.out.println("Выходим"); exit = true; break; } } } } }
package xtrus.ex.mci.message; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.commons.io.IOUtils; import xtrus.ex.mci.ExMciCode; import xtrus.ex.mci.ExMciConfig; import xtrus.ex.mci.ExMciException; import xtrus.ex.mci.Utils; public class NonStdMciMessage extends MciMessage { private int stx = (int)0x02; //HEADER private int messageLength ; //메시지 길이(4) private String senderSystemCode ; //시스템 구분코드(SEND, 3) private String senderRoadCode ; //송신자 시스템 차로(3) private String recverSystemCode ; //시스템 구분코드(RECV, 3) private String recverRoadCode ; //수신자 시스템 차로(3) private String roleTypeCode ; //업무구분코드, 4 private String workTypeCode ; //작업구분코드, 4 private String createdTime ; //전문 송수신 일시, 14 private String responseCode ; //응답코드, 4 // DATA private byte[] dataBytes; private int etx = (int)0x03; public NonStdMciMessage() { setType(Message.NON_STANDARD_TYPE); } public int getMessageLength() { return messageLength; } public void setMessageLength(int messageLength) { this.messageLength = messageLength; } public String getSenderSystemCode() { return senderSystemCode; } public void setSenderSystemCode(String senderSystemCode) { this.senderSystemCode = senderSystemCode; } public String getRecverSystemCode() { return recverSystemCode; } public void setRecverSystemCode(String recverSystemCode) { this.recverSystemCode = recverSystemCode; } public String getRoleTypeCode() { return roleTypeCode; } public void setRoleTypeCode(String roleTypeCode) { this.roleTypeCode = roleTypeCode; } public String getWorkTypeCode() { return workTypeCode; } public void setWorkTypeCode(String workTypeCode) { this.workTypeCode = workTypeCode; } public String getCreatedTime() { return createdTime; } public void setCreatedTime(String createdTime) { this.createdTime = createdTime; } public String getResponseCode() { return responseCode; } public void setResponseCode(String responseCode) { this.responseCode = responseCode; } public byte[] getDataBytes() { return dataBytes; } public void setDataBytes(byte[] dataBytes) { this.dataBytes = dataBytes; } public String getSenderRoadCode() { return senderRoadCode; } public void setSenderRoadCode(String senderRoadCode) { this.senderRoadCode = senderRoadCode; } public String getRecverRoadCode() { return recverRoadCode; } public void setRecverRoadCode(String recverRoadCode) { this.recverRoadCode = recverRoadCode; } @Override public void marshal(byte[] rawBytes) throws ExMciException { setRawBytes(rawBytes); ByteArrayInputStream in = null; try { in = new ByteArrayInputStream(rawBytes); in.read(); // ignore STX(0x02) messageLength = Utils.readToInt(in, 4); senderSystemCode = Utils.readToString(in, 3).trim(); senderRoadCode = Utils.readToString(in, 3).trim(); recverSystemCode = Utils.readToString(in, 3).trim(); recverRoadCode = Utils.readToString(in, 3).trim(); roleTypeCode = Utils.readToString(in, 4).trim(); workTypeCode = Utils.readToString(in, 4).trim(); createdTime = Utils.readToString(in, 14).trim(); responseCode = Utils.readToString(in, 4).trim(); this.dataBytes = new byte[messageLength-38]; // header(38) 제외 in.read(this.dataBytes); in.read(); // ignore ETX(0x03) } catch (IOException e) { throw new ExMciException(ExMciCode.ERROR_CLIENT_READ_WRITE, "marshal()", "Data bytes reading failed.", e); } finally { IOUtils.closeQuietly(in); } } @Override public byte[] unmarshal() throws ExMciException { StringBuffer mBuffer = new StringBuffer(); mBuffer.append(Utils.writeToString(this.senderSystemCode , 3)); mBuffer.append(Utils.writeToString(this.senderRoadCode , 3)); mBuffer.append(Utils.writeToString(this.recverSystemCode , 3)); mBuffer.append(Utils.writeToString(this.recverRoadCode , 3)); mBuffer.append(Utils.writeToString(this.roleTypeCode , 4)); mBuffer.append(Utils.writeToString(this.workTypeCode , 4)); mBuffer.append(Utils.writeToString(this.createdTime , 14)); mBuffer.append(Utils.writeToString(this.responseCode , 4)); StringBuffer buffer = new StringBuffer(); buffer.append(Utils.writeToNumeric(String.valueOf(mBuffer.length()+dataBytes.length), 4)); buffer.append(mBuffer.toString()); ByteArrayOutputStream out = null; try { out = new ByteArrayOutputStream(); out.write(stx); out.write(buffer.toString().getBytes(ExMciConfig.DEFAULT_ENCODING)); out.write(this.getDataBytes()); out.write(etx); return out.toByteArray(); } catch (Exception e) { throw new ExMciException(ExMciCode.ERROR_GENERATE_MESSAGE, "unmarshal()", "Message unmarshing failed.", e); } finally { IOUtils.closeQuietly(out); } } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("stx =["+stx+"]"+System.lineSeparator()); buffer.append("messageLength =["+messageLength+"]"+System.lineSeparator()); buffer.append("senderSystemCode =["+senderSystemCode+"]"+System.lineSeparator()); buffer.append("recverSystemCode =["+recverSystemCode+"]"+System.lineSeparator()); buffer.append("roleTypeCode =["+roleTypeCode+"]"+System.lineSeparator()); buffer.append("workTypeCode =["+workTypeCode+"]"+System.lineSeparator()); buffer.append("createdTime =["+createdTime+"]"+System.lineSeparator()); buffer.append("responseCode =["+responseCode+"]"+System.lineSeparator()); try { buffer.append("data = ["+new String(this.dataBytes, ExMciConfig.DEFAULT_ENCODING)+"]"+System.lineSeparator()); } catch (UnsupportedEncodingException e) { buffer.append("data = ["+new String(this.dataBytes)+"]"+System.lineSeparator()); } buffer.append("etx =["+etx+"]"+System.lineSeparator()); return buffer.toString(); } }
package ru.sbt.test.refactoring; public class Position { private static final int borderValue = 5; private int x; private int y; public Position(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } public void incPosX() { this.x++; } public void incPosY() { this.y++; } public void decPosX() { this.x--; } public void decPosY() { this.y--; } public boolean isNotValid() { return (getX() > borderValue || getY() > borderValue); } }
package com.esum.wp.ims.errorsummary.service; import com.esum.appframework.service.IBaseService; public interface IErrorSummaryService extends IBaseService { Object selectDocumentPageList(Object object); Object selectErrCodeDetailPageList(Object object); }
package com.allmsi.plugin.flow.service; import java.util.List; import com.allmsi.plugin.flow.model.ivo.FlowInstanceIVo; import com.allmsi.plugin.flow.model.ivo.FlowInstance4ListIVo; import com.allmsi.plugin.flow.model.ovo.FlowInstanceOVo; public interface FlowInstanceService { int selectCountInstanceList(FlowInstance4ListIVo flowInstanceIVo); List<FlowInstanceOVo> selectInstanceList(FlowInstance4ListIVo flowInstanceIVo, Integer page, Integer pageSize); int selectCountInstanceMyList(FlowInstance4ListIVo flowInstanceIVo); List<FlowInstanceOVo> selectInstanceMyList(FlowInstance4ListIVo flowInstanceIVo, Integer page, Integer pageSize); String addFlowInstance(FlowInstanceIVo flowInstanceIVo); boolean delFlowInstance(String id); }
/** * */ package net.sf.taverna.t2.component.preference; import static net.sf.taverna.t2.component.preference.ComponentDefaults.DEFAULT_REGISTRY_LIST; import static net.sf.taverna.t2.component.preference.ComponentDefaults.REGISTRY_LIST; import static net.sf.taverna.t2.component.preference.ComponentDefaults.getDefaultProperties; import static net.sf.taverna.t2.component.registry.ComponentUtil.calculateRegistry; import static org.apache.log4j.Logger.getLogger; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.SortedMap; import java.util.TreeMap; import net.sf.taverna.raven.appconfig.ApplicationRuntime; import net.sf.taverna.t2.component.api.Registry; import net.sf.taverna.t2.component.api.RegistryException; import net.sf.taverna.t2.workbench.configuration.AbstractConfigurable; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; /** * @author alanrw * */ public class ComponentPreference extends AbstractConfigurable { public static final String DISPLAY_NAME = "Components"; private final Logger logger = getLogger(ComponentPreference.class); private static ComponentPreference instance = null; private final SortedMap<String, Registry> registryMap = new TreeMap<String, Registry>(); public static ComponentPreference getInstance() { if (instance == null) instance = new ComponentPreference(); return instance; } private ComponentPreference() { super(); updateRegistryMap(); } private void updateRegistryMap() { registryMap.clear(); for (String key : getRegistryKeys()) { String value = super.getProperty(key); try { registryMap.put(key, calculateRegistry(new URL( value))); } catch (MalformedURLException e) { logger.error("bogus url (" + value + ") in configuration file", e); } catch (RegistryException e) { logger.error("failed to construct registry handle for " + value, e); } } } private String[] getRegistryKeys() { String registryNamesConcatenated = super.getProperty(REGISTRY_LIST); if (registryNamesConcatenated == null) { return (String[])getDefaultPropertyMap().keySet().toArray(new String[]{}); } else { return registryNamesConcatenated.split(","); } } public String getFilePrefix() { return "Component"; } public String getUUID() { return "2317A297-2AE0-42B5-86DC-99C9B7C0524A"; } /** * @return the registryMap */ public SortedMap<String, Registry> getRegistryMap() { return registryMap; } public String getRegistryName(URL registryBase) { // Trim trailing '/' characters to ensure match. String base = registryBase.toString(); while (base.endsWith("/")) base = base.substring(0, base.length() - 1); for (Entry<String, Registry> entry : registryMap.entrySet()) if (entry.getValue().getRegistryBaseString().equals(base)) return entry.getKey(); return base; } public void setRegistryMap(SortedMap<String, Registry> registries) { registryMap.clear(); registryMap.putAll(registries); super.clear(); List<String> keyList = new ArrayList<String>(); for (Entry<String, Registry> entry : registryMap.entrySet()) { final String key = entry.getKey(); keyList.add (key); super.setProperty(key, entry.getValue() .getRegistryBaseString()); } Collections.sort(keyList); String registryNamesConcatenated = StringUtils.join(keyList, ","); super.setProperty(REGISTRY_LIST, registryNamesConcatenated); } @Override public Map<String, String> getDefaultPropertyMap() { return getDefaultProperties(); } @Override public String getDisplayName() { return DISPLAY_NAME; } @Override public String getCategory() { return "general"; } }
package matrixstudio.model; import fr.minibilles.basics.model.ChangeRecorder; import fr.minibilles.basics.model.ModelObject; import fr.minibilles.basics.serializer.Boost; import fr.minibilles.basics.serializer.BoostObject; import java.text.ParseException; import matrixstudio.formula.EvaluationException; import matrixstudio.formula.FormulaCache; public abstract class Matrix implements ModelObject, BoostObject, Named { private Model model; private boolean random = true; private boolean ARGB = false; private boolean rainbow = false; private boolean ndRange = false; private String sizeX = "512"; private String sizeY = "256"; private String sizeZ = "1"; private String name; public Matrix() { } protected Matrix(Boost boost) { boost.register(this); int version = boost.getFileVersion(); model = boost.readObject(Model.class); random = boost.readBoolean(); ndRange = boost.readBoolean(); if (version >= 3) { sizeX = boost.readString(); sizeY = boost.readString(); sizeZ = boost.readString(); if(version >= 5) { ARGB = boost.readBoolean(); } if(version >= 6) { rainbow = boost.readBoolean(); } }else { boost.readInt(); // deprecated size field. sizeX = Integer.toString(boost.readInt()); sizeY = Integer.toString(boost.readInt()); sizeZ = Integer.toString(boost.readInt()); } name = boost.readString(); } /** * <p>Gets model.</p> */ public Model getModel() { return model; } /** * <p>Sets model.</p> */ public void setModel(Model newValue) { if (model == null ? newValue != null : (model.equals(newValue) == false)) { getChangeRecorder().recordChangeAttribute(this, "model", this.model); this.model= newValue; } } /** * <p>Gets random.</p> */ public boolean isRandom() { return random; } /** * <p>Sets random.</p> */ public void setRandom(boolean newValue) { if (random != newValue) { getChangeRecorder().recordChangeAttribute(this, "random", this.random); this.random= newValue; } } /** * <p>Gets ARGB.</p> */ public boolean isARGB() { return ARGB; } /** * <p>Sets ARGB.</p> */ public void setARGB(boolean newValue) { if (ARGB != newValue) { getChangeRecorder().recordChangeAttribute(this, "ARGB", this.ARGB); this.ARGB= newValue; } } /** * <p>Gets rainbow.</p> */ public boolean isRainbow() { return rainbow; } /** * <p>Sets rainbow.</p> */ public void setRainbow(boolean newValue) { if (rainbow != newValue) { getChangeRecorder().recordChangeAttribute(this, "Rainbow", this.rainbow); this.rainbow = newValue; } } /** * <p>Gets ndRange.</p> */ public boolean isNdRange() { return ndRange; } /** * <p>Sets ndRange.</p> */ public void setNdRange(boolean newValue) { if (ndRange != newValue) { getChangeRecorder().recordChangeAttribute(this, "ndRange", this.ndRange); this.ndRange= newValue; } } /** * <p>Gets sizeX.</p> */ public String getSizeX() { return sizeX; } /** * <p>Gets computed sizeX.</p> */ public int getSizeXValue() throws EvaluationException, ParseException { return FormulaCache.SHARED.computeValue(sizeX, getModel()); } public int safeGetSizeXValue() { try { return getSizeXValue(); } catch (ParseException | EvaluationException e) { return 0; } } /** * <p>Sets sizeX.</p> */ public void setSizeX(String newValue) { if (sizeX != newValue) { getChangeRecorder().recordChangeAttribute(this, "sizeX", this.sizeX); this.sizeX= newValue; } } /** * <p>Gets sizeY.</p> */ public String getSizeY() { return sizeY; } /** * <p>Gets computed sizeY.</p> */ public int getSizeYValue() throws EvaluationException, ParseException { return FormulaCache.SHARED.computeValue(sizeY, getModel()); } public int safeGetSizeYValue() { try { return getSizeYValue(); } catch (ParseException | EvaluationException e) { return 0; } } /** * <p>Sets sizeY.</p> */ public void setSizeY(String newValue) { if (sizeY != newValue) { getChangeRecorder().recordChangeAttribute(this, "sizeY", this.sizeY); this.sizeY= newValue; } } /** * <p>Gets sizeZ.</p> */ public String getSizeZ() { return sizeZ; } /** * <p>Gets computed sizeZ.</p> */ public int getSizeZValue() throws EvaluationException, ParseException { return FormulaCache.SHARED.computeValue(sizeZ, getModel()); } public int safeGetSizeZValue() { try { return getSizeZValue(); } catch (ParseException | EvaluationException e) { return 0; } } /** * <p>Sets sizeZ.</p> */ public void setSizeZ(String newValue) { if (sizeZ != newValue) { getChangeRecorder().recordChangeAttribute(this, "sizeZ", this.sizeZ); this.sizeZ= newValue; } } /** * <p>Gets name.</p> */ public String getName() { return name; } /** * <p>Sets name.</p> */ public void setName(String newValue) { if (name == null ? newValue != null : (name.equals(newValue) == false)) { getChangeRecorder().recordChangeAttribute(this, "name", this.name); this.name= newValue; } } public abstract void initBlank(boolean force); public abstract String getCType(); public abstract void setToInitialValues(); public abstract Number getValueAt(int i, int j, int k); public abstract void setValueAt(int i, int j, int k, Number v); public abstract Number getInitValueAt(int i, int j, int k); public abstract void setInitValueAt(int i, int j, int k, Number v); public void writeToBoost(Boost boost) { boost.writeObject(model); boost.writeBoolean(random); boost.writeBoolean(ndRange); boost.writeString(sizeX); boost.writeString(sizeY); boost.writeString(sizeZ); boost.writeBoolean(ARGB); boost.writeBoolean(rainbow); boost.writeString(name); } /** * Visitor accept method. */ public abstract void accept(ModelVisitor visitor); public ChangeRecorder getChangeRecorder() { if ( getModel() != null ) { return getModel().getChangeRecorder(); } return ChangeRecorder.Stub; } }
public abstract class Player { public enum PLAYERTYPE { POSITIVE_ONLY, NEGATIVE_POSITIVE } private String name; private String color; private int points; private PLAYERTYPE ptype; private boolean hasMove; private Move moveCurrent; Player(String name, String color, PLAYERTYPE ptype) { this.name = name; this.color = color; this.points = 0; this.ptype = ptype; } public abstract Move getMove(); public boolean hasMove() { return this.moveCurrent != NULL; } public String name() { return this.name; } public String color() { return this.color; } public String setColor(String newColor) { this.color = newColor; return this.color; } public int points() { return this.points; } // returns new number of points public int addPoint() { this.points += 1; return this.points; } public int addPoints(int more) { this.points += more; return this.points; } public int removePoint() { this.points -= 1; if (this.points < 0) { switch (this.ptype) { case POSITIVE_ONLY: this.points = 0; break; case NEGATIVE_POSITIVE: break; default: break; } } return this.points; } public int removePoints(int less) { this.points -= less; if (this.points < 0) { switch (this.ptype) { case POSITIVE_ONLY: this.points = 0; break; case NEGATIVE_POSITIVE: break; default: break; } } return this.points; } public int setPoints(int set) { this.points = set; if (this.points < 0) { switch (this.ptype) { case POSITIVE_ONLY: this.points = 0; break; case NEGATIVE_POSITIVE: break; default: break; } } return this.points; } }
// // Decompiled by Procyon v0.5.36 // package com.ideabus.contec_sdk.code.b; public class d extends g { private String az; public d() { this.az = "CMS50F"; } }
/** * Spring Data JPA repositories. */ package com.broadcom.websocketsampleapp.repository;
package webDriveDemo; import org.testng.annotations.Test; import org.testng.annotations.BeforeTest; import static org.testng.Assert.assertEquals; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.AfterTest; public class VerifyTitle { WebDriver driver; @BeforeTest public void beforeTest() { System.setProperty("webdriver.chrome.driver", "Resources/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); } @Test public void verifyTitle() throws InterruptedException { driver.get("http://www.newtours.demoaut.com/"); //store runtime page title String pageTitle = driver.getTitle(); System.out.println("Actual Result: Home Page Title - "+ pageTitle); assertEquals(pageTitle, "Welcome: Mercury Tours"); driver.findElement(By.linkText("REGISTER")).click(); System.out.println("Actual Result: Register Page Title - "+ driver.getTitle()); assertEquals(driver.getTitle(), "Register: Mercury Tours"); driver.findElement(By.xpath("//input[@name='firstName']")).sendKeys("Prapti"); driver.findElement(By.xpath("//input[@name='lastName']")).sendKeys("Sanghavi"); driver.findElement(By.xpath("//input[@name='phone']")).sendKeys("8890044822"); driver.findElement(By.xpath("//input[@name='address1']")).sendKeys("Thane, Mumbai"); driver.findElement(By.xpath("//input[@name='city']")).sendKeys("Mumbai"); driver.findElement(By.xpath("//input[@name='state']")).sendKeys("Maharashtra"); driver.findElement(By.xpath("//input[@name='postalCode']")).sendKeys("380004"); driver.findElement(By.xpath("//input[@name='userName']")).sendKeys("prapti@gmail.com"); driver.findElement(By.xpath("//input[@name='email']")).sendKeys("PraptiSan"); driver.findElement(By.xpath("//input[@name='password']")).sendKeys("poojapooja"); driver.findElement(By.xpath("//input[@name='confirmPassword']")).sendKeys("poojapooja"); Select countryname = new Select(driver.findElement(By.name("country"))); countryname.selectByIndex(8); Thread.sleep(3000); countryname.selectByValue("6"); Thread.sleep(3000); countryname.selectByVisibleText("INDIA"); Thread.sleep(3000); // driver.findElement(By.xpath("//input[@name='register']")).submit(); } @AfterTest public void afterTest() { driver.close(); } }
package com.crmiguez.aixinainventory.repository; import com.crmiguez.aixinainventory.entities.MoveType; import com.crmiguez.aixinainventory.entities.Movement; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository("movementRepository") public interface MovementRepository extends CrudRepository<Movement, Long> { Movement findByMovementId(Long movementId); List<Movement> findAllByMoveType(MoveType moveType); }
package com.metoo.foundation.dao; import org.springframework.stereotype.Repository; import com.metoo.core.base.GenericDAO; import com.metoo.foundation.domain.StoreGrade; @Repository("storeGradeDAO") public class StoreGradeDAO extends GenericDAO<StoreGrade> { }
package edu.mit.cci.simulation.model; import edu.mit.cci.simulation.util.ScenarioJAXBAdapter; import edu.mit.cci.simulation.util.VariableJAXBAdapter; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.Date; import java.util.Set; /** * User: jintrone * Date: 2/10/11 * Time: 3:07 PM */ @XmlJavaTypeAdapter(ScenarioJAXBAdapter.class) @XmlRootElement public interface Scenario { public Simulation getSimulation(); public void setSimulation(Simulation sim); public Tuple getVariableValue(Variable v); public Set<Tuple> getValues_(); public Date getCreated(); public void setCreated(Date created); public void setId(Long id); public Long getId(); String getName(); void setName(String name); public String getUser(); public void setUser(String user); }
package c01.todoteamname.project.SPORTCRED; import java.io.IOException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; public class UserRegistration implements HttpHandler { private Neo4JDB neoDB = Neo4JDB.createInstanceOfDatabase(); public UserRegistration() {} @Override public void handle(HttpExchange r) throws IOException { try { if (r.getRequestMethod().equals("POST")) { handlePost(r); } } catch (Exception e) { } } private void handlePost(HttpExchange r) throws IOException, JSONException { String body = Utils.convert(r.getRequestBody()); JSONObject deserialized = new JSONObject(body); boolean checkReq = deserialized.has("username") && deserialized.has("password") && deserialized.has("email") && deserialized.has("answeredQuestions"); if (checkReq) { String username = deserialized.getString("username"); String password = deserialized.getString("password"); String email = deserialized.getString("email"); JSONArray arrayForQuestions = deserialized.getJSONArray("answeredQuestions"); String[] answeredQuestions = new String[arrayForQuestions.length()]; for (int i = 0; i < arrayForQuestions.length(); i++) { answeredQuestions[i] = arrayForQuestions.getString(i); } int returnVal = neoDB.createUser(username, password, email, answeredQuestions); r.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); r.sendResponseHeaders(returnVal, -1); } else { r.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); r.sendResponseHeaders(400, -1); } } }
package com.scp.bean; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonAutoDetect; @XmlRootElement public class User { private String userId; private String userName; public User() { super(); // TODO Auto-generated constructor stub } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Override public String toString() { return "User [userId=" + userId + ", userName=" + userName + "]"; } }
package com.xyz.jdbnk.exception; public class UserAlreadyExistsException extends Exception { private static final long serialVersionUID = -7634767090481356066L; public UserAlreadyExistsException(String message) { super(message); } }
package com.parking.utilities; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.com.parking.beans.LotAndDistance; import com.gimbal.android.sample.R; import java.util.ArrayList; public class LotAdapter extends ArrayAdapter<LotAndDistance> { private Context context; private ArrayList<LotAndDistance> objects; public LotAdapter(Context context, int layoutResourceId, ArrayList<LotAndDistance> objects) { super(context, layoutResourceId, objects); this.context = context; this.objects = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if(row == null) { LayoutInflater inflater = ((Activity)context).getLayoutInflater(); row = inflater.inflate(R.layout.activity_lots, parent, false); LotAndDistance lotAndDistance = objects.get(position); if(lotAndDistance != null) { TextView lotID = (TextView) convertView.findViewById(R.id.lot_id); lotID.setText(lotAndDistance.getLot().getLotID()); TextView lotName = (TextView) convertView.findViewById(R.id.lot_name); lotName.setText(lotAndDistance.getLot().getLotName()); TextView lotDistance = (TextView) convertView.findViewById(R.id.lot_distance); lotDistance.setText(String.format("%s",lotAndDistance.getDistance())); } } return row; } }
/* * Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.engine.bulkops; import java.util.AbstractMap; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pl.edu.icm.unity.db.generic.bulk.ProcessingRuleDB; import pl.edu.icm.unity.engine.bulkops.BulkProcessingSupport.RuleWithTS; import pl.edu.icm.unity.engine.transactions.SqlSessionTL; import pl.edu.icm.unity.exceptions.EngineException; import pl.edu.icm.unity.server.api.internal.TransactionalRunner; import pl.edu.icm.unity.server.bulkops.ScheduledProcessingRule; import pl.edu.icm.unity.utils.ScheduledUpdaterBase; /** * Checks if persisted bulk operations are changed wrt to what is loaded in QuartzScheduler * and if needed updates it. * @author K. Benedyczak */ @Component public class BulkOperationsUpdater extends ScheduledUpdaterBase { @Autowired private ProcessingRuleDB ruleDB; @Autowired private BulkProcessingSupport bulkSupport; @Autowired private TransactionalRunner tx; public BulkOperationsUpdater() { super("bulk entity operations"); } @Override protected void updateInternal() throws EngineException { Collection<RuleWithTS> scheduledRulesWithTS; scheduledRulesWithTS = bulkSupport.getScheduledRulesWithTS(); tx.runInTransaction(() -> { SqlSession sql = SqlSessionTL.get(); Map<String, AbstractMap.SimpleEntry<Date, ScheduledProcessingRule>> rulesInDb = getRuleChangeTime(sql); Set<String> toRemove = new HashSet<>(); Set<AbstractMap.SimpleEntry<Date, ScheduledProcessingRule>> toUpdate = new HashSet<>(); for (RuleWithTS rule: scheduledRulesWithTS) { Map.Entry<Date, ScheduledProcessingRule> fromDb = rulesInDb.remove(rule.rule.getId()); if (fromDb == null) toRemove.add(rule.rule.getId()); else if (!fromDb.getKey().equals(rule.ts)) toUpdate.add(new AbstractMap.SimpleEntry<>(rule.ts, rule.rule)); } for (AbstractMap.SimpleEntry<Date, ScheduledProcessingRule> toAdd: rulesInDb.values()) bulkSupport.scheduleJob(toAdd.getValue(), toAdd.getKey()); for (String removed: toRemove) bulkSupport.undeployJob(removed); for (AbstractMap.SimpleEntry<Date, ScheduledProcessingRule> updated: toUpdate) bulkSupport.updateJob(updated.getValue(), updated.getKey()); }); } private Map<String, AbstractMap.SimpleEntry<Date, ScheduledProcessingRule>> getRuleChangeTime(SqlSession sql) throws EngineException { Map<String, AbstractMap.SimpleEntry<Date, ScheduledProcessingRule>> changedRules = new HashMap<>(); List<Map.Entry<ScheduledProcessingRule, Date>> ruleNames = ruleDB.getAllWithUpdateTimestamps(sql); for (Map.Entry<ScheduledProcessingRule, Date> rule: ruleNames) changedRules.put(rule.getKey().getId(), new AbstractMap.SimpleEntry<>( rule.getValue(), rule.getKey())); return changedRules; } }
package com.learn.dubbo.provider.service; import com.alibaba.dubbo.config.annotation.Service; import com.learn.dubbo.nacos.api.DemoService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.io.Serializable; /** * @program: dubbo-nacos * @description: * @author: zjj * @create: 2020-01-08 15:30 **/ @Slf4j @Component @Service public class DemoServiceImpl implements DemoService{ @Override public String sayHello(String name) { log.info("hello, this is provider's home, can I help you?"); return "hello, this is provider's home, can I help you?"; } }
package lecture02; public class Palindrome { private int value; public Palindrome() { } public int getValue() { return value; } public void setValue(int value) throws NotFiveDigitException, NotPalindromeException { if (value / 10000 < 1 || value / 10000 > 9) { throw new NotFiveDigitException(); } if (!isPalindrome(value)) { throw new NotPalindromeException(); } this.value = value; } private boolean isPalindrome(int newNum) { int tempNum = newNum; int reversedNum = 0; while (tempNum > 0) { reversedNum = reversedNum * 10 + tempNum % 10; tempNum /= 10; } return reversedNum == newNum; } public class NotFiveDigitException extends Exception { public NotFiveDigitException() { super("Number must be 5 digits"); } } public class NotPalindromeException extends Exception { public NotPalindromeException() { super("NotPalindrome"); } } @Override public String toString() { return String.valueOf(value); } }
package com.UBQPageObjectLib; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import com.UBQGenericLib.WebDriverCommonLib; /** * @author Basanagouda * */ public class SyncWithServer extends WebDriverCommonLib { WebDriver driver; // ----------------------Constructor----------------------// public SyncWithServer(WebDriver driver) { this.driver = driver; } // ----------------------UI Elements----------------------// // ---For Entity Code---// @FindBy(how = How.XPATH, using = "//input[@name='chkSynchItem']") private WebElement AllCheckBoxs; // ---For Entity Code---// @FindBy(how = How.XPATH, using = "//input[@id='synchButton']") private WebElement SyncronizeBtn; // ---For Status Msg---// @FindBy(how = How.XPATH, using = "//input[@id='status']") private WebElement StatusMsg; // ----------------------Basic functions----------------------// // ---For Making all check Box Active---// public void MakeAllCheckBoxsChecked() { if (AllCheckBoxs.isEnabled()) { checkboxselect(AllCheckBoxs); } } // ---For Making all check Box Active---// public void ClickonSyncronizeBtn() { buttonClick(SyncronizeBtn); } /*public String waitforstatusMsg() { return waitForTextToAppear("Sync process completed", StatusMsg); }*/ }
package util; import static org.junit.Assert.*; import org.junit.Test; public class RegistrationExpressionTest { private String t1 = "1"; private String t2 = "1 2 3"; private String t3 = "1,2 3"; private String t4 = "2 ,, 5"; private String t5 = " 1 2 "; private String t6 = "3-7"; private String t7 = "7-3"; private String t8 = " c- 10"; private String t9 = "1, 3-6, 12"; private String t10 = "1 3- 6 12"; private String t11 = "1, 3-c10 14"; private String t12 = "1 @Damer 3-c10, 14"; private String t13 = "@seniorer @juniorer 1-3"; @Test public void testWithOneInput() { String[] correctStartNbrs = new String[]{"1"}; EvaluatedExpression evaled = RegistrationExpression.eval(t1); assertTrue(0 == evaled.errorList.size()); for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } } @Test public void testWithWhitespace() { String[] correctStartNbrs = new String[]{"1", "2", "3"}; EvaluatedExpression evaled = RegistrationExpression.eval(t2); assertTrue(0 == evaled.errorList.size()); for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } } @Test public void testWithWhitespaceAndComma() { String[] correctStartNbrs = new String[]{"1", "2", "3"}; EvaluatedExpression evaled = RegistrationExpression.eval(t3); assertTrue(0 == evaled.errorList.size()); for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } } @Test public void testWithTwoCommas() { String[] correctStartNbrs = new String[]{"2", "5"}; EvaluatedExpression evaled = RegistrationExpression.eval(t4); assertTrue(0 == evaled.errorList.size()); for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } } @Test public void testWithTrailingWhitespace() { String[] correctStartNbrs = new String[]{"1", "2"}; EvaluatedExpression evaled = RegistrationExpression.eval(t5); assertTrue(0 == evaled.errorList.size()); for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } } @Test public void testWithInterval() { String[] correctStartNbrs = new String[]{"3", "4", "5", "6", "7"}; EvaluatedExpression evaled = RegistrationExpression.eval(t6); assertTrue(0 == evaled.errorList.size()); for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } } @Test public void testWithInvalidInterval() { String[] wrongStartNbrs = new String[]{"7-3"}; EvaluatedExpression evaled = RegistrationExpression.eval(t7); assertTrue(0 == evaled.evaluatedNbrs.size()); for(int i = 0; i < wrongStartNbrs.length; i++) { assertEquals(wrongStartNbrs[i], evaled.errorList.get(i)); } } @Test public void testWithInvalidIntervalWithNonDigit() { String[] wrongStartNbrs = new String[]{"c-10"}; EvaluatedExpression evaled = RegistrationExpression.eval(t8); assertTrue(0 == evaled.evaluatedNbrs.size()); for(int i = 0; i < wrongStartNbrs.length; i++) { assertEquals(wrongStartNbrs[i], evaled.errorList.get(i)); } } @Test public void testWithMixedInput1() { String[] correctStartNbrs = new String[]{"1", "3", "4", "5", "6", "12"}; EvaluatedExpression evaled = RegistrationExpression.eval(t9); assertTrue(0 == evaled.errorList.size()); for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } } @Test public void testWithMixedInput2() { String[] correctStartNbrs = new String[]{"1", "3", "4", "5", "6", "12"}; EvaluatedExpression evaled = RegistrationExpression.eval(t10); assertTrue(0 == evaled.errorList.size()); for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } } @Test public void testWithMixedInputWithError1() { String[] correctStartNbrs = new String[]{"1", "14"}; String[] wrongStartNbrs = new String[]{"3-c10"}; EvaluatedExpression evaled = RegistrationExpression.eval(t11); for(int i = 0; i < wrongStartNbrs.length; i++) { assertEquals(wrongStartNbrs[i], evaled.errorList.get(i)); } for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } } @Test public void testWithMixedInputWithError2() { String[] correctClasses = new String[]{"Damer"}; String[] correctStartNbrs = new String[]{"1","14"}; String[] wrongStartNbrs = new String[]{"3-c10"}; EvaluatedExpression evaled = RegistrationExpression.eval(t12); for(int i = 0; i < wrongStartNbrs.length; i++) { assertEquals(wrongStartNbrs[i], evaled.errorList.get(i)); } for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } for(int i = 0; i < correctClasses.length; i++) { assertEquals(correctClasses[i], evaled.evaluatedClasses.get(i)); } } @Test public void testWithMixedInput3() { String[] correctClasses = new String[]{"seniorer","juniorer"}; String[] correctStartNbrs = new String[]{"1","2","3"}; EvaluatedExpression evaled = RegistrationExpression.eval(t13); for(int i = 0; i < correctStartNbrs.length; i++) { assertEquals(correctStartNbrs[i], evaled.evaluatedNbrs.get(i)); } for(int i = 0; i < correctClasses.length; i++) { assertEquals(correctClasses[i], evaled.evaluatedClasses.get(i)); } } }
package com.example.u5_pastragram1; public class Post { }
package br.com.fiap.beans; /** * Classe de login no sistema web. Faz a autenticação do usuário * @author Lucas 74795, Mateus 74793, Gustavo 74816, Estevão 74803 * @since 1.0 * @version 3.0 */ public class Login { private String email; private String senha; public Login(String email, String senha) { super(); this.email = email; this.senha = senha; } public Login() { super(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } }
package com.UBQPageObjectLib; public class test { public static void main(String[] args) { String s = "11.0"; s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", ""); System.out.println(s); } }
package com.sunrj.application.System; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class TaskTest { /*@Scheduled(fixedDelay = 5000) */ @Scheduled(cron = "0 39 16 * * ?") public void doSomething() { System.out.println("-----------------定时任务----------------"); } }
package com.example.vibrationcustom; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.wearable.activity.WearableActivity; import android.util.Log; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import java.io.DataInputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.Enumeration; public class ResultScreenActivity extends WearableActivity { private TextView textView; private TextView textView2; private boolean threadCondition = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result_screen); Log.d("ClientStream", getLocalIpAddress()); textView = (TextView) findViewById(R.id.text); textView2 = (TextView) findViewById(R.id.text2); ServerThread thread = new ServerThread(); thread.start(); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Enables Always-on setAmbientEnabled(); } class ServerThread extends Thread { String thisuser; @SuppressLint("HandlerLeak") final Handler handler = new Handler() { @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); if(thisuser.contentEquals("0")) textView2.setText("Attacker"); else textView2.setText("User " + thisuser); } }; @Override public void run() { while (threadCondition) { int port = 4000; try { ServerSocket server = new ServerSocket(port); Log.d("ServerThread", "Server Started."); Socket socket = server.accept(); Log.d("ServerThread", "socket accepted."); DataInputStream instream = new DataInputStream(socket.getInputStream()); int input = instream.read(); thisuser = String.valueOf(input); Log.d("ServerThread", thisuser); Message msg = handler.obtainMessage(); handler.sendMessage(msg); socket.close(); threadCondition = false; } catch (Exception e) { e.printStackTrace(); } } try { ServerThread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } Intent intent = new Intent(getApplicationContext(), MainActivity.class); //지금 액티비티에서 다른 액티비티로 이동하는 인텐트 설정 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //인텐트 플래그 설정 Log.d("TAG", "onBackPressed: clear stack"); startActivity(intent); //인텐트 이동 finish(); //현재 액티비티 종료 } } public static String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } } } } catch (SocketException ex) { ex.printStackTrace(); } return null; } }
package com.foda.campus.ui.activity; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.view.View; import android.widget.AdapterView; import android.widget.RadioGroup; import com.android.volley.error.VolleyError; import com.foda.campus.R; import com.foda.campus.app.ApiClient; import com.foda.campus.model.News; import com.foda.campus.model.NewsData; import com.foda.campus.util.UIHelper; import com.foda.campus.view.EndOfListView; import com.foda.campus.view.PMSwipeRefreshLayout; import com.foda.campus.volley.ResponseListener; import com.lemon.aklib.adapter.BaseAdapterHelper; import com.lemon.aklib.adapter.QuickAdapter; import java.util.ArrayList; import java.util.List; public class NewsActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, EndOfListView.OnEndOfListListener { private static final String TAG = "NewsActivity"; private PMSwipeRefreshLayout pullRefreshLayout; private EndOfListView listView; private QuickAdapter<NewsData> adapter; private List<NewsData> dataList1 = new ArrayList<NewsData>(); private List<NewsData> dataList2 = new ArrayList<NewsData>(); private List<NewsData> dataList3 = new ArrayList<NewsData>(); private RadioGroup radioGroup; // private final static String SEARCH_TYPE_1 = "热点关注"; // private final static String SEARCH_TYPE_2 = "学校新闻"; // private final static String SEARCH_TYPE_3 = "公告信息"; private final static String SEARCH_TYPE_1 = "1"; private final static String SEARCH_TYPE_2 = "2"; private final static String SEARCH_TYPE_3 = "3"; private String search = SEARCH_TYPE_1; private final static int DEFAULT_PAGE = 1; private int page1 = DEFAULT_PAGE; private int page2 = DEFAULT_PAGE; private int page3 = DEFAULT_PAGE; private boolean isFirstLoadingomplete1 = false; private boolean isFirstLoadingomplete2 = false; private boolean isFirstLoadingomplete3 = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_news); initView(); getNews1(); } @Override protected int getActionBarTitle() { return R.string.title_news; } @Override protected boolean hasBackButton() { return true; } private void initView() { adapter = new QuickAdapter<NewsData>(NewsActivity.this, R.layout.listitem_news) { @Override protected void convert(BaseAdapterHelper helper, NewsData item) { helper.setText(R.id.tvTitle, item.title); helper.setText(R.id.tvPublishTime, "发布时间:" + item.publishTime); helper.setText(R.id.tvPublisher, "发布人:" + item.publisher); } }; pullRefreshLayout = (PMSwipeRefreshLayout) findViewById(R.id.pullRefreshLayout); pullRefreshLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); pullRefreshLayout.setOnRefreshListener(this); pullRefreshLayout.setRefreshing(true); listView = (EndOfListView) findViewById(R.id.listView); listView.setOnEndOfListListener(this); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { UIHelper.showNewsDetails(NewsActivity.this, adapter.getItem(position)); } }); radioGroup = (RadioGroup) findViewById(R.id.radioGroup); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rbNews1: search = SEARCH_TYPE_1; if (!dataList1.isEmpty()) { adapter.replaceAll(dataList1); } else { isFirstLoadingomplete1 = true; getNews1(); } break; case R.id.rbNews2: search = SEARCH_TYPE_2; if (!dataList2.isEmpty()) { adapter.replaceAll(dataList2); } else { isFirstLoadingomplete2 = true; getNews2(); } break; case R.id.rbNews3: search = SEARCH_TYPE_3; if (!dataList3.isEmpty()) { adapter.replaceAll(dataList3); } else { isFirstLoadingomplete3 = true; getNews3(); } break; } } }); } @Override public void onRefresh() { if (search.equals(SEARCH_TYPE_1)) { isFirstLoadingomplete1 = false; page1 = DEFAULT_PAGE; getNews1(); } else if (search.equals(SEARCH_TYPE_2)) { isFirstLoadingomplete2 = false; page2 = DEFAULT_PAGE; getNews2(); } else if (search.equals(SEARCH_TYPE_3)) { isFirstLoadingomplete3 = false; page3 = DEFAULT_PAGE; getNews3(); } } @Override public void onEndOfList(Object lastItem) { if (search.equals(SEARCH_TYPE_1)) { if (isFirstLoadingomplete1) { adapter.showIndeterminateProgress(true); if (dataList1.size() < 5) { return; } page1++; getNews1(); } } else if (search.equals(SEARCH_TYPE_2)) { if (isFirstLoadingomplete2) { adapter.showIndeterminateProgress(true); if (dataList2.size() < 5) { return; } page2++; getNews2(); } } else if (search.equals(SEARCH_TYPE_3)) { if (isFirstLoadingomplete3) { adapter.showIndeterminateProgress(true); if (dataList3.size() < 5) { return; } page3++; getNews3(); } } } private void showIndeterminateProgress(boolean visibility) { adapter.showIndeterminateProgress(visibility); } private void getNews1() { ApiClient.getNewsList(TAG, page1, search, new ResponseListener() { @Override public void onStarted() { if (page1 != DEFAULT_PAGE) { return; } if (!pullRefreshLayout.isRefreshing()) { pullRefreshLayout.setRefreshing(true); } } @Override public void onResponse(Object response) { if (page1 != DEFAULT_PAGE) { showIndeterminateProgress(false); } pullRefreshLayout.setRefreshing(false); isFirstLoadingomplete1 = true; List<NewsData> list = ((News) response).items; if (page1 == DEFAULT_PAGE) { dataList1 = list; } else { dataList1.addAll(list); } adapter.replaceAll(dataList1); } @Override public void onErrorResponse(VolleyError volleyError) { showIndeterminateProgress(false); pullRefreshLayout.setRefreshing(false); } }); } private void getNews2() { ApiClient.getNewsList(TAG, page2, search, new ResponseListener() { @Override public void onStarted() { if (page2 != DEFAULT_PAGE) { return; } if (!pullRefreshLayout.isRefreshing()) { pullRefreshLayout.setRefreshing(true); } } @Override public void onResponse(Object response) { if (page1 != DEFAULT_PAGE) { showIndeterminateProgress(false); } pullRefreshLayout.setRefreshing(false); isFirstLoadingomplete2 = true; List<NewsData> list = ((News) response).items; if (page2 == DEFAULT_PAGE) { dataList2 = list; } else { dataList2.addAll(list); } adapter.replaceAll(dataList2); } @Override public void onErrorResponse(VolleyError volleyError) { showIndeterminateProgress(false); pullRefreshLayout.setRefreshing(false); } }); } private void getNews3() { ApiClient.getNewsList(TAG, page3, search, new ResponseListener() { @Override public void onStarted() { if (page3 != DEFAULT_PAGE) { return; } if (!pullRefreshLayout.isRefreshing()) { pullRefreshLayout.setRefreshing(true); } } @Override public void onResponse(Object response) { if (page3 != DEFAULT_PAGE) { showIndeterminateProgress(false); } pullRefreshLayout.setRefreshing(false); isFirstLoadingomplete3 = true; List<NewsData> list = ((News) response).items; if (page3 == DEFAULT_PAGE) { dataList3 = list; } else { dataList3.addAll(list); } adapter.replaceAll(dataList3); } @Override public void onErrorResponse(VolleyError volleyError) { showIndeterminateProgress(false); pullRefreshLayout.setRefreshing(false); } }); } }
package alien4cloud.model.components; import java.util.Map; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor public class ComplexPropertyValue extends PropertyValue<Map<String, Object>> { public ComplexPropertyValue(Map<String, Object> value) { super(value); } }
package com.beike.dao.trx.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.List; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; import com.beike.common.entity.trx.TrxLog; import com.beike.common.enums.trx.TrxLogType; import com.beike.common.enums.trx.TrxlogSubType; import com.beike.dao.GenericDaoImpl; import com.beike.dao.trx.TrxLogDao; import com.beike.util.EnumUtil; /** * @Title: TrxLogDaoImpl.java * @Package com.beike.dao * @Description: 交易相关业务日志,运营使用 * @date Jun 30, 2011 5:18:10 PM * @author wh.cheng * @version v1.0 */ @Repository("trxLogDao") public class TrxLogDaoImpl extends GenericDaoImpl<TrxLog, Long> implements TrxLogDao { public Long addTrxLog(final TrxLog trxLog) { KeyHolder keyHolder = new GeneratedKeyHolder(); if (trxLog == null) { throw new IllegalArgumentException("trxLog not null"); } else { final StringBuffer sb = new StringBuffer(); sb.append("insert into beiker_trxlog(trx_goods_sn,create_date,trxlog_type,log_title,log_content,trxlog_sub_type) value(?,?,?,?,?,?)"); this.getJdbcTemplate().update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(sb.toString(), new String[] { "trx_goods_sn", "create_date", "trxlog_type", "log_title","log_content","trxlog_sub_type" }); ps.setString(1, trxLog.getTrxGoodsSn()); ps.setTimestamp(2, new Timestamp(trxLog.getCreateDate() .getTime())); ps.setString(3, EnumUtil.transEnumToString(trxLog .getTrxLogType())); ps.setString(4,trxLog.getLogTitle()); ps.setString(5, trxLog.getLogContent()); ps.setString(6, EnumUtil.transEnumToString(trxLog.getTrxlogSubType())); return ps; } }, keyHolder); } Long trxLogId = keyHolder.getKey().longValue(); return trxLogId; } public void updateTrxLog(Long id,String content){ if(id==null){ throw new IllegalArgumentException(); } String upSql="update beiker_trxlog set log_content=? where id=?"; this.getSimpleJdbcTemplate().update(upSql,content,id); } public TrxLog findTtxLogById(Long id){ if(id ==null){ throw new IllegalArgumentException("id is not null"); } String qrySql="select id,trx_goods_sn,create_date,trxlog_type,log_content,log_title,trxlog_sub_type from beiker_trxlog where id=?"; List<TrxLog> trxLogList=this.getSimpleJdbcTemplate().query(qrySql,new RowMapperImpl(), id); if(trxLogList.size()>0){ return trxLogList.get(0); } return null; } protected class RowMapperImpl implements ParameterizedRowMapper<TrxLog> { public TrxLog mapRow(ResultSet rs, int rowNum) throws SQLException { TrxLog trxLog = new TrxLog(); trxLog.setId(rs.getLong("id")); trxLog.setTrxGoodsSn(rs.getString("trx_goods_sn")); trxLog.setCreateDate(rs.getTimestamp("create_date")); trxLog.setTrxLogType(EnumUtil.transStringToEnum(TrxLogType.class,rs.getString("trxlog_type"))); trxLog.setLogContent(rs.getString("log_content")); trxLog.setLogTitle(rs.getString("log_title")); trxLog.setTrxlogSubType(EnumUtil.transStringToEnum(TrxlogSubType.class,rs.getString("trxlog_sub_type"))); return trxLog; } } }
package org.study.admin; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.study.member.MemberVO; @Repository public class ScheduleDAO { @Autowired private SqlSession sqlSession; public List<ScheduleVO> selectSchedule(int movie_code) throws Exception { List<ScheduleVO> results = sqlSession.selectList("org.study.schedule.selectSchedule", movie_code); return results; } //예약가능 날짜 public List<ScheduleVO> selectSchedule_date() throws Exception { List<ScheduleVO> listSchedule_date = sqlSession.selectList("org.study.schedule.selectSchedule_date"); return listSchedule_date; } //예약가능스케줄 출력 public List<ScheduleVO> reserveSelectDay() throws Exception { List<ScheduleVO> listSchedule = sqlSession.selectList("org.study.schedule.reserveSelectDay"); return listSchedule; } public List<ScheduleVO> reserveSelectTime(String movie_code, String cinema_code, String day) throws Exception{ Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("movie_code", movie_code); paramMap.put("cinema_code", cinema_code); paramMap.put("day", day); List<ScheduleVO> listSchedule = sqlSession.selectList("org.study.schedule.reserveSelectTime", paramMap); return listSchedule; } public ScheduleVO reserveSelectSchedule(String schedule_code) throws Exception{ ScheduleVO scheduleInfo = sqlSession.selectOne("org.study.schedule.reserveSelectSchedule", schedule_code); return scheduleInfo; } public void insert(ScheduleVO scheduleVO) throws Exception { sqlSession.insert("org.study.schedule.insert", scheduleVO); } public MovieVO selectByCode(int movie_code) throws Exception { List<MovieVO> results = sqlSession.selectList("org.study.schedule.selectByCode", movie_code); return results.isEmpty() ? null : results.get(0); } public List<CinemaVO> selectAll() throws Exception { List<CinemaVO> results = sqlSession.selectList("org.study.schedule.selectCinema"); return results; } public List<CinemaRoomVO> selectRoom(int cinema_code) throws Exception { List<CinemaRoomVO> results = sqlSession.selectList("org.study.schedule.selectRoom",cinema_code); return results; } public void delete(int schedule_code) throws Exception { sqlSession.delete("org.study.schedule.deleteSchedule", schedule_code); } }
package com.zc.pivas.printlabel.controller; import com.google.gson.Gson; import com.zc.base.common.controller.SdDownloadController; import com.zc.base.common.exception.ExceptionCodeConstants; import com.zc.base.common.exception.SdExceptionFactory; import com.zc.base.common.util.StrUtil; import com.zc.base.orm.mybatis.paging.JqueryStylePaging; import com.zc.base.orm.mybatis.paging.JqueryStylePagingResults; import com.zc.base.sc.modules.batch.entity.Batch; import com.zc.base.sc.modules.batch.repository.BatchDao; import com.zc.base.sc.modules.batch.service.BatchService; import com.zc.base.sys.common.util.DefineCollectionUtil; import com.zc.pivas.inpatientarea.bean.InpatientAreaBean; import com.zc.pivas.inpatientarea.dao.InpatientAreaDAO; import com.zc.pivas.inpatientarea.service.InpatientAreaService; import com.zc.pivas.medicaments.entity.Medicaments; import com.zc.pivas.medicaments.service.MedicamentsService; import com.zc.pivas.medicamentscategory.entity.MedicCategory; import com.zc.pivas.medicamentscategory.repository.MedicCategoryDao; import com.zc.pivas.medicamentslabel.entity.MedicLabel; import com.zc.pivas.medicamentslabel.repository.MedicLabelDao; import com.zc.pivas.printlabel.entity.PrintLabelConBean; import com.zc.pivas.printlabel.service.PrintLabelConService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 瓶签条件配置控制类 * * @author kunkka * @version 1.0 */ @Controller() @RequestMapping(value = "/printLabelCon") public class PrintLabelConController extends SdDownloadController { /** * 业务异常工厂 */ @Resource private SdExceptionFactory sdExceptionFactory; @Resource private BatchService batchService; @Resource private InpatientAreaDAO inpatientAreaDAO; @Resource private MedicCategoryDao medicCategoryDao; @Resource private MedicamentsService medicamentsService; @Resource private MedicLabelDao medicLabelDao; @Resource private PrintLabelConService printLabelConService; @Resource private BatchDao batchDao; @Resource private InpatientAreaService inpatientAreaService; @RequestMapping("/initBottleLabelCon") public String init(Model model) { // 批次列表 List<Batch> batchList = batchService.queryByPaging(null, null); // 药品分类列表 List<MedicCategory> medicCategories = medicCategoryDao.queryAllMedicCategory(); // 获取药品标签 List<MedicLabel> medicLabelList = medicLabelDao.listMedicLabel(null, new JqueryStylePaging()); model.addAttribute("batchList", batchList); model.addAttribute("medicCategoryList", medicCategories); model.addAttribute("medicLabelList", medicLabelList); return "pivas/bottleLabel/printLabelConList"; } /** * 初始化所有下拉列表数据 * * @return */ @RequestMapping("/querySelectDatareq") @ResponseBody public String querySelectDatareq() { Map<String, Object> map = new HashMap<String, Object>(); // // 批次列表 // List<Batch> batchList = batchService.queryByPaging(null, null); // // // 药品分类列表 // List<MedicCategory> medicCategories = medicCategoryDao.queryAllMedicCategory(); // // // 获取药品标签 // List<MedicLabel> medicLabelList = medicLabelDao.listMedicLabel(null, new JqueryStylePaging()); // // InpatientAreaBean bean = new InpatientAreaBean(); // bean.setEnabled("1"); // List<InpatientAreaBean> inpatientAreaList = inpatientAreaService.getInpatientAreaBeanList(bean,new JqueryStylePaging()); // // map.put("batchList", batchList); // map.put("medicCategoryList", medicCategories); // map.put("medicLabelList", medicLabelList); // map.put("inpatientAreaList", inpatientAreaList); map.put("success", true); return new Gson().toJson(map); } /*** * 查询所有数据 * @param * @param jquryStylePaging 分页参数 * @return json字符串 * @throws Exception 系统异常 */ @RequestMapping(value = "/printBottleLabelList", produces = "application/json") @ResponseBody public String printLabelConList(PrintLabelConBean bean, JqueryStylePaging jquryStylePaging) throws Exception { JqueryStylePagingResults<PrintLabelConBean> pagingResults = printLabelConService.queryPrintLabelConList(bean, jquryStylePaging); return new Gson().toJson(pagingResults); } /** * 添加 * * @param bean 添加数据 * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/addPrtLabelCon", produces = "application/json") @ResponseBody public String addPrintLabelCon(PrintLabelConBean bean) throws Exception { // 判断名称是否存在 List<PrintLabelConBean> printLabelConList = printLabelConService.queryPrintLabelCon(bean); try { if (DefineCollectionUtil.isNotEmpty(printLabelConList)) { throw sdExceptionFactory.createSdException(ExceptionCodeConstants.NAME_REPEAT, null, null); } else { int count = printLabelConService.getCountOrder(bean); if (count > 0) { return buildFailJsonMsg("优先级重复"); } printLabelConService.insert(bean); // addOperLog(AmiLogConstant.MODULE_BRANCH.CF.TRIAL_ERROR_TYPE, // AmiLogConstant.BRANCH_SYSTEM.CF, // getMessage("log.errortype.tip.add", new String[] {bean.getName()}), // true); } return buildSuccessJsonMsg(messageHolder.getMessage("common.op.success")); } catch (Exception e) { // addOperLog(AmiLogConstant.MODULE_BRANCH.CF.TRIAL_ERROR_TYPE, // AmiLogConstant.BRANCH_SYSTEM.CF, // getMessage("log.errortype.tip.add", new String[] {bean.getName()}), // false); throw e; } } /*** * * 初始化 * @return json字符串 */ @RequestMapping(value = "/initUpdateprtLabelCon", produces = "application/json") @ResponseBody public String initUpdateprintLabelCon(PrintLabelConBean bean) { List<PrintLabelConBean> printLabelConList = printLabelConService.queryPrintLabelCon(bean); if (DefineCollectionUtil.isEmpty(printLabelConList)) { throw sdExceptionFactory.createSdException(ExceptionCodeConstants.RECORD_DELETE, null, null); } PrintLabelConBean printLabelCon = printLabelConList.get(0); if (StrUtil.isNotNull(printLabelCon.getBatchid())) { String[] batchIDs = printLabelCon.getBatchid().split(","); String batchName = ""; for (String batch : batchIDs) { batchName = batchDao.selectByPrimaryKey(Long.valueOf(batch)).getName() + "," + batchName; } printLabelCon.setBatchName(batchName.substring(0, batchName.length() - 1)); } if (StrUtil.isNotNull(printLabelCon.getMedicCategoryID())) { String[] medicCategoryIDs = printLabelCon.getMedicCategoryID().split(","); String medicCategory = ""; MedicCategory category = null; for (String medicCategoryID : medicCategoryIDs) { category = new MedicCategory(); category.setCategoryId(Long.valueOf(medicCategoryID)); medicCategory = medicCategoryDao.listMedicCategory(category, new JqueryStylePaging()).get(0).getCategoryName() + "," + medicCategory; } printLabelCon.setMedicCategory(medicCategory.substring(0, medicCategory.length() - 1)); } if (StrUtil.isNotNull(printLabelCon.getMedicLabelID())) { String[] mediclabelIDs = printLabelCon.getMedicLabelID().split(","); String mediclabelName = ""; MedicLabel mediclabel = null; for (String mediclabelID : mediclabelIDs) { mediclabel = new MedicLabel(); mediclabel.setLabelId(Long.valueOf(mediclabelID)); mediclabelName = medicLabelDao.listMedicLabel(mediclabel, new JqueryStylePaging()).get(0).getLabelName() + "," + mediclabelName; } printLabelCon.setMediclabel(mediclabelName.substring(0, mediclabelName.length() - 1)); } if (StrUtil.isNotNull(printLabelCon.getMedicalID())) { String[] medicalIDs = printLabelCon.getMedicalID().split(","); String medicalIDName = ""; for (String medicalID : medicalIDs) { medicalIDName = medicamentsService.getMediclByCode(medicalID).getMedicamentsName() + "," + medicalIDName; } printLabelCon.setMedical(medicalIDName.substring(0, medicalIDName.length() - 1)); } if (StrUtil.isNotNull(printLabelCon.getDeptCode())) { String[] deptCodes = printLabelCon.getDeptCode().split(","); String deptName = ""; InpatientAreaBean inpatientArea = null; for (String deptCode : deptCodes) { inpatientArea = new InpatientAreaBean(); inpatientArea.setDeptCode(deptCode); deptName = inpatientAreaService.getInpatientAreaBean(inpatientArea).getDeptName() + "," + deptName; } printLabelCon.setDeptName(deptName.substring(0, deptName.length() - 1)); } return new Gson().toJson(printLabelCon); } /** * 修改 * * @param bean 修改数据 * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/updatePrtLabelCon", produces = "application/json") @ResponseBody public String updatePrintLabelCon(PrintLabelConBean bean) throws Exception { // 判断名称是否存在 boolean isExist = printLabelConService.checkPrintLabelConName(bean); try { if (isExist) { throw sdExceptionFactory.createSdException(ExceptionCodeConstants.NAME_REPEAT, null, null); } else { if ("false".equals(bean.getIsSame())) { int count = printLabelConService.getCountOrder(bean); if (count > 0) { return buildFailJsonMsg("优先级重复"); } } printLabelConService.updatePrintLabelCon(bean); // addOperLog(AmiLogConstant.MODULE_BRANCH.CF.TRIAL_ERROR_TYPE, // AmiLogConstant.BRANCH_SYSTEM.CF, // getMessage("log.errortype.tip.update", new String[] {bean.getName()}), // true); return buildSuccessJsonMsg(messageHolder.getMessage("common.op.success")); } } catch (Exception e) { // addOperLog(AmiLogConstant.MODULE_BRANCH.CF.TRIAL_ERROR_TYPE, // AmiLogConstant.BRANCH_SYSTEM.CF, // getMessage("log.errortype.tip.update", new String[] {bean.getName()}), // false); throw e; } } /** * 删除 * * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/delprtLabelCon", produces = "application/json") @ResponseBody public String delprintLabelCon(String id) throws Exception { try { printLabelConService.delPrintLabelCon(id.split(",")); // addOperLog(AmiLogConstant.MODULE_BRANCH.CF.TRIAL_ERROR_TYPE, // AmiLogConstant.BRANCH_SYSTEM.CF, // getMessage("log.errortype.tip.del", new String[] {gid}), // true); return buildSuccessJsonMsg(messageHolder.getMessage("common.op.success")); } catch (Exception e) { // addOperLog(AmiLogConstant.MODULE_BRANCH.CF.TRIAL_ERROR_TYPE, // AmiLogConstant.BRANCH_SYSTEM.CF, // getMessage("log.errortype.tip.del", new String[] {gid}), // false); throw e; } } /** * 查询批次信息 * * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/qryBatchs", produces = "application/json") @ResponseBody public String queryBatchs() throws Exception { String[] columns = new String[]{"num", "name"}; JqueryStylePagingResults<Batch> results = new JqueryStylePagingResults<Batch>(columns); List<Batch> datas = batchService.queryByPaging(new JqueryStylePaging(), new Batch()); // 总数 Integer total = null; if (null != datas) { results.setDataRows(datas); total = datas.size(); } results.setTotal(total); return new Gson().toJson(results); } /** * 查询药品分类信息 * * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/qryMedicCategorys", produces = "application/json") @ResponseBody public String queryMedicCategorys() throws Exception { String[] columns = new String[]{"categoryId", "categoryName"}; JqueryStylePagingResults<MedicCategory> results = new JqueryStylePagingResults<MedicCategory>(columns); List<MedicCategory> datas = medicCategoryDao.qryMedicCategory(); // 总数 Integer total = null; if (null != datas) { results.setDataRows(datas); total = datas.size(); } results.setTotal(total); return new Gson().toJson(results); } /** * 查询药品标签信息 * * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/qryMedicLabels", produces = "application/json") @ResponseBody public String queryMedicLabels() throws Exception { String[] columns = new String[]{"labelId", "labelName"}; JqueryStylePagingResults<MedicLabel> results = new JqueryStylePagingResults<MedicLabel>(columns); List<MedicLabel> datas = medicLabelDao.listMedicLabel(new MedicLabel(), new JqueryStylePaging()); // 总数 Integer total = null; if (null != datas) { results.setDataRows(datas); total = datas.size(); } results.setTotal(total); return new Gson().toJson(results); } /** * 查询药品溶媒信息 * * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/qryMedicals", produces = "application/json") @ResponseBody public String queryMedicals() throws Exception { String[] columns = new String[]{"medicamentsCode", "medicamentsName"}; JqueryStylePagingResults<Medicaments> results = new JqueryStylePagingResults<Medicaments>(columns); Medicaments medicament = new Medicaments(); medicament.setMedicamentsMenstruum(1); List<Medicaments> datas = medicamentsService.queryByPaging(new JqueryStylePaging(), medicament); // 总数 Integer total = null; if (null != datas) { results.setDataRows(datas); total = datas.size(); } results.setTotal(total); return new Gson().toJson(results); } /** * 查询病区信息 * * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/qryDepts", produces = "application/json") @ResponseBody public String queryDepts() throws Exception { String[] columns = new String[]{"deptCode", "deptName"}; JqueryStylePagingResults<InpatientAreaBean> results = new JqueryStylePagingResults<InpatientAreaBean>(columns); InpatientAreaBean bean = new InpatientAreaBean(); bean.setEnabled("1"); List<InpatientAreaBean> inpatientAreaList = inpatientAreaService.getInpatientAreaBeanList(bean, new JqueryStylePaging()); // 总数 Integer total = null; if (null != inpatientAreaList) { results.setDataRows(inpatientAreaList); total = inpatientAreaList.size(); } results.setTotal(total); return new Gson().toJson(results); } }
package br.com.julianocelestino.persistence; import org.hibernate.dialect.PostgreSQL9Dialect; import java.sql.Types; public class MyPostgreSQL9Dialect extends PostgreSQL9Dialect { public MyPostgreSQL9Dialect() { this.registerColumnType(Types.JAVA_OBJECT, "json"); } }
package com.maliang.core.exception; import java.util.Map; import com.maliang.core.arithmetic.AE; import com.maliang.core.arithmetic.function.Function; public class ReturnException extends RuntimeException { private static final long serialVersionUID = 1L; private final Function function; public ReturnException(Function fun){ super(fun.getExpression()); this.function = fun; } public Object excute(Map<String,Object> params) { System.out.println(" return es : " + this.function.expression); return this.function.executeExpression(params); } public static void main(String[] args) { String s = "{list:['111','222','3333']}"; Map<String,Object> params = (Map<String,Object>)AE.execute(s); s = "if(true) {{h:22,c2:i.set(99),c:44,g:55,p:return(i)}}else {return('bbbbb')}"; Object val = AE.execute(s,params); System.out.println("---- val : " + val); s = ""; } }
package uz.otash.shop.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; import uz.otash.shop.entity.Brand; import uz.otash.shop.projections.CustomBrand; @RepositoryRestResource(path = "brand",collectionResourceRel = "objs",excerptProjection = CustomBrand.class) public interface BrandRepository extends JpaRepository<Brand,Integer> { @RestResource(path = "nameStartsWith", rel = "nameStartsWith") public Page findByNameStartsWith(@Param("name") String name, Pageable p); }
/** * FileName: ClientHandler * Author: yangqinkuan * Date: 2019-1-22 15:54 * Description: */ package com.ice.find.client; import com.alibaba.fastjson.JSONObject; import com.ice.find.client.childhandle.ChildFacade; import com.ice.find.message.BusenessMessage; import com.ice.find.message.Header; import com.ice.find.message.MessageFactory; import com.ice.find.message.NettyMessage; import com.ice.find.utils.enums.EventType; import io.netty.channel.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClientHandler extends ChannelInboundHandlerAdapter { private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); private ChildFacade childFacade = new ChildFacade(); @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { BusenessMessage busenessMessage = JSONObject.parseObject((String) msg,BusenessMessage.class); logger.info("msgid{}--body{}",busenessMessage.getMessageId(), msg.toString()); childFacade.childHandle(busenessMessage); //childFacade.childHandle(busenessMessage); } catch (Exception e) { logger.info("accept msg error ctxid{},exception{}",ctx.channel().id().asShortText(),e); ctx.close(); } } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { logger.info("通道开始注册"); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { logger.info("通道激活"); ClientVariables.channel = ctx.channel(); ctx.writeAndFlush(MessageFactory.getMessageByte(EventType.CON_REQ,null,ClientVariables.clientId)); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.info("失去连接......."); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error("发送错误"+cause); cause.printStackTrace(); ctx.close(); } private NettyMessage getNettyMessage(){ NettyMessage nettyMessage = new NettyMessage(); Header header = new Header(); header.setLength(1234); header.setSessionID(123125124); String str = "这是一条消息"; nettyMessage.setBody(str); return nettyMessage; } }
package com.example.databindingtest.util; import androidx.databinding.Observable; import androidx.databinding.PropertyChangeRegistry; import androidx.lifecycle.ViewModel; /** * @author hy * @Date 2019/10/23 0023 * <p> * An [Observable] [ViewModel] for Data Binding. **/ @SuppressWarnings("unused") public class ObservableViewModel extends ViewModel implements Observable { private PropertyChangeRegistry callBacks = new PropertyChangeRegistry(); @Override public void addOnPropertyChangedCallback(OnPropertyChangedCallback callback) { callBacks.add(callback); } @Override public void removeOnPropertyChangedCallback(OnPropertyChangedCallback callback) { callBacks.remove(callback); } /** * 通知监听器此实例的所有属性均已更改。 */ public void notifyChange() { callBacks.notifyCallbacks(this, 0, null); } /** * 通知侦听器某个特定属性已更改,属性的getter方法应该被标记为 [Bindable] 来在' BR '中生成一个字段作为' fieldId '使用。 */ public void notifyPropertyChanged(int fieldId) { callBacks.notifyCallbacks(this, fieldId, null); } }
package org.itstep; public class Triangle extends Shape { private int heigh; private int baseLine; public int getHeigh() { return heigh; } public void setHeigh(int heigh) { this.heigh = heigh; } public int getBaseLine() { return baseLine; } public void setBaseLine(int baseLine) { this.baseLine = baseLine; } }
package org.sales.controller; import org.sales.model.Product; import org.sales.util.*; import java.sql.*; import org.sales.util.DBConnection; import java.util.*;//for List And array Lists public class ProductDAO { public int insertData(Product ob) { int count=0; try { Connection con=DBConnection.getConnection(); String sql="insert into product(name,price,qty,remarks)values(?,?,?,?)"; PreparedStatement st=con.prepareStatement(sql); st.setString(1,ob.getName()); st.setDouble(2,ob.getPrice()); st.setInt(3,ob.getQty()); st.setString(4,ob.getRemarks()); count= st.executeUpdate(); con.close(); } catch(Exception ex) { System.out.println(ex); } return count; } public List<Product> fetchData() { List<Product> productList=new ArrayList(); try { Connection con=DBConnection.getConnection(); String sql="select * from product"; Statement st=con.createStatement(); ResultSet rs=st.executeQuery(sql); while(rs.next()) { Product ob=new Product(); ob.setId(rs.getInt("id")); ob.setName(rs.getString("name")); ob.setPrice(rs.getDouble("price")); ob.setQty(rs.getInt("qty")); ob.setRemarks(rs.getString("remarks")); productList.add(ob); } con.close(); } catch(Exception ex) { System.out.println(ex); } return productList; } public int updateData(Product ob) { int count=0; try { Connection con=DBConnection.getConnection(); String sql="update product set name=?,price=?,qty=?,remarks=? where id=?"; PreparedStatement st=con.prepareStatement(sql); st.setString(1,ob.getName()); st.setDouble(2,ob.getPrice()); st.setInt(3,ob.getQty()); st.setString(4,ob.getRemarks()); st.setInt(5,ob.getId()); count= st.executeUpdate(); con.close(); } catch(Exception ex) { System.out.println(ex); } return count; } public int deleteData(Product ob) { int count=0; try { Connection con=DBConnection.getConnection(); String sql="delete from product where id=?"; PreparedStatement st=con.prepareStatement(sql); // st.setString(1,ob.getName()); // st.setDouble(2,ob.getPrice()); // st.setInt(3,ob.getQty()); // st.setString(4,ob.getRemarks()); st.setInt(1,ob.getId()); count= st.executeUpdate(); con.close(); } catch(Exception ex) { System.out.println(ex); } return count; } //for sell product public Product fetchData(int id) { Product ob=new Product(); try { Connection con=DBConnection.getConnection(); String sql="select * from product where id=? and qty>0"; PreparedStatement st=con.prepareStatement(sql); st.setInt(1, id); ResultSet rs=st.executeQuery(); if(rs.next()) { ob.setId(rs.getInt("id")); ob.setName(rs.getString("name")); ob.setPrice(rs.getDouble("price")); } con.close(); } catch(Exception ex) { System.out.println(ex); } return ob; } public int getQty(int id,Connection con) { int qty=0; try { String sql="select qty from product where id=?"; PreparedStatement pst=con.prepareStatement(sql); pst.setInt(1,id); ResultSet rs=pst.executeQuery(); while(rs.next()) { qty=rs.getInt("qty"); } }catch(Exception ex) { System.out.println(ex); } return qty; } public void updateQty(int id,int newQty,Connection con) { try { String sql="update product set qty=? where id=?"; PreparedStatement pst=con.prepareStatement(sql); pst.setInt(1,newQty); pst.setInt(2,id); pst.execute(); } catch(Exception ex) { System.out.println(ex); } } }
package tictactoe; import javax.swing.JOptionPane; public class Tester { public static void main(String[] args) { String[][] Board = {{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}}; GameClass Game = new GameClass(Board); int L = 1; String userName; userName = JOptionPane.showInputDialog(" Please enter your name"); JOptionPane.showMessageDialog(null, "Greetings " + userName + "!" + "\n" + "I'm glad you want to play Tic-Tac-Toe" + "\n" + "\n" + "\n" + "This game is very simple, all you have to do its choose where you want to put your 'X'" + "\n" + "and compete against the computer, the rules are the same as a conventional Tic-Tac-Toe game" + "\n" + "\n" + "So lets get started!"); JOptionPane.showMessageDialog(null, "Every time you choose a position the Tic-Tac-Toe board will be updated on the console"); while (Game.status == false) { Game.playerTurn(); Game.BoardLook(Board); Game.computerTurn(); Game.BoardLook(Board); } }}
package breakout; import javafx.scene.Group; import javafx.scene.control.Label; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.BackgroundImage; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; /** * This class is used to display the player's level, score, and number of lives left * In order to use this class, call the setup method, and then call the included methods to change one part of the display (level, score or lives). */ public class StatusDisplay { public static final int STATUS_BAR_HEIGHT = 20; public static final int STARTING_LIVES = 3; public static final int STARTING_LEVEL = 0; Text levelText; Text scoreText; Text livesText; private int level; private int score; private int lives; private Group root; private Rectangle statusBarOutline; StatusDisplay(Group root){ this.root = root; } /** * This method sets up the statusDisplay and adds children to the root * If screenWidth is negative, this method may fail * @param screenWidth this is the width of the game window in pixels * */ public void setup(int screenWidth){ level = STARTING_LEVEL; score = 0; lives = STARTING_LIVES; levelText = new Text(" Level: "+ level); textSetup(levelText, 0); scoreText = new Text("Score: "+ score); textSetup(scoreText, screenWidth/2 - scoreText.getBoundsInParent().getWidth()/2); livesText = new Text("Lives: "+ lives); textSetup(livesText, screenWidth- scoreText.getBoundsInParent().getWidth()); statusBarOutline = new Rectangle(0, 0, screenWidth, STATUS_BAR_HEIGHT); statusBarOutline.setFill(Color.BLACK); root.getChildren().add(statusBarOutline); root.getChildren().add(levelText); root.getChildren().add(scoreText); root.getChildren().add(livesText); } /** * This method sets up the text for each portion of the status display * @param text this is the Text object you wish to setup * @param x this is the x coordinates to place the Text object */ public void textSetup(Text text, double x){ text.setX(x); text.setY(15); text.setFill(Color.GREEN); text.setStroke(Color.GREEN); } /** * This method could be used to update the number of lives the user has in the status display * @param lives the number to set the user's ives to. */ public void updateLives(int lives){ livesText.setText("Lives: "+ lives); } /** * This method takes one life away from the user, and updates the status display accordingly * */ public void loseLife(){ lives = lives - 1; livesText.setText("Lives: "+ lives); } /** * This method gives the user one extra life, and updates the status display accordingly */ public void extraLife(){ lives = lives + 1; livesText.setText("Lives: "+ lives); } /** * This method updates the level, and updates the status display accordingly * @param level this is the level the user wishes to go to */ public void setLevel(int level){ this.level = level; levelText.setText("Level: " + level); } /** * This method adds points to the score, and updates the status display accordingly * @param pointsAdded this is the number of points to add to the user's score */ public void updateScore(int pointsAdded){ score+= pointsAdded; scoreText.setText("Score: " + score); } /** * This method returns the current level * @return the current level */ public int getLevel(){ return level; } /** * This method returns the height of the status display * @return the height of the status display as an int */ public int getStatusBarHeight(){ return STATUS_BAR_HEIGHT; } /** * This method returns the number of lives the user has * @return the number of lives the user has as an int */ public int getLives(){ return lives; } /** * This method resets the status display to the default values */ public void reset(){ level = 0; levelText.setText("Level: " + level); score = 0; scoreText.setText("Score: " + score); lives = STARTING_LIVES; livesText.setText("Lives: "+ lives); } /** * This method returns the user's current score * @return the users current score as an int */ public int getScore(){ return score; } }
package com.zimu.ao.item.equipment; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import com.zimu.ao.character.AbstractChar; public class BasicArmor extends Equipment { public BasicArmor() throws SlickException { super("BasicArmor", 150, new Image("resource/image/item/basicarmor.gif"), new Image("resource/image/item/basicarmor_label.jpg"), new Image("resource/image/item/basicarmor_desc.jpg")); this.equipmentType = ARMOR; this.armorDefence = 5; this.health = 10; } @Override public void equip(AbstractChar character) { } }