text
stringlengths
10
2.72M
/* * Copyright (c) 2008-2019 Haulmont. * * 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.haulmont.reports.libintegration; import com.haulmont.chile.core.datatypes.Datatype; import com.haulmont.chile.core.datatypes.Datatypes; import com.haulmont.chile.core.model.Instance; import com.haulmont.cuba.core.global.Messages; import com.haulmont.cuba.core.global.UserSessionSource; import com.haulmont.yarg.formatters.impl.DefaultFormatProvider; import javax.inject.Inject; public class CubaFieldFormatProvider implements DefaultFormatProvider { @Inject protected UserSessionSource userSessionSource; @Inject protected Messages messages; @Override public String format(Object o) { if (o != null) { Datatype datatype = Datatypes.get(o.getClass()); if (datatype != null) { if (userSessionSource.checkCurrentUserSession()) { return datatype.format(o, userSessionSource.getLocale()); } else { return datatype.format(o); } } else if (o instanceof Enum) { return messages.getMessage((Enum) o); } else if (o instanceof Instance) { return ((Instance) o).getInstanceName(); } else { return String.valueOf(o); } } else { return null; } } }
package yi.letlangproj.exp; import yi.letlangproj.Environment; import yi.letlangproj.Expression; public class DiffExpression implements Expression { private final Expression e0; private final Expression e1; public DiffExpression(Expression e0, Expression e1) { this.e0 = e0; this.e1 = e1; } @Override public int evaluate(Environment environment) { return e0.evaluate(environment) - e1.evaluate(environment); } }
package com.wonjin.computer.hw4projectwonjin.hw3ManagerWonjin; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import com.wonjin.computer.hw4projectwonjin.R; import com.wonjin.computer.hw4projectwonjin.hw1LoginWonjin.LoginWonjinActivity; // 여러 액티비티에서 공통으로 사용되는 로직을 통합한 상위 액티비티 클래스 public abstract class CommonActivity extends AppCompatActivity { // DB 루트 경로 protected String _dbRootPath; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 이전 액티비티(로그인)로부터 전달받은 정보를 복원 __retrieveValues(); } private void __retrieveValues() { // 로그인 액티비티로부터 계정 정보를 전달받음. Bundle receivedData = getIntent().getExtras(); _dbRootPath = receivedData.getString("db_root_path"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_manager_wonjin, menu); int currentItemId = 0; switch (_getActivityType()) { case GROUP: currentItemId = R.id.MENU_MANAGER_managingGroup; break; case USER: currentItemId = R.id.MENU_MANAGER_managingUser; break; case SETTINGS: currentItemId = R.id.MENU_MANAGER_managingSettings; break; } // 현태 선택한 메뉴 정보에 따라 해당 액션을 disable 시킴 menu.findItem(currentItemId).setEnabled(false); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent = null; switch (item.getItemId()) { case R.id.MENU_MANAGER_managingGroup: intent = new Intent(this, ManagingGroupActivity.class); intent.putExtra("db_root_path", _dbRootPath); break; case R.id.MENU_MANAGER_managingUser: intent = new Intent(this, ManagingUserActivity.class); intent.putExtra("db_root_path", _dbRootPath); break; case R.id.MENU_MANAGER_managingSettings: intent = new Intent(this, ManagingSettingsActivity.class); intent.putExtra("db_root_path", _dbRootPath); break; case R.id.MENU_MANAGER_logout: intent = new Intent(this, LoginWonjinActivity.class); break; } // 선택한 메뉴 아이템에 따라 액티비티를 새로 띄운다. startActivity(intent); // 액티비티 변경 뒤 이전 액티비티 종료 finish(); return super.onOptionsItemSelected(item); } // 이 클래스를 상속한 액티비티는 자신의 액티비티 타입을 알려줄 수 있어야 함 protected abstract ActivityType _getActivityType(); }
/* * Dado um vetor de números reais e um número real, fazer um programa que * multiplique os elementos de posição ímpar do vetor pelo número real dado e * imprima o resultado. */ package Lista4; import java.util.Scanner; public class Exercicio10 { static Scanner input = new Scanner (System.in); static void multiplicaImpar(double vetor[], double n){ double resultado,resto; for(int i=0;i<vetor.length;i++){ resto=i%2; if(resto!=0){ resultado=vetor[i]*n; System.out.println("posição "+i+" = "+resultado); } } } public static void main(String[] args) { System.out.print("tamanho vetor: "); int tamanho=input.nextInt(); double vetor[]=Exercicio2.vetor(tamanho); vetor=Exercicio2.populaVetor(vetor); System.out.print("Número que o vetor vai ser multiplicado: "); double n=Exercicio2.entrada(); multiplicaImpar(vetor, n); } }
package org.spring.chat.bot.config; import org.spring.chat.bot.util.ChatBotConstants; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Value("${relay.broker.host}") private String relayHost; @Value("${relay.broker.port}") private Integer relayPort; @Value("${relay.broker.username}") private String relayUsername; @Value("${relay.broker.passcode}") private String relayPasscode; @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint(ChatBotConstants.WEB_SOCKET_ENDPOINT_URL).withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.setApplicationDestinationPrefixes(ChatBotConstants.WEB_SOCKET_APP_PATH_PREFIX); //TODO: To enable simple inmemory message broker registry.enableSimpleBroker(ChatBotConstants.WEB_SOCKET_TOPIC_PATH_PREFIX); //TODO: Use this for enabling a Full featured broker like RabbitMQ/ActiveMQ //registry.enableStompBrokerRelay(ChatBotConstants.WEB_SOCKET_TOPIC_PATH_PREFIX) // .setRelayHost(relayHost) // .setRelayPort(relayPort) // .setClientLogin(relayUsername) // .setClientPasscode(relayPasscode); } }
package com.jit.lembda03; @FunctionalInterface public interface Interf { public int getLength(String s); }
package domain; import java.util.Collection; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Entity; import javax.persistence.OneToMany; import javax.validation.Valid; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.SafeHtml; import org.hibernate.validator.constraints.SafeHtml.WhiteListType; @Entity @Access(AccessType.PROPERTY) public class Sponsor extends Actor { // Attributes ------------------------------------------------------------- private String middleName; private String surname; @SafeHtml(whitelistType = WhiteListType.NONE) public String getMiddleName() { return this.middleName; } public void setMiddleName(final String middleName) { this.middleName = middleName; } @NotBlank @SafeHtml(whitelistType = WhiteListType.NONE) public String getSurname() { return this.surname; } public void setSurname(final String surname) { this.surname = surname; } // Relationships ---------------------------------------------------------- private Collection<Sponsorship> sponsorships; @Valid @OneToMany(mappedBy = "sponsor") public Collection<Sponsorship> getSponsorships() { return this.sponsorships; } public void setSponsorships(final Collection<Sponsorship> sponsorships) { this.sponsorships = sponsorships; } }
package controller.drawCOR.copy; import view.interfaces.DrawingAreaInt; /** * L'expert parser de cercle. * @author baptiste * */ public class ExpertParserCercle extends ExpertParser { @Override public boolean draw1(String toParse, DrawingAreaInt toDraw) { String type = "cercle:"; if(toParse.startsWith(type)){ String content[] = toParse.substring(type.length()).split(","); if(content.length == 4){ String couleur = content[0].trim(); int x1 = (int) Double.parseDouble(content[1].trim()); int y1 = (int) Double.parseDouble(content[2].trim()); int radius = (int) Double.parseDouble(content[3].trim()); toDraw.drawEllipse(couleur, x1, y1, radius); return true; } } return false; } }
package com.gsccs.sme.api.domain.base; import java.util.Date; public class Video extends Domain { private static final long serialVersionUID = 4878121741748856161L; /** * 视频关联记录创建时间(格式:yyyy-MM-dd HH:mm:ss) */ private Date created; /** * 视频关联记录的id,和商品相对应 */ private Long id; /** * 视频记录关联的商品的数字id(注意:iid近期即将废弃,请用num_iid参数) */ private String iid; /** * 视频关联记录修改时间(格式:yyyy-MM-dd HH:mm:ss) */ private Date modified; /** * 视频记录所关联的商品的数字id */ private Long numIid; /** * video的url连接地址。 */ private String url; /** * video的id */ private Long videoId; }
package chapter14; import java.util.InputMismatchException; import java.util.Scanner; public class CompareStringPortion { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a word to compare"); String temp = scan.nextLine(); System.out.println("Enter 2nd word to compare"); String temp2 = scan.nextLine(); boolean tempCompare = temp.toLowerCase().regionMatches(1, temp2.toLowerCase(), 0, 4); if(tempCompare) { System.out.printf("%s is eqaul to from index 1 %s%n", temp, temp2); }else { System.out.printf("%s is not eqaul to from index 1 %s%n", temp, temp2); } int count = 1; while(true) { try { System.out.println("Enter a word to compare"); temp = scan.nextLine(); System.out.println("Enter 2nd word to compare"); temp2 = scan.nextLine(); tempCompare = temp.regionMatches(true, 1, temp2, 1, 4); }catch(InputMismatchException e) { System.out.println(e.getMessage()); System.out.println(e.getCause()); } if(tempCompare) { System.out.printf("%s is eqaul to from index 1 %s%n", temp, temp2); }else { System.out.printf("%s is not eqaul to from index 1 %s%n", temp, temp2); } count++; if(count == 5) break; } scan.close(); } }
package com.mybatis.day03; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import oracle.net.aso.f; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import com.mybatis.bean.ConditionUser; import com.mybatis.bean.User; import com.mybatis.util.MybatisUtils; public class MybatisTest { /** * 一级缓存 * 默认开启 * 是session级的缓存 * @throws IOException */ @Test public void t01() throws IOException{ SqlSessionFactory factory = MybatisUtils.getFactory(); SqlSession session = factory.openSession(); String statement = "com.mybatis.day03.userMapper.getUser"; User user = session.selectOne(statement,1); System.out.println(user); System.out.println("------------"); session.clearCache(); //清除缓存 User user2 = session.selectOne(statement,1); System.out.println(user2); session.close(); } /** * 一级缓存 * 执行增删改操作 * @throws IOException */ @Test public void t02() throws IOException{ SqlSessionFactory factory = MybatisUtils.getFactory(); SqlSession session = factory.openSession(); String statement = "com.mybatis.day03.userMapper.getUser"; User user = session.selectOne(statement,1); System.out.println(user); System.out.println("------------"); //执行增删改操作 int i = session.update("com.mybatis.day03.userMapper.updateUser",new User(1, "a", "ea", "2")); session.commit(); System.out.println(i); user = session.selectOne(statement,1); System.out.println(user); session.close(); } /** * 一级缓存 * 不是同一个session对象 * @throws IOException */ @Test public void t03() throws IOException{ SqlSessionFactory factory = MybatisUtils.getFactory(); SqlSession session = factory.openSession(); String statement = "com.mybatis.day03.userMapper.getUser"; User user = session.selectOne(statement,1); System.out.println(user); System.out.println("------------"); session.close();//关闭 session = factory.openSession(); //在开启 //不是同一个缓存 user = session.selectOne(statement,1); System.out.println(user); session.close(); } }
/** * */ /** * @author milan * */ module interview { }
package com.wwh.mapper; import com.wwh.entity.UpFile; import com.wwh.entity.User; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Map; @Repository public interface UserMapper { //----查找列表 public List<User> findList(); //---------新增 public void addUser(User user); //-----用户登录 //---登录或者少参数可以使用注解来写,多的参数可以使用map或者实体类 public User userLogin(@Param("userid") String userid, @Param("pwd") String pwd); //---------带条件查找用户列表 public List<User> findUser(Map<String,Object> map); //-------------验证注册用户是否存在 public User regTest(@Param("userid") String userid); //-------------------注册用户 public int addUser(UpFile upFile); //-----------多表查询 public UpFile check(Integer id); //-------一对多 public List<UpFile> findc(Integer id); }
package com.san.sexInLanguage; import org.springframework.data.repository.CrudRepository; public interface SexInLanguageRepository extends CrudRepository<SexInLanguage, Integer> { }
package br.com.ocjp7.design; public class TestaAcessoProtegido { public static void main(String[] args) { DesignClass dc = new DesignClass(); //dc.b = 10; //dc.c = 20; } }
package com.davivienda.sara.procesos.edccargue.servicio; import com.davivienda.sara.base.BaseServicio; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import com.davivienda.sara.constantes.CodigoError; import com.davivienda.sara.constantes.EstadoProceso; import com.davivienda.sara.entitys.Cajero; import com.davivienda.sara.tablas.cajero.servicio.CajeroServicio; import java.io.FileNotFoundException; import java.util.Date; import javax.persistence.EntityManager; import javax.annotation.Resource; import javax.transaction.UserTransaction; import com.davivienda.sara.entitys.EdcCargue; import com.davivienda.sara.tablas.edccargue.servicio.EdcCargueServicio; /** * AdministradorProcesosEdcCargueServicio - 22/08/2008 * Descripción : * Versión : 1.0 * * @author jjvargas * Davivienda 2008 */ public class AdministradorProcesosEdcCargueServicio extends BaseServicio { private CajeroServicio cajeroServicio; private EdcCargueServicio edcCargueServicio; @Resource private UserTransaction utx; public AdministradorProcesosEdcCargueServicio(EntityManager em) { super(em); cajeroServicio = new CajeroServicio(em); edcCargueServicio=new EdcCargueServicio(em); } /** * Carga los datos de un archivo en EdcCargue * @param codigoCajero * @param fecha * @param nombreArchivo * @param tamano * @param ciclo * @return * @throws java.io.FileNotFoundException * @throws com.davivienda.sara.base.exception.EntityServicioExcepcion * @throws java.lang.IllegalArgumentException */ public Integer guardarProcesoTransmisionTiras(String nombreArchivo,Integer tamano,Integer ciclo,Date fecha,Integer codigoCajero ,Integer estado,boolean actualiza) throws FileNotFoundException, EntityServicioExcepcion, IllegalArgumentException { Integer codigoErrorProceso=0; Cajero cajero = cajeroServicio.buscar(codigoCajero); Integer regGuardados=0; EdcCargue regProcesoTransmisionTira=new EdcCargue(); if (cajero == null) { codigoErrorProceso=CodigoError.CAJERO_NO_EXISTE.getCodigo(); } //OJO DESCOMENTAREAR 27 regProcesoTransmisionTira.setCodigoCajero(codigoCajero); regProcesoTransmisionTira.setCiclo(ciclo); regProcesoTransmisionTira.setError(codigoErrorProceso); //regProcesoTransmisionTira.setEstadoproceso(EstadoProceso.INICIADO.getEstado()); regProcesoTransmisionTira.setEstadoproceso(estado); regProcesoTransmisionTira.setFechaEdcCargue(fecha); regProcesoTransmisionTira.setNombrearchivo(nombreArchivo); regProcesoTransmisionTira.setTamano(tamano); regProcesoTransmisionTira.setUltimaSecuencia(0); // regProcesoTransmisionTira.setIdEdcCargue(7); regProcesoTransmisionTira.setVersion(0); try { //se revisa que ese registro no exista ya EdcCargue edcCargue=edcCargueServicio.buscarPorArchivo(nombreArchivo) ; if (edcCargue == null ) { edcCargueServicio.adicionar(regProcesoTransmisionTira); regGuardados=1; } else { //revisar cual es el estado deberia ser 15 if(actualiza) { edcCargue.setEstadoproceso(estado); edcCargueServicio.actualizar(edcCargue); } } } catch (Exception ex) { java.util.logging.Logger.getLogger("globalApp").info("Error cargando en EDCCARGUE registro datos archivos :" + nombreArchivo + " descripcion Error : " + ex.getMessage()); } return regGuardados; } }
package kodiaproject.demo.service; import kodiaproject.demo.model.UniversityDetailModel; import kodiaproject.demo.model.UniversityRequestModel; import kodiaproject.demo.repository.UniversityRepository; import lombok.Data; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service @Data public class UniversityServiceIMP implements UniversityService { private final UniversityRepository universityRepository; @Override public List<UniversityRequestModel> getUniversities() { List<UniversityRequestModel> universities = universityRepository.findAllBy(); return universities; } @Override public UniversityDetailModel findUniversity(int id) { Optional<UniversityDetailModel> byId = universityRepository.findByApiId(id); if (byId.isPresent()) { return byId.get(); } else throw new RuntimeException(); } }
package com.sinodynamic.hkgta.entity.crm; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Version; import org.apache.commons.lang.math.NumberUtils; /** * The persistent class for the corporate_addition_contact database table. * */ @Entity @Table(name = "corporate_addition_contact") @NamedQuery(name = "CorporateAdditionContact.findAll", query = "SELECT c FROM CorporateAdditionContact c") public class CorporateAdditionContact implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "contact_id") private Long contactId; @Column(name = "contact_email") private String contactEmail; @Column(name = "contact_person_firstname") private String contactPersonFirstname; @Column(name = "contact_person_lastname") private String contactPersonLastname; @Column(name = "contact_phone") private String contactPhone; @Column(name = "contact_phone_mobile") private String contactPhoneMobile; @Column(name = "contact_type") private String contactType; @Column(name = "corporate_id") private Long corporateId; @Column(name = "create_by") private String createBy; @Temporal(TemporalType.TIMESTAMP) @Column(name = "create_date") private Date createDate; @Column(name = "district") private String district; @Column(name = "postal_address1") private String postalAddress1; @Column(name = "postal_address2") private String postalAddress2; @Column(name = "update_by") private String updateBy; @Temporal(TemporalType.TIMESTAMP) @Column(name = "update_date") private Date updateDate; @Version @Column(name="ver_no", nullable = false) private Long version; public CorporateAdditionContact() { } public Long getContactId() { return this.contactId; } public void setContactId(Object contactId) { this.contactId = (contactId != null ? NumberUtils.toLong(contactId.toString()) : null); } public String getContactEmail() { return this.contactEmail; } public void setContactEmail(String contactEmail) { this.contactEmail = contactEmail; } public String getContactPersonFirstname() { return this.contactPersonFirstname; } public void setContactPersonFirstname(String contactPersonFirstname) { this.contactPersonFirstname = contactPersonFirstname; } public String getContactPersonLastname() { return this.contactPersonLastname; } public void setContactPersonLastname(String contactPersonLastname) { this.contactPersonLastname = contactPersonLastname; } public String getContactPhone() { return this.contactPhone; } public void setContactPhone(String contactPhone) { this.contactPhone = contactPhone; } public String getContactPhoneMobile() { return this.contactPhoneMobile; } public void setContactPhoneMobile(String contactPhoneMobile) { this.contactPhoneMobile = contactPhoneMobile; } public String getContactType() { return this.contactType; } public void setContactType(String contactType) { this.contactType = contactType; } public Long getCorporateId() { return this.corporateId; } public void setCorporateId(Object corporateId) { this.corporateId = (corporateId != null ? NumberUtils.toLong(corporateId.toString()) : null); } public String getCreateBy() { return this.createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateDate() { return this.createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getDistrict() { return this.district; } public void setDistrict(String district) { this.district = district; } public String getPostalAddress1() { return this.postalAddress1; } public void setPostalAddress1(String postalAddress1) { this.postalAddress1 = postalAddress1; } public String getPostalAddress2() { return this.postalAddress2; } public void setPostalAddress2(String postalAddress2) { this.postalAddress2 = postalAddress2; } public String getUpdateBy() { return this.updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateDate() { return this.updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public Long getVersion() { return version; } public void setVersion(Object version) { this.version = (version != null ? NumberUtils.toLong(version.toString()) : null); } public Boolean equals(CorporateProfile corporateProfile){ if(corporateProfile==null){ return false; } if (!compare(this.contactPersonFirstname, corporateProfile.getContactPersonFirstname())) { return false; } if (!compare(this.contactPersonLastname, corporateProfile.getContactPersonLastname())) { return false; } if (!compare(this.contactPhone, corporateProfile.getContactPhone())) { return false; } if (!compare(this.contactPhoneMobile, corporateProfile.getContactPhoneMobile())) { return false; } if (!compare(this.contactEmail, corporateProfile.getContactEmail())) { return false; } if (!compare(this.postalAddress1, corporateProfile.getAddress1())) { return false; } if (!compare(this.postalAddress2, corporateProfile.getAddress2())) { return false; } if (!compare(this.district, corporateProfile.getDistrict())) { return false; } return true; } public boolean compare(Object source,Object target){ if (null != source) { if(!source.equals(target)){ return false; } }else { if (null != target){ return false; } } return true; } }
package stockhelper; import java.net.*; import java.util.*; import java.io.*; public class ProxyDetector { public static void detectProxy(String args[]) throws Exception{ System.setProperty("java.net.useSystemProxies", "true"); System.out.println("detecting proxies"); List<Proxy> pl = ProxySelector.getDefault().select(new URI("http://www.google.com")); for(Proxy p : pl){ System.out.println(p); InetSocketAddress addr = (InetSocketAddress)p.address(); if(addr == null) System.out.println("no proxy"); else System.out.println("proxy hostname: "+addr.getHostName()+" proxy port: "+addr.getPort()); } } public static void connectURL() throws Exception{ URL url = new URL("http://www.google.com"); URLConnection urlConnection = url.openConnection(); InputStream is = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line= null; while((line = reader.readLine())!= null){ System.out.println(line); } } public static void main(String args[]){ try{ connectURL(); }catch(Exception e){ e.printStackTrace(); } } }
package warmachine.mcqueen.prueba.model; import java.util.ArrayList; public class VehiculoModel { private int idVehiculo; private String patente; private int valor; private int ano; private String color; private TipoVehiculoModel tipoVehiculo; private VersionModel version; public static ArrayList<VehiculoModel> vehiculos = new ArrayList<>(); public int getIdVehiculo() { return idVehiculo; } public void setIdVehiculo(int idVehiculo) { this.idVehiculo = idVehiculo; } public String getPatente() { return patente; } public void setPatente(String patente) { this.patente = patente; } public int getValor() { return valor; } public void setValor(int valor) { this.valor = valor; } public int getAno() { return ano; } public void setAno(int ano) { this.ano = ano; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public TipoVehiculoModel getTipoVehiculo() { return tipoVehiculo; } public void setTipoVehiculo(TipoVehiculoModel tipoVehiculo) { this.tipoVehiculo = tipoVehiculo; } public VersionModel getVersion() { return version; } public void setVersion(VersionModel version) { this.version = version; } public VehiculoModel() { } public VehiculoModel(String patente, int valor, int ano, String color, TipoVehiculoModel tipoVehiculo, VersionModel version) { this.patente = patente; this.valor = valor; this.ano = ano; this.color = color; this.tipoVehiculo = tipoVehiculo; this.version = version; } private VehiculoModel(int idVehiculo, String patente, int valor, int ano, String color, TipoVehiculoModel tipoVehiculo, VersionModel version) { this.idVehiculo = idVehiculo; this.patente = patente; this.valor = valor; this.ano = ano; this.color = color; this.tipoVehiculo = tipoVehiculo; this.version = version; } public boolean nuevoVehiculo(VehiculoModel nuevoVehiculo){ int id = 0; if (!vehiculos.isEmpty()) { for (VehiculoModel vehiculo : vehiculos) { if (vehiculo.getIdVehiculo()> id) { id = vehiculo.getIdVehiculo(); } } } id++; vehiculos.add(new VehiculoModel(id, nuevoVehiculo.getPatente(), nuevoVehiculo.getValor(), nuevoVehiculo.getAno(), nuevoVehiculo.getColor(), nuevoVehiculo.getTipoVehiculo(), nuevoVehiculo.getVersion())); return true; } public VehiculoModel buscaVehiculo(int idVehiculoBuscado){ VehiculoModel vehiculoEncontrado = null; if(!vehiculos.isEmpty()){ for (VehiculoModel vehiculo : vehiculos) { if (vehiculo.getIdVehiculo()== idVehiculoBuscado) { vehiculoEncontrado = vehiculo; } } } return vehiculoEncontrado; } public VehiculoModel editarVehiculo(int idVehiculo, VehiculoModel vehiculoEditar){ VehiculoModel vehiculoEditado = null; if(!vehiculos.isEmpty()){ for (VehiculoModel vehiculo : vehiculos) { if (vehiculo.getIdVehiculo()== idVehiculo) { vehiculo.setPatente(vehiculoEditar.getColor()); vehiculo.setValor(vehiculoEditar.getValor()); vehiculo.setAno(vehiculoEditar.getAno()); vehiculo.setColor(vehiculoEditar.getColor()); vehiculo.setTipoVehiculo(vehiculoEditar.getTipoVehiculo()); vehiculo.setVersion(vehiculoEditar.getVersion()); vehiculoEditado = vehiculo; } } } return vehiculoEditado; } public boolean eliminarVehiculo(int id){ VehiculoModel vehiculoEliminado = null; if(!vehiculos.isEmpty()){ for (VehiculoModel vehiculo : vehiculos) { if (vehiculo.getIdVehiculo()== id) { vehiculoEliminado = vehiculo; } } } vehiculos.remove(vehiculoEliminado); return true; } }
// Data Processing Instruction public class InstructionDP extends Instruction{ private String rd = null; private String rs = null; private String rt = null; private int imm = 0; public InstructionDP(String command, String rd, String rs, String rt) { super(command); this.rs = rs; this.rt = rt; this.rd = rd; } public InstructionDP(String command, String rt, String rs, int imm) { super(command); this.rs = rs; this.rt = rt; this.imm = imm; } public void execute(RegFile regFile, DataMemory dataMem){ switch(command){ case "add": case "addu": regFile.writeRegValue(rd, regFile.getRegValue(rs) + regFile.getRegValue(rt)); break; case "addi": case "addiu": regFile.writeRegValue(rt, regFile.getRegValue(rs) + imm); break; case "and": regFile.writeRegValue(rd, regFile.getRegValue(rs) & regFile.getRegValue(rt)); break; case "andi": regFile.writeRegValue(rt, regFile.getRegValue(rs) & imm); break; case "nor": regFile.writeRegValue(rd, ~(regFile.getRegValue(rs) | regFile.getRegValue(rt))); break; case "or": regFile.writeRegValue(rd, regFile.getRegValue(rs) | regFile.getRegValue(rt)); break; case "ori": regFile.writeRegValue(rt, regFile.getRegValue(rs) | imm); break; case "slt": case "sltu": regFile.writeRegValue(rd, (regFile.getRegValue(rs) < regFile.getRegValue(rt)) ? 1 : 0); break; case "slti": case "sltiu": regFile.writeRegValue(rt, (regFile.getRegValue(rs) < imm) ? 1 : 0); break; case "sll": regFile.writeRegValue(rt, regFile.getRegValue(rs) << imm); break; case "srl": regFile.writeRegValue(rt, regFile.getRegValue(rs) >> imm); break; case "sub": regFile.writeRegValue(rd, regFile.getRegValue(rs) - regFile.getRegValue(rt)); break; case "subu": regFile.writeRegValue(rd, regFile.getRegValue(rs) - imm); break; default: break; } } }
package org.xbill.DNS; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.io.IOException; import org.junit.jupiter.api.Test; class EDNS0MessageTests { /* dig +nocookie foo.dns.addere.ch */ private static final byte[] EDNS0_EMPTY = { 0x7d, 0x59, 0x01, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x64, 0x6e, 0x73, 0x06, 0x61, 0x64, 0x64, 0x65, 0x72, 0x65, 0x02, 0x63, 0x68, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x29, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; /* dig foo.dns.addere.ch */ private static final byte[] EDNS0_COOKIE = { (byte) 0x95, (byte) 0xa6, 0x01, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x64, 0x6e, 0x73, 0x06, 0x61, 0x64, 0x64, 0x65, 0x72, 0x65, 0x02, 0x63, 0x68, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x29, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x0a, 0x00, 0x08, 0x28, 0x75, (byte) 0x83, 0x7f, 0x00, 0x32, (byte) 0xe5, 0x6f }; /* dig +keepalive foo.dns.addere.ch */ private static final byte[] EDNS0_COOKIE_KEEPALIVE = { (byte) 0x8e, (byte) 0xdd, 0x01, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x64, 0x6e, 0x73, 0x06, 0x61, 0x64, 0x64, 0x65, 0x72, 0x65, 0x02, 0x63, 0x68, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x29, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0a, 0x00, 0x08, (byte) 0xeb, (byte) 0xed, (byte) 0xfc, 0x4c, 0x1c, 0x45, 0x20, 0x01, 0x00, 0x0b, 0x00, 0x00 }; /* dig +keepalive +subnet=1.2.3.4 foo.dns.addere.ch */ private static final byte[] EDNS0_SUBNET_COOKIE_KEEPALIVE = { 0x42, 0x3a, 0x01, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x64, 0x6e, 0x73, 0x06, 0x61, 0x64, 0x64, 0x65, 0x72, 0x65, 0x02, 0x63, 0x68, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x29, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x08, 0x00, 0x08, 0x00, 0x01, 0x20, 0x00, 0x01, 0x02, 0x03, 0x04, 0x00, 0x0a, 0x00, 0x08, 0x7c, 0x2e, 0x0d, 0x0e, (byte) 0x95, (byte) 0xf3, 0x4d, (byte) 0xff, 0x00, 0x0b, 0x00, 0x00 }; @Test void testParseEdns0Empty() throws IOException { Message msg = new Message(EDNS0_EMPTY); assertArrayEquals(EDNS0_EMPTY, msg.toWire()); } @Test void testParseEdns0Cookie() throws IOException { Message msg = new Message(EDNS0_COOKIE); assertArrayEquals(EDNS0_COOKIE, msg.toWire()); } @Test void testParseEdns0CookieKeepalive() throws IOException { Message msg = new Message(EDNS0_COOKIE_KEEPALIVE); assertArrayEquals(EDNS0_COOKIE_KEEPALIVE, msg.toWire()); } @Test void testParseEdns0SubnetCookieKeepalive() throws IOException { Message msg = new Message(EDNS0_SUBNET_COOKIE_KEEPALIVE); assertArrayEquals(EDNS0_SUBNET_COOKIE_KEEPALIVE, msg.toWire()); } }
package week05.d04; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class ProductTest { @Test public void testConstructorThrows() throws IllegalArgumentException { Exception ex = assertThrows(IllegalArgumentException.class, () -> new Product(-1, null)); assertEquals("Price must be positive.", ex.getMessage()); ex = assertThrows(IllegalArgumentException.class, () -> new Product(1, null)); assertEquals("Currency can't be null.", ex.getMessage()); } @Test public void testConvertPrice() { assertEquals(1, new Product(1, Currency.USD).convertPrice(Currency.USD)); assertEquals(300, new Product(1, Currency.USD).convertPrice(Currency.HUF)); assertEquals(300, new Product(300, Currency.HUF).convertPrice(Currency.HUF)); assertEquals(1, new Product(300, Currency.HUF).convertPrice(Currency.USD)); assertEquals(.5, new Product(150, Currency.HUF).convertPrice(Currency.USD)); } }
package com.rednovo.ace.common; import android.annotation.SuppressLint; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; /** * 键生成器 * * @author YongChao.Yang */ public class KeyGenerator { /** * 格式化工具 */ private static DecimalFormat decimalFormat = new DecimalFormat("000000"); /** * 随机数 */ private static Random radm = new Random(); /** * 获取六位随机数,且不为0开头的数字 * * @return * @author sg.z * @since 2014年8月18日下午10:33:56 */ public static String getSixRandom() { return "" + (int) ((Math.random() * 9 + 1) * 100000); } public static String getRandom() { return decimalFormat.format(radm.nextInt(999999)); } /** * 生成美播官方5位用户号码 * * @return * @author sg.z * @since 2014年9月16日上午10:54:22 */ public static String getMeiboNum() { Random random = new Random(); int num = random.nextInt(10000) + 90000; return num + ""; } // /** // * 生成一个唯一的数据库主键,带有计数器 // * // * @return // */ // public static String createTransReferenceId(String transActionType) { // StringBuffer pk = new StringBuffer(transActionType); // pk.append("-"); // pk.append(DateUtil.getNo(6)); // return pk.toString(); // } // /** // * 获取唯一主键值 // * // * @return // * @author YongChao.Yang/2012-9-20/2012 // */ // public static String createUniqueId() { // StringBuffer sb = new StringBuffer(DateUtil.getNo(6)); // sb.append(getRandom()); // return sb.toString(); // } public static String createUniqueId() { StringBuffer sb = new StringBuffer(); sb.append("ANDROID_"); sb.append(getCurrentTime()); sb.append(getSixRandom()); return sb.toString(); } @SuppressLint("SimpleDateFormat") private static String getCurrentTime() { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSS"); String fomatDate = format.format(date); return fomatDate; } }
package def; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class cvtColor { public static void main(String[] args) { // load the opencv library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // creating the image path variable String fpath = "C:\\Users\\Shirley\\eclipse-workspace\\HelloUI\\src\\profile.jpg"; // creating codecs Imgcodecs imgcodecs = new Imgcodecs(); Mat matrix = imgcodecs.imread(fpath); // create empty destination matrix Mat dst = new Mat(); // convert the image to grayscale and saving it to new matrix Imgproc improc = new Imgproc(); // cvtColor improc.cvtColor(matrix, dst, improc.COLOR_RGB2GRAY); // extracting data from the transformed image // creating a byte array from size of t byte[] data1 = new byte[dst.rows() * dst.cols() * (int)(dst.elemSize())]; dst.get(0,0,data1); // creating the buffere image BufferedImage img = new BufferedImage(dst.cols(), dst.rows(), BufferedImage.TYPE_BYTE_GRAY); // setting thedata elemets to the image img.getRaster().setDataElements(0, 0, dst.cols(), dst.rows(), data1); JFrame frame = new JFrame(); frame.getContentPane().add(new JLabel(new ImageIcon(img))); frame.pack(); frame.setVisible(true); } }
/* * TraceLogs.java * ********************************************************************** Copyright (c) 2013 - 2014 netty-apns ***********************************************************************/ package apns.netty.connpool; /** * The Class TraceLogs. * @author arung */ public class TraceLogs { }
package tw.org.iii.AbnerJava; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class JavaNetURLImage { public static void main(String[] args) { // TODO Auto-generated method stub try { //URL url = new URL("http://a.ecimg.tw/pic/v1/data/item/201609/D/R/A/G/6/S/DRAG6S-19007D0LW000_57d0c1eba36c7.jpg"); URL url = new URL("http://pdfmyurl.com/?url=http://www.gamer.com.tw"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.connect(); InputStream ins = conn.getInputStream(); //FileOutputStream fout = new FileOutputStream("dir1/Abner.jpg"); FileOutputStream fout = new FileOutputStream("dir1/Gamer.pdf"); byte []buf = new byte[4096]; int len; while ( (len = ins.read(buf)) != -1 ) { fout.write(buf,0,len); } fout.flush(); fout.close(); ins.close(); System.out.println("OK"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/** * */ package com.engine; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; //import java.util.List; // //import org.jsoup.Jsoup; //import org.jsoup.nodes.Document; //import org.jsoup.nodes.Element; import com.getRand.XRandomNounGetter; /** * @author jmaro * */ public class XDaysAdderTraditional implements IXDaysAdder { private int days = 0; // private final String random_noun_url = "http://www.desiquintans.com/noungenerator?count=1"; // private final String random_noun_url_multi = "http://www.desiquintans.com/noungenerator?count="; private final String[] orig12Items = {"partridge in a pear tree", "turtle doves", "french hens", "calling birds", "gold rings", "geese a-laying", "swans a-swimming", "maids a-milking", "ladies dancing", "lords a-leaping", "pipers piping", "drummers drumming" }; private ArrayList<String> itemText = new ArrayList<String>(Arrays.asList(orig12Items)); // public XDaysAdderTraditional() { // itemText = new ArrayList<String>(Arrays.asList(orig12Items)); // } /* (non-Javadoc) * @see com.engine.IXDaysAdder#getTotalItems(int) */ @Override public int getTotalItems(int days) { int result = days; this.days = days; if (days > 1) { result = 0; for (int i = 1; i <= days; i++) { result += i; } } return result; } @Override public void printItems(PrintStream ps) { String outputList = "No days were supplied."; String currentDay = null; if (days > 0) { if (days > 12) { addToItemList(days - 12); // add enough items after the 12 given } outputList = ""; // clear the output list for (int i = 0; i < days; i++) { int currDay = i + 1; currentDay = "Day: " + currDay + "\tItems: " + currDay + " " + itemText.get(i) + "\n"; outputList = outputList.concat(currentDay); } } ps.print(outputList); } private void addToItemList(int amountToAdd) { itemText.addAll(XRandomNounGetter.getRandomNouns(amountToAdd)); } // private List<String> getRandomNouns(int nounCount) { // List<String> result = new ArrayList<String>(); // int remaining = nounCount; // String url; // while (remaining / 10 > 0) { // url = random_noun_url_multi + "10"; // String[] nouns = randomNounGet(url); // for (int i = 0; i < 10; i++) { // String newItem = nouns[i].toLowerCase() + "s"; // result.add(newItem); // } // remaining -= 10; // } // url = random_noun_url_multi + remaining; // String[] nouns = randomNounGet(url); // for (int i = 0; i < remaining; i++) { // String newItem = nouns[i].toLowerCase() + "s"; // result.add(newItem); // } // return result; // } // //// protected String getRandomNoun() { //// String result = "Panther"; //// try { //// Document doc = Jsoup.connect(random_noun_url).get(); //// Element content = doc.getElementById("ContentContainer"); //// Elements greenBoxes = content.getElementsByClass("greenBox"); //// Element li = greenBoxes.get(0).getElementsByTag("ol"). //// get(0).getElementsByTag("li").get(0); //// result = li.text(); //// } catch (Exception e) { //// System.out.println("ERROR: Could not reach the random noun website: " + random_noun_url); //// System.out.println("Error message: " + e.getMessage()); //// } //// System.out.println("Result: " + result); //// return result; //// } // // private String[] randomNounGet(String url) { // String[] result = null; // try { // Document doc = Jsoup.connect(url).get(); // Element ol = doc.getElementById("ContentContainer").getElementsByClass("greenBox"). // get(0).getElementsByTag("ol").get(0); // result = ol.text().trim().split(" "); // } catch (Exception e) { // System.out.println("ERROR: Could not reach the random noun website: " + random_noun_url); // System.out.println("Error message: " + e.getMessage()); // } // return result; // } }
package com.impetus.dao; import java.io.IOException; import java.util.List; import com.impetus.model.JobData; import com.impetus.model.JobDetail; import com.impetus.model.JobInfo; /** * DAO class for performing desired DB operations * @author punit * @since 03-Aug-2012 */ public interface JobServiceDAO { /** * Get All Jobs Details. * * @return List of JobInfo * @throws IOException Signals that an I/O exception has occurred. */ List<JobInfo> getJobs() throws IOException; /** * Get Job Details * @param jobId * @return JobDetail * @throws IOException */ JobDetail getJob(String jobId) throws IOException; /** * Save. * * @param jobInfo the job info * @return the string * @throws IOException Signals that an I/O exception has occurred. */ String save(JobInfo jobInfo) throws IOException; /** * Update. * * @param jobInfo the job info * @return the string * @throws IOException Signals that an I/O exception has occurred. */ String update(JobInfo jobInfo) throws IOException; void saveJobOutput(List<JobDetail> jobDetailList) throws Exception; List<JobDetail> getClusterList(String jobId) throws Exception; List<JobData> getDataForCluster(String jobId, String clusterId) throws Exception; }
package com.zantong.mobilecttx.weizhang.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.zantong.mobilecttx.R; import com.jcodecraeer.xrecyclerview.BaseAdapter; import com.jcodecraeer.xrecyclerview.BaseRecyclerViewHolder; import com.zantong.mobilecttx.weizhang.bean.ViolationInfo; import com.zantong.mobilecttx.utils.StringUtils; import butterknife.Bind; import butterknife.ButterKnife; /** * 缴费记录适配器 * @author Sandy * create at 16/6/7 下午2:38 */ public class PayHistoryAdapter extends BaseAdapter<ViolationInfo> { private Context mContext; @Override public void showData(BaseRecyclerViewHolder viewHolder, int position, ViolationInfo data) { ViewHolder holder = (ViewHolder)viewHolder; if (data != null){ StringBuilder sb = new StringBuilder(); try { sb.append(data.getViolationdate().substring(0,4)).append("-"). append(data.getViolationdate().substring(4, 6)).append("-"). append(data.getViolationdate().substring(6,8)); holder.mTm.setText(sb.toString()); }catch (Exception e){ } holder.mCarNum.setText(data.getCarnum()); holder.mAmount.setText("罚:"+ StringUtils.getPriceDoubleFormat(data.getViolationamt())); holder.mScore.setText("扣:"+data.getViolationcent()); } } @Override public View createView(ViewGroup viewGroup, int i) { mContext = viewGroup.getContext(); LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.mine_payhistory_item, viewGroup,false); return view; } @Override public BaseRecyclerViewHolder createViewHolder(View view,int itemType) { return new ViewHolder(view); } /** * 自定义的ViewHolder,持有每个Item的的所有界面元素 */ public static class ViewHolder extends BaseRecyclerViewHolder { @Bind(R.id.payhistory_item_tm) TextView mTm; @Bind(R.id.payhistory_item_carnum) TextView mCarNum;//车牌号 @Bind(R.id.payhistory_item_violationamt) TextView mAmount;//罚款金额 @Bind(R.id.payhistory_item_violationcent) TextView mScore;//扣分数 public ViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } }
/* * Copyright 2014 Soichiro Kashima * * 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. */ //https://code.google.com/p/android/issues/detail?id=28057 package com.application.ui.adapter; import java.util.ArrayList; import android.content.Context; import android.support.v7.widget.AppCompatTextView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.application.beans.Chat; import com.application.ui.view.CircleImageView; import com.application.ui.view.FlexibleDividerDecoration; import com.application.utils.ApplicationLoader; import com.application.utils.FileLog; import com.mobcast.R; import com.nostra13.universalimageloader.core.ImageLoader; public class ChatRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements FlexibleDividerDecoration.VisibilityProvider{ private static final String TAG = ChatRecyclerAdapter.class.getSimpleName(); private static final int VIEW_TYPE_HEADER = 0; private static final int VIEW_TYPE_TEXT = 1; private LayoutInflater mInflater; private ArrayList<Chat> mArrayListChat; private View mHeaderView; public OnItemClickListener mItemClickListener; private Context mContext; private ImageLoader mImageLoader; public ChatRecyclerAdapter(Context context, ArrayList<Chat> mArrayListChat, View headerView) { mInflater = LayoutInflater.from(context); mContext = context; this.mArrayListChat = mArrayListChat; mHeaderView = headerView; mImageLoader = ApplicationLoader.getUILImageLoader(); } @Override public int getItemCount() { if (mHeaderView == null) { return mArrayListChat.size(); } else { return mArrayListChat.size() + 1; } } public void addChatObjList(ArrayList<Chat> mListChat){ mArrayListChat= mListChat; notifyDataSetChanged(); } public void updateChatObj(int position, ArrayList<Chat> mListChat){ mArrayListChat = mListChat; notifyDataSetChanged(); } @Override public int getItemViewType(int position) { switch(position){ case 0: return VIEW_TYPE_HEADER; default: return getItemTypeFromObject(position-1); } } public int getItemTypeFromObject(int position){ return VIEW_TYPE_TEXT; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch(viewType){ case VIEW_TYPE_TEXT: return new ChatTextViewHolder(mInflater.inflate(R.layout.item_recycler_chat, parent, false)); default: return new HeaderViewHolder(mHeaderView); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { position-=1; if (viewHolder instanceof ChatTextViewHolder) { processChatTextViewHolder(viewHolder, position); } } public interface OnItemClickListener { public void onItemClick(View view, int position); } public void setOnItemClickListener( final OnItemClickListener mItemClickListener) { this.mItemClickListener = mItemClickListener; } static class HeaderViewHolder extends RecyclerView.ViewHolder { public HeaderViewHolder(View view) { super(view); } } public class ChatTextViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ FrameLayout mChatTextRootLayout; View mChatTextReadView; CircleImageView mChatTextIv; AppCompatTextView mChatTextTitleTv; AppCompatTextView mChatTextMessageTv; public ChatTextViewHolder(View view) { super(view); mChatTextRootLayout = (FrameLayout)view.findViewById(R.id.itemRecyclerChatRootLayout); mChatTextReadView = (View)view.findViewById(R.id.itemRecyclerChatReadView); mChatTextTitleTv = (AppCompatTextView) view.findViewById(R.id.itemRecyclerChatTitleTv); mChatTextMessageTv = (AppCompatTextView) view.findViewById(R.id.itemRecyclerChatMessageTv); mChatTextIv = (CircleImageView) view.findViewById(R.id.itemRecyclerChatIv); mChatTextReadView.setVisibility(View.INVISIBLE); mChatTextRootLayout.setOnClickListener(this); } public void onClick(View v) { if (mItemClickListener != null) { mItemClickListener.onItemClick(v, getLayoutPosition()); } } } /* (non-Javadoc) * @see com.application.ui.view.FlexibleDividerDecoration.VisibilityProvider#shouldHideDivider(int, android.support.v7.widget.RecyclerView) */ @Override public boolean shouldHideDivider(int position, RecyclerView parent) { // TODO Auto-generated method stub if (position == 0) { return true; } return false; } @SuppressWarnings("deprecation") private void processChatTextViewHolder(RecyclerView.ViewHolder viewHolder, int position){ try{ Chat mObj = mArrayListChat.get(position); ((ChatTextViewHolder)viewHolder).mChatTextTitleTv.setText(mObj.getmName()); mImageLoader.displayImage(mObj.getmUserDpLink(), ((ChatTextViewHolder)viewHolder).mChatTextIv); }catch(Exception e){ FileLog.e(TAG, e.toString()); } } }
package keyinfo; import java.util.ArrayList; import data.TicketsPerson; public class RespData_UserInfo { private int code =-1; private String result = null; private ArrayList<TicketsPerson> users = null; public RespData_UserInfo(int code,String result,ArrayList<TicketsPerson> users) { this.code=code; this.result=result; this.users=users; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public ArrayList<TicketsPerson> getUsers() { return users; } public void setUsers(ArrayList<TicketsPerson> users) { this.users = users; } }
package application; import java.io.IOException; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; public class Main extends Application { Stage stage; @Override public void start(Stage primaryStage) { try { stage = primaryStage; initialize(); } catch(Exception e) { e.printStackTrace(); } } public void initialize(){ FXMLLoader loader = new FXMLLoader(Main.class.getResource("View.fxml")); AnchorPane root; try { root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); stage.setScene(scene); stage.show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { launch(args); } }
package View; import java.sql.SQLException; import java.util.Date; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.VPos; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class UsersView extends GridPane implements ViewInterface{ Stage window; TableView<User> table; VBox vBox; GridPane bottomPane; private Button deletebtn; private Button updateRolebtn;; public UsersView() { super(); createFormPane(); setHeader(); table = createUsersTable(); vBox = new VBox(); vBox.getChildren().addAll(table); add(vBox, 0, 1,4,1); GridPane.setHalignment(vBox, HPos.CENTER); GridPane.setValignment(vBox, VPos.CENTER); GridPane.setMargin(vBox, new Insets(10, 0,0,0)); createBootomPane(); } /*public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { window = primaryStage; window.setTitle("User Page"); gridPane = createFormPane(); setHeader(); table = createUsersTable(); vBox = new VBox(); vBox.getChildren().addAll(table); gridPane.add(vBox, 0, 1,4,1); GridPane.setHalignment(vBox, HPos.CENTER); GridPane.setValignment(vBox, VPos.CENTER); GridPane.setMargin(vBox, new Insets(10, 0,0,0)); createBootomPane(); Scene scene = new Scene(gridPane,800,500); window.setScene(scene); window.show(); } */ private void setHeader() { // Add Header Label headerLabel = new Label("Users Managment Form"); headerLabel.setFont(ViewEffects.getHeadersFont()); headerLabel.setEffect(ViewEffects.getShadowEffect(5, 5)); add(headerLabel,0,0,2,1); GridPane.setHalignment(headerLabel, HPos.CENTER); GridPane.setValignment(headerLabel, VPos.TOP); GridPane.setMargin(headerLabel, new Insets(10, 0,0,0)); } private TableView<User> createUsersTable() { //User Name column TableColumn<User, String> usernameColumn = new TableColumn<>("User Name"); usernameColumn.setMinWidth(100); usernameColumn.setCellValueFactory(new PropertyValueFactory<>("UserName")); // Role Name column TableColumn<User, String> roleNameColumn = new TableColumn<>("Role Name"); roleNameColumn.setMinWidth(100); roleNameColumn.setCellValueFactory(new PropertyValueFactory<>("RoleName")); //Balance column TableColumn<User, Double> balanceColumn = new TableColumn<>("Balance"); balanceColumn.setMinWidth(100); balanceColumn.setCellValueFactory(new PropertyValueFactory<>("Balance")); //Start Date column TableColumn<User, Date> hireDateColumn = new TableColumn<>("Hire Date"); hireDateColumn.setMinWidth(100); hireDateColumn.setCellValueFactory(new PropertyValueFactory<>("HireDate")); //Seniority column TableColumn<User, Double> seniorityColumn = new TableColumn<>("Seniority"); seniorityColumn.setMinWidth(100); seniorityColumn.setCellValueFactory(new PropertyValueFactory<>("Seniority")); TableView<User> t = new TableView<User>(); t.setMaxHeight(300); t.setItems(getUsers()); t.getColumns().addAll(usernameColumn,roleNameColumn,balanceColumn, hireDateColumn,seniorityColumn); return t; } private void createFormPane() { // Position the pane at the center of the screen, both vertically and horizontally //gridPane.setAlignment(Pos.CENTER); // Set a padding of 20px on each side setPadding(new Insets(20, 20, 20, 20)); // Set the horizontal gap between columns setHgap(10); // Set the vertical gap between rows setVgap(10); // Add Column Constraints // columnOneConstraints will be applied to all the nodes placed in column one. ColumnConstraints columnOneConstraints = new ColumnConstraints(100, 100, Double.MAX_VALUE); columnOneConstraints.setHalignment(HPos.RIGHT); // columnTwoConstraints will be applied to all the nodes placed in column two. ColumnConstraints columnTwoConstrains = new ColumnConstraints(200,200, Double.MAX_VALUE); columnTwoConstrains.setHgrow(Priority.ALWAYS); getColumnConstraints().addAll(columnOneConstraints, columnTwoConstrains); } private void createBootomPane() { // Add delete Button deletebtn = new Button("Delete User"); deletebtn.setPrefHeight(40); deletebtn.setDefaultButton(true); deletebtn.setPrefWidth(100); //add(deletebtn, 0,2, 2, 1); GridPane.setHalignment(deletebtn, HPos.LEFT); GridPane.setMargin(deletebtn, new Insets(20, 0,20,0)); deletebtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { ControllerInstance.getInstance().getCont().deleteUser(table.getSelectionModel().getSelectedItem().getUserName()); refreshTable(); ErrorMessage.getInstance().showAlert(Alert.AlertType.CONFIRMATION, DataPane.getInstance().getScene().getWindow(), "Form Error!", "User have been deleted!"); } catch (Exception e) { ErrorMessage.getInstance().showAlert(Alert.AlertType.ERROR, DataPane.getInstance().getScene().getWindow(), "Form Error!", e.toString()); } } }); // Add update role Button updateRolebtn = new Button("Update User Role"); updateRolebtn.setPrefHeight(40); updateRolebtn.setDefaultButton(true); updateRolebtn.setPrefWidth(110); add(updateRolebtn, 1,2, 2, 1); GridPane.setHalignment(updateRolebtn, HPos.LEFT); GridPane.setMargin(updateRolebtn, new Insets(20, 0,20,0)); ObservableList<String> options = FXCollections.observableArrayList( "Admin", "Employee", "Customer" ); final ComboBox comboBox = new ComboBox(options); comboBox.getSelectionModel().selectFirst(); comboBox.setPrefHeight(40); comboBox.setPrefWidth(100); add(comboBox, 2,2,2,1); GridPane.setHalignment(comboBox, HPos.LEFT); GridPane.setMargin(comboBox, new Insets(20, 0,20,0)); updateRolebtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { User currentSelected = table.getSelectionModel().getSelectedItem(); try { ControllerInstance.getInstance().getCont().updateUserRole(comboBox.getSelectionModel().getSelectedItem().toString(), table.getSelectionModel().getSelectedItem().getUserName()); refreshTable(); ErrorMessage.getInstance().showAlert(Alert.AlertType.CONFIRMATION, DataPane.getInstance().getScene().getWindow(), "Form Error!", "Role Updated Sucssesfully"); } catch (Exception e) { ErrorMessage.getInstance().showAlert(Alert.AlertType.ERROR, DataPane.getInstance().getScene().getWindow(), "Form Error!", e.toString()); } } }); } public void refreshTable() { table.setItems(null); table.setItems(getUsers()); table.refresh(); } //Get all of the products public ObservableList<User> getUsers(){ /*ObservableList<User> users = FXCollections.observableArrayList(); users.add(new User("Zur","0548070390","Customer",456.56,2.5,new Date(1993,11,24))); users.add(new User("Guy","0548070391","Admin",123.56,2.5,new Date(1990,11,24))); users.add(new User("Oren","0548070392","Woker",147.56,2.5,new Date(1989,11,24))); users.add(new User("Oren","0548070392","Woker",147.56,2.5,new Date(1989,11,24))); users.add(new User("Oren","0548070392","Woker",147.56,2.5,new Date(1989,11,24))); users.add(new User("Oren","0548070392","Woker",147.56,2.5,new Date(1989,11,24))); users.add(new User("Oren","0548070392","Woker",147.56,2.5,new Date(1989,11,24)));*/ ObservableList<User> users = FXCollections.observableArrayList(); try { for (User user : ControllerInstance.getInstance().getCont().get_users()) { users.add(user); } } catch (SQLException e) { ErrorMessage.getInstance().showAlert(Alert.AlertType.ERROR, DataPane.getInstance().getScene().getWindow(), "Form Error!", e.getMessage()); } return users; } @Override public void updateData(DataType data) { // TODO Auto-generated method stub } @Override public void clearData() { // TODO Auto-generated method stub } }
package com.example.candace.pslapplication; import android.content.Intent; import android.os.Handler; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Iterator; public class WordActivity extends AppCompatActivity { private TextView word_text; private TextView wordFilipino_text; private Button favorite; /* For the Navigation Menu */ protected DrawerLayout drawerLayout; private ActionBarDrawerToggle actionBarDrawer; private NavigationView navView; /* For the GIF Viewer */ private ImageView word_image; /* For the Firebase */ private DatabaseReference mDatabase; private int image[]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_word); word_text = findViewById(R.id.word_text); wordFilipino_text = findViewById(R.id.wordFilipino_text); word_image = findViewById(R.id.word_image); favorite = findViewById(R.id.favorite); image = new int[]{ R.drawable.heart, R.drawable.heart_clicked, }; Intent intent = getIntent(); final WordModel model = (WordModel)intent.getSerializableExtra("WordModelObject"); initializeNavigationMenu(model.getWord()); /* For the GIF Viewer */ Glide.with(this.getApplicationContext()).load(model.getLink()).into(word_image); word_text.setText(model.getWord()); wordFilipino_text.setText(model.getWordFilipino()); if(model.getFavorite() == true){ favorite.setBackgroundResource(image[1]); } else favorite.setBackgroundResource(image[0]); favorite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(model.getFavorite() == true){ model.setFavorite(false); // favorite.setText(getResources().getString(R.string.add_fave)); mDatabase = FirebaseDatabase.getInstance().getReference().child("words"); mDatabase.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){ WordModel word = postSnapshot.getValue(WordModel.class); if(model.getWord().equals(word.getWord())){ DatabaseReference mDatabaseRef = postSnapshot.getRef().child("favorite"); mDatabaseRef.setValue(false); favorite.setBackgroundResource(image[0]); Toast.makeText(WordActivity.this, "Removed from Favorites!", Toast.LENGTH_LONG).show(); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } else{ model.setFavorite(true); // favorite.setText(getResources().getString(R.string.remove_fave)); mDatabase = FirebaseDatabase.getInstance().getReference().child("words"); mDatabase.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){ WordModel word = postSnapshot.getValue(WordModel.class); if(model.getWord().equals(word.getWord())){ DatabaseReference mDatabaseRef = postSnapshot.getRef().child("favorite"); mDatabaseRef.setValue(true); favorite.setBackgroundResource(image[1]); Toast.makeText(WordActivity.this, "Added to Favorites!", Toast.LENGTH_LONG).show(); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } } }); } public void initializeNavigationMenu(String word){ drawerLayout = findViewById(R.id.activity_word); actionBarDrawer = new ActionBarDrawerToggle(this, drawerLayout,R.string.open, R.string.close); drawerLayout.addDrawerListener(actionBarDrawer); actionBarDrawer.syncState(); ActionBar myActionBar = getSupportActionBar(); if (myActionBar != null) { myActionBar.setDisplayHomeAsUpEnabled(true); myActionBar.setTitle(word); } navView = findViewById(R.id.navigation_view); navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); switch(id) { case R.id.home: new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(getApplicationContext(), MainActivity.class); WordActivity.this.startActivity(intent); finish(); } }, 100); drawerLayout.closeDrawers(); return true; case R.id.favorites: new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(getApplicationContext(), FavoritesActivity.class); WordActivity.this.startActivity(intent); finish(); } }, 100); drawerLayout.closeDrawers(); return true; case R.id.dictionary: new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(getApplicationContext(), DictionaryActivity.class); WordActivity.this.startActivity(intent); finish(); } }, 100); drawerLayout.closeDrawers(); return true; case R.id.categories: new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(getApplicationContext(), CategoriesActivity.class); WordActivity.this.startActivity(intent); finish(); } }, 120); drawerLayout.closeDrawers(); return true; case R.id.quizzes: new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(getApplicationContext(), QuizzesActivity.class); WordActivity.this.startActivity(intent); finish(); } }, 120); drawerLayout.closeDrawers(); return true; case R.id.about: { new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(getApplicationContext(), AboutActivity.class); WordActivity.this.startActivity(intent); finish(); } }, 100); drawerLayout.closeDrawers(); return true; } default: return true; } } }); } /* For Navigation Menu */ @Override public boolean onOptionsItemSelected(MenuItem item) { if(actionBarDrawer.onOptionsItemSelected(item)) return true; return super.onOptionsItemSelected(item); } }
package views; import java.sql.SQLException; import java.util.List; import bean.ColorMstBean; import bean.GoodsListBean; import bean.KindMstBean; import com.cloudgarden.resource.SWTResourceManager; import common.Consts; import common.Utilities; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import service.GoodsListDetailService; import service.GoodsListService; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class GoodsListDetail extends org.eclipse.swt.widgets.Dialog { private Shell dialogShell; private Composite sellGoodsComposite; private Button goodsListDetailCancelButton; private Button goodsListDetailConfirmButton; private Text goodsListDetailNameValueText; private Text goodsListDetailMemoValueText; private Text goodsListDetailBuyPriceValueText; private Text goodsListDetailSellHopePriceValueText; private Text goodsListDetailPlaceValueText; private Label goodsListDetailNameLabel; private Button goodsListDetailAddKindButton; private Button goodsListDetailAddColorButton; private Combo goodsListDetailKindCombo; private Combo goodsListDetailColorCombo; private Label goodsListDetailKindLabel; private Button goodsListDetail; private Label goodsListDetailColorLabel; private Label goodsListDetailMemoLabel; private Label goodsListDetailBuyPriceLabel; private Label goodsListDetailBuyPriceWonLabel; private Label goodsListDetailSellHopePriceLabel; private Label goodsListDetailSellHopePriceWonLabel; private Label goodsListDetailPlaceLabel; private Label goodsListDetailNoLabel; private Label goodsListDetailNoValueLabel; private Label goodsListDetailBuyDateLabel; GoodsListService goodsListService = new GoodsListService(); GoodsListDetailService goodsListDetailService = new GoodsListDetailService(); private Text buyDateYearText; private Label buyDateYearLabel; private Text buyDateMonthText; private Label BuyDateMonthLabel; private Text buyDateDayText; private Label buyDateDayLabel; Long id = null; // ArrayList<GoodsListBean> result = new ArrayList<GoodsListBean>(); GoodsListBean bean = new GoodsListBean(); private Label goodsListDetailInfoLabel; Utilities util = new Utilities(); Main main = null; boolean returnOk = false; public GoodsListDetail(Shell parent, int style) { super(parent, style); } public GoodsListBean open(Main main, Long goodsId) throws SQLException { this.main = main; Shell parent = getParent(); dialogShell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); { //Register as a resource user - SWTResourceManager will //handle the obtaining and disposing of resources SWTResourceManager.registerResourceUser(dialogShell); } dialogShell.setLayout(new FormLayout()); dialogShell.layout(); dialogShell.pack(); dialogShell.setSize(386, 487); dialogShell.setText("상품 정보 수정"); this.id = goodsId; GoodsListBean dbData = goodsListDetailService.getGoodsDetail(this.id); { sellGoodsComposite = new Composite(dialogShell, SWT.NONE); FormData composite1LData = new FormData(); composite1LData.left = new FormAttachment(0, 1000, 0); composite1LData.top = new FormAttachment(0, 1000, -20); composite1LData.width = 386; composite1LData.height = 468; sellGoodsComposite.setLayoutData(composite1LData); sellGoodsComposite.setLayout(null); { goodsListDetailNoLabel = new Label(sellGoodsComposite, SWT.RIGHT); goodsListDetailNoLabel.setText("\uc0c1\ud488No : "); goodsListDetailNoLabel.setBounds(19, 65, 65, 19); goodsListDetailNoLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); } { goodsListDetailNoValueLabel = new Label(sellGoodsComposite, SWT.LEFT); goodsListDetailNoValueLabel.setText(String.valueOf(this.id)); goodsListDetailNoValueLabel.setBounds(92, 66, 106, 19); } { goodsListDetailNameLabel = new Label(sellGoodsComposite, SWT.RIGHT); goodsListDetailNameLabel.setText("\uc0c1\ud488\uba85 : "); goodsListDetailNameLabel.setBounds(19, 93, 65, 19); goodsListDetailNameLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); } { goodsListDetailNameValueText = new Text(sellGoodsComposite, SWT.MULTI | SWT.WRAP); goodsListDetailNameValueText.setBounds(92, 96, 281, 42); goodsListDetailNameValueText.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 0, false, false)); goodsListDetailNameValueText.setBackground(SWTResourceManager.getColor(255, 255, 255)); goodsListDetailNameValueText.setText(dbData.getName() != null ? dbData.getName() : ""); goodsListDetailNameValueText.setTextLimit(255); } { goodsListDetailKindLabel = new Label(sellGoodsComposite, SWT.RIGHT); goodsListDetailKindLabel.setText("\uc0c1\ud488\uc885\ub958 :"); goodsListDetailKindLabel.setBounds(7, 149, 73, 17); goodsListDetailKindLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); } { goodsListDetailKindCombo = new Combo(sellGoodsComposite, SWT.READ_ONLY); showKindCombo(); if (! util.isEmpty(dbData.getKind())) { for (int i = 0; i < goodsListDetailKindCombo.getItemCount(); i++) { if (dbData.getKind().equals(goodsListDetailKindCombo.getItem(i))) { goodsListDetailKindCombo.select(i); } } } else { goodsListDetailKindCombo.select(0); } } { goodsListDetailAddKindButton = new Button(sellGoodsComposite, SWT.PUSH | SWT.CENTER); goodsListDetailAddKindButton.setText("\uadf8\uc678\uc758 \uc885\ub958 \uc785\ub825"); goodsListDetailAddKindButton.setBounds(250, 146, 123, 26); goodsListDetailAddKindButton.setToolTipText("\uc67c\ucabd \uc885\ub958 \ub9ac\uc2a4\ud2b8\uc5d0 \ub098\uc640\uc788\ub294 \uac83 \uc774\uc678\uc758 \uc885\ub958\ub97c \uc785\ub825\ud560 \ub54c\ub294 \uc774 \ubc84\ud2bc\uc744 \ub204\ub974\uace0 \uc0c8\ub85c\uc6b4 \uc885\ub958 \uc774\ub984\uc744 \uc785\ub825\ud574\uc8fc\uc2ed\uc2dc\uc624."); goodsListDetailAddKindButton.addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent evt) { goodsListDetailAddKindButtonMouseUp(evt); } }); } { goodsListDetailColorLabel = new Label(sellGoodsComposite, SWT.RIGHT); goodsListDetailColorLabel.setText("\uc0c9\uc0c1 :"); goodsListDetailColorLabel.setBounds(17, 178, 63, 17); goodsListDetailColorLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); } { goodsListDetailColorCombo = new Combo(sellGoodsComposite, SWT.READ_ONLY); showColorCombo(); if (! util.isEmpty(dbData.getKind())) { for (int i = 0; i < goodsListDetailColorCombo.getItemCount(); i++) { if (dbData.getColor() != null && dbData.getColor().equals(goodsListDetailColorCombo.getItem(i))) { goodsListDetailColorCombo.select(i); } } } else { goodsListDetailColorCombo.select(0); } } { goodsListDetailAddColorButton = new Button(sellGoodsComposite, SWT.PUSH | SWT.CENTER); goodsListDetailAddColorButton.setText("\uadf8\uc678\uc758 \uc0c9\uc0c1 \uc785\ub825"); goodsListDetailAddColorButton.setBounds(250, 174, 123, 26); goodsListDetailAddColorButton.setToolTipText("\uc67c\ucabd \uc0c9\uc0c1 \ub9ac\uc2a4\ud2b8\uc5d0 \ub098\uc640\uc788\ub294 \uac83 \uc774\uc678\uc758 \uc0c9\uc0c1\uc744 \uc785\ub825\ud560 \ub54c\ub294 \uc774 \ubc84\ud2bc\uc744 \ub204\ub974\uace0 \uc0c8\ub85c\uc6b4 \uc885\ub958 \uc774\ub984\uc744 \uc785\ub825\ud574\uc8fc\uc2ed\uc2dc\uc624."); goodsListDetailAddColorButton.addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent evt) { goodsListDetailAddColorButtonMouseUp(evt); } }); } { goodsListDetailMemoLabel = new Label(sellGoodsComposite, SWT.RIGHT); goodsListDetailMemoLabel.setText("\uba54\ubaa8 : "); goodsListDetailMemoLabel.setBounds(33, 206, 51, 17); goodsListDetailMemoLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); } { goodsListDetailMemoValueText = new Text(sellGoodsComposite, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER); goodsListDetailMemoValueText.setBounds(92, 207, 279, 57); goodsListDetailMemoValueText.setBackground(SWTResourceManager.getColor(255, 255, 255)); goodsListDetailMemoValueText.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 0, false, false)); goodsListDetailMemoValueText.setText(dbData.getMemo() != null ? dbData.getMemo() : ""); goodsListDetailMemoValueText.setTextLimit(500); } { goodsListDetailBuyPriceLabel = new Label(sellGoodsComposite, SWT.RIGHT); goodsListDetailBuyPriceLabel.setText("\uad6c\uc785\uac00 : "); goodsListDetailBuyPriceLabel.setBounds(17, 276, 83, 17); goodsListDetailBuyPriceLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); } { goodsListDetailBuyPriceValueText = new Text(sellGoodsComposite, SWT.SINGLE | SWT.RIGHT | SWT.WRAP); goodsListDetailBuyPriceValueText.setBounds(114, 277, 137, 20); goodsListDetailBuyPriceValueText.setBackground(SWTResourceManager.getColor(255, 255, 255)); goodsListDetailBuyPriceValueText.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 0, false, false)); goodsListDetailBuyPriceValueText.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent evt) { // 숫자만 입력 가능 evt.doit = evt.text.matches("[0-9]*"); } }); goodsListDetailBuyPriceValueText.setText(dbData.getBuyPrice() != null ? String.valueOf(dbData.getBuyPrice()) : ""); } { goodsListDetailBuyPriceWonLabel = new Label(sellGoodsComposite, SWT.LEFT); goodsListDetailBuyPriceWonLabel.setText("\uc6d0"); goodsListDetailBuyPriceWonLabel.setBounds(256, 278, 51, 20); goodsListDetailBuyPriceWonLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 0, false, false)); } { goodsListDetailSellHopePriceLabel = new Label(sellGoodsComposite, SWT.RIGHT); goodsListDetailSellHopePriceLabel.setText("\ud310\ub9e4\uc608\uc815\uac00 : "); goodsListDetailSellHopePriceLabel.setBounds(6, 310, 90, 18); goodsListDetailSellHopePriceLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); } { goodsListDetailSellHopePriceValueText = new Text(sellGoodsComposite, SWT.SINGLE | SWT.RIGHT | SWT.WRAP); goodsListDetailSellHopePriceValueText.setBounds(114, 310, 137, 20); goodsListDetailSellHopePriceValueText.setBackground(SWTResourceManager.getColor(255, 255, 255)); goodsListDetailSellHopePriceValueText.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 0, false, false)); goodsListDetailSellHopePriceValueText.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent evt) { // 숫자만 입력 가능 evt.doit = evt.text.matches("[0-9]*"); } }); goodsListDetailSellHopePriceValueText.setText(dbData.getSellHopePrice() != null ? String.valueOf(dbData.getSellHopePrice()) : ""); } { goodsListDetailSellHopePriceWonLabel = new Label(sellGoodsComposite, SWT.LEFT); goodsListDetailSellHopePriceWonLabel.setText("\uc6d0"); goodsListDetailSellHopePriceWonLabel.setBounds(256, 312, 51, 20); goodsListDetailSellHopePriceWonLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 0, false, false)); } // { // goodsListDetailSellPriceLabel = new Label(sellGoodsComposite, SWT.RIGHT); // goodsListDetailSellPriceLabel.setText("\ud310\ub9e4\uac00 : "); // goodsListDetailSellPriceLabel.setBounds(15, 224, 83, 17); // goodsListDetailSellPriceLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); // } // { // goodsListDetailSellPriceValueText = new Text(sellGoodsComposite, SWT.SINGLE | SWT.RIGHT | SWT.WRAP | SWT.BORDER); // goodsListDetailSellPriceValueText.setText(this.sellGoodsData.getSellHopePrice() != null ? String.valueOf(this.sellGoodsData.getSellHopePrice()) : ""); // goodsListDetailSellPriceValueText.setBounds(112, 222, 140, 22); // goodsListDetailSellPriceValueText.setBackground(SWTResourceManager.getColor(255, 255, 255)); // goodsListDetailSellPriceValueText.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 0, false, false)); // goodsListDetailSellPriceValueText.addVerifyListener(new VerifyListener() { // public void verifyText(VerifyEvent evt) { // 숫자만 입력 가능 // evt.doit = evt.text.matches("[0-9]*"); // } // }); //} // { // goodsListDetailSellPriceWonLabel = new Label(sellGoodsComposite, SWT.LEFT); // goodsListDetailSellPriceWonLabel.setText("\uc6d0"); // goodsListDetailSellPriceWonLabel.setBounds(254, 225, 51, 20); // goodsListDetailSellPriceWonLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 0, false, false)); // } { goodsListDetailPlaceLabel = new Label(sellGoodsComposite, SWT.RIGHT); goodsListDetailPlaceLabel.setText("\uad6c\uc785\ucc98 : "); goodsListDetailPlaceLabel.setBounds(29, 345, 70, 17); goodsListDetailPlaceLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); } { goodsListDetailPlaceValueText = new Text(sellGoodsComposite, SWT.SINGLE | SWT.WRAP); goodsListDetailPlaceValueText.setBounds(113, 347, 261, 20); goodsListDetailPlaceValueText.setBackground(SWTResourceManager.getColor(255, 255, 255)); goodsListDetailPlaceValueText.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 0, false, false)); goodsListDetailPlaceValueText.setText(dbData.getPlace() != null ? dbData.getPlace() : ""); goodsListDetailPlaceValueText.setTextLimit(255); } { goodsListDetailBuyDateLabel = new Label(sellGoodsComposite, SWT.RIGHT); goodsListDetailBuyDateLabel.setText("\uad6c\uc785\ub0a0\uc9dc : "); goodsListDetailBuyDateLabel.setBounds(13, 380, 85, 17); goodsListDetailBuyDateLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); } // { // goodsListDetailBuyDateLabel = new Label(sellGoodsComposite, SWT.RIGHT); // goodsListDetailBuyDateLabel.setText("\uad6c\uc785\ub0a0\uc9dc : "); // goodsListDetailBuyDateLabel.setBounds(18, 280, 74, 17); // goodsListDetailBuyDateLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 1, false, false)); // } // { // goodsListDetailBuyDateValueText = new Text(sellGoodsComposite, SWT.SINGLE | SWT.WRAP); // goodsListDetailBuyDateValueText.setBounds(110, 279, 261, 20); // goodsListDetailBuyDateValueText.setBackground(SWTResourceManager.getColor(255, 255, 255)); // goodsListDetailBuyDateValueText.setEditable(false); // goodsListDetailBuyDateValueText.setFont(SWTResourceManager.getFont("Lucida Grande", 11, 0, false, false)); // } // { // goodsListDetailBarcodeLabel = new Label(sellGoodsComposite, SWT.RIGHT); // goodsListDetailBarcodeLabel.setText("\ubc14\ucf54\ub4dc : "); // goodsListDetailBarcodeLabel.setBounds(12, 310, 74, 17); // goodsListDetailBarcodeLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 14, 0, false, false)); // } // { // goodsListDetailBarcodeValueText = new Text(sellGoodsComposite, SWT.SINGLE | SWT.WRAP); // goodsListDetailBarcodeValueText.setText(util.isEmpty(this.sellGoodsData.getBarcode()) ? "" : this.sellGoodsData.getBarcode()); // goodsListDetailBarcodeValueText.setBounds(89, 310, 285, 20); // goodsListDetailBarcodeValueText.setBackground(SWTResourceManager.getColor(232, 232, 232)); // goodsListDetailBarcodeValueText.setEditable(false); // goodsListDetailBarcodeValueText.setFont(SWTResourceManager.getFont("Lucida Grande", 14, 0, false, false)); // } { goodsListDetailCancelButton = new Button(sellGoodsComposite, SWT.PUSH | SWT.CENTER); goodsListDetailCancelButton.setText("\ucde8 \uc18c"); goodsListDetailCancelButton.setBounds(15, 422, 67, 37); goodsListDetailCancelButton.addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent evt) { dialogShell.dispose(); } }); goodsListDetailCancelButton.addTraverseListener(new TraverseListener() { public void keyTraversed(TraverseEvent evt) { if (evt.detail == SWT.TRAVERSE_RETURN) { dialogShell.dispose(); } } }); } { goodsListDetailConfirmButton = new Button(sellGoodsComposite, SWT.PUSH | SWT.CENTER); goodsListDetailConfirmButton.setText("\uc704 \ub0b4\uc6a9\ub300\ub85c \uc0c1\ud488 \uc815\ubcf4 \uc218\uc815"); goodsListDetailConfirmButton.setBounds(182, 422, 193, 37); goodsListDetailConfirmButton.addTraverseListener(new TraverseListener() { public void keyTraversed(TraverseEvent evt) { if (evt.detail == SWT.TRAVERSE_RETURN) { goodsListDetailConfirmButtonMouseUp(); } } }); goodsListDetailConfirmButton.addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent evt) { goodsListDetailConfirmButtonMouseUp(); } }); // goodsListDetailConfirmButton.setFocus(); } { goodsListDetailInfoLabel = new Label(sellGoodsComposite, SWT.NONE); goodsListDetailInfoLabel.setText("\ud604\uc7ac \ubcf4\uc720\uc911\uc778 \uc0c1\ud488\uc758 \uc815\ubcf4\uc785\ub2c8\ub2e4.\n\uc0c1\ud488\uba85\uacfc \uad6c\uc785\uac00\ub294 \ud544\uc218 \uc785\ub825 \ud56d\ubaa9\uc785\ub2c8\ub2e4."); goodsListDetailInfoLabel.setBounds(9, 23, 345, 41); } { goodsListDetail = new Button(sellGoodsComposite, SWT.PUSH | SWT.CENTER); goodsListDetail.setText("\uc0ad\uc81c"); goodsListDetail.setBounds(100, 429, 65, 24); goodsListDetail.addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent evt) { int selected = util.showYesOrNoMsgBox(dialogShell, "이 구입상품 정보를 정말로 삭제하시겠습니까?\n구입했던 상품 정보가 삭제되어 구입하지 않았던 상태가 됩니다."); if (selected == SWT.YES) { try { goodsListDetailService.deleteGoods(id); returnOk = true; dialogShell.dispose(); } catch (SQLException e) { util.showErrorMsg(dialogShell, "상품정보를 삭제하는 과정에서 에러가 발생했습니다.\n\n" + e.getMessage()); } } } }); } { buyDateDayLabel = new Label(sellGoodsComposite, SWT.LEFT); buyDateDayLabel.setText("\uc77c"); buyDateDayLabel.setBounds(309, 381, 24, 20); buyDateDayLabel.setFont(SWTResourceManager.getFont("Lucida Grande",11,0,false,false)); } { buyDateDayText = new Text(sellGoodsComposite, SWT.SINGLE | SWT.RIGHT | SWT.WRAP); buyDateDayText.setTextLimit(2); buyDateDayText.setFont(SWTResourceManager.getFont("Lucida Grande",11,0,false,false)); buyDateDayText.setText(util.applyDateFormat(dbData.getBuyDate(), "dd")); buyDateDayText.setBackground(SWTResourceManager.getColor(255,255,255)); buyDateDayText.setBounds(270, 380, 33, 20); buyDateDayText.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent evt) { // 숫자만 입력 가능 evt.doit = evt.text.matches("[0-9]*"); } }); } { BuyDateMonthLabel = new Label(sellGoodsComposite, SWT.LEFT); BuyDateMonthLabel.setText("\uc6d4"); BuyDateMonthLabel.setBounds(242, 381, 24, 20); BuyDateMonthLabel.setFont(SWTResourceManager.getFont("Lucida Grande",11,0,false,false)); } { buyDateMonthText = new Text(sellGoodsComposite, SWT.SINGLE | SWT.RIGHT | SWT.WRAP); buyDateMonthText.setTextLimit(2); buyDateMonthText.setFont(SWTResourceManager.getFont("Lucida Grande",11,0,false,false)); buyDateMonthText.setText(util.applyDateFormat(dbData.getBuyDate(), "MM")); buyDateMonthText.setBackground(SWTResourceManager.getColor(255,255,255)); buyDateMonthText.setBounds(201, 380, 37, 20); buyDateMonthText.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent evt) { // 숫자만 입력 가능 evt.doit = evt.text.matches("[0-9]*"); } }); } { buyDateYearLabel = new Label(sellGoodsComposite, SWT.LEFT); buyDateYearLabel.setText("\ub144"); buyDateYearLabel.setBounds(178, 382, 23, 20); buyDateYearLabel.setFont(SWTResourceManager.getFont("Lucida Grande",11,0,false,false)); } { buyDateYearText = new Text(sellGoodsComposite, SWT.SINGLE | SWT.RIGHT | SWT.WRAP); buyDateYearText.setTextLimit(4); buyDateYearText.setFont(SWTResourceManager.getFont("Lucida Grande",11,0,false,false)); buyDateYearText.setText(util.applyDateFormat(dbData.getBuyDate(), "yyyy")); buyDateYearText.setBackground(SWTResourceManager.getColor(255,255,255)); buyDateYearText.setBounds(114, 380, 60, 20); buyDateYearText.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent evt) { // 숫자만 입력 가능 evt.doit = evt.text.matches("[0-9]*"); } }); } } dialogShell.setLocation(getParent().toDisplay(250, -20)); dialogShell.open(); Display display = dialogShell.getDisplay(); while (!dialogShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } if (returnOk) { return bean; } else { return null; } } // 이 상품을 판매리스트에 추가 버튼 클릭시. private void goodsListDetailConfirmButtonMouseUp() { if (util.isEmpty(goodsListDetailNameValueText.getText())) { util.showMsg(dialogShell, "상품명을 입력해주십시오."); return; } if (util.isEmpty(goodsListDetailBuyPriceValueText.getText())) { util.showMsg(dialogShell, "구입가를 입력해주십시오."); return; } if (util.isEmpty(buyDateYearText.getText()) || util.isEmpty(buyDateMonthText.getText()) || util.isEmpty(buyDateDayText.getText())) { util.showMsg(dialogShell, "구입날짜의 연월일을 모두 입력해주십시오."); return; } else { if ( ! util.isCorrectDate(buyDateYearText.getText(), buyDateMonthText.getText(), buyDateDayText.getText())) { util.showMsg(dialogShell, "구입날짜의 입력치가 올바른 날짜가 아닙니다."); return; } } int yesOrNo = util.showYesOrNoMsgBox(dialogShell, "이 상품 정보를 수정하시겠습니까?"); if (yesOrNo != SWT.YES) { return; } try { bean.setId(this.id); bean.setName(goodsListDetailNameValueText.getText().trim()); bean.setKind(goodsListDetailKindCombo.getText()); bean.setColor(goodsListDetailColorCombo.getText()); String memo = goodsListDetailMemoValueText.getText().trim(); bean.setMemo(! util.isEmpty(memo) ? memo : null); bean.setBuyPrice(Long.valueOf(goodsListDetailBuyPriceValueText.getText())); bean.setSellHopePrice(! util.isEmpty(goodsListDetailSellHopePriceValueText.getText()) ? Long.valueOf(goodsListDetailSellHopePriceValueText.getText()) : null); bean.setBuyDate(util.getDateFromString(buyDateYearText.getText(), buyDateMonthText.getText(), buyDateDayText.getText())); String place = goodsListDetailPlaceValueText.getText().trim(); bean.setPlace(! util.isEmpty(place) ? place : null); try { goodsListDetailService.updateGoods(bean); } catch (SQLException e) { util.showErrorMsg(dialogShell, "상품정보를 갱신하는 과정에서 에러가 발생했습니다.\n\n" + e.getMessage()); } returnOk = true; dialogShell.dispose(); } catch (NumberFormatException e) { util.showMsg(dialogShell, "숫자 입력에 에러가 있습니다."); } } private void goodsListDetailAddKindButtonMouseUp(MouseEvent evt) { AddKind addKind = new AddKind(dialogShell, SWT.NONE); String addedName = addKind.open(main); if (addedName != null && goodsListDetailKindCombo.getItemCount() > 0) { showKindCombo(); int count = goodsListDetailKindCombo.getItemCount(); for (int i = 0; i < count; i++) { if (addedName.equals(goodsListDetailKindCombo.getItem(i))) { goodsListDetailKindCombo.select(i); break; } } } } private void goodsListDetailAddColorButtonMouseUp(MouseEvent evt) { AddColor addColor = new AddColor(dialogShell, SWT.NONE); String addedName = addColor.open(main); if (addedName != null && goodsListDetailColorCombo.getItemCount() > 0) { showColorCombo(); int count = goodsListDetailColorCombo.getItemCount(); for (int i = 0; i < count; i++) { if (addedName.equals(goodsListDetailColorCombo.getItem(i))) { goodsListDetailColorCombo.select(i); break; } } } } private void showKindCombo() { try { goodsListDetailKindCombo.removeAll(); goodsListDetailKindCombo.setBounds(92, 146, 152, 22); List<KindMstBean> kindMstList = goodsListService.getKindMst(); goodsListDetailKindCombo.add(""); for (KindMstBean kindMstBean : kindMstList) { goodsListDetailKindCombo.add(kindMstBean.getName()); } } catch (SQLException e) { util.showErrorMsg(dialogShell, "상품종류를 읽어들이는 과정에서 에러가 발생했습니다.\n\n" + e.getMessage()); } } private void showColorCombo() { try { goodsListDetailColorCombo.removeAll(); goodsListDetailColorCombo.setBounds(92, 175, 152, 22); List<ColorMstBean> colorMstList = goodsListService.getColorMst(); goodsListDetailColorCombo.add(""); for (ColorMstBean colorMstBean : colorMstList) { goodsListDetailColorCombo.add(colorMstBean.getName()); } } catch (SQLException e) { util.showErrorMsg(dialogShell, "상품색상을 읽어들이는 과정에서 에러가 발생했습니다.\n\n" + e.getMessage()); } } }
package us.gibb.dev.gwt.event; import us.gibb.dev.gwt.location.LocationManager; import com.google.gwt.event.shared.HandlerRegistration; public interface EventBus extends LocationManager { public <E extends Event<T, H>, H extends EventHandler<E>, T> HandlerRegistration add(EventHandler<E> handler); public void fire(Event<?, ?> event); public boolean isHandled(Class<?> typeClass); public void fireCurrentLocation(); public void failure(String msg); public void failure(Throwable t); public void failure(String msg, Throwable t); }
package com.hackathon.domain.entity; import lombok.Data; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @Data public class School { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true) private String code; @Column private String name; @Fetch(FetchMode.SELECT) @OneToMany(mappedBy = "school", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE) private List<User> users = new ArrayList<>(); @Fetch(FetchMode.SELECT) @OneToMany(mappedBy = "school", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE) private List<Post> post = new ArrayList<>(); public School(String code, String name) { this.code = code; this.name = name; } public School() { } }
package dev.nowalk.app; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import dev.nowalk.pages.WikiMain; public class PomPlayground { public static void main(String[] args) { String driverPath = "C:/Users/cjyes/OneDrive/Desktop/Chrome Driver/chromedriver.exe"; System.setProperty("webdriver.chrome.driver", driverPath); WebDriver driver = new ChromeDriver(); WikiMain wikiMain = new WikiMain(driver); String url = "http://www.wikipedia.org/"; driver.get(url); //wikiMain.english.click(); wikiMain.clickEnglish(); driver.get(url); wikiMain.clickJapanese(); driver.get(url); wikiMain.clickSpanish(); driver.get(url); wikiMain.clickGerman(); driver.get(url); wikiMain.clickRussian(); driver.get(url); wikiMain.clickFrench(); //just a quick sleep so we can actually see what Selenium is doing try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } driver.quit(); } }
/** * Created by owen on 2017/9/18. */ public class ReverseList { public ListNode reverse(ListNode head){ if (head==null) return null; ListNode pre,node; pre=null; node=head; while (head!=null){ node=head.next; head.next=pre; pre=head; head=node; } return pre; } }
package AppUtilisateur; import java.sql.*; import Cryptage.BCrypt; public class DataBase { static PreparedStatement psInsererEtudiant; static PreparedStatement psConnexion; static PreparedStatement psConnexionMdpCrypt; static PreparedStatement psListeExamens; static PreparedStatement psInsererEtudiantExamen; static PreparedStatement psInscriptionTousExamensUnBloc; static PreparedStatement psVisualiserHoraireExamens; static PreparedStatement psRecupererBlocId; public DataBase (){ Connection conn = connectToDb("postgres", "azerty"); try { psInsererEtudiant = conn.prepareStatement("SELECT projetSQL.insererEtudiant(?,?,?,?,?)"); psConnexion = conn.prepareStatement("SELECT projetSQL.connexion(?)"); psConnexionMdpCrypt = conn.prepareStatement("SELECT projetSQL.connexionMdpCrypt(?)"); psListeExamens = conn.prepareStatement("SELECT * FROM projetSQL.ListeExamens"); psInsererEtudiantExamen = conn.prepareStatement("SELECT projetSQL.insererEtudiantExamen(?,?)"); psInscriptionTousExamensUnBloc = conn.prepareStatement("SELECT projetSQL.inscriptionTousExamensUnBloc(?)"); psVisualiserHoraireExamens = conn.prepareStatement("SELECT * FROM projetSQL.HoraireExamens WHERE \"Etudiant id\" = ?"); psRecupererBlocId = conn.prepareStatement("SELECT b.bloc_id FROM projetSQL.Blocs b WHERE b.code = ?"); } catch (SQLException se) { se.printStackTrace(); } } //Connection to dataBase private Connection connectToDb(String username, String password) { Connection conn = null; try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { System.out.println("Driver PostgreSQL manquant !"); System.exit(1); } String url = "jdbc:postgresql://127.0.0.1:5432/dbu2binDORREKENS"; try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { System.out.println("Impossible de joindre le server !"); System.exit(1); } return conn; } public void inscription(String nom, String prenom, String mail, String mdp, String codeBloc) { String blocId = getIdFromDb(codeBloc, psRecupererBlocId); try { psInsererEtudiant.setString(1, nom); psInsererEtudiant.setString(2, prenom); psInsererEtudiant.setString(3, mail); psInsererEtudiant.setString(4, mdp); psInsererEtudiant.setInt(5, Integer.parseInt(blocId)); psInsererEtudiant.execute(); System.out.println("Inscription validée, vous pouvez maintenant vous connecter \n"); } catch (SQLException se) { System.out.println("Erreur lors de l’insertion !"); System.out.println(se.getMessage()); } } public int connexion(String nom, String mdp) { Boolean mdpCorrect = false; String sessionId = null; ResultSet rs=null; //Comparison passwords try { psConnexionMdpCrypt.setString(1, nom); rs = psConnexionMdpCrypt.executeQuery(); { while (rs.next()) { mdpCorrect = BCrypt.checkpw(mdp,rs.getString(1)); } } } catch (SQLException se) { System.out.println(se.getMessage()); } //If correct password : get etudiant_id if(mdpCorrect) { try { psConnexion.setString(1, nom); rs = psConnexion.executeQuery(); { while (rs.next()) { sessionId = rs.getString(1); } } } catch (SQLException se) { System.out.println(se.getMessage()); } } //If connection succeed return etudiant_id , else return 0 if(sessionId == null) { return 0; } else { return Integer.parseInt(sessionId); } } public void visualiserExamens() { ResultSet rs = null; try { rs = psListeExamens.executeQuery(); { while (rs.next()) { String espaceNom = ""; for(int i = 0 ; i<(11-rs.getString(2).length());i++) { espaceNom += " "; } System.out.println(rs.getString(1) + " || " + rs.getString(2) + espaceNom + "|| " + rs.getString(3) + " || " + rs.getString(4)); } } } catch (SQLException se) { System.out.println(se.getMessage()); } } public void inscriptionExamen(int etudiantId, String codeExamen) { try { psInsererEtudiantExamen.setInt(1, etudiantId); psInsererEtudiantExamen.setString(2, codeExamen); psInsererEtudiantExamen.execute(); System.out.println("Inscription à l'examen validée \n"); } catch (SQLException se) { System.out.println("Erreur lors de l’insertion !"); System.out.println(se.getMessage()); } } public void inscriptionTousExamenBloc(int etudiantId) { try { psInscriptionTousExamensUnBloc.setInt(1, etudiantId); psInscriptionTousExamensUnBloc.execute(); System.out.println("Inscription à tous les examens du bloc validée \n"); } catch (SQLException se) { System.out.println("Erreur lors de l’insertion !"); System.out.println(se.getMessage()); } } public void visualiserHoraireExamen(int etudiantId) { ResultSet rs = null; try { psVisualiserHoraireExamens.setInt(1, etudiantId); rs = psVisualiserHoraireExamens.executeQuery(); { while (rs.next()) { String espaceNom = ""; for(int i = 0 ; i<(11-rs.getString(2).length());i++) { espaceNom += " "; } if(rs.getString(4) == null) { System.out.println(rs.getString(1) + " || " + rs.getString(2) + espaceNom + "|| " + rs.getString(3) + " || " + rs.getString(4) + " || " + rs.getString(5) + " || " + rs.getString(6) ); } else { System.out.println(rs.getString(1) + " || " + rs.getString(2) + espaceNom + "|| " + rs.getString(3) + " || " + rs.getString(4) + " || " + rs.getString(5) + " || " + rs.getString(6)); } } } } catch (SQLException se) { System.out.println(se.getMessage()); } } //Function to omit duplicate code //Gets various id's from DB private String getIdFromDb(String nom, PreparedStatement statement) { String id = ""; ResultSet rs=null; try { statement.setString(1, nom); rs = statement.executeQuery(); { while (rs.next()) { id += rs.getString(1); } } } catch (SQLException se) { System.out.println(se.getMessage()); } return id; } }
package io.snice.buffer; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Test; import java.util.UUID; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class BuffersTest { @Test public void testEquals() { final var a = Buffers.wrap((byte) 0x00, (byte) 0x01, (byte) 0x02); final var b = Buffers.wrap((byte) 0x00, (byte) 0x01, (byte) 0x02); assertThat(a, is(b)); } /** * Test so that we can "extend/concatenate" a given buffer. */ @Test public void testConcatenate() { final var original = Buffers.wrap("hello"); final var extended1 = Buffers.wrap(original, (byte)0xFF); final var extended2 = Buffers.wrap(original, (byte)0xFF, (byte)0xAA); assertThat(extended1.capacity(), is(original.capacity() + 1)); assertThat(extended2.capacity(), is(original.capacity() + 2)); assertThat(extended1.getByte(extended1.capacity() - 1), is((byte)0xFF)); assertThat(extended2.getByte(extended2.capacity() - 2), is((byte)0xFF)); assertThat(extended2.getByte(extended2.capacity() - 1), is((byte)0xAA)); assertThat(extended1.slice(extended1.capacity() - 1).toString(), is("hello")); assertThat(extended2.slice(extended2.capacity() - 2).toString(), is("hello")); // test with "bad" values final var extended3 = Buffers.wrap(original, null); assertThat(extended3, is(original)); } @Test public void testTBCD() { final var tbcd01 = Buffers.wrapAsTbcd("1234"); assertThat(tbcd01.toTBCD(), is("1234")); assertThat(tbcd01, is(Buffers.wrap((byte)0x21, (byte)0x43))); final var tbcd02 = Buffers.wrapAsTbcd("56789"); assertThat(tbcd02.toTBCD(), is("56789")); assertThat(tbcd02, is(Buffers.wrap((byte)0x65, (byte)0x87, (byte)0xF9))); final var tbcd03 = Buffers.wrapAsTbcd("7"); assertThat(tbcd03.toTBCD(), is("7")); assertThat(tbcd03, is(Buffers.wrap((byte)0xF7))); final var tbcd04 = Buffers.wrapAsTbcd("78"); assertThat(tbcd04.toTBCD(), is("78")); assertThat(tbcd04, is(Buffers.wrap((byte)0x87))); } @Test public void testWrapAsInt() { assertThat(Buffers.wrapAsInt(123).getInt(0), is(123)); assertThat(Buffers.wrapAsInt(-123).getInt(0), is(-123)); assertThat(Buffers.wrapAsInt(0).getInt(0), is(0)); assertThat(Buffers.wrapAsInt(Integer.MAX_VALUE).getInt(0), is(Integer.MAX_VALUE)); assertThat(Buffers.wrapAsInt(Integer.MIN_VALUE).getInt(0), is(Integer.MIN_VALUE)); } @Test public void testWrapAsLong() { assertThat(Buffers.wrapAsLong(123L).getLong(0), is(123L)); assertThat(Buffers.wrapAsLong(-123L).getLong(0), is(-123L)); assertThat(Buffers.wrapAsLong(0L).getLong(0), is(0L)); assertThat(Buffers.wrapAsLong(Long.MAX_VALUE).getLong(0), is(Long.MAX_VALUE)); assertThat(Buffers.wrapAsLong(Long.MIN_VALUE).getLong(0), is(Long.MIN_VALUE)); } @Test public void testCreateUiid() { final var uuid = Buffers.uuid(); System.out.println(uuid.toHexString()); } @Test public void testWrapUiid() { final var uuid = UUID.randomUUID(); final var b = Buffers.wrap(uuid); assertThat(b.getLong(0), is(uuid.getMostSignificantBits())); assertThat(b.getLong(64), is(uuid.getLeastSignificantBits())); } }
package automation.homeworkoop2extends; /** * @author cosminghicioc * */ public class Talk extends Breathe { /** * @return Method which returns talk to caller */ public String talk() { return "I can talk"; } }
package com.uchain.storage; public interface LowLevelWriteBatch { void set(byte[] key, byte[] value); void delete(byte[] key); void close(); }
/** * Command Line Tool to extract Excel Lists to XML * * Copyright 2017 St. Wissel * 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 net.wissel.tools.excel; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class E2xCmdline { private static final String OUTPUT_EXTENSION = ".xml"; public static void main(final String[] args) throws ParseException, IOException, XMLStreamException, FactoryConfigurationError { final CommandLineParser parser = new DefaultParser(); final Options options = new Options(); options.addOption("i", "input", true, "Input xlsx File"); options.addOption("o", "output", true, "Output XML (or otherwise if transformed) file"); options.addOption("w", "workbooks", true, "optional: Workbook numbers to export 0,1,2,...,n"); options.addOption("e", "empty", false, "optional: generate tags for empty cells"); options.addOption("s", "single", false, "optional: export all worksheets into a single output file"); options.addOption("t", "template", true, "optional: transform resulting XML file(s) using XSLT Stylesheet"); final CommandLine cmd = parser.parse(options, args); final E2xCmdline ex = new E2xCmdline(cmd, options); ex.parse(); System.out.println("Done"); } private final boolean exportAllSheets; private final boolean exportEmptyCells; private final boolean exportSingleFile; private final boolean transform; private final String outputExtension; // Name of an optional template private final String templateName; // Input file with extension private String inputFileName; // Output file without extension!! private String outputFileName; // The sheet number or sheet names to export private final Set<String> sheetNumbers = new HashSet<>(); /** * Constructor for programatic use * * @param emptyCells * Should it export empty cells * @param allSheets * Should it export all sheets */ public E2xCmdline(final boolean emptyCells, final boolean allSheets) { this.exportAllSheets = allSheets; this.exportEmptyCells = emptyCells; this.exportSingleFile = true; this.transform = false; this.templateName = null; this.outputExtension = ".xml"; } /** * Constructor for command line use * * @param cmd * the parameters ready parsed * @param options * the expected options */ public E2xCmdline(final CommandLine cmd, final Options options) { boolean canContinue = true; if (cmd.hasOption("w")) { this.exportAllSheets = false; final String[] sheetNums = cmd.getOptionValue("w").trim().split(","); for (int i = 0; i < sheetNums.length; i++) { this.sheetNumbers.add(sheetNums[i].trim().toLowerCase()); } } else { this.exportAllSheets = true; } if (cmd.hasOption("i")) { this.inputFileName = cmd.getOptionValue("i"); } else { canContinue = false; } if (cmd.hasOption("o")) { // Strip .xml since we need the sheet number // before the .xml entry if we have more than one sheet String outputFileNameCandidate = cmd.getOptionValue("o"); int lastDot = outputFileNameCandidate.lastIndexOf("."); this.outputExtension = (lastDot < 1) ? ".xml" : outputFileNameCandidate.substring(lastDot); this.outputFileName = outputFileNameCandidate.substring(0, lastDot); } else { // We add the .xml entry later anyway this.outputFileName = this.inputFileName; this.outputExtension = ".xml"; } if (cmd.hasOption("t")) { this.transform = true; this.templateName = cmd.getOptionValue("t"); } else { this.transform = false; this.templateName = null; } this.exportEmptyCells = cmd.hasOption("e"); this.exportSingleFile = cmd.hasOption("s"); if (!canContinue) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("excel2xml", options); System.exit(1); } if (this.exportEmptyCells) { System.out.println("- Generating empty cells"); } if (this.exportSingleFile) { System.out.println("- Output to single file"); } else { System.out.println("- Output to one file per sheet"); } if (this.exportAllSheets) { System.out.println("- Exporting all sheets"); } else { System.out.println("- Exporting selected sheets"); } if (this.transform) { System.out.println("- transforming using " + String.valueOf(this.templateName)); } } /** * Parses an inputstream containin xlsx into an outputStream containing XML * * @param inputStream * the source * @param outputStream * the result * @throws IOException * @throws XMLStreamException */ public void parse(final InputStream inputStream, final OutputStream outputStream) throws IOException, XMLStreamException { final XSSFWorkbook workbook = new XSSFWorkbook(inputStream); final XMLStreamWriter out = this.getXMLWriter(outputStream); out.writeStartDocument(); out.writeStartElement("workbook"); final int sheetCount = workbook.getNumberOfSheets(); for (int i = 0; i < sheetCount; i++) { final XSSFSheet sheet = workbook.getSheetAt(i); try { this.export(sheet, out); } catch (FileNotFoundException | XMLStreamException | FactoryConfigurationError e) { e.printStackTrace(); } } out.writeEndElement(); out.writeEndDocument(); out.close(); workbook.close(); } /** * Exports a single sheet to a file * * @param sheet * @throws FactoryConfigurationError * @throws XMLStreamException * @throws UnsupportedEncodingException * @throws FileNotFoundException */ private void export(final XSSFSheet sheet, final XMLStreamWriter out) throws XMLStreamException, FactoryConfigurationError, FileNotFoundException { boolean isFirst = true; final Map<String, String> columns = new HashMap<>(); final String sheetName = sheet.getSheetName(); System.out.print(sheetName); out.writeStartElement("sheet"); out.writeAttribute("name", sheetName); final Iterator<Row> rowIterator = sheet.rowIterator(); while (rowIterator.hasNext()) { final Row row = rowIterator.next(); if (isFirst) { isFirst = false; this.writeFirstRow(row, out, columns); } else { this.writeRow(row, out, columns); } } out.writeEndElement(); System.out.println(".."); } private boolean exportThisSheet(final XSSFSheet sheet, final int i) { String name1 = sheet.getSheetName().trim().toLowerCase(); String name2 = String.valueOf(i); return this.sheetNumbers.contains(name1) || this.sheetNumbers.contains(name2); } private String getCellValue(final Cell cell) { return this.getCellValue(cell, -1); } private String getCellValue(final Cell cell, final int count) { String cellValue = null; final CellType ct = cell.getCellType(); switch (ct) { case STRING: cellValue = cell.getStringCellValue(); break; case NUMERIC: cellValue = String.valueOf(cell.getNumericCellValue()); break; case BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case BLANK: if (count > -1) { cellValue = "BLANK" + String.valueOf(count); } break; case FORMULA: final CellType cacheCellType = cell.getCachedFormulaResultType(); { switch (cacheCellType) { case STRING: cellValue = cell.getStringCellValue(); break; case NUMERIC: cellValue = String.valueOf(cell.getNumericCellValue()); break; case BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; default: cellValue = cell.getCellFormula(); } } break; default: cellValue = null; } return cellValue; } /** * Create an XML Streamwriter to write into an output Stream * * @param outputStream * the steam e.g. a file * @return the StreamWriter * @throws XMLStreamException * @throws UnsupportedEncodingException */ private XMLStreamWriter getXMLWriter(final OutputStream outputStream) throws UnsupportedEncodingException, XMLStreamException { final XMLOutputFactory factory = XMLOutputFactory.newInstance(); final XMLStreamWriter out = factory.createXMLStreamWriter(new OutputStreamWriter(outputStream, "utf-8")); return out; } private XMLStreamWriter getXMLWriter(final XSSFSheet sheet) throws FileNotFoundException, UnsupportedEncodingException, XMLStreamException { final String outputSheetName = this.outputFileName + "." + sheet.getSheetName() + this.outputExtension; final File outFile = new File(outputSheetName); if (outFile.exists()) { outFile.delete(); } final OutputStream outputStream = new TransformingOutputStream(new FileOutputStream(outFile), this.templateName); return this.getXMLWriter(outputStream); } /** * Reads the input file and exports all sheets * * @throws IOException * @throws FactoryConfigurationError * @throws XMLStreamException */ private void parse() throws IOException, XMLStreamException { final InputStream inputStream = new FileInputStream(new File(this.inputFileName)); final XSSFWorkbook workbook = new XSSFWorkbook(inputStream); final int sheetCount = workbook.getNumberOfSheets(); XMLStreamWriter out = null; if (this.exportSingleFile) { final String targetFile = this.outputFileName + E2xCmdline.OUTPUT_EXTENSION; System.out.println("Exporting Workbook to " + targetFile); final File outFile = new File(targetFile); if (outFile.exists()) { outFile.delete(); } out = this.getXMLWriter(new FileOutputStream(outFile)); out.writeStartDocument(); out.writeStartElement("workbook"); } for (int i = 0; i < sheetCount; i++) { try { final XSSFSheet sheet = workbook.getSheetAt(i); if (this.exportAllSheets || this.exportThisSheet(sheet, i)) { if (!this.exportSingleFile) { out = this.getXMLWriter(sheet); out.writeStartDocument(); } this.export(sheet, out); } } catch (final Exception e) { e.printStackTrace(); } finally { if (!this.exportSingleFile) { out.writeEndDocument(); out.close(); } } } // Close the XML if still open if (this.exportSingleFile) { out.writeEndElement(); out.writeEndDocument(); } if (out != null) { out.close(); } workbook.close(); inputStream.close(); } /** * Writes out an XML cell based on coordinates and provided value * * @param row * the row index of the cell * @param col * the column index * @param cellValue * value of the cell, can be null for an empty cell * @param out * the XML output stream * @param columns * the Map with column titles */ private void writeAnyCell(final int row, final int col, final String cellValue, final XMLStreamWriter out, final Map<String, String> columns) { try { out.writeStartElement("cell"); final String colNum = String.valueOf(col); out.writeAttribute("row", String.valueOf(row)); out.writeAttribute("col", colNum); if (columns.containsKey(colNum)) { out.writeAttribute("title", columns.get(colNum)); } if (cellValue != null) { if (cellValue.contains("<") || cellValue.contains(">")) { out.writeCData(cellValue); } else { out.writeCharacters(cellValue); } } else { out.writeAttribute("empty", "true"); } out.writeEndElement(); } catch (final XMLStreamException e) { e.printStackTrace(); } } /** * Writes out an XML cell based on an Excel cell's actual value * * @param cell * The Excel cell * @param out * the output stream * @param columns * the Map with column titles */ private void writeCell(final Cell cell, final XMLStreamWriter out, final Map<String, String> columns) { final String cellValue = this.getCellValue(cell); final int col = cell.getColumnIndex(); final int row = cell.getRowIndex(); this.writeAnyCell(row, col, cellValue, out, columns); } /** * Gets field names from column titles and writes the titles element with * columns out * * @param row * the row to parse * @param columns * the map with the values */ private void writeFirstRow(final Row row, final XMLStreamWriter out, final Map<String, String> columns) { final Iterator<Cell> cellIterator = row.iterator(); int count = 0; try { out.writeStartElement("columns"); while (cellIterator.hasNext()) { final Cell cell = cellIterator.next(); // Generate empty headers if required if (this.exportEmptyCells) { final int columnIndex = cell.getColumnIndex(); while (count < columnIndex) { final String noLabel = "NoLabel" + String.valueOf(count); columns.put(String.valueOf(count), noLabel); out.writeStartElement("column"); out.writeAttribute("empty", "true"); out.writeAttribute("col", String.valueOf(count)); out.writeAttribute("title", noLabel); out.writeEndElement(); count++; } } final String cellValue = this.getCellValue(cell, count); if (cellValue != null) { columns.put(String.valueOf(cell.getColumnIndex()), cellValue); out.writeStartElement("column"); out.writeAttribute("title", cellValue); out.writeAttribute("col", String.valueOf(cell.getColumnIndex())); out.writeEndElement(); } count++; } out.writeEndElement(); } catch (final XMLStreamException e) { e.printStackTrace(); } } private void writeRow(final Row row, final XMLStreamWriter out, final Map<String, String> columns) { try { final int rowIndex = row.getRowNum(); out.writeStartElement("row"); final String rowNum = String.valueOf(rowIndex); out.writeAttribute("row", rowNum); int count = 0; final Iterator<Cell> cellIterator = row.iterator(); while (cellIterator.hasNext()) { final Cell cell = cellIterator.next(); final int columnIndex = cell.getColumnIndex(); if (this.exportEmptyCells) { while (count < columnIndex) { this.writeAnyCell(rowIndex, count, null, out, columns); count++; } } this.writeCell(cell, out, columns); count++; } out.writeEndElement(); } catch (final XMLStreamException e) { e.printStackTrace(); } } }
package com.leetcode.oj.recursion; import java.util.ArrayList; import java.util.List; // output all n-bit binary number with k set bits. public class KSetBitPermutation { public List<String> permRec(int n, int k) { List<String> res = new ArrayList<>(); if (n < k) return res; if (k == 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) sb.append('0'); res.add(sb.toString()); return res; } List<String> tmp = permRec(n - 1, k - 1); StringBuilder sb = new StringBuilder("1"); for (String s : tmp) { res.add(sb.append(s).toString()); sb.delete(1, sb.length()); } tmp = permRec(n - 1, k); sb = new StringBuilder("0"); for (String s : tmp) { res.add(sb.append(s).toString()); sb.delete(1, sb.length()); } return res; } public static void main(String[] args) { List<String> perm = new KSetBitPermutation().permRec(5, 2); System.out.println(perm); } }
package main.java.constant; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class ErrorConstants { public static String actionLogFile = ""; public static String errorLogFile = ""; public static String ConnectionException = "08"; private static String GetDateFormat() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); Date date = new Date(); return dateFormat.format(date); } public static String GetErrorLogFile() { if ("".equals(errorLogFile)) { errorLogFile = "Logs/[" + GetDateFormat() + "]ErrorLog.log"; } return errorLogFile; } public static String GetActionLogFile() { if ("".equals(actionLogFile)) { errorLogFile = "Logs/[" + GetDateFormat() + "]ActionLog.log"; } return errorLogFile; } }
package com.adityathebe.bitcoin.script; import com.adityathebe.bitcoin.utils.Utils; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; import static com.adityathebe.bitcoin.script.ScriptOpCodes.*; public class Script { protected List<ScriptChunk> chunks; protected byte[] program; Script(List<ScriptChunk> chunks) { this.chunks = new ArrayList<>(chunks); } public Script(byte[] programBytes) { program = programBytes; parse(programBytes); } private void parse(byte[] program) { chunks = new ArrayList<>(); ByteArrayInputStream bis = new ByteArrayInputStream(program); while (bis.available() > 0) { // Each byte corresponds to an opCOde int opcode = bis.read(); long numBytesOfData = -1; if (opcode >= 0 && opcode < OP_PUSHDATA1) { numBytesOfData = opcode; } else if (opcode == OP_PUSHDATA1) { numBytesOfData = bis.read(); } else if (opcode == OP_PUSHDATA2) { numBytesOfData = bis.read(); numBytesOfData += bis.read(); } else if (opcode == OP_PUSHDATA4) { numBytesOfData = bis.read(); numBytesOfData += bis.read(); numBytesOfData += bis.read(); numBytesOfData += bis.read(); } ScriptChunk chunk; if (numBytesOfData == -1) { chunk = new ScriptChunk(opcode, null); } else { byte[] data = new byte[(int) numBytesOfData]; bis.read(data, 0, (int) numBytesOfData); chunk = new ScriptChunk(opcode, data); } chunks.add(chunk); } } public static void main(String[] args) { String scriptPubKey = "76a91443849383122ebb8a28268a89700c9f723663b5b888ac"; byte[] program = Utils.hexToBytes(scriptPubKey); Script s = new Script(program); for (ScriptChunk c : s.chunks) { System.out.println(c.opcode); if (c.data != null) { System.out.println(Utils.bytesToHex(c.data)); } } } // /** // * Exposes the script interpreter. Normally you should not use this directly, instead use // * {@link TransactionInput#verify(TransactionOutput)} or // * {@link Script#correctlySpends(Transaction, int, TransactionWitness, Coin, Script, Set)}. This method // * is useful if you need more precise control or access to the final state of the stack. This interface is very // * likely to change in future. // */ // public static void executeScript(@Nullable Transaction txContainingThis, long index, // Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags) throws ScriptException { // int opCount = 0; // int lastCodeSepLocation = 0; // // LinkedList<byte[]> altstack = new LinkedList<>(); // LinkedList<Boolean> ifStack = new LinkedList<>(); // // int nextLocationInScript = 0; // for (ScriptChunk chunk : script.chunks) { // boolean shouldExecute = !ifStack.contains(false); // int opcode = chunk.opcode; // nextLocationInScript += chunk.size(); // // if (OP_0 <= opcode && opcode <= OP_PUSHDATA4) { // if (opcode == OP_0) // stack.add(new byte[]{}); // else // stack.add(chunk.data); // } else { // // switch (opcode) { // case OP_DUP: // if (stack.size() < 1) // throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_DUP on an empty stack"); // stack.add(stack.getLast()); // break; // case OP_EQUALVERIFY: // if (stack.size() < 2) // throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_EQUALVERIFY on a stack with size < 2"); // if (!Arrays.equals(stack.pollLast(), stack.pollLast())) // throw new ScriptException(ScriptError.SCRIPT_ERR_EQUALVERIFY, "OP_EQUALVERIFY: non-equal data"); // break; // case OP_HASH160: // if (stack.size() < 1) // throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_HASH160 on an empty stack"); // stack.add(Utils.sha256hash160(stack.pollLast())); // break; // case OP_CHECKSIG: // if (txContainingThis == null) // throw new IllegalStateException("Script attempted signature check but no tx was provided"); // executeCheckSig(txContainingThis, (int) index, script, stack, lastCodeSepLocation, opcode, verifyFlags); // break; // // default: // throw new ScriptException(ScriptError.SCRIPT_ERR_BAD_OPCODE, "Script used a reserved or disabled opcode: " + opcode); // } // } // // if (stack.size() + altstack.size() > MAX_STACK_SIZE || stack.size() + altstack.size() < 0) // throw new ScriptException(ScriptError.SCRIPT_ERR_STACK_SIZE, "Stack size exceeded range"); // } // // if (!ifStack.isEmpty()) // throw new ScriptException(ScriptError.SCRIPT_ERR_UNBALANCED_CONDITIONAL, "OP_IF/OP_NOTIF without OP_ENDIF"); // } }
package Day4.UnitTesting; /** * Created by student on 06-May-16. */ public class Cafe { private int beansInStock = 0; private int milkInStock = 0; public void restockBeans(int beansInGrams) { beansInStock += beansInGrams; } public void restockMilk(int milkInMilileters) { milkInStock += milkInMilileters; } public int getBeansInStock(){ return beansInStock; } public int getMilkInStock(){ return milkInStock; } public Coffee brewCoffee(CoffeeType coffeeType) { return brewCoffee(coffeeType,1); } public Coffee brewCoffee(CoffeeType coffeeType,int quantity) { int requiredBeans = coffeeType.getRequiredBeans() * quantity; int requiredMilk = coffeeType.getRequiredMilk() * quantity; if(requiredBeans > beansInStock || requiredMilk > getMilkInStock()) { throw new IllegalStateException("Not Enough stock to brea man!"); } beansInStock -= requiredBeans; milkInStock -= requiredMilk; return new Coffee(coffeeType,requiredBeans,requiredMilk); } }
package sch.frog.calculator.compile.semantic; import sch.frog.calculator.compile.semantic.result.IResult; import sch.frog.calculator.exception.CalculatorException; public class NoValueException extends CalculatorException { private static final long serialVersionUID = 1L; public NoValueException(IResult.ResultType resultType){ super("no value fetch from this result. result type : " + resultType.name()); } }
package app.akeorcist.deviceinformation.fragment.main; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import com.inthecheesefactory.thecheeselibrary.fragment.support.v4.app.StatedFragment; import com.pnikosis.materialishprogress.ProgressWheel; import com.squareup.otto.Subscribe; import app.akeorcist.deviceinformation.R; import app.akeorcist.deviceinformation.adapter.HardwearCardAdapter; import app.akeorcist.deviceinformation.event.ViewEvent; import app.akeorcist.deviceinformation.provider.BusProvider; import app.akeorcist.deviceinformation.utility.AnimateUtils; /** * A simple {@link Fragment} subclass. */ public class HardwareFragment extends StatedFragment { private Activity activity; private RecyclerView rvHardwareCard; private ProgressWheel progressWheel; public static Fragment newInstance(boolean fromSwitcher) { Fragment fragment = new HardwareFragment(); Bundle bundle = new Bundle(); bundle.putBoolean("from_switcher", fromSwitcher); fragment.setArguments(bundle); return fragment; } public HardwareFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_hardware, container, false); progressWheel = (ProgressWheel) rootView.findViewById(R.id.progress_wheel); rvHardwareCard = (RecyclerView) rootView.findViewById(R.id.rv_hardware_card); int column = getResources().getInteger(R.integer.hardware_card_column); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(column, StaggeredGridLayoutManager.VERTICAL); rvHardwareCard.setLayoutManager(layoutManager); if(savedInstanceState == null) { rvHardwareCard.setVisibility(View.GONE); progressWheel.setVisibility(View.VISIBLE); boolean fromSwitcher = getArguments().getBoolean("from_switcher", false); if(fromSwitcher) { initView(true); } } setHasOptionsMenu(true); return rootView; } @Override public void onSaveState(Bundle outState) { super.onSaveState(outState); } @Override public void onRestoreState(Bundle savedInstanceState) { super.onRestoreState(savedInstanceState); progressWheel.setVisibility(View.GONE); rvHardwareCard.setVisibility(View.VISIBLE); initView(false); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activity = getActivity(); BusProvider.getInstance().register(this); } @Override public void onDestroy() { super.onDestroy(); BusProvider.getInstance().unregister(this); } @Subscribe public void loadView(ViewEvent event) { if(ViewEvent.EVENT_MENU_SELECTED.equals(event.getEventState())) { initView(true); } } private void initView(boolean fromFirstTime) { RecyclerView.Adapter adapter = new HardwearCardAdapter(activity); rvHardwareCard.setAdapter(adapter); if(fromFirstTime) { animateView(); } } private void animateView() { AnimateUtils.fadeOutAnimate(progressWheel, new AnimateUtils.OnProgressGoneListener() { @Override public void onGone() { AnimateUtils.fadeInAnimateWithZero(rvHardwareCard); } }); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); } }
package com.sh.base.sort; /** * 计数排序 * https://www.cnblogs.com/developerY/p/3166462.html * @Auther: bjshaohang * @Date: 2019/1/25 */ public class c1CountingSort { public static void main(String[] args) { int[] a = {2,5,3,0,2,3,04,3}; int k = 5; int[] b = sort(a,k); for (int s: b) { System.out.println(s); } } public static int[] sort(int[] a, int k){ int [] c = new int [k+1]; int length = a.length; int sum = 0; for (int i = 0; i< length; i++){ c[a[i]] +=1; } for(int i = 0; i<k+1; i++){ c[i] += sum; sum = c[i]; } int [] b = new int[length]; for(int i = length-1; i>=0;i--){ b[c[a[i]]-1]=a[i]; c[a[i]]--; } return b; } }
package dk.webbies.tscreate.paser.AST; import com.google.javascript.jscomp.parsing.parser.util.SourceRange; import dk.webbies.tscreate.paser.ExpressionVisitor; import java.util.List; /** * Created by Erik Krogh Kristensen on 06-09-2015. */ public class MethodCallExpression extends Expression { private final MemberExpression memberExpression; private final List<Expression> arguments; public MethodCallExpression(SourceRange loc, MemberExpression memberExpression, List<Expression> arguments) { super(loc); this.memberExpression = memberExpression; this.arguments = arguments; } public MemberExpression getMemberExpression() { return memberExpression; } public List<Expression> getArgs() { return arguments; } @Override public <T> T accept(ExpressionVisitor<T> visitor) { return visitor.visit(this); } }
package com.redsun.platf.dao.tag.easyui.model.common; import com.redsun.platf.entity.account.UserAccount; import org.springframework.security.core.userdetails.User; import java.io.Serializable; public class SessionInfo implements Serializable { private UserAccount user; public UserAccount getUser() { return user; } public void setUser(UserAccount user) { this.user = user; } }
package controlador; import Juego.DragonAlgoBall; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Label; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import modelo.Personaje; import modelo.excepciones.AtaqueInvalido; import modelo.turnos.Turno; import vista.CanvasTablero; import vista.ContenedorPrincipal; public class BotonAtacarBasicoHandler implements EventHandler<ActionEvent> { private Turno turno; private ContenedorPrincipal contenedor; private final DragonAlgoBall juego; private CanvasTablero canvasTablero; private Personaje atacante; private Personaje enemigo; public BotonAtacarBasicoHandler(DragonAlgoBall juego, ContenedorPrincipal contenedor) { this.juego = juego; this.contenedor =contenedor; this.canvasTablero = contenedor.getTablero(); this.turno = juego.getTurnoActual(); } @Override public void handle(ActionEvent actionEvent) { this.atacante = this.turno.getPersonajeatacante(); this.enemigo = this.turno.getPersonajeAtacado(); try{ this.atacante.atacarConBasico(enemigo); this.contenedor.dibujarTablero(); if(turno.verificarAccionesTurno()){ this.contenedor.cambioDeTurno(); return; } this.canvasTablero.setOnMousePressed(new SeleccionarPersonajeHandler(this.juego,this.contenedor)); this.contenedor.setBotoneraMovimiento(true); this.contenedor.setContenedorIzquierda(true); this.contenedor.actualizarBotones(turno); } catch(AtaqueInvalido p){ if(turno.verificarAccionesTurno()){ this.contenedor.cambioDeTurno(); } Label etiqueta = new Label(); etiqueta.setText("Ataque invalido: Enemigo fuera del alcance"); etiqueta.setFont(Font.font("courier new", FontWeight.SEMI_BOLD, 14)); etiqueta.setTextFill(Color.WHITE); this.contenedor.actualizarConsola(etiqueta); } } }
package com.ssafy.entity; import java.util.ArrayList; import java.util.List; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; @Entity @NoArgsConstructor @RequiredArgsConstructor @Getter @Setter @Table(name="hashtag") public class Hashtag { @Id @GeneratedValue(strategy = GenerationType.TABLE) private Long id; @NonNull private String name; @JsonIgnore @OneToMany(mappedBy="HASHTAG", fetch = FetchType.LAZY) private List<Tagging> taggings = new ArrayList<Tagging>(); }
package com.sailaminoak.saiii; public class Notes { private String noteText; public Notes(){ } public void setText(String noteText) { this.noteText =noteText; } public String getText() { return noteText; } }
package com.study.repository; import com.study.entity.Position; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * @author changxu13 * @date 2020/10/17 16:31 */ public interface PositionRepository extends JpaRepository<Position, Integer> { @Query(nativeQuery = true, value = "select p.id, p.name, p.salary, p.city, pd.description from position p left join position_detail pd on p.id = pd.pid where p.id=:id") Object findPositionById(@Param("id") Long id); }
/* Delete Node at a given position in a linked list head pointer input could be NULL as well for empty list Node is defined as class Node { int data; Node next; } */ // This is a "method-only" submission. // You only need to complete this method. Node Delete(Node head, int position) { // Complete this method int length = 0; Node temp = head; while(temp!=null) { temp = temp.next; length++; } if(length==1 || position==0) return deleteAtHead(head); else if(length == position-1) return deleteAtLast(head); else return deleteInBetween(head,position); } Node deleteAtHead(Node head) { Node temp = head; if(head == null) return null; else { head = temp.next; } return head; } Node deleteAtLast(Node head) { Node temp = head; while(temp.next!=null) { temp = temp.next; } temp.next = null; return head; } Node deleteInBetween(Node head,int position) { Node temp = head; for (int i=0; temp!=null && i<position-1; i++) temp = temp.next; temp.next = temp.next.next; return head; }
public class Record { private String MNOIMSI; private String MNOMSISDN; private String ADDON_ACTION; public Record(){}; public Record(String mNOIMSI, String mNOMSISDN, String aDDON_ACTION) { super(); MNOIMSI = mNOIMSI; MNOMSISDN = mNOMSISDN; ADDON_ACTION = aDDON_ACTION; } public String getMNOIMSI() { return MNOIMSI; } public void setMNOIMSI(String mNOIMSI) { MNOIMSI = mNOIMSI; } public String getMNOMSISDN() { return MNOMSISDN; } public void setMNOMSISDN(String mNOMSISDN) { MNOMSISDN = mNOMSISDN; } public String getADDON_ACTION() { return ADDON_ACTION; } public void setADDON_ACTION(String aDDON_ACTION) { ADDON_ACTION = aDDON_ACTION; } }
package com.example.bookspace.adapters; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.res.Resources; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.example.bookspace.R; import com.example.bookspace.model.RetrofitClient; import com.example.bookspace.model.books.SearchBook; import java.util.List; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SearchBookAdapter extends BaseAdapter { private Context mContextTop; private List<SearchBook> mBooksListTop; ImageButton addButton; public SearchBookAdapter(Context mContext, List<SearchBook> mBooksList){ this.mContextTop = mContext; this.mBooksListTop = mBooksList; } @Override public int getCount() { return mBooksListTop.size(); } @Override public Object getItem(int position) { return mBooksListTop.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View row2 = View.inflate(mContextTop, R.layout.row2, null); TextView myTitle = row2.findViewById(R.id.topBookTitle); TextView myAuthor = row2.findViewById(R.id.topBookAuthor); TextView myGenre = row2.findViewById(R.id.topBookGenre); myTitle.setText(mBooksListTop.get(position).getTitle()); myAuthor.setText(mBooksListTop.get(position).getAuthor()); myGenre.setText(mBooksListTop.get(position).getGenre()); addButton = row2.findViewById(R.id.addbtn1); addButton.setTag(mBooksListTop.get(position).getId()); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { SharedPreferences prefs = v.getContext().getSharedPreferences("AppPreferences", Context.MODE_PRIVATE); final String token = prefs.getString("token", ""); AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()); builder.setTitle(R.string.bookChoose); final Resources res = mContextTop.getResources(); String[] items= {res.getString(R.string.bookRead), res.getString(R.string.bookReading), res.getString(R.string.bookWillRead)}; builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case 0: Call<ResponseBody> addBook = RetrofitClient .getInstance() .getBookSpaceAPI() .addBook("Bearer " + token, mBooksListTop.get(position).getId(), "DN"); addBook.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Toast toast = Toast.makeText(v.getContext(),res.getString(R.string.statusToRead),Toast.LENGTH_SHORT); toast.show(); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); break; case 1: Call<ResponseBody> addBook2 = RetrofitClient .getInstance() .getBookSpaceAPI() .addBook("Bearer " + token, mBooksListTop.get(position).getId(), "IP"); addBook2.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Toast toast = Toast.makeText(v.getContext(),res.getString(R.string.statusToReading),Toast.LENGTH_SHORT); toast.show(); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); break; case 2: Call<ResponseBody> addBook3 = RetrofitClient .getInstance() .getBookSpaceAPI() .addBook("Bearer " + token, mBooksListTop.get(position).getId(), "WR"); addBook3.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Toast toast = Toast.makeText(v.getContext(),res.getString(R.string.statusToWillRead),Toast.LENGTH_SHORT); toast.show(); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); break; } } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }); row2.setTag(mBooksListTop.get(position).getId()); return row2; } @Override public boolean isEnabled(int position){ return true; } }
package io.chark.food.app.moderate.comment; import io.chark.food.app.account.AccountService; import io.chark.food.app.administrate.audit.AuditService; import io.chark.food.app.article.ArticleService; import io.chark.food.app.comment.CommentService; import io.chark.food.app.thread.ThreadService; import io.chark.food.domain.article.Article; import io.chark.food.domain.comment.Comment; import io.chark.food.domain.comment.CommentRepository; import io.chark.food.domain.thread.Thread; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date; import java.util.List; import java.util.Optional; @Service public class CommentModerationService { private final CommentRepository commentRepository; private final AuditService auditService; private final CommentService commentService; private final AccountService accountService; private final ArticleService articleService; private final ThreadService threadService; private static final Logger LOGGER = LoggerFactory.getLogger(CommentModerationService.class); @Autowired public CommentModerationService(CommentRepository commentRepository, AuditService auditService, AccountService accountService, CommentService commentService, ArticleService articleService, ThreadService threadService) { this.commentRepository = commentRepository; this.auditService = auditService; this.accountService = accountService; this.commentService = commentService; this.articleService = articleService; this.threadService = threadService; } public List<Comment> getComments() { return commentRepository.findAll(); } public Comment getComment(long id) { return commentRepository.findOne(id); } public Optional<Comment> saveComment(long id, Comment commentDetails) { Optional<Comment> optional; if (id <= 0) { optional = commentService.register( commentDetails.getAccount(), commentDetails.getText(), commentDetails.isHidden() ); } else { optional = Optional.of(commentRepository.findOne(id)); } if (!optional.isPresent()) { return Optional.empty(); } optional = commentService.update(optional.get(), commentDetails); // Update other details editable only by admins. Comment comment = optional.get(); comment.setAccount(accountService.getAccount()); comment.setText(commentDetails.getText()); comment.setEditDate(new Date()); comment.setHidden(commentDetails.isHidden()); try { comment = commentRepository.save(comment); LOGGER.debug("Saved Comment{id={}}", comment.getId()); auditService.debug("%s Comment with id: %d via admin panel", id <= 0 ? "Created new" : "Updated", comment.getId()); return Optional.of(comment); } catch (DataIntegrityViolationException e) { LOGGER.error("Could not save comment", e); auditService.error("Failed to save comment"); return Optional.empty(); } } public void delete(long id) { Comment comment = commentRepository.findOne(id); for (Article a : articleService.getArticles()) { a.removeComment(comment); } for (Thread t : threadService.getThreads()) { t.removeComment(comment); } commentRepository.delete(comment); auditService.info("Deleted comment with id: %d", id); } }
package cn.test.demo03; //匿名内部类,简化了以往的实现类,重写方法,new对象过程。 public class Test2 { public static void main(String[] args) { /* * 必须有继承父类,or,实现接口,否则无法多态 * * 格式: * new 接口或者父类(){ * 重写抽象方法 * }; * 从new开始,到分号结束,创建了接口的实现类对象 */ new Smoking() { public void smoking() { System.out.println("xiyan"); } }.smoking(); } }
package oops; abstract public class Person1 { String name; int age; String gender; abstract void name(); abstract void age(); abstract void gender(); } abstract class Ramesh extends Person1 { abstract void age(); abstract void gender(); } class Suresh extends Ramesh { void name() { System.out.println("name is vishal rana"); } void gender() { System.out.println("male"); } void age() { System.out.println("age is 12 "); } }
package com.example.qunxin.erp.activity; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.example.qunxin.erp.R; import com.example.qunxin.erp.UserBaseDatus; import com.example.qunxin.erp.modle.KehuDatus; import org.json.JSONException; import java.util.Map; public class EditKehuActivity extends AppCompatActivity implements View.OnClickListener { View backBtn; View saveBtn; View deleteBtn; TextView kehumingchengText; TextView lianxirenText; TextView lianxidianhuaText; TextView bianhaoText; TextView youxiangText; TextView chuanzhenText; TextView lianxidizhiText; TextView fuzerenText; //TextView qichuqinakuanText; TextView remarksText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_kehu); initView(); } String id; void initView(){ kehumingchengText=findViewById(R.id.edit_kehu_kehumingcheng); lianxirenText=findViewById(R.id.edit_kehu_lianxiren); lianxidianhuaText=findViewById(R.id.edit_kehu_lianxirendianhua); bianhaoText=findViewById(R.id.edit_kehu_bianhao); youxiangText=findViewById(R.id.edit_kehu_youxiang); lianxidizhiText=findViewById(R.id.edit_kehu_lianxidizhi); fuzerenText=findViewById(R.id.edit_kehu_fuzeren); //qichuqinakuanText=findViewById(R.id.edit_kehu_qichuqiankuan); remarksText=findViewById(R.id.edit_kehu_remark); backBtn=findViewById(R.id.edit_kehu_back); saveBtn=findViewById(R.id.edit_kehu_save); deleteBtn=findViewById(R.id.btn_delete); backBtn.setOnClickListener(this); saveBtn.setOnClickListener(this); deleteBtn.setOnClickListener(this); Intent intent=getIntent(); id=intent.getStringExtra("id"); initModel(); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.edit_kehu_back: finish(); break; case R.id.edit_kehu_save: save(); break; case R.id.btn_delete: delete(id); break; } } void initModel(){ Intent intent=getIntent(); kehumingchengText.setText(intent.getStringExtra("kehumingcheng")); lianxirenText.setText(intent.getStringExtra("lianxiren")); lianxidianhuaText.setText(intent.getStringExtra("lianxidianhua")); bianhaoText.setText(intent.getStringExtra("bianhao")); youxiangText.setText(intent.getStringExtra("youxiang")); lianxidizhiText.setText(intent.getStringExtra("lianxidizhi")); fuzerenText.setText(intent.getStringExtra("fuzeren")); //qichuqinakuanText.setText(intent.getStringExtra("qichuqiankuan")); remarksText.setText(intent.getStringExtra("remarks")); } void save(){ new Thread(new Runnable() { @Override public void run() { saveKehu(); } }).start(); } void saveKehu(){ String custName=kehumingchengText.getText().toString(); String signa=UserBaseDatus.getInstance().getSign(); String contactPeople=lianxirenText.getText().toString(); String phone=lianxidianhuaText.getText().toString(); String localtion=lianxidizhiText.getText().toString(); String qxLeader=fuzerenText.getText().toString(); String userId=UserBaseDatus.getInstance().userId; String id=this.id; final String stringData = "custName="+custName+"&&signa="+signa+"&&contactPeople="+contactPeople+"&&phone="+phone+ "&&localtion="+localtion+"&&qxLeader="+qxLeader+"&&userId="+userId+"&&id="+id; final String contentType = "application/x-www-form-urlencoded"; final String url=UserBaseDatus.getInstance().url+"api/custs/edit"; Map map=UserBaseDatus.getInstance().isSuccessPost(url, stringData, contentType); if((boolean)(map.get("isSuccess"))){ finish(); } } void delete(final String id){ new Thread(new Runnable() { @Override public void run() { final String strUrl = UserBaseDatus.getInstance().url+"api/custs/remove"; final String strData = "id="+id+"&&signa="+UserBaseDatus.getInstance().getSign(); final String contentType = "application/x-www-form-urlencoded"; Map map=UserBaseDatus.getInstance().isSuccessPost(strUrl, strData, contentType); if ((boolean)(map.get("isSuccess"))) { Intent intent=new Intent(EditKehuActivity.this,MainActivity.class); startActivity(intent); } } }).start(); } }
package com.example.parcial3capas.repositories; import com.example.parcial3capas.domain.CentroEscolar; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface CentroEscolarRepo extends JpaRepository<CentroEscolar, Integer> { @Query(nativeQuery=true, value="SELECT * FROM public.centro_escolar c WHERE c.c_centro_escolar = :ID") CentroEscolar findByCodigoC(Integer ID); @Query(nativeQuery=true, value="SELECT * FROM public.centro_escolar WHERE c_municipio = :ID") List<CentroEscolar> findByCodigoMunicipio(Integer ID); List<CentroEscolar> findAllByOrderByCodigoCentroAsc(); }
package ru.vyarus.dropwizard.guice.module.yaml.report; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.vyarus.dropwizard.guice.module.installer.util.Reporter; import ru.vyarus.dropwizard.guice.module.lifecycle.GuiceyLifecycleAdapter; import ru.vyarus.dropwizard.guice.module.lifecycle.event.run.BeforeRunEvent; /** * Configuration bindings debug listener. Must be registered with * {@link ru.vyarus.dropwizard.guice.GuiceBundle.Builder#listen( *ru.vyarus.dropwizard.guice.module.lifecycle.GuiceyLifecycleListener...)}. * Could be configured to filter out not required info. * * @author Vyacheslav Rusakov * @see ru.vyarus.dropwizard.guice.GuiceBundle.Builder#printConfigurationBindings() * @see ru.vyarus.dropwizard.guice.GuiceBundle.Builder#printCustomConfigurationBindings() * @since 13.06.2018 */ public class DebugConfigBindings extends GuiceyLifecycleAdapter { private final Logger logger = LoggerFactory.getLogger(DebugConfigBindings.class); private final BindingsConfig config; public DebugConfigBindings(final BindingsConfig config) { this.config = config; } @Override protected void beforeRun(final BeforeRunEvent event) { final boolean customOnly = config.isShowCustomConfigOnly(); final String report; if (customOnly && event.getConfigurationTree().getRootTypes().size() == 1) { report = Reporter.NEWLINE + Reporter.NEWLINE + Reporter.TAB + "No custom bindings"; } else { report = new ConfigBindingsRenderer(event.getConfigurationTree()).renderReport(config); } logger.info("Available {}configuration bindings = {}", customOnly ? "custom " : "", report); } }
package tests; import java.io.*; /** * Created by Gauthier on 13/03/2017. */ public class LireSemaine { public static void main(String[] args) { FileReader flot; BufferedReader flotFiltre; int nbDeJour=0; try{ flot= new FileReader("semaine.txt"); flotFiltre= new BufferedReader(flot); String ligne= flotFiltre.readLine(); while(ligne!= null){ ligne = flotFiltre.readLine(); nbDeJour++; } System.out.println("Nombre de jours :" + nbDeJour); }catch (IOException e){ System.out.println("Ma vie est une longue semaine, et pour une fois j'attends pas le week-end"); } } }
package BasicProgram; public class FLName { public static void main(String[] args) { String firstName = "Nirbhay" ; String lastName = "sinha" ; System.out.println(firstName + " " + lastName); } }
package br.edu.fadam.estruturadedados.ead.aula3; public class ArvoreGenerica { NoGenerico noRaiz; }
package me.draimgoose.draimmenu.commandtags; import me.realized.tokenmanager.api.TokenManager; import me.draimgoose.draimmenu.DraimMenu; import me.draimgoose.draimmenu.api.GUI; import me.draimgoose.draimmenu.commandtags.tags.economy.BuyCommandTags; import me.draimgoose.draimmenu.commandtags.tags.economy.BuyItemTags; import me.draimgoose.draimmenu.commandtags.tags.economy.SellItemTags; import me.draimgoose.draimmenu.commandtags.tags.other.DataTags; import me.draimgoose.draimmenu.commandtags.tags.other.PlaceholderTags; import me.draimgoose.draimmenu.commandtags.tags.other.SpecialTags; import me.draimgoose.draimmenu.commandtags.tags.standard.BasicTags; import me.draimgoose.draimmenu.commandtags.tags.standard.BungeeTags; import me.draimgoose.draimmenu.commandtags.tags.standard.ItemTags; import me.draimgoose.draimmenu.openguimanager.GUIPosition; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; public class CommandTags { DraimMenu plugin; public CommandTags(DraimMenu pl) { this.plugin = pl; } public void runCommands(GUI gui, GUIPosition position,Player p, List<String> commands, ClickType click){ for (String command : commands) { command = plugin.commandTags.hasCorrectClick(command,click); if(command.equals("")){ continue; } PaywallOutput val = plugin.commandTags.commandPayWall(gui,p,command); if(val == PaywallOutput.Blocked){ break; } if(val == PaywallOutput.NotApplicable){ plugin.commandTags.runCommand(gui,position,p, command); } } } public void runCommands(GUI gui, GUIPosition position,Player p, List<String> commands){ for (String command : commands) { PaywallOutput val = plugin.commandTags.commandPayWall(gui,p,command); if(val == PaywallOutput.Blocked){ break; } if(val == PaywallOutput.NotApplicable){ plugin.commandTags.runCommand(gui,position,p, command); } } } public void runCommand(GUI gui, GUIPosition position,Player p, String commandRAW){ CommandTagEvent tags = new CommandTagEvent(plugin,gui,position,p,commandRAW); Bukkit.getPluginManager().callEvent(tags); if(!tags.commandTagUsed){ Bukkit.dispatchCommand(p, plugin.tex.placeholders(gui,position,p,commandRAW.trim())); } } public void registerBuiltInTags(){ plugin.getServer().getPluginManager().registerEvents(new BuyCommandTags(plugin), plugin); plugin.getServer().getPluginManager().registerEvents(new BuyItemTags(plugin), plugin); plugin.getServer().getPluginManager().registerEvents(new SellItemTags(plugin), plugin); plugin.getServer().getPluginManager().registerEvents(new DataTags(plugin), plugin); plugin.getServer().getPluginManager().registerEvents(new PlaceholderTags(plugin), plugin); plugin.getServer().getPluginManager().registerEvents(new SpecialTags(plugin), plugin); plugin.getServer().getPluginManager().registerEvents(new BasicTags(plugin), plugin); plugin.getServer().getPluginManager().registerEvents(new BungeeTags(plugin), plugin); plugin.getServer().getPluginManager().registerEvents(new ItemTags(plugin), plugin); } public String hasCorrectClick(String command, ClickType click){ try { switch(command.split("\\s")[0]){ case "right=":{ command = command.replace("right= ", ""); if (click != ClickType.RIGHT) { return ""; } break; } case "rightshift=":{ command = command.replace("rightshift= ", ""); if (click != ClickType.SHIFT_RIGHT) { return ""; } break; } case "left=":{ command = command.replace("left= ", ""); if (click != ClickType.LEFT) { return ""; } break; } case "leftshift=":{ command = command.replace("leftshift= ", ""); if (click != ClickType.SHIFT_LEFT) { return ""; } break; } case "middle=":{ command = command.replace("middle= ", ""); if (click != ClickType.MIDDLE) { return ""; } break; } } return command; } catch (Exception ex) { return ""; } } @SuppressWarnings("deprecation") public PaywallOutput commandPayWall(GUI gui, Player p, String command) { String tag = plugin.config.getString("config.format.tag") + " "; switch(command.split("\\s")[0]){ case "paywall=": { try { if (plugin.econ != null) { if (plugin.econ.getBalance(p) >= Double.parseDouble(command.split("\\s")[1])) { plugin.econ.withdrawPlayer(p, Double.parseDouble(command.split("\\s")[1])); plugin.tex.sendString(p,Objects.requireNonNull(plugin.config.getString("purchase.currency.success")).replaceAll("%dm-args%", command.split("\\s")[1])); return PaywallOutput.Passed; } else { plugin.tex.sendString(p,plugin.config.getString("purchase.currency.failure")); return PaywallOutput.Blocked; } } else { plugin.tex.sendString(p, tag + ChatColor.RED + "Для метода оплаты требуется Vault и Economy!"); return PaywallOutput.Blocked; } } catch (Exception buyc) { plugin.debug(buyc,p); plugin.tex.sendString(p, tag + plugin.config.getString("config.format.error") + " " + "команды: " + command); return PaywallOutput.Blocked; } } case "tokenpaywall=": { try { if (plugin.getServer().getPluginManager().isPluginEnabled("TokenManager")) { TokenManager api = (TokenManager) Bukkit.getServer().getPluginManager().getPlugin("TokenManager"); assert api != null; int balance = Integer.parseInt(Long.toString(api.getTokens(p).orElse(0))); if (balance >= Double.parseDouble(command.split("\\s")[1])) { api.removeTokens(p, Long.parseLong(command.split("\\s")[1])); plugin.tex.sendString(p,Objects.requireNonNull(plugin.config.getString("purchase.tokens.success")).replaceAll("%dm-args%", command.split("\\s")[1])); return PaywallOutput.Passed; } else { plugin.tex.sendString(p,plugin.config.getString("purchase.tokens.failure")); return PaywallOutput.Blocked; } } else { plugin.tex.sendString(p, tag + ChatColor.RED + "Чтобы это работало, требуется TokenManager!"); return PaywallOutput.Blocked; } } catch (Exception buyc) { plugin.debug(buyc,p); plugin.tex.sendString(p, tag + plugin.config.getString("config.format.error") + " " + "команды: " + command); return PaywallOutput.Blocked; } } case "item-paywall=": { List<ItemStack> cont = new ArrayList<>(Arrays.asList(plugin.inventorySaver.getNormalInventory(p))); try { short id = 0; if(command.split("\\s").length == 4){ id = Short.parseShort(command.split("\\s")[3]); } ItemStack sellItem; if(command.split("\\s").length == 2) { sellItem = plugin.itemCreate.makeCustomItemFromConfig(gui,GUIPosition.Top,gui.getConfig().getConfigurationSection("custom-item." + command.split("\\s")[1]), p, true, true, false); }else{ sellItem = new ItemStack(Objects.requireNonNull(Material.matchMaterial(command.split("\\s")[1])), Integer.parseInt(command.split("\\s")[2]), id); } PaywallOutput removedItem = PaywallOutput.Blocked; for(int f = 0; f < 36; f++){ if(cont.get(f) == null){ continue; } if(command.split("\\s").length == 2){ if(plugin.itemCreate.isIdentical(sellItem,cont.get(f))){ if (sellItem.getAmount() <= cont.get(f).getAmount()) { if (plugin.inventorySaver.hasNormalInventory(p)) { p.getInventory().getItem(f).setAmount(cont.get(f).getAmount() - sellItem.getAmount()); p.updateInventory(); } else { cont.get(f).setAmount(cont.get(f).getAmount() - sellItem.getAmount()); plugin.inventorySaver.inventoryConfig.set(p.getUniqueId().toString(), plugin.itemSerializer.itemStackArrayToBase64(cont.toArray(new ItemStack[0]))); } removedItem = PaywallOutput.Passed; break; } } }else { if (cont.get(f).getType() == sellItem.getType()) { if (sellItem.getAmount() <= cont.get(f).getAmount()) { if(plugin.inventorySaver.hasNormalInventory(p)){ p.getInventory().getItem(f).setAmount(cont.get(f).getAmount() - sellItem.getAmount()); p.updateInventory(); }else{ cont.get(f).setAmount(cont.get(f).getAmount() - sellItem.getAmount()); plugin.inventorySaver.inventoryConfig.set(p.getUniqueId().toString(), plugin.itemSerializer.itemStackArrayToBase64(cont.toArray(new ItemStack[0]))); } removedItem = PaywallOutput.Passed; break; } } } } if(removedItem == PaywallOutput.Blocked){ plugin.tex.sendString(p, tag + plugin.config.getString("purchase.item.failure")); }else{ plugin.tex.sendString(p,Objects.requireNonNull(plugin.config.getString("purchase.item.success")).replaceAll("%dm-args%",sellItem.getType().toString())); } return removedItem; } catch (Exception buyc) { plugin.debug(buyc,p); plugin.tex.sendString(p, tag + plugin.config.getString("config.format.error") + " " + "команды: " + command); return PaywallOutput.Blocked; } } case "xp-paywall=": { try { int balance = p.getLevel(); if (balance >= Integer.parseInt(command.split("\\s")[1])) { p.setLevel(p.getLevel() - Integer.parseInt(command.split("\\s")[1])); plugin.tex.sendString(p,Objects.requireNonNull(plugin.config.getString("purchase.xp.success")).replaceAll("%dm-args%", command.split("\\s")[1])); return PaywallOutput.Passed; } else { plugin.tex.sendString(p, plugin.config.getString("purchase.xp.failure")); return PaywallOutput.Blocked; } } catch (Exception buyc) { plugin.debug(buyc,p); plugin.tex.sendString(p, tag + plugin.config.getString("config.format.error") + " " + "команды: " + command); return PaywallOutput.Blocked; } } } return PaywallOutput.NotApplicable; } }
package online.lahloba.www.lahloba.data.model; import android.net.Uri; public class MainMenuItem { int arrange; String image; String title; String id; public MainMenuItem() { } public int getArrange() { return arrange; } public String getImage() { return image; } public String getTitle() { return title; } public String getId() { return id; } public void setArrange(int arrange) { this.arrange = arrange; } public void setImage(String image) { this.image = image; } public void setTitle(String title) { this.title = title; } public void setId(String id) { this.id = id; } }
package broker.three.server; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.ArrayList; import broker.three.exception.DuplicateSSNException; import broker.three.exception.InvalidTransactionException; import broker.three.exception.RecordNotFoundException; import broker.three.shares.Command; import broker.three.shares.Result; import broker.three.vo.CustomerRec; import broker.three.vo.StockRec; public class JuryThread extends Thread{ private Socket s; private Database db; private Command cmd; private ObjectInputStream ois; private ObjectOutputStream oos; public JuryThread(Socket s, Database db) { try { this.s=s; this.db = db; ois = new ObjectInputStream(s.getInputStream()); oos = new ObjectOutputStream(s.getOutputStream()); } catch(Exception e) { e.printStackTrace(); } }// 생성자 public void run() { System.out.println("Jury running...."); while (true) { //1. 도시락 받는다 try { cmd = (Command)ois.readObject(); System.out.println("cmd...jury reading...."); }catch(Exception e) { e.printStackTrace(); } //2. 열어본다. (Data Unpack | getter) int commValue = cmd.getCommandValue(); //10~90 String[] args = cmd.getArgs(); Result r = cmd.getResults(); // switch(commValue) { // 정수, 스트링 | 실수형은 안된다. case Command.BUYSHARES : try { db.buyShares(args[0], args[1], Integer.parseInt(args[2])); r.setStatus(0); }catch(Exception e){ e.printStackTrace(); } break; case Command.SELLSHARES : try { db.sellShares(args[0], args[1], Integer.parseInt(args[2])); r.setStatus(0); }catch(RecordNotFoundException e){ r.setStatus(-1); }catch(InvalidTransactionException e) { r.setStatus(-3); }catch(Exception e){ e.printStackTrace(); } break; case Command.GETALLSSTOCK : try { ArrayList<StockRec> list = db.getAllStocks(); r.setStatus(0); r.add(list); }catch(Exception e) { e.printStackTrace(); } break; case Command.GETSTOCKPRICE : try { float price = db.getStockPrice(args[0]); r.setStatus(0); r.add(price); }catch(Exception e) { e.printStackTrace(); } break; case Command.GETALLCUSTOMERS : try { ArrayList<CustomerRec> list = db.getAllCustomers(); r.setStatus(0); r.add(list); }catch(Exception e) { e.printStackTrace(); } break; case Command.GETCUSTOMER : try { CustomerRec cr = db.getCustomer(args[0]); r.setStatus(0); r.add(cr); }catch(Exception e) { } break; case Command.ADDCUSTOMER : try { db.addCustomer(new CustomerRec(args[0], args[1], args[2])); r.setStatus(0); }catch(DuplicateSSNException e){ r.setStatus(-2); }catch(Exception e) { e.printStackTrace(); } break; case Command.DELETECUSTOMER : try { db.deleteCustomer(args[0]); r.setStatus(0); }catch(RecordNotFoundException e) { r.setStatus(-1); }catch(Exception e) { e.printStackTrace(); } break; case Command.UPDATECUSTOMER : try { db.updateCustomer(new CustomerRec(args[0], args[1], args[2])); r.setStatus(0); }catch(RecordNotFoundException e) { r.setStatus(-1); }catch(Exception e) { e.printStackTrace(); } break; }// switch //4. 다시 클라이언트 쪽으로 날린다. try { oos.writeObject(cmd); }catch(IOException e) { e.printStackTrace(); } }//while }//run }//class
package com.niceinfo.eais.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.niceinfo.eais.dao.EaisRepository; import com.niceinfo.eais.dto.DataVO; @Service public class EaisServiceImpl implements EaisService { @Autowired EaisRepository eaisRepository; @Override public int insertData(DataVO data) { return eaisRepository.insertData(data); } @Override public int createDataSet(List<DataVO> data) { return eaisRepository.insertDataSet(data); } @Override public List<DataVO> getAllData() { return eaisRepository.selectDataSet(); } @Override public List<DataVO> getData(String MGM_BLDRGST_PK) { return eaisRepository.selectData(MGM_BLDRGST_PK); } }
package net.droidlabs.viking.bindings.map.models; import androidx.annotation.Nullable; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; /** * BindableCircle is a Viking class which connects CircleOptions with Circle in order to be aware * which circle have you created from CircleOptions. */ public class BindableCircle { private CircleOptions circleOptions; private Circle circle; public BindableCircle(CircleOptions circleOptions) { this.circleOptions = circleOptions; } public CircleOptions getCircleOptions() { return circleOptions; } @Nullable public Circle getCircle() { return circle; } public void setCircle(Circle circle) { this.circle = circle; } }
package com.kevappsgaming.coursemanagementsqlite; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatButton; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.kevappsgaming.coursemanagementsqlite.adapters.CourseAdapter; import com.kevappsgaming.coursemanagementsqlite.database.CourseHelper; import com.kevappsgaming.coursemanagementsqlite.utils.CourseInformation; import com.kevappsgaming.coursemanagementsqlite.utils.InputValidation; import java.util.List; public class MainActivity extends AppCompatActivity { private CourseHelper myDB; public RecyclerView recyclerView; private InputValidation inputValidation; private CourseAdapter adapter; private List<CourseInformation> coursesList; private List<CourseInformation> queryList; private TextInputLayout TextInputLayoutCourseNumber; private TextInputLayout TextInputLayoutCourseName; private TextInputLayout TextInputLayoutCourseCredits; private TextInputEditText TextInputEditTextCourseNumber; private TextInputEditText TextInputEditTextCourseName; private TextInputEditText TextInputEditTextCourseCredits; private AppCompatButton ButtonInsert; private AppCompatButton ButtonDelete; private AppCompatButton ButtonUpdate; private AppCompatButton ButtonQuery; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = (RecyclerView) findViewById(R.id.courses_recyclerView); myDB = new CourseHelper(MainActivity.this); TextInputLayoutCourseNumber = (TextInputLayout) findViewById(R.id.textInputLayoutCourseNumber); TextInputLayoutCourseName = (TextInputLayout) findViewById(R.id.textInputLayoutCourseName); TextInputLayoutCourseCredits = (TextInputLayout) findViewById(R.id.textInputLayoutCourseCredits); TextInputEditTextCourseNumber = (TextInputEditText) findViewById(R.id.textInputEditTextCourseNumber); TextInputEditTextCourseName = (TextInputEditText) findViewById(R.id.textInputEditTextCourseName); TextInputEditTextCourseCredits = (TextInputEditText) findViewById(R.id.textInputEditTextCourseCredits); ButtonInsert = (AppCompatButton) findViewById(R.id.ButtonInsert); ButtonDelete = (AppCompatButton) findViewById(R.id.ButtonDelete); ButtonUpdate = (AppCompatButton) findViewById(R.id.ButtonUpdate); ButtonQuery = (AppCompatButton) findViewById(R.id.ButtonQuery); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); recyclerView.addItemDecoration(new DividerItemDecoration(MainActivity.this, DividerItemDecoration.VERTICAL)); coursesList = myDB.fetchCourseInfo(); adapter = new CourseAdapter(this, coursesList); recyclerView.setAdapter(adapter); findViewById(R.id.relativeLayout).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); return true; } }); ButtonInsert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(checkInputValidity()){ if(!myDB.searchCourse(TextInputEditTextCourseNumber.getText().toString())){ myDB.saveCourseInfo(TextInputEditTextCourseNumber.getText().toString(), TextInputEditTextCourseName.getText().toString(), TextInputEditTextCourseCredits.getText().toString()); coursesList.add(new CourseInformation(TextInputEditTextCourseNumber.getText().toString(), TextInputEditTextCourseName.getText().toString(), TextInputEditTextCourseCredits.getText().toString())); adapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, "course added...", Toast.LENGTH_LONG).show(); clearInputFields(); } else{ Toast.makeText(MainActivity.this, "course number is unique", Toast.LENGTH_LONG).show(); } } } }); ButtonDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(checkInputValidity()){ if(!myDB.searchCourse(TextInputEditTextCourseNumber.getText().toString())){ Toast.makeText(MainActivity.this, "course number not found", Toast.LENGTH_LONG).show(); } else{ myDB.deleteCourse(TextInputEditTextCourseNumber.getText().toString()); adapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, "course deleted...", Toast.LENGTH_LONG).show(); clearInputFields(); } } } }); ButtonUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(checkInputValidity()){ if(!myDB.searchCourse(TextInputEditTextCourseNumber.getText().toString())){ Toast.makeText(MainActivity.this, "course number is not editable", Toast.LENGTH_LONG).show(); } else{ myDB.updateCourseInfo(TextInputEditTextCourseNumber.getText().toString(), TextInputEditTextCourseName.getText().toString(), TextInputEditTextCourseCredits.getText().toString()); adapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, "course updated...", Toast.LENGTH_LONG).show(); clearInputFields(); } } } }); ButtonQuery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(checkInputValidity()){ try{ coursesList = myDB.queryCourseInfo(TextInputEditTextCourseNumber.getText().toString()); } catch (Exception e){ Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show(); } recyclerView.setAdapter(adapter); } } }); } public boolean checkInputValidity(){ inputValidation = new InputValidation(MainActivity.this); if(!inputValidation.isInputEditTextFilled(TextInputEditTextCourseNumber, TextInputLayoutCourseNumber, getString(R.string.error_message_courseNumber))){ return false; } if(!inputValidation.isInputEditTextFilled(TextInputEditTextCourseName, TextInputLayoutCourseName, getString(R.string.error_message_courseName))){ return false; } if(!inputValidation.isInputEditTextFilled(TextInputEditTextCourseCredits, TextInputLayoutCourseCredits, getString(R.string.error_message_courseCredits))){ return false; } if(!inputValidation.isInputEditTextInteger(TextInputEditTextCourseCredits, TextInputLayoutCourseCredits, getString(R.string.error_message_courseCredits))){ return false; } return true; } public void clearInputFields(){ TextInputEditTextCourseNumber.getText().clear(); TextInputEditTextCourseName.getText().clear(); TextInputEditTextCourseCredits.getText().clear(); } }
package br.com.hype.medan; import retrofit.Callback; import retrofit.client.Response; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.POST; /** * Created by IQBAL on 9/8/2016. */ public interface HashtagAPI { @FormUrlEncoded @POST("/androidapi/kirim_hastag.php") public void kirimHastagAPI( @Field("hastag_kirim") String hastag_kirim, @Field("email_kirim") String email_kirim, Callback<Response> callback); }
package com.logicbig.example; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import org.springframework.web.context.support.RequestHandledEvent; @Component public class MyBean { @EventListener public void handleEvent (RequestHandledEvent e) { System.out.println("-- RequestHandledEvent --"); System.out.println(e); } }
/* * 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 Inheritance; /** * * @author YNZ */ class SuperClass { public float a = 0.12f; static void superMethod() { System.out.println(SuperClass.class.getSimpleName()); } public SuperClass() { System.out.println("Super class!"); } static int size = 10; private void lowerMethod() { } } class SubClass extends SuperClass { private float a = 12.56f; static float size = 20; public SubClass() { System.out.println("Sub-Class!"); } static void superMethod() { System.out.println(SubClass.class.getSimpleName()); } //instance method cannot override class method. //sub-class class method cannot hide the super-class instancec method. //private method cannot be inheritted, so it won't cause such an issue. static void lowerMethod() { } public float getA(){ return this.a; } } class AnotherSubClass extends SuperClass{ } class Test { public static void main(String[] args) { SubClass.superMethod(); SuperClass.superMethod(); System.out.println(SubClass.size); System.out.println(new SubClass().getA()); SuperClass sc = new SubClass(); System.out.println(""+sc.a); SubClass subClass = new SubClass(); System.out.println(""+subClass.getA() +" "+ ((SuperClass)subClass).a); //subClass.a for subclass type instance, a is hidden by the local private a variable. so you cannot access public a in the super class. //on this casee, you have to fully qualify it, by casting the sub-class into its super-class. //in java pratice, when fields having the same name but different scope, the one in a higher scope is hidden by the one in the lower part. // System.out.println(Boolean.toString(subClass instanceof SuperClass)+"aha"); System.out.println("how many interfaces " +SubClass.class.getInterfaces().length); } }
package com.revolut.moneytransfer.controller; import com.revolut.moneytransfer.exceptions.InvalidUuidException; import com.revolut.moneytransfer.model.CreditTransactionRequest; import com.revolut.moneytransfer.model.MoneyTransferRequest; import com.revolut.moneytransfer.util.RequestValidator; import spark.Request; import spark.Response; import spark.Route; import java.util.UUID; import static com.revolut.moneytransfer.Application.transactionService; public class TransactionController { public static Route creditMoney = (Request request, Response response) -> { /* This API is required because account creation API creates an account with zero balance. * We need to add some money to our account in order to transfer it. * */ try { CreditTransactionRequest creditTransactionRequest = RequestValidator.getCreditTransactionRequest(request.body()); return transactionService.credit(creditTransactionRequest, UUID.fromString(request.params("uuid").trim())); } catch (IllegalArgumentException e) { throw new InvalidUuidException(); } }; public static Route transferMoney = (Request request, Response response) -> { try { MoneyTransferRequest moneyTransferRequest = RequestValidator.getMoneyTransferRequest(request.body()); return transactionService.transfer(moneyTransferRequest, UUID.fromString(request.params("uuid").trim())); } catch (IllegalArgumentException e) { throw new InvalidUuidException(); } }; }
public class CategoriasIoTs { public int Id; public String Categoria; }
package de.digitalstreich.Manufact.service; import de.digitalstreich.Manufact.db.ProductRepository; import de.digitalstreich.Manufact.model.Product; import de.digitalstreich.Manufact.service.interfaces.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.List; @Service public class ProductServiceImpl implements ProductService { private ProductRepository productRepository; @Autowired public ProductServiceImpl(ProductRepository productRepository) { this.productRepository = productRepository; } @Override public List<Product> findAllManufacturerProducts(Long manufacturerId) { return productRepository.findAll(manufacturerId, Sort.unsorted()); } }
package com.deepakm.algo.backtrack.ratinamaze.algo; /** * Created by dmarathe on 1/22/16. */ public interface Solve { public boolean isSolvable(); public boolean solve(); public void printPath(); }
package cz.metacentrum.perun.spRegistration.persistence.connectors; import static java.lang.System.currentTimeMillis; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import cz.metacentrum.perun.spRegistration.persistence.configuration.RpcConnectorProperties; import cz.metacentrum.perun.spRegistration.persistence.exceptions.PerunConnectionException; import cz.metacentrum.perun.spRegistration.persistence.exceptions.PerunUnknownException; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; import org.apache.http.HeaderElement; import org.apache.http.HeaderElementIterator; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicHeaderElementIterator; import org.apache.http.protocol.HTTP; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.client.InterceptingClientHttpRequestFactory; import org.springframework.http.client.support.BasicAuthenticationInterceptor; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; /** * Connector for calling Perun RPC * * @author Dominik Frantisek Bucik <bucik@ics.muni.cz> */ @Component @Slf4j public class PerunConnectorRpc { private final RpcConnectorProperties properties; private final String perunUrl; private final RestTemplate restTemplate = new RestTemplate(); @Autowired public PerunConnectorRpc(RpcConnectorProperties properties) { this.properties = properties; this.perunUrl = properties.getPerunUrl(); } @PostConstruct public void postInit() { RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(properties.getRequestTimeout()) // The timeout when requesting a connection from the connection manager .setConnectTimeout(properties.getConnectTimeout()) // Determines the timeout in milliseconds until a connection is established .setSocketTimeout(properties.getSocketTimeout()) // The timeout for waiting for data .build(); PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager(); poolingConnectionManager.setMaxTotal(properties.getMaxConnections()); // max total connections poolingConnectionManager.setDefaultMaxPerRoute(properties.getMaxConnectionsPerRoute()); ConnectionKeepAliveStrategy connectionKeepAliveStrategy = (response, context) -> { HeaderElementIterator it = new BasicHeaderElementIterator (response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } return 20000L; }; CloseableHttpClient httpClient = HttpClients.custom() .setDefaultRequestConfig(requestConfig) .setConnectionManager(poolingConnectionManager) .setKeepAliveStrategy(connectionKeepAliveStrategy) .build(); HttpComponentsClientHttpRequestFactory poolingRequestFactory = new HttpComponentsClientHttpRequestFactory(); poolingRequestFactory.setHttpClient(httpClient); // basic auth List<ClientHttpRequestInterceptor> interceptors = Collections.singletonList(new BasicAuthenticationInterceptor(properties.getPerunUser(), properties.getPerunPassword())); InterceptingClientHttpRequestFactory authenticatingRequestFactory = new InterceptingClientHttpRequestFactory(poolingRequestFactory, interceptors); restTemplate.setRequestFactory(authenticatingRequestFactory); } /** * Make post call to Perun RPC * @param manager String value representing manager to be called. Use constants from this class. * @param method Method to be called (i.e. getUserById) * @param map Map of parameters to be passed as request body * @return Response from Perun * @throws PerunUnknownException Thrown as wrapper of unknown exception thrown by Perun interface. * @throws PerunConnectionException Thrown when problem with connection to Perun interface occurs. */ public JsonNode call(String manager, String method, Map<String, Object> map) throws PerunUnknownException, PerunConnectionException { String actionUrl = this.perunUrl + "/json/" + manager + '/' + method; // make the call try { log.trace("calling {} with {}", actionUrl, map); long startTime = currentTimeMillis(); JsonNode result = restTemplate.postForObject(actionUrl, map, JsonNode.class); long endTime = currentTimeMillis(); long responseTime = endTime - startTime; log.trace("POST call proceeded in {} ms.",responseTime); return result; } catch (HttpClientErrorException ex) { return handleHttpClientErrorException(ex, actionUrl); } catch (Exception e) { throw new PerunConnectionException(e); } } private JsonNode handleHttpClientErrorException(HttpClientErrorException ex, String actionUrl) throws PerunUnknownException { MediaType contentType = null; if (ex.getResponseHeaders() != null) { contentType = ex.getResponseHeaders().getContentType(); } String body = ex.getResponseBodyAsString(); if (contentType != null && "json".equalsIgnoreCase(contentType.getSubtype())) { try { JsonNode json = new ObjectMapper().readValue(body,JsonNode.class); if (json.has("errorId") && json.has("name")) { switch (json.get("name").asText()) { case "ExtSourceNotExistsException": case "FacilityNotExistsException": case "GroupNotExistsException": case "MemberNotExistsException": case "ResourceNotExistsException": case "VoNotExistsException": case "UserNotExistsException": return JsonNodeFactory.instance.nullNode(); } } } catch (IOException e) { log.error("cannot parse error message from JSON", e); throw new PerunUnknownException(ex); } } log.error("HTTP ERROR {} URL {} Content-Type: {}", ex.getRawStatusCode(), actionUrl, contentType, ex); throw new PerunUnknownException(ex); } }
package org.androidtown.tutorial.graphic; /** * Created by BlackBean on 2017-03-12. */ public interface OnPenSelectedListener { public void onPenSelected(int pen); }
package be.openclinic.datacenter; import java.util.*; import javax.mail.*; import javax.mail.internet.*; import be.mxs.common.util.db.MedwanQuery; public class SMTPAckSender { public void send(ImportMessage importMessage) throws AddressException, MessagingException{ String host = MedwanQuery.getInstance().getConfigString("datacenterSMTPHost","localhost"); String from = MedwanQuery.getInstance().getConfigString("datacenterSMTPFrom",""); String to = importMessage.getRef().split("\\:")[1]; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.localhost", "127.0.0.1"); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("datacenter.ack: "+importMessage.getServerId()+"."+importMessage.getObjectId()); //Create message content Date sentDateTime=new Date(); message.setText(importMessage.asAckXML()); Transport.send(message); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /* URL https://www.acmicpc.net/problem/14499 */ public class Main14499_주사위굴리기 { static int r, c, k; static int[] dice, start, comms, roundIndex; static int[][] map, dir; static StringBuilder result; public static void main(String[] args) throws IOException { input(); roll(0, 6, start[0], start[1]); print(); } private static void input() throws IOException { result = new StringBuilder(); roundIndex = new int[]{0, 3, 4, 2, 5}; dice = new int[]{0, 0, 0, 0, 0, 0, 0}; dir = new int[][]{ {0, 0}, {0, 1}, {0, -1}, {-1, 0}, {1, 0} }; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine().trim()); r = Integer.parseInt(st.nextToken()); c = Integer.parseInt(st.nextToken()); start = new int[]{Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())}; k = Integer.parseInt(st.nextToken()); map = new int[r][c]; for (int i = 0; i < r; i++) { st = new StringTokenizer(br.readLine().trim()); for (int j = 0; j < c; j++) { map[i][j] = Integer.parseInt(st.nextToken()); } } comms = new int[k]; st = new StringTokenizer(br.readLine().trim()); for (int i = 0; i < k; i++) { comms[i] = Integer.parseInt(st.nextToken()); } } private static void roll(int commIndex, int presIndex, int fromR, int fromC) { if (commIndex == k) return; int dirIndex = comms[commIndex]; int toR = fromR + dir[dirIndex][0], toC = fromC + dir[dirIndex][1]; int nextIndex = roundIndex[dirIndex]; if (toR >=0 && toC >= 0 && toR < r && toC < c) { if (map[toR][toC] == 0) { map[toR][toC] = dice[nextIndex]; } else { dice[nextIndex] = map[toR][toC]; map[toR][toC] = 0; } renewDir(presIndex, dirIndex); result.append(dice[7-nextIndex]).append("\n"); roll(commIndex+1, nextIndex, toR, toC); } else { roll(commIndex+1, presIndex, fromR, fromC); } } private static void renewDir(int presIndex, int dirIndex) { switch(dirIndex) { case 1: roundIndex[1] = 7 - presIndex; roundIndex[2] = presIndex; break; case 2: roundIndex[1] = presIndex; roundIndex[2] = 7 - presIndex; break; case 3: roundIndex[3] = 7 - presIndex; roundIndex[4] = presIndex; break; case 4: roundIndex[3] = presIndex; roundIndex[4] = 7 - presIndex; break; } } private static void print() { System.out.println(result.toString()); } }
package demo; import java.util.Scanner; public class PrintCalendar { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Please input full year ex) 2019 : "); int year = input.nextInt(); System.out.println("Please input month ex) (1-12) : "); int month = input.nextInt(); //print a whole year printCalendar(year); //print a month printCalendar(year, month); input.close(); } public static boolean isLeapYear(int year) { return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0); } public static int howManyDaysInTheMonth(int year, int month) { if(isLeapYear(year) && (month==2)) return 29; else if((month == 1)||(month == 3)||(month == 5)||(month == 7)||(month == 8)||(month == 10)||(month == 12)) return 31; else if(month ==2) return 28; else return 30; } public static int getStartDay(int year, int month) { final int START_DAY_FOR_JAN_1_1800 = 3; // Get total number of days from 1/1/1800 to month/1/year int totalNumberOfDays = getTotalNumberOfDays(year, month); return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7; } public static int getTotalNumberOfDays(int year, int month) { int total = 0 ; for(int i = 1800; i < year; i++) { if(isLeapYear(i)) total += 366; else total += 365; } for(int i = 1 ; i < month ; i++ ) { total += howManyDaysInTheMonth(year, i); } return total; } public static String getMonthName(int month) { String[] monthName= {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JLY", "AUG", "SEP", "OCT", "NOV", "DEC"}; return monthName[month-1]; } public static void printCalendar(int year) { for(int month = 1 ; month <= 12 ; month ++) { printTitle(year, month); printBody(year, month); } } public static void printCalendar(int year, int month) { printTitle(year, month); printBody(year, month); } public static void printTitle(int year, int month) { System.out.println("\n\n"); System.out.println(" "+ year + " " + getMonthName(month)); System.out.println("----------------------------"); System.out.println(" Sun Mon Tue Wed Thu Fri Sat"); } public static void printBody(int year, int month) { int i = 1; int day = 1; while( i <= getStartDay(year, month)) { System.out.printf("%4s", ""); i++; } while (day <= howManyDaysInTheMonth(year, month)) { if( i % 7 ==0 ) { System.out.printf("%4d\n", day++); i++; } else { System.out.printf("%4d", day++); i++; } } } }
package com.paragon.sensonic.ui.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.RecyclerView; import com.paragon.sensonic.R; import com.paragon.sensonic.databinding.RowGuestProfileItemBinding; import com.paragon.sensonic.utils.CustomItemClickListener; import com.paragon.brdata.dto.GuestData; import com.paragon.brdata.dto.GuestProfileSubTitle; import com.paragon.utils.anim.list.SpringAdapterAnimationType; import com.paragon.utils.anim.list.SpringAdapterAnimator; import java.util.List; public class GuestsProfileAdapter extends RecyclerView.Adapter<GuestsProfileAdapter.ViewHolder> { private final Context context; private final List<GuestData> list; private final CustomItemClickListener customItemClickListener; private final SpringAdapterAnimator animator; public GuestsProfileAdapter(Context context, List<GuestData> list, RecyclerView recyclerView, CustomItemClickListener customItemClickListener) { this.context = context; this.customItemClickListener = customItemClickListener; this.list = list; this.animator = new SpringAdapterAnimator(recyclerView); this.animator.setSpringAnimationType(SpringAdapterAnimationType.SLIDE_FROM_BOTTOM); this.animator.addConfig(85, 18); } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); RowGuestProfileItemBinding rowGuestProfileHeaderBinding = DataBindingUtil.inflate(layoutInflater, R.layout.row_guest_profile_item, parent, false); animator.onSpringItemCreate(rowGuestProfileHeaderBinding.getRoot()); return new ViewHolder(rowGuestProfileHeaderBinding); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { animator.onSpringItemBind(holder.itemView, position); holder.rowGuestProfileHeaderBinding.rowGuestProfileHeader.setText(list.get(position).getTitle()); ListAdapter guestSubTitleAdapter = new ListAdapter(context, list.get(position).getSubTitles()); guestSubTitleAdapter.setOnClickListener(customItemClickListener); holder.rowGuestProfileHeaderBinding.rowGuestProfileList.setAdapter(guestSubTitleAdapter); } @Override public int getItemCount() { return list.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { RowGuestProfileItemBinding rowGuestProfileHeaderBinding; public ViewHolder(RowGuestProfileItemBinding itemView) { super(itemView.getRoot()); this.rowGuestProfileHeaderBinding = itemView; } } private class ListAdapter extends BaseAdapter { private final Context context; private final List<GuestProfileSubTitle> items; private CustomItemClickListener customItemClickListener; public ListAdapter(Context context, List<GuestProfileSubTitle> items) { this.context = context; this.items = items; } @Override public int getCount() { return items.size(); } @Override public Object getItem(int position) { return items.get(position); } @Override public long getItemId(int position) { return position; } public void setOnClickListener(CustomItemClickListener onClickListener) { this.customItemClickListener = onClickListener; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { GuestProfileSubTitle guestProfileSubTitle = items.get(position); convertView = LayoutInflater.from(context).inflate(R.layout.row_guest_profile_list_item, parent, false); TextView title = convertView.findViewById(R.id.row_guest_profile_title); TextView date = convertView.findViewById(R.id.row_guest_profile_date); TextView subTitle = convertView.findViewById(R.id.row_guest_profile_sub_title); View divider = convertView.findViewById(R.id.row_guest_profile_divider); title.setText(guestProfileSubTitle.getTitle()); date.setText(guestProfileSubTitle.getDate()); convertView.setOnClickListener(view -> customItemClickListener.onItemClickListener(position, guestProfileSubTitle)); } return convertView; } } }
package ru.yandex.yamblz.ui.recyclerstuff.interfaces; /** * Created by dalexiv on 8/7/16. */ public interface IMoveCallback { void moveHappened(int initialPos, int positionAfterMove); }
package com.example.zloiy.customfileexplorer; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import java.io.File; /** * Created by ZloiY on 21-Aug-16. */ public class CopyTask extends AsyncTask<File, Long, Boolean> { ProgressDialog progress; Context context; String outputPath; String inputPath; boolean cut; FileOperations operations; public CopyTask(Context context, String outputPath, String inputPath, boolean cut){ this.context=context; this.outputPath=outputPath; this.inputPath = inputPath; this.cut = cut; operations = new FileOperations(); } protected void onPreExecute() { progress = ProgressDialog.show(context,"","Loading...",true); } protected Boolean doInBackground(File... files) { for (File ff: files){ operations.setInputPath(inputPath, ff.getName(), cut); operations.copyFile(outputPath); } return true; } protected void onPostExecute(Boolean success) { progress.dismiss(); // Show dialog with result } protected void onProgressUpdate(Long... values) { for (int numFile=0; numFile<values.length; numFile++) { progress.setMessage("Transferred " + values[numFile] + "files"); } } }
package com.dataart.was.dao; import java.sql.Connection; public abstract class Dao { private Connection connection; public Dao(Connection connection){ this.connection = connection; } public Dao(){}; public Connection getConnection() { return connection; } public void setConnection(Connection connection) { this.connection = connection; } }
package com.example.arena.validation; import android.content.Context; import com.example.arena.integration.CoreCommunicationService; import com.example.arena.singleton.UserSession; public class ValueValidator { private Context context; private CoreCommunicationService coreCommunicationService; public ValueValidator(Context context) { this.coreCommunicationService = new CoreCommunicationService(context); } public boolean validateUsername(String username) { if (UserSession.loggedUser.getUsername().equals(username)) return true; return !coreCommunicationService.checkUserExistsByUsernameRequest(username); } public boolean validateFullname(String fullname) { return fullname.matches("[a-zA-Z ]+"); } public boolean validateAge(Integer age) { return age >= 10 && age <= 99; } public boolean validateCurrentPassword(String currentPassword) { return UserSession.loggedUser.getPassword().equals(currentPassword); } public boolean validateNewPassword(String newPassword) { return newPassword.length() >= 8; } public boolean validateCodeforcesUsername(String codeforcesUsername) { codeforcesUsername = codeforcesUsername.trim(); if (codeforcesUsername.contains(" ")) return false; return coreCommunicationService.checkCodeforcesUsernameExists(codeforcesUsername); } public boolean validateCodewarsUsername(String codewarsUsername) { codewarsUsername = codewarsUsername.trim(); if (codewarsUsername.contains(" ")) return false; return coreCommunicationService.checkCodewarsUsernameExists(codewarsUsername); } }
package cn.com.hzzc.industrial.pro; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import cn.com.hzzc.industrial.pro.cons.SystemConst; import cn.com.hzzc.industrial.pro.entity.ActivityEntity; import cn.com.hzzc.industrial.pro.util.ActUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.nostra13.universalimageloader.core.ImageLoader; public class ActivityIntroductionFragment extends ParentActFragment { private TextView add_act_title, add_act_type, add_act_beginDate, add_act_endDate, add_act_introduce; private ImageView add_act_self, add_act_img; public ActivityEntity entity; public ActivityIntroductionFragment() { super(); } public ActivityIntroductionFragment(String cId) { this.cId = cId; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflater = getActivity().getLayoutInflater(); mMainView = inflater.inflate( R.layout.activity_intro_fragment, (ViewGroup) getActivity().findViewById( R.id.act_fragment_parent_viewpager), false); init(); getCommonInfo(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); ViewGroup p = (ViewGroup) mMainView.getParent(); if (p != null) { p.removeAllViewsInLayout(); } return mMainView; } /** * @user:pang * @data:2015年10月20日 * @todo:初始化 * @return:void */ private void init() { add_act_title = (TextView) mMainView.findViewById(R.id.add_act_title); add_act_type = (TextView) mMainView.findViewById(R.id.add_act_type); add_act_beginDate = (TextView) mMainView .findViewById(R.id.add_act_beginDate); add_act_endDate = (TextView) mMainView .findViewById(R.id.add_act_endDate); add_act_introduce = (TextView) mMainView .findViewById(R.id.add_act_introduce); add_act_self = (ImageView) mMainView.findViewById(R.id.add_act_self); add_act_img = (ImageView) mMainView.findViewById(R.id.add_act_img); } /** * @param entity * @user:pang * @data:2015年10月20日 * @todo:渲染 * @return:void */ public void render(ActivityEntity entity) { add_act_title.setText(entity.getTitle()); String proType = entity.getType(); String t = ""; if ("0".equals(proType)) { t = "线下活动"; } else if ("1".equals(proType)) { t = "调查活动"; } else if ("2".equals(proType)) { t = "统计活动"; } else if ("3".equals(proType)) { t = "优惠活动"; } add_act_type.setText(t); add_act_beginDate.setText(entity.getBeginDate()); add_act_endDate.setText(entity.getEndDate()); add_act_introduce.setText(entity.getIntroduction()); boolean isSelf = entity.isIfNeedSelfSociety(); if (isSelf) { add_act_self.setImageResource(R.drawable.table_on); } else { add_act_self.setImageResource(R.drawable.table_off); } String imgId = entity.getImgId(); if (imgId != null && !"".equals(imgId)) { String pic_url = SystemConst.server_url + SystemConst.Type2Url.getImgByImgId + "?para={imgId:" + imgId + "}"; ImageLoader.getInstance().displayImage(pic_url, add_act_img, GloableApplication.getDisplayImageOption()); } else { String imageUri = "drawable://" + R.drawable.visitor_me_cover; ImageLoader.getInstance().displayImage(imageUri, add_act_img); } } /** * @user:pang * @data:2015年10月20日 * @todo:获取互动的通用信息 * @return:void */ private void getCommonInfo() { String url = SystemConst.server_url + SystemConst.Type2Url.queryCommenActivityByIdForQuestionDetailIdByType; try { JSONObject d = new JSONObject(); d.put("Id", cId); RequestCallBack<String> rcb = new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { String data = responseInfo.result; entity = ActUtils.getActivityEntity(data); render(entity); } @Override public void onFailure(HttpException error, String msg) { } }; Map map = new HashMap(); map.put("para", d.toString()); send_normal_request(url, map, rcb); } catch (Exception e) { e.printStackTrace(); } } }
package hw4.task9; public class FactorialFor { public static void main(String[] args) { int varInt = (int) (Math.random() * 100); System.out.println(varInt + "! = " + factorialFor(varInt)); System.out.println(varInt + "! = " + factorialClassic(varInt)); } public static long factorialFor(int var) { long res = 1; if (var == 0 || var == 1) return 1; else { for (int i = 2; i <= var; i++) { res *= i; } } return res; } public static long factorialClassic(int var) { if (var == 0) return 1; else return var * factorialClassic(var - 1); } }
package opendict.dictionary.longman.response; import opendict.common.AbstractMeaning; /** * Created by baoke on 21/12/2016. */ public class Response extends AbstractMeaning { public int status; public int offset; public int limit; public int count; public int total; public String url; public Result[] results; @Override public Result[] getResults() { return results; } public void setResults(Result[] results) { this.results = results; } }
/* * * SWT-Praktikum TU Dresden 2015 * Gruppe 32 - Computech * * Stephan Fischer * Anna Gromykina * Kevin Horst * Philipp Oehme * */ package computech.model; import org.salespointframework.useraccount.UserAccount; import org.springframework.data.repository.CrudRepository; /** * * Contains every customer (private and business customer). * */ public interface CustomerRepository extends CrudRepository<Customer, Long> { void delete(Long id); Customer findByUserAccount(UserAccount userAccount); }
package xtrus.user.apps.comp.socket.efms; import com.esum.comp.socket.packet.ReaderableMessage; public abstract class AbstractEfmsPacket implements ReaderableMessage { private byte[] rawBytes = null; @Override public byte[] getRawPacket() { return rawBytes; } @Override public void setRawPacket(byte[] rawdata) { this.rawBytes = rawdata; } }
package toasty.messageinabottle.exception; public class AuthenticationException extends Exception { }
package com.wenyuankeji.spring.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wenyuankeji.spring.dao.IBaseConfigDao; import com.wenyuankeji.spring.dao.IUserProfessionLevelDao; import com.wenyuankeji.spring.dao.IUsersubinfoDao; import com.wenyuankeji.spring.model.BaseConfigModel; import com.wenyuankeji.spring.model.UserProfessionLevelModel; import com.wenyuankeji.spring.model.UsersubinfoModel; import com.wenyuankeji.spring.service.IUsersubinfoService; import com.wenyuankeji.spring.util.BaseException; @Service public class UsersubinfoServiceImpl implements IUsersubinfoService{ @Autowired private IUsersubinfoDao usersubinfoDao; @Autowired private IUserProfessionLevelDao userProfessionLevelDao; @Autowired private IBaseConfigDao baseConfigDao; /************管理端************/ @Override public List<UsersubinfoModel> searchUserinfo(String cityid, String userid, String tel, String startTime, String endTime, String checkstate,String txtNickname, int page, int rows) throws BaseException { return usersubinfoDao.searchUsersubinfo(cityid, userid, tel, startTime, endTime, checkstate, txtNickname,page, rows); } @Override public int searchUserinfoCount(String cityid, String userid, String tel, String startTime, String endTime, String checkstate,String txtNickname) throws BaseException { return usersubinfoDao.searchUserinfoCount(cityid, userid, tel, startTime, endTime, checkstate,txtNickname); } @Override public UsersubinfoModel searchUsersubinfo(int userid) throws BaseException { return usersubinfoDao.searchUsersubinfo(userid); } @Override public boolean updateUsersubinfo(UsersubinfoModel usersubinfoModel, int type)throws BaseException { if (0 == type) { //定级和状态都更新 return usersubinfoDao.updateUsersubinfo(usersubinfoModel); } return usersubinfoDao.updateUsersubinfo(usersubinfoModel, type); } @Override public List<UserProfessionLevelModel> searchUserProfessionLevel() throws BaseException { return userProfessionLevelDao.searchUserProfessionLevel(); } @Override public UsersubinfoModel searchUserSubInfoByUserId(int userId) { return usersubinfoDao.searchUserSubInfoByUserId(userId); } @Override public int addUserSubInfo(UsersubinfoModel userSubInfo) { return usersubinfoDao.addUserSubInfo(userSubInfo); } @Override public boolean updateUserSubInfoByUserId(UsersubinfoModel userSubInfo) throws BaseException{ return usersubinfoDao.updateUserSubInfoByUserId(userSubInfo); } @Override public BaseConfigModel searchBaseConfigByCode(String configcode) throws BaseException { return baseConfigDao.searchBaseConfigByCode(configcode); } }