text
stringlengths
10
2.72M
package zm.gov.moh.common.submodule.form.model.widgetModel; public class CodedConceptWidgetModel extends AbstractCodedConceptWidgetModel { public CodedConceptWidgetModel(){ super(); } }
/** * Created by SeAxiAoD on 2019/11/12. */ import java.util.Random; public class Main { public static void main(String[] args){ /************************ Step 1: Initialization ***********************/ SpinalEncoder encoder = new SpinalEncoder(4,32,6,1); SpinalDecoder decoder = new SpinalDecoder(4,32,6,1, 16, 1); String message128 = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567"; // String message = "11111111"; byte[] message_bytes = message128.getBytes(); /************************ Step 2: Decoding ***********************/ long start_time = System.currentTimeMillis(); byte[] symbols = encoder.encode(message_bytes); long encoding_time = System.currentTimeMillis(); /************************ Step 3: Disturbance ***********************/ // System.out.println(symbols[62]); // symbols[60] = -76; /************************ Step 4: Decoding ***********************/ byte[] decoded_symbols = decoder.decode(symbols); long decoding_time = System.currentTimeMillis(); System.out.printf("Message\t\t\tDecoded message\n"); for (int i = 0; i < decoded_symbols.length; i++) { System.out.printf("%d\t\t\t%d\n", message_bytes[i], decoded_symbols[i]); } /************************ Step 5: Output ***********************/ System.out.println("Encoding cost:"); System.out.println(encoding_time - start_time); System.out.println("Decoding cost:"); System.out.println(decoding_time - encoding_time); } }
package ru.Makivay.sandbox.searcher; /** * Created by makivay on 14.02.17. */ public class Expression { private final Type type; private final String text; private final int position; private final int minLength; private final int maxLength; public Expression(Type type, String text, int exprPosition) { this.type = type; this.text = text; this.position = exprPosition; this.minLength = 0; this.maxLength = text.length(); } public Expression(Type type, String text, int position, int minLength, int maxLength) { this.type = type; this.text = text; this.position = position; this.minLength = minLength; this.maxLength = maxLength; } public Type getType() { return type; } public String getText() { return text; } public int getPosition() { return position; } public int getMaxLength() { return maxLength; } public int getMinLength() { return minLength; } enum Type {String, Any} }
package day2; public class PalindromeNumber { public static void main(String[] args) { System.out.println(isPalindrome(12321)); } public static boolean isPalindrome(long num){ long remain = num; //12321 long rev =0; while(remain != 0){ long digit = remain % 10; rev = rev * 10 + digit; remain /= 10; } return num == rev; } }
package com.tencent.mm.pluginsdk.ui; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import com.tencent.mm.R; import com.tencent.mm.sdk.platformtools.af; import com.tencent.mm.ui.base.h; public final class j { public static boolean eY(final Context context) { if (!af.Wp("network_doctor_shown")) { return false; } h.a(context, R.l.network_doctor, R.l.app_tip, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { context.startActivity(new Intent("android.settings.WIRELESS_SETTINGS")); } }, null); return true; } }
package com.JoyUCUU.testng; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.BeforeClass; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeSuite; import org.testng.annotations.AfterSuite; public class NewTest { /** * 除了以下几种方法还有 * @Factory 作为一个工厂,返回testNG的测试类对象,该方法必须返回Object[] * @Listeners 定义一个测试类的监听器 * @parameters 介绍如何将参数传递给@Test方法 */ @Test(dataProvider = "dp") /** * 测试类或者方法 * @param n * @param s */ public void f(Integer n, String s) { System.out.println("this is @Test " + n + "\t" + s); } @BeforeMethod /** * 注解的方法运行次数与@Test个数有关,运行@Test前运行,如果有N个@Test运行N次 */ public void beforeMethod() { System.out.println("This is @BeforeMethod"); } @AfterMethod /** * 注解的方法运行次数与@Test个数有关,运行@Test后运行,如果有N个@Test运行N次 */ public void afterMethod() { System.out.println("This is @AfterMethod"); } @DataProvider /** * 为一个方法提供数据,必须返回Object[][],如果一个方法想获取数据,必须用dataProvider接收数据 * @return */ public Object[][] dp() { System.out.println("This is @DataProvider"); return new Object[][] { new Object[] { 1, "a" }, new Object[] { 2, "b" }, }; } @BeforeClass /** * 注释的方法只运行一次,运行在此套件类前 */ public void beforeClass() { System.out.println("This is @BeforeClass"); } @AfterClass /** * 注释的方法只运行一次,运行在此套件类后 */ public void afterClass() { System.out.println("This is @AfterClass"); } @BeforeTest /** * 注释的方法只运行一次,运行在此套件前 */ public void beforeTest() { System.out.println("This is @BeforeTest"); } @AfterTest /** * 注释的方法只运行一次,运行在此套件后 */ public void afterTest() { System.out.println("This is @AfterTest"); } @BeforeSuite /** * 注释的方法只运行一次,运行此套件中所有测试方法前运行 */ public void beforeSuite() { System.out.println("This is @BeforeSuite"); } @AfterSuite /** * 注释的方法只运行一次,运行完此套件的所有测试方法后运行 */ public void afterSuite() { System.out.println("This is @AfterSuite"); } }
package alkamli.fahad.teammanagment.teammanagment.requests.task; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import alkamli.fahad.teammanagment.teammanagment.CommonFunctions; public class AssignTaskToUserRequest { private String adminSession; private int userId; private ArrayList<Integer> taskIds; public String getAdminSession() { return adminSession; } public void setAdminSession(String adminSession) { if(CommonFunctions.clean(adminSession) ==null || CommonFunctions.clean(adminSession).length()<1) { return; } this.adminSession = adminSession; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public AssignTaskToUserRequest() { super(); // TODO Auto-generated constructor stub } public ArrayList<Integer> getTaskIds() { return taskIds; } public void setTaskIds(ArrayList<Integer> taskIds) { if(taskIds == null || taskIds.size()<1) { return; } this.taskIds = taskIds; } public AssignTaskToUserRequest(String adminSession, int userId, ArrayList<Integer> taskIds) { super(); this.adminSession = adminSession; this.userId = userId; this.taskIds = taskIds; } public String getJson(AssignTaskToUserRequest request) { try{ ObjectMapper mapper = new ObjectMapper(); String jsonInString = mapper.writeValueAsString(request); return jsonInString; }catch(Exception e) { System.out.println(e.getMessage()); } return null; } }
package myPkg.lecture; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; public class LectureDAO { private Connection conn = null; private static LectureDAO instance; private LectureDAO() throws Exception { System.out.println("LectureDAO()"); Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup("java:/comp/env"); DataSource ds = (DataSource)envContext.lookup("jdbc/OracleDB"); conn = ds.getConnection(); //System.out.println("conn:" + conn); } // 积己磊 public static LectureDAO getInstance() throws Exception { if(instance == null) { instance = new LectureDAO(); } return instance; } // 寇何狼 按眉 茄锅 积己 public ArrayList<LectureVO> getAllLecture() throws SQLException { ArrayList<LectureVO> list = new ArrayList<LectureVO>(); String sql = "select * from lecture order by num"; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while(rs.next()) { LectureVO vo = new LectureVO(); vo.setNum(rs.getInt("num")); vo.setName( rs.getString("name")); vo.setTeacher( rs.getString("teacher")); vo.setStuNo(rs.getString("stuNo")); vo.setMaxcount(rs.getInt("maxcount")); vo.setLec_date(rs.getString("lec_date")); vo.setTime(rs.getString("time")); vo.setContext(rs.getString("context")); list.add(vo); } return list; } // getAllLecture public int insertLecture(LectureVO lv) throws SQLException { int cnt = -1; String sql = "insert into lecture values(lec_seq.nextval,?,?,'',20,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, lv.getName()); ps.setString(2, lv.getTeacher()); ps.setString(3, lv.getLec_date()); ps.setString(4, lv.getTime()); ps.setString(5, lv.getContext()); cnt = ps.executeUpdate(); System.out.println("insert cnt: "+cnt); return cnt; } // insertLecture public LectureVO getLectureByNum(String num) throws SQLException { LectureVO vo = null; String sql = "select * from lecture where num="+num; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if(rs.next()) { vo = new LectureVO(); vo.setNum(rs.getInt("num")); vo.setName(rs.getString("name")); vo.setTeacher(rs.getString("teacher")); vo.setStuNo(rs.getString("stuNo")); vo.setMaxcount(rs.getInt("maxcount")); vo.setLec_date(rs.getString("lec_date")); vo.setTime(rs.getString("time")); vo.setContext(rs.getString("context")); } return vo; } // getLectureByNum public int getAllCount() throws SQLException { int count = 0; String sql = "select count(*) cnt from lecture"; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if(rs.next()) { count = rs.getInt("cnt"); } return count; } // getAllCount public int updateLecture(LectureVO vo) throws SQLException { int cnt = -1; String sql = "update lecture set name=?, teacher=?, lec_date=?, time=?, context=? where num=?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, vo.getName()); ps.setString(2, vo.getTeacher()); ps.setString(3, vo.getLec_date()); ps.setString(4, vo.getTime()); ps.setString(5, vo.getContext()); ps.setInt(6, vo.getNum()); cnt = ps.executeUpdate(); return cnt; } // updateLecture public int deleteLecture(String num) throws SQLException { int cnt = -1; String sql = "delete from lecture where num="+num; PreparedStatement ps = conn.prepareStatement(sql); cnt = ps.executeUpdate(); return cnt; } // deleteLecture public ArrayList<LectureVO> getLectureByTeacher(String t) throws SQLException { ArrayList<LectureVO> list = new ArrayList<LectureVO>(); System.out.println(t); String sql = "select * from lecture where teacher=? order by num"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, t); ResultSet rs = ps.executeQuery(); while(rs.next()) { LectureVO vo = new LectureVO(); vo.setNum(rs.getInt("num")); vo.setName( rs.getString("name")); vo.setTeacher( rs.getString("teacher")); vo.setStuNo(rs.getString("stuNo")); vo.setMaxcount(rs.getInt("maxcount")); vo.setLec_date(rs.getString("lec_date")); vo.setTime(rs.getString("time")); vo.setContext(rs.getString("context")); list.add(vo); } return list; } // getLectureByTeacher public int updateLecturebynum(String num, String stu) throws SQLException { int cnt = -1; System.out.println("Dao class "+num+"/"+stu); String sql = "select * from lecture where num="+num; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if(rs.next()) { System.out.println(rs.getString("stuNo")); if(rs.getString("stuNo") == null || !rs.getString("stuNo").contains(stu)) { sql = "update lecture set stuNo=? where num=?"; ps = conn.prepareStatement(sql); if(rs.getString("stuNo") == null ) { stu = stu + ""; } else if(!rs.getString("stuNo").contains(stu)) { stu += rs.getString("StuNo"); } ps.setString(1, stu); ps.setString(2, num); cnt = ps.executeUpdate(); } } return cnt; } // updateLecturebynum }
package jzoffer; /** * 二维数组中的查找 * * 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到 * 下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 * * @author ZhaoJun * @date 2019/7/25 17:55 */ public class Solution1 { public boolean Find(int target, int[][] array) { int rowCount = array.length; int colCount = array[0].length; for (int i = rowCount - 1, j = 0; j < colCount && i >= 0; ) { if (target == array[i][j]) { return true; } else if (target < array[i][j]) { i--; } else if (target > array[i][j]) { j++; } } return false; } }
package net.plazmix.core.api; import net.plazmix.core.api.common.command.CommandArgumentBuilder; import net.plazmix.core.api.common.command.CommandBuilder; import net.plazmix.core.api.service.Service; import java.util.List; import java.util.logging.Logger; /** * @author MasterCapeXD */ public interface CoreApi { <T extends Service> T getService(Class<T> serviceClass); <T extends Service> void registerService(Class<T> serviceClass, T serviceImpl, boolean autoEnable); Iterable<Service> getServices(); Logger getLogger(); CommandBuilder newCommand(String name); CommandBuilder newCommand(String holder, String name); CommandArgumentBuilder newCommandArgument(String name); String colorize(String str); List<String> colorize(List<String> stringList); }
package se.jaitco.queueticketapi.service; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.*; import org.springframework.security.core.userdetails.UserDetails; import se.jaitco.queueticketapi.model.Roles; import se.jaitco.queueticketapi.model.User; import java.util.Arrays; import java.util.Optional; import static org.hamcrest.CoreMatchers.is; public class UserDetailsServiceImplTest { @InjectMocks private final UserDetailsServiceImpl classUnderTest = new UserDetailsServiceImpl(); @Mock private UserService userService; @Before public void setup() { MockitoAnnotations.initMocks(this); } @Test public void testLoadUserByUsername() { final String userName = "USERNAME"; Mockito.when(userService.getUser(Matchers.anyString())) .thenReturn(Optional.of(User.builder() .username(userName) .password("Fotboll") .grantedRoles(Arrays.asList(Roles.CUSTOMER)) .build())); UserDetails userDetails = classUnderTest.loadUserByUsername(userName); Assert.assertThat(userDetails.getUsername(), is(userName)); Mockito.verify(userService, Mockito.times(1)) .getUser(userName); } }
package ru.bm.eetp.controler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import ru.bm.eetp.config.ConfigProperties; import ru.bm.eetp.dto.ProcessResult; import ru.bm.eetp.dto.RequestResult; import java.net.URI; import java.net.URISyntaxException; import static ru.bm.eetp.config.Constants.*; import static ru.bm.eetp.config.Utils.getDummyURL; @Component public class InternalServiceCallerImpl implements InternalServiceCaller { @Autowired private ConfigProperties configProperties; @Autowired private RestServiceCaller<String> restServiceCaller; @Override public RequestResult callInternalService(ProcessResult processResult, String body){ URI uri = getURI(processResult != ProcessResult.OK); restServiceCaller.call(body, uri); return restServiceCaller.getRequestResult(); } @Override public RequestResult getRequestResult(){ return restServiceCaller.getRequestResult(); } public URI getURI(boolean isError){ String url; if (DEBUG){ //если включен DEBUG url = getDummyURL(); } else{ //обычгая ветвь исполнения if (isError){ url = configProperties.internal_error_url; } else { url = configProperties.internal_ok_url; } } try { return new URI(url); } catch (URISyntaxException e) { return null; } } }
package com.forsrc.cxf.server.restful.login.service; import com.forsrc.exception.NoSuchUserException; import com.forsrc.exception.PasswordNotMatchException; import com.forsrc.exception.ServiceException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; /** * The interface Login cxf service. */ @Service @Transactional public interface LoginCxfService { /** * Login. * * @param soapMessage the soap message * @throws SOAPException the soap exception * @throws ServiceException the service exception */ @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) public void login(SOAPMessage soapMessage) throws SOAPException, ServiceException; }
package com.boot.web.inf; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(name="boot-service") public interface ServiceInterface { @RequestMapping(value = "/test/test",method = RequestMethod.GET) public String test(String isWho); }
package exercicio_214; import java.util.Scanner; public class Exercicio_214 { public static void main(String[] args) { Scanner teclado = new Scanner(System.in); double soma_media, media, media_total,nota1,nota2; String nome; System.out.println("Calcula a media de duas notas dos alunos de uma sala"); System.out.println("Calcula a media geral de uma sala"); soma_media = 0.0; for (int i=1 ;i<=10;i++){ System.out.println("Informe o nome do aluno: "); nome = teclado.next(); System.out.println("Informe a nota P1: "); nota1 = teclado.nextDouble(); System.out.println("Informe a nota P2: "); nota2 = teclado.nextDouble(); media = (nota1 + nota2)/2.0; soma_media += media; System.out.println("O aluno "+nome+", teve media: "+media); } media_total = soma_media /10.0; System.out.println("A media geral foi de: "+ media_total); } }
package cn.com.ykse.santa.common.functions; import java.io.IOException; /** * Created by youyi on 2016/1/20. */ @FunctionalInterface public interface Action4<P1, P2, P3, P4> { void invoke(P1 var1, P2 var2, P3 var3, P4 var4) throws IOException; }
package br.com.univag.service; import br.com.univag.dao.UsuarioDao; import br.com.univag.dominio.PerfilUsuario; import br.com.univag.exception.DaoException; import br.com.univag.model.UsuarioVo; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; /** * * @author CRISTIANO */ public class UsuarioService { private Connection con; private List<PerfilUsuario> perfil; public UsuarioService() { } public void salvar(UsuarioVo usuario) throws DaoException { String senhaGerada = usuario.getSenha(); String senhaMd5 = convertMD5(usuario.getSenha()); usuario.setSenha(senhaMd5); new UsuarioDao(con).salvarUsuarioVo(usuario); usuario.setSenha(senhaGerada); enviarSenhaPorEmail(usuario); } public String convertMD5(String nome) { MessageDigest mdigest; try { mdigest = MessageDigest.getInstance("MD5"); byte[] valorMd5 = mdigest.digest(nome.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : valorMd5) { sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3)); } System.out.println("A senha criptografada é:" + sb.toString()); return sb.toString(); } catch (NoSuchAlgorithmException e) { System.out.println("Erro de criptografia"); e.getMessage(); return null; } catch (UnsupportedEncodingException e) { System.out.println("Erro de criptografia02"); e.getMessage(); return null; } } public String geraSenha() { String[] novaSenha = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; String senha = ""; for (int x = 0; x < 5; x++) { int j = (int) (Math.random() * novaSenha.length); senha += novaSenha[j]; } System.out.println("A senha gerada é:" + senha); return senha; } @SuppressWarnings("deprecation") public void enviarSenhaPorEmail(UsuarioVo usuario) { System.out.println("Iniciando envio de Emails"); SimpleEmail emailSimples = new SimpleEmail(); System.out.println("Executou SimpleEmail"); emailSimples.setHostName("smtp.gmail.com"); System.out.println("passou pelo setHostName"); emailSimples.setSmtpPort(465); System.out.println("setSmtpPort"); try { emailSimples.setFrom("tad2013estacionamento@gmail.com", "Univag"); System.out.println("setFrom"); emailSimples.addTo(usuario.getEmail(), "Usuario"); System.out.println("addTo"); emailSimples.setSubject("Dados de Acesso ao Sistema.");// assunto System.out.println("setSubject"); emailSimples.setMsg("SENHA DE ACESSO AO SISTEMA : " + usuario.getSenha() + "\n EMAIL DE LOGIN : " + usuario.getEmail());// mensagem System.out.println("setMsg"); emailSimples.setSSL(true); System.out.println("setSSL"); emailSimples.setAuthentication("tad2013estacionamento@gmail.com", "jamaissabera");// dados // do // email System.out.println("setAuthentication"); System.out.println("Iniciar o envio"); emailSimples.send(); System.out.println("Email foi enviado com sucesso"); } catch (EmailException e) { System.out.println("erro de envio de email"); } } public int verificarUsuarioVo(UsuarioVo vo) throws DaoException { UsuarioDao dao = new UsuarioDao(con); UsuarioVo usuarioCpf = dao.consutarUsuarioPorCpf(vo.getCpf()); UsuarioVo usuarioemail = dao.consultarUsuarioEmail(vo.getEmail()); if (usuarioCpf != null || usuarioemail != null) { if (usuarioCpf != null && usuarioemail != null) { return 3; } else if (usuarioCpf != null) { return 1; } else if (usuarioemail != null) { return 2; } } return 0; } /* SimpleEmail email = new SimpleEmail(); email.setSSLOnConnect(true); email.setHostName( "smtp.seudominio.com.br" ); email.setSslSmtpPort( "465" ); email.setAuthenticator( new DefaultAuthenticator( "rodrigo@seudominio.com.br" , "1234" ) ); try { email.setFrom( "rodrigo@seudominio.com.br"); email.setDebug(true); email.setSubject( "Assunto do E-mail" ); email.setMsg( "Texto sem formatação" ); email.addTo( "rodrigoaramburu@gmail.com" );//por favor trocar antes de testar!!!! email.send(); } catch (EmailException e) { e.printStackTrace(); } */ /** * @return the perfil */ public List<PerfilUsuario> getPerfil() { return Arrays.asList(PerfilUsuario.values()); } /** * @param perfil the perfil to set */ public void setPerfil(List<PerfilUsuario> perfil) { this.perfil = perfil; } /** * @param con the con to set */ public void setCon(Connection con) { this.con = con; } public List<UsuarioVo> listUsuario(int valor) throws DaoException { List<UsuarioVo> list = new UsuarioDao(con).listaUsuarioVo(valor); return list; } public int quantidadePaginas() throws DaoException { double total = new UsuarioDao(con).totalUsuarioVo(); if (total <= 10) { return 1; } int resultado = (int) Math.ceil(total / 10); return resultado; } public int quantidadeRegistros() throws DaoException { int total = new UsuarioDao(con).totalUsuarioVo(); return total; } public UsuarioVo selecionaUserById(int codigo) throws DaoException { UsuarioVo vo = new UsuarioVo(); vo = new UsuarioDao(con).selectUsuarioById(codigo); return vo; } public void AlterarPerfilUser(UsuarioVo vo) throws DaoException { new UsuarioDao(con).updateUsuarioVoPerfil(vo); } public void deleteUserById(int codigo) throws DaoException { new UsuarioDao(con).deleteUser(codigo); } public UsuarioVo autenticarUser(String usuario, String senha) throws DaoException { UsuarioDao dao = new UsuarioDao(con); String senhaMd5 = convertMD5(senha); UsuarioVo vo = dao.autenticarUsuarioVo(usuario, senhaMd5); return vo; } public void recuperUserByEmail(UsuarioVo vo) throws DaoException { String senhaNova = geraSenha(); vo.setSenha(senhaNova); enviarSenhaPorEmail(vo); String cript = convertMD5(vo.getSenha()); vo.setSenha(cript); new UsuarioDao(con).updateUsuarioVoSenha(vo); } public UsuarioVo selecionarUserByEmail(String email) throws DaoException { UsuarioVo usuario = new UsuarioDao(con).consultarUsuarioEmail(email); return usuario; } public List<UsuarioVo> pesquisaUsuarioService(UsuarioVo vo) throws DaoException { List<UsuarioVo> list = new ArrayList<>(); UsuarioVo usuario = null; if (vo.getEmail() != null) { usuario = new UsuarioDao(con).consultarUsuarioEmail(vo.getEmail()); if (usuario != null) { list.add(usuario); } } else if (vo.getCpf() != null) { usuario = new UsuarioDao(con).consutarUsuarioPorCpf(vo.getCpf()); if (usuario != null) { list.add(usuario); } } return list; } public void updateSenhaUsuarioVoPerfil(UsuarioVo vo) throws DaoException{ UsuarioDao dao = new UsuarioDao(con); if(!vo.getSenha().equals("")){ String senhaCript = convertMD5(vo.getSenha()); String nome = vo.getNome()+" "+vo.getSobrenome(); vo.setNome(nome.trim()); vo.setSenha(senhaCript); dao.updateUsuarioVoPerfil(vo); dao.updateUsuarioVoSenha(vo); } else{ String nome = vo.getNome()+" "+vo.getSobrenome(); vo.setNome(nome.trim()); dao.updateUsuarioVoPerfil(vo); } } }
package bean; public class InfoMessageComment { private int im_id; private int u_id; private String im_reply_content; private String im_reply_time; private String u_name; private String icon; public int getIm_id() { return im_id; } public void setIm_id(int im_id) { this.im_id = im_id; } public int getU_id() { return u_id; } public void setU_id(int u_id) { this.u_id = u_id; } public String getIm_reply_content() { return im_reply_content; } public void setIm_reply_content(String im_reply_content) { this.im_reply_content = im_reply_content; } public String getIm_reply_time() { return im_reply_time; } public void setIm_reply_time(String im_reply_time) { this.im_reply_time = im_reply_time; } public String getU_name() { return u_name; } public void setU_name(String u_name) { this.u_name = u_name; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public InfoMessageComment(String im_reply_content, String im_reply_time, String u_name, String icon) { super(); this.im_reply_content = im_reply_content; this.im_reply_time = im_reply_time; this.u_name = u_name; this.icon = icon; } public InfoMessageComment(int im_id, int u_id, String im_reply_content, String im_reply_time, String u_name, String icon) { super(); this.im_id = im_id; this.u_id = u_id; this.im_reply_content = im_reply_content; this.im_reply_time = im_reply_time; this.u_name = u_name; this.icon = icon; } public InfoMessageComment(int im_id, int u_id, String im_reply_content, String im_reply_time) { super(); this.im_id = im_id; this.u_id = u_id; this.im_reply_content = im_reply_content; this.im_reply_time = im_reply_time; } }
package edu.buet.cse.spring.ch02; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import edu.buet.cse.spring.ch02.model.Performer; public class App10 { public static void main(String... args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("/edu/buet/cse/spring/ch02/spring-beans.xml"); Performer lank = (Performer) appContext.getBean("lank"); lank.perform(); } }
package com.tencent.mm.plugin.webview.ui.tools; import com.tencent.mm.plugin.webview.ui.tools.WebViewUI.23; import com.tencent.mm.sdk.platformtools.bi; class WebViewUI$23$27 implements Runnable { final /* synthetic */ boolean gnL; final /* synthetic */ 23 pZM; final /* synthetic */ boolean qae; WebViewUI$23$27(23 23, boolean z, boolean z2) { this.pZM = 23; this.qae = z; this.gnL = z2; } public final void run() { if (this.qae) { if (!(this.pZM.pZJ.mhH == null || bi.oW(this.pZM.pZJ.mhH.getUrl()))) { WebViewUI.e(this.pZM.pZJ).put(this.pZM.pZJ.mhH.getUrl(), Boolean.valueOf(false)); } this.pZM.pZJ.ka(false); return; } if (!(this.pZM.pZJ.mhH == null || bi.oW(this.pZM.pZJ.mhH.getUrl()))) { WebViewUI.e(this.pZM.pZJ).put(this.pZM.pZJ.mhH.getUrl(), Boolean.valueOf(this.gnL)); } this.pZM.pZJ.ka(this.gnL); } }
package cn.timebusker.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import io.swagger.annotations.Api; @Api("SwaggerController接口测试") @Controller @RequestMapping("/api") public class SwaggerController { @RequestMapping(value="",method = RequestMethod.GET) public String swagger() { return "index"; } }
package android.support.v7.widget; import android.content.Context; import android.content.res.Configuration; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.support.v7.view.menu.ActionMenuItemView; import android.support.v7.view.menu.f; import android.support.v7.view.menu.h; import android.support.v7.view.menu.m; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewDebug.ExportedProperty; import android.view.accessibility.AccessibilityEvent; public class ActionMenuView extends LinearLayoutCompat implements android.support.v7.view.menu.f.b, m { private Context Jn; private int KA; private int KP; ActionMenuPresenter KQ; private android.support.v7.view.menu.l.a KR; private android.support.v7.view.menu.f.a KS; private boolean KT; private int KU; private int KV; private d KW; boolean Kr; f bq; public interface a { boolean dA(); boolean dz(); } public interface d { boolean onMenuItemClick(MenuItem menuItem); } public static class LayoutParams extends android.support.v7.widget.LinearLayoutCompat.LayoutParams { @ExportedProperty public boolean KY; @ExportedProperty public int KZ; @ExportedProperty public int La; @ExportedProperty public boolean Lb; @ExportedProperty public boolean Lc; boolean Ld; public LayoutParams(Context context, AttributeSet attributeSet) { super(context, attributeSet); } public LayoutParams(android.view.ViewGroup.LayoutParams layoutParams) { super(layoutParams); } public LayoutParams(LayoutParams layoutParams) { super(layoutParams); this.KY = layoutParams.KY; } public LayoutParams() { super(-2, -2); this.KY = false; } } private class b implements android.support.v7.view.menu.l.a { private b() { } /* synthetic */ b(ActionMenuView actionMenuView, byte b) { this(); } public final void a(f fVar, boolean z) { } public final boolean d(f fVar) { return false; } } private class c implements android.support.v7.view.menu.f.a { private c() { } /* synthetic */ c(ActionMenuView actionMenuView, byte b) { this(); } public final boolean a(f fVar, MenuItem menuItem) { return ActionMenuView.this.KW != null && ActionMenuView.this.KW.onMenuItemClick(menuItem); } public final void b(f fVar) { if (ActionMenuView.this.KS != null) { ActionMenuView.this.KS.b(fVar); } } } public ActionMenuView(Context context) { this(context, null); } public ActionMenuView(Context context, AttributeSet attributeSet) { super(context, attributeSet); setBaselineAligned(false); float f = context.getResources().getDisplayMetrics().density; this.KA = (int) (56.0f * f); this.KV = (int) (f * 4.0f); this.Jn = context; this.KP = 0; } public void setPopupTheme(int i) { if (this.KP != i) { this.KP = i; if (i == 0) { this.Jn = getContext(); } else { this.Jn = new ContextThemeWrapper(getContext(), i); } } } public int getPopupTheme() { return this.KP; } public void setPresenter(ActionMenuPresenter actionMenuPresenter) { this.KQ = actionMenuPresenter; this.KQ.a(this); } public void onConfigurationChanged(Configuration configuration) { if (VERSION.SDK_INT >= 8) { super.onConfigurationChanged(configuration); } if (this.KQ != null) { this.KQ.n(false); if (this.KQ.isOverflowMenuShowing()) { this.KQ.hideOverflowMenu(); this.KQ.showOverflowMenu(); } } } public void setOnMenuItemClickListener(d dVar) { this.KW = dVar; } protected void onMeasure(int i, int i2) { boolean z = this.KT; this.KT = MeasureSpec.getMode(i) == 1073741824; if (z != this.KT) { this.KU = 0; } int size = MeasureSpec.getSize(i); if (!(!this.KT || this.bq == null || size == this.KU)) { this.KU = size; this.bq.p(true); } int childCount = getChildCount(); int i3; LayoutParams layoutParams; if (!this.KT || childCount <= 0) { for (i3 = 0; i3 < childCount; i3++) { layoutParams = (LayoutParams) getChildAt(i3).getLayoutParams(); layoutParams.rightMargin = 0; layoutParams.leftMargin = 0; } super.onMeasure(i, i2); return; } int mode = MeasureSpec.getMode(i2); size = MeasureSpec.getSize(i); int size2 = MeasureSpec.getSize(i2); i3 = getPaddingLeft() + getPaddingRight(); int paddingTop = getPaddingTop() + getPaddingBottom(); int childMeasureSpec = getChildMeasureSpec(i2, paddingTop, -2); int i4 = size - i3; int i5 = i4 / this.KA; size = i4 % this.KA; if (i5 == 0) { setMeasuredDimension(i4, 0); return; } View childAt; int i6; int d; Object obj; int i7; int i8 = this.KA + (size / i5); int i9 = 0; int i10 = 0; int i11 = 0; i3 = 0; Object obj2 = null; long j = 0; int childCount2 = getChildCount(); int i12 = 0; while (i12 < childCount2) { childAt = getChildAt(i12); if (childAt.getVisibility() != 8) { boolean z2 = childAt instanceof ActionMenuItemView; i6 = i3 + 1; if (z2) { childAt.setPadding(this.KV, 0, this.KV, 0); } layoutParams = (LayoutParams) childAt.getLayoutParams(); layoutParams.Ld = false; layoutParams.La = 0; layoutParams.KZ = 0; layoutParams.Lb = false; layoutParams.leftMargin = 0; layoutParams.rightMargin = 0; z = z2 && ((ActionMenuItemView) childAt).hasText(); layoutParams.Lc = z; d = d(childAt, i8, layoutParams.KY ? 1 : i5, childMeasureSpec, paddingTop); i10 = Math.max(i10, d); if (layoutParams.Lb) { i3 = i11 + 1; } else { i3 = i11; } if (layoutParams.KY) { obj = 1; } else { obj = obj2; } i7 = i5 - d; int max = Math.max(i9, childAt.getMeasuredHeight()); if (d == 1) { j = ((long) (1 << i12)) | j; i11 = i3; i9 = max; } else { i11 = i3; i9 = max; } } else { obj = obj2; i6 = i3; i7 = i5; } i12++; obj2 = obj; i3 = i6; i5 = i7; } Object obj3 = (obj2 == null || i3 != 2) ? null : 1; Object obj4 = null; long j2 = j; d = i5; while (i11 > 0 && d > 0) { i6 = Integer.MAX_VALUE; j = 0; i5 = 0; size = 0; while (true) { int i13 = size; if (i13 >= childCount2) { break; } layoutParams = (LayoutParams) getChildAt(i13).getLayoutParams(); if (layoutParams.Lb) { if (layoutParams.KZ < i6) { i5 = layoutParams.KZ; j = (long) (1 << i13); size = 1; i6 = i5; } else if (layoutParams.KZ == i6) { j |= (long) (1 << i13); size = i5 + 1; } i13++; } size = i5; i13++; } j2 |= j; if (i5 > d) { break; } i7 = i6 + 1; i6 = 0; i5 = d; while (i6 < childCount2) { View childAt2 = getChildAt(i6); layoutParams = (LayoutParams) childAt2.getLayoutParams(); if ((((long) (1 << i6)) & j) != 0) { if (obj3 != null && layoutParams.Lc && i5 == 1) { childAt2.setPadding(this.KV + i8, 0, this.KV, 0); } layoutParams.KZ++; layoutParams.Ld = true; size = i5 - 1; } else if (layoutParams.KZ == i7) { j2 |= (long) (1 << i6); size = i5; } else { size = i5; } i6++; i5 = size; } obj4 = 1; d = i5; } j = j2; obj = (obj2 == null && i3 == 1) ? 1 : null; if (d <= 0 || j == 0 || (d >= i3 - 1 && obj == null && i10 <= 1)) { obj3 = obj4; } else { float f; float bitCount = (float) Long.bitCount(j); if (obj == null) { if (!((1 & j) == 0 || ((LayoutParams) getChildAt(0).getLayoutParams()).Lc)) { bitCount -= 0.5f; } if (!((((long) (1 << (childCount2 - 1))) & j) == 0 || ((LayoutParams) getChildAt(childCount2 - 1).getLayoutParams()).Lc)) { f = bitCount - 0.5f; i3 = f <= 0.0f ? (int) (((float) (d * i8)) / f) : 0; i5 = 0; obj3 = obj4; while (i5 < childCount2) { if ((((long) (1 << i5)) & j) != 0) { View childAt3 = getChildAt(i5); layoutParams = (LayoutParams) childAt3.getLayoutParams(); if (childAt3 instanceof ActionMenuItemView) { layoutParams.La = i3; layoutParams.Ld = true; if (i5 == 0 && !layoutParams.Lc) { layoutParams.leftMargin = (-i3) / 2; } obj = 1; } else if (layoutParams.KY) { layoutParams.La = i3; layoutParams.Ld = true; layoutParams.rightMargin = (-i3) / 2; obj = 1; } else { if (i5 != 0) { layoutParams.leftMargin = i3 / 2; } if (i5 != childCount2 - 1) { layoutParams.rightMargin = i3 / 2; } } i5++; obj3 = obj; } obj = obj3; i5++; obj3 = obj; } } } f = bitCount; if (f <= 0.0f) { } i5 = 0; obj3 = obj4; while (i5 < childCount2) { if ((((long) (1 << i5)) & j) != 0) { View childAt32 = getChildAt(i5); layoutParams = (LayoutParams) childAt32.getLayoutParams(); if (childAt32 instanceof ActionMenuItemView) { layoutParams.La = i3; layoutParams.Ld = true; if (i5 == 0 && !layoutParams.Lc) { layoutParams.leftMargin = (-i3) / 2; } obj = 1; } else if (layoutParams.KY) { layoutParams.La = i3; layoutParams.Ld = true; layoutParams.rightMargin = (-i3) / 2; obj = 1; } else { if (i5 != 0) { layoutParams.leftMargin = i3 / 2; } if (i5 != childCount2 - 1) { layoutParams.rightMargin = i3 / 2; } } i5++; obj3 = obj; } obj = obj3; i5++; obj3 = obj; } } if (obj3 != null) { size = 0; while (true) { i3 = size; if (i3 >= childCount2) { break; } childAt = getChildAt(i3); layoutParams = (LayoutParams) childAt.getLayoutParams(); if (layoutParams.Ld) { childAt.measure(MeasureSpec.makeMeasureSpec(layoutParams.La + (layoutParams.KZ * i8), 1073741824), childMeasureSpec); } size = i3 + 1; } } if (mode == 1073741824) { i9 = size2; } setMeasuredDimension(i4, i9); } static int d(View view, int i, int i2, int i3, int i4) { boolean z; int i5; boolean z2 = false; LayoutParams layoutParams = (LayoutParams) view.getLayoutParams(); int makeMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(i3) - i4, MeasureSpec.getMode(i3)); ActionMenuItemView actionMenuItemView = view instanceof ActionMenuItemView ? (ActionMenuItemView) view : null; if (actionMenuItemView == null || !actionMenuItemView.hasText()) { z = false; } else { z = true; } if (i2 <= 0 || (z && i2 < 2)) { i5 = 0; } else { view.measure(MeasureSpec.makeMeasureSpec(i * i2, Integer.MIN_VALUE), makeMeasureSpec); int measuredWidth = view.getMeasuredWidth(); i5 = measuredWidth / i; if (measuredWidth % i != 0) { i5++; } if (z && i5 < 2) { i5 = 2; } } if (!layoutParams.KY && z) { z2 = true; } layoutParams.Lb = z2; layoutParams.KZ = i5; view.measure(MeasureSpec.makeMeasureSpec(i5 * i, 1073741824), makeMeasureSpec); return i5; } protected void onLayout(boolean z, int i, int i2, int i3, int i4) { if (this.KT) { LayoutParams layoutParams; int measuredWidth; int paddingLeft; int i5; int childCount = getChildCount(); int i6 = (i4 - i2) / 2; int dividerWidth = getDividerWidth(); int i7 = 0; int paddingRight = ((i3 - i) - getPaddingRight()) - getPaddingLeft(); Object obj = null; boolean bv = at.bv(this); int i8 = 0; while (i8 < childCount) { View childAt = getChildAt(i8); if (childAt.getVisibility() != 8) { layoutParams = (LayoutParams) childAt.getLayoutParams(); if (layoutParams.KY) { measuredWidth = childAt.getMeasuredWidth(); if (aK(i8)) { measuredWidth += dividerWidth; } int measuredHeight = childAt.getMeasuredHeight(); if (bv) { paddingLeft = layoutParams.leftMargin + getPaddingLeft(); i5 = paddingLeft + measuredWidth; } else { i5 = (getWidth() - getPaddingRight()) - layoutParams.rightMargin; paddingLeft = i5 - measuredWidth; } int i9 = i6 - (measuredHeight / 2); childAt.layout(paddingLeft, i9, i5, measuredHeight + i9); paddingLeft = paddingRight - measuredWidth; obj = 1; measuredWidth = i7; } else { paddingLeft = paddingRight - (layoutParams.rightMargin + (childAt.getMeasuredWidth() + layoutParams.leftMargin)); aK(i8); measuredWidth = i7 + 1; } } else { paddingLeft = paddingRight; measuredWidth = i7; } i8++; paddingRight = paddingLeft; i7 = measuredWidth; } if (childCount == 1 && obj == null) { View childAt2 = getChildAt(0); measuredWidth = childAt2.getMeasuredWidth(); i5 = childAt2.getMeasuredHeight(); paddingRight = ((i3 - i) / 2) - (measuredWidth / 2); i7 = i6 - (i5 / 2); childAt2.layout(paddingRight, i7, measuredWidth + paddingRight, i5 + i7); return; } paddingLeft = i7 - (obj != null ? 0 : 1); paddingRight = Math.max(0, paddingLeft > 0 ? paddingRight / paddingLeft : 0); View childAt3; int i10; if (bv) { measuredWidth = getWidth() - getPaddingRight(); i5 = 0; while (i5 < childCount) { childAt3 = getChildAt(i5); layoutParams = (LayoutParams) childAt3.getLayoutParams(); if (childAt3.getVisibility() == 8 || layoutParams.KY) { paddingLeft = measuredWidth; } else { measuredWidth -= layoutParams.rightMargin; i8 = childAt3.getMeasuredWidth(); dividerWidth = childAt3.getMeasuredHeight(); i10 = i6 - (dividerWidth / 2); childAt3.layout(measuredWidth - i8, i10, measuredWidth, dividerWidth + i10); paddingLeft = measuredWidth - ((layoutParams.leftMargin + i8) + paddingRight); } i5++; measuredWidth = paddingLeft; } return; } measuredWidth = getPaddingLeft(); i5 = 0; while (i5 < childCount) { childAt3 = getChildAt(i5); layoutParams = (LayoutParams) childAt3.getLayoutParams(); if (childAt3.getVisibility() == 8 || layoutParams.KY) { paddingLeft = measuredWidth; } else { measuredWidth += layoutParams.leftMargin; i8 = childAt3.getMeasuredWidth(); dividerWidth = childAt3.getMeasuredHeight(); i10 = i6 - (dividerWidth / 2); childAt3.layout(measuredWidth, i10, measuredWidth + i8, dividerWidth + i10); paddingLeft = ((layoutParams.rightMargin + i8) + paddingRight) + measuredWidth; } i5++; measuredWidth = paddingLeft; } return; } super.onLayout(z, i, i2, i3, i4); } public void onDetachedFromWindow() { super.onDetachedFromWindow(); dismissPopupMenus(); } public void setOverflowIcon(Drawable drawable) { getMenu(); ActionMenuPresenter actionMenuPresenter = this.KQ; if (actionMenuPresenter.Ko != null) { actionMenuPresenter.Ko.setImageDrawable(drawable); return; } actionMenuPresenter.Kq = true; actionMenuPresenter.Kp = drawable; } public Drawable getOverflowIcon() { getMenu(); ActionMenuPresenter actionMenuPresenter = this.KQ; if (actionMenuPresenter.Ko != null) { return actionMenuPresenter.Ko.getDrawable(); } return actionMenuPresenter.Kq ? actionMenuPresenter.Kp : null; } public void setOverflowReserved(boolean z) { this.Kr = z; } private static LayoutParams en() { LayoutParams layoutParams = new LayoutParams(); layoutParams.gravity = 16; return layoutParams; } private LayoutParams c(AttributeSet attributeSet) { return new LayoutParams(getContext(), attributeSet); } protected static LayoutParams c(android.view.ViewGroup.LayoutParams layoutParams) { if (layoutParams == null) { return en(); } LayoutParams layoutParams2 = layoutParams instanceof LayoutParams ? new LayoutParams((LayoutParams) layoutParams) : new LayoutParams(layoutParams); if (layoutParams2.gravity > 0) { return layoutParams2; } layoutParams2.gravity = 16; return layoutParams2; } protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams layoutParams) { return layoutParams != null && (layoutParams instanceof LayoutParams); } public static LayoutParams eo() { LayoutParams en = en(); en.KY = true; return en; } public final boolean f(h hVar) { return this.bq.a((MenuItem) hVar, null, 0); } public int getWindowAnimations() { return 0; } public final void a(f fVar) { this.bq = fVar; } public Menu getMenu() { if (this.bq == null) { Context context = getContext(); this.bq = new f(context); this.bq.a(new c(this, (byte) 0)); this.KQ = new ActionMenuPresenter(context); this.KQ.ej(); this.KQ.bp = this.KR != null ? this.KR : new b(this, (byte) 0); this.bq.a(this.KQ, this.Jn); this.KQ.a(this); } return this.bq; } public final void a(android.support.v7.view.menu.l.a aVar, android.support.v7.view.menu.f.a aVar2) { this.KR = aVar; this.KS = aVar2; } public final void dismissPopupMenus() { if (this.KQ != null) { this.KQ.ek(); } } private boolean aK(int i) { boolean z = false; if (i == 0) { return false; } View childAt = getChildAt(i - 1); View childAt2 = getChildAt(i); if (i < getChildCount() && (childAt instanceof a)) { z = ((a) childAt).dA() | 0; } return (i <= 0 || !(childAt2 instanceof a)) ? z : ((a) childAt2).dz() | z; } public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent accessibilityEvent) { return false; } public void setExpandedActionViewsExclusive(boolean z) { this.KQ.Kz = z; } }
import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import javax.swing.JOptionPane; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Button; import org.eclipse.wb.swt.SWTResourceManager; //import com.sun.media.sound.Toolkit; import org.eclipse.swt.widgets.Spinner; /** * This class is used to represent the stock management interface * @author Refined Storage developers * */ public class GuiManageInventory extends Composite { /** * Object super */ public Object Super; private Text inputId; /** * This method represents the stock management interface along with his functionality * @param parent the composite parent * @param style the desired style * @param name the current user name * @param Rs refined storage * @param Db the database * @throws Throwable error generating interface */ public GuiManageInventory(Composite parent, int style, String name, Refined_storage Rs, DbFunctions Db) throws Throwable { super(parent, style); setLayout(null); Super = this; this.setVisible(false); this.setVisible(true); Composite composite_1 = new Composite(this, SWT.NONE); composite_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); composite_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW)); composite_1.setBounds(0, 504, 869, 80); Composite composite = new Composite(this, SWT.NONE); composite.setForeground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW)); composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW)); composite.setBounds(0, 0, 869, 80); Label labelMain_1 = new Label(composite, SWT.NONE); labelMain_1.setText("Stock Management"); labelMain_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); labelMain_1.setFont(SWTResourceManager.getFont("Corbel", 20, SWT.NORMAL)); labelMain_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW)); labelMain_1.setBounds(342, 23, 278, 47); Button btnBack = new Button(composite, SWT.NONE); btnBack.setBounds(10, 10, 75, 25); btnBack.setText("Back"); btnBack.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { ((Control) Super).dispose(); if(Rs.get_user_prio() == 1) { new GuiAdminMenu(parent, style, name, Rs, Db); }else if(Rs.get_user_prio() == 2) { new GuiEmployeeMenu(parent, style, name, Rs, Db); } } catch (Throwable e1) { e1.printStackTrace(); } } }); //Element that assures correct window size Label labelSizing1 = new Label(this, SWT.NONE); labelSizing1.setBounds(766, 559, 103, 25); Label labelSizing2 = new Label(this, SWT.NONE); labelSizing2.setBounds(10, 10, 55, 15); Label labelLine = new Label(this, SWT.NONE); labelLine.setText("______________"); labelLine.setFont(SWTResourceManager.getFont("Corbel", 16, SWT.NORMAL)); labelLine.setBounds(361, 461, 147, 40); this.setVisible(true); this.pack(); this.setVisible(true); Composite composite_2_1 = new Composite(this, SWT.NONE); composite_2_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); composite_2_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); composite_2_1.setBounds(402, 86, 303, 361); Label lblQuantity = new Label(composite_2_1, SWT.NONE); lblQuantity.setText("Quantity"); lblQuantity.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); lblQuantity.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); lblQuantity.setBounds(73, 194, 70, 20); Button btnConfirm = new Button(composite_2_1, SWT.NONE); btnConfirm.setBounds(145, 268, 100, 32); btnConfirm.setText("Confirm"); Button btnRemove = new Button(composite_2_1, SWT.RADIO); btnRemove.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK)); btnRemove.setBounds(196, 99, 86, 28); btnRemove.setText("Remove"); Button btnAdd = new Button(composite_2_1, SWT.FLAT | SWT.RADIO); btnAdd.setSelection(true); btnAdd.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK)); btnAdd.setBounds(73, 99, 86, 28); btnAdd.setText("Add"); Spinner spinner = new Spinner(composite_2_1, SWT.BORDER); spinner.setBounds(177, 191, 105, 28); Composite composite_2_1_1 = new Composite(this, SWT.NONE); composite_2_1_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); composite_2_1_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); composite_2_1_1.setBounds(146, 86, 303, 361); Label lblCurrentStock = new Label(composite_2_1_1, SWT.NONE); lblCurrentStock.setText("Current Stock"); lblCurrentStock.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); lblCurrentStock.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); lblCurrentStock.setBounds(24, 190, 90, 20); Label labelStock = new Label(composite_2_1_1, SWT.NONE); labelStock.setBounds(151, 190, 90, 25); Label lblId = new Label(composite_2_1_1, SWT.NONE); lblId.setText("ID"); lblId.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); lblId.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY)); lblId.setBounds(24, 102, 70, 20); inputId = new Text(composite_2_1_1, SWT.BORDER); inputId.setBounds(151, 99, 90, 28); Button btnCheckStock = new Button(composite_2_1_1, SWT.NONE); btnCheckStock.setBounds(104, 266, 90, 32); btnCheckStock.setText("Check Stock"); btnCheckStock.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String input1 = inputId.getText(); int id = Db.CheckValidId(input1); boolean m = false; if(id!=0) { try { int qty = Db.getQuantityFromID(id); labelStock.setText(String.valueOf(qty)); } catch (Throwable e1) { // TODO Auto-generated catch block System.out.println(e1.getMessage()); } try { m = DbFunctions.check_id(id, "material"); } catch (Throwable e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(m==false) { JOptionPane.showMessageDialog(null, "Invalid id"); } } else if(id==0) { JOptionPane.showMessageDialog(null, "Invalid id"); } } }); btnConfirm.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { int i=1; boolean m=false; String input1 = inputId.getText(); int id = Db.CheckValidId(input1); try { m = DbFunctions.check_id(id, "material"); } catch (Throwable e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if((Rs.get_user_prio() == 1) && (m == true)) { i = Rs.get_admin().manage_inventory(Db, id, spinner.getSelection(), btnAdd.getSelection(), btnRemove.getSelection()); }else if((Rs.get_user_prio() == 2)&& (m == true)){ i = Rs.get_employee().manage_inventory(Db, id, spinner.getSelection(), btnAdd.getSelection(), btnRemove.getSelection()); } else if(m == false) { JOptionPane.showMessageDialog(null, "Invalid id"); } if (i==0) { JOptionPane.showMessageDialog(null, "Not enough stock available"); } } }); } @Override protected void checkSubclass() { } }
package com.distributedShopping.resources; import java.nio.file.Path; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class TestLogger implements Logger{ private String logType; public TestLogger() { setLogType("Test App"); } public void newEntry(String message) { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println(now.format(formatter) + ": " + this.logType + ": " + message); } public void newEntry(Path path) { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println(now.format(formatter) + ": " + this.logType + ": Se encontro el archivo " + path); } private void setLogType(String logType){ this.logType = logType; } }
package co.nayt.picnic; import android.graphics.Bitmap; import android.widget.ImageView; import java.lang.ref.WeakReference; import co.nayt.picnic.TaskRunnable.TaskRunnableDownloadMethods; /** * This class manages the TaskRunnable object which downloads and decodes images. It implements * the TaskRunnableDownloadMethods interface that the TaskRunnable defines to perform the action. */ class Task implements TaskRunnableDownloadMethods { /* * Creates a weak reference to the ImageView that this Task will populate * to prevent memory leaks and crashes. */ private WeakReference<ImageView> mImageWeakRef; private String mImageURL; private int mTargetHeight; private int mTargetWidth; private Runnable mDownloadRunnable; private Bitmap mImageBitmap; private Thread mCurrentThread; private static Picnic sInstance; Thread mThreadThis; /** * Creates a Task containing the download runnable object */ Task() { mDownloadRunnable = new TaskRunnable(this); sInstance = Picnic.getInstance(); } /** * Initializes the Task * * @param instance A ThreadPool object * @param imageView An ImageView instance that shows the downloaded image * @param targetWidth The target width of the downloaded image * @param targetHeight The target height of the downloaded image */ void initializeDownloaderTask(Picnic instance, ImageView imageView, String url, int targetWidth, int targetHeight) { sInstance = instance; mImageURL = url; mImageWeakRef = new WeakReference<>(imageView); mTargetWidth = targetWidth; mTargetHeight = targetHeight; } /** * Recycles a Task object before it's put back into the pool. One reason to do * this is to avoid memory leaks. */ void recycle() { if (mImageWeakRef != null) { mImageWeakRef.clear(); mImageWeakRef = null; } mImageBitmap = null; } /** * Delegates handling the current state of the task to the Picnic object. * * @param state The current state */ private void handleState(int state) { sInstance.handleState(this, state); } /** * Returns the instance that downloaded the image. */ Runnable getHTTPDownloadRunnable() { return mDownloadRunnable; } /** * Returns the ImageView that's being constructed. */ public ImageView getView() { if (mImageWeakRef != null) { return mImageWeakRef.get(); } return null; } /** * Returns the Thread that this Task is running on. It uses a lock on the ThreadPool singleton * to prevent thread interference. */ Thread getCurrentThread() { synchronized(sInstance) { return mCurrentThread; } } /** * Sets the identifier for the current Thread. */ private void setCurrentThread(Thread thread) { synchronized(sInstance) { mCurrentThread = thread; } } @Override public Bitmap getBitmap() { return mImageBitmap; } @Override public int getTargetWidth() { return mTargetWidth; } @Override public int getTargetHeight() { return mTargetHeight; } @Override public void clearCache() { sInstance.clearCache(); } @Override public String getImageURL() { return mImageURL; } @Override public void setBitmap(Bitmap bitmap) { mImageBitmap = bitmap; } @Override public void setDownloadThread(Thread currentThread) { setCurrentThread(currentThread); } @Override public void handleTaskState(int state) { int outState; switch(state) { case TaskRunnable.HTTP_STATE_COMPLETED: outState = Picnic.DOWNLOAD_COMPLETE; break; case TaskRunnable.HTTP_STATE_FAILED: outState = Picnic.DOWNLOAD_FAILED; break; case TaskRunnable.HTTP_STATE_STARTED: outState = Picnic.DOWNLOAD_STARTED; break; case TaskRunnable.DECODE_STATE_COMPLETED: outState = Picnic.TASK_COMPLETE; break; case TaskRunnable.DECODE_STATE_FAILED: outState = Picnic.DOWNLOAD_FAILED; break; default: outState = Picnic.DECODE_STARTED; break; } handleState(outState); } }
package com.jiuzhe.app.hotel.dto; /** * @Description:订单成功后返回的数据 */ public class OrderSuccessDto { /** * 房间id */ private String skuId; /** * 订单id */ private String OrderId; /** * 商户id */ private String merchantId; public String getSkuId() { return skuId; } public void setSkuId(String skuId) { this.skuId = skuId; } public String getOrderId() { return OrderId; } public void setOrderId(String orderId) { OrderId = orderId; } public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } }
package selenium; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.*; import org.testng.annotations.Test; public class GroupTest1 { WebDriver d; @Test(groups="G1") public void meth1() { System.out.println("Meth1 in GT1"); System.setProperty("webdriver.gecko.driver", "C:/Users/Nisum/Desktop/jahangir/Softwares/geckodriver.exe"); d = new FirefoxDriver(); } @Test(groups="G2") public void meth2() { System.out.println("Meth2 in GT2"); } @Test(groups="G1") public void meth3() { System.out.println("Meth3 in GT3"); } @Test(groups="G2") public void meth4() { System.out.println("Meth4 in GT4"); } }
package com.ibm.ive.tools.japt.reduction.ita; import com.ibm.ive.tools.japt.reduction.ita.ObjectSet.ObjectSetEntry; /** * This class wraps a PropagatedObject to store more information associated with the object. * * PropagatedObject is aware of this class, so that when this class is compared to a propagated object, or vice versa, * the wrapped objects are unwrapped before the comparison. * * @author sfoley * */ public class WrappedObject extends ObjectSetEntry { public final PropagatedObject object; //public Object link; public WrappedObject(PropagatedObject obj) { this.object = obj; } public WrappedObject(PropagatedObject obj, Object link) { this(obj); //this.link = link; } public PropagatedObject getObject() { return object; } public int hashCode() { return object.hashCode(); } public boolean equals(Object o) { return object.equals(o); } public int compareTo(Object obj) { return object.compareTo(obj); } }
package com.rofour.baseball.dao.activity.bean; import java.io.Serializable; public class AcctQuotaBean implements Serializable { private static final long serialVersionUID = -4123266529071234148L; private Integer quotaId; private String quotaName; private String fieldName; private Boolean state; public AcctQuotaBean(Integer quotaId, String quotaName, String fieldName, Boolean state) { this.quotaId = quotaId; this.quotaName = quotaName; this.fieldName = fieldName; this.state = state; } public AcctQuotaBean() { super(); } public Integer getQuotaId() { return quotaId; } public void setQuotaId(Integer quotaId) { this.quotaId = quotaId; } public String getQuotaName() { return quotaName; } public void setQuotaName(String quotaName) { this.quotaName = quotaName == null ? null : quotaName.trim(); } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName == null ? null : fieldName.trim(); } public Boolean getState() { return state; } public void setState(Boolean state) { this.state = state; } }
package edunova; import javax.swing.JOptionPane; public class Zadatak4 { // Za dva unesena broja ispiši njihovu razliku u apsolutnoj vrijednosti public static void main(String[] args) { int i=Integer.parseInt(JOptionPane.showInputDialog("pb")); int j=Integer.parseInt(JOptionPane.showInputDialog("db")); if(i-j<0) { System.out.println((i-j)* -1); }else { System.out.println(i-j); } if(i<j) { System.out.println(j-i); }else { System.out.println(i-j); } } }
package ru.kirilushkin.housemanaging.repository; import org.springframework.data.jpa.repository.JpaRepository; import ru.kirilushkin.housemanaging.entity.Apartment; public interface ApartmentRepository extends JpaRepository<Apartment, Integer> { }
package mat06.sim.missingitemreminder.fragments.category_dialog; public interface CategoryDialogListener { void saveCustomCategory(String category); }
package pl.jstk.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import pl.jstk.constants.ViewNames; import pl.jstk.enumerations.BookCategory; import pl.jstk.repository.CustomRepository; import pl.jstk.service.BookService; import pl.jstk.to.BookTo; import java.util.List; @Controller @RequestMapping("/books") public class BookController { private BookService bookService; @Autowired public BookController(BookService bookService) { this.bookService = bookService; } @GetMapping("/allBooks") public String getAllBooks(Model model) { model.addAttribute("bookList",bookService.findAllBooks()); return ViewNames.BOOKS; } @GetMapping("/book") public String getBook(@RequestParam("id") Long id, Model model) { model.addAttribute("book",bookService.findById(id)); return ViewNames.BOOK; } @GetMapping("/addBook") public ModelAndView showFormAddBook() { ModelAndView modelAndView = new ModelAndView(ViewNames.ADDBOOK); modelAndView.addObject("newBook", new BookTo()); modelAndView.addObject("categories", BookCategory.values()); return modelAndView; } @PostMapping("/addBook") public String saveBook(@ModelAttribute("newBook") BookTo bookTo, BindingResult result, final RedirectAttributes redirectAttributes) { if(result.hasErrors()) { return ViewNames.ADDBOOK; } // redirectAttributes.addFlashAttribute("message","Book added successfully!"); // redirectAttributes.addFlashAttribute("alertClass","success"); BookTo bookTo1 = bookService.saveBook(bookTo); return "redirect:/books/book?id=" + bookTo1.getId(); } @GetMapping("/findBook") public ModelAndView showFormFindBook(){ ModelAndView modelAndView = new ModelAndView(ViewNames.FINDBOOK); modelAndView.addObject("newBook", new BookTo()); modelAndView.addObject("categories", BookCategory.values()); return modelAndView; } @PostMapping("/findBook") public ModelAndView findBooksByCriteria(@ModelAttribute("newBook") BookTo bookTo) { List<BookTo> booksByCriteria = bookService.findBooksByCriteria(bookTo); ModelAndView modelAndView = new ModelAndView(ViewNames.BOOKS); modelAndView.addObject("bookList",booksByCriteria); return modelAndView; } @GetMapping("/deleteBook") public String deleteBook(@RequestParam("id") Long id) { bookService.deleteBook(id); return ViewNames.BOOKDELETE; } }
package com.app.cash.tools.entity; import com.app.cash.tools.dto.Menu; public class Minuman extends Menu { public Minuman(String nama_minuman, double harga){ setNama_menu(nama_minuman); setHarga(harga); setKategori("Minuman"); } }
package com.tencent.mm.aq; import com.tencent.mm.protocal.c.ayp; import com.tencent.mm.protocal.k.b; import com.tencent.mm.protocal.k.d; class a$b extends d implements b { public ayp ebZ = new ayp(); a$b() { } public final byte[] Ie() { return this.ebZ.toByteArray(); } public final int If() { return 681; } }
package com.axicik; import java.sql.SQLException; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; /** * REST Web Service * * @author ioulios */ @Path("modifyFromFile") public class ModifyGrades { @Context private UriInfo context; // Δημιουργείτε μόνο του απο το Net-beans, όταν δημιουργείτε η κλάση και δεν το χρησιμοποιούμε κάπου. private final int serviceNum=1; // Σταθερά - Μοναδικός Κωδικός του κάθε web service. /** * Creates a new instance of ModifyFromFileResource */ public ModifyGrades() { } /** * Προσθέτει η αλλάζει τον βαθμό σε έναν ή περισότερουw φοιτητές. Ο χρήστης πρέπει να * έχει τα απαραίτητα δικαιώματα και να έχει κάνει login. * * @param username Όνομα Χρήστη * @param key Κλείδι Χρηστη * @param info Json Κώδικας με τα στοιχεία του νέου χρήστη * Μορφή json: * { "lessonID": κωδικός μαθήματος, * "Grades": * [{ "am": Αριθμός μητρώου , * "grade": βαθμός}, * ... , * { "am": Αριθμός μητρώου, * "grade": βαθμός} * ] * } * @return ένα String που περιέχει ένα μήνυμα που αφορά την επιτυχία ή όχι του web service. * @throws ClassNotFoundException * @throws SQLException */ @GET @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.TEXT_PLAIN) public String putGradesFromFile(@QueryParam ("usr") String username,@QueryParam("key") String key,@QueryParam ("info") String info) throws SQLException, ClassNotFoundException { DBManager dbm=DBManager.getInstance(); // Πέρνει το μοναδικό αντεικήμενο τηs κλάσης DBManager. User u=dbm.checkKey(username,key); //Ελέγχει αν υπάρχει χρήστης και επιστρέφει ένα αντικείμενο User στοιχεία του χρήστη . if(u.getUsrExist())// Αν ο χρήστης υπάρχει τότε επιστρέφει true αλλιώς false. if(u.hasService(serviceNum)) // Αν ο χρήστης έχει δικαίωμα να καλεί το συγκεκριμένο web service τότε επιστρέφει true αλλιώς false. return dbm.putGrades(info); //Μετατρέπει το string σε json και προσθέτει τους νέους βαθμούς στην βάση. else return "An error has occured: Permission Denied"; else return "An error has occured: User not added"; } }
package com.tyss.cg.jpa.beans; import java.io.Serializable; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import lombok.Data; import lombok.ToString.Exclude; @SuppressWarnings("serial") @Data @Entity @Table(name = "projects_info") public class ProjectBean implements Serializable { @Id @Column private Integer projectId; @Column private String projectName; @Column private String duration; @Column private String projectType; @Exclude @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "employee_projects", joinColumns = @JoinColumn(name = "projectId"), inverseJoinColumns = @JoinColumn(name = "empId")) private List<EmployeeInfoBean> employeeInfoBeanList; }
package com.sporsimdi.action.service; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.model.SelectItem; import com.sporsimdi.action.facade.GrupFacade; import com.sporsimdi.model.entity.Grup; @ManagedBean(name = "grupService") @ViewScoped public class GrupService extends GenericService implements Serializable { private static final long serialVersionUID = 2775406662196454231L; @EJB private GrupFacade grupFacade; private List<Grup> grupListesi = new ArrayList<Grup>(); private List<SelectItem> gunListesi; public List<Grup> getGrupListesi() { return grupListesi; } public void setGrupListesi(List<Grup> grupListesi) { this.grupListesi = grupListesi; } public String yonlendir(Long id) { super.yonlendir(id); if (id==null) { return "/menu/grupTanimlama?faces-redirect=true&amp;includeViewParams=true&amp;donemId=" ; } else { return "/menu/grupTanimlama?faces-redirect=true&amp;includeViewParams=true&amp;grupId=" + id; } } public List<SelectItem> getGunListesi() { if (gunListesi == null || gunListesi.isEmpty()) { gunListesi = new ArrayList<SelectItem>(); for(int i = 1; i<31; i++) { SelectItem si = new SelectItem(i, Integer.toString(i)); gunListesi.add(si); } } return gunListesi; } public void setGunListesi(List<SelectItem> gunListesi) { this.gunListesi = gunListesi; } }
package com.tencent.mm.ui.base; public interface MMViewPager$b { void O(float f, float f2); void P(float f, float f2); }
package com.greedy; import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class beautifulPairs { // Complete the beautifulPairs function below. static int beautifulPairs(int[] A, int[] B) { int sizeA = A.length; int sizeB = B.length; int count = 0; // Arrays.sort(A); // Arrays.sort(B); // // System.out.println(Arrays.toString(A)); // System.out.println(Arrays.toString(B)); // for(int i = 0; i < sizeA; i++){ // // } for(int i = 0; i < sizeA; i++){ for(int j = 0; j < sizeB; j++){ if(A[i] == B[j]){ A[i] = -1; B[j] = -1; count++; break; } } } for(int i = 0; i < sizeA; i++){ if(A[i] != -1){ for(int j = 0; j < sizeB; j++){ if(B[j] != -1){ return ++count; } } } } return count; } public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new FileInputStream(new File("input/dummy"))); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] A = new int[n]; String[] AItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int AItem = Integer.parseInt(AItems[i]); A[i] = AItem; } int[] B = new int[n]; String[] BItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int BItem = Integer.parseInt(BItems[i]); B[i] = BItem; } int result = beautifulPairs(A, B); System.out.println(String.valueOf(result)); scanner.close(); } }
package com.example.quizapp; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; public class QuizQuestions extends AppCompatActivity implements View.OnClickListener { private String username, number, category, difficulty; private RequestQueue mQueue; ArrayList<Question> questionArrayList = new ArrayList<>(); private TextView twPoints, twQuestion, twCurrent; private RadioButton rb1, rb2, rb3, rb4; private RadioGroup rbGroup; private Button btnNext; private Question firstQuestion; private int changer; private int changer2 = 1; private ArrayList<String> allOptions = new ArrayList<>(); private boolean answered; private int points = 0; private RadioButton selectedRb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz_questions); initComponents(); mQueue = Volley.newRequestQueue(this); jsonParse(); } private void initComponents() { Bundle extras = getIntent().getExtras(); username = extras.getString("username"); number = extras.getString("number"); category = extras.getString("category"); difficulty = extras.getString("difficulty"); twQuestion = findViewById(R.id.twQuestion); twPoints = findViewById(R.id.twPoints); twCurrent = findViewById(R.id.twCurrent); rbGroup = findViewById(R.id.radioGroup); rb1 = findViewById(R.id.rbAnswer1); rb2 = findViewById(R.id.rbAnswer2); rb3 = findViewById(R.id.rbAnswer3); rb4 = findViewById(R.id.rbAnswer4); btnNext = findViewById(R.id.btnNext); btnNext.setOnClickListener(this); } private void jsonParse() { String url = "https://opentdb.com/api.php?amount=" + number + "&category=" + category +"&difficulty=" + difficulty + "&type=multiple"; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("results"); parseJsonArray(jsonArray); if (questionArrayList.size() == 0) { Toast.makeText(QuizQuestions.this, "Please insert smaller number of questions or select other category.", Toast.LENGTH_LONG).show(); }else { changer = 0; startQuestions(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); mQueue.add(request); } private void startQuestions() { firstQuestion = questionArrayList.get(changer); String firstOption = firstQuestion.getOption1(); String secondOption = firstQuestion.getOption2(); String thirdOption = firstQuestion.getOption3(); String fourthOption = firstQuestion.getAnswer(); allOptions.add(firstOption); allOptions.add(secondOption); allOptions.add(thirdOption); allOptions.add(fourthOption); Collections.shuffle(allOptions); twQuestion.setText(android.text.Html.fromHtml(firstQuestion.getQuestion()).toString().trim().replaceAll("&(.*)+;", "")); rb1.setText(android.text.Html.fromHtml(allOptions.get(0)).toString().trim().replaceAll("&(.*)+;", "")); rb2.setText(android.text.Html.fromHtml(allOptions.get(1)).toString().trim().replaceAll("&(.*)+;", "")); rb3.setText(android.text.Html.fromHtml(allOptions.get(2)).toString().trim().replaceAll("&(.*)+;", "")); rb4.setText(android.text.Html.fromHtml(allOptions.get(3)).toString().trim().replaceAll("&(.*)+;", "")); twCurrent.setText("" + changer2 + " / " + number); answered = false; } private void changeQuestion() { rb1.setBackgroundResource(R.drawable.btn_border); rb2.setBackgroundResource(R.drawable.btn_border); rb3.setBackgroundResource(R.drawable.btn_border); rb4.setBackgroundResource(R.drawable.btn_border); rbGroup.clearCheck(); allOptions.clear(); changer++; int limit = Integer.parseInt(number); if (changer < limit) { changer2++; startQuestions(); }else{ Intent intent = new Intent(this, FinishPage.class); Bundle extras = new Bundle(); String sPoints = String.valueOf(points); extras.putString("username", username); extras.putString("number", number); extras.putString("points", sPoints); extras.putString("difficulty", difficulty); Database db = new Database(this); db.addResult(username, number, difficulty, sPoints); intent.putExtras(extras); startActivity(intent); } } private void checkAnswer(){ answered = true; btnNext.setText(R.string.next); int selectedId = rbGroup.getCheckedRadioButtonId(); selectedRb = findViewById(selectedId); String radioAnswer = selectedRb.getText().toString(); String correctAnswer = android.text.Html.fromHtml(firstQuestion.getAnswer()).toString().trim().replaceAll("&(.*)+;", ""); if (radioAnswer.equals(correctAnswer)){ selectedRb.setBackgroundResource(R.drawable.correct_background); switch(difficulty){ case "easy": points++; break; case "medium": points += 2; break; case "hard": points += 3; break; } twPoints.setText(getString(R.string.points) + points); }else{ selectedRb.setBackgroundResource(R.drawable.incorrect_background); String option1 = rb1.getText().toString(); if (option1.equals(correctAnswer)){ rb1.setBackgroundResource(R.drawable.correct_background); } String option2 = rb2.getText().toString(); if (option2.equals(correctAnswer)){ rb2.setBackgroundResource(R.drawable.correct_background); } String option3 = rb3.getText().toString(); if (option3.equals(correctAnswer)){ rb3.setBackgroundResource(R.drawable.correct_background); } String option4 = rb4.getText().toString(); if (option4.equals(correctAnswer)){ rb4.setBackgroundResource(R.drawable.correct_background); } } } private void parseJsonArray(JSONArray array){ for (int i = 0; i < array.length(); i++) { try { JSONObject result = array.getJSONObject(i); Question questionModel = new Question(); questionModel.setQuestion(result.getString("question")); questionModel.setAnswer(result.getString("correct_answer")); JSONArray jArray = result.getJSONArray("incorrect_answers"); if (jArray != null) { for (int j = 0; j < jArray.length(); j++) { questionModel.setOption1(jArray.getString(0)); questionModel.setOption2(jArray.getString(1)); questionModel.setOption3(jArray.getString(2)); } } questionArrayList.add(questionModel); }catch (JSONException e){ e.printStackTrace(); } } } @Override public void onClick(View v) { System.out.println("ANSWERED: " + answered); if (!answered) { if (rb1.isChecked() || rb2.isChecked() || rb3.isChecked() || rb4.isChecked()) { checkAnswer(); } else { Toast.makeText(this, "Please select an answer", Toast.LENGTH_SHORT).show(); } } else { btnNext.setText("Continue"); changeQuestion(); } } }
package com.huanuo.npo.controller; import com.huanuo.npo.pojo.People; import com.huanuo.npo.service.PeopleService; import com.huanuo.npo.service.PeopleServiceTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; @RestController public class PeopleConTest { /* 类型:大驼峰写法 变量名:小驼峰写法(除第一个单词首字母小写,其他大写) */ @Autowired PeopleServiceTest peopleService; @GetMapping("qian") public List<People> get(){ return peopleService.get(); } @PostMapping("qian") public List post(@RequestBody Map<String,String> map){ String name; int age; name=map.get("name"); age=Integer.valueOf( map.get("age")); return peopleService.post(name,age); } @DeleteMapping("/qian/{name}") public List delete(@PathVariable String name){ return peopleService.delete(name); } }
package com.jeywei.update; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Description: * Data:2018/11/2-16:46 * Author: Allen */ public class DownloadUtil { public static final int DOWNLOAD_FAIL = 0; public static final int DOWNLOAD_PROGRESS = 1; public static final int DOWNLOAD_SUCCESS = 2; private static DownloadUtil downloadUtil; private final OkHttpClient okHttpClient; public static DownloadUtil getInstance() { if (downloadUtil == null) { downloadUtil = new DownloadUtil(); } return downloadUtil; } private DownloadUtil() { okHttpClient = new OkHttpClient(); } /** * @param url 下载地址 * @param saveDir 保存文件目录 * @param pathName 保存的文件名称 * @param listener 监听器 */ public void download(final String url, final String saveDir, final String pathName, final OnDownloadListener listener) { this.listener = listener; Request request = new Request.Builder().url(url).build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { Message message = Message.obtain(); message.what = DOWNLOAD_FAIL; mHandler.sendMessage(message); } @Override public void onResponse(okhttp3.Call call, final Response response) throws IOException { Log.e("这里是什么线程>>>>", Thread.currentThread().getName()); runOnSubThread(new Runnable() { @Override public void run() { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; //储存下载文件的目录 String savePath = null; try { savePath = isExistDir(saveDir); } catch (IOException e) { e.printStackTrace(); } try { is = response.body().byteStream(); long total = response.body().contentLength(); File file = null; if (TextUtils.isEmpty(pathName)) { file = new File(savePath, UpdateUtils.getNameFromUrl(url)); } else { file = new File(savePath, pathName); } fos = new FileOutputStream(file); long sum = 0; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); sum += len; int progress = (int) (sum * 1.0f / total * 100); //下载中 Message message = Message.obtain(); message.what = DOWNLOAD_PROGRESS; message.obj = progress; mHandler.sendMessage(message); Log.e("哈哈哈", "这里走了吗"); } fos.flush(); //下载完成 Message message = Message.obtain(); message.what = DOWNLOAD_SUCCESS; message.obj = file.getAbsolutePath(); mHandler.sendMessage(message); } catch (Exception e) { Message message = Message.obtain(); message.what = DOWNLOAD_FAIL; mHandler.sendMessage(message); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) { fos.close(); } } catch (IOException e) { } } } }); } }); } /** * description: 不传入保存路径,默认使用FILEPATH * author: Allen * date: 2018/11/2 17:05 */ public void download(final String url, String apkName, final OnDownloadListener listener) { download(url, UpdateUtils.FILEPATH, apkName, listener); } public void download(final String url, final OnDownloadListener listener) { download(url, UpdateUtils.FILEPATH, UpdateUtils.getNameFromUrl(url), listener); } private String isExistDir(String saveDir) throws IOException { File downloadFile = new File(saveDir); if (!downloadFile.mkdirs()) { downloadFile.createNewFile(); } String savePath = downloadFile.getAbsolutePath(); return savePath; } private Handler mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(final Message msg) { super.handleMessage(msg); switch (msg.what) { case DOWNLOAD_PROGRESS: listener.onDownloading((Integer) msg.obj); break; case DOWNLOAD_FAIL: listener.onDownloadFailed(); break; case DOWNLOAD_SUCCESS: listener.onDownloadSuccess((String) msg.obj); break; } } }; OnDownloadListener listener; public interface OnDownloadListener { /** * 下载成功 */ void onDownloadSuccess(String path); /** * 下载进度 * * @param progress */ void onDownloading(int progress); /** * 下载失败 */ void onDownloadFailed(); } private static Handler sHandler = new Handler(Looper.getMainLooper()); private static ExecutorService sExecutorService = Executors.newCachedThreadPool(); //Runnable:任务,必须依附于某一个线程 //Thread:线程,线程用来执行任务 //Process:进程 //保证r这个任务一定是在主线程中执行 public static void runOnUiThread(Runnable r) { if (Looper.myLooper() == Looper.getMainLooper()) { //主线程 //new Thread(r).start(); 一旦new了Thread就一定是子线程 r.run(); } else { //new Thread(r).start() sHandler.post(r); } } //保证r一定在子线程中得到执行 public static void runOnSubThread(Runnable r) { // new Thread(r).start(); //线程池的概念,线程池里面装的是线程,使用线程池可以达到线程的复用,提高性能 sExecutorService.submit(r);//将r丢到线程池中,线程池中的线程就会来执行r这个任务 } }
package com.stark.heap; import com.stark.util.ArrayUtil; /** * Created by Stark on 2017/8/31. */ public class HeapSort { public static void heapSort(int[] arr) { int len = arr.length; int temp; //构建堆 for (int i = len / 2 - 1; i >= 0; i--) { keepBigHeap(arr, i, len); } //排序 for (int i = len - 1; i >= 0; i--) { temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; keepBigHeap(arr, 0, i); } } //维护大顶堆性质 private static void keepBigHeap(int[] arr, int node, int len) { int l = node * 2 + 1; int r = node * 2 + 2; int largest = node; int temp; if (len > l && arr[l] > arr[largest]) { largest = l; } if (len > r && arr[r] > arr[largest]) { largest = r; } if (largest != node) {//发生交换 temp = arr[largest]; arr[largest] = arr[node]; arr[node] = temp; keepBigHeap(arr, largest, len); } } public static void main(String[] args) { int[] array = ArrayUtil.makeArray(10); ArrayUtil.print(array); System.out.println(); //insertionSort_V1(array); heapSort(array); ArrayUtil.print(array); } }
package com.fanbo.kai.zhihu_funny.view.base; import android.support.v7.widget.RecyclerView; import android.view.View; import butterknife.ButterKnife; /** * Created by HK on 2017/1/24. * Email: kaihu1989@gmail.com. */ public abstract class RecyclerViewBaseHolder<D> extends RecyclerView.ViewHolder { public RecyclerViewBaseHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } public abstract void populate(D item); }
class Current { public static void main(String args[]) { System.out.println("Let's Find Current Thread"); Thread t=Thread.currentThread(); System.out.println("Current Thread: "+t); System.out.println("It's Name: "+t.getName()); } }
package com.tencent.mm.plugin.luckymoney.ui; import android.view.View; import android.widget.ImageView; import android.widget.TextView; class i$c { ImageView hVP; View ido; TextView jYA; TextView kLE; TextView kLF; TextView kLG; TextView kLH; ImageView kLI; TextView kLJ; final /* synthetic */ i kXv; i$c(i iVar) { this.kXv = iVar; } }
package co.th.aten.network.web; import java.io.IOException; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.j2ee.servlets.ImageServlet; import org.jboss.solder.logging.Logger; import co.th.aten.network.control.CustomerControl; import co.th.aten.network.control.TransactionHeaderControl; import co.th.aten.network.entity.MemberCustomer; import co.th.aten.network.entity.StockProduct; import co.th.aten.network.entity.TransactionSellDetail; import co.th.aten.network.entity.TransactionSellHeader; import co.th.aten.network.entity.TransactionSellHeaderStatus; import co.th.aten.network.entity.UserLogin; import co.th.aten.network.model.DropDownModel; import co.th.aten.network.model.ProductModel; import co.th.aten.network.model.TrxProductModel; import co.th.aten.network.producer.DBDefault; import co.th.aten.network.report.AbstractReport; import co.th.aten.network.report.ProductTrxReport; import co.th.aten.network.security.CurrentUserManager; import co.th.aten.network.util.BathText; import co.th.aten.network.util.StringUtil; @SessionScoped @Named public class ProductTrxController implements Serializable { private static final long serialVersionUID = 1L; @Inject private Logger log; @Inject @DBDefault private EntityManager em; @Inject private CurrentUserManager currentUser; @Inject private FacesContext facesContext; @Inject private CustomerControl customerControl; @Inject private TransactionHeaderControl transactionHeaderControl; private List<TrxProductModel> trxProductModelList; private List<DropDownModel> trxStatusList; private List<DropDownModel> trxStatusForDataTable; private int selectedTrxStatus; private Date startDate; private Date endDate; private String receiptNo; @PostConstruct public void init(){ log.info("init method ProductTrxController"); Calendar calStart = Calendar.getInstance(); calStart.add(Calendar.DATE, -30); calStart.set(Calendar.HOUR_OF_DAY, 0); calStart.set(Calendar.MINUTE, 0); calStart.set(Calendar.SECOND, 0); calStart.set(Calendar.MILLISECOND, 0); startDate = calStart.getTime(); Calendar calEnd = Calendar.getInstance(); calEnd.set(Calendar.HOUR_OF_DAY, 23); calEnd.set(Calendar.MINUTE, 59); calEnd.set(Calendar.SECOND, 59); calEnd.set(Calendar.MILLISECOND, 999); endDate = calEnd.getTime(); if(trxStatusList==null || trxStatusForDataTable==null){ trxStatusList = new ArrayList<DropDownModel>(); trxStatusForDataTable = new ArrayList<DropDownModel>(); List<TransactionSellHeaderStatus> statusList = em.createQuery("From TransactionSellHeaderStatus order by statusId",TransactionSellHeaderStatus.class).getResultList(); if(statusList!=null){ for(TransactionSellHeaderStatus trxStatus:statusList){ DropDownModel model = new DropDownModel(); model.setIntKey(trxStatus.getStatusId()); model.setThLabel(trxStatus.getStatusDesc()); model.setEnLabel(trxStatus.getStatusDesc()); trxStatusList.add(model); trxStatusForDataTable.add(model); } DropDownModel model = new DropDownModel(); model.setIntKey(-1); model.setThLabel(""); model.setEnLabel(""); trxStatusList.add(0,model); selectedTrxStatus = -1; } } search(); } public void search(){ try{ trxProductModelList = new ArrayList<TrxProductModel>(); String statusSql = ""; String receiptNoSql = ""; if(selectedTrxStatus > 0){ statusSql = " And trxHeaderStatus = "+selectedTrxStatus+" "; } if(receiptNo!=null && receiptNo.trim().length()>0){ receiptNoSql = " And receiptNo = '"+StringUtil.checkSql(receiptNo)+"' "; } List<TransactionSellHeader> trxHeaderList = em.createQuery(" From TransactionSellHeader " + " Where trxHeaderDatetime Between :startDate And :endDate " + statusSql + receiptNoSql + " Order by trxHeaderDatetime desc ",TransactionSellHeader.class) .setParameter("startDate", startDate) .setParameter("endDate", endDate) .getResultList(); if(trxHeaderList!=null){ for(TransactionSellHeader trx:trxHeaderList){ TrxProductModel model = new TrxProductModel(); model.setHeaderId(StringUtil.n2b(trx.getTrxHeaderId())); MemberCustomer customer = em.find(MemberCustomer.class,trx.getCustomerId()); if(customer!=null){ model.setMemberId(customer.getCustomerId().intValue()); model.setMemberCode(customer.getCustomerMember()); model.setMemberName(customerControl.genNameMenber(customer)); } model.setReceiptNo(StringUtil.n2b(trx.getReceiptNo())); model.setTotalPrice(StringUtil.n2b(trx.getTotalPrice()).doubleValue()); model.setTotalPv(StringUtil.n2b(trx.getTotalPv()).doubleValue()); model.setTrxDateTime(trx.getTrxHeaderDatetime()); UserLogin userLogin = em.find(UserLogin.class, trx.getCreateBy()); if(userLogin!=null && userLogin.getCustomerId()!=null) model.setMemberCodeKey(userLogin.getCustomerId().getCustomerMember()); TransactionSellHeaderStatus status = em.find(TransactionSellHeaderStatus.class, trx.getTrxHeaderStatus()); if(status!=null){ model.setStatusId(StringUtil.n2b(status.getStatusId())); model.setStatus(StringUtil.n2b(status.getStatusDesc())); } model.setTrxStatusList(trxStatusForDataTable); List<TransactionSellDetail> detailList = em.createQuery("From TransactionSellDetail Where trxHeaderId =:trxHeaderId ",TransactionSellDetail.class) .setParameter("trxHeaderId", trx.getTrxHeaderId()) .getResultList(); if(detailList!=null && detailList.size()>0){ List<ProductModel> productModelList = new ArrayList<ProductModel>(); int order = 0; for(TransactionSellDetail detail:detailList){ ProductModel productModel = new ProductModel(); StockProduct stockProduct = em.find(StockProduct.class, detail.getProductId()); productModel.setOrder(++order); if(stockProduct!=null){ productModel.setProductCode(StringUtil.n2b(stockProduct.getProductCode())); productModel.setProductThDesc(StringUtil.n2b(stockProduct.getThDesc())); } productModel.setQty(StringUtil.n2b(detail.getQty()).intValue()); productModel.setPrice(StringUtil.n2b(detail.getPrice()).doubleValue()); productModel.setTotalPrice(StringUtil.n2b(detail.getTotalPrice()).doubleValue()); productModelList.add(productModel); } model.setProductModelList(productModelList); } trxProductModelList.add(model); } } }catch(Exception e){ e.printStackTrace(); } } public void saveEditStatus(TrxProductModel trxModel){ try{ log.info("saveEditStatus Trx Header ID = "+trxModel.getHeaderId()); log.info("saveEditStatus Trx Status ID = "+trxModel.getStatusId()); TransactionSellHeader trxHeader = em.find(TransactionSellHeader.class, new Integer(trxModel.getHeaderId())); trxHeader.setTrxHeaderStatus(trxModel.getStatusId()); trxHeader.setUpdateBy(currentUser.getCurrentAccount().getUserId()); trxHeader.setUpdateDate(new Date()); em.merge(trxHeader); }catch(Exception ex){ ex.printStackTrace(); } } public void exportReport(TrxProductModel trxProductModel) { try { HttpServletRequest request = (HttpServletRequest) facesContext .getExternalContext().getRequest(); AbstractReport report = null; report = new ProductTrxReport(); Map<String, Object> parameters = ((ProductTrxReport) report) .getParameter(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); parameters.put("printDate", sdf2.format(new Date())); parameters.put("printBy", currentUser.getCurrentAccount() .getUserName()); if(trxProductModel.getTrxDateTime()!=null) parameters.put("paymentDate", sdf.format(trxProductModel.getTrxDateTime())); if(trxProductModel.getMemberCode()!=null) parameters.put("contracId", trxProductModel.getMemberCode()); parameters.put("totalAmount", trxProductModel.getTotalPrice()); if(trxProductModel.getMemberName()!=null) parameters.put("clientName", trxProductModel.getMemberName()); parameters.put("address", transactionHeaderControl.getAddressByHeaderId(trxProductModel.getHeaderId())); if(trxProductModel.getReceiptNo()!=null) parameters.put("receiptNo", trxProductModel.getReceiptNo()); parameters.put("totalAmountText", BathText.bahtText(trxProductModel.getTotalPrice())); ((ProductTrxReport) report).setModel(trxProductModel.getProductModelList()); report.fill(); if (request != null) { request.getSession().setAttribute( ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, report.getJasperPrint()); } byte[] pdf = report.exportPDF(); HttpServletResponse response = (HttpServletResponse) facesContext .getExternalContext().getResponse(); response.setContentType("application/pdf"); response.setContentLength(pdf.length); response.setHeader("Content-disposition", "inline; filename=" + "TopupReportByDate" + ".pdf"); ServletOutputStream out; out = response.getOutputStream(); out.write(pdf); out.flush(); // new out.close(); response.flushBuffer(); facesContext.responseComplete(); // new } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public List<TrxProductModel> getTrxProductModelList() { return trxProductModelList; } public void setTrxProductModelList(List<TrxProductModel> trxProductModelList) { this.trxProductModelList = trxProductModelList; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public List<DropDownModel> getTrxStatusList() { return trxStatusList; } public void setTrxStatusList(List<DropDownModel> trxStatusList) { this.trxStatusList = trxStatusList; } public int getSelectedTrxStatus() { return selectedTrxStatus; } public void setSelectedTrxStatus(int selectedTrxStatus) { this.selectedTrxStatus = selectedTrxStatus; } public String getReceiptNo() { return receiptNo; } public void setReceiptNo(String receiptNo) { this.receiptNo = receiptNo; } }
package inordertraversal; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; public class Solution { public List<Integer> inorder(TreeNode root){ List<Integer> inorder = new ArrayList<Integer>(); Deque<TreeNode> stack = new LinkedList<TreeNode>(); TreeNode cur = root; while(cur!= null||!stack.isEmpty()){ if (cur!=null){ stack.offerFirst(cur); cur = cur.left; } else{ cur = stack.pollFirst(); inorder.add(cur.key); cur = cur.right; } } return inorder; } }
package com.dev.jdbc; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Scanner; public class JDBCDeletion { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt = null; try { //step 1 Class.forName("com.mysql.jdbc.Driver"); System.out.println("driver loaded.."); //step 2 get the connection String url = "jdbc:mysql://localhost:3306/caps_buggers"; System.out.println("enter username"); String user = sc.nextLine(); System.out.println("enter password"); String password = sc.nextLine(); conn = DriverManager.getConnection(url,user,password); System.out.println("Connection Estd..."); //step 3 issue query String query="delete from users_info where userid = ?"; pstmt = conn.prepareStatement(query); System.out.println("enter user id "); int uid = sc.nextInt(); pstmt.setInt(1, uid); int count = pstmt.executeUpdate(); //step 4: process the result if(count>0) { System.out.println("row deleted..."); }else { System.out.println("error!!!"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //step 5:close jdbc objects finally { if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if(pstmt!=null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class NonBlockingServer { private Map<SocketChannel, List<byte[]>> keepDataTrack = new HashMap<>(); private ByteBuffer buffer = ByteBuffer.allocate(2 * 1024); private void startEchoServer() { try ( //try블록이 끝날 때 괄호 아래의 두 자원들을 자동으로 해제해준다 Selector selector = Selector.open(); //Selector는 자신에게 등록된 채널에 변경사항이 발생했는지 검사하고 변경사항이 발생한 채널에 접근하게 한다. ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //블로킹 소켓의 ServerSocket에 대응하는 논블로킹 소켓의 서버 소켓 채널을 생성한다 //블로킹 소켓과 다른점은, 소켓채널을 먼저 생성하고 포트로 바인딩한다. ){ if((serverSocketChannel.isOpen()) && (selector.isOpen())) { //Selector와 ServerSocketChannel이 제대로 생성되었는지 확인 serverSocketChannel.configureBlocking(false); //소켓채널의 블로킹을 풀어준다. 기본값은 true로 블로킹모드이다. serverSocketChannel.bind(new InetSocketAddress(8000)); //연결 대기할 포트를 8000번으로 지정하고, 생성된 ServerSocketChannel에 할당한다. //이것으로 ServerSocketChannel이 포트로부터 클라이언트의 연결을 생성할 수 있다. serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); //ServerSocketChannel객체를 Selector객체에 등록한다.Selector는 //연결요청 이벤트인 Selection.OP_ACCEPT를 감지한다. System.out.println("접속 대기중"); while(true) { selector.select(); //Selector에 등록된 채널에서 변경사항이 있는지 검사한다. //아무런 I/O이벤트도 발생하지 않았다면 스레드는 이 부분에서 블로킹처리된다. Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); //Selector에 등록된 채널 중에서 I/O이벤트가 발생한 채널들의 목록을 조회한다. while(keys.hasNext()) { SelectionKey key = (SelectionKey) keys.next(); keys.remove(); //I/O이벤트가 발생한 채널에서 동일한 이벤트가 감지되는 것을 방지하기 위해 조회된 목록에서 제거한다. if(!key.isValid()) { continue; } if(key.isAcceptable()) { //조회된 이벤트의 종류가 연결요청인지 확인하고 this.acceptOP(key,selector); //연결요청이라면 연결처리 메소드acceptOP로 이롱 }else if(key.isReadable()) { //조회된 이벤트의 종류가 데이터 수신인지 확인하고 this.readOP(key); //데이터 수신이라면 데이터 읽이 처리 메소드readOP로 이동 }else if(key.isWritable()) { //조회된 이벤트의 종류가 데이터 쓰기 가능인지 확인하고 this.writeOP(key); //데이터 쓰기 가능이라면 데이터 쓰기 처리 메소드writeOP로 이동 } } } } else { System.out.println("서버 소켓을 생성하지 못했습니다."); } } catch(IOException ex) { System.out.println(ex); } } private void acceptOP(SelectionKey key, Selector selector) throws IOException{ ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); //연결요청 이벤트가 발생하는 채널은 항상 ServerSocketChannel이므로 발생한 채널을 ServerSocketChannel로 캐스팅한다. SocketChannel socketChannel = serverChannel.accept(); //ServerSocketChannel을 이용하여 클라이언트의 연결을 수락하고 연결된 소켓 채널을 가져온다. socketChannel.configureBlocking(false); //연결된 클라이언트 소켓 채널을 nonblocking으로 설정한다. System.out.println("클라이언트 연결됨 :" + socketChannel.getRemoteAddress()); keepDataTrack.put(socketChannel, new ArrayList<byte[]>()); socketChannel.register(selector, SelectionKey.OP_ACCEPT); //클라이언트 소켓 채널을 Selector에 등록하여 I/O이벤트를 감시한다. } private void readOP(SelectionKey key) { try { SocketChannel socketChannel = (SocketChannel) key.channel(); buffer.clear(); //채널read메소드를 사용하기 전에 버퍼를 클리어한다. int numRead = -1; try { numRead = socketChannel.read(buffer); } catch(IOException e) { System.err.println("데이터 읽기 에러"); } if(numRead == -1) { this.keepDataTrack.remove(socketChannel); System.out.println("클라이언트 연결 종료 :" +socketChannel.getRemoteAddress()); socketChannel.close(); key.cancel(); return; } byte[] data = new byte[numRead]; System.arraycopy(buffer.array(), 0, data, 0, numRead); System.out.println(new String(data, "UTF-8") + "from" + socketChannel.getRemoteAddress()); doEchoJob(key,data); } catch(IOException ex) { System.err.println(ex); } } private void writeOP(SelectionKey key) throws IOException{ SocketChannel socketChannel = (SocketChannel) key.channel(); List<byte[]> channelData = keepDataTrack.get(socketChannel); Iterator<byte[]> its = channelData.iterator(); //Iterator는 컬렉션 클래스의 데이터를 읽어올 때 사용한다. while(its.hasNext()) { //hasNext -> next()가 예외를 throw하지 않고 원소를 반환하는 경우 true byte[] it = its.next(); //Iterator의 다음 요소를 돌려준다. its.remove(); //Iterator에 의해 반환되는 마지막 요소를 삭제한다. next()메소드 한번 호출당 한번 씩 호출할 수 있다. socketChannel.write(ByteBuffer.wrap(it)); } key.interestOps(SelectionKey.OP_ACCEPT); } private void doEchoJob(SelectionKey key, byte[] data) { SocketChannel socketChannel = (SocketChannel) key.channel(); List<byte[]> channelData = keepDataTrack.get(socketChannel); channelData.add(data); key.interestOps(SelectionKey.OP_ACCEPT); } public static void main(String[] args) { NonBlockingServer main = new NonBlockingServer(); main.startEchoServer(); } }
package pomocneKlase; import korisnici.Osoba; import java.util.List; public class PrijavaRegistracija { /* TODO: 1. Izmjeniti algoritam za prijavu tako da pretražuje po listi stringova 2. Nakon nađenog korisnika generisati novi objekat prijavljeniKorisnik 3. Prijava se vrši isključivo na osnovu prethodno učitanih fajlova u nizove!!! */ // Pronalaženje traženog korisnika u fajlu: public Osoba prijavaNaSistem(String korisnikckoIme, String lozinka, List<Osoba> listaKorisnika) { Osoba prijavljeniKorisnik = null; for (Osoba korisnik : listaKorisnika) { System.out.println("Trazeni: " + korisnikckoIme + " " + lozinka + " ; Nađeni: " + korisnik.getIme() + " " + korisnik.getLozinka()); if (korisnikckoIme.equals(korisnik.getKorisnickoIme()) && lozinka.equals(korisnik.getLozinka())) { prijavljeniKorisnik = korisnik; break; } } if (prijavljeniKorisnik == null) { System.out.println("Nije pronađen korisnik molimo pokušajte ponovo "); // TODO: Ovdje pokrenuti prozor kada korisnik nije pronađen } return prijavljeniKorisnik; } // TODO: Implementovati funkciju regostracija!!! public void registracija() { } }
package Restaurante; import java.util.TreeSet; public class Restaurante { TreeSet<Producto> productos = new TreeSet<Producto>(); TreeSet<Producto> productosPedidos = new TreeSet<Producto>(); // NO HACE FALTA NINGUN METODO Q DISTINGA LOS NUMEROS DE IDENTIFICACION PARA Q // HAYA REPETIDOS // PORQ LO HACE EL MISMO TREESET // ESTA ORDENADO PARA FACILITAR EL INGRESO DEL PRODUCTO YA QUE SE TIENE QUE // INGRESAR ID private String nombre2; private String cuit2; public Restaurante(String nombre2, String cuit2) { this.nombre2 = nombre2; this.cuit2 = cuit2; } // MUESTRA TODA LA ARRAY public Boolean mostrarCarta() { Integer contador = 0; for (Producto P : productos) { if (productos == null) { return false; } System.out.println(P.hashCode() + " -- " + P.toString()); } return false; } public EstadoPedido verEstado(Pedido pedido) { // HACER QUE EL PEDIDO TENGA UNA ID Y BUSCARLO POR ID return pedido.getEstado(); } public String getNombre2() { return nombre2; } public void setNombre2(String nombre2) { this.nombre2 = nombre2; } public String getCuit2() { return cuit2; } public void setCuit2(String cuit2) { this.cuit2 = cuit2; } }
package safeflyeu; import safeflyeu.model.Osiguranje; import safeflyeu.view.Izbornik; import safeflyeu.view.Login; import safeflyeu.view.Osiguranja; import safeflyeu.view.Registracija; import safeflyeu.view.SplashScreen; public class Start { public static void main(String[] args) { new SplashScreen().setVisible(true); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sia.ui.transaksi; /** * * @author ARCH */ public class Bayar extends javax.swing.JFrame { /** * Creates new form NewJFrame */ public Bayar() { initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); panelGlass5 = new usu.widget.glass.PanelGlass(); jDate = new javax.swing.JLabel(); jTgl = new javax.swing.JLabel(); panelGlass6 = new usu.widget.glass.PanelGlass(); jDate1 = new javax.swing.JLabel(); panelGlass7 = new usu.widget.glass.PanelGlass(); jDate2 = new javax.swing.JLabel(); jDate3 = new javax.swing.JLabel(); panelGlass8 = new usu.widget.glass.PanelGlass(); jDate4 = new javax.swing.JLabel(); jDate6 = new javax.swing.JLabel(); jDate7 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jDate8 = new javax.swing.JLabel(); jTextField4 = new javax.swing.JTextField(); btnAdd = new usu.widget.ButtonGlass(); btnRefresh = new usu.widget.ButtonGlass(); jPanel2 = new javax.swing.JPanel(); btnRefresh1 = new usu.widget.ButtonGlass(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); keluar = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(51, 51, 51)); jPanel1.setMinimumSize(new java.awt.Dimension(0, 0)); jPanel1.setPreferredSize(new java.awt.Dimension(600, 500)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); panelGlass5.setRound(false); jDate.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N jDate.setForeground(new java.awt.Color(255, 255, 255)); jDate.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jDate.setText("23-07-2015"); jDate.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jTgl.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N jTgl.setForeground(new java.awt.Color(255, 255, 255)); jTgl.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jTgl.setText("23:45"); jTgl.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); javax.swing.GroupLayout panelGlass5Layout = new javax.swing.GroupLayout(panelGlass5); panelGlass5.setLayout(panelGlass5Layout); panelGlass5Layout.setHorizontalGroup( panelGlass5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelGlass5Layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jDate, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(6, 6, 6) .addComponent(jTgl, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)) ); panelGlass5Layout.setVerticalGroup( panelGlass5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelGlass5Layout.createSequentialGroup() .addContainerGap() .addGroup(panelGlass5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDate, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTgl, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel1.add(panelGlass5, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 150, 50)); panelGlass6.setRound(false); jDate1.setFont(new java.awt.Font("Segoe UI Light", 0, 36)); // NOI18N jDate1.setForeground(new java.awt.Color(255, 255, 255)); jDate1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jDate1.setText("Bayar Tunai"); javax.swing.GroupLayout panelGlass6Layout = new javax.swing.GroupLayout(panelGlass6); panelGlass6.setLayout(panelGlass6Layout); panelGlass6Layout.setHorizontalGroup( panelGlass6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelGlass6Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jDate1) .addContainerGap(15, Short.MAX_VALUE)) ); panelGlass6Layout.setVerticalGroup( panelGlass6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelGlass6Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jDate1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel1.add(panelGlass6, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 0, 210, 60)); panelGlass7.setRound(false); jDate2.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N jDate2.setForeground(new java.awt.Color(255, 255, 255)); jDate2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jDate2.setText("No. Transaksi"); jDate3.setBackground(new java.awt.Color(204, 204, 204)); jDate3.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N jDate3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jDate3.setText("738jahsksak"); jDate3.setOpaque(true); javax.swing.GroupLayout panelGlass7Layout = new javax.swing.GroupLayout(panelGlass7); panelGlass7.setLayout(panelGlass7Layout); panelGlass7Layout.setHorizontalGroup( panelGlass7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelGlass7Layout.createSequentialGroup() .addContainerGap() .addComponent(jDate2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jDate3, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelGlass7Layout.setVerticalGroup( panelGlass7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelGlass7Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(panelGlass7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jDate2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jDate3, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27)) ); jPanel1.add(panelGlass7, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 80, 340, 50)); panelGlass8.setRound(false); jDate4.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N jDate4.setForeground(new java.awt.Color(255, 255, 255)); jDate4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jDate4.setText("Total Harga"); jDate6.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N jDate6.setForeground(new java.awt.Color(255, 255, 255)); jDate6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jDate6.setText("Bayar"); jDate7.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N jDate7.setForeground(new java.awt.Color(255, 255, 255)); jDate7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jDate7.setText("Tax"); jTextField1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField1.setText("jTextField1"); jTextField2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField2.setText("jTextField1"); jTextField3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField3.setText("jTextField1"); jDate8.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N jDate8.setForeground(new java.awt.Color(255, 255, 255)); jDate8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jDate8.setText("Kembali"); jTextField4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTextField4.setText("jTextField1"); javax.swing.GroupLayout panelGlass8Layout = new javax.swing.GroupLayout(panelGlass8); panelGlass8.setLayout(panelGlass8Layout); panelGlass8Layout.setHorizontalGroup( panelGlass8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelGlass8Layout.createSequentialGroup() .addContainerGap() .addGroup(panelGlass8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelGlass8Layout.createSequentialGroup() .addComponent(jDate7, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(panelGlass8Layout.createSequentialGroup() .addComponent(jDate4, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(panelGlass8Layout.createSequentialGroup() .addComponent(jDate6, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(panelGlass8Layout.createSequentialGroup() .addComponent(jDate8, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(25, Short.MAX_VALUE)) ); panelGlass8Layout.setVerticalGroup( panelGlass8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelGlass8Layout.createSequentialGroup() .addContainerGap() .addGroup(panelGlass8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE) .addComponent(jDate4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(panelGlass8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jDate7, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(8, 8, 8) .addGroup(panelGlass8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jDate6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(panelGlass8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jDate8, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(17, Short.MAX_VALUE)) ); jPanel1.add(panelGlass8, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 150, 340, 190)); btnAdd.setForeground(new java.awt.Color(255, 255, 255)); btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/doc_new.png"))); // NOI18N btnAdd.setFont(new java.awt.Font("Meiryo UI", 0, 12)); // NOI18N btnAdd.setRoundRect(true); btnAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddActionPerformed(evt); } }); jPanel1.add(btnAdd, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 370, 110, 40)); btnRefresh.setForeground(new java.awt.Color(255, 255, 255)); btnRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/Printer.png"))); // NOI18N btnRefresh.setFont(new java.awt.Font("Meiryo UI", 0, 12)); // NOI18N btnRefresh.setPreferredSize(new java.awt.Dimension(117, 41)); btnRefresh.setRoundRect(true); btnRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefreshActionPerformed(evt); } }); jPanel1.add(btnRefresh, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 430, 50, -1)); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 530, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 460, Short.MAX_VALUE) ); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 10, 530, 460)); btnRefresh1.setForeground(new java.awt.Color(255, 255, 255)); btnRefresh1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/doc_refresh.png"))); // NOI18N btnRefresh1.setFont(new java.awt.Font("Meiryo UI", 0, 12)); // NOI18N btnRefresh1.setPreferredSize(new java.awt.Dimension(117, 41)); btnRefresh1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefresh1ActionPerformed(evt); } }); jPanel1.add(btnRefresh1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 370, -1, -1)); jMenuBar1.setBackground(new java.awt.Color(51, 51, 51)); jMenuBar1.setBorder(null); jMenuBar1.setPreferredSize(new java.awt.Dimension(1, 20)); jMenu1.setBackground(new java.awt.Color(51, 51, 51)); jMenu1.setForeground(new java.awt.Color(255, 255, 255)); jMenu1.setText("Exit"); keluar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0)); keluar.setText("jMenuItem1"); keluar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { keluarActionPerformed(evt); } }); jMenu1.add(keluar); jMenuBar1.add(jMenu1); jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0)); jMenuItem1.setText("jMenuItem1"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu2.add(jMenuItem1); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 938, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 488, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); setSize(new java.awt.Dimension(954, 546)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed // TODO add your handling code here: // err_msg.setVisible(true); // createPengguna(); }//GEN-LAST:event_btnAddActionPerformed private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed // TODO add your handling code here: // loadTable(); // clear(); }//GEN-LAST:event_btnRefreshActionPerformed private void btnRefresh1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefresh1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btnRefresh1ActionPerformed private void keluarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_keluarActionPerformed // TODO add your handling code here: this.dispose(); }//GEN-LAST:event_keluarActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed // TODO add your handling code here: this.dispose(); }//GEN-LAST:event_jMenuItem1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Bayar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Bayar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Bayar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Bayar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Bayar().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private usu.widget.ButtonGlass btnAdd; private usu.widget.ButtonGlass btnRefresh; private usu.widget.ButtonGlass btnRefresh1; private javax.swing.JLabel jDate; private javax.swing.JLabel jDate1; private javax.swing.JLabel jDate2; private javax.swing.JLabel jDate3; private javax.swing.JLabel jDate4; private javax.swing.JLabel jDate6; private javax.swing.JLabel jDate7; private javax.swing.JLabel jDate8; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JLabel jTgl; private javax.swing.JMenuItem keluar; private usu.widget.glass.PanelGlass panelGlass5; private usu.widget.glass.PanelGlass panelGlass6; private usu.widget.glass.PanelGlass panelGlass7; private usu.widget.glass.PanelGlass panelGlass8; // End of variables declaration//GEN-END:variables }
package com.jim.multipos.ui.mainpospage.model; import com.jim.multipos.data.db.model.Discount; import com.jim.multipos.data.db.model.order.OrderProduct; /** * Created by developer on 27.12.2017. */ public class DiscountItem { private Discount discount; private double ammount; public Discount getDiscount() { return discount; } public void setDiscount(Discount discount) { this.discount = discount; } public double getAmmount() { return ammount; } public void setAmmount(double ammount) { this.ammount = ammount; } }
package cloud.metaapi.sdk.clients.copy_factory.models; import java.util.List; /** * CopyFactory calendar new filter */ public class CopyFactoryStrategyCalendarNewsFilter { /** * List of calendar news priorities to stop trading on, or {@code null}, leave empty to disable calendar news filter. * One of election, high, medium, low. */ public List<String> priorities; /** * Optional time interval specifying when to force close an already open position before calendar news, * or {@code null}. Default value is 60 minutes */ public Integer closePositionTimeGapInMinutes; /** * Optional time interval specifying when it is still allowed to open position before calendar news, or {@code null}. * Default value is 120 minutes */ public Integer openPositionPrecedingTimeGapInMinutes; /** * Optional time interval specifying when it is allowed to open position after calendar news, or {@code null}. * Default value is 60 minutes */ public Integer openPositionFollowingTimeGapInMinutes; }
package com.ymt.tools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * */ public class CmdUtil { private static final Logger logger = LoggerFactory.getLogger(CmdUtil.class); private String deviceId; public CmdUtil(String deviceId) { this.deviceId = deviceId; } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } /** * 调用并执行控制台命令 * * @param cmd 控制台命令 * @return output */ public String runAdbCmd(String cmd) { String adbCmd = String.format("adb %s", cmd); logger.debug("执行的adb 命令为:{}",adbCmd); return this.run(adbCmd); } /** * 调用并执行控制台命令 * * @param cmd 控制台命令 * @return output */ public String runAdbShell(String cmd) { String adbCmd = String.format("adb -s %s shell %s",this.deviceId, cmd); logger.debug("执行的shell 命令为:{}",adbCmd); return this.run(adbCmd); } /** * 调用并执行控制台命令 * * @param cmd 控制台命令 * @return output */ public String run(String cmd) { String line; String cmdOut = ""; BufferedReader br = null; try { br = getBufferedReader(cmd); while ((line = br.readLine()) != null) { cmdOut = cmdOut + line + System.getProperty("line.separator"); } } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } logger.debug("执行的cmd 命令为 : {}", cmd); logger.debug("执行的cmd 命令结果为 : {}", cmdOut); return null == cmdOut ? null : cmdOut.trim(); } /** * 判断是否Windows操作系统 * * @return 是否windows系统 */ public static boolean isWindows() { String os = System.getProperty("os.name"); return (os.toLowerCase().startsWith("win")) ? true : false; } public BufferedReader getBufferedReader(String cmd) { BufferedReader br = null; Process p; try { if (isWindows()) { String command = "cmd /c " + cmd; p = Runtime.getRuntime().exec(command); } else { String[] shell = {"sh", "-c", cmd}; p = Runtime.getRuntime().exec(shell); } br = new BufferedReader(new InputStreamReader(p.getInputStream())); } catch (IOException e) { e.printStackTrace(); } return br; } public static void main(String args[]) { CmdUtil cmd = new CmdUtil(null); cmd.run("taskkill /f /t /im cmd.exe"); cmd.run("taskkill /f /t /im adb.exe"); cmd.run("taskkill /f /t /im conhost.exe"); } }
package com.mod.apigateway.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; @RestController public class FallbackController { @GetMapping("/courseFallback") public Mono<ResponseEntity<?>> courseFallback() { return Mono.just(new ResponseEntity<String>("Course service down", HttpStatus.SERVICE_UNAVAILABLE)); } @GetMapping("/userFallback") public Mono<ResponseEntity<?>> userFallback() { return Mono.just(new ResponseEntity<String>("User service down", HttpStatus.SERVICE_UNAVAILABLE)); } @GetMapping("/userCourseFallback") public Mono<ResponseEntity<?>> userCourseFallback() { return Mono.just(new ResponseEntity<String>("User-Course service down", HttpStatus.SERVICE_UNAVAILABLE)); } @GetMapping("/authFallback") public Mono<ResponseEntity<?>> authFallback() { return Mono.just(new ResponseEntity<String>("Auth service down", HttpStatus.SERVICE_UNAVAILABLE)); } }
package Tasks.LessonSix.Converters; public class FahrenheitKelvin extends BaseConverter { private double inputFahrenheit; FahrenheitKelvin(double inputFahrenheit) { this.inputFahrenheit = inputFahrenheit; } private double fahrenheitKelvinFormula(double value) { return (value - 32) * 5/9 + 273.15; } @Override public double convert() { return fahrenheitKelvinFormula(inputFahrenheit); } }
package com.example.harry.cymbyl_3.Fragments; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.harry.cymbyl_3.MainActivity; import com.example.harry.cymbyl_3.R; public class AboutFragment extends Fragment { private ImageView mStartButton; private TextView mDescription; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); mStartButton = view.findViewById(R.id.about_StartBTN); mStartButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((MainActivity)getActivity()).changeFragment(2); } }); mDescription = view.findViewById(R.id.about_description); mDescription.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((MainActivity)getActivity()).changeFragment(0); } }); return view; } }
package uk.gov.hmcts.befta.dse.ccd; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.gov.hmcts.befta.dse.ccd.definition.converter.ExcelTransformer; import uk.gov.hmcts.befta.dse.ccd.definition.converter.JsonTransformer; public class DefinitionConverter { private static Logger logger = LoggerFactory.getLogger(DefinitionConverter.class); public static final String DEFAULT_DEFINITIONS_PATH = "uk/gov/hmcts/befta/dse/ccd/definitions/valid"; /** * Main method to convert between json and excel versions of a definition file * @param args * arg1: to-json | to-excel : key word to convert from excel to json or from json to excel * arg2 input file path for excel document or parent jurisdiction folder for json version * arg3 (Optional) output folder path for resulting json or excel file. By default will use parent folder from the input location * arg4 (Optional) Boolean: true - use jurisdiction name to generate the parent folder name when converting from excel to JSON, * false - use file name as the folder name */ public static void main(String[] args) { validateArgs(args); String transformationKeyword = args[0]; String inputPath = args[1]; String outputPath = args.length > 2 ? args[2] : null; boolean useJurisdictionAsFolder = args.length <= 3 || Boolean.parseBoolean(args[3]); try { switch (transformationKeyword) { case "to-json": new ExcelTransformer(inputPath, outputPath, useJurisdictionAsFolder).transformToJson(); break; case "to-excel": new JsonTransformer(inputPath, outputPath).transformToExcel(); break; } System.out.println("Definition conversion completed successfully."); } catch (Exception ex) { ex.printStackTrace(); } finally { } } private static void validateArgs(String[] args) throws IllegalArgumentException { String instructions = "Arguments expected as follows: <to-json|to-excel> <input folder/file path> <Optional: output path> " + "<Optional boolean: use jurisdiction as as folder name for json to excel transformation>"; if (args.length < 2) { logger.info(instructions); throw new IllegalArgumentException( "At least 2 arguments expected: <to-json|to-excel> <input folder/file path> " + "<Optional: output path> <Optional boolean: use jurisdiction as as folder name for json to excel transformation>"); } String transformerKeyword = args[0]; if (!transformerKeyword.equals("to-json") && !transformerKeyword.equals("to-excel")) { logger.info(instructions); throw new IllegalArgumentException( "First arg should be either 'to-json' or 'to-excel' but got " + transformerKeyword); } if (args.length > 2) { String outputPath = args[2]; if (outputPath.equals("true") || outputPath.equals("false")) { logger.info(instructions); throw new IllegalArgumentException( "Third arg should be a path not a boolean, if you wish to set Jurisdiction " + "name boolean and want the output path to be the same as the input path you can put null for this arg"); } } if (args.length > 3) { String jurisdictionAsFolderBool = args[3]; logger.info(instructions); if (!jurisdictionAsFolderBool.equals("true") && !jurisdictionAsFolderBool.equals("false")) { throw new IllegalArgumentException( "Forth arg should be a boolean but got: " + jurisdictionAsFolderBool); } } } }
package LC1800_2000.LC1800_1850; public class LC1816_Truncate_Sentence { public String truncateSentence(String s, int k) { StringBuilder sb = new StringBuilder(); String[] ss = s.split(" "); for (int i = 0; i < k; ++i) { sb.append(ss[i]); if (i != k - 1) sb.append(" "); } return sb.toString(); } }
/** */ package sdo.util; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; import sdo.*; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see sdo.SdoPackage * @generated */ public class SdoAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static SdoPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SdoAdapterFactory() { if (modelPackage == null) { modelPackage = SdoPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SdoSwitch<Adapter> modelSwitch = new SdoSwitch<Adapter>() { @Override public Adapter caseSDO(SDO object) { return createSDOAdapter(); } @Override public Adapter caseSDOSystemElement(SDOSystemElement object) { return createSDOSystemElementAdapter(); } @Override public Adapter caseOrganization(Organization object) { return createOrganizationAdapter(); } @Override public Adapter caseOrganizationProperty(OrganizationProperty object) { return createOrganizationPropertyAdapter(); } @Override public Adapter caseConfigurationProfile(ConfigurationProfile object) { return createConfigurationProfileAdapter(); } @Override public Adapter caseServiceProfile(ServiceProfile object) { return createServiceProfileAdapter(); } @Override public Adapter caseDeviceProfile(DeviceProfile object) { return createDeviceProfileAdapter(); } @Override public Adapter caseStatus(Status object) { return createStatusAdapter(); } @Override public Adapter caseNameValue(NameValue object) { return createNameValueAdapter(); } @Override public Adapter caseUniqueIdentifier(UniqueIdentifier object) { return createUniqueIdentifierAdapter(); } @Override public Adapter caseDependencyType(DependencyType object) { return createDependencyTypeAdapter(); } @Override public Adapter caseSDOService(SDOService object) { return createSDOServiceAdapter(); } @Override public Adapter caseParameter(Parameter object) { return createParameterAdapter(); } @Override public Adapter caseConfigurationSet(ConfigurationSet object) { return createConfigurationSetAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link sdo.SDO <em>SDO</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.SDO * @generated */ public Adapter createSDOAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.SDOSystemElement <em>SDO System Element</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.SDOSystemElement * @generated */ public Adapter createSDOSystemElementAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.Organization <em>Organization</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.Organization * @generated */ public Adapter createOrganizationAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.OrganizationProperty <em>Organization Property</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.OrganizationProperty * @generated */ public Adapter createOrganizationPropertyAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.ConfigurationProfile <em>Configuration Profile</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.ConfigurationProfile * @generated */ public Adapter createConfigurationProfileAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.ServiceProfile <em>Service Profile</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.ServiceProfile * @generated */ public Adapter createServiceProfileAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.DeviceProfile <em>Device Profile</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.DeviceProfile * @generated */ public Adapter createDeviceProfileAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.Status <em>Status</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.Status * @generated */ public Adapter createStatusAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.NameValue <em>Name Value</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.NameValue * @generated */ public Adapter createNameValueAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.UniqueIdentifier <em>Unique Identifier</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.UniqueIdentifier * @generated */ public Adapter createUniqueIdentifierAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.DependencyType <em>Dependency Type</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.DependencyType * @generated */ public Adapter createDependencyTypeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.SDOService <em>SDO Service</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.SDOService * @generated */ public Adapter createSDOServiceAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.Parameter <em>Parameter</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.Parameter * @generated */ public Adapter createParameterAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link sdo.ConfigurationSet <em>Configuration Set</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see sdo.ConfigurationSet * @generated */ public Adapter createConfigurationSetAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //SdoAdapterFactory
package instruments.winds.airreservoirs; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class BagpipeTest{ Bagpipe bagpipe; @Before public void before() { bagpipe = new Bagpipe("DM1", "Rooseback's Bagpipes", "Great Highland Bagpipe", 105.86, 188.90, "boo boooo", 3,"3/4"); } @Test public void bagpipeCanHaveModel() { assertEquals("DM1", bagpipe.getModel()); } @Test public void bagpipeCanHaveBrand() { assertEquals("Rooseback's Bagpipes", bagpipe.getBrand()); } @Test public void bagpipeCanHaveType() { assertEquals("Great Highland Bagpipe", bagpipe.getType()); } @Test public void bagpipeCanHaveNumberOfDroneReeds() { assertEquals(3, bagpipe.getNumberOfDroneReeds()); } @Test public void bagpipeCanHaveSize() { assertEquals("3/4", bagpipe.getSize()); } @Test public void bagpipeCanHaveBuyingPrice() { assertEquals(105.86, bagpipe.getBuyingPrice(), 0.001); } @Test public void bagpipeCanHaveSellingPrice() { assertEquals(188.90, bagpipe.getSellingPrice(), 0.001); } @Test public void bagpipeCanPlay() { assertEquals("boo boooo", bagpipe.play()); } @Test public void bagpipeHaveAMarkup() { assertEquals(78.44, bagpipe.markup(), 0.01); } }
package net.razorvine.pickle; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.Set; /** * Object output pretty printing, to help with the test scripts. * Nothing fancy, just a simple readable output format for a handfull of classes. * * @author Irmen de Jong (irmen@razorvine.net) */ public class PrettyPrint { /*** * Prettyprint into a string, no type header. */ public static String printToStr(Object o) { StringWriter sw=new StringWriter(); try { print(o,sw,false); } catch (IOException e) { sw.write("<<error>>"); } return sw.toString().trim(); } /** * Prettyprint directly to the standard output. */ public static void print(Object o) throws IOException { OutputStreamWriter w=new OutputStreamWriter(System.out,"UTF-8"); print(o, w, true); w.flush(); } /** * Prettyprint the object to the outputstream. (UTF-8 output encoding is used) */ public static void print(Object o, OutputStream outs, boolean typeheader) throws IOException { OutputStreamWriter w=new OutputStreamWriter(outs,"UTF-8"); print(o,w,typeheader); w.flush(); } /** * Prettyprint the object to the writer. */ public static void print(Object o, java.io.Writer writer, boolean typeheader) throws IOException { if (o == null) { if(typeheader) writer.write("null object\n"); writer.write("null\n"); writer.flush(); return; } Class<?> arraytype = o.getClass().getComponentType(); if (arraytype != null) { if(typeheader) writer.write("array of " + arraytype+"\n"); if (!arraytype.isPrimitive()) { writer.write(Arrays.deepToString((Object[]) o)); writer.write("\n"); } else if (arraytype.equals(Integer.TYPE)) { writer.write(Arrays.toString((int[]) o)); writer.write("\n"); } else if (arraytype.equals(Double.TYPE)) { writer.write(Arrays.toString((double[]) o)); writer.write("\n"); } else if (arraytype.equals(Boolean.TYPE)) { writer.write(Arrays.toString((boolean[]) o)); writer.write("\n"); } else if (arraytype.equals(Short.TYPE)) { writer.write(Arrays.toString((short[]) o)); writer.write("\n"); } else if (arraytype.equals(Long.TYPE)) { writer.write(Arrays.toString((long[]) o)); writer.write("\n"); } else if (arraytype.equals(Float.TYPE)) { writer.write(Arrays.toString((float[]) o)); writer.write("\n"); } else if (arraytype.equals(Character.TYPE)) { writer.write(Arrays.toString((char[]) o)); writer.write("\n"); } else if (arraytype.equals(Byte.TYPE)) { writer.write(Arrays.toString((byte[]) o)); writer.write("\n"); } else { writer.write("?????????\n"); } } else if (o instanceof Set) { @SuppressWarnings("unchecked") Set<Object> set = (Set<Object>) o; ArrayList<String> list=new ArrayList<String>(set.size()); for(Object obj: set) { list.add(obj.toString()); } Collections.sort(list); if(typeheader) { writer.write(o.getClass().getName()); writer.write("\n"); } writer.write(list.toString()); writer.write("\n"); } else if (o instanceof Map) { @SuppressWarnings("unchecked") Map<Object,Object> map=(Map<Object, Object>) o; ArrayList<String> list=new ArrayList<String>(map.size()); for(Object key: map.keySet()) { list.add(key.toString()+"="+map.get(key)); } Collections.sort(list); if(typeheader) { writer.write(o.getClass().getName()); writer.write("\n"); } writer.write(list.toString()); writer.write("\n"); } else if (o instanceof Collection) { if(typeheader) { writer.write(o.getClass().getName()); writer.write("\n"); } writer.write(o.toString()); writer.write("\n"); } else if (o instanceof String) { if(typeheader) writer.write("String\n"); writer.write(o.toString()); writer.write("\n"); } else if (o instanceof java.util.Calendar) { if(typeheader) writer.write("java.util.Calendar\n"); DateFormat f = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.UK); Calendar c = (Calendar) o; writer.write(f.format(c.getTime()) + " millisec=" + c.get(Calendar.MILLISECOND)+"\n"); } else { if(typeheader) { writer.write(o.getClass().getName()); writer.write("\n"); } writer.write(o.toString()); writer.write("\n"); } writer.flush(); } }
package com.example.dataaccessmybatis; import com.example.dataaccessmybatis.model.Note; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DataAccessMybatisApplication { public static void main(String[] args) { SpringApplication.run(DataAccessMybatisApplication.class, args); } }
package com.didiglobal.thriftmock.server; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.thrift.TBase; import org.apache.thrift.TFieldRequirementType; import org.apache.thrift.meta_data.FieldMetaData; import org.apache.thrift.meta_data.FieldValueMetaData; import org.apache.thrift.protocol.TStruct; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TType; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import java.util.BitSet; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; /** * The origin source of this class is generated by thrift command with a thrift file, * I modified the code to make it work without dependency on any specified thrift service. */ public class MockResult implements TBase<MockResult, MockResult._Fields>, java.io.Serializable, Cloneable, Comparable<MockResult> { private static final String SUCCESS_NAME = "success"; private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(SUCCESS_NAME, TType.STRUCT, (short)0); public final String methodName; public final TStruct structDesc; public final Map<_Fields, FieldMetaData> metaDataMap; public final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<>(); private TBase success; public MockResult(String methodName, TBase value) { this.methodName = methodName; this.success = value; this.structDesc = new TStruct(methodName+"_result"); //init metaDatMap Map<_Fields, FieldMetaData> tmpMap = new EnumMap<>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new FieldMetaData(SUCCESS_NAME, TFieldRequirementType.DEFAULT, new FieldValueMetaData(TType.STRUCT , value.getClass().getCanonicalName()))); metaDataMap = Collections.unmodifiableMap(tmpMap); FieldMetaData.addStructMetaDataMap(MockResult.class, metaDataMap); schemes.put(StandardScheme.class, new MockResultStandardSchemeFactory(structDesc)); schemes.put(TupleScheme.class, new MockResultTupleSchemeFactory()); } public MockResult(MockResult mockResult) { this(mockResult.methodName, mockResult.success); } /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, SUCCESS_NAME); private static final Map<String, _Fields> byName = new HashMap<>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } private final short thriftId; private final String fieldName; _Fields(short thriftId, String fieldName) { this.thriftId = thriftId; this.fieldName = fieldName; } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { return fieldId == 0 ? SUCCESS : null; } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) { throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); } return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } public short getThriftFieldId() { return thriftId; } public String getFieldName() { return fieldName; } } /** * Performs a deep copy on <i>other</i>. */ /** public MockResult(MockResult other) { if (other.isSetSuccess()) { this.success = other.success; } } **/ //face deep copy public MockResult deepCopy() { return this; } @Override public void clear() { this.success = null; } public TBase getSuccess() { return this.success; } public MockResult setSuccess(TBase success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public void setFieldValue(_Fields field, Object value) { if (field == _Fields.SUCCESS) { if (value == null) { unsetSuccess(); } else { setSuccess((TBase) value); } } } public Object getFieldValue(_Fields field) { if (field == _Fields.SUCCESS) { return getSuccess(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } if (field != _Fields.SUCCESS) { throw new IllegalStateException(); } return isSetSuccess(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof MockResult) return this.equals((MockResult)that); return false; } public boolean equals(MockResult that) { if (that == null) { return false; } boolean thisPresentSuccess = this.isSetSuccess(); boolean thatPresentSuccess = that.isSetSuccess(); if (thisPresentSuccess || thatPresentSuccess) { if (!(thisPresentSuccess && thatPresentSuccess)) return false; if (!this.success.equals(that.success)) return false; } return true; } @Override public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); boolean presentSuccess = isSetSuccess(); builder.append(presentSuccess); if (presentSuccess) builder.append(success); return builder.toHashCode(); } @Override public int compareTo(MockResult other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("MockResult("); sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class MockResultStandardSchemeFactory implements SchemeFactory { private TStruct desc; public MockResultStandardSchemeFactory(TStruct desc) { this.desc = desc; } public MockResultStandardScheme getScheme() { return new MockResultStandardScheme(desc); } } private static class MockResultStandardScheme extends StandardScheme<MockResult> { private TStruct desc; public MockResultStandardScheme(TStruct desc) { this.desc = desc; } public void read(org.apache.thrift.protocol.TProtocol iprot, MockResult struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == TType.STOP) { break; } processSchemeField(schemeField, iprot, struct); iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } private void processSchemeField(org.apache.thrift.protocol.TField schemeField, org.apache.thrift.protocol.TProtocol iprot, MockResult struct) throws org.apache.thrift.TException { if (schemeField.id == SUCCESS_FIELD_DESC.id) { readSuccessStruct(schemeField, iprot, struct); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } } private void readSuccessStruct(org.apache.thrift.protocol.TField schemeField, org.apache.thrift.protocol.TProtocol iprot, MockResult struct) throws org.apache.thrift.TException { if (schemeField.type == TType.STRUCT) { try { struct.success = struct.success.getClass().newInstance(); } catch (Exception e) { throw new IllegalArgumentException("init object failed:" + struct.success.getClass() + e); } struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } } public void write(org.apache.thrift.protocol.TProtocol oprot, MockResult struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(desc); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class MockResultTupleSchemeFactory implements SchemeFactory { public MockResultTupleScheme getScheme() { return new MockResultTupleScheme(); } } private static class MockResultTupleScheme extends TupleScheme<MockResult> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, MockResult struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetSuccess()) { struct.success.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, MockResult struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { try { struct.success = struct.success.getClass().newInstance(); } catch (Exception e) { throw new IllegalArgumentException("init object failed:" + struct.success.getClass() + e); } struct.success.read(iprot); struct.setSuccessIsSet(true); } } } }
package cn.canlnac.onlinecourse.data.entity.mapper; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import cn.canlnac.onlinecourse.data.entity.UploadEntity; import cn.canlnac.onlinecourse.domain.Upload; /** * 上传文件类转换. */ @Singleton public class UploadEntityDataMapper { @Inject public UploadEntityDataMapper() {} /** * 转换 * @param uploadEntity 上传文件类 * @return */ public Upload transform(UploadEntity uploadEntity) { Upload upload = null; if (uploadEntity != null) { upload = new Upload(); upload.setFileUrl(uploadEntity.getFileName()); upload.setFileSize(uploadEntity.getFileSize()); upload.setFileType(uploadEntity.getFileType()); } return upload; } /** * 转换列表 * @param uploadEntityList 上传文件实体类列表 * @return */ public List<Upload> transform(List<UploadEntity> uploadEntityList) { List<Upload> uploadList = new ArrayList<>(uploadEntityList.size()); Upload upload; for (UploadEntity uploadEntity : uploadEntityList) { upload = transform(uploadEntity); if (upload != null) { uploadList.add(upload); } } return uploadList; } }
package com.vilio.bps.temptest.bean; /** * Created by dell on 2017/5/9/0009. */ public class BaffleData { private String returnCodeA; private String totalPriceA; private String returnCodeB; private String totalPriceB; private String returnCodeC; private String totalPriceC; public String getReturnCodeA() { return returnCodeA; } public void setReturnCodeA(String returnCodeA) { this.returnCodeA = returnCodeA; } public String getTotalPriceA() { return totalPriceA; } public void setTotalPriceA(String totalPriceA) { this.totalPriceA = totalPriceA; } public String getReturnCodeB() { return returnCodeB; } public void setReturnCodeB(String returnCodeB) { this.returnCodeB = returnCodeB; } public String getTotalPriceB() { return totalPriceB; } public void setTotalPriceB(String totalPriceB) { this.totalPriceB = totalPriceB; } public String getReturnCodeC() { return returnCodeC; } public void setReturnCodeC(String returnCodeC) { this.returnCodeC = returnCodeC; } public String getTotalPriceC() { return totalPriceC; } public void setTotalPriceC(String totalPriceC) { this.totalPriceC = totalPriceC; } }
package com.zngcloudcms.dao; public class MultipleDataSourceAspectAdvice { /*@Pointcut("execution(* com.zngcloudcms.dao.mysql.*.*(..))") public void doMySql() { } @Pointcut("execution(* com.zngcloudcms.dao.mssql..*(..))") public void doMsSql(){} @Pointcut("execution(* com.zngcloudcms.dao.oracle..*(..))") public void doOracle(){} @Before("doMySql()") public void doMySqlBefore(JoinPoint joinPoint) { MultipleDataSource.setDataSourceKey("mySqlDataSource"); } @After("doMySql()") public void doMySqlAfter(JoinPoint joinPoint) { MultipleDataSource.setDataSourceKey("mySqlDataSource"); } @Before("doMsSql()") public void doMsSqlBefore(JoinPoint joinPoint) { MultipleDataSource.setDataSourceKey("MsSqlDataSource"); } @After("doMsSql()") public void doMsSqlAfter(JoinPoint joinPoint) { MultipleDataSource.setDataSourceKey("mySqlDataSource"); } */ }
package geometry.service; import geometry.entity.Circle; import geometry.entity.Figure; /** * class CircleCreator. * * @author Ihor Zhytchenko (igor.zhytchenko@gmail.com) * @version $1$ * @since 18.08.2018 */ public class CircleCreator implements Creator { @Override public Figure createFigure() { return new Circle(); } }
package com.fleet.cxf; import com.alibaba.fastjson.JSON; import com.fleet.cxf.entity.User; import com.fleet.cxf.service.UserService; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory; import org.apache.cxf.transport.http.HTTPConduit; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class CxfApplicationTests { /** * 调用方式:动态调用 */ @Test public void test1() throws Exception { JaxWsDynamicClientFactory jaxWsDynamicClientFactory = JaxWsDynamicClientFactory.newInstance(); Client client = jaxWsDynamicClientFactory.createClient("http://127.0.0.1:8000/services/userService?wsdl"); Object[] objects = client.invoke("getName", 1L); System.out.println("查询到用户名:" + objects[0].toString()); objects = client.invoke("get", 1L); System.out.println("查询到用户:" + JSON.toJSONString(objects[0])); } /** * 调用方式:通过接口协议获取数据类型 */ @Test public void test2() { JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean(); jaxWsProxyFactoryBean.setAddress("http://127.0.0.1:8000/services/userService?wsdl"); jaxWsProxyFactoryBean.setServiceClass(UserService.class); UserService userService = (UserService) jaxWsProxyFactoryBean.create(); String name = userService.getName(1L); System.out.println("查询到用户名:" + name); User user = userService.get(1L); System.out.println("查询到用户:" + JSON.toJSONString(user)); } /** * 调用方式:通过接口协议获取数据类型,设置链接超时和响应时间 */ @Test public void test3() { JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean(); jaxWsProxyFactoryBean.setAddress("http://127.0.0.1:8000/services/userService?wsdl"); jaxWsProxyFactoryBean.setServiceClass(UserService.class); UserService userService = (UserService) jaxWsProxyFactoryBean.create(); Client client = ClientProxy.getClient(userService); HTTPConduit httpConduit = (HTTPConduit) client.getConduit(); HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); httpClientPolicy.setConnectionTimeout(1000); httpClientPolicy.setReceiveTimeout(1000); httpConduit.setClient(httpClientPolicy); String name = userService.getName(1L); System.out.println("查询到用户名:" + name); User user = userService.get(1L); System.out.println("查询到用户:" + JSON.toJSONString(user)); } /** * 调用方式:HttpClient 调用 */ @Test public void test4() throws Exception { String address = "http://127.0.0.1:8000/services/userService"; HttpPost request = new HttpPost(address); request.setHeader("Content-Type", "application/soap+xml; charset=utf-8"); String requestXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + " xmlns:sam=\"http://services.cxf.fleet.com\" " + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body>" + "<sam:getName>" + "<id>1</id>" + "</sam:getName>" + "</soap:Body>" + "</soap:Envelope>"; HttpEntity entity = new StringEntity(requestXml, "UTF-8"); request.setEntity(entity); HttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse httpResponse = httpClient.execute(request); if (httpResponse.getStatusLine().getStatusCode() == 200) { String jsonString = EntityUtils.toString(httpResponse.getEntity()); System.out.println("查询到用户名:" + jsonString); } } /** * 调用方式:HttpClient 调用 */ @Test public void test5() throws Exception { String address = "http://127.0.0.1:8000/services/userService"; HttpPost request = new HttpPost(address); request.setHeader("Content-Type", "application/soap+xml; charset=utf-8"); String requestXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + " xmlns:sam=\"http://services.cxf.fleet.com\" " + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body>" + "<sam:get>" + "<id>1</id>" + "</sam:get>" + "</soap:Body>" + "</soap:Envelope>"; HttpEntity entity = new StringEntity(requestXml, "UTF-8"); request.setEntity(entity); HttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse httpResponse = httpClient.execute(request); if (httpResponse.getStatusLine().getStatusCode() == 200) { String jsonString = EntityUtils.toString(httpResponse.getEntity()); System.out.println("查询到用户:" + jsonString); } } }
package com.tencent.mm.plugin.game.model; import com.tencent.mm.plugin.ac.a; import com.tencent.mm.plugin.game.e.c; import com.tencent.mm.pluginsdk.model.app.f; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.Iterator; import java.util.LinkedList; class k$1 implements Runnable { final /* synthetic */ LinkedList jLR; k$1(LinkedList linkedList) { this.jLR = linkedList; } public final void run() { LinkedList linkedList = new LinkedList(); Iterator it = this.jLR.iterator(); while (it.hasNext()) { Iterator it2 = j.m(((k) it.next()).optJSONArray("items")).iterator(); while (it2.hasNext()) { d dVar = (d) it2.next(); if (!bi.oW(dVar.field_appId)) { linkedList.add(dVar.field_appId); } } } it = c.aVi().iterator(); while (it.hasNext()) { f fVar = (f) it.next(); if (!linkedList.contains(fVar.field_appId)) { a.bmf().b(fVar, new String[0]); x.i("MicroMsg.GameDataSearchGameList", "delete appid : " + fVar.field_appId); } } } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.devtools_bridge; import org.chromium.base.CalledByNative; import org.chromium.base.JNINamespace; import java.nio.ByteBuffer; /** * Native implementation of session dependency factory on top of C++ * libjingle API. */ @JNINamespace("devtools_bridge::android") public class SessionDependencyFactoryNative extends SessionDependencyFactory { private final long mFactoryPtr; public SessionDependencyFactoryNative() { mFactoryPtr = nativeCreateFactory(); assert mFactoryPtr != 0; } @Override public AbstractPeerConnection createPeerConnection( RTCConfiguration config, AbstractPeerConnection.Observer observer) { assert config != null; assert observer != null; long configPtr = nativeCreateConfig(); for (RTCConfiguration.IceServer server : config.iceServers) { nativeAddIceServer(configPtr, server.uri, server.username, server.credential); } return new PeerConnectionImpl(mFactoryPtr, configPtr, observer); } @Override public SocketTunnel newSocketTunnelServer(String socketBase) { return new SocketTunnelServerImpl(mFactoryPtr, socketBase); } @Override public void dispose() { nativeDestroyFactory(mFactoryPtr); } private static final class PeerConnectionImpl extends AbstractPeerConnection { private final long mConnectionPtr; // Takes ownership on |configPtr|. public PeerConnectionImpl( long factoryPtr, long configPtr, AbstractPeerConnection.Observer observer) { mConnectionPtr = nativeCreatePeerConnection(factoryPtr, configPtr, observer); assert mConnectionPtr != 0; } @Override public void createAndSetLocalDescription(SessionDescriptionType type) { switch (type) { case OFFER: nativeCreateAndSetLocalOffer(mConnectionPtr); break; case ANSWER: nativeCreateAndSetLocalAnswer(mConnectionPtr); break; } } @Override public void setRemoteDescription(SessionDescriptionType type, String description) { switch (type) { case OFFER: nativeSetRemoteOffer(mConnectionPtr, description); break; case ANSWER: nativeSetRemoteAnswer(mConnectionPtr, description); break; } } @Override public void addIceCandidate(String candidate) { // TODO(serya): Handle IllegalArgumentException exception. IceCandidate parsed = IceCandidate.fromString(candidate); nativeAddIceCandidate(mConnectionPtr, parsed.sdpMid, parsed.sdpMLineIndex, parsed.sdp); } @Override public void dispose() { nativeDestroyPeerConnection(mConnectionPtr); } @Override public AbstractDataChannel createDataChannel(int channelId) { return new DataChannelImpl(nativeCreateDataChannel(mConnectionPtr, channelId)); } } private static final class DataChannelImpl extends AbstractDataChannel { private final long mChannelPtr; public DataChannelImpl(long ptr) { assert ptr != 0; mChannelPtr = ptr; } long nativePtr() { return mChannelPtr; } @Override public void registerObserver(Observer observer) { nativeRegisterDataChannelObserver(mChannelPtr, observer); } @Override public void unregisterObserver() { nativeUnregisterDataChannelObserver(mChannelPtr); } @Override public void send(ByteBuffer message, MessageType type) { assert message.position() == 0; int length = message.limit(); assert length > 0; switch (type) { case BINARY: nativeSendBinaryMessage(mChannelPtr, message, length); break; case TEXT: nativeSendTextMessage(mChannelPtr, message, length); break; } } @Override public void close() { nativeCloseDataChannel(mChannelPtr); } @Override public void dispose() { nativeDestroyDataChannel(mChannelPtr); } } private static class SocketTunnelServerImpl implements SocketTunnel { private final String mSocketName; private final long mFactoryPtr; private DataChannelImpl mDataChannel; private long mTunnelPtr; public SocketTunnelServerImpl(long factoryPtr, String socketName) { mFactoryPtr = factoryPtr; mSocketName = socketName; } @Override public void bind(AbstractDataChannel dataChannel) { mDataChannel = (DataChannelImpl) dataChannel; mTunnelPtr = nativeCreateSocketTunnelServer( mFactoryPtr, mDataChannel.nativePtr(), mSocketName); } @Override public AbstractDataChannel unbind() { AbstractDataChannel result = mDataChannel; nativeDestroySocketTunnelServer(mTunnelPtr); mTunnelPtr = 0; mDataChannel = null; return result; } @Override public boolean isBound() { return mDataChannel != null; } @Override public void dispose() { assert !isBound(); } } // Peer connection callbacks. @CalledByNative private static void notifyLocalOfferCreatedAndSetSet(Object observer, String description) { ((AbstractPeerConnection.Observer) observer).onLocalDescriptionCreatedAndSet( AbstractPeerConnection.SessionDescriptionType.OFFER, description); } @CalledByNative private static void notifyLocalAnswerCreatedAndSetSet(Object observer, String description) { ((AbstractPeerConnection.Observer) observer).onLocalDescriptionCreatedAndSet( AbstractPeerConnection.SessionDescriptionType.ANSWER, description); } @CalledByNative private static void notifyRemoteDescriptionSet(Object observer) { ((AbstractPeerConnection.Observer) observer).onRemoteDescriptionSet(); } @CalledByNative private static void notifyConnectionFailure(Object observer, String description) { ((AbstractPeerConnection.Observer) observer).onFailure(description); } @CalledByNative private static void notifyIceCandidate( Object observer, String sdpMid, int sdpMLineIndex, String sdp) { ((AbstractPeerConnection.Observer) observer) .onIceCandidate(new AbstractPeerConnection.IceCandidate( sdpMid, sdpMLineIndex, sdp).toString()); } @CalledByNative private static void notifyIceConnectionChange(Object observer, boolean connected) { ((AbstractPeerConnection.Observer) observer) .onIceConnectionChange(connected); } // Data channel callbacks. @CalledByNative private static void notifyChannelOpen(Object observer) { ((AbstractDataChannel.Observer) observer) .onStateChange(AbstractDataChannel.State.OPEN); } @CalledByNative private static void notifyChannelClose(Object observer) { ((AbstractDataChannel.Observer) observer) .onStateChange(AbstractDataChannel.State.CLOSED); } @CalledByNative private static void notifyMessage(Object observer, ByteBuffer message) { ((AbstractDataChannel.Observer) observer) .onMessage(message); } private static native long nativeCreateFactory(); private static native void nativeDestroyFactory(long factoryPtr); private static native long nativeCreateConfig(); private static native void nativeAddIceServer( long configPtr, String uri, String username, String credential); // Takes ownership on |configPtr|. private static native long nativeCreatePeerConnection( long factoryPtr, long configPtr, Object observer); private static native void nativeDestroyPeerConnection(long connectionPtr); private static native void nativeCreateAndSetLocalOffer(long connectionPtr); private static native void nativeCreateAndSetLocalAnswer(long connectionPtr); private static native void nativeSetRemoteOffer(long connectionPtr, String description); private static native void nativeSetRemoteAnswer(long connectionPtr, String description); private static native void nativeAddIceCandidate( long peerConnectionPtr, String sdpMid, int sdpMLineIndex, String sdp); private static native long nativeCreateDataChannel(long connectionPtr, int channelId); private static native void nativeDestroyDataChannel(long channelPtr); private static native void nativeRegisterDataChannelObserver( long channelPtr, Object observer); private static native void nativeUnregisterDataChannelObserver(long channelPtr); private static native void nativeSendBinaryMessage( long channelPtr, ByteBuffer message, int size); private static native void nativeSendTextMessage(long channelPtr, ByteBuffer message, int size); private static native void nativeCloseDataChannel(long channelPtr); private static native long nativeCreateSocketTunnelServer( long factoryPtr, long channelPtr, String socketName); private static native void nativeDestroySocketTunnelServer(long tunnelPtr); }
package com.ray.gg; import android.app.Application; import android.content.Context; import com.facebook.drawee.backends.pipeline.Fresco; import com.ray.gg.init.FrescoConfig; import log.Log; public class App extends Application { private static Application sApp; public App() { super(); } public static Application get() { return sApp; } @Override public void onCreate() { super.onCreate(); Log.setIsDebug(BuildConfig.DEBUG); Fresco.initialize(this, FrescoConfig.getImagePipelineConfig(getApplicationContext())); } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); sApp = this; } }
package com.tencent.mm.plugin.appbrand.jsapi.audio; import android.text.TextUtils; import com.tencent.mm.g.a.lk; import com.tencent.mm.plugin.appbrand.appstorage.AppBrandLocalMediaObject; import com.tencent.mm.plugin.appbrand.appstorage.AppBrandLocalMediaObjectManager; import com.tencent.mm.plugin.appbrand.e$b; import com.tencent.mm.plugin.appbrand.jsapi.audio.i.a; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.plugin.appbrand.media.record.b; import com.tencent.mm.plugin.appbrand.media.record.e; import com.tencent.mm.plugin.appbrand.media.record.e.6; import com.tencent.mm.plugin.appbrand.media.record.e.8; import com.tencent.mm.plugin.appbrand.media.record.f; import com.tencent.mm.plugin.appbrand.media.record.h; import com.tencent.mm.plugin.appbrand.media.record.record_imp.RecordParam; import com.tencent.mm.plugin.appbrand.r.m; import com.tencent.mm.plugin.mmsight.segment.FFmpegMetadataRetriever; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; class i$b extends a { public int action; public String appId; private byte[] bVL; private boolean bVM; private int duration = 0; public l fFa; public int fFd; public String fHW = ""; public boolean fHX = false; private i fIH; public String fII; private String fIJ = ""; private String fIK; private int fIL; private final c<lk> fIM = new 1(this); e$b fIs; public String fIt; private String filePath = ""; private int fileSize = 0; public String processName = ""; private String state = ""; public i$b(i iVar, l lVar, int i) { this.fIH = iVar; this.fFa = lVar; this.fFd = i; this.fIK = AppBrandLocalMediaObjectManager.genMediaFilePath(lVar.mAppId, "frameBuffer"); } public final void ahW() { boolean z = false; try { JSONObject jSONObject = new JSONObject(this.fII); String optString = jSONObject.optString("operationType"); if (TextUtils.isEmpty(optString)) { x.e("MicroMsg.Record.JsApiOperateRecorder", "operationType is null"); this.fHX = true; this.action = -1; this.fHW = "operationType is null"; En(); return; } x.i("MicroMsg.Record.JsApiOperateRecorder", "operationType;%s", new Object[]{optString}); this.fHX = false; this.action = -1; boolean z2; e ale; if (optString.equals("start")) { int optInt = jSONObject.optInt(FFmpegMetadataRetriever.METADATA_KEY_DURATION, 60000); int optInt2 = jSONObject.optInt("sampleRate", 44100); int optInt3 = jSONObject.optInt("numberOfChannels", 2); int optInt4 = jSONObject.optInt("encodeBitRate", 128000); String optString2 = jSONObject.optString("format"); int optInt5 = jSONObject.optInt("frameSize", 0); b a = b.a(jSONObject.optString("audioSource").toUpperCase(), b.MIC); com.tencent.mm.plugin.appbrand.media.record.c.b(this.appId, this.fIM); RecordParam recordParam = new RecordParam(); recordParam.duration = optInt; recordParam.sampleRate = optInt2; recordParam.gji = optInt3; recordParam.gjj = optInt4; recordParam.fIJ = optString2; recordParam.scene = 8; recordParam.aft = optInt5; recordParam.dfX = System.currentTimeMillis(); recordParam.processName = this.processName; recordParam.appId = this.appId; recordParam.gjk = a; this.fIJ = optString2; com.tencent.mm.plugin.appbrand.media.record.c.alb(); e ale2 = e.ale(); x.i("MicroMsg.Record.AudioRecordMgr", JsApiStartRecordVoice.NAME); if (ale2.giw == null || recordParam.appId == null || recordParam.appId.equalsIgnoreCase(ale2.giw.appId)) { if (ale2.mIsRecording) { x.e("MicroMsg.Record.AudioRecordMgr", "startRecord fail, is recording"); } else if (ale2.wc()) { x.e("MicroMsg.Record.AudioRecordMgr", "startRecord fail, is pause"); } if (z) { x.i("MicroMsg.Record.JsApiOperateRecorder", "star record ok"); this.action = -1; } else if (e.ale().mIsRecording) { this.fHX = true; this.fHW = "audio is recording, don't start record again"; } else { this.fHX = true; this.fHW = "start record fail"; } } else { x.e("MicroMsg.Record.AudioRecordMgr", "appId is diff, must stop record first"); ale2.we(); } z2 = !TextUtils.isEmpty(recordParam.fIJ) && recordParam.duration >= 0 && recordParam.gjj > 0 && recordParam.sampleRate > 0 && recordParam.gji > 0; if (!z2) { x.e("MicroMsg.Record.AudioRecordMgr", "startRecord fail, param is invalid"); h.li(15); } else if (f.uy(recordParam.fIJ)) { if (TextUtils.isEmpty(recordParam.dfX)) { recordParam.dfX = System.currentTimeMillis(); } h.all(); x.i("MicroMsg.Record.RecordParamCompatibility", "recordParam duration:%d, numberOfChannels:%d, sampleRate:%d, encodeBitRate:%d", new Object[]{Integer.valueOf(recordParam.duration), Integer.valueOf(recordParam.gji), Integer.valueOf(recordParam.sampleRate), Integer.valueOf(recordParam.gjj)}); if (recordParam.duration <= 0) { recordParam.duration = 60000; } else if (recordParam.duration >= 600000) { recordParam.duration = 600000; } if (recordParam.gji <= 0 && recordParam.gji > 2) { recordParam.gji = 2; } if (recordParam.sampleRate > 48000) { recordParam.sampleRate = 48000; } else if (recordParam.sampleRate < 8000) { recordParam.sampleRate = 8000; } if (recordParam.gjj > 320000) { recordParam.gjj = 320000; } else if (recordParam.gjj < 16000) { recordParam.gjj = 16000; } com.tencent.mm.sdk.f.e.post(new 6(ale2, recordParam), "app_brand_start_record"); z = true; } else { x.e("MicroMsg.Record.AudioRecordMgr", "startRecord fail, encode format %s is not support!", new Object[]{recordParam.fIJ}); h.li(16); } if (z) { x.i("MicroMsg.Record.JsApiOperateRecorder", "star record ok"); this.action = -1; } else if (e.ale().mIsRecording) { this.fHX = true; this.fHW = "audio is recording, don't start record again"; } else { this.fHX = true; this.fHW = "start record fail"; } } else if (optString.equals("resume")) { ale = e.ale(); if (ale.mIsRecording) { x.e("MicroMsg.Record.AudioRecordMgr", "resumeRecord fail, is recording"); } else if (ale.giw == null) { x.e("MicroMsg.Record.AudioRecordMgr", "resumeRecord fail, mRecordParam is null"); } else { h.all(); com.tencent.mm.sdk.f.e.post(new Runnable() { public final void run() { synchronized (e.this.giv) { e.h(e.this); } } }, "app_brand_resume_record"); z = true; } if (z) { this.action = -1; x.i("MicroMsg.Record.JsApiOperateRecorder", "resume record ok"); } else if (e.ale().mIsRecording) { this.fHX = true; this.fHW = "audio is recording, don't resume record again"; } else { this.fHX = true; this.fHW = "resume record fail"; } } else if (optString.equals("pause")) { ale = e.ale(); x.i("MicroMsg.Record.AudioRecordMgr", "pauseRecord"); if (ale.giu == null) { x.e("MicroMsg.Record.AudioRecordMgr", "mRecord is null"); z2 = false; } else if (ale.wc()) { x.e("MicroMsg.Record.AudioRecordMgr", "is paused, don't pause again"); z2 = true; } else { com.tencent.mm.sdk.f.e.post(new 8(ale), "app_brand_pause_record"); z2 = true; } if (z2) { this.action = -1; x.i("MicroMsg.Record.JsApiOperateRecorder", "pause record ok"); } else if (e.ale().wc()) { this.fHX = true; this.fHW = "audio is pause, don't pause record again"; } else { this.fHX = true; this.fHW = "pause record fail"; } } else if (!optString.equals("stop")) { x.e("MicroMsg.Record.JsApiOperateRecorder", "operationType is invalid"); this.fHX = true; this.fHW = "operationType is invalid"; } else if (e.ale().we()) { this.action = -1; x.i("MicroMsg.Record.JsApiOperateRecorder", "stop record ok"); } else if (e.ale().alf()) { this.fHX = true; this.fHW = "audio is stop, don't stop record again"; } else { this.fHX = true; this.fHW = "stop record fail"; } if (this.fHX) { x.e("MicroMsg.Record.JsApiOperateRecorder", this.fHW); } En(); } catch (JSONException e) { x.e("MicroMsg.Record.JsApiOperateRecorder", "new json exists exception, data is invalid, dataStr:%s", new Object[]{this.fII}); this.fHX = true; this.action = -1; this.fHW = "parser data fail, data is invalid"; x.e("MicroMsg.Record.JsApiOperateRecorder", "exception:%s" + e.getMessage()); En(); } } public final void En() { Throwable e; com.tencent.mm.plugin.appbrand.jsapi.h a; super.En(); if (this.fFa == null) { x.e("MicroMsg.Record.JsApiOperateRecorder", "service is null, don't callback"); } else if (this.action != -1) { a aVar = new a(); switch (this.action) { case 0: case 1: i.a(this.fIH, true); if (!i.ahY().contains(this.appId)) { com.tencent.mm.plugin.appbrand.e.a(this.appId, this.fIs); i.ahY().add(this.appId); break; } break; case 2: case 3: case 4: i.a(this.fIH, false); if (this.action == 2 || this.action == 4) { com.tencent.mm.plugin.appbrand.e.b(this.appId, this.fIs); i.ahY().remove(this.appId); break; } } if (this.action == 2) { Map hashMap = new HashMap(); hashMap.put("state", this.state); x.i("MicroMsg.Record.JsApiOperateRecorder", "filePath:%s, encodeFormat:%s", new Object[]{this.filePath, this.fIJ}); AppBrandLocalMediaObject attach = AppBrandLocalMediaObjectManager.attach(this.fFa.mAppId, this.filePath, f.ux(this.fIJ), false); if (attach != null) { hashMap.put("tempFilePath", attach.bNH); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "AppBrandLocalMediaObject obj is null"); hashMap.put("tempFilePath", ""); } hashMap.put(FFmpegMetadataRetriever.METADATA_KEY_DURATION, Integer.valueOf(this.duration)); hashMap.put("fileSize", Integer.valueOf(this.fileSize)); this.fIt = new JSONObject(hashMap).toString(); } if (this.action == 5) { Map hashMap2 = new HashMap(); hashMap2.put("state", this.state); hashMap2.put("isLastFrame", Boolean.valueOf(this.bVM)); if (this.fIL > 819200) { long nanoTime = System.nanoTime(); File file; FileInputStream fileInputStream; try { file = new File(this.fIK); try { if (file.exists()) { fileInputStream = new FileInputStream(file); try { this.bVL = new byte[this.fIL]; fileInputStream.read(this.bVL); fileInputStream.close(); try { fileInputStream.close(); } catch (Throwable e2) { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e2, "", new Object[0]); } if (file.exists()) { file.delete(); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); } } catch (FileNotFoundException e3) { e2 = e3; try { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e2, "", new Object[0]); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e22) { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e22, "", new Object[0]); } } if (file == null) { } x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); x.d("MicroMsg.Record.JsApiOperateRecorder", "time:%d", new Object[]{Long.valueOf(System.nanoTime() - nanoTime)}); if (this.bVL != null) { x.e("MicroMsg.Record.JsApiOperateRecorder", "framBuffer is null, error"); } else { hashMap2.put("frameBuffer", ByteBuffer.wrap(this.bVL)); } if (m.a(this.fFa, hashMap2, aVar)) { this.fIt = new JSONObject(hashMap2).toString(); } x.i("MicroMsg.Record.JsApiOperateRecorder", "operateRecorder onRecorderStateChange callback action:%d, jsonResult:%s", new Object[]{Integer.valueOf(this.action), this.fIt}); a = aVar.a(this.fFa); a.mData = this.fIt; a.ahM(); } catch (Throwable th) { e22 = th; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e4) { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e4, "", new Object[0]); } } if (file == null) { } x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); throw e22; } } catch (IOException e5) { e22 = e5; x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e22, "", new Object[0]); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e222) { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e222, "", new Object[0]); } } if (file == null) { } x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); x.d("MicroMsg.Record.JsApiOperateRecorder", "time:%d", new Object[]{Long.valueOf(System.nanoTime() - nanoTime)}); if (this.bVL != null) { hashMap2.put("frameBuffer", ByteBuffer.wrap(this.bVL)); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "framBuffer is null, error"); } if (m.a(this.fFa, hashMap2, aVar)) { this.fIt = new JSONObject(hashMap2).toString(); } x.i("MicroMsg.Record.JsApiOperateRecorder", "operateRecorder onRecorderStateChange callback action:%d, jsonResult:%s", new Object[]{Integer.valueOf(this.action), this.fIt}); a = aVar.a(this.fFa); a.mData = this.fIt; a.ahM(); } x.d("MicroMsg.Record.JsApiOperateRecorder", "time:%d", new Object[]{Long.valueOf(System.nanoTime() - nanoTime)}); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, return"); if (file.exists()) { file.delete(); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); } } } catch (FileNotFoundException e6) { e222 = e6; fileInputStream = null; x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e222, "", new Object[0]); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e2222) { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e2222, "", new Object[0]); } } if (file == null && file.exists()) { file.delete(); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); } x.d("MicroMsg.Record.JsApiOperateRecorder", "time:%d", new Object[]{Long.valueOf(System.nanoTime() - nanoTime)}); if (this.bVL != null) { x.e("MicroMsg.Record.JsApiOperateRecorder", "framBuffer is null, error"); } else { hashMap2.put("frameBuffer", ByteBuffer.wrap(this.bVL)); } if (m.a(this.fFa, hashMap2, aVar)) { this.fIt = new JSONObject(hashMap2).toString(); } x.i("MicroMsg.Record.JsApiOperateRecorder", "operateRecorder onRecorderStateChange callback action:%d, jsonResult:%s", new Object[]{Integer.valueOf(this.action), this.fIt}); a = aVar.a(this.fFa); a.mData = this.fIt; a.ahM(); } catch (IOException e7) { e2222 = e7; fileInputStream = null; x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e2222, "", new Object[0]); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e22222) { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e22222, "", new Object[0]); } } if (file == null && file.exists()) { file.delete(); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); } x.d("MicroMsg.Record.JsApiOperateRecorder", "time:%d", new Object[]{Long.valueOf(System.nanoTime() - nanoTime)}); if (this.bVL != null) { hashMap2.put("frameBuffer", ByteBuffer.wrap(this.bVL)); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "framBuffer is null, error"); } if (m.a(this.fFa, hashMap2, aVar)) { this.fIt = new JSONObject(hashMap2).toString(); } x.i("MicroMsg.Record.JsApiOperateRecorder", "operateRecorder onRecorderStateChange callback action:%d, jsonResult:%s", new Object[]{Integer.valueOf(this.action), this.fIt}); a = aVar.a(this.fFa); a.mData = this.fIt; a.ahM(); } catch (Throwable th2) { e22222 = th2; fileInputStream = null; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e42) { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e42, "", new Object[0]); } } if (file == null && file.exists()) { file.delete(); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); } throw e22222; } } catch (FileNotFoundException e8) { e22222 = e8; fileInputStream = null; file = null; x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e22222, "", new Object[0]); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e222222) { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e222222, "", new Object[0]); } } if (file == null) { } x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); x.d("MicroMsg.Record.JsApiOperateRecorder", "time:%d", new Object[]{Long.valueOf(System.nanoTime() - nanoTime)}); if (this.bVL != null) { x.e("MicroMsg.Record.JsApiOperateRecorder", "framBuffer is null, error"); } else { hashMap2.put("frameBuffer", ByteBuffer.wrap(this.bVL)); } if (m.a(this.fFa, hashMap2, aVar)) { this.fIt = new JSONObject(hashMap2).toString(); } x.i("MicroMsg.Record.JsApiOperateRecorder", "operateRecorder onRecorderStateChange callback action:%d, jsonResult:%s", new Object[]{Integer.valueOf(this.action), this.fIt}); a = aVar.a(this.fFa); a.mData = this.fIt; a.ahM(); } catch (IOException e9) { e222222 = e9; fileInputStream = null; file = null; x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e222222, "", new Object[0]); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e2222222) { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e2222222, "", new Object[0]); } } if (file == null) { } x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); x.d("MicroMsg.Record.JsApiOperateRecorder", "time:%d", new Object[]{Long.valueOf(System.nanoTime() - nanoTime)}); if (this.bVL != null) { hashMap2.put("frameBuffer", ByteBuffer.wrap(this.bVL)); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "framBuffer is null, error"); } if (m.a(this.fFa, hashMap2, aVar)) { this.fIt = new JSONObject(hashMap2).toString(); } x.i("MicroMsg.Record.JsApiOperateRecorder", "operateRecorder onRecorderStateChange callback action:%d, jsonResult:%s", new Object[]{Integer.valueOf(this.action), this.fIt}); a = aVar.a(this.fFa); a.mData = this.fIt; a.ahM(); } catch (Throwable th3) { e2222222 = th3; fileInputStream = null; file = null; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e422) { x.printErrStackTrace("MicroMsg.Record.JsApiOperateRecorder", e422, "", new Object[0]); } } if (file == null) { } x.e("MicroMsg.Record.JsApiOperateRecorder", "frameBufferFile is not exist, delete error"); throw e2222222; } } if (this.bVL != null) { hashMap2.put("frameBuffer", ByteBuffer.wrap(this.bVL)); } else { x.e("MicroMsg.Record.JsApiOperateRecorder", "framBuffer is null, error"); } if (m.a(this.fFa, hashMap2, aVar)) { this.fIt = new JSONObject(hashMap2).toString(); } } x.i("MicroMsg.Record.JsApiOperateRecorder", "operateRecorder onRecorderStateChange callback action:%d, jsonResult:%s", new Object[]{Integer.valueOf(this.action), this.fIt}); a = aVar.a(this.fFa); a.mData = this.fIt; a.ahM(); } else if (this.fHX) { x.e("MicroMsg.Record.JsApiOperateRecorder", "operateRecorder fail:%s", new Object[]{this.fHW}); this.fFa.E(this.fFd, this.fIH.f("fail:" + this.fHW, null)); } else { x.i("MicroMsg.Record.JsApiOperateRecorder", "operateRecorder ok"); this.fFa.E(this.fFd, this.fIH.f("ok", null)); } } }
/* */ package datechooser.beans.editor.utils; /* */ /* */ import java.awt.Font; /* */ import java.awt.Graphics; /* */ import java.awt.Graphics2D; /* */ import java.awt.Rectangle; /* */ import java.awt.geom.Rectangle2D; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class TextOutput /* */ { /* 22 */ private static Font defaultFont = new Font("Dialog", 0, 14); /* */ /* */ public TextOutput() {} /* */ /* 26 */ public static void paintBoxed(Graphics g, Rectangle bounds, String text, Font font) { Graphics2D g2d = (Graphics2D)g; /* 27 */ Rectangle2D rec = font.getStringBounds(text, g2d.getFontRenderContext()); /* 28 */ double x = (bounds.width - rec.getWidth()) / 2.0D; /* 29 */ if (x < 0.0D) x = 0.0D; /* 30 */ g2d.drawString(text, (float)x, (float)((bounds.height - rec.getHeight()) / 2.0D - rec.getY())); /* */ } /* */ /* */ /* */ public static void paintBoxed(Graphics g, Rectangle bounds, String text) /* */ { /* 36 */ paintBoxed(g, bounds, text, defaultFont); /* */ } /* */ } /* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/beans/editor/utils/TextOutput.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UI.LopHoc.ChiTietLopHoc; import DTO.dto_ChuongTrinh; import UI.LopHoc.ChiTietLopHoc.FormThemVaoLop; import UI.LopHoc.FormCapNhatLH; import java.awt.Color; import java.awt.Font; import java.util.ArrayList; import javax.swing.table.DefaultTableModel; /** * * @author ThinkPro */ public class UI_ChiTietLop extends javax.swing.JFrame { /** * Creates new form FormLichSuLH */ public UI_ChiTietLop() { initComponents(); tbLopHoc.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); tbLopHoc.getTableHeader().setOpaque(false); tbLopHoc.getTableHeader().setForeground(new Color(22, 105, 158)); tbLopHoc.setSelectionBackground(new Color(204,204,204)); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pnLop = new javax.swing.JPanel(); btnThemLop = new javax.swing.JButton(); jspLH = new javax.swing.JScrollPane(); tbLopHoc = new javax.swing.JTable(); btnChiTietLop = new javax.swing.JButton(); btnXoaLop = new javax.swing.JButton(); btnUpdateLop = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jTextArea1 = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("CHI TIẾT LỚP HỌC"); setResizable(false); pnLop.setBackground(new java.awt.Color(230, 245, 255)); btnThemLop.setBackground(new java.awt.Color(230, 245, 255)); btnThemLop.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnThemLop.setForeground(new java.awt.Color(255, 255, 255)); btnThemLop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/taomoi.png"))); // NOI18N btnThemLop.setContentAreaFilled(false); btnThemLop.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnThemLop.setFocusable(false); btnThemLop.setOpaque(true); btnThemLop.setPreferredSize(new java.awt.Dimension(183, 40)); btnThemLop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnThemLopActionPerformed(evt); } }); jspLH.setBackground(new java.awt.Color(255, 255, 255)); jspLH.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jspLH.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jspLH.setPreferredSize(new java.awt.Dimension(450, 400)); tbLopHoc.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N tbLopHoc.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {"1", "a", null, null, null, null, null, null, null, null}, {"2", "a", null, null, null, null, null, null, null, null}, {"3", "a", null, null, null, null, null, null, null, null}, {"4", "a", null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null} }, new String [] { "STT", "Mã KH", "Tên Khách Hàng", "Giới Tính", "Số Điện Thoại", "Nghe", "Nói", "Đọc", "Viết", "TB" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false, false, false, true, true, true, true, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tbLopHoc.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); tbLopHoc.setDoubleBuffered(true); tbLopHoc.setFocusable(false); tbLopHoc.setPreferredSize(new java.awt.Dimension(600, 450)); tbLopHoc.setRowHeight(30); tbLopHoc.setSelectionBackground(new java.awt.Color(232, 57, 95)); tbLopHoc.getTableHeader().setReorderingAllowed(false); jspLH.setViewportView(tbLopHoc); if (tbLopHoc.getColumnModel().getColumnCount() > 0) { tbLopHoc.getColumnModel().getColumn(0).setMaxWidth(50); tbLopHoc.getColumnModel().getColumn(1).setMaxWidth(100); tbLopHoc.getColumnModel().getColumn(2).setMinWidth(150); tbLopHoc.getColumnModel().getColumn(3).setMaxWidth(100); } btnChiTietLop.setBackground(new java.awt.Color(230, 245, 255)); btnChiTietLop.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnChiTietLop.setForeground(new java.awt.Color(255, 255, 255)); btnChiTietLop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/chuyenlop.png"))); // NOI18N btnChiTietLop.setText("CHUYỂN LỚP"); btnChiTietLop.setActionCommand(""); btnChiTietLop.setContentAreaFilled(false); btnChiTietLop.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnChiTietLop.setFocusable(false); btnChiTietLop.setOpaque(true); btnChiTietLop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnChiTietLopActionPerformed(evt); } }); btnXoaLop.setBackground(new java.awt.Color(230, 245, 255)); btnXoaLop.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnXoaLop.setForeground(new java.awt.Color(255, 255, 255)); btnXoaLop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xoa.png"))); // NOI18N btnXoaLop.setContentAreaFilled(false); btnXoaLop.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnXoaLop.setFocusable(false); btnXoaLop.setMaximumSize(new java.awt.Dimension(129, 49)); btnXoaLop.setMinimumSize(new java.awt.Dimension(129, 49)); btnXoaLop.setOpaque(true); btnXoaLop.setPreferredSize(new java.awt.Dimension(129, 49)); btnXoaLop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnXoaLopActionPerformed(evt); } }); btnUpdateLop.setBackground(new java.awt.Color(230, 245, 255)); btnUpdateLop.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnUpdateLop.setForeground(new java.awt.Color(255, 255, 255)); btnUpdateLop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/capnhatbangdiem.png"))); // NOI18N btnUpdateLop.setContentAreaFilled(false); btnUpdateLop.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnUpdateLop.setFocusable(false); btnUpdateLop.setMaximumSize(new java.awt.Dimension(129, 49)); btnUpdateLop.setMinimumSize(new java.awt.Dimension(129, 49)); btnUpdateLop.setOpaque(true); btnUpdateLop.setPreferredSize(new java.awt.Dimension(129, 49)); btnUpdateLop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnUpdateLopActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setText("LỚP AV1 - 12343432"); jTextArea1.setBackground(new java.awt.Color(230, 245, 255)); jTextArea1.setColumns(20); jTextArea1.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N jTextArea1.setRows(5); jTextArea1.setText("<KHU VỰC THÔNG TIN LỚP HỌC>"); javax.swing.GroupLayout pnLopLayout = new javax.swing.GroupLayout(pnLop); pnLop.setLayout(pnLopLayout); pnLopLayout.setHorizontalGroup( pnLopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnLopLayout.createSequentialGroup() .addGap(527, 527, 527) .addComponent(jLabel1) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(pnLopLayout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(pnLopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnLopLayout.createSequentialGroup() .addComponent(jTextArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 571, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 275, Short.MAX_VALUE) .addComponent(btnUpdateLop, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnChiTietLop, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnThemLop, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnXoaLop, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jspLH, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(30, 30, 30)) ); pnLopLayout.setVerticalGroup( pnLopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnLopLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(pnLopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextArea1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnLopLayout.createSequentialGroup() .addGroup(pnLopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnChiTietLop, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnThemLop, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnUpdateLop, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnXoaLop, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(11, 11, 11))) .addGap(7, 7, 7) .addComponent(jspLH, javax.swing.GroupLayout.PREFERRED_SIZE, 540, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnLop, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnLop, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btnThemLopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemLopActionPerformed new FormThemVaoLop().show(); }//GEN-LAST:event_btnThemLopActionPerformed private void btnChiTietLopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChiTietLopActionPerformed new FormChuyenLop().show(); }//GEN-LAST:event_btnChiTietLopActionPerformed private void btnXoaLopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaLopActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btnXoaLopActionPerformed private void btnUpdateLopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateLopActionPerformed new FormCapNhatBangDiem().show(); }//GEN-LAST:event_btnUpdateLopActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(UI_ChiTietLop.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(UI_ChiTietLop.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(UI_ChiTietLop.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(UI_ChiTietLop.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new UI_ChiTietLop().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnChiTietLop; private javax.swing.JButton btnThemLop; private javax.swing.JButton btnUpdateLop; private javax.swing.JButton btnXoaLop; private javax.swing.JLabel jLabel1; private javax.swing.JTextArea jTextArea1; private javax.swing.JScrollPane jspLH; private javax.swing.JPanel pnLop; private javax.swing.JTable tbLopHoc; // End of variables declaration//GEN-END:variables }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package co.th.aten.football.dao; import co.th.aten.football.model.VideoModel; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import java.util.List; import java.util.Locale; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; /** * * @author Atenpunk */ public class JdbcVideoPlayersDao implements VideoPlayersDao { private final Log logger = LogFactory.getLog(getClass()); private SimpleJdbcTemplate simpleJdbcTemplate; private DataSource dataSource; private SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); } public int getMaxVideoId() { String sql = "select max(VIDEO_ID) from VIDEO_PLAYERS "; return this.simpleJdbcTemplate.queryForInt(sql); } public boolean deleteVideoByPlayerId(int playerId) { logger.debug("delete Video by PLAYER_ID = " + playerId); try { String sql = " DELETE FROM VIDEO_PLAYERS WHERE PLAYER_ID = ? "; return (this.simpleJdbcTemplate.update(sql, playerId) > 0) ? true : false; } catch (Exception e) { e.printStackTrace(); } return false; } public boolean deleteVideoByVideoId(int videoId) { logger.debug("delete Video by VIDEO_ID = " + videoId); try { String sql = " DELETE FROM VIDEO_PLAYERS WHERE VIDEO_ID = ? "; return (this.simpleJdbcTemplate.update(sql, videoId) > 0) ? true : false; } catch (Exception e) { e.printStackTrace(); } return false; } public boolean insertVideoPlayer(VideoModel videoModel) { logger.info("Insert Video_ID = " + videoModel.getVideoId()); logger.info(" Player_ID = " + videoModel.getPlayerId()); try { String sql = " INSERT INTO VIDEO_PLAYERS (VIDEO_ID, PLAYER_ID, VIDEO_NAME " + " , CREATE_BY, CREATE_DATE, UPDATE_BY, UPDATE_DATE ) " + " VALUES (?, ?, ?, ?, ?, ?, ?) "; boolean insert = (this.simpleJdbcTemplate.update(sql, videoModel.getVideoId(), videoModel.getPlayerId(), videoModel.getVideoName(), videoModel.getCreateBy(), sdfDate.parse(sdfDate.format(videoModel.getCreateDate())), videoModel.getUpdateBy(), sdfDate.parse(sdfDate.format(videoModel.getUpdateDate()))) > 0) ? true : false; return insert; } catch (Exception e) { e.printStackTrace(); } return false; } public List<VideoModel> searchByKeyWord(int playerId) { try { String sql = " select vd.VIDEO_ID, vd.PLAYER_ID, vd.VIDEO_NAME, vd.CREATE_BY , vd.CREATE_DATE , vd.UPDATE_BY , vd.UPDATE_DATE " + " from VIDEO_PLAYERS vd " + " where vd.PLAYER_ID = " + playerId + " " + " order by vd.CREATE_BY desc "; ParameterizedRowMapper<VideoModel> mapper = new ParameterizedRowMapper<VideoModel>() { @Override public VideoModel mapRow(ResultSet rs, int arg1) throws SQLException { VideoModel model = new VideoModel(); model.setVideoId(rs.getInt("VIDEO_ID")); model.setPlayerId(rs.getInt("PLAYER_ID")); model.setVideoName(rs.getString("VIDEO_NAME")); model.setCreateBy(rs.getInt("CREATE_BY")); model.setCreateDate(rs.getDate("CREATE_DATE")); model.setUpdateBy(rs.getInt("UPDATE_BY")); model.setUpdateDate(rs.getDate("UPDATE_DATE")); return model; } }; return this.simpleJdbcTemplate.query(sql, mapper); } catch (Exception e) { logger.info("" + e); e.printStackTrace(); } return null; } }
package com.rajitha; public class NestedIfCondition { public static void main(String args[]){ int i=80; int j=80; if(i>j){ System.out.println("It is false"); }if(i<j) { System.out.println("It is true"); }if(i==j){ System.out.println("Both are equal"); } } //else { // System.out.println("None of the above statements are correct"); //} }
package com.cristovantamayo.ubsvoce.services; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.Test; import com.cristovantamayo.ubsvoce.services.util.Paginador; public class PaginadorTest { @Test public void deveCorresponderAListaParginada() { List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ,15, 16, 17, 18); assertThat( Paginador.ofSize(lista, 6), is( Arrays.asList( Arrays.asList(1, 2, 3, 4, 5, 6), Arrays.asList(7, 8, 9, 10, 11, 12), Arrays.asList(13, 14, 15, 16, 17, 18) ) ) ); } @Test public void deveCorresponderASubListaParginada() { List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ,15, 16, 17, 18); Paginador listas = Paginador.ofSize(lista, 6); assertThat( listas.get(0), is(Arrays.asList(1, 2, 3, 4, 5, 6)) ); } @Test public void deveRetornarONumeroDeSubListas() { List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ,15, 16, 17, 18); Paginador listas = Paginador.ofSize(lista, 6); assertEquals(3, listas.size()); } }
package com.microservices.userservice.dto; import lombok.Data; import lombok.Getter; import lombok.Setter; public class ResponseLoginDTO { public String message; private String statusCode; private Object object; private Object objectModel; public ResponseLoginDTO(String message, String statusCode, Object object, Object objectModel) { this.message = message; this.statusCode = statusCode; this.object = object; this.objectModel = objectModel; } public ResponseLoginDTO(Object object){ this.object = object; } }
package com.smxknife.java2.nio.socket; import org.junit.jupiter.api.Test; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2020/10/7 */ public class _03_ServerSocket { @Test public void serverSocketTest() { try { ServerSocket socket = new ServerSocket(8088); System.out.println("server阻塞开始= " + System.currentTimeMillis()); socket.accept(); System.out.println("server阻塞结束= " + System.currentTimeMillis()); socket.close(); } catch (IOException e) { e.printStackTrace(); } } @Test public void clientConnectToServerTest() { System.out.println("client连接准备=" + System.currentTimeMillis()); try { Socket socket = new Socket("localhost", 8088); System.out.println("client连接结束=" + System.currentTimeMillis()); socket.close(); } catch (IOException e) { e.printStackTrace(); } } @Test public void webServerTest() throws IOException { ServerSocket serverSocket = new ServerSocket(6666); Socket socket = serverSocket.accept(); System.out.println("接收到连接,port = " + socket.getPort()); InputStream inputStream = socket.getInputStream(); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(streamReader); String getString = ""; while (!"".equals(getString = bufferedReader.readLine())) { System.out.println(getString); } OutputStream outputStream = socket.getOutputStream(); outputStream.write("HTTP/1.1 200 OK\r\n\r\n".getBytes()); outputStream.write("<html><body><a href='http://www.baidu.com'>I am baidu.com welcome you!</a></body></html>".getBytes()); outputStream.flush(); outputStream.close(); socket.close(); serverSocket.close(); } @Test public void inputStreamReadBlockTest() { try(ServerSocket serverSocket = new ServerSocket(6666); Socket socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream();) { System.out.println(inputStream.getClass().getName()); System.out.println("read begin " + System.currentTimeMillis()); byte[] bytes = new byte[inputStream.available()]; int readLength = inputStream.read(bytes); System.out.println("read end " + System.currentTimeMillis()); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } @Test public void inputStreamReadBlockClientTest() { System.out.println("client socket begin " + System.currentTimeMillis()); try(Socket socket = new Socket("localhost", 6666)) { System.out.println("client socket end " + System.currentTimeMillis()); TimeUnit.SECONDS.sleep(30); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void acceptTimeoutTest() { try(ServerSocket serverSocket = new ServerSocket(6666);) { serverSocket.setSoTimeout(5000); Socket socket = serverSocket.accept(); } catch (IOException e) { e.printStackTrace(); } } @Test public void backlogServerTest() { try(ServerSocket serverSocket = new ServerSocket(6666, 3)) { TimeUnit.SECONDS.sleep(30); // 这里睡眠30s是为了先不让serversocket进行accept,先让客户端连接 while (true) { Socket socket = serverSocket.accept(); int port = socket.getPort(); System.out.println("client port = " + port + "接入!"); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } @Test public void backlogClientTest() { for (int i = 0; i < 10; i++) { new Thread(() -> { System.out.println("线程 " + Thread.currentThread().getName() + " 准备ok..."); Socket socket = null; try { socket = new Socket("localhost", 6666); System.out.println("client 连接成功 " + socket.getLocalPort() + " | thread = " + Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(30); System.out.println("client port = " + socket.getLocalPort() + " finished"); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + " 连接失败"); e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Throwable e) { e.printStackTrace(); } }, "th-" + i).start(); // try { // TimeUnit.SECONDS.sleep(1); // } catch (InterruptedException e) { // e.printStackTrace(); // } } } }
package com.hb.rssai.bean; import java.util.List; /** * Created by Administrator on 2017/8/15. */ public class ResCollection { /** * retObj : {"total":2,"rows":[{"img":"1221","createTime":"2017-02-02 11:00:00","link":"www.baidu.com","id":"f731e3dc-819b-11e7-af84-b083fe8f693c","title":"cesss","userId":"ee19fa97-7fda-11e7-99c9-206a8a32e7b2"},{"img":"1221","createTime":"2017-02-02 11:00:00","link":"www.baidu.com","id":"ff566c05-819b-11e7-af84-b083fe8f693c","title":"sasdfsdf","userId":"ee19fa97-7fda-11e7-99c9-206a8a32e7b2"}]} * retCode : 0 * retMsg : 操作成功 */ private RetObjBean retObj; private int retCode; private String retMsg; public RetObjBean getRetObj() { return retObj; } public void setRetObj(RetObjBean retObj) { this.retObj = retObj; } public int getRetCode() { return retCode; } public void setRetCode(int retCode) { this.retCode = retCode; } public String getRetMsg() { return retMsg; } public void setRetMsg(String retMsg) { this.retMsg = retMsg; } public static class RetObjBean { /** * total : 2 * rows : [{"img":"1221","createTime":"2017-02-02 11:00:00","link":"www.baidu.com","id":"f731e3dc-819b-11e7-af84-b083fe8f693c","title":"cesss","userId":"ee19fa97-7fda-11e7-99c9-206a8a32e7b2"},{"img":"1221","createTime":"2017-02-02 11:00:00","link":"www.baidu.com","id":"ff566c05-819b-11e7-af84-b083fe8f693c","title":"sasdfsdf","userId":"ee19fa97-7fda-11e7-99c9-206a8a32e7b2"}] */ private int total; private List<RowsBean> rows; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<RowsBean> getRows() { return rows; } public void setRows(List<RowsBean> rows) { this.rows = rows; } public static class RowsBean { /** * img : 1221 * createTime : 2017-02-02 11:00:00 * link : www.baidu.com * id : f731e3dc-819b-11e7-af84-b083fe8f693c * title : cesss * userId : ee19fa97-7fda-11e7-99c9-206a8a32e7b2 */ private String img; private String createTime; private String link; private String id; private String title; private String userId; private String informationId; public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getInformationId() { return informationId; } public void setInformationId(String informationId) { this.informationId = informationId; } } } }
package org.proyectofinal.gestorpacientes.vista.dialogos; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Frame; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import org.proyectofinal.gestorpacientes.modelo.entidades.Paciente; import org.proyectofinal.gestorpacientes.modelo.entidades.PruebaDeLaboratorio; public class DialogResultadosLaboratorio extends IDialog{ /** * */ private static final long serialVersionUID = 1L; private JPanel panelContenedorTabla; private JTextField id; private JTextField resultado; private JScrollPane scrollTabla; private JPanel editarGuardar; private JPanel nuevoEliminar; private JLabel lblCodigo; private JLabel lblResultado; private JComboBox<Paciente> paciente; private JLabel lblPrueba; private JComboBox<PruebaDeLaboratorio> prueba; public DialogResultadosLaboratorio(Frame padre, boolean modal) { super(padre, modal); init(); // TODO Auto-generated constructor stub } public void init(){ getContentPane().setLayout(null); getContentPane().add(getId()); getContentPane().add(getResultado()); getContentPane().add(getScrollTabla()); getContentPane().add(getEditarGuardar()); getContentPane().add(getNuevoEliminar()); getContentPane().add(getLblCodigo()); getContentPane().add(getLblResultado()); getContentPane().add(getPaciente()); JLabel lblPaciente = new JLabel("Paciente:"); lblPaciente.setBounds(43, 109, 46, 14); getContentPane().add(lblPaciente); getContentPane().add(getLblPrueba()); getContentPane().add(getPrueba()); } /*********************************************************************** * Combo box Prueba de laboratorio ***********************************************************************/ public JComboBox<PruebaDeLaboratorio> getPrueba(){ if(prueba == null){ prueba = new JComboBox<PruebaDeLaboratorio>(); prueba.setBounds(114, 62, 86, 20); prueba.setEditable(false); } return prueba; } /*********************************************************************** * Combo box Paciente ***********************************************************************/ public JComboBox<Paciente> getPaciente(){ if(paciente == null){ paciente = new JComboBox(); paciente.setBounds(112, 106, 119, 20); } return paciente; } /*********************************************************************** * TextField Codigo ***********************************************************************/ public JTextField getId(){ if(id == null){ id = new JTextField(10); id.setBounds(114, 25, 86, 20); id.setName("codigo"); id.setEditable(false); } return id; } /*********************************************************************** * TextField Resultado ***********************************************************************/ public JTextField getResultado(){ if(resultado == null){ resultado = new JTextField(30); resultado.setBounds(321, 62, 246, 20); resultado.setName("nombre"); resultado.setEditable(false); } return resultado; } /*************************************************** * SCrollPanel de la tabla **************************************************/ public JScrollPane getScrollTabla(){ if(scrollTabla == null){ scrollTabla = new JScrollPane(getPanelContenedorTable()); scrollTabla.setBounds(20, 137, 569, 214); } return scrollTabla; } /*********************************************************************** * Panel Contenedor del Scroll de la tabla ***********************************************************************/ public JPanel getPanelContenedorTable(){ if(panelContenedorTabla == null){ panelContenedorTabla = new JPanel(); panelContenedorTabla.setLayout(new BorderLayout(0, 0)); panelContenedorTabla.add(getPanelTabla()); } return panelContenedorTabla; } /*********************************************************************** * Panel Contenedor de los botones Editar y Guardar ***********************************************************************/ public JPanel getEditarGuardar(){ if(editarGuardar == null){ editarGuardar = new JPanel(new FlowLayout()); editarGuardar.setBounds(380, 93, 187, 35); editarGuardar.add(getEditar()); editarGuardar.add(getGuardar()); } return editarGuardar; } /*********************************************************************** * Panel Contenedor de los botones Nuevo y Eliminar ***********************************************************************/ public JPanel getNuevoEliminar(){ if(nuevoEliminar == null){ nuevoEliminar = new JPanel(new FlowLayout()); nuevoEliminar.setBounds(372, 357, 195, 43); nuevoEliminar.add(getNuevo()); nuevoEliminar.add(getEliminar()); } return nuevoEliminar; } private JLabel getLblCodigo() { if (lblCodigo == null) { lblCodigo = new JLabel("ID:"); lblCodigo.setBounds(43, 28, 46, 14); } return lblCodigo; } private JLabel getLblResultado() { if (lblResultado == null) { lblResultado = new JLabel("Resultado:"); lblResultado.setBounds(242, 65, 69, 14); } return lblResultado; } private JLabel getLblPrueba() { if (lblPrueba == null) { lblPrueba = new JLabel("Prueba"); lblPrueba.setBounds(43, 65, 46, 14); } return lblPrueba; } }
package fr.clivana.lemansnews.async; import fr.clivana.lemansnews.utils.reseau.Reseau; import fr.clivana.lemansnews.view.ListeEvenementsActivity; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; public class AsyncTaskListeEvenements extends AsyncTask<Void, Void, Void> { Context context; ProgressDialog progress; public AsyncTaskListeEvenements(Context context) { super(); this.context = context; progress=new ProgressDialog(this.context); progress.setMessage("Mise à jour en cours..."); } @Override protected void onPreExecute() { super.onPreExecute(); progress.show(); } @Override protected Void doInBackground(Void... params) { Reseau.majEvenements(context, 0, 0); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); progress.dismiss(); ((ListeEvenementsActivity) context).initAdapters(); } }
package com.cz.android.simplehttp.socket; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; public class SimpleOutputHTTPServer { public static void main(String args[]) throws IOException { ServerSocket server = new ServerSocket(8090); System.out.println("Listening for connection on port 8090 ...."); while (true) { Socket clientSocket = server.accept(); InputStream isr = clientSocket.getInputStream(); try { int read; byte[] bytes=new byte[100*1024]; FileOutputStream fileOutputStream=new FileOutputStream(new File("request.txt")); while (-1!=(read = isr.read(bytes))) { fileOutputStream.write(bytes,0,read); System.out.println("read:"+read+"\n"+new String(bytes,0,read)); } OutputStream outputStream = clientSocket.getOutputStream(); outputStream.write("response!".getBytes()); outputStream.flush(); } catch (SocketException e){ clientSocket.close(); } } } }
package com.findme.exception.handler; import com.findme.exception.BadRequestException; import com.findme.exception.InternalServerError; import com.findme.exception.NotFoundException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; @RestControllerAdvice(basePackages = "com.findme.api") public class RestControllerExceptionHandler { @ExceptionHandler(value = BadRequestException.class) public ResponseEntity<String> handleBadRequestException(HttpServletRequest request, Exception e){ return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = InternalServerError.class) public ResponseEntity<String> handleInternalServerError(HttpServletRequest request, Exception e){ return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(value = NotFoundException.class) public ResponseEntity<String> handleNotFoundException(HttpServletRequest request, Exception e){ return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND); } }
/* * Copyright (c) 2021, salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.salesforce.cdp.queryservice.core; import com.salesforce.cdp.queryservice.util.Constants; import static com.salesforce.cdp.queryservice.util.Messages.QUERY_EXCEPTION; import com.salesforce.cdp.queryservice.util.QueryExecutor; import com.salesforce.cdp.queryservice.ResponseEnum; import okhttp3.*; import org.apache.http.HttpStatus; import org.assertj.core.api.Assertions; import org.junit.Assert; import static org.assertj.core.api.Assertions.catchThrowableOfType; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Optional; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class QueryServiceStatementTest { @Mock private QueryServiceConnection queryServiceConnection; private QueryExecutor queryExecutor; private QueryServiceStatement queryServiceStatement; @Before public void init() { queryExecutor = mock(QueryExecutor.class); queryServiceStatement = new QueryServiceStatement(queryServiceConnection, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY) { @Override protected QueryExecutor createQueryExecutor() { return queryExecutor; } }; } @Test public void testExecuteQueryWithFailedResponse() throws SQLException, IOException { String jsonString = ResponseEnum.UNAUTHORIZED.getResponse(); Response response = new Response.Builder().code(HttpStatus.SC_UNAUTHORIZED). request(buildRequest()).protocol(Protocol.HTTP_1_1). message("Unauthorized"). body(ResponseBody.create(jsonString, MediaType.parse("application/json"))).build(); doReturn(response).when(queryExecutor).executeQuery(anyString(), anyBoolean(), any(Optional.class), any(Optional.class), any(Optional.class)); Throwable ex = catchThrowableOfType(() -> { queryServiceStatement.executeQuery("select FirstName__c from Individual__dlm limit 10"); }, SQLException.class); Assertions.assertThat(ex.getMessage()).contains("Failed to get the response for the query. Please try again."); } @Test public void testExecuteQueryWithSuccessfulResponse() throws IOException, SQLException { String jsonString = ResponseEnum.QUERY_RESPONSE.getResponse(); Response response = new Response.Builder().code(HttpStatus.SC_OK). request(buildRequest()).protocol(Protocol.HTTP_1_1). message("Successful"). body(ResponseBody.create(jsonString, MediaType.parse("application/json"))).build(); doReturn(response).when(queryExecutor).executeQuery(anyString(), anyBoolean(), any(Optional.class), any(Optional.class), any(Optional.class)); ResultSet resultSet = queryServiceStatement.executeQuery("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1"); int count = 0; while (resultSet.next()) { Assert.assertNotNull(resultSet.getString(1)); count++; } Assert.assertEquals(resultSet.getMetaData().getColumnCount(), 1); Assert.assertEquals(resultSet.getMetaData().getColumnName(1), "telephonenumber__c"); Assert.assertEquals(resultSet.getMetaData().getColumnType(1), 12); Assert.assertEquals(count, 2); } @Test public void testExecuteQueryWithNoData() throws IOException, SQLException { String jsonString = ResponseEnum.EMPTY_RESPONSE.getResponse(); Response response = new Response.Builder().code(HttpStatus.SC_OK). request(buildRequest()).protocol(Protocol.HTTP_1_1). message("Successful"). body(ResponseBody.create(jsonString, MediaType.parse("application/json"))).build(); doReturn(response).when(queryExecutor).executeQuery(anyString(), anyBoolean(), any(Optional.class), any(Optional.class), any(Optional.class)); ResultSet resultSet = queryServiceStatement.executeQuery("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1"); Assert.assertFalse(resultSet.next()); } @Test public void testExceuteQueryWithIOException() throws IOException, SQLException { doThrow(new IOException("IO Exception")).when(queryExecutor).executeQuery(anyString(), anyBoolean(), any(Optional.class), any(Optional.class), any(Optional.class)); Throwable ex = catchThrowableOfType(() -> { queryServiceStatement.executeQuery("select FirstName__c from Individual__dlm limit 10"); }, SQLException.class); Assertions.assertThat(ex.getMessage()).contains(QUERY_EXCEPTION); } @Test public void testPagination() throws IOException, SQLException { String paginationResponseString = ResponseEnum.PAGINATION_RESPONSE.getResponse(); Response paginationResponse = new Response.Builder().code(HttpStatus.SC_OK). request(buildRequest()).protocol(Protocol.HTTP_1_1). message("Successful"). body(ResponseBody.create(paginationResponseString, MediaType.parse("application/json"))).build(); String queryResponseString = ResponseEnum.QUERY_RESPONSE.getResponse(); Response queryResponse = new Response.Builder().code(HttpStatus.SC_OK). request(buildRequest()).protocol(Protocol.HTTP_1_1). message("Successful"). body(ResponseBody.create(queryResponseString, MediaType.parse("application/json"))).build(); doReturn(paginationResponse).doReturn(queryResponse).when(queryExecutor).executeQuery(anyString(), anyBoolean(), any(Optional.class), any(Optional.class), any(Optional.class)); QueryServiceStatement queryServiceStatementSpy = Mockito.spy(queryServiceStatement); ResultSet resultSet = queryServiceStatementSpy.executeQuery("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1"); int count = 0; while (resultSet.next()) { count++; } Assert.assertEquals(count, 4); verify(queryServiceStatementSpy, times(2)).executeQuery(eq("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1")); } @Test public void testDataWithMetadataResponse() throws IOException, SQLException { String jsonString = ResponseEnum.QUERY_RESPONSE_WITH_METADATA.getResponse(); Response response = new Response.Builder().code(HttpStatus.SC_OK). request(buildRequest()).protocol(Protocol.HTTP_1_1). message("Successful"). body(ResponseBody.create(jsonString, MediaType.parse("application/json"))).build(); doReturn(response).when(queryExecutor).executeQuery(anyString(), anyBoolean(), any(Optional.class), any(Optional.class), any(Optional.class)); ResultSet resultSet = queryServiceStatement.executeQuery("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1"); int count = 0; while (resultSet.next()) { Assert.assertNotNull(resultSet.getString(1)); count++; } Assert.assertEquals(resultSet.getMetaData().getColumnCount(), 1); Assert.assertEquals(resultSet.getMetaData().getColumnName(1), "count_num"); Assert.assertEquals(resultSet.getMetaData().getColumnTypeName(1), "DECIMAL"); Assert.assertEquals(count, 1); } @Test public void testQueryResponseWithoutPagination() throws IOException, SQLException { String paginationResponseString = ResponseEnum.QUERY_RESPONSE_WITHOUT_DONE_FLAG.getResponse(); Response paginationResponse = new Response.Builder().code(HttpStatus.SC_OK). request(buildRequest()).protocol(Protocol.HTTP_1_1). message("Successful"). body(ResponseBody.create(paginationResponseString, MediaType.parse("application/json"))).build(); doReturn(paginationResponse).when(queryExecutor).executeQuery(anyString(), anyBoolean(), any(Optional.class), any(Optional.class), any(Optional.class)); QueryServiceStatement queryServiceStatementSpy = Mockito.spy(queryServiceStatement); ResultSet resultSet = queryServiceStatementSpy.executeQuery("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1"); int count = 0; while (resultSet.next()) { count++; } Assert.assertEquals(count, 2); verify(queryServiceStatementSpy, times(1)).executeQuery(eq("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1")); } @Test public void testExecuteQueryForOrderByQueries() throws IOException, SQLException { String paginationResponseString = ResponseEnum.QUERY_RESPONSE_WITHOUT_DONE_FLAG.getResponse(); Response paginationResponse = new Response.Builder().code(HttpStatus.SC_OK). request(buildRequest()).protocol(Protocol.HTTP_1_1). message("Successful"). body(ResponseBody.create(paginationResponseString, MediaType.parse("application/json"))).build(); doReturn(paginationResponse).when(queryExecutor).executeQuery(anyString(), anyBoolean(), any(Optional.class), any(Optional.class), any(Optional.class)); QueryServiceStatement queryServiceStatementSpy = Mockito.spy(queryServiceStatement); ResultSet resultSet = queryServiceStatementSpy.executeQuery("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1 ORDER BY TelephoneNumber__c"); int count = 0; while (resultSet.next()) { count++; } Assert.assertEquals(count, 2); ArgumentCaptor<Optional> captor = ArgumentCaptor.forClass(Optional.class); verify(queryExecutor, times(1)).executeQuery(eq("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1 ORDER BY TelephoneNumber__c"), anyBoolean(), any(Optional.class), any(Optional.class), captor.capture()); Optional<String> value = captor.getValue(); Assert.assertFalse(value.isPresent()); } @Test public void testExecuteQueryForTableauQueries() throws IOException, SQLException { String paginationResponseString = ResponseEnum.QUERY_RESPONSE_WITHOUT_DONE_FLAG.getResponse(); Response paginationResponse = new Response.Builder().code(HttpStatus.SC_OK). request(buildRequest()).protocol(Protocol.HTTP_1_1). message("Successful"). body(ResponseBody.create(paginationResponseString, MediaType.parse("application/json"))).build(); doReturn(paginationResponse).when(queryExecutor).executeQuery(anyString(), anyBoolean(), any(Optional.class), any(Optional.class), any(Optional.class)); doReturn(Constants.TABLEAU_USER_AGENT_VALUE).when(queryServiceConnection).getClientInfo(eq(Constants.USER_AGENT)); QueryServiceStatement queryServiceStatementSpy = Mockito.spy(queryServiceStatement); ResultSet resultSet = queryServiceStatementSpy.executeQuery("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1"); int count = 0; while (resultSet.next()) { count++; } Assert.assertEquals(count, 2); ArgumentCaptor<Optional> captor = ArgumentCaptor.forClass(Optional.class); verify(queryExecutor, times(1)).executeQuery(eq("select TelephoneNumber__c from ContactPointPhone__dlm GROUP BY 1"), anyBoolean(), any(Optional.class), any(Optional.class), captor.capture()); Optional<String> value = captor.getValue(); String val = value.get(); Assert.assertEquals(val, "1 ASC"); } private Request buildRequest() { return new Request.Builder() .url("https://mjrgg9bzgy2dsyzvmjrgkmzzg1.c360a.salesforce.com" + Constants.CDP_URL + Constants.ANSI_SQL_URL + Constants.QUESTION_MARK) .method(Constants.POST, RequestBody.create("{test: test}", MediaType.parse("application/json"))) .build(); } }
package KBPBot; import com.google.gson.*; import com.vk.api.sdk.client.VkApiClient; import com.vk.api.sdk.client.actors.Actor; import com.vk.api.sdk.client.actors.GroupActor; import com.vk.api.sdk.exceptions.ApiException; import com.vk.api.sdk.exceptions.ClientException; import com.vk.api.sdk.objects.users.User; import java.util.List; public class JsonInObject { public static String getFirstName(int userId, VkApiClient vk, GroupActor actor) throws ClientException, ApiException { List listName = vk.users().get(actor).userIds(""+userId).execute(); String name = listName.get(0).toString(); JsonParser parser = new JsonParser(); return parser.parse(listName.get(0).toString()).getAsJsonObject().get("first_name").getAsString(); } public static String getLastName(int userId, VkApiClient vk, GroupActor actor) throws ClientException, ApiException { List listName = vk.users().get(actor).userIds(""+userId).execute(); String name = listName.get(0).toString(); JsonParser parser = new JsonParser(); return parser.parse(listName.get(0).toString()).getAsJsonObject().get("last_name").getAsString(); } }
package com.yinghai.a24divine_user.module.divine.divinelist.presenter; import android.content.Context; import com.yinghai.a24divine_user.base.MyBasePresenter; import com.yinghai.a24divine_user.bean.CollectBean; import com.yinghai.a24divine_user.bean.MasterBean; import com.yinghai.a24divine_user.module.collect.mvp.CollectModel; import com.yinghai.a24divine_user.module.collect.mvp.ContractCollect; import com.yinghai.a24divine_user.module.divine.divinelist.ContractDivine; import com.yinghai.a24divine_user.module.divine.divinelist.model.GetDivineModel; /** * Created by chenjianrun on 2017/10/30. * 描述:查看所有名师占卜的列表的Presenter */ public class DivinePresenter extends MyBasePresenter<GetDivineModel, ContractDivine.IDivineView> implements ContractDivine.IDivinePresenter, ContractDivine.IDivineModel.IDivineCallback, ContractCollect.ICollectModel.IAddCollectCallback, ContractCollect.ICollectModel.ICancelCollectCallback { private int mPageNum = 1; private CollectModel mCollectModel; public DivinePresenter(ContractDivine.IDivineView baseView, Context context) { attachView(baseView); } private CollectModel getCollectModel() { if (mCollectModel == null) { mCollectModel = new CollectModel(); } return mCollectModel; } @Override protected GetDivineModel createModel() { return new GetDivineModel(); } @Override public void onGetMaster(int pageSize,String businessType) { mBaseModel.getMasterList(mPageNum, pageSize,businessType, this); } @Override public void onCollectMaster(int masterId, boolean isCollect) { if (isCollect) { getCollectModel().cancelCollect(1, masterId, this); } else { getCollectModel().addCollect(1, masterId, this); } } @Override public void onGetMasterSuccess(MasterBean.DataBean bean) { if (isViewAttached()) { getBaseView().showGetMasterSuccess(bean); mPageNum++; } } @Override public void onGetMasterFailure(String errMsg) { if (isViewAttached()) { getBaseView().showGetMasterFailure(errMsg); } } @Override public void onAddCollectSuccess(CollectBean bean,int id) { if (isViewAttached()) { getBaseView().showCollectMasterSuccess(id); } } @Override public void onAddCollectFailure(String errMsg) { if (isViewAttached()) { getBaseView().showCollectMasterFailure(errMsg); } } @Override public void handlerResultCode(int code) { handleResultCode(code); } /** * 上拉刷新时,需要重置页码 */ public void resetPage() { mPageNum = 1; } @Override public void detachView() { super.detachView(); if (mCollectModel != null) { mCollectModel.onDestroy(); mCollectModel = null; } } @Override public void onCancelCollectSuceess(CollectBean bean,int id) { if (isViewAttached()) { getBaseView().showCancelCollectMasterSuccess(id); } } @Override public void onCancelCollectFailure(String errMsg ) { if (isViewAttached()) { getBaseView().showCancelCollectMasterFailure(errMsg); } } }
package com.kzw.leisure.ui.activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.SeekBar; import com.kzw.leisure.R; import com.kzw.leisure.adapter.ChapterAdapter; import com.kzw.leisure.base.BaseActivity; import com.kzw.leisure.bean.Chapter; import com.kzw.leisure.bean.ChapterRule; import com.kzw.leisure.bean.Query; import com.kzw.leisure.contract.ReadBookContract; import com.kzw.leisure.model.ReadBookModel; import com.kzw.leisure.presenter.ReadBookPresenter; import com.kzw.leisure.realm.BookContentBean; import com.kzw.leisure.realm.BookRealm; import com.kzw.leisure.realm.ChapterList; import com.kzw.leisure.realm.SourceRuleRealm; import com.kzw.leisure.utils.AppUtils; import com.kzw.leisure.utils.LogUtils; import com.kzw.leisure.utils.RealmHelper; import com.kzw.leisure.utils.StatusBarUtil; import com.kzw.leisure.utils.SystemUtil; import com.kzw.leisure.widgets.AdjustMenu; import com.kzw.leisure.widgets.ReadBookChangeSourceDialog; import com.kzw.leisure.widgets.SettingMenu; import com.kzw.leisure.widgets.UISettingMenu; import com.kzw.leisure.widgets.VerticalSeekBar; import com.kzw.leisure.widgets.anim.PageAnimation; import com.kzw.leisure.widgets.pageView.BottomMenuWidget; import com.kzw.leisure.widgets.pageView.PageLoader; import com.kzw.leisure.widgets.pageView.PageView; import com.kzw.leisure.widgets.pageView.ReadBookControl; import com.kzw.leisure.widgets.pageView.TopMenuWidget; import com.zia.easybook.widget.TxtChapter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.drawerlayout.widget.DrawerLayout; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import butterknife.BindView; import io.reactivex.Flowable; public class ReadBookActivity extends BaseActivity<ReadBookPresenter, ReadBookModel> implements ReadBookContract.View { @BindView(R.id.pageView) PageView pageView; @BindView(R.id.topmenu) TopMenuWidget topmenu; @BindView(R.id.bottommenu) BottomMenuWidget bottommenu; @BindView(R.id.menu_layout) FrameLayout menuLayout; @BindView(R.id.recyclerview) RecyclerView recyclerview; @BindView(R.id.slideLayout) LinearLayout slideLayout; @BindView(R.id.drawerlayout) DrawerLayout drawerlayout; @BindView(R.id.swipeRefresh) SwipeRefreshLayout swipeRefresh; @BindView(R.id.adjust_menu) AdjustMenu adjustMenu; @BindView(R.id.setting_menu) SettingMenu settingMenu; @BindView(R.id.ui_setting_menu) UISettingMenu uiSettingMenu; @BindView(R.id.vertical_seekbar) VerticalSeekBar verticalSeekbar; BookRealm bookRealm;//保存的书籍信息 SourceRuleRealm currentRule;//保存的书籍章节解析规则 ChapterList currentChapterListUrl;//保存的书籍的章节列表和获取章节列表的path url ChapterRule chapterRule;//将保存的章节解析规则转换成对象 ReadBookControl readBookControl = ReadBookControl.getInstance(); List<Chapter> chapterList = new ArrayList<>(); ChapterAdapter adapter; Animation menuTopIn, menuTopOut, menuBottomIn, menuBottomOut; PageLoader mPageLoader; int screenTimeOut; Runnable keepScreenRunnable; @Override protected int getContentView() { return R.layout.activity_read_book; } @Override public void initView(Bundle savedInstanceState) { StatusBarUtil.fullScreen(this); StatusBarUtil.StatusBarLightMode(this, true); setActionBar(bookRealm.getBookName(), true, topmenu.toolbar); keepScreenRunnable = this::unKeepScreenOn; drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); menuBottomIn = AnimationUtils.loadAnimation(this, R.anim.anim_readbook_bottom_in); menuTopIn = AnimationUtils.loadAnimation(this, R.anim.anim_readbook_top_in); menuTopOut = AnimationUtils.loadAnimation(this, R.anim.anim_readbook_top_out); menuBottomOut = AnimationUtils.loadAnimation(this, R.anim.anim_readbook_bottom_out); menuTopIn.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { menuLayout.setOnClickListener(view -> menuMiss()); } @Override public void onAnimationRepeat(Animation animation) { } }); menuBottomIn.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { menuLayout.setOnClickListener(view -> menuMiss()); } @Override public void onAnimationRepeat(Animation animation) { } }); menuTopOut.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { menuLayout.setOnClickListener(null); } @Override public void onAnimationEnd(Animation animation) { allMenuMiss(); } @Override public void onAnimationRepeat(Animation animation) { } }); menuBottomOut.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { menuLayout.setOnClickListener(null); } @Override public void onAnimationEnd(Animation animation) { allMenuMiss(); } @Override public void onAnimationRepeat(Animation animation) { } }); adjustMenu.initData(this); settingMenu.setListener(new SettingMenu.Callback() { @Override public void upBar() { } @Override public void keepScreenOnChange(int keepScreenOn) { screenTimeOut = getResources().getIntArray(R.array.screen_time_out_value)[keepScreenOn]; screenOffTimerStart(); } @Override public void recreate() { ReadBookActivity.this.recreate(); } @Override public void refreshPage() { mPageLoader.refreshUi(); } }); uiSettingMenu.setListener(this, new UISettingMenu.Callback() { @Override public void upPageMode() { if (mPageLoader != null) { mPageLoader.setPageMode(PageAnimation.Mode.getPageMode(readBookControl.getPageMode())); } } @Override public void upTextSize() { if (mPageLoader != null) { mPageLoader.setTextSize(); } } @Override public void bgChange() { readBookControl.initTextDrawableIndex(); pageView.setBackground(readBookControl.getTextBackground(ReadBookActivity.this)); if (mPageLoader != null) { mPageLoader.refreshUi(); } } @Override public void refresh() { if (mPageLoader != null) { mPageLoader.refreshUi(); } } }); recyclerview.setLayoutManager(new LinearLayoutManager(this)); recyclerview.setItemAnimator(new DefaultItemAnimator()); adapter = new ChapterAdapter(); recyclerview.setAdapter(adapter); adapter.setOnItemClickListener((adapter, view, position) -> { drawerlayout.closeDrawer(slideLayout); mPageLoader.skipToChapter(position, 0); }); swipeRefresh.setColorSchemeResources(R.color.colorPrimary); swipeRefresh.setEnabled(false); pageView.setBackground(readBookControl.getTextBackground(mContext)); mPageLoader = pageView.getPageLoader(this, bookRealm, new PageLoader.Callback() { @Override public List<Chapter> getChapterList() { return chapterList; } @Override public void onChapterChange(int pos) { if (bookRealm.getChapterListSize() == 1) { bottommenu.setTvPre(false); bottommenu.setTvNext(false); } else { if (pos == 0) { bottommenu.setTvPre(false); bottommenu.setTvNext(true); } else if (pos == bookRealm.getChapterListSize() - 1) { bottommenu.setTvPre(true); bottommenu.setTvNext(false); } else { bottommenu.setTvPre(true); bottommenu.setTvNext(true); } } } @Override public void onCategoryFinish(List<Chapter> chapters) { chapterList = chapters; adapter.setNewData(chapterList); recyclerview.scrollToPosition(bookRealm.getDurChapter()); } @Override public void onPageCountChange(int count) { bottommenu.getReadProgress().setMax(Math.max(0, count - 1)); bottommenu.getReadProgress().setProgress(0); // 如果处于错误状态,那么就冻结使用 bottommenu.getReadProgress().setEnabled(mPageLoader.getPageStatus() != TxtChapter.Status.LOADING && mPageLoader.getPageStatus() != TxtChapter.Status.ERROR); } @Override public void onPageChange(int chapterIndex, int pageIndex, boolean resetReadAloud) { bottommenu.getReadProgress().post(() -> bottommenu.getReadProgress().setProgress(pageIndex)); } @Override public void vipPop() { } @Override public Flowable<BookContentBean> getContent(Chapter chapter) { return mModel.getContent(chapterRule, chapter); } }); pageView.setTouchListener(new PageView.TouchListener() { @Override public void onTouch() { } @Override public void onTouchClearCursor() { } @Override public void onLongPress() { } @Override public void center() { menuShow(); } }); bottommenu.setListener(new BottomMenuWidget.Callback() { @Override public void skipToPage(int id) { mPageLoader.skipToPage(id); } @Override public void onMediaButton() { } @Override public void autoPage() { } @Override public void setNightTheme() { } @Override public void skipPreChapter() { mPageLoader.skipPreChapter(); } @Override public void skipNextChapter() { mPageLoader.skipNextChapter(); } @Override public void openReplaceRule() { } @Override public void openChapterList() { getChapterList(true); drawerlayout.openDrawer(slideLayout); swipeRefresh.setRefreshing(true); menuMiss(); } @Override public void openAdjust() { menuMiss(); AppUtils.runOnUIDelayed(ReadBookActivity.this::adjustMenuShow, menuBottomOut.getDuration() + 100); } @Override public void openReadInterface() { menuMiss(); AppUtils.runOnUIDelayed(ReadBookActivity.this::uiSettingMenuShow, menuBottomOut.getDuration() + 100); } @Override public void openMoreSetting() { menuMiss(); AppUtils.runOnUIDelayed(ReadBookActivity.this::settingMenuShow, menuBottomOut.getDuration() + 100); } @Override public void toast(int id) { } @Override public void dismiss() { menuMiss(); } }); verticalSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { if (i > 0) { double result = new BigDecimal((double) i / (double) 100).setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue(); recyclerview.scrollToPosition(chapterList.size() - Double.valueOf(result * chapterList.size()).intValue()); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); switch (newState) { case RecyclerView.SCROLL_STATE_DRAGGING: AppUtils.removeRunnable(ReadBookActivity.this::scrollbarDismiss); if (!isFinishing() && verticalSeekbar.getVisibility() == View.INVISIBLE) { verticalSeekbar.setVisibility(View.VISIBLE); } break; case RecyclerView.SCROLL_STATE_IDLE: if (!isFinishing() &&!verticalSeekbar.isSelect()) { AppUtils.runOnUIDelayed(ReadBookActivity.this::scrollbarDismiss, 2000); } break; } } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int range = recyclerView.computeVerticalScrollRange(); int offset = recyclerView.computeVerticalScrollOffset(); if (!isFinishing() &&!verticalSeekbar.isSelect()) { double result = new BigDecimal((double) offset / (double) range).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); verticalSeekbar.setProgress(100 - Double.valueOf(result * 100).intValue()); } } }); } private void scrollbarDismiss() { verticalSeekbar.setVisibility(View.INVISIBLE); } @Override protected void initPresenter() { mPresenter.setVM(this, mModel); RealmHelper.getInstance().init(); bookRealm = RealmHelper.getInstance().getBook(); currentRule = bookRealm.getCurrentRule(); currentChapterListUrl = bookRealm.getCurrentChapterListRule(); if (currentRule == null) { currentRule = bookRealm.getSourceRuleRealmList().get(0); } if (currentChapterListUrl == null) { currentChapterListUrl = bookRealm.getSearchNoteUrlList().get(0); } readBookControl.initTextDrawableIndex(); readBookControl.setPageMode(3); } @Override public void initData() { getChapterList(false); } private void getChapterList(boolean isFromNet) { try { chapterRule = new ChapterRule(currentRule);//realm不能在子线程调用get或set方法,这里转换成其他对象 LogUtils.d(chapterRule.toString()); Query query = new Query(currentChapterListUrl.getChapterListUrlRule(), null, chapterRule.getBaseUrl()); mPresenter.getChapterList(query, chapterRule, currentChapterListUrl, isFromNet); } catch (Exception e) { e.printStackTrace(); } } @Override public void returnResult(List<Chapter> list) { chapterList = list; adapter.setNewData(chapterList); mPageLoader.refreshChapterList(); if (bookRealm.getDurChapter() < list.size()) { recyclerview.scrollToPosition(bookRealm.getDurChapter()); } else { recyclerview.scrollToPosition(list.size() - 1); } if (swipeRefresh.isRefreshing()) { swipeRefresh.setRefreshing(false); } } @Override public void returnFail(String message) { showToast(message); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.top_menu_bar, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; case R.id.action_change_source: menuMiss(); ReadBookChangeSourceDialog .builder(mContext, currentRule) .setList(bookRealm.getSourceRuleRealmList()) .setListener((bean, position) -> { currentRule = bean; currentChapterListUrl = bookRealm.getSearchNoteUrlList().get(position); RealmHelper.getInstance().getRealm().executeTransaction(realm -> { bookRealm.setCurrentRule(currentRule); bookRealm.setCurrentChapterListRule(currentChapterListUrl); }); mPageLoader.setStatus(TxtChapter.Status.CHANGE_SOURCE); getChapterList(false); }) .show(); break; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); } @Override protected void onDestroy() { super.onDestroy(); AppUtils.removeRunnable(this::scrollbarDismiss); RealmHelper.getInstance().closeRealm(); if (mPageLoader != null) { mPageLoader.closeBook(); mPageLoader = null; } } private void menuMiss() { if (menuLayout.getVisibility() == View.VISIBLE) { if (topmenu.getVisibility() == View.VISIBLE) { topmenu.startAnimation(menuTopOut); } if (bottommenu.getVisibility() == View.VISIBLE) { bottommenu.startAnimation(menuBottomOut); } if (adjustMenu.getVisibility() == View.VISIBLE) { adjustMenu.startAnimation(menuBottomOut); } if (settingMenu.getVisibility() == View.VISIBLE) { settingMenu.startAnimation(menuBottomOut); } if (uiSettingMenu.getVisibility() == View.VISIBLE) { uiSettingMenu.startAnimation(menuBottomOut); } } } private void allMenuMiss() { menuLayout.setVisibility(View.INVISIBLE); topmenu.setVisibility(View.INVISIBLE); bottommenu.setVisibility(View.INVISIBLE); adjustMenu.setVisibility(View.INVISIBLE); settingMenu.setVisibility(View.INVISIBLE); uiSettingMenu.setVisibility(View.INVISIBLE); } private void menuShow() { menuLayout.setVisibility(View.VISIBLE); topmenu.setVisibility(View.VISIBLE); topmenu.startAnimation(menuTopIn); bottommenu.setVisibility(View.VISIBLE); bottommenu.startAnimation(menuBottomIn); } private void adjustMenuShow() { menuLayout.setVisibility(View.VISIBLE); adjustMenu.setVisibility(View.VISIBLE); adjustMenu.startAnimation(menuBottomIn); } private void settingMenuShow() { menuLayout.setVisibility(View.VISIBLE); settingMenu.setVisibility(View.VISIBLE); settingMenu.startAnimation(menuBottomIn); } private void uiSettingMenuShow() { menuLayout.setVisibility(View.VISIBLE); uiSettingMenu.setVisibility(View.VISIBLE); uiSettingMenu.startAnimation(menuBottomIn); } /** * 重置黑屏时间 */ private void screenOffTimerStart() { if (screenTimeOut < 0) { keepScreenOn(true); return; } int screenOffTime = screenTimeOut * 1000 - SystemUtil.getScreenOffTime(this); if (screenOffTime > 0) { AppUtils.removeRunnable(keepScreenRunnable); keepScreenOn(true); AppUtils.runOnUIDelayed(keepScreenRunnable, screenOffTime); } else { keepScreenOn(false); } } /** * @param keepScreenOn 是否保持亮屏 */ public void keepScreenOn(boolean keepScreenOn) { if (keepScreenOn) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } /** * 取消亮屏保持 */ private void unKeepScreenOn() { keepScreenOn(false); } }
package com.appdear.client.Adapter; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView.ScaleType; import com.appdear.client.R; import com.appdear.client.commctrls.AsynLoadImageView; import com.appdear.client.commctrls.Common; import com.appdear.client.commctrls.GalleryFlow; import com.appdear.client.model.GalleryFlowInfo; import com.appdear.client.service.Constants; import com.appdear.client.utility.ServiceUtils; public class GalleryAdAdapter extends BaseAdapter{ private String TAG = "GalleryAdAdapter"; public Context context; ArrayList<GalleryFlowInfo> images = null; public GalleryAdAdapter(Context context,ArrayList<GalleryFlowInfo> galleryFlowAdModel){ this.context = context; this.images = galleryFlowAdModel; } @Override public int getCount() { //return Integer.MAX_VALUE; return images.size(); } @Override public Object getItem(int position) { return images.get(position-1); } @Override public long getItemId(int position) { return position-1; } @Override public View getView(int position, View view, ViewGroup parent) { DisplayMetrics metrics = ServiceUtils.getMetrics(((Activity)context).getWindowManager()); int winHeight = metrics.heightPixels; int winWidth = metrics.widthPixels; AsynLoadImageView asynImageView = new AsynLoadImageView(context); asynImageView.setPadding(5, 10, 5, 8); asynImageView.setScaleType(ScaleType.FIT_XY); if(winWidth<=480){ asynImageView.setLayoutParams(new GalleryFlow.LayoutParams(75,75)); } if(winWidth<=320){ asynImageView.setLayoutParams(new GalleryFlow.LayoutParams(65,65)); } if(winWidth<=240){ asynImageView.setLayoutParams(new GalleryFlow.LayoutParams(50,50)); } asynImageView.setDefaultImage(R.drawable.soft_lsit_icon_default); asynImageView.setImageResource(R.drawable.soft_lsit_icon_default); if (Constants.DEBUG) { if(position<=this.images.size()) Log.i(TAG,"Load image from :"+ this.images.get(position).url); } if (Common.ISLOADSOFTICON&&position<=this.images.size()) asynImageView.setImageUrl(this.images.get(position).url, true); return asynImageView; } }
package cc.stan.example.graphql.resolver; import cc.stan.example.graphql.model.Author; import com.coxautodev.graphql.tools.GraphQLQueryResolver; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; @Component public class AuthorQuery implements GraphQLQueryResolver { public List<Author> queryAuthor() { return Arrays.asList( Author.builder().id(1L).name("hello").build(), Author.builder().id(2L).name("world").build() ); } }
package com.yixin.kepler.core.rabbitmq; import java.util.Map; /** * 消息通知解析类 */ public abstract class MsgResolver<T> { /** * 解析器 * @param msg 接收到的kafka消息 * @return * * key value 对应的消息 */ public abstract Map<String, String> resolve(final T msg); }
package com.lin.paper.service; import java.util.List; import com.lin.paper.pojo.PProgress; /** * 进度的业务逻辑接口 * @ * @date 2018年3月12日下午3:34:33 * @version 1.0 */ public interface ProgressService { /** * 添加进度信息 * @param userid * @param string * @return */ String addProgress(String name, String userid); /** * 根据ID查询当前进度 * @param progressid * @return */ PProgress getProgressById(String progressid); /** * 查询学生的所有进度 * @param userid * @return */ List<PProgress> getProgressByStu(String userid); /** * 更新指定进度的指定状态 * @param progressid * @param i */ void updateProgressStateById(String progressid, int i); /** * 更新进度数据 * @param progress */ void updateProgress(PProgress progress); /** * 查询教师的所有需要审核的进度 * @param userid * @return */ List<PProgress> getProgressByTeach(String userid); /** * 创建新的进度 * @param progressid * @return */ PProgress startNewProgress(String progressid); }
package com.hawk.application.web; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.DataAccessException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; @Controller @PropertySource("classpath:/spring/data-access.properties") public class SdkDownloadController { private static final Logger LOGGER = LoggerFactory .getLogger(SdkDownloadController.class); @Autowired Environment env; private static String SYS_SDK_PATH; @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "File not found") @ExceptionHandler(SdkNotFoundException.class) public void fileNotFound(Exception e) { LOGGER.warn("Request raised a FileNotFoundException: {}", e.getMessage()); } @RequestMapping(value = "/download/{id}", method = RequestMethod.GET) public void getFile(@PathVariable("id") Long id, HttpServletResponse response) throws DataAccessException, SdkNotFoundException { FileInputStream fileInputStream = null; try { SYS_SDK_PATH = env.getProperty("sdk.download.location"); LOGGER.debug("!!!!!the SYS_SDK_PATH is " + SYS_SDK_PATH); File file = new File(SYS_SDK_PATH + File.separator + "test_download_file.zip"); fileInputStream = new FileInputStream(file); response.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); response.setContentType("application/octet-stream"); IOUtils.copy(fileInputStream, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { LOGGER.error("Error writing file content to output stream"); throw new SdkNotFoundException( "IOError writing file to output stream"); } finally { IOUtils.closeQuietly(fileInputStream); } } }
package com.qunchuang.carmall.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * 小程序配置类 * * @author Curtain * @date 2018/11/9 8:37 */ @Component @Data @ConfigurationProperties("wechatmini") public class WeChatMiniResources { private String appId; private String secret; private String authUrl; }
package org.seed419.founddiamonds.util; import org.bukkit.ChatColor; /* Copyright 2011-2012 Blake Bartenbach This file is part of FoundDiamonds. FoundDiamonds is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FoundDiamonds is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FoundDiamonds. If not, see <http://www.gnu.org/licenses/>. */ public class Prefix { private final static String chatPrefix = "[FD]"; private final static String menuPrefix = ChatColor.BOLD + "[FD] " + ChatColor.RESET; private final static String adminPrefix = ChatColor.RED + "[FD]"; private final static String debugPrefix = "[FD Debug] "; private final static String loggingPrefix = "[FoundDiamonds] "; public static String getChatPrefix() { return chatPrefix; } public static String getAdminPrefix() { return adminPrefix; } public static String getDebugPrefix() { return debugPrefix; } public static String getLoggingPrefix() { return loggingPrefix; } public static String getMenuPrefix() { return menuPrefix; } }