text
stringlengths
10
2.72M
package kr.co.shop.batch.kakaopay.model.master.base; import lombok.Data; import java.io.Serializable; import kr.co.shop.common.bean.BaseBean; @Data public class BaseRvKakaoComparison extends BaseBean implements Serializable { /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 결제고유번호 */ private String tid; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 호출고유번호 */ private String aid; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 가맹점코드 */ private String cid; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 결제상태값 */ private String status; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 가맹점주문번호 */ private String partnerOrderId; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 가맹점회원id */ private String partnerUserId; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 결제수단 */ private String paymentMethodType; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 상품이름 */ private String itemName; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 상품코드 */ private String itemCode; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 상품수량 */ private java.lang.Integer quantity; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 카드빈 */ private String cardBin; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 할부개월수 */ private java.lang.Integer installMonth; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 카드사정보 */ private String cardCorpName; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 무이자할부여부 */ private String interestFreeInstall; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 결제/취소거래시간 */ private String approvedAt; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 결제/취소총액 */ private java.lang.Integer amount; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 결제/취소포인트금액 */ private java.lang.Integer pointAmount; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 할인금액 */ private java.lang.Integer discountAmount; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 결제타입 */ private String paymentActionType; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : Request로전달한값 */ private String payload; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 상세로그 */ private String dtlLogInfo; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 등록일자 */ private java.sql.Timestamp rgstDtm; }
package com.improlabs.auth.ResponseBuilder; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.apache.log4j.Logger; import com.improlabs.auth.RequestHandler.RequestHandler; import com.improlabs.auth.entity.DataPacket; import com.improlabs.auth.entity.ServerDataEvent; import com.improlabs.auth.main.MainRunner; import com.improlabs.auth.queue.RequestQueue; import com.improlabs.auth.taskprocessor.TaskProcessor; import com.improlabs.auth.util.LoggerUtil; import com.improlabs.auth.util.Utils; public class ResponseBuilder extends Thread { public static Logger LOGGER = LoggerUtil.getLogger(ResponseBuilder.class); // private List queue = new LinkedList(); //private BlockingQueue<ServerDataEvent> requestBlockingQueue = new LinkedBlockingQueue<ServerDataEvent>(); private TaskProcessor taskProcessor; private boolean runFlag=true; private Integer counter = 0; private Integer breakCounter = 0; public ResponseBuilder(TaskProcessor taskProcessor) { this.taskProcessor = taskProcessor; } // public void processData(RequestHandler requestHandler,DatagramChannel // datagramChannel, DataPacket dataPacket) { // byte[] dataCopy = new byte[dataPacket.getDataCount()]; // System.arraycopy(dataPacket.getData(), 0, dataCopy, 0, // dataPacket.getDataCount()); // dataPacket.setData(dataCopy); // System.out.println("receiving::" + new String(dataPacket.getData()) + " // size::" + dataPacket.getDataCount() + " src::" // + dataPacket.getSocketAddress()); // // requestBlockingQueue.offer(new // ServerDataEvent(requestHandler,datagramChannel, dataPacket)); // } // public void processData(SelectionKey key, DataPacket dataPacket) { byte[] dataCopy = new byte[dataPacket.getDataCount()]; System.arraycopy(dataPacket.getData(), 0, dataCopy, 0, dataPacket.getDataCount()); dataPacket.setData(dataCopy); LOGGER.debug("receiving::" + new String(dataPacket.getData()) + " size::" + dataPacket.getDataCount() + " src::" + dataPacket.getSocketAddress()); //requestBlockingQueue.offer(new ServerDataEvent(key, dataPacket)); RequestQueue.getInstance().pushData(new ServerDataEvent(key, dataPacket)); } public void run() { ServerDataEvent dataEvent; while (isRunFlag()) { // Wait for data to become available // synchronized(queue) { // while(queue.isEmpty()) { // try { // queue.wait(); // } catch (InterruptedException e) { // } // } // dataEvent = (ServerDataEvent) queue.remove(0); // } try { dataEvent = (ServerDataEvent) RequestQueue.getInstance().popData(); // dataEvent.requestHandler.send(dataEvent.datagramChannel,dataEvent.dataPacket); if (!sendData(dataEvent.key, dataEvent.dataPacket)) { //requestBlockingQueue.offer(dataEvent); RequestQueue.getInstance().pushData(dataEvent); synchronized (breakCounter) { breakCounter++; } } else { synchronized (counter) { counter++; } } LOGGER.debug("failed packet count::"+ breakCounter + "success packet count::"+ counter); // send to task processor queue // taskProcessor.processData(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // Return to sender } } public boolean sendData(SelectionKey key, DataPacket dp) { try { DatagramChannel datagramChannel = (DatagramChannel) key.channel(); ByteBuffer buf = ByteBuffer.wrap(dp.getData()); SocketAddress sa = dp.getSocketAddress(); LOGGER.debug("sending::" + new String(dp.getData()) + " size::" + dp.getDataCount() + " src::" + dp.getSocketAddress()); int bytesSent = datagramChannel.send(buf, sa); if (buf.remaining() > 0) { // ... or the socket's buffer fills up return false; } } catch (Exception e) { e.printStackTrace(); return false; } return true; } public void stopThread() { this.setRunFlag(false); // try { // Thread.sleep(1); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // this.interrupt(); } private boolean isRunFlag() { return runFlag; } private void setRunFlag(boolean runFlag) { this.runFlag = runFlag; } }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.orm.emoji; import java.util.List; /** * Emoji配置 * * @author 小流氓[176543888@qq.com] * @since 3.4 */ class EmojiConfig { private String emoji; private List<String> aliases; public String getEmoji() { return emoji; } public void setEmoji(String emoji) { this.emoji = emoji; } public List<String> getAliases() { return aliases; } public void setAliases(List<String> aliases) { this.aliases = aliases; } @Override public String toString() { return "Emoji [emoji=" + emoji + ", aliases=" + aliases + "]"; } }
package jgame.entity.mob.ai; import jgame.entity.Mob; import jgame.level.Path; /** * * @author hector */ public class Killer extends Seeker { private static final int SEEK_RADIUS = 15; public Killer(Mob mob) { super(mob); } @Override public void update(int delta) { if(target == null) seek(SEEK_RADIUS, delta); else if(target.isDead()) target = null; else { Path path = mob.getPathTo(target); if(path.getLength() < 3) mob.attack(); else mob.follow(path, delta); } } }
package com.t.core.remote; /** * @author tb * @date 2018/12/18 17:02 */ public enum RemoteEventType { CONNECT, CLOSE, READER_IDLE, WRITER_IDLE, ALL_IDLE, EXCEPTION, ; }
package services; import models.Reservation; import models.Performance; import readwrite.write.Writer; public class ReservationService { private Reservation reservation; private final Writer audit = new Writer(); public boolean confirmReservation(Reservation reservation, String answer) { audit.writeData("ReservationService", "confirmReservation"); return answer.equals("YES"); } public boolean enoughSeatsAvailable(int number, Performance performance) { audit.writeData("ReservationService","enoughSeatsAvailable"); int numberOfSeats = performance.getAvailableSeats().size(); return numberOfSeats >= number; } /* public void chooseSeat(int number, String typeOfSeat, Performance performance){ audit.writeData("ReservationService", "chooseSeat"); PerformanceService performanceService = new PerformanceService(); for (int i = 0; i < number; i++) { int index = performanceService.getFirstOfTypeIndex(typeOfSeat, performance); if (index != -1) { Seat newSeat = performance.getAvailableSeats().get(index); reservation.getSeats().add(newSeat); performanceService.deleteSeat(index, spectacle); } } } */ }
package cliente; public class CirculoNotFoundException extends Exception{ /** * */ private static final long serialVersionUID = -7331861696548215622L; public CirculoNotFoundException(String circuloId) { } public String getCirculoNaoEncontrado() { return null; } }
package com.pdd.pop.sdk.http.api.response; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.PopBaseHttpResponse; public class PddGoodsCpsUnitChangeResponse extends PopBaseHttpResponse{ /** * 是否修改成功 */ @JsonProperty("is_change_success") private Boolean isChangeSuccess; public Boolean getIsChangeSuccess() { return isChangeSuccess; } }
package scater.Handle; import javax.servlet.http.HttpSession; import org.json.JSONObject; import scater.Service.FoodOrderService; import csAsc.EIO.MsgEngine.CEIOMsgRouter.CParam; public class FoodOrderHandle extends CMsgBaseHandle { @Override public int handleMsg(CParam param) throws Exception { JSONObject data=getReqMessage(param); JSONObject user=getCurrentUser(param); String op=data.getString("op"); JSONObject result=null; FoodOrderService service=new FoodOrderService(param); switch(op){ case "newOrder": //下订单 data.put("user", user); result=service.newOrder(data); break; case "payOrder": //支付功能,目前只是一个模拟接口 result=service.payOrder(data); break; case "cancelOrder": //取消订单 result=service.cancelOrder(data); break; case "queryOrder": //查询自己的以往订单信息 data.put("userId", user.getInt("id")); result=service.queryOrder(data); break; } param.respData.append(result.toString()); return 0; } }
package com.ekuaibao.invoice; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import com.google.gson.Gson; import com.tenpay.TencentSM.SM2Algo; import com.tenpay.TencentSM.SM3Algo; import com.tenpay.TencentSM.SM4Algo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.GZIPInputStream; import org.xerial.snappy.Snappy; import java.util.List; public class Sm2SDK { private static final int BUFFER = 4096; private static String id = "trustsql.qq.com"; public String[] GenerateBase64KeyPair() throws Exception { String[] keyPairs={"",""}; try { SM2Algo sm2algo = new SM2Algo(); sm2algo.initCtx(); String[] tmpKeyPairs = sm2algo.generateBase64KeyPair(); sm2algo.freeCtx(); String strHex = new String(Base64.decodeBase64(tmpKeyPairs[0])); strHex = strHex.substring(0,64); keyPairs[0] = Base64.encodeBase64String(Hex.decodeHex(strHex.toCharArray())); strHex = new String(Base64.decodeBase64(tmpKeyPairs[1])); strHex = strHex.substring(0,130); keyPairs[1] = Base64.encodeBase64String(Hex.decodeHex(strHex.toCharArray())); }catch(Exception e) { throw new Exception("generate base64 key pair fail"); } return keyPairs; } /* 服务商通讯请求签名 * IN PARAM: * sHttpMethod : http请求的method, 例如:POST * sUrlPath : 请求url的path,例如: /v2/ReceiptApply * iTimestamp : http请求头Authorization中的timestamp字段,表示当前utc时间戳,单位:秒 * sHttpBody: http请求的原始body * sSpPubkeyBase64: 服务商的sm2公钥(base64编码) * sSpPrikeyBase64: 服务商的sm2私钥(base64编码) * RETURN: * 成功返回 保存签名后的内容(作base16编码) * 失败抛出异常 */ public String Sm2SignForSp(String sHttpMethod, String sUrlPath, long lTimestamp, String sHttpBody, String sSpPubkeyBase64, String sSpPrikeyBase64) throws Exception { String toBeSignStr = sHttpMethod + "\n" + sUrlPath + "\n" + String.valueOf(lTimestamp) + "\n" + sHttpBody + "\n"; return _Sm2Sign(toBeSignStr, false, sSpPubkeyBase64, sSpPrikeyBase64); } /* 服务商通讯应答验签 * IN PARAM: * sTimestamp: http应答头中的"BERS-Timestamp"对应的内容, 表示服务端应答的utc时间搓,单位:秒 * sSignatureBase16: http应答头中的"BERS-Signature"对应的内容, 表示服务端应答的签名信息 * sHttpBody: http应答的原始body * sSpvPubkeyBase64: 服务端用于验签的sm2公钥(线下跟服务端沟通获取) * RETURN: * 验签成功返回true,失败返回false */ public boolean Sm2CheckSignForSpv(String sTimestamp, String sHttpBody, String sSignatureBase16, String sSpvPubkeyBase64) { String sRawString = sTimestamp + "\n" + sHttpBody + "\n"; return _Sm2Verify(sRawString, false, sSignatureBase16, sSpvPubkeyBase64); } /* 企业上链签名接口 * IN PARAM: * sToBeSignedBase16: Apply请求返回的to_be_signed字段 * sEpPubkeyBase64: 企业的sm2公钥(base64编码) * sEpPrikeyBase64: 企业的sm2私钥(base64编码) * OUT PARAM: * RETURN: * 成功返回签名后的内容(作base16编码), * 失败抛出异常 */ public String Sm2SignForEp(String sToBeSignedBase16, String sEpPubkeyBase64, String sEpPrikeyBase64) throws Exception { return _Sm2Sign(sToBeSignedBase16, true, sEpPubkeyBase64, sEpPrikeyBase64); } /* 构造请求中dst_addr.sp_sign字段 * IN PARAM: * sPubkeyBase64: dst_addr.pubkey字段 * sSpId: dst_addr.sp_id字段 * sSpPubkeyBase64: sp_id对应服务商的sm2公钥(base64编码) * sSpPrikeyBase64: sp_id对应服务商的sm2私钥(base64编码) * OUT PARAM: * RETURN: * 成功返回签名后的内容(作base16编码), 应该赋值给dst_addr.sp_sign字段 * 失败抛出异常 */ public String Sm2SignForDstAddr(String sPubkeyBase64, String sSpId, String sSpPubkeyBase64, String sSpPrikeyBase64) throws Exception { String sRawString = sPubkeyBase64 + sSpId; String sToBeSignBase16 = String.valueOf(Hex.encodeHex(sRawString.getBytes())); return _Sm2Sign(sToBeSignBase16, true,sSpPubkeyBase64, sSpPrikeyBase64); } private String _uncompressData(int compType, String compData) throws Exception { try { String strUncompData=null; byte[] uncompData={}; if (compType == 1) // gzip { uncompData = decompress(Base64.decodeBase64(compData.getBytes())); }else if (compType == 2) // snappy { uncompData = Snappy.uncompress(Base64.decodeBase64(compData.getBytes())); }else { throw new Exception("unknow compress type"); } strUncompData = new String(uncompData,"utf-8"); return strUncompData; }catch(Exception e) { throw new Exception("uncompress data fail"); } } private String _DecodeData( String encodeData, String key) throws Exception { String decodeData; try { byte[] plaintext = SM4Algo.decrypt_ecb(Base64.decodeBase64(encodeData),Base64.decodeBase64(key)); decodeData = Base64.encodeBase64String(plaintext); return decodeData; }catch(Exception e) { throw new Exception("decode data fail"); } } public String _Sm2Sign(String toBeSign, boolean bNotUseSm3,String sSpPubkeyBase64, String sSpPrikeyBase64) throws Exception { byte[] hash={}; byte[] sign={}; try { String priKeyHex = Hex.encodeHexString(Base64.decodeBase64(sSpPrikeyBase64)); byte[] priKeyByte = Base64.encodeBase64(priKeyHex.getBytes()); String pubKeyHex = Hex.encodeHexString(Base64.decodeBase64(sSpPubkeyBase64)); byte[] pubKeyByte = Base64.encodeBase64(pubKeyHex.getBytes()); SM2Algo sm2algo = new SM2Algo(); sm2algo.initCtx(); if (!bNotUseSm3) { SM3Algo sm3 = new SM3Algo(); sm3.update(toBeSign.getBytes()); hash = sm3.digest(); sign = sm2algo.sign(hash, id.getBytes(), Base64.decodeBase64(pubKeyByte),Base64.decodeBase64(priKeyByte)); }else { sign = sm2algo.sign(Hex.decodeHex(toBeSign.toCharArray()), id.getBytes(), Base64.decodeBase64(pubKeyByte),Base64.decodeBase64(priKeyByte)); } sm2algo.freeCtx(); }catch(Exception e) { throw new Exception("sm sign fail"); } return Hex.encodeHexString(sign); } public boolean _Sm2Verify(String msg, boolean isHash, String sSignatureBase16, String pubKeyBase64) { boolean result=false; try { byte[] hashMsg={}; SM2Algo sm2algo = new SM2Algo(); sm2algo.initCtx(); String pubKeyHex = Hex.encodeHexString(Base64.decodeBase64(pubKeyBase64)); byte[] pubKeyByte = Base64.encodeBase64(pubKeyHex.getBytes()); if (!isHash) { SM3Algo sm3 = new SM3Algo(); sm3.update(msg.getBytes()); hashMsg = sm3.digest(); result = sm2algo.verify(hashMsg, id.getBytes(), Hex.decodeHex(sSignatureBase16.toCharArray()), Base64.decodeBase64(pubKeyByte)); }else { result = sm2algo.verify(msg.getBytes(), id.getBytes(), Hex.decodeHex(sSignatureBase16.toCharArray()), Base64.decodeBase64(pubKeyByte)); } sm2algo.freeCtx(); }catch(Exception e) { return false; } return result; } /** * 数据解压缩 * * @param is * @param os * @throws Exception */ private void decompress(InputStream is, OutputStream os) throws Exception { GZIPInputStream gis = new GZIPInputStream(is); int count; byte data[] = new byte[BUFFER]; while ((count = gis.read(data, 0, BUFFER)) != -1) { os.write(data, 0, count); } gis.close(); } /** * 数据解压缩 * * @param data * @return * @throws Exception */ private byte[] decompress(byte[] data) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(data); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 解压缩 decompress(bais, baos); data = baos.toByteArray(); baos.flush(); baos.close(); bais.close(); return data; } }
package com.chaojicode; public class TopEngine implements Engine { @Override public void run() { System.out.println("我是顶级跑车引擎,点火启动"); } }
package play; /** * @author husan * @Date 2013-10-15 * @description */ public class InterfaceImplementTest { public static void main(String[] args) { Interface1 ii1 = new InterfaceImplement1(); ii1.method1(); } }
package com.freakybyte.movies.control.movies.constructor; /** * Created by Jose Torres on 20/10/2016. */ public interface GridMoviesPresenter { void getMovies(int page); void setFilterType(int filter); int getFilterType(); void getMovieDetail(int id); void onDestroy(); void cancelDownload(); }
package de.mbur.acme.storage; import java.time.LocalDateTime; import javax.inject.Inject; import de.mbur.acme.User; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import static org.assertj.core.api.Assertions.assertThat; @ActiveProfiles("MySQL-Test") @DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @Transactional(propagation = Propagation.NOT_SUPPORTED) class UserPersistenzTest { private static final Logger LOG = LoggerFactory.getLogger(UserPersistenzTest.class); @Inject private UserRepository userRepository; @Test void test() { LOG.debug("User repository: {}", userRepository); assertThat(userRepository).as("There is an user repository").isNotNull(); final User user = new User(); user.setUsername("hwurst"); final User save = userRepository.save(user); assertThat(save.getId()).as("User has an id after save").isNotNull(); assertThat(save.getCreated()).as("User has a created time stamp after save").isBeforeOrEqualTo( LocalDateTime.now()); userRepository.delete(save); } }
/* * Copyright 2017 Rundeck, Inc. (http://rundeck.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rundeck.client.api.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.rundeck.client.util.DataOutput; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; @JsonIgnoreProperties(ignoreUnknown = true) @XmlRootElement() public class JobItem implements DataOutput { private String id; private String name; private String group; private String project; private String description; private String href; private String permalink; private Long averageDuration; @XmlElement() public String getId() { return id; } public void setId(String id) { this.id = id; } @XmlElement() public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement() public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } @XmlElement public String getProject() { return project; } public void setProject(String project) { this.project = project; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @XmlAttribute() public String getHref() { return href; } public void setHref(String href) { this.href = href; } @XmlElement() public String getPermalink() { return permalink; } public void setPermalink(String permalink) { this.permalink = permalink; } @Override public String toString() { return "org.rundeck.client.api.model.JobItem{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", group='" + group + '\'' + ", project='" + project + '\'' + ", description='" + description + '\'' + ", href='" + href + '\'' + ", permalink='" + permalink + '\'' + '}'; } public Map<Object, Object> toMap() { HashMap<Object, Object> map = new LinkedHashMap<>(); map.put("id", getId()); map.put("name", getName()); if (null != getGroup()) { map.put("group", getGroup()); } map.put("project", getProject()); map.put("href", getHref()); map.put("permalink", getPermalink()); map.put("description", getDescription()); if(null!=getAverageDuration()){ map.put("averageDuration", getAverageDuration()); } return map; } @Override public Map<?, ?> asMap() { return toMap(); } public String toBasicString() { return String.format("%s %s%s", id, group != null ? group + "/" : "", name != null ? name : ""); } @XmlAttribute() public Long getAverageDuration() { return averageDuration; } public void setAverageDuration(Long averageDuration) { this.averageDuration = averageDuration; } }
/** * Copyright 2017 伊永飞 * * 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.yea.dispatcher.zookeeper; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooDefs.Perms; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Id; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.yea.core.dispatcher.DispatcherEndpoint; import com.yea.core.remote.AbstractEndpoint; import com.yea.core.serializer.ISerializer; import com.yea.core.serializer.fst.Serializer; import com.yea.remote.netty.client.NettyClient; import com.yea.remote.netty.server.NettyServer; /** * Zookeeper实现 * @author yiyongfei * */ public class ZookeeperDispatcher implements DispatcherEndpoint { private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperDispatcher.class); private ISerializer serializer; private CuratorFramework zkClient; private String host; private int port; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public void init(){ serializer = new Serializer(); RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5); zkClient = createWithOptions(host + ":" + port, retryPolicy, 10000, 10000); zkClient.start(); } private CuratorFramework createWithOptions(String connectionString, RetryPolicy retryPolicy, int connectionTimeoutMs, int sessionTimeoutMs) { //默认创建的根节点是没有做权限控制的 ACLProvider aclProvider = new ACLProvider() { private List<ACL> acl; @Override public List<ACL> getDefaultAcl() { if (acl == null) { List<ACL> acl = ZooDefs.Ids.CREATOR_ALL_ACL; acl.clear(); acl.add(new ACL(Perms.ALL, new Id("auth", "admin:admin"))); this.acl = acl; } return acl; } @Override public List<ACL> getAclForPath(String path) { return acl; } }; byte[] auth = "admin:admin".getBytes(); String namespace = "netty"; return CuratorFrameworkFactory.builder().aclProvider(aclProvider). authorization("digest", auth). connectionTimeoutMs(connectionTimeoutMs). sessionTimeoutMs(sessionTimeoutMs). connectString(connectionString). namespace(namespace). retryPolicy(retryPolicy).build(); } @Override public void register(AbstractEndpoint endpoint) throws Throwable { String registerName = endpoint.getRegisterName(); SocketAddress socketAddress = new InetSocketAddress(endpoint.getHost(), endpoint.getPort()); try { if (endpoint instanceof NettyClient) { String zkPath = "/DISPATCHER/CONSUMER/"+registerName+socketAddress; if (zkClient.checkExists().forPath(zkPath) != null) { logout(endpoint); } zkClient.create().creatingParentsIfNeeded().forPath(zkPath, serializer.serialize(socketAddress)); // 设置节点的cache @SuppressWarnings("resource") TreeCache treeCache = new TreeCache(zkClient, "/DISPATCHER/PROVIDER/"+registerName); TreeCacheListener listener = new ConsumerListener((NettyClient)endpoint); // 设置监听器和处理过程 treeCache.getListenable().addListener(listener); // 开始监听 treeCache.start(); LOGGER.info("" + endpoint.getHost() + ":" + endpoint.getPort() +"向" + getHost() + ":" + getPort() +"注册("+endpoint.getRegisterName()+")服务消费者成功"); } if (endpoint instanceof NettyServer) { String zkPath = "/DISPATCHER/PROVIDER/"+registerName+socketAddress; if (zkClient.checkExists().forPath(zkPath) != null) { logout(endpoint); } zkClient.create().creatingParentsIfNeeded().forPath(zkPath, serializer.serialize(socketAddress)); LOGGER.info("" + endpoint.getHost() + ":" + endpoint.getPort() +"向" + getHost() + ":" + getPort() +"注册("+endpoint.getRegisterName()+")服务提供者成功"); } } catch (Throwable ex) { LOGGER.error("" + endpoint.getHost() + ":" + endpoint.getPort() +"向" + getHost() + ":" + getPort() +"注册("+endpoint.getRegisterName()+")失败"); throw ex; } } @Override public void logout(AbstractEndpoint endpoint) throws Throwable { String registerName = endpoint.getRegisterName(); SocketAddress socketAddress = new InetSocketAddress(endpoint.getHost(), endpoint.getPort()); try { if (endpoint instanceof NettyClient) { zkClient.delete().forPath("/DISPATCHER/CONSUMER/"+registerName+socketAddress); LOGGER.info("" + endpoint.getHost() + ":" + endpoint.getPort() + "向" + getHost() + ":" + getPort() +"注销("+endpoint.getRegisterName()+")服务消费者成功"); } if (endpoint instanceof NettyServer) { zkClient.delete().forPath("/DISPATCHER/PROVIDER/"+registerName+socketAddress); LOGGER.info("" + endpoint.getHost() + ":" + endpoint.getPort() + "向" + getHost() + ":" + getPort() +"注销("+endpoint.getRegisterName()+")服务提供者成功"); } } catch (Throwable ex) { LOGGER.error("" + endpoint.getHost() + ":" + endpoint.getPort() + "向" + getHost() + ":" + getPort() +"注销("+endpoint.getRegisterName()+")失败"); throw ex; } } @Override public List<SocketAddress> discover(AbstractEndpoint endpoint) throws Throwable { try { List<SocketAddress> listAddress = new ArrayList<SocketAddress>(); List<String> list = zkClient.getChildren().forPath("/DISPATCHER/PROVIDER/"+endpoint.getRegisterName()); for(String str : list) { String[] tmp = str.split(":"); listAddress.add(new InetSocketAddress(tmp[0], Integer.parseInt(tmp[1]))); } return listAddress; } catch (Throwable ex) { LOGGER.error("" + endpoint.getHost() + ":" + endpoint.getPort() + "向" + getHost() + ":" + getPort() +"查找("+endpoint.getRegisterName()+")失败"); throw ex; } } class ConsumerListener implements TreeCacheListener { private NettyClient nettyClient; public ConsumerListener(NettyClient endpoint) { this.nettyClient = endpoint; } @Override public void childEvent(CuratorFramework zkClient, TreeCacheEvent zkEvent) throws Exception { ChildData data = zkEvent.getData(); if (data != null && data.getData().length > 0) { SocketAddress socketAddress = (SocketAddress) serializer.deserialize(data.getData()); LOGGER.info(zkEvent.getType() + data.getPath() + " 数据:" + socketAddress); switch (zkEvent.getType()) { case NODE_ADDED: //新增服务提供者节点时,客户端将连接新增的节点 nettyClient.connect(socketAddress); break; case NODE_REMOVED: nettyClient.disconnect(socketAddress); break; default: break; } } else { LOGGER.info("zookeeper data is null : " + zkEvent.getType()); } } } }
class Base { void f1() { System.out.println("base class function"); } public static void main(String... harsh) { Base b=new Child(); b.f1(); System.out.println("base class"); } } class Child extends Base { void f1() { System.out.println("child class function"); } }
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.*; import javax.servlet.http.*; import java.util.List; public class ViewBook extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); // request.setCharacterEncoding("UTF-8"); // response.setCharacterEncoding("UTF-8"); String searchField = request.getParameter("searchField"); //System.out.println("Search " + searchField); BookSetter objBook = new BookSetter(searchField); request.getRequestDispatcher("ViewBook.jsp").include(request, response); out.println("<div class='container'>"); List<BookSearch> list = DbUpdate.searchBook(objBook); out.println("<table class='table table-bordered'>"); out.println("<br><br><tr><th>Isbn</th><th>Book Title</th><th>Author Name</th><th>Check Out</th></tr>"); BorrowerSetter borrowerSetter = new BorrowerSetter(); for(BookSearch bookSearch:list){ //out.println("<tr><td>"+bookSearch.getIsbn()+"</td><td>"+bookSearch.getTitle()+"</td><td>"+bookSearch.getName()+"</td><td align=\"center\"><a href=\"#textboxid\" style=\"margin:auto; text-align:center; display:block;\" onClick=\"myPopUp()\">Click</a></td></tr>"); if (bookSearch.getStatus().equals("Available")) { out.println("<tr><td align=\"center\">"+bookSearch.getIsbn()+"</td><td align=\"center\">"+bookSearch.getTitle()+"</td><td align=\"center\">"+bookSearch.getName()+"</td><td align=\"center\"><a href='CheckOutBook?Isbn="+bookSearch.getIsbn()+"&Author="+bookSearch.getName()+"'>Available</a></td></tr>"); } else { out.println("<tr><td align=\"center\">"+bookSearch.getIsbn()+"</td><td align=\"center\">"+bookSearch.getTitle()+"</td><td align=\"center\">"+bookSearch.getName()+"</td><td align=\"center\">Not Available</td></tr>"); } //out.println("<tr><td align=\"center\">"+bookSearch.getIsbn()+"</td><td align=\"center\">"+bookSearch.getTitle()+"</td><td align=\"center\">"+bookSearch.getName()+"</td><td align=\"center\"><a href='CheckOutBook?Isbn="+bookSearch.getIsbn()+"&Author="+bookSearch.getName()+"&listSearch="+list+"'>Click</a></td></tr>"); //out.println("<tr><td>"+bookSearch.getIsbn()+"</td><td>"+bookSearch.getTitle()+"</td></tr>"); } out.println("</table>"); out.println("</div>"); out.close(); } }
package com.social.server.service.impl; import com.social.server.dao.EventRepository; import com.social.server.dao.UserRepository; import com.social.server.dto.EventDto; import com.social.server.entity.Event; import com.social.server.entity.EventType; import com.social.server.service.EventService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Slf4j @Service public class EventServiceImpl implements EventService { private final EventRepository eventRepository; private final UserRepository userRepository; @Autowired public EventServiceImpl(EventRepository eventRepository, UserRepository userRepository) { this.eventRepository = eventRepository; this.userRepository = userRepository; } @Override public Page<EventDto> findBy(long userId, int page) { return eventRepository.findByUserFriendsIdInOrderByDateDesc(userId, PageRequest.of(page, 10)).map(EventDto::of); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public void createEvent(long userId, long targetId, String targetActionName, EventType type) { log.debug("Create new event userId={}; targetId={}; targetActionName={}; type={}", userId, targetId, targetActionName, type); Event event = new Event(); event.setType(type); event.setTargetActionName(targetActionName); event.setTargetActionId(targetId); event.setUser(userRepository.getOne(userId)); log.debug("Save event"); eventRepository.save(event); log.debug("Creation completed successfully"); } private void validate(long userId, long targetId, EventType type) { if (userId == 0 || targetId == 0 || type == null) { throw new IllegalArgumentException(); } } }
package ex01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; public class ProductDAO { //데이터접속 public Connection con() throws Exception{ String driver = "oracle.jdbc.driver.OracleDriver"; String url = "jdbc:oracle:thin:@localhost:1521:xe"; String user = "system"; String password = "1234"; Class.forName(driver); Connection con=DriverManager.getConnection(url, user, password); return con; } //데이터 입력메소드 생성하기 public void insert(ProductVO vo) throws Exception{ String sql="insert into tbl_product (pno,pname,price) values (?,?,?)"; PreparedStatement ps=con().prepareStatement(sql); ps.setString(1, vo.getPno()); ps.setString(2, vo.getPname()); ps.setInt(3,vo.getPrice()); ps.execute(); con().close(); } //데이터 목록 메소드만들기 public ArrayList<ProductVO> list()throws Exception{ ArrayList<ProductVO> array=new ArrayList<ProductVO>(); String sql="select * from tbl_product"; PreparedStatement ps=con().prepareStatement(sql); ResultSet rs=ps.executeQuery(); while(rs.next()) { ProductVO vo=new ProductVO(); vo.setPno(rs.getNString("pno")); vo.setPname(rs.getNString("pname")); vo.setPrice(rs.getInt("price")); array.add(vo); } return array; } }
package com.example.daniel.podcastplayer.fragment; import android.app.ActivityOptions; import android.content.Intent; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import com.example.daniel.podcastplayer.R; import com.example.daniel.podcastplayer.activity.PodcastActivity; import com.example.daniel.podcastplayer.adapter.ImageAdapter; import com.example.daniel.podcastplayer.data.DbHelper; /** * A simple {@link Fragment} subclass. */ public class SubscriptionsFragment extends Fragment { private GridView gv; public SubscriptionsFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_subscriptions, container, false); gv = (GridView)v.findViewById(R.id.subs_gv); gv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor c = ((ImageAdapter)parent.getAdapter()).getCursor(); c.moveToPosition(position); Intent i = new Intent(view.getContext(), PodcastActivity.class); i.putExtra(DbHelper.Tbls.COLUMN_ID, c.getString(c.getColumnIndex(DbHelper.Tbls.COLUMN_ID))); //Shared element transition if (Build.VERSION.SDK_INT >= 21) { ActivityOptions transitionOptions = ActivityOptions.makeSceneTransitionAnimation(getActivity(), view, getString(R.string.transition_artwork)); startActivity(i, transitionOptions.toBundle()); } else startActivity(i); } }); return v; } @Override public void onResume() { super.onResume(); Cursor c = DbHelper.getInstance(getContext()).getPodcastsCursor(); if (c.getCount() > 0) { gv.setAdapter(new ImageAdapter(getContext(), c)); } else{ c.close(); gv.setVisibility(View.GONE); getView().findViewById(R.id.podcasts_message_tv).setVisibility(View.VISIBLE); } } }
package utils; import java.util.HashMap; import org.json.JSONObject; import com.baidu.aip.ocr.AipOcr; public class BaiDuOCR { //设置APPID/AK/SK public static final String APP_ID = "16730582"; public static final String API_KEY = "I6Z5VNyvKVgXGGpOCsYtRM1P"; public static final String SECRET_KEY = "pRUMiBV1K6YjtQjMBKiQkcRbeqmu4t8Z"; /** * @category通用文字识别(普通版,50000次/天 免费) * @param PicPath * @return */ public static String startOCR(String PicPath) { // 初始化一个AipOcr AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY); // 可选:设置网络连接参数 client.setConnectionTimeoutInMillis(2000); client.setSocketTimeoutInMillis(60000); // 可选:设置代理服务器地址, http和socket二选一,或者均不设置 //client.setHttpProxy("proxy_host", proxy_port); // 设置http代理 //client.setSocketProxy("proxy_host", proxy_port); // 设置socket代理 // 可选:设置log4j日志输出格式,若不设置,则使用默认配置 // 也可以直接通过jvm启动参数设置此环境变量 System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties"); // 调用接口 String path = PicPath; JSONObject res = client.basicGeneral(path, new HashMap<String, String>()); String result = res.getJSONArray("words_result").toString(); //System.out.println(result); return result; } /** * @category通用文字识别高精度版(500次/天 免费) * @param args */ public static String startOCR_Heigh(String PicPath) { // 传入可选参数调用接口 HashMap<String, String> options = new HashMap<String, String>(); options.put("detect_direction", "true"); options.put("probability", "true"); AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY); // 参数为本地图片路径 String image = PicPath; JSONObject res = client.basicAccurateGeneral(image, options); String text = res.getJSONArray("words_result").toString(); return text; } public static void main(String[] args) { String text = startOCR_Heigh("C:\\Users\\lenovo\\Desktop\\ab\\1526.png"); System.out.print(text); } }
package com.karya.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.karya.dao.IUserRoleDAO; import com.karya.model.Login001MB; import com.karya.model.Role001MB; import com.karya.model.UserRole001MB; import com.karya.service.IUserRoleService; @Service("RoleService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class UserRoleService implements IUserRoleService { @Autowired private IUserRoleDAO roleDAO; @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void userRoleAddAction(UserRole001MB userrole001mb) { roleDAO.userRoleAddAction(userrole001mb); } public UserRole001MB userRoleEditAction(int id) { return roleDAO.userRoleEditAction(id); } public void userRoleDeleteAction(int id) { roleDAO.userRoleDeleteAction(id); } public List<UserRole001MB> listallusers() { return roleDAO.listallusers(); } public List<Role001MB> getRoleList() { return roleDAO.getRoleList(); } public List<Login001MB> getUserList() { return roleDAO.getUserList(); } }
package company.classes; import java.util.Locale; import java.util.Scanner; /** * Class function utils */ public class FunUtils { /** * Rewrites to US output format and rounding numbers * @param number Number * @return Reformatting number */ public static String floatFromat (final double number){ final Locale locale = Locale.getDefault(); Locale.setDefault(Locale.US); final String result = String.format("%6.2f", number); Locale.setDefault(locale); return result; } /** * Is this number double? * @param str Input data * @return This number is double */ public static double isDouble(final Scanner str) { while (!str.hasNextDouble()) { System.out.println("That not a number!"); str.next(); } return str.nextDouble(); } /** * Is this number positive? * @param str Input data * @return This number is positive */ public static int isPositive(final Scanner str) { int positive = isInt(str); while (positive < 0) { System.out.println("That not a positive number!"); positive = isInt(str); } return positive; } /** * Is this number int? * @param str Input data * @return This number is int */ private static int isInt(final Scanner str) { while (!str.hasNextInt()) { System.out.println("That not a number!"); str.next(); } return str.nextInt(); } }
import java.util.Scanner; public class Main10 { /** * * xcopy /s c:\ d:\, * 参数1:命令字xcopy * 参数2:字符串/s * 参数3:字符串c:\ * 参数4: 字符串d:\ * 请编写一个参数解析程序,实现将命令行各个参数解析出来。 */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); while(scanner.hasNextLine()) { String str = scanner.nextLine(); int count = 0; int yhcount = 0; String [] array = str.split("\\s+"); for(String s : array) { count++; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='\"'); { yhcount++; System.out.print(" "+yhcount);yhcount++; } } System.out.println(count); count = count-(yhcount/2); } System.out.println(count); } } }
package com.company; public class Cliente { private int idCliente; private int tiempoArribo; private int tiempoSeAtendio; private int tiempoServicio; public Cliente(int id,int t_a,int t_s_a,int t_s){ this.idCliente = id; this.tiempoArribo = t_a; this.tiempoSeAtendio = t_s_a; this.tiempoServicio = t_s; } public int getIdCliente() { return idCliente; } public void setIdCliente(int idCliente) { this.idCliente = idCliente; } public int getTiempoArribo() { return tiempoArribo; } public void setTiempoArribo(int tiempoArribo) { this.tiempoArribo = tiempoArribo; } public int getTiempoSeAtendio() { return tiempoSeAtendio; } public void setTiempoSeAtendio(int tiempoSeAtendio) { this.tiempoSeAtendio = tiempoSeAtendio; } public int getTiempoServicio() { return tiempoServicio; } public void setTiempoServicio(int tiempoServicio) { this.tiempoServicio = tiempoServicio; } }
package com.experian.brand.enums; /** * 榜单类别 * 榜单性质、榜单大类、榜单小类 * @author e00898a * */ public enum BrandType { NATURE(),BIG(),SMALL() }
package com.intel.realsense.camera; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.intel.realsense.librealsense.Device; import com.intel.realsense.librealsense.DeviceList; import com.intel.realsense.librealsense.RsContext; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class PresetsActivity extends AppCompatActivity { private static final String TAG = "librs camera presets"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); } @Override protected void onResume() { super.onResume(); TextView message = findViewById(R.id.list_view_title); final Resources resources = getResources(); String[] presets; try { presets = resources.getAssets().list("presets"); } catch (IOException e) { message.setText("No presets found"); return; } if(presets.length == 0) { message.setText("No presets found"); return; } message.setText("Select a preset:"); final ListView listview = findViewById(R.id.list_view); final ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.files_list_view, presets); listview.setAdapter(adapter); final String[] finalPresets = presets; listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { RsContext ctx = new RsContext(); try(DeviceList devices = ctx.queryDevices()) { if(devices.getDeviceCount() == 0){ Log.e(TAG, "failed to set preset, no device found"); finish(); } try(Device device = devices.createDevice(0)){ if(device == null || !device.isInAdvancedMode()){ Log.e(TAG, "failed to set preset, device not in advanced mode"); finish(); } final String item = finalPresets[position]; try { InputStream is = resources.getAssets().open("presets/" + item); byte[] buffer = new byte[is.available()]; is.read(buffer); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(buffer); baos.close(); is.close(); device.loadPresetFromJson(buffer); } catch (IOException e) { Log.e(TAG, "failed to set preset, failed to open preset file, error: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "failed to set preset, error: " + e.getMessage()); }finally { finish(); } } } } }); } }
import processing.core.*; import processing.xml.*; import java.applet.*; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.MouseEvent; import java.awt.event.KeyEvent; import java.awt.event.FocusEvent; import java.awt.Image; import java.io.*; import java.net.*; import java.text.*; import java.util.*; import java.util.zip.*; import java.util.regex.*; public class MandelOrbits extends PApplet { Loopy loopy; int g_orbitI = width/2; int g_orbitJ = height/2; boolean g_drawAxes = true; boolean g_drawSet = true; boolean g_drawOrbits = true; boolean g_continuousOrbitUpdate = true; public void setup() { //size(screen.width,screen.height); size(640,480); float aspect = PApplet.parseFloat(height)/PApplet.parseFloat(width); loopy = new Loopy( -2.0f, 1.0f , -3.f*aspect/2.f, 3.f*aspect/2.f ); if( g_continuousOrbitUpdate) { frameRate(10); } else { noLoop(); } } public void draw() { background(0); loopy.draw(g_orbitI,g_orbitJ); } class Loopy { Loopy( float x0, float x1, float y0, float y1) { m_x0 = x0; m_x1 = x1; m_dx = ( m_x1-m_x0)/PApplet.parseFloat(width); m_y0 = y0; m_y1 = y1; m_dy = ( m_y1-m_y0)/PApplet.parseFloat(height); println(m_x0 + " " + m_x1 + " " + m_dx); println(m_y0 + " " + m_y1 + " " + m_dy); } public void draw( int orbitI, int orbitJ) { int i, j, n; int itns; int max_itns=511;//255; float zi, zitemp, zj; float ci, cj; n=0; if( g_drawSet) { loadPixels(); for( j=0, cj=m_y0; j<height; j++, cj+=m_dy) { for( i=0, ci=m_x0; i<width; i++, ci+=m_dx) { for( itns=0, zi=ci, zj=cj; zi*zi+zj*zj<=4.f && itns<max_itns; itns++) { zitemp = zi*zi - zj*zj + ci; zj = 2.f*zi*zj + cj; zi = zitemp; } //print( itns + ", "); //if( itns != 255) { pixels[n] = color( itns, 255-itns, 255-itns);}//25*(itns%11) //if( itns != 255) { pixels[n] = color( 25*(itns%11), 100*(itns%3), 50*(itns%6));} if( itns != 255) { pixels[n] = color( 0, 0, 10*(itns%11));} //if( itns != 255) { pixels[n] = color( 22*(itns%11), 21*(itns%12), (20*(itns%13))%256);} //if( itns != 255) { pixels[n] = color( 0, 0, itns%256);} //if( itns != 255) { pixels[n] = color( random(255), random(255), itns%256);} n++; } // for( i=0; i<width; i++) } // for( j=0; j<height; j++) } // Plot orbit of coordinate (orbitI,orbitJ). int ii, jj; if( g_continuousOrbitUpdate) { i = mouseX; zi = ci = m_x0 + i*m_dx; j = mouseY; zj = cj = m_y0 + j*m_dy; } else { i = orbitI; zi = ci = m_x0 + i*m_dx; j = orbitJ; zj = cj = m_y0 + j*m_dy; } n = i + j*width; if( g_drawSet) { pixels[n ] = color(255); pixels[n+1 ] = color(255); pixels[n +width] = color(255); pixels[n+1+width] = color(255); updatePixels(); } if( g_drawAxes) { stroke(255,255,255, 32); line( 0, PApplet.parseInt( floor( (0.f-m_y0)/m_dy)), width, PApplet.parseInt( floor( (0.f-m_y0)/m_dy))); line( PApplet.parseInt( floor( (0.f-m_x0)/m_dx)), 0, PApplet.parseInt( floor( (0.f-m_x0)/m_dx)), height); } if( g_drawOrbits) { for( itns=0; zi*zi+zj*zj<=4.f && itns<max_itns; itns++) { zitemp = zi*zi - zj*zj + ci; zj = 2.f*zi*zj + cj; zi = zitemp; ii = PApplet.parseInt( floor( (zi-m_x0)/m_dx)); jj = PApplet.parseInt( floor( (zj-m_y0)/m_dy)); stroke((itns%6)*25 + 130); line( i, j, ii, jj); i = ii; j = jj; } fill(0,255,0); stroke(0,255,0); ellipse( i, j, 8, 8); if( g_continuousOrbitUpdate) { fill(255,0,0); stroke(255,0,0); ellipse( mouseX, mouseY, 8, 8); } else { fill(255,0,0); stroke(255,0,0); ellipse( orbitI, orbitJ, 8, 8); } } } // void draw() public void up( int fac) { m_y0+=(fac*m_dy); m_y1+=(fac*m_dy);} public void down( int fac) { m_y0-=(fac*m_dy); m_y1-=(fac*m_dy);} public void left( int fac) { m_x0+=(fac*m_dx); m_x1+=(fac*m_dx);} public void right( int fac) { m_x0-=(fac*m_dx); m_x1-=(fac*m_dx);} public void zoomin( int fac) { float x = (m_x1+m_x0)/2.f; float y = (m_y1+m_y0)/2.f; m_x0 = x - (x-m_x0)/fac; m_x1 = x + (m_x1-x)/fac; m_dx = (m_x1-m_x0)/width; m_y0 = y - (y-m_y0)/fac; m_y1 = y + (m_y1-y)/fac; m_dy = (m_y1-m_y0)/height; println( m_dx); println( m_dy); } public void zoomout( int fac) { float x = (m_x1+m_x0)/2.f; float y = (m_y1+m_y0)/2.f; m_x0 = x - (x-m_x0)*fac; m_x1 = x + (m_x1-x)*fac; m_dx = (m_x1-m_x0)/width; m_y0 = y - (y-m_y0)*fac; m_y1 = y + (m_y1-y)*fac; m_dy = (m_y1-m_y0)/height; } float m_x0, m_x1, m_dx; float m_y0, m_y1, m_dy; }; public void keyPressed() { if( key==CODED) { switch( keyCode) { case UP : loopy.up( 50); redraw(); break; case DOWN : loopy.down( 50); redraw(); break; case LEFT : loopy.left( 50); redraw(); break; case RIGHT: loopy.right(50); redraw(); break; } } else { switch( key) { case ' ': loopy.zoomin( 2); redraw(); break; case 'b': loopy.zoomout(2); redraw(); break; } } } public void mouseClicked() { g_orbitI = mouseX; g_orbitJ = mouseY; redraw(); } static public void main(String args[]) { PApplet.main(new String[] { "--bgcolor=#F0F0F0", "MandelOrbits" }); } }
package com.example.administrator.killdragonx.ThreadTest; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; /** * Created by Administrator on 2017/3/26 0026. */ public class ThirdThread { public static void main(String[] args) { FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { int i = 0; for (; i < 50; i++) { System.out.println(Thread.currentThread().getName() + " " + i); } return i; } }); // try { // System.out.println("子线程返回的结果:" + task.get()); // } catch (InterruptedException | ExecutionException e) { // e.printStackTrace(); // } // for (int i = 0; i < 50; i++) { System.out.println(Thread.currentThread().getName() + " " + i); if(i == 10){ new Thread(task, "新线程").start(); } } try { System.out.println("子线程返回的结果:" + task.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }
package com.spr.controller; import com.spr.exception.CoworkingSpaceNotFound; import com.spr.model.CoworkingSpace; import com.spr.model.Office; import com.spr.model.User; import com.spr.utils.InitialSpacesFactory; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.validation.Valid; import java.util.ArrayList; import java.util.List; /** * Created by cata_ on 1/5/2018. */ @Controller @RequestMapping(value = "/space") public class CoworkingSpaceController { // @Autowired // private CoworkingSpaceValidator coworkingSpaceValidator; // // @InitBinder // private void initBinder(WebDataBinder binder) { // binder.setValidator(coworkingSpaceValidator); // } private int coworkingSpaceId; @RequestMapping(value = "/create/message", method = RequestMethod.GET) public ModelAndView newCoworkingSpacePage(HttpSession session) { ModelAndView mav = new ModelAndView("my-account", "space", new CoworkingSpace()); String message = ""; message = "Space added successfully"; mav.addObject("message", message); mav.addObject("username", session.getAttribute("loggedUser")); return mav; } @RequestMapping(value = "/create", method = RequestMethod.GET) public ModelAndView afterCreateSendMessage(HttpSession session) { ModelAndView mav = new ModelAndView("add-space", "coworkingSpace", new CoworkingSpace()); List<String> amenities = new ArrayList<>(); amenities.add("coffee machine"); amenities.add("computer devices"); amenities.add("projector devices"); amenities.add("home cinema 5.1"); amenities.add("whiteboard device"); amenities.add("colored markers"); mav.addObject("generalAmenities", amenities); List<String> type = new ArrayList<>(); type.add("open space"); type.add("private office"); mav.addObject("type", type); List<Integer> officeNr = new ArrayList<>(); officeNr.add(1); officeNr.add(2); officeNr.add(3); officeNr.add(4); officeNr.add(5); officeNr.add(6); officeNr.add(7); officeNr.add(8); officeNr.add(9); officeNr.add(10); mav.addObject("numberOfOffices", officeNr); mav.addObject("username", session.getAttribute("loggedUser")); return mav; } @RequestMapping(value = "/create", method = RequestMethod.POST) public ModelAndView createNewCoworkingSpace(@ModelAttribute @Valid CoworkingSpace coworkingSpace, HttpServletResponse response, BindingResult result, final RedirectAttributes redirectAttributes, HttpSession session) { if (result.hasErrors()) return new ModelAndView("add-space"); String message = "Space " + coworkingSpace.getName().replaceAll(",", "") + " was successfully created."; ModelAndView mav = new ModelAndView("my-account", "user", new User()); mav.addObject("username", session.getAttribute("loggedUser")); List<String> userList = new ArrayList<>(); userList.add("mihai_Virgil@gmail.com"); userList.add("alina.gigel@yahoo.com"); userList.add("popescu-marcel@gmail.com"); userList.add("plic.sanzi@yahoo.com"); mav.addObject("userList", userList); List<CoworkingSpace> spaceList; try { spaceList = (List<CoworkingSpace>) session.getAttribute("loggedUserSpaces"); session.removeAttribute("loggedUserSpaces"); session.setAttribute("loggedUserSpaces", spaceList); if (spaceList == null) { spaceList = new ArrayList<>(); InitialSpacesFactory spacesFactory = new InitialSpacesFactory(); spaceList = spacesFactory.getFirstNSpaces(4); session.setAttribute("loggedUserSpaces", spaceList); } else { if (spaceList.size() == 0) { spaceList = new ArrayList<>(); InitialSpacesFactory spacesFactory = new InitialSpacesFactory(); spaceList = spacesFactory.getFirstNSpaces(4); session.setAttribute("loggedUserSpaces", spaceList); } } } catch (Exception e) { spaceList = new ArrayList<>(); InitialSpacesFactory spacesFactory = new InitialSpacesFactory(); spaceList = spacesFactory.getFirstNSpaces(4); session.setAttribute("loggedUserSpaces", spaceList); } spaceList.add(coworkingSpace); session.removeAttribute("loggedUserSpaces"); session.setAttribute("loggedUserSpaces", spaceList); mav.addObject("message", message); redirectAttributes.addFlashAttribute("message", message); return mav; } @RequestMapping(value = "/list", method = RequestMethod.GET) public ModelAndView coworkingSpaceListPage() { ModelAndView mav = new ModelAndView("coworkingSpace-list"); List<CoworkingSpace> coworkingSpaceList = new ArrayList<>(); mav.addObject("coworkingSpaceList", coworkingSpaceList); return mav; } @RequestMapping(value = "/edit", method = RequestMethod.GET) public ModelAndView manageSpace(HttpSession session) { ModelAndView mav = new ModelAndView("manage-space", "space", new CoworkingSpace()); mav.addObject("username", session.getAttribute("loggedUser")); List<CoworkingSpace> spaceList; try { spaceList = (List<CoworkingSpace>) session.getAttribute("loggedUserSpaces"); session.removeAttribute("loggedUserSpaces"); session.setAttribute("loggedUserSpaces", spaceList); if (spaceList == null) { spaceList = new ArrayList<>(); InitialSpacesFactory spacesFactory = new InitialSpacesFactory(); spaceList = spacesFactory.getFirstNSpaces(4); session.setAttribute("loggedUserSpaces", spaceList); } else { if (spaceList.size() == 0) { spaceList = new ArrayList<>(); InitialSpacesFactory spacesFactory = new InitialSpacesFactory(); spaceList = spacesFactory.getFirstNSpaces(4); session.setAttribute("loggedUserSpaces", spaceList); } } } catch (Exception e) { spaceList = new ArrayList<>(); InitialSpacesFactory spacesFactory = new InitialSpacesFactory(); spaceList = spacesFactory.getFirstNSpaces(4); session.setAttribute("loggedUserSpaces", spaceList); } mav.addObject("message", ""); mav.addObject("spaceList", spaceList); return mav; } @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET) public ModelAndView editCoworkingSpacePage(@PathVariable Integer id, HttpSession session) { ModelAndView mav = new ModelAndView("edit-space"); List<CoworkingSpace> spaceList; spaceList = (List<CoworkingSpace>) session.getAttribute("loggedUserSpaces"); CoworkingSpace spaceToEdit = null; for (CoworkingSpace s : spaceList) { if (s.getId() == id) { spaceToEdit = s; break; } } List<String> type = new ArrayList<>(); type.add("open space"); type.add("private office"); mav.addObject("type", type); mav.addObject("username", session.getAttribute("loggedUser")); mav.addObject("space", spaceToEdit); mav.addObject("message", ""); return mav; } @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST) public ModelAndView editCoworkingSpace(@ModelAttribute @Valid CoworkingSpace coworkingSpace, BindingResult result, @PathVariable Integer id, final RedirectAttributes redirectAttributes, HttpSession session) throws CoworkingSpaceNotFound { String message = ""; if (result.hasErrors()) { message = "Error editing space!"; redirectAttributes.addFlashAttribute("message", message); return new ModelAndView("manage-space"); } ModelAndView mav = new ModelAndView("manage-space", "space", new CoworkingSpace()); mav.addObject("username", session.getAttribute("loggedUser")); List<CoworkingSpace> spaceList; boolean found = false; spaceList = (List<CoworkingSpace>) session.getAttribute("loggedUserSpaces"); for (CoworkingSpace s : spaceList) { if (s.getId() == coworkingSpace.getId()) { found = true; s.setName(coworkingSpace.getName()); s.setISBN(coworkingSpace.getISBN()); s.setClosingHour(coworkingSpace.getClosingHour()); s.setOpeningHour(coworkingSpace.getOpeningHour()); s.setWebURL(coworkingSpace.getWebURL()); s.setOwnerEmail(coworkingSpace.getOwnerEmail()); s.setDescription(coworkingSpace.getDescription()); s.setFacebookUrl(coworkingSpace.getFacebookUrl()); s.setOwnerPhone(coworkingSpace.getOwnerPhone()); s.setTwitterUrl(coworkingSpace.getTwitterUrl()); break; } } if (!found) { message = "Space requested not found"; } else { message = "Space edited!"; } session.removeAttribute("loggedUserSpaces"); session.setAttribute("loggedUserSpaces", spaceList); mav.addObject("spaceList", spaceList); mav.addObject("message", message); redirectAttributes.addFlashAttribute("message", message); return mav; } @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) public ModelAndView deleteCoworkingSpace(@PathVariable Integer id, final RedirectAttributes redirectAttributes, HttpSession session) throws CoworkingSpaceNotFound { String message = ""; if (id == null) { message = "Error editing space!"; redirectAttributes.addFlashAttribute("message", message); return new ModelAndView("manage-space"); } ModelAndView mav = new ModelAndView("manage-space", "space", new CoworkingSpace()); mav.addObject("username", session.getAttribute("loggedUser")); List<CoworkingSpace> spaceList; List<CoworkingSpace> spaceListAfterDelete = new ArrayList<>(); spaceList = (List<CoworkingSpace>) session.getAttribute("loggedUserSpaces"); for (CoworkingSpace s : spaceList) { if (s.getId() != id) { spaceListAfterDelete.add(s); } } session.removeAttribute("loggedUserSpaces"); session.setAttribute("loggedUserSpaces", spaceListAfterDelete); message = "Space deleted!"; mav.addObject("spaceList", spaceListAfterDelete); mav.addObject("message", message); redirectAttributes.addFlashAttribute("message", message); return mav; } @RequestMapping(value = "/view/{id}", method = RequestMethod.GET) public ModelAndView viewSpace(@PathVariable Integer id, final RedirectAttributes redirectAttributes, HttpSession session) throws CoworkingSpaceNotFound { InitialSpacesFactory initialSpacesFactory = new InitialSpacesFactory(); List<CoworkingSpace> coworkingSpaces = initialSpacesFactory.getCoworkingSpaces(); CoworkingSpace cs = coworkingSpaces.get(id - 1); ModelAndView mav = new ModelAndView("view-space"); mav.addObject("cs", cs); List<String> userReservations = new ArrayList<>(); userReservations.add("Grigorescu Team at 16:30 for 4 hours in 20.01.2018"); userReservations.add("Manastur HUB at 10:30 for 2 hours in 23.01.2018"); mav.addObject("userReservations", userReservations); String message = ""; boolean isLogged = false; String user; try { user = (String) session.getAttribute("loggedUser"); if (user != null && user != "") { isLogged = true; mav.addObject("username", session.getAttribute("loggedUser")); } } catch (Exception e) { } mav.addObject("isLogged", isLogged); mav.addObject("currentSpID", id); redirectAttributes.addFlashAttribute("message", message); return mav; } @RequestMapping(value = "/create-office/{id}", method = RequestMethod.POST) public ModelAndView createOfiice(@PathVariable Integer id, @ModelAttribute @Valid Office office, BindingResult result, final RedirectAttributes redirectAttributes, HttpSession session) throws CoworkingSpaceNotFound { ModelAndView mav = new ModelAndView("add-space", "coworkingSpace", new CoworkingSpace()); List<String> amenities = new ArrayList<>(); amenities.add("coffee machine"); amenities.add("computer devices"); amenities.add("projector devices"); amenities.add("home cinema 5.1"); amenities.add("whiteboard device"); amenities.add("colored markers"); mav.addObject("generalAmenities", amenities); List<String> type = new ArrayList<>(); type.add("open space"); type.add("private office"); mav.addObject("type", type); List<Integer> officeNr = new ArrayList<>(); officeNr.add(1); officeNr.add(2); officeNr.add(3); officeNr.add(4); officeNr.add(5); officeNr.add(6); officeNr.add(7); mav.addObject("numberOfOffices", officeNr); mav.addObject("username", session.getAttribute("loggedUser")); List<Office> offices; try { offices = (List<Office>) session.getAttribute("addedOfficesList"); if (offices == null) { offices = new ArrayList<>(); offices.add(office); session.removeAttribute("addedOfficesList"); session.setAttribute("addedOfficesList", offices); } else if (offices.size() == 0) { offices = new ArrayList<>(); offices.add(office); session.removeAttribute("addedOfficesList"); session.setAttribute("addedOfficesList", offices); } } catch (Exception e) { offices = new ArrayList<>(); offices.add(office); session.removeAttribute("addedOfficesList"); session.setAttribute("addedOfficesList", offices); } return mav; } @RequestMapping(value = "/messageUs/{id}", method = RequestMethod.GET) public ModelAndView messageUs(@PathVariable Integer id, final RedirectAttributes redirectAttributes, HttpSession session) throws CoworkingSpaceNotFound { InitialSpacesFactory initialSpacesFactory = new InitialSpacesFactory(); List<CoworkingSpace> coworkingSpaces = initialSpacesFactory.getCoworkingSpaces(); CoworkingSpace cs = coworkingSpaces.get(id - 1); ModelAndView mav = new ModelAndView("view-space"); mav.addObject("cs", cs); String message = "Message to space " + cs.getName() + " was successfully sent."; boolean isLogged = false; String user; try { user = (String) session.getAttribute("loggedUser"); if (user != null && user != "") { isLogged = true; mav.addObject("username", session.getAttribute("loggedUser")); } } catch (Exception e) { } List<String> userReservations = new ArrayList<>(); userReservations.add("Grigorescu Team at 16:30 for 4 hours in 20.01.2018"); userReservations.add("Manastur HUB at 10:30 for 2 hours in 23.01.2018"); mav.addObject("userReservations", userReservations); mav.addObject("isLogged", isLogged); mav.addObject("currentSpID", id); mav.addObject("message", message); redirectAttributes.addFlashAttribute("message", message); return mav; } @RequestMapping(value = "/scheduleTour/{id}", method = RequestMethod.GET) public ModelAndView scheduleTour(@PathVariable Integer id, final RedirectAttributes redirectAttributes, HttpSession session) throws CoworkingSpaceNotFound { InitialSpacesFactory initialSpacesFactory = new InitialSpacesFactory(); List<CoworkingSpace> coworkingSpaces = initialSpacesFactory.getCoworkingSpaces(); CoworkingSpace cs = coworkingSpaces.get(id - 1); ModelAndView mav = new ModelAndView("view-space"); mav.addObject("cs", cs); String message = "Tour was scheduled at space " + cs.getName() + "."; boolean isLogged = false; String user; try { user = (String) session.getAttribute("loggedUser"); if (user != null && user != "") { isLogged = true; mav.addObject("username", session.getAttribute("loggedUser")); } } catch (Exception e) { } List<String> userReservations = new ArrayList<>(); userReservations.add("Grigorescu Team at 16:30 for 4 hours in 20.01.2018"); userReservations.add("Manastur HUB at 10:30 for 2 hours in 23.01.2018"); mav.addObject("userReservations", userReservations); mav.addObject("isLogged", isLogged); mav.addObject("currentSpID", id); mav.addObject("message", message); redirectAttributes.addFlashAttribute("message", message); return mav; } @RequestMapping(value = "/invite/{id}", method = RequestMethod.GET) public ModelAndView invite(@PathVariable Integer id, final RedirectAttributes redirectAttributes, HttpSession session) throws CoworkingSpaceNotFound { InitialSpacesFactory initialSpacesFactory = new InitialSpacesFactory(); List<CoworkingSpace> coworkingSpaces = initialSpacesFactory.getCoworkingSpaces(); CoworkingSpace cs = coworkingSpaces.get(id - 1); ModelAndView mav = new ModelAndView("view-space"); mav.addObject("cs", cs); String message = "Invitation sent!"; boolean isLogged = false; String user; try { user = (String) session.getAttribute("loggedUser"); if (user != null && user != "") { isLogged = true; mav.addObject("username", session.getAttribute("loggedUser")); } } catch (Exception e) { } List<String> userReservations = new ArrayList<>(); userReservations.add("Grigorescu Team at 16:30 for 4 hours in 20.01.2018"); userReservations.add("Manastur HUB at 10:30 for 2 hours in 23.01.2018"); mav.addObject("userReservations", userReservations); mav.addObject("isLogged", isLogged); mav.addObject("currentSpID", id); mav.addObject("message", message); redirectAttributes.addFlashAttribute("message", message); return mav; } @RequestMapping(value = "/pay/{id}", method = RequestMethod.GET) public ModelAndView reserve(@PathVariable Integer id, final RedirectAttributes redirectAttributes, HttpSession session) throws CoworkingSpaceNotFound { InitialSpacesFactory initialSpacesFactory = new InitialSpacesFactory(); List<CoworkingSpace> coworkingSpaces = initialSpacesFactory.getCoworkingSpaces(); CoworkingSpace cs = coworkingSpaces.get(id - 1); ModelAndView mav = new ModelAndView("view-space"); mav.addObject("cs", cs); String message = "Reservation to " + cs.getName() + " is made and payment is process by an external service"; boolean isLogged = false; String user; try { user = (String) session.getAttribute("loggedUser"); if (user != null && user != "") { isLogged = true; mav.addObject("username", session.getAttribute("loggedUser")); } } catch (Exception e) { } List<String> userReservations = new ArrayList<>(); userReservations.add("Grigorescu Team at 16:30 for 4 hours in 20.01.2018"); userReservations.add("Manastur HUB at 10:30 for 2 hours in 23.01.2018"); mav.addObject("userReservations", userReservations); mav.addObject("isLogged", isLogged); mav.addObject("currentSpID", id); mav.addObject("message", message); redirectAttributes.addFlashAttribute("message", message); return mav; } }
package factoring.fermat.mod; import factoring.fermat.FermatFact; import factoring.math.PrimeMath; import factoring.math.SquaresMod; import java.util.Collection; import static factoring.math.PrimeMath.mod; /** * It factorizes the number n, by * * For x^2 + 1 = y^2 mod 24 there is only two solution for x (0, 12). 24 = 2^3 * 3 * We need a n' = n * m = -1 mod 24. m = -n mod 24 does this since: * 5*-5 = -25 = -1 mod 24 * 7*-7 = -49 = -1 mod 24 * 11*-11 = -121 = -1 mod 24 * * Created by Thilo Harich on 29.11.2017. */ public class FermatResiduesBit extends FermatFact { private static final int MAX_FACTOR = 15; private final long minFactor = 3; private int[] residueClasses; protected int [] residuesArray = {2,3,5,7,11,13,17,19}; // 25, 27, 49 private long[] squares; private int[][] xArray; private int[] modOldInvert; private long modProd = 1; private int lastLevel = 0; private long xEnd; public FermatResiduesBit() { } public void init (long n) { xEnd = (n / minFactor + minFactor) / 2; int [] residueClasses = calculateResidueClasses(xEnd); init(n, residueClasses); } public void initSquares(int level, int mod) { // TODO use (-i)^2 = i^2 int square = 0; // in squares the bit k is set if k is a square modulo mod for (int i = 1; i < mod+1; i += 2) { squares[level] |= (1L << square); // we want to avoid the % and since (s+1)^2 = s^2 + 2s + 1, we always add i=2s+1 // we might move out the last call square += i; square = square>=mod ? (square>=2*mod ? square-2*mod : square-mod) : square; } } public void initX(int level, int mod, long n) { // TODO put the x with x^2 - n = 0 mod mod to the front // i.e. check if squareMinN == 0 then exchange j/2 with the front int exchangePos = 0; xArray[level] = new int[mod + 1]; int nMod = PrimeMath.mod(n, mod); int resIndex= 0; int squareMinN = nMod == 0 ? 0 : mod-nMod; for (int i = 1; i <2*mod; i += 2) { if (((1L << squareMinN) & squares[level]) != 0) { xArray[level][resIndex++] = i / 2; } // we want to avoid the % and since (s+1)^2 = s^2 + 2s + 1, we always add i=2s+1 // we might move out the last call squareMinN += i; squareMinN -= squareMinN >= mod ? (squareMinN >= 2*mod ? 2*mod : mod) : 0; } xArray[level][resIndex] = -1; } public void init( long n, int[] residueClasses) { long modProd = 1; modOldInvert = new int [residueClasses.length]; xArray = new int [lastLevel][]; squares = new long [lastLevel]; for (int level=0; level < residueClasses.length-1 && residueClasses[level] > 0; level++) { int mod = residueClasses[level]; initSquares(level, mod); initX(level, mod, n); if (mod > 0) { if (modProd > 1) modOldInvert[level] = (int) PrimeMath.invert(modProd, mod); modProd *= mod; } } } /** * Determine the residue classes for a given search interval, such that sieving with the * solutions has maximal speed. * This is we have a minimal number of solutions for the product of the generated * residueClasses. * if all P_i^(e_i) are equal it looks like a good solution. * * We get good results for products of the following numbers: * - 2 and small powers -> 8 (maximal : 4, avg : 2,3) * - 3 and small powers -> 9 (maximal : 2, avg : 2) * - any prime q (maximal (q+1)/2, avg ) * * * @param searchInterval * @return */ public int [] calculateResidueClasses(long searchInterval) { residueClasses = new int [residuesArray.length+1]; // be sure we have at least one thing to search residueClasses [0] = 4; modProd = 1; int i = 0; for (; i < residuesArray.length && modProd * 4 *residuesArray[i] <= searchInterval && i<residuesArray.length; i++) { int prime = residuesArray[i]; int modPerPrime = prime; modProd *= prime; while(modPerPrime * prime <= MAX_FACTOR) { modPerPrime *= prime; modProd *= prime; } residueClasses [i] = modPerPrime; lastLevel++; } return residueClasses; } public long findFactors(long n, Collection<Long> factors, int x, int level) { if (residueClasses[level] == 0) { // adjust sqrtN to be a multiple of modOld long xL = x; // if (modulus * mod > xRange/SEARCH_COUNT) { while (xL <= xEnd) { long right = xL * xL - n; if (SquaresMod.isSquare(right)) { long y = PrimeMath.sqrt(right); long factorHigh = xL + y; long factorLow = xL - y; factors.add(factorHigh); return factorLow; } xL+= modProd; } return n; } // TODO put the x with x^2 - n = 0 mod mod to the front long factor = findFactorsByMerge(n, factors, x, level); if (factor != n) return factor; return n; } public long findFactorsByMerge(long n, Collection<Long> factors, int x, int level) { for (int k = 0; xArray[level][k] >= 0; k++ ) { int i = mod((xArray[level][k] - x)*modOldInvert[level], residueClasses[level]); int xMerge = x + i * residueClasses[level-1]; long factor = findFactors(n, factors, xMerge, level+1); if (factor != n) return factor; } return n; } public long findFactors(long n, Collection<Long> factors) { if(n < 200) return super.findFactors(n, factors); init(n); for (int i=0; xArray[0][i] >= 0; i++) { long factor = findFactors(n, factors, xArray[0][i],1); if (factor != n) return factor; } return n; } }
// github.com/sweetpand import java.util.Scanner; // Time Complexity: O(n) // Space Complexity: O(1) by doing an "in place" rotation public class Solution { public static void main(String[] args) { /* Save input */ Scanner scan = new Scanner(System.in); int size = scan.nextInt(); int numRotations = scan.nextInt(); int array[] = new int[size]; for (int i = 0; i < size; i++) { array[i] = scan.nextInt(); } scan.close(); /* Rotate array (in place) using 3 reverse operations */ numRotations %= size; // to account for numRotations > size int rotationSpot = size - 1 - numRotations; reverse(array, 0, size - 1); reverse(array, 0, rotationSpot); reverse(array, rotationSpot + 1, size - 1); /* Print rotated array */ for (int i = 0; i < size; i++) { System.out.print(array[i] + " "); } } /* Reverses array from "start" to "end" inclusive */ private static void reverse(int[] array, int start, int end) { if (array == null || start < 0 || start >= array.length || end < 0 || end >= array.length) { return; } while (start < end) { swap(array, start++, end--); } } private static void swap(int [] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } }
package io.taaem.vertretungsplan; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import java.net.URL; import java.net.ProtocolException; import java.io.InputStream; import java.io.BufferedInputStream; import java.io.Reader; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import java.net.HttpURLConnection; import android.net.ConnectivityManager; import android.content.Context; import android.net.NetworkInfo; import org.json.JSONObject; public class ServiceHandler { static String response = null; public final static int GET = 1; public final static int POST = 2; Context mContext; NetworkInfo mNetworkInfo; public ServiceHandler() { /*//this.mContext = mContext; ConnectivityManager connMgr = (ConnectivityManager) this.mContext.getSystemService(Context.CONNECTIVITY_SERVICE); mNetworkInfo = connMgr.getActiveNetworkInfo(); */ } /** * Check Internet Connection */ public boolean checkInternet() { if (mNetworkInfo != null && mNetworkInfo.isConnected()) { return true; } else { return false; } } // Reads an InputStream and converts it to a String. public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer); } /** * Making service call * * @url - url to make request * @param - apiKey - ApiKey for Server */ public String makeServiceCall(String url, String apiKey) { int len = 1000; InputStream in = null; String response = ""; try { URL nUrl = new URL(url); // Http Client HttpURLConnection urlConnection = (HttpURLConnection) nUrl.openConnection(); urlConnection.setRequestProperty("x-apikey", apiKey); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream is = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ( (line = br.readLine()) != null) response += line; br.close(); is.close(); return response; } catch (IOException e){ e.printStackTrace(); } finally{ if (in != null) { try { in.close(); }catch(IOException e) { e.printStackTrace(); } } } return response; } }
package com.bofsoft.laio.customerservice.Database; import java.util.List; /** * 数据库查询结果回调 * * @param <T> * @author yedong */ public interface DBCallBackImp<T> { /** * 返回查询的T * * @param data */ void onCallBackData(T data); /** * 返回查询的List<T> * * @param list */ void onCallBackList(List<T> list); }
package com.qfc.yft.ui.custom.list; import java.util.ArrayList; import java.util.List; import com.qfc.yft.YftApplication; import android.content.Context; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; public abstract class ListAbsAdapter extends BaseAdapter { public abstract class ViewHolderImpl{ View holderView; public ViewHolderImpl(){ holderView = LayoutInflater.from(context).inflate(getLayoutId(), null); init(); holderView.setTag(this); } public abstract int getLayoutId(); public abstract void init(); public abstract void setup(int position); public View getHolderView(){ return holderView; } } public interface ListItemImpl{ public static final int ITEMTYPE_PRODUCT_SEARCH = 110; public static final int ITEMTYPE_COMPANY_SEARCH = 111; public static final int ITEMTYPE_PEOPLE_SEARCH = 112; public static final int ITEMTYPE_LOCALHISTORY = 113; public static final int ITEMTYPE_IMAGINE = 114; public static final int ITEMTYPE_PEOPLE_MY = 115; } SparseArray<View> viewMap; List<ListItemImpl> contentList; Context context; public ListAbsAdapter(){ this(new ArrayList<ListItemImpl>()); } public ListAbsAdapter(List<ListItemImpl> contentList){ this.contentList = contentList; viewMap = new SparseArray<View>(); this.context = YftApplication.app(); } @Override public int getCount() { return getList().size(); } @Override public long getItemId(int position) { return position; } @Override public ListItemImpl getItem(int position) { return getList().get(position);// } @Override public View getView(int position, View convertView, ViewGroup parent) { View view=viewMap.get(position); ViewHolderImpl holder; if(null==view){ holder= getHolderInstance(); view = holder.getHolderView(); viewMap.put(position, view); }else{ holder= (ViewHolderImpl)view.getTag(); } holder.setup(position); return view; } public List<ListItemImpl> getList(){ if(contentList==null) contentList=new ArrayList<ListAbsAdapter.ListItemImpl>(); return contentList; } public abstract ViewHolderImpl getHolderInstance(); }
package com.rkc.codeQualityAnalysis.payloads; import java.util.ArrayList; import java.util.List; public class CPDReport { private String requestId; private String totalWarnings; private String averageWarnings; private String totalFiles; List<CPDFileReport> cpdFileReports = new ArrayList<>(); public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getTotalWarnings() { return totalWarnings; } public void setTotalWarnings(String totalWarnings) { this.totalWarnings = totalWarnings; } public String getAverageWarnings() { return averageWarnings; } public void setAverageWarnings(String averageWarnings) { this.averageWarnings = averageWarnings; } public String getTotalFiles() { return totalFiles; } public void setTotalFiles(String totalFiles) { this.totalFiles = totalFiles; } public List<CPDFileReport> getCpdFileReports() { return cpdFileReports; } public void setCpdFileReports(List<CPDFileReport> cpdFileReports) { this.cpdFileReports = cpdFileReports; } }
package dao; import models.Department; import models.User; import org.junit.*; import org.sql2o.Connection; import org.sql2o.Sql2o; import java.util.Arrays; import static org.junit.Assert.*; public class Sql2oUserDaoTest { private static Connection conn; private static Sql2oUserDao userDao; private static Sql2oDepartmentDao departmentDao; @BeforeClass public static void setUp() throws Exception { String connectionString = "jdbc:postgresql://localhost:5432/organisational_api_test"; Sql2o sql2o = new Sql2o(connectionString, "laurent", "laurent"); userDao = new Sql2oUserDao(sql2o); departmentDao=new Sql2oDepartmentDao(sql2o); conn = sql2o.open(); } @After public void tearDown() throws Exception { System.out.println("clearing database"); userDao.clearAll(); //clear all restaurants after every test } @AfterClass public static void shutDown() throws Exception{ conn.close(); System.out.println("connection closed"); } //Helpers public User setupNewUser(){ User user = new User("c4","CEO","Overseeing Deals",1); userDao.add(user); return user; } public Department setupNewDepartment(){ Department department = new Department("finance","money",0); departmentDao.add(department); return department; } @Test public void add_CorrectlyAddsUser() { User user = setupNewUser(); assertEquals(1,userDao.getAll().size()); } @Test public void findById_correctlyReturnsUser() { User user=setupNewUser(); User otherUser=new User("savage","NA","Overseeing",1); userDao.add(otherUser); assertEquals(otherUser,userDao.findById(otherUser.getId())); } @Test public void getAllUsersByDepartment_reurnsCorrectly() { Department department=setupNewDepartment(); User user=setupNewUser(); User otherUser=new User("savage","NA","Overseeing",department.getId()); userDao.add(otherUser); User otherNewUser=new User("savage","NA","Overseeing",department.getId()); userDao.add(otherNewUser); User[] departmentUsers={otherUser,otherNewUser}; assertEquals(Arrays.asList(departmentUsers),userDao.getAllUsersByDepartment(department.getId())); } }
package cn.edu.njnu.main_part; import cn.edu.njnu.nnu_creative_cloud.R; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; public class LoginFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.main_login, container, false); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ImageButton login = (ImageButton) getActivity().findViewById( R.id.login_button);// 获取登陆按钮 login.setOnClickListener(new OnClickListener() { // 为登陆按钮设置点击事件 @Override public void onClick(View v) { EditText account = (EditText) getActivity().findViewById( R.id.login_number_edit); EditText password = (EditText) getActivity().findViewById( R.id.login_password_edit); if (account.getText().toString().equals("") || password.getText().toString().equals("")) { Toast.makeText(getActivity().getApplicationContext(), "未正确填写账户或密码", Toast.LENGTH_SHORT) .show(); } else { // 登陆,与服务器交互 } } }); ImageButton register = (ImageButton) getActivity().findViewById( R.id.register_button);// 获取注册按钮 register.setOnClickListener(new OnClickListener() {// 为注册按钮设置点击事件 @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), RegisterActivity.class); startActivity(intent); } }); } }
package com.example.ive.ggbw2.Room; import android.app.Activity; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.example.ive.ggbw2.Dialog.CreateRoom; import com.example.ive.ggbw2.R; import com.example.ive.ggbw2.Util.Constant; import com.example.ive.ggbw2.Util.GlobalApplication; public class ReceptionActivity extends Activity { private GlobalApplication applicationClass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reception); applicationClass = (GlobalApplication) getApplicationContext(); } }
package edu.rit.se.reichmafia.htmleditor.models; /** * Interface for elements in an HTML file. * * @author Team ReichMafia */ public interface Element { /** * Get the name of this Element. * * @return Name of this Element. */ public String getName(); }
package negocio.repositorio; import hibernate.util.HibernateUtil; import java.util.List; import negocio.basica.Monitor; public class RepositorioMonitor { public void incluir(Monitor pMonitor){ HibernateUtil.getSession().save(pMonitor); } public void alterar(Monitor pMonitor){ HibernateUtil.getSession().update(pMonitor); } public void remover(Monitor pMonitor){ HibernateUtil.getSession().delete(pMonitor); } public Monitor consultarPorChavePrimaria(Monitor pMonitor){ pMonitor = (Monitor) HibernateUtil.getSession().get(Monitor.class, pMonitor.getId()); return pMonitor; } public List<Monitor> listar(){ List<Monitor> retorno; retorno = HibernateUtil.getSession().createCriteria(Monitor.class).list(); return retorno; } }
package practice; import java.util.Scanner; public class TwoProduct { public static void main(String[] args) { // WAP to find product of two numbers without using "*" Scanner s = new Scanner(System.in); System.out.println("Enter two numbers:"); int num1 = s.nextInt(); int num2 = s.nextInt(); int product = 0; for (int i = 1; i <= num2; i++) { product += num1; } System.out.println("Prdoduct is = " + product); s.close(); } }
package ru.job4j.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; /** * Класс PropertyLoader реализует функционал загрузки файлов свойств. * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2019-05-28 * @since 2017-12-23 */ public final class PropertyLoader { /** * Путь до файла. */ private String path; /** * Свойства. */ private final Properties props = new Properties(); /** * Конструктор без параметров. */ public PropertyLoader() { } /** * Конструктор. * @param name имя properties-файла. * @throws IOException исключение ввода-вывода. */ public PropertyLoader(String name) throws IOException { this(); this.load(name); } /** * Конструктор. * @param url имя properties-файла. * @throws IOException исключение ввода-вывода. */ public PropertyLoader(URL url) throws IOException { this(); this.load(new File(url.getFile()).toString()); } /** * Получает свойства. * @return объект со свойствами. */ public Properties getProperties() { return this.props; } /** * Получает свойство по имени. * @param propName имя свойства. * @return значение свойства. */ public String getPropValue(String propName) { return this.props.getProperty(propName); } /** * Загружает свойства из файла. * @param name имя properties-файла. * @throws IOException исключение ввода-вывода. */ public void load(String name) throws IOException { Path path = Paths.get(name); InputStream is = Files.newInputStream(path); this.props.load(is); } }
package com.example.fiszking; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.provider.UserDictionary; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.HashMap; import java.util.LinkedList; public class WordsAdapter extends RecyclerView.Adapter<WordsAdapter.WordViewHolder>{ private final LinkedList<HashMap<String, String>> words; private Activity activity; private Context context; public WordsAdapter(Activity activity, Context context, LinkedList<HashMap<String, String>> words) { this.activity = activity; this.words = words; this.context = context; } @NonNull @Override public WordViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); View mItemView = inflater.inflate(R.layout.wordlist_item, parent, false); return new WordViewHolder(mItemView, this); } @Override public void onBindViewHolder(@NonNull WordViewHolder holder, int position) { String mCurrent = words.get(position).get("word"); if (mCurrent.length() > 18) { mCurrent = mCurrent.substring(0, 15) + "..."; } holder.wordItemView.setText(mCurrent); } @Override public int getItemCount() { return words.size(); } public class WordViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public final TextView wordItemView; final WordsAdapter mAdapter; private final Context context; public WordViewHolder(View itemView, WordsAdapter adapter) { super(itemView); context = itemView.getContext(); wordItemView = itemView.findViewById(R.id.word_item); this.mAdapter = adapter; itemView.setOnClickListener(this); } @Override public void onClick(View view) { int mPosition = getLayoutPosition(); HashMap<String, String> element = words.get(mPosition); Intent intent = new Intent(context, EditWord.class); intent.putExtra("EXTRA_ID", element.get("Id")); intent.putExtra("EXTRA_WORD", element.get("word")); intent.putExtra("EXTRA_MEANING", element.get("meaning")); activity.startActivityForResult(intent,1); } } public void removeItem(int position) { DatabaseHelper myDB = new DatabaseHelper(WordsAdapter.this.context); String elem_id = words.get(position).get("Id"); Log.i("removeItem", words.toString()); words.remove(position); myDB.deleteOneRow(elem_id); notifyItemRemoved(position); notifyItemRangeChanged(position, getItemCount()); } public void restoreItem(HashMap<String, String> item, int position) { DatabaseHelper myDB = new DatabaseHelper(WordsAdapter.this.context); int itemPosition = myDB.addWord(item.get("word"), item.get("meaning")); HashMap<String, String> restored = new HashMap<String, String>(); restored.put("Id", itemPosition+""); restored.put("word", item.get("word")); restored.put("meaning", item.get("meaning")); Log.i("restoreItem", words.toString()); words.add(position, restored); Log.i("restoreItem", words.toString()); notifyItemInserted(position); notifyItemRangeChanged(position, getItemCount()); } public LinkedList<HashMap<String, String>> getData() { return words; } }
package io.github.yanhu32.xpathkit.converter; import io.github.yanhu32.xpathkit.utils.Strings; import java.time.LocalDate; import java.time.format.DateTimeFormatter; /** * @author yh * @since 2021/4/22 */ public class LocalDateTextConverter extends AbstractDateTimeTextConverter<LocalDate> { public LocalDateTextConverter() { super(null); } public LocalDateTextConverter(String format) { super(format); } @Override public LocalDate apply(String text) { if (Strings.isEmpty(text)) { return null; } String format = Strings.defaultIfEmpty(getFormat(), DEFAULT_DATE_FORMAT); return LocalDate.parse(text, DateTimeFormatter.ofPattern(format)); } }
/* * Copyright (c) 2004 Steve Northover and Mike Wilson * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ package part1.ch9; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; import org.eclipse.swt.layout.*; public class Table8a { static final int COLUMNS = 3, ROWS = 100000, PAGE = 100; static final String [] [] DATA = new String [ROWS] [COLUMNS]; static { for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLUMNS; j++) { DATA [i][j] = "Item " + i + "-" + j; } } } public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); RowLayout layout = new RowLayout(SWT.VERTICAL); layout.fill = true; shell.setLayout(layout); final Table table = new Table(shell, SWT.BORDER); table.setLayoutData(new RowData(400, 400)); table.setHeaderVisible(true); for (int i = 0; i < COLUMNS; i++) { TableColumn column=new TableColumn(table,SWT.NONE); column.setText("Column " + i); column.setWidth(128); } final ProgressBar progress = new ProgressBar(shell, SWT.NONE); progress.setMaximum(ROWS - 1); shell.pack(); shell.open(); fillTable(table, progress, PAGE); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } static void fillTable( final Table table, final ProgressBar progress, final int page) { final Display display = table.getDisplay(); Runnable runnable = new Runnable() { int index = 0; long time = 0; public void run() { if (table.isDisposed()) return; if (index == 0) time = -System.currentTimeMillis(); int end = Math.min(index + page, ROWS); while (index < end) { TableItem item = new TableItem(table, SWT.NULL); for (int j = 0; j < COLUMNS; j++) { item.setText(j, DATA[index][j]); } index++; } if (end == ROWS) { time += System.currentTimeMillis(); System.out.println(ROWS + " items: " + time + "(ms)"); } if (end == ROWS) end = 0; progress.setSelection(end); if (index < ROWS) display.asyncExec(this); } }; display.asyncExec(runnable); } }
import java.io.FileInputStream; import java.util.Properties; public class AsignarPropiedadesDelSistema { public static void main(String[] args){ try { FileInputStream archivo = new FileInputStream("src/config.properties"); Properties p = new Properties(System.getProperties()); p.load(archivo); p.setProperty("config.animal.nombre", "Napoleon"); System.setProperties(p); // System.getProperties().list(System.out); p.list(System.out); System.out.println(p.getProperty("config.animal.nombre")); } catch (Exception e){ System.out.println("no existe el archivo = " + e); } } }
package cualtos.examples; public class Operand { }
package com.adam.base.weatherview.util; import android.content.Context; /** * Created by adamDeng on 2019/11/8 * Copyright © 2019年 . All rights reserved. */ public class DisplayUtils { public static int dp2px(Context context, float dpValue) { float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }
package com.fotoable.fotoime.fonts.callback; /** * Created by chenxiaojian on 2016/12/6. */ public interface DownloadCallback { public void notNetwork(); public void downloadSuccess(); public void downloadFail(); }
package guillaumeagis.perk4you.api; import android.app.Activity; import guillaumeagis.perk4you.managers.ProfileManager; /** * Created by Appytemplate * http://www.appytemplate.com/ * Copyright © 2016 AppyTemplate * * Execute calls to the API from within thread to not block the main thread / UI */ public final class ApiExecutor { /** * Broadcast an event to activities / fragments * @param event enum, event to send */ public static void broadcastEVent(final EventManager event) { ProfileManager.getInstance().getBus().post(event); } /** * Load list of conversations and send event to the fragments to refresh the list * the task is done from within a thread, to avoid blocking the main Thread/ UI * Use events to avoid race conditions * @param apiManager api manager * @param activity current activity */ public static void loadData(final IAPIManager apiManager, final Activity activity) { Thread thread = new Thread(new Runnable() { public void run() { apiManager.loadData(activity); broadcastEVent(EventManager.READY); }}); thread.start(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.burgosanchez.tcc.venta.ejb; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author TID01 */ @Entity @Table(name = "USUARIO", catalog = "", schema = "TCC") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Usuario.findAll", query = "SELECT u FROM Usuario u")}) public class Usuario implements Serializable { @Size(max = 50) @Column(name = "NOM_USER") private String nomUser; private static final long serialVersionUID = 1L; @EmbeddedId protected UsuarioPK usuarioPK; @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "PASSWORD") private String password; @Size(max = 5) @Column(name = "TIPO_USUARIO") private String tipoUsuario; @JoinColumn(name = "COD_PERSONA", referencedColumnName = "COD_PERSONA", insertable = false, updatable = false) @ManyToOne(optional = false) private Persona persona; public Usuario() { } public Usuario(UsuarioPK usuarioPK) { this.usuarioPK = usuarioPK; } public Usuario(UsuarioPK usuarioPK, String password) { this.usuarioPK = usuarioPK; this.password = password; } public Usuario(String codUsuario, String codPersona) { this.usuarioPK = new UsuarioPK(codUsuario, codPersona); } public UsuarioPK getUsuarioPK() { return usuarioPK; } public void setUsuarioPK(UsuarioPK usuarioPK) { this.usuarioPK = usuarioPK; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTipoUsuario() { return tipoUsuario; } public void setTipoUsuario(String tipoUsuario) { this.tipoUsuario = tipoUsuario; } public Persona getPersona() { return persona; } public void setPersona(Persona persona) { this.persona = persona; } @Override public int hashCode() { int hash = 0; hash += (usuarioPK != null ? usuarioPK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Usuario)) { return false; } Usuario other = (Usuario) object; if ((this.usuarioPK == null && other.usuarioPK != null) || (this.usuarioPK != null && !this.usuarioPK.equals(other.usuarioPK))) { return false; } return true; } @Override public String toString() { return "com.burgosanchez.tcc.venta.ejb.Usuario[ usuarioPK=" + usuarioPK + " ]"; } public String getNomUser() { return nomUser; } public void setNomUser(String nomUser) { this.nomUser = nomUser; } }
package enchanted; import interfaces.AbstractRoom; public class EnchantedRoom implements AbstractRoom { public EnchantedRoom() { } @Override public void create() { System.out.println("Você criou uma porta mágica!"); } }
package adapter; import adapter.duckturkeyadapter.Duck; import adapter.duckturkeyadapter.Turkey; import adapter.duckturkeyadapter.TurkeyAdapter; import adapter.duckturkeyadapter.WildTurkey; import java.util.Arrays; import java.util.List; /** * Преобразует интерфейс класса к другому интерфейсу, на который рассчитан клиент. Адаптер обеспечивает совместную * работу классов, невозможную в обычных условиях из-за несовместимости интерфейсов. Адаптер получает конвертируемый * объект в конструкторе или через параметры своих методов. * * Реализация: * 1.Описываем общий интерфейс. * 2.Создаем класс адаптера, реализовав этот интерфейс. * 3.В адаптере необходимо поле, которое будет хранить ссылку на объект класса, использующего другой интерфейс. * Обычно это поле заполняют объектом, переданным в конструктор адаптера. * 4.Реализуем все методы клиентского интерфейса в адаптере. Адаптер должен делегировать основную работу внутреннему * объекту. * * @author Vladimir Ryazanov (v.ryazanov13@gmail.com) */ public class Example { public static void main(String[] args) { Turkey turkey = new WildTurkey(); //Приводим интерфейс индейки к интерфейсу утки через адаптер, таким образом мы сможем обращатсья к объекту //индейки как к утке. Duck duckTurkey = new TurkeyAdapter(turkey); duckTurkey.fly(); duckTurkey.quack(); //Unsupported operation, т.к. плавать индейку через адаптер мы не научим. //duckTurkey.swim(); String[] stringArray = new String[]{"1", "2", "3"}; //Пример из стандартной библиотеки java List<String> strings = Arrays.asList(stringArray); //Unsupported operation //strings.add("4"); for (String string : strings) { System.out.println(string); } } }
package com.XJK.service.impl; import com.XJK.dao.UserDao; import com.XJK.dao.impl.UserDaoImpl; import com.XJK.pojo.User; import com.XJK.service.UserService; /** * 实现UserService功能 */ public class UserServiceImpl implements UserService { private UserDao userDao = new UserDaoImpl(); @Override public void registerUser(User user) { userDao.saveUser(user); } @Override public User login(User user) { return userDao.queryUserByUsernameAndPassword(user.getUsername(),user.getPassword()); } @Override public boolean existUsername(String username) { if (userDao.queryUserByUsername(username) != null){ return true; } return false; } }
package project; /************************************************************************************************** * Created by: Robert Darrow * Date: 9/24/18 * Description: subclass of product that implements multimediaControl interface to create * an object representing an audio player. **************************************************************************************************/ public class AudioPlayer extends Product implements MultimediaControl { //FindBugs wants Serializable to be implemented. Ignored. String audioSpecification; ItemType mediaType = ItemType.AUDIO; /** * Constructor of project.AudioPlayer class. * * @param name name of the audio player product * @param audioSpecification specification of player audio */ public AudioPlayer(String name, String audioSpecification) { super(name); // call the constructor of project.Product to set name this.audioSpecification = audioSpecification; } /** * Displays messaging indicating device is playing. */ public void play() { System.out.println("Playing"); } /** * Displaying message indicating device is stopping. */ public void stop() { System.out.println("Stopping"); } /** * Displays message indicating moving to the previous song. */ public void previous() { System.out.println("Previous"); } /** * Displays message indicating moving to the next song. */ public void next() { System.out.println("Next"); } /** * Returns formatted string displaying details of audio player. * * @return String details of audio player */ public String toString() { return (super.toString() + "\nAudio Spec : " + audioSpecification + "\nMedia Type : " + mediaType); } }
package com.company.javasample; import java.util.HashMap; import java.util.Set; public class TransparencyCheckerImpl implements TransparencyChecker { private HashMap<String, Integer> reachabilityMap = new HashMap<String, Integer>(); public boolean isTransparent(Set<Exchange> exchanges) { // populate reachability map for (Exchange exchange : exchanges) { String name = exchange.getName(); for (String outgoingName : exchange.getOutgoingConnections()) { String connection = getConnectionName(name, outgoingName); Integer counter = reachabilityMap.get(connection); if ( counter == null ) { counter = 0; } reachabilityMap.put(connection, counter + 1); } } for (String connection : reachabilityMap.keySet()) { if (reachabilityMap.get(connection) < 2) { System.out.println("Connection is not dual: " + connection); return false; } } return true; } private String getConnectionName(String name1, String name2) { if (name1.compareToIgnoreCase(name2) < 0) { return name1 + ":" + name2; } return name2 + ":" + name1; } }
/* * Zzt_JIF_Buliding.java * * Created on __DATE__, __TIME__ */ package zzt.view; import java.lang.reflect.Array; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Vector; import javax.swing.DefaultBoundedRangeModel; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import com.mysql.jdbc.Connection; import zzt.dao.Zzt_Classroom_access; import zzt.model.Zzt_Teacher_login; import global.dao.Databaseconnection; import global.dao.Teacheraccess; import global.dao.Teachingplanaccess; import global.model.Department; import global.model.Major; import global.model.Office; import global.model.Teachingplan; /** * * @author __USER__ */ public class Zzt_JIF_Classroom extends javax.swing.JInternalFrame { private static final Object Classroomlist = null; private String d_id; /** Creates new form Zzt_JIF_Buliding */ public Zzt_JIF_Classroom() { initComponents(); } public void Classroomtable() { Databaseconnection mysql = new Databaseconnection(); try { java.sql.Connection con = Databaseconnection.getconnection(); DefaultTableModel dtm = (DefaultTableModel) jTable2.getModel(); ResultSet rs; rs = (ResultSet) Zzt_Classroom_access.getClassroom(d_id); dtm.setRowCount(0); while (rs.next()) { int cr_id = rs.getInt("cr_id"); String cr_name = rs.getString("cr_name"); d_id = rs.getString("d_id"); int ct_id = rs.getInt("ct_id"); int cr_seating = rs.getInt("cr_seating"); int b_id = rs.getInt("b_id"); Vector v = new Vector(); v.add(cr_id); v.add(cr_name); v.add(d_id); v.add(ct_id); v.add(cr_seating); v.add(b_id); // v.add(classroomlist[0]); // v.add(classroomlist[1]); // v.add(classroomlist[2]); // v.add(classroomlist[3]); // v.add(classroomlist[4]); // v.add(classroomlist[5]); dtm.addRow(v); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ //GEN-BEGIN:initComponents // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jComboBox4 = new javax.swing.JComboBox(); jLabel5 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jComboBox3 = new javax.swing.JComboBox(); jLabel1 = new javax.swing.JLabel(); jComboBox2 = new javax.swing.JComboBox(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); setTitle("\u6559\u5ba4\u4fe1\u606f\u7ba1\u7406"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.MatteBorder(null), "\u6559\u5ba4\u4fe1\u606f")); jLabel2.setText("\u6240\u5c5e\u6821\u533a\uff1a"); jLabel3.setText("\u6559\u5ba4\u540d\u79f0\uff1a"); jLabel4.setText("\u6559\u5ba4\u4eba\u6570\uff1a"); jLabel5.setText("\u6559\u5ba4\u7c7b\u578b\uff1a"); jLabel6.setText("\u6559\u5b66\u697c\u540d\uff1a"); jLabel1.setText("\u90e8\u95e8\u540d\u79f0\uff1a"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(34, 34, 34) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel6) .addComponent(jLabel5)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox4, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGap(78, 78, 78) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField1) .addComponent(jComboBox1, 0, 166, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE))) .addGap(25, 25, 25)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(38, 38, 38) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(39, 39, 39) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel4) .addComponent(jLabel3) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(37, 37, 37)) ); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "教学楼名称", "部门名称", "所属校区", "教室类型", "教室人数", "教室名称" } )); jScrollPane2.setViewportView(jTable2); jButton2.setText("\u53d6\u6d88"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("\u5220\u9664"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("\u4fee\u6539"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton1.setText("\u6dfb\u52a0"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(523, Short.MAX_VALUE)) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 901, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(35, 35, 35) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(38, Short.MAX_VALUE)) ); pack(); }// </editor-fold> //GEN-END:initComponents private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) { } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } //GEN-BEGIN:variables // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JComboBox jComboBox1; private javax.swing.JComboBox jComboBox2; private javax.swing.JComboBox jComboBox3; private javax.swing.JComboBox jComboBox4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JTable jTable2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.db.generic; import org.apache.ibatis.session.SqlSession; import pl.edu.icm.unity.exceptions.EngineException; /** * Implementation is notified about the pre- add/update/remove operations on a * generic object. The type of the dependency generic object is returned by the listener. * <p> * The implementation may either perform maintenance of its object or block the whole operation by * throwing an exception. * * * @author K. Benedyczak */ public interface DependencyChangeListener<T> { public String getDependencyObjectType(); public void preAdd(T newObject, SqlSession sql) throws EngineException; public void preUpdate(T oldObject, T updatedObject, SqlSession sql) throws EngineException; public void preRemove(T removedObject, SqlSession sql) throws EngineException; }
package com.fb.controller.sys; // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖保佑 永无BUG // 佛曰: // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见满街漂亮妹,哪个归得程序员? import com.fb.controller.BaseController; import com.fb.core.Const; import com.fb.kit.CommonUtils; import com.fb.kit.DateUtils; import com.fb.kit.ToolsUtils; import com.fb.model.TDictionary; import com.jfinal.ext.route.ControllerBind; import com.jfinal.log.Logger; import org.apache.commons.lang.StringUtils; /** * 数据字典 * @author sun * */ @ControllerBind(controllerKey = "/sys/dictionary") public class DictionaryController extends BaseController { protected static final Logger LOG = Logger.getLogger(DictionaryController.class); private static final String PATH = "/sys/dictionary"; /** * 分页查询所有的数据字典 */ public void search() { String keyword = ToolsUtils.trim(getPara("keyword")); String chatCode = getPara("chatCode"); setAttr("page", TDictionary.me.findPage(pageSort("chat_code,sort", "asc,asc"), keyword, chatCode)); searchConfig(); keepPara("chatCode"); keepPara("keyword"); } /** * 查询所有的字典类型, 字典config */ public void searchConfig() { //查询所有的字典类型, 字典config setAttr("config", TDictionary.me.findTypeAll()); } /** * 添加 */ public void add() { if (isGet()) { setAttr("model", new TDictionary()); searchConfig(); render("_form.html"); } if (isPost()) { try { TDictionary _model = getModel(TDictionary.class, "model"); String selectType = getPara("selectChatCode"); if(!StringUtils.isEmpty(selectType)){ if("0".equals(selectType)){ _model.set("chat_code", getPara("inputChatCode")); }else{ _model.set("chat_code", selectType); } _model.set("type", 0);//0 是默认 _model.set("platform", CommonUtils.DICTIONARY_PLATFORM_SYSTEM); _model.set("add_time", DateUtils.getDate()); _model.save(); setMsg(Const.MsgType.SUCCESS, "10101", true); }else{ setMsg(Const.MsgType.SUCCESS, "20101,30501", true); } } catch (Exception e) { setMsg(Const.MsgType.ERROR, "20101,90901", true); } redirect(PATH, "search"); } } /** * 编辑 */ public void edit() { if (isGet()) { setAttr("model", TDictionary.me.findById(getParaToLong("id"))); searchConfig(); render("_form.html"); } if (isPost()) { TDictionary _model = getModel(TDictionary.class, "model"); try { TDictionary model = TDictionary.me.findById(_model.getLong("id")); // model.set("chat_code", _model.get("chat_code"));//此项不允许更改 model.set("label", _model.get("label")); model.set("val", _model.get("val")); model.set("sort", _model.get("sort")); model.set("color", _model.get("color")); model.set("description", _model.get("description")); model.set("stu", _model.get("stu")); model.set("update_time", DateUtils.getDate()); model.update(); setMsg(Const.MsgType.SUCCESS, "10103", true); } catch (Exception e) { setMsg(Const.MsgType.ERROR, "20103,90901", true); } redirect(PATH, "search"); } } //不开发删除功能 public void remove() { try { TDictionary dict = TDictionary.me.findById(getParaToLong("id")); if(dict!=null){ dict.set("stu", -1).set("update_time", DateUtils.getDate()).update(); setMsg(Const.MsgType.SUCCESS, "10102", true); } } catch (Exception e) { setMsg(Const.MsgType.ERROR, "20102,90901", true); } redirect(PATH, "search"); } }
package nesto.walker.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import nesto.walker.R; import nesto.walker.bean.DistanceHistory; /** * Created on 2015/8/6 16:28 */ public class HistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private ArrayList<DistanceHistory> histories; private LayoutInflater inflater; public HistoryAdapter(Context context, ArrayList<DistanceHistory> histories) { inflater = LayoutInflater.from(context); this.histories = new ArrayList<>(); refresh(histories); } public void refresh(ArrayList<DistanceHistory> histories) { this.histories.addAll(histories); notifyDataSetChanged(); } public class ItemViewHolder extends RecyclerView.ViewHolder { public TextView data; public TextView distance; public ItemViewHolder(View convertView) { super(convertView); data = (TextView) convertView.findViewById(R.id.data); distance = (TextView) convertView.findViewById(R.id.distance); } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View convertView = inflater.inflate(R.layout.list_item, parent, false); return new ItemViewHolder(convertView); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ItemViewHolder itemViewHolder = (ItemViewHolder) holder; itemViewHolder.data.setText(histories.get(position).getData()); itemViewHolder.distance.setText(histories.get(position).getDistance()); } @Override public int getItemCount() { return histories.size(); } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.db.generic.reg; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pl.edu.icm.unity.db.generic.DefaultEntityHandler; import pl.edu.icm.unity.db.model.GenericObjectBean; import pl.edu.icm.unity.exceptions.InternalException; import pl.edu.icm.unity.types.registration.EnquiryForm; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; /** * Handler for {@link EnquiryForm} * @author K. Benedyczak */ @Component public class EnquiryFormHandler extends DefaultEntityHandler<EnquiryForm> { public static final String ENQUIRY_FORM_OBJECT_TYPE = "enquiryForm"; @Autowired public EnquiryFormHandler(ObjectMapper jsonMapper) { super(jsonMapper, ENQUIRY_FORM_OBJECT_TYPE, EnquiryForm.class); } @Override public GenericObjectBean toBlob(EnquiryForm value, SqlSession sql) { try { ObjectNode root = value.toJson(); byte[] contents = jsonMapper.writeValueAsBytes(root); return new GenericObjectBean(value.getName(), contents, supportedType); } catch (JsonProcessingException e) { throw new InternalException("Can't serialize enquiry form to JSON", e); } } @Override public EnquiryForm fromBlob(GenericObjectBean blob, SqlSession sql) { try { ObjectNode root = (ObjectNode) jsonMapper.readTree(blob.getContents()); return new EnquiryForm(root); } catch (Exception e) { throw new InternalException("Can't deserialize enquiry form from JSON", e); } } }
package com.tiger.util; public class hash { private String data; private String method; public hash(String _data){ this.data = _data; this.method = "DJB"; } public long generate(String _data){ switch(this.method){ case "DJB": return this.DJB(_data); } return 0; } public long DJB(String _data){ return 0; } }
package com.sunny.netty.chat.server.handler; import com.sunny.netty.chat.protocol.request.HeartBeatRequestPacket; import com.sunny.netty.chat.protocol.response.HeartBeatResponsePacket; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; @ChannelHandler.Sharable public class HeartBeatRequestHandler extends SimpleChannelInboundHandler<HeartBeatRequestPacket> { public static final HeartBeatRequestHandler INSTANCE = new HeartBeatRequestHandler(); private HeartBeatRequestHandler() { } @Override protected void channelRead0(ChannelHandlerContext ctx, HeartBeatRequestPacket requestPacket) { System.out.println("netty server heart beat!"); ctx.writeAndFlush(new HeartBeatResponsePacket()); } }
package eu.bittrade.steem.steemstats.datacollector.dao; import java.util.List; import javax.persistence.NoResultException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hibernate.Session; import org.hibernate.Transaction; import eu.bittrade.steem.steemstats.datacollector.BlockchainSynchronization; import eu.bittrade.steem.steemstats.datacollector.entities.Record; /** * @author <a href="http://steemit.com/@dez1337">dez1337</a> */ public class RecordDaoImpl implements RecordDao<Record, Long> { private static final Logger LOGGER = LogManager.getLogger(TransactionsDaoImpl.class); private Session session; @Override public void delete(Record entity) { session = BlockchainSynchronization.sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.remove(entity); transaction.commit(); session.close(); } @Override public void deleteAll() { session = BlockchainSynchronization.sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); for (Record record : findAll()) { session.remove(record); } transaction.commit(); session.close(); } @Override public List<Record> findAll() { session = BlockchainSynchronization.sessionFactory.openSession(); List<Record> result = session.createQuery("SELECT r FROM Record r", Record.class).getResultList(); session.close(); return result; } @Override public Record findNewest() { session = BlockchainSynchronization.sessionFactory.openSession(); Record result = session.createQuery("SELECT r FROM Record r ORDER BY id DESC", Record.class).setMaxResults(1) .uniqueResult(); session.close(); return result; } @Override public Record findOldest() { session = BlockchainSynchronization.sessionFactory.openSession(); Record result = session.createQuery("SELECT r FROM Record r ORDER BY id ASC", Record.class).setMaxResults(1) .getSingleResult(); session.close(); return result; } @Override public Record findById(Long id) { session = BlockchainSynchronization.sessionFactory.openSession(); Record result = null; try { result = session.createQuery("SELECT r FROM Record r WHERE id=:id", Record.class).setParameter("id", id) .getSingleResult(); } catch (NoResultException e) { LOGGER.trace("No result found.", e); } session.close(); return result; } @Override public void persist(Record entity) { session = BlockchainSynchronization.sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.persist(entity); transaction.commit(); session.close(); } }
package com.gtambit.gt.app.mission; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; import com.ambit.city_guide.R; import com.google.zxing.client.android.CaptureActivity; import com.gtambit.gt.app.api.GtApi; import com.gtambit.gt.app.api.GtLayoutApi; import com.gtambit.gt.app.component.URActionBarActivity; import com.gtambit.gt.app.member.MemberWebActivity; import com.gtambit.gt.app.mission.api.TaskApi; import com.gtambit.gt.app.mission.api.TaskRequestApi; import com.gtambit.gt.app.mission.api.TaskSharedPreferences; import com.gtambit.gt.app.mission.obj.RedeemTaskResultType; import com.gtambit.gt.app.mission.obj.TaskDetailType; import org.json.JSONException; import org.json.JSONObject; import lib.hyxen.ui.SimpleDialog; import ur.ga.URGAManager; public class TaskTask_10006_EnterInviteCode extends URActionBarActivity implements OnClickListener { private ProgressDialog mProgressDialog; private Handler mHandler = new Handler(); private EditText mEditText_InviteCode; private TaskDetailType mDetail; private RedeemTaskResultType mRedeemType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.t_enter_invite); String api_token = TaskSharedPreferences.getApiToken(TaskTask_10006_EnterInviteCode.this); if (api_token.equals("")) { SimpleDialog.showAlert(getSupportFragmentManager(), "尚未登入會員", "您需要登入會員才能進行賺點數活動喔!", "登入/註冊", "知道了", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(TaskTask_10006_EnterInviteCode.this, MemberWebActivity.class)); TaskTask_10006_EnterInviteCode.this.finish(); } }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { TaskTask_10006_EnterInviteCode.this.finish(); } }); return; } initailLayout(); setTaskDetail(); setTitleName(getString(R.string.mission_content)); URGAManager.sendScreenName(TaskTask_10006_EnterInviteCode.this,"輸入會員推荐碼"); } private void initailLayout() { mEditText_InviteCode = (EditText)findViewById(R.id.EditText_InviteCode); // mEditText_InviteCode.setFocusable(false); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mEditText_InviteCode.getWindowToken(), 0); mEditText_InviteCode.clearFocus(); resignKeyboard(TaskTask_10006_EnterInviteCode.this); // findViewById(R.id.ImageButtonBack).setOnClickListener(this); findViewById(R.id.Button_Ignore).setOnClickListener(this); findViewById(R.id.Button_Send).setOnClickListener(this); // findViewById(R.id.Button_QrCode).setVisibility(View.GONE); findViewById(R.id.Button_QrCode).setOnClickListener(this); findViewById(R.id.ImgaeViewInput).setLayoutParams(GtLayoutApi.setLinearLayoutParamsScale(TaskTask_10006_EnterInviteCode.this, 640, 350, 640)); } private void setTaskDetail() { new Thread(new Runnable() { @Override public void run() { mDetail = TaskRequestApi.getTaskDetail(TaskTask_10006_EnterInviteCode.this, "10006"); runOnUiThread(new Runnable() { @Override public void run() { if(mDetail == null) return; TextView mTextView_TaskName = (TextView) findViewById(R.id.TextView_TaskName); TextView mTextView_TaskPoint = (TextView) findViewById(R.id.TextView_TaskPoint); TextView mTextView_Deadline = (TextView) findViewById(R.id.TextView_Deadline); TextView mTextView_LimitMember = (TextView) findViewById(R.id.TextView_LimitMember); mTextView_TaskName.setText(mDetail.taskName); URGAManager.sendScreenName(getApplicationContext(), getString(R.string.ga_task) + "_" + mDetail.taskName); mTextView_TaskPoint.setText(mDetail.point); mTextView_Deadline.setText(TaskApi.getDateFromTs(mDetail.endTs*1000)); mTextView_LimitMember.setText(getString(R.string.mission_limit_without)); } }); } }).start(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.Button_Ignore: GtApi.alertYesNoMessage(this, "", "略過此步驟後將無法再次輸入邀請碼,是否確認略過?", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { goToNextActivity(); } }, null); break; case R.id.Button_Send: String code = mEditText_InviteCode.getText().toString(); if (code.equals("")) { GtApi.alertOKMessage(this, "", "請輸入邀請碼。", null); } else { sendInviteCode(code); } break; case R.id.Button_QrCode: URGAManager.setGaEvent(TaskTask_10006_EnterInviteCode.this,"輸入推荐碼","掃描","輸入推荐碼-掃描"); try { startActivityForResult(new Intent(this, CaptureActivity.class), 88); } catch (Exception e) { return; } break; } } public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); //barcode number if (requestCode == 88) { mEditText_InviteCode.setText(contents); } else { finish(); } } } private void sendInviteCode(final String code) { mProgressDialog = ProgressDialog.show(this, "請稍候", "驗證中,請稍候..."); Thread t = new Thread(){ @Override public void run() { String optJson = ""; try { JSONObject json = new JSONObject(); json.put("type", 10006); json.put("other_icode", code); optJson = json.toString(); } catch (JSONException e) { e.printStackTrace(); } String verifyCode = TaskRequestApi.varifyCode(TaskTask_10006_EnterInviteCode.this, "10006", TaskApi.getTaskKey()); mRedeemType = TaskRequestApi.redeemTask(TaskTask_10006_EnterInviteCode.this, "10006", optJson, verifyCode); final int errorCode = mRedeemType.errorCode; mHandler.post(new Runnable() { @Override public void run() { mProgressDialog.dismiss(); if (errorCode == 0) { GtApi.alertOKMessage(TaskTask_10006_EnterInviteCode.this, "", "上傳邀請碼成功", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { goToNextActivity(); } }); } else { if (errorCode == -1) { GtApi.alertOKMessage(TaskTask_10006_EnterInviteCode.this, "", "邀請碼錯誤!", null); } else if (errorCode == -3) { GtApi.alertOKMessage(TaskTask_10006_EnterInviteCode.this, "", "您已經執行過邀請任務了!)", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { goToNextActivity(); } }); } else { GtApi.alertOKMessage(TaskTask_10006_EnterInviteCode.this, "", "邀請失敗,伺服器異常!", null); } } } }); } }; t.start(); } private void goToNextActivity() { TaskSharedPreferences.saveIsEnterInviteCode(this,true); TaskApi.openTaskResult(this, this, mDetail, mRedeemType); } public static void resignKeyboard(Activity activity) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if (imm == null) return; View focusView = activity.getCurrentFocus(); if (focusView == null) return; focusView.clearFocus(); imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0); } }
package xhu.wncg.firesystem.modules.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import xhu.wncg.firesystem.modules.mapper.PoliceStationMapper; import xhu.wncg.firesystem.modules.service.PoliceStationService; import xhu.wncg.firesystem.modules.controller.vo.PoliceStationVO; import xhu.wncg.firesystem.modules.controller.qo.PoliceStationQO; /** * @author zhaobo * @email 15528330581@163.com * @version 2017-11-02 15:58:16 */ @Service("policeStationService") public class PoliceStationServiceImpl implements PoliceStationService { @Autowired private PoliceStationMapper policeStationMapper; @Override public PoliceStationVO queryObject(Integer policeStationId){ return policeStationMapper.queryObject(policeStationId); } @Override public List<PoliceStationVO> queryList(Map<String, Object> map){ return policeStationMapper.queryList(map); } @Override public int queryTotal(Map<String, Object> map){ return policeStationMapper.queryTotal(map); } @Override public void save(PoliceStationQO policeStation){ policeStationMapper.save(policeStation); } @Override public void update(PoliceStationQO policeStation){ policeStationMapper.update(policeStation); } @Override public void delete(Integer policeStationId){ policeStationMapper.delete(policeStationId); } @Override public void deleteBatch(Integer[] policeStationIds){ policeStationMapper.deleteBatch(policeStationIds); } }
package net.mapthinks.web.rest.common; import com.codahale.metrics.annotation.Timed; import net.mapthinks.domain.base.AbstractBaseEntity; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; /** * REST controller for managing T. */ public abstract class AbstractSimpleResource<T extends AbstractBaseEntity,SR extends ElasticsearchRepository<T,Long>,R extends JpaRepository<T,Long>> extends AbstractResource<T,SR,R> { public AbstractSimpleResource(R repo, SR searchRepo) { super(repo,searchRepo); } /** * GET /entitys -> get all the entitys. */ @RequestMapping( method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public List<T> getAll() { log.debug("REST request to get all "+restPathName); return repo.findAll(); } }
package maven_ssm.utils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class DigestUtil { private DigestUtil() {} private static DigestUtil instance; public static DigestUtil getInstance() { if(instance == null) { synchronized (DigestUtil.class) { if(instance == null) { instance = new DigestUtil(); } } } return instance; } /** * * version:md5加密 * @param msg 要加密的数据 * @return *---------------------- * author:xiezhyan * date:2017-6-5 */ public String md5(String msg) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); byte[] bs = digest.digest(msg.getBytes("UTF-8")); if(bs != null) { StringBuffer sb = new StringBuffer(); String hexStr; for(byte b : bs) { int i = b & 0xFF; hexStr = Integer.toHexString(i); if(hexStr.length() < 2) { hexStr = "0" + hexStr; } sb.append(hexStr); } return sb.toString(); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; } /** * * version:加密方法 * @param encodeStr 需要加密的数据 * @return 加密后的数据 *------------------------------------- * author:xiezhyan * date:2017-4-28 */ public String encode(String encodeStr) { if(encodeStr != null && !"".equals(encodeStr)) { BASE64Encoder encoder = new BASE64Encoder(); try { return encoder.encode(encodeStr.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return ""; } /** * 解密 * @param decodeStr 需要解密的数据 * @return 原始数据 */ public String decode(String decodeStr){ if(decodeStr != null && !"".equals(decodeStr)) { BASE64Decoder decoder = new BASE64Decoder(); try { return new String(decoder.decodeBuffer(decodeStr),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return ""; } }
package stack; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Stack; /** * Created by gouthamvidyapradhan on 20/01/2018. * Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive * time of these functions. Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function. A log is a string has this format : function_id:start_or_end:timestamp. For example, "0:start:0" means function 0 starts from the very beginning of time 0. "0:end:0" means function 0 ends to the very end of time 0. Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id. Example 1: Input: n = 2 logs = ["0:start:0", "1:start:2", "1:end:5", "0:end:6"] Output:[3, 4] Explanation: Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time. Note: Input logs will be sorted by timestamp, NOT log id. Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0. Two functions won't start or end at the same time. Functions could be called recursively, and will always end. 1 <= n <= 100 Solution: Use a stack to store the logs and update time. */ public class ExclusiveTimeOfFunctions { class Log{ int funId, time; String fun; Log(int funId, String fun, int time){ this.funId = funId; this.fun = fun; this.time = time; } } /** * Main method * @param args * @throws Exception */ public static void main(String[] args) throws Exception{ int[] N = new ExclusiveTimeOfFunctions().exclusiveTime(2, Arrays.asList("0:start:0", "1:start:2", "1:end:5", "0:end:6")); Arrays.stream(N).forEach(System.out::println); } public int[] exclusiveTime(int n, List<String> logs) { int[] N = new int[n]; List<Log> functions = new ArrayList<>(); for(String s : logs){ String[] parts = s.split(":"); functions.add(new Log(Integer.parseInt(parts[0]), parts[1], Integer.parseInt(parts[2]))); } Stack<Log> stack = new Stack<>(); stack.push(functions.get(0)); for(int i = 1, l = functions.size(); i < l; i ++){ Log next = functions.get(i); if(stack.isEmpty()){ stack.push(next); continue; } Log curr = stack.peek(); if(next.fun.equals("end")){ N[curr.funId] += (next.time - curr.time + 1); stack.pop(); //since the end has reached, remove from stack if(!stack.isEmpty()){ stack.peek().time = next.time + 1; //IMPORTANT: update the time of the old function to a new start // time } } else { stack.push(next); N[curr.funId] += (next.time - curr.time); } } return N; } }
package awaitTermination; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @author zhuzhisheng * @Description * @date on 2016/6/1. */ public class TestShutdown { public static void main(String[] args) throws InterruptedException { ScheduledExecutorService service = Executors.newScheduledThreadPool(4); service.submit(new Task()); service.submit(new Task()); service.submit(new LongTask()); service.submit(new Task()); service.shutdown(); while (!service.awaitTermination(3, TimeUnit.SECONDS)) { System.out.println("线程池没有关闭"); } System.out.println("线程池已经关闭"); } } class LongTask implements Callable { @Override public Object call() throws Exception { System.out.println("长时间任务"); TimeUnit.SECONDS.sleep(50); return null; } } class Task implements Callable{ @Override public Object call() throws Exception { System.out.println("普通任务"); return null; } }
package com.psl.training.college; public class GraduateFaculty extends Faculty implements IPerson, ITemporary, ISalaried { public int contract = ISalaried.years; public int id; public String name; public GraduateFaculty(int id, String name) { // TODO Auto-generated constructor stub super(id,name); } @Override public void display() { // TODO Auto-generated method stub System.out.println("I am a Graduate faculty.."); System.out.println("I am working for "+ contract +" years."); } @Override void facultyDetails(int id, String name) { // TODO Auto-generated method stub System.out.println("id : "+id); System.out.println("id : "+name); } }
package blackbird.core.packets; import blackbird.core.HostDevice; import blackbird.core.Packet; /** * The handshake packet used by the host connection to identify * the device on the remote side of the connection. */ public class HandshakePacket extends Packet { private static final long serialVersionUID = 5603371753276866796L; private HostDevice device; private int rmiImplementationID; public HandshakePacket(HostDevice device, int rmiImplementationID) { super(); this.device = device; this.rmiImplementationID = rmiImplementationID; } public HostDevice getDevice() { return device; } public int getRmiImplementationID() { return rmiImplementationID; } }
import java.util.Scanner; public class MetodeBiseksi{ public static void main(String[] args) { Scanner input=new Scanner(System.in); float a,b,e,fa,fb; float xr = 0; float fxr = 0; int n; System.out.print("Batas bawah : "); a=input.nextFloat(); System.out.print("Batas atas : "); b=input.nextFloat(); System.out.print("Toleransi eror : "); e=input.nextFloat(); System.out.print("jumlah pembagi N : "); n=input.nextInt(); fa = (a*a*a) - (7*a) + 1; fb = (b*b*b) - (7*b) + 1; if ((fa*fb) > 0) { System.out.print("Tidak ada akar"); } else{ int kondisi = 1; int iterasi = 0; while (kondisi == 1) { iterasi++; xr = (a+b)/2; fxr = (xr*xr*xr)-(7*xr)+1; if ((Math.abs(b-a) < e)||(iterasi > n)) { kondisi = 0; }else { if ((fa*fxr) < 0 ) { b = xr; fb = fxr; } else{ a = xr; fa = fxr; } } } System.out.println("nilai xr = " + xr); System.out.println("nilai f(xr) = " + fxr); } } }
package com.github.gaoyangthu.esanalysis; import com.github.gaoyangthu.esanalysis.bdb.service.BDBService; import com.github.gaoyangthu.esanalysis.bdb.service.impl.BDBServiceImpl; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; /** * BerkeleyDB 定时任务 * * Author: gaoyangthu * Date: 2014/4/2 * Time: 15:05 */ public class BDBJob implements Job { /** * 定时生成bdb数据库,并上传到hdfs * * @param context * @throws org.quartz.JobExecutionException if there is an exception while executing the job. */ @Override public void execute(JobExecutionContext context) throws JobExecutionException { BDBService bdbService = new BDBServiceImpl(); bdbService.report(); } }
package com.bnebit.sms.util.page; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.tags.form.AbstractHtmlElementTag; import org.springframework.web.servlet.tags.form.TagWriter; public class PagingTag extends AbstractHtmlElementTag { private static final long serialVersionUID = 6219333267087907329L; private static final Logger LOGGER = LoggerFactory.getLogger(PagingTag.class); private String linkUrl; private String pageParamName; private PageSet pageSet; public String getLinkUrl() { return linkUrl; } public String getPageParamName() { return pageParamName; } public PageSet getPageSet() { return pageSet; } public void setPageParamName(String pageParamName) { this.pageParamName = pageParamName; } public void setLinkUrl(String linkUrl) { this.linkUrl = linkUrl; } public void setPageSet(PageSet pageSet) { this.pageSet = pageSet; } private String getLinkAddParam(final long targetPage) { return linkUrl + "?" + pageParamName + "=" + targetPage + this.pageSet.getParamString(); } @Override protected int writeTagContent(TagWriter tagWriter) throws JspException { StringBuilder pagingTag = new StringBuilder(); if (pageSet.hasPreviousPageGroup()) { pagingTag.append("<a href=\""); pagingTag.append(getLinkAddParam(pageSet.getPageGroupStartPage() - 1)); pagingTag.append("\">"); pagingTag.append(pageSet.getPreviousLabel()); pagingTag.append("</a>"); } long pageGroupStartPage = pageSet.getPageGroupStartPage(); long pageGroupEndPage = pageSet.getPageGroupEndPage(); long currentPage = pageSet.getCurrentPage(); for (long i = pageGroupStartPage; i <= pageGroupEndPage; i++ ) { if (currentPage == i) { pagingTag.append("<a href=\"#!"); pagingTag.append("\" class=\""); pagingTag.append(pageSet.getCurrentPageClass()); pagingTag.append("\">"); pagingTag.append(i); pagingTag.append("</a>"); } else { pagingTag.append("<a href=\""); pagingTag.append(getLinkAddParam(i)); pagingTag.append("\" class=\""); pagingTag.append(pageSet.getPageClass()); pagingTag.append("\">"); pagingTag.append(i); pagingTag.append("</a>"); } pagingTag.append("&nbsp;"); } if (pageSet.hasNextPageGroup()) { pagingTag.append("<a href=\""); pagingTag.append(getLinkAddParam(pageSet.getPageGroupEndPage() + 1)); pagingTag.append("\">"); pagingTag.append(pageSet.getNextLabel()); pagingTag.append("</a>"); } JspWriter writer = this.pageContext.getOut(); try { writer.write(pagingTag.toString()); writer.flush(); } catch (IOException e) { LOGGER.error("페이징 태그 에러!!!", e); } return EVAL_PAGE; } }
package Problem_1436; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int count = 0; int answer = 666; String str; for(int i = 666; count < N; i++) { str = String.valueOf(i); if(str.contains("666")) { answer = i; count++; } } System.out.println(answer); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context.support; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import org.springframework.test.context.MergedContextConfiguration; import static org.assertj.core.api.Assertions.assertThat; /** * Unit test which verifies that extensions of * {@link AbstractGenericContextLoader} are able to <em>customize</em> the * newly created {@code ApplicationContext}. Specifically, this test * addresses the issues raised in <a * href="https://opensource.atlassian.com/projects/spring/browse/SPR-4008" * target="_blank">SPR-4008</a>: <em>Supply an opportunity to customize context * before calling refresh in ContextLoaders</em>. * * @author Sam Brannen * @since 2.5 */ class CustomizedGenericXmlContextLoaderTests { @Test void customizeContext() throws Exception { AtomicBoolean customizeInvoked = new AtomicBoolean(false); GenericXmlContextLoader customLoader = new GenericXmlContextLoader() { @Override protected void customizeContext(GenericApplicationContext context) { assertThat(context.isActive()).as("The context should not yet have been refreshed.").isFalse(); customizeInvoked.set(true); } }; MergedContextConfiguration mergedConfig = new MergedContextConfiguration(getClass(), null, null, null, null); customLoader.loadContext(mergedConfig); assertThat(customizeInvoked).as("customizeContext() should have been invoked").isTrue(); } }
package com.example.baitaptuan9; public class Music { private String tenbh; private String mota; private int hinh; public Music(String mota, String tenbh, int hinh) { this.mota = mota; this.tenbh = tenbh; this.hinh = hinh; } public String getMota() { return mota; } public void setMota(String mota) { this.mota = mota; } public String getTenbh() { return tenbh; } public void setTenbh(String tenbh) { this.tenbh = tenbh; } public int getHinh() { return hinh; } public void setHinh(int hinh) { this.hinh = hinh; } }
/* * 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 br.com.oop; import java.util.ArrayList; /** * * @author root */ public class Database { private static ArrayList<Pessoa> pessoas = new ArrayList<>(); private static ArrayList<Fornecedor> fornecedor = new ArrayList<>(); /** * @return */ public static ArrayList<Pessoa> getPessoasList() { return pessoas; } public static ArrayList<Fornecedor> getFornecedorList() { return fornecedor; } public static Object select(String tableName) { if(tableName.equals("pessoa")) return pessoas; else if(tableName.equals("fornecedor")) return fornecedor; else return new ArrayList<>(); } public static Object select(String tableName, int index) { if(tableName.equals("pessoa")) return pessoas.get(index); else if(tableName.equals("fornecedor")) return fornecedor.get(index); else return false; } public static boolean insert(String tableName, Object dados) { if(tableName.equals("pessoa")) return pessoas.add((Pessoa)dados); else if(tableName.equals("fornecedor")) return fornecedor.add((Fornecedor)dados); else return false; } public static boolean update(String tableName, String[] dados, int index) { if(tableName.equals("pessoa")) { Pessoa p = pessoas.get(index); p.setNome(dados[0]); p.setEmail(dados[1]); p.setTelefone(dados[2]); p.setEndereco(dados[3]); p.setCpf(dados[4]); p.setRg(dados[5]); return true; } else if(tableName.equals("fornecedor")) { Fornecedor f = fornecedor.get(index); f.setNome(dados[0]); f.setEmail(dados[1]); f.setTelefone(dados[2]); f.setEndereco(dados[3]); f.setCnpj(dados[4]); f.setNome_social(dados[5]); return true; } else return false; } public static boolean delete(String tableName, int index) { if(tableName.equals("pessoa")) { pessoas.remove(index); return true; } else if(tableName.equals("fornecedor")) { fornecedor.remove(index); return true; } else return false; } }
/*package utility; import org.apache.commons.mail.EmailException; import org.openqa.selenium.WebDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import factory.BrowserFactory; import factory.DataProviderFactory; public class BaseClass { WebDriver driver; ExtentReports report; ExtentTest logger; @BeforeMethod public void setUp() throws EmailException { driver = BrowserFactory.getBrowser("Firefox"); Mail.SendEmail(); //System.out.println("Email sent"); report = new ExtentReports(".\\Reports\\MMPHomePageReport.html",true); logger = report.startTest("Verify MMPHome Page - Logs and reports added"); driver.get(DataProviderFactory.getConfig().getApplicationUrl()); logger.log(LogStatus.INFO, "Application up and running"); } @BeforeMethod public void setUp() { driver = BrowserFactory.getBrowser("Firefox"); driver.get(DataProviderFactory.getConfig().getApplicationUrl()); } @AfterMethod public void tearDown() { BrowserFactory.closeBrowser(); report.endTest(logger); report.flush(); } @AfterMethod public void tearDown(){ BrowserFactory.closeBrowser(); } } */
package ca.brocku.cosc3p97.bigbuzzerquiz.messages.host; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.List; import ca.brocku.cosc3p97.bigbuzzerquiz.messages.common.JsonMessage; import ca.brocku.cosc3p97.bigbuzzerquiz.messages.common.Response; /** * A response object responsible for sending a response to the player from the host responding * with a the list of names of the players that are connected to the host. */ public class GetPlayersResponse extends Response { public static final String NAMES = "NAMES"; /** * Constructor which exposes the constructor of the super class and builds the internal * JSONObject frpm the string passed in as an argument * @param string JSON string of values * @throws JSONException */ public GetPlayersResponse(String string) throws JSONException { super(string); } /** * Constructor that calls an override for the setIdentifier method */ public GetPlayersResponse() { super(); setIdentifier(); } /** * Override the setIdentifier method with the value GET_PLAYERS */ @Override public void setIdentifier() { try { put(JsonMessage.IDENTIFIER, HostRequestContract.GET_PLAYERS); } catch (JSONException e) { e.printStackTrace(); } } /** * Create the NAMES attribute and assign to it the value passed as an argument * @param toBeSerialized the boolean value to assign to the attribute */ @Override public void serialize(Object toBeSerialized) { List<String> names = (List<String>) toBeSerialized; try { JSONArray jsonNames = new JSONArray(); for (String name : names) { jsonNames.put(name); } put(GetPlayersResponse.NAMES, jsonNames); } catch (JSONException e) { e.printStackTrace(); } } /** * Convert the internal value of the NAMES attribute into a List<String> value and return * it to the calling method */ @Override public Object deserialize() { List<String> names = new ArrayList<>(); try { JSONArray jsonNames = getJSONArray(GetPlayersResponse.NAMES); for (int i = 0; i < jsonNames.length(); i++) { names.add((String) jsonNames.get(i)); } } catch (JSONException e) { e.printStackTrace(); } return names; } }
package com.layduo.web.test; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * @author layduo * @createTime 2019年11月15日 上午10:28:12 */ /** * 一、线程池: 提供一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁的额外开销,提高了响应的速度。 二、线程池的体系结构: java.util.concurrent.Executor 负责线程的使用和调度的根接口 |--ExecutorService 子接口: 线程池的主要接口 |--ThreadPoolExecutor 线程池的实现类 |--ScheduledExceutorService 子接口: 负责线程的调度 |--ScheduledThreadPoolExecutor : 继承ThreadPoolExecutor,实现了ScheduledExecutorService 三、工具类 : Executors ExecutorService newFixedThreadPool() : 创建固定大小的线程池 ExecutorService newCachedThreadPool() : 缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。 ExecutorService newSingleThreadExecutor() : 创建单个线程池。 线程池中只有一个线程 ScheduledExecutorService newScheduledThreadPool() : 创建固定大小的线程,可以延迟或定时的执行任务 * */ public class TestShutDown { public static Runnable getTask(int threadNo) { final Random random = new Random(); final int no = threadNo; Runnable task = new Runnable() { @Override public void run() { try { System.out.println(no + "-->" + random.nextInt(10) + "-->" + Thread.currentThread().getName()); Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("thread " + no + " has error: " + e); } } }; return task; } /** * shutDown后可以使用awaitTermination等待所有线程执行完毕当前任务。 * @param startNo * @throws InterruptedException */ public static void testShutDown(int startNo) throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(2); for (int i = 0; i < 5; i++) { executorService.execute(getTask(i + startNo)); } //shutdown后不能submit任务,awaitTermination后可以submit,shutdown不阻塞,awaitTermination阻塞 executorService.shutdown(); //然后返回true(shutdown请求后所有已提交任务执行完毕)或false(已超时) boolean flag = executorService.awaitTermination(120, TimeUnit.SECONDS); System.out.println(flag == true ? "all task finished" : "timeout"); System.out.println("shutDown->all thread shutdown"); } /** * shutDownNow就会迫使当前执行的所有任务停止工作。 * @param startNo * @throws InterruptedException */ public static void testShutDownNow(int startNo) throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(2); for (int i = 0; i < 5; i++) { executorService.execute(getTask(i + startNo)); } executorService.shutdownNow(); executorService.awaitTermination(120, TimeUnit.SECONDS); System.out.println("shutDownNow->all thread shutdown"); } public static void main(String[] args) { try { testShutDown(100); testShutDownNow(200); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.programapprentice.app; import java.util.HashMap; /** * User: program-apprentice * Date: 8/18/15 * Time: 6:29 PM */ public class MultiplyStrings_43 { public String addStrings(String s1, String s2) { if(s1 == null || s2 == null) { return null; } if(s1.equals("")) { return s2; } if(s2.equals("")) { return s1; } int maxLength = Math.max(s1.length(), s2.length()); char[] buffer = new char[maxLength+1]; int minLength = Math.min(s1.length(), s2.length()); int i = 0; int l1 = s1.length(); int l2 = s2.length(); int l = maxLength + 1; int carry = 0; int tmp = 0; for(i = 0; i < minLength; i++) { tmp = char2int(s1.charAt(l1-1-i)) + char2int(s2.charAt(l2-i-1)) + carry; buffer[l - i - 1] = int2char(tmp % 10); carry = tmp / 10; } String s = null; if(s2.length() > minLength) { s = s2; } else { s = s1; } for(; i < maxLength; i++) { tmp = char2int(s.charAt(s.length()-1-i)) + carry; buffer[l-i-1] = int2char(tmp % 10); carry = tmp / 10; } buffer[0] = int2char(carry); if(carry == 0) { return new String(buffer, 1, buffer.length-1); } else { return new String(buffer); } } public int char2int(char c) { return c - '0'; } public char int2char(int i) { return (char)('0' + i); } public String charMultiply(String s, char c) { if(c == '0') { return "0"; } char[] buffer = new char[s.length() + 1]; int carry = 0; int multiply = 0; int i = 0; for(i = s.length()-1; i >= 0; i--) { multiply = char2int(s.charAt(i)) * char2int(c) + carry; buffer[i+1] = int2char(multiply % 10); carry = multiply / 10; } buffer[0] = int2char(carry); if(carry == 0) { return new String(buffer, 1, buffer.length-1); } else { return new String(buffer); } } public String multiply(String s1, String s2) { if(s1 == null || s2 == null) { return null; } if(s1.isEmpty() || s2.isEmpty()) { return ""; } if(s1.equals("0") || s2.equals("0")) { return "0"; } HashMap<Character, String> record = new HashMap<Character, String>(); String zeros = ""; String newString = ""; for(int i = s2.length()-1; i >= 0; i--) { char c = s2.charAt(i); String rec = record.get(c); if(rec == null) { rec = charMultiply(s1, c); record.put(c, rec); } rec = rec + zeros; newString = addStrings(newString, rec); zeros += "0"; } return newString; } }
package com.needii.dashboard.service; import java.util.List; import com.needii.dashboard.model.AdminBalanceHistory; import com.needii.dashboard.utils.Option; public interface AdminBalanceHistoryService { List<AdminBalanceHistory> findAll(); List<AdminBalanceHistory> findAll(Option option); long count(Option option); AdminBalanceHistory findOne(long id); AdminBalanceHistory findLatestOne(); void create(AdminBalanceHistory entity); void update(AdminBalanceHistory entity); void delete(AdminBalanceHistory entity); }
package com.billy.cc.core.ipc; import android.text.TextUtils; import android.util.Log; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class CP_Util { private static final String TAG = "IPCCaller"; private static final String VERBOSE_TAG = "IPCCaller_VERBOSE"; private static final String PROCESS_UNKNOWN = "UNKNOWN"; private static String processName = null; static boolean DEBUG = false; static boolean VERBOSE_LOG = false; static { if (BuildConfig.DEBUG) { DEBUG = true; VERBOSE_LOG = true; } } public static void log(String s, Object... args) { if (DEBUG) { s = format(s, args); Log.i(TAG, "(" + getProcessName() +")(" + Thread.currentThread().getName() + ")" + " >>>> " + s); } } public static void verboseLog(String s, Object... args) { if (VERBOSE_LOG) { s = format(s, args); Log.i(VERBOSE_TAG, "(" + getProcessName() +")(" + Thread.currentThread().getName() + ")" + " >>>> " + s); } } public static void logError(String s, Object... args) { if (DEBUG) { s = format(s, args); Log.e(TAG, "(" + getProcessName() +")(" + Thread.currentThread().getName() + ")" + " >>>> " + s); } } public static void printStackTrace(Throwable t) { if (DEBUG && t != null) { t.printStackTrace(); } } public static String getProcessName() { if (processName != null) { return processName; } String ret = getProcessName(android.os.Process.myPid()); if (!TextUtils.isEmpty(ret)) { processName = ret; } else { processName = PROCESS_UNKNOWN; } return processName; } public static String getProcessName(int pid) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline")); String processName = reader.readLine(); if (!TextUtils.isEmpty(processName)) { processName = processName.trim(); } return processName; } catch (Exception e) { } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { } } return PROCESS_UNKNOWN; } private static String format(String s, Object... args) { try { if (args != null && args.length > 0) { s = String.format(s, args); } } catch (Exception e) { CP_Util.printStackTrace(e); } return s; } }
package Exception; public class AlunoInexistenteException extends Exception { public AlunoInexistenteException(String e){ super(e); } }
package myProject; import java.awt.Graphics; public class M { public static void main(String []args) { Display1 a = new Display1(); a.setVisible(true); } }
package sonar.socket; import static org.junit.jupiter.api.Assertions.*; import java.util.Random; import java.util.concurrent.*; import java.util.zip.CRC32; import org.junit.jupiter.api.*; import org.junit.jupiter.api.condition.*; import sonar.minimodem.*; public class SocketTest { @BeforeEach public void setUp() throws InterruptedException { Thread.sleep(3000); } @Test public void testPacketCRC() { Packet p1 = new Packet(420, 69); Random random = new Random(); int min = 0; int max = Packet.BUFF - Packet.HEADERS; int randomLen = random.ints(min, max).findFirst().getAsInt(); for (int i = 0; i < randomLen; i++) { p1.write((byte) random.nextInt()); } Packet p2 = new Packet(p1.data.clone()); assertEquals(p1.getCRC32(), p2.getCRC32()); assertEquals(p1.getAck(), p2.getAck()); assertEquals(p1.getSeq(), p2.getSeq()); assertEquals(p1.getDataLength(), p2.getDataLength()); for (int i = 0; i < Packet.BUFF; i++) { assertEquals(p1.data[i], p2.data[i]); } // Verificar crc32 CRC32 calculated = new CRC32(); calculated.update(p2.getSeq()); calculated.update(p2.getAck()); // calculated.update(p.data, Packet.HEADERS, p.getDataLength()); for (int i = Packet.HEADERS; i < Packet.HEADERS + p2.getDataLength(); i++) { calculated.update(p2.data[i]); } assertEquals(calculated.getValue(), p2.getCRC32()); } @Test @DisplayName("Enviar y recibir un paquete") // @Disabled() public void sendSinglePacket() { try { MinimodemReceiver rx = new MinimodemReceiver(BaudMode.BELL202); MinimodemTransmitter tx = new MinimodemTransmitter(BaudMode.BELL202); BufferedTransmitter transmitter = new BufferedTransmitter(tx); BufferedReceiver receiver = new BufferedReceiver(rx); SonarSocket socket = new SonarSocket(receiver, transmitter); Packet sent = new Packet(24, 10009); assertEquals(sent.getSeq(), 24); assertEquals(sent.getAck(), 10009); // for (int i = Packet.HEADERS; i < 60; i++) { // sent.write((byte) random.nextInt()); // } socket.writePacket(sent); Packet received = socket.receivePacket(); assertEquals(sent.getDataLength(), 0); assertEquals(received.getDataLength(), 0); assertEquals(sent.getCRC32(), received.getCRC32()); assertEquals(sent.getSeq(), received.getSeq()); assertEquals(sent.getAck(), received.getAck()); // Verificar que es un paquete lleno // assertEquals(sent.getDataLength(), Packet.BUFF - Packet.HEADERS); for (int i = 0; i < Packet.BUFF; i++) { assertEquals(sent.data[i], received.data[i]); } // Verificar que coinciden los crc CRC32 crc32 = new CRC32(); crc32.update(received.getSeq()); crc32.update(received.getAck()); crc32.update(received.data, Packet.HEADERS, received.getDataLength()); long calculated = crc32.getValue(); long got = received.getCRC32(); assertEquals(got, calculated); socket.close(); } catch (Exception e) { System.err.println(e.toString()); fail(); } } @Test @DisplayName("Recibir un paquete en un lapso de tiempo") @Disabled() public void testReceiveTimedPacket() { try { MinimodemReceiver rx = new MinimodemReceiver(BaudMode.BELL202); MinimodemTransmitter tx = new MinimodemTransmitter(BaudMode.BELL202); BufferedTransmitter transmitter = new BufferedTransmitter(tx); BufferedReceiver receiver = new BufferedReceiver(rx); SonarSocket socket = new SonarSocket(receiver, transmitter); Random random = new Random(); Packet sent = new Packet(24, 10009); for (int i = Packet.HEADERS; i < Packet.BUFF; i++) { sent.write((byte) random.nextInt()); } socket.writePacket(sent); Future<Packet> future = socket.timedReceivePacket0(); Packet received = future.get(SonarSocket.DELAY_MS, TimeUnit.MILLISECONDS); for (int i = 0; i < Packet.BUFF; i++) { assertEquals(sent.data[i], received.data[i]); } socket.close(); } catch (Exception e) { fail("El paquete no se mandó en el timeout"); } } @Test @DisplayName("Test de writeLockStep con bandera EOF") public void testWriteLockstep() { try { MinimodemReceiver rx = new MinimodemReceiver(BaudMode.BELL202); MinimodemTransmitter tx = new MinimodemTransmitter(BaudMode.BELL202); BufferedTransmitter transmitter = new BufferedTransmitter(tx); BufferedReceiver receiver = new BufferedReceiver(rx); SonarSocket socket = new SonarSocket(receiver, transmitter); Random random = new Random(); Packet sent = new Packet(24, 10009); for (int i = Packet.HEADERS; i < Packet.BUFF; i++) { sent.write((byte) random.nextInt()); } socket.signalEOF(); Packet received = socket.writeLockstep(sent, SonarSocket.DELAY_MS * 2); for (int i = 0; i < Packet.BUFF; i++) { assertEquals(sent.data[i], received.data[i]); } assertTrue(received.getEOF()); socket.close(); } catch (Exception e) { fail("El paquete no se mandó en el timeout"); } } @Test @DisplayName("Probar dos veces el lockstep") public void testTwoLockstep() { try { MinimodemReceiver rx = new MinimodemReceiver(BaudMode.BELL202); MinimodemTransmitter tx = new MinimodemTransmitter(BaudMode.BELL202); BufferedTransmitter transmitter = new BufferedTransmitter(tx); BufferedReceiver receiver = new BufferedReceiver(rx); SonarSocket socket = new SonarSocket(receiver, transmitter); Random random = new Random(); Packet sent1 = new Packet(24, 10009); Packet sent2 = new Packet(48, 20009); for (int i = Packet.HEADERS; i < Packet.BUFF; i++) { sent1.write((byte) random.nextInt()); sent2.write((byte) random.nextInt()); } Packet received1 = socket.writeLockstep(sent1, SonarSocket.DELAY_MS * 2); Thread.sleep(SonarSocket.DELAY_MS); Packet received2 = socket.writeLockstep(sent2, SonarSocket.DELAY_MS * 2); Thread.sleep(SonarSocket.DELAY_MS); for (int i = 0; i < Packet.BUFF; i++) { assertEquals(sent1.data[i], received1.data[i]); } for (int i = 0; i < Packet.BUFF; i++) { assertEquals(sent2.data[i], received2.data[i]); } socket.close(); } catch (Exception e) { System.err.println(e.toString()); fail(); } } }
package com.intel.realsense.librealsense; public enum StreamType { ANY(0), DEPTH(1), COLOR(2), INFRARED(3), FISHEYE(4), GYRO(5), ACCEL(6), GPIO(7), POSE(8), CONFIDENCE(9); private final int mValue; private StreamType(int value) { mValue = value; } public int value() { return mValue; } }
package com.fr.io; import java.io.File; import java.io.FileOutputStream; import com.fr.base.FRContext; import com.fr.base.dav.LocalEnv; import com.fr.report.ResultWorkBook; import com.fr.report.WorkBook; import com.fr.report.io.CSVExporter; import com.fr.report.io.ExcelExporter; import com.fr.report.io.PDFExporter; import com.fr.report.io.TemplateExporter; import com.fr.report.io.TemplateImporter; import com.fr.report.io.TextExporter; import com.fr.report.io.WordExporter; import com.fr.report.io.core.EmbeddedTableDataExporter; import com.fr.report.parameter.Parameter; public class ExportApi { public static void main(String[] args) { // 定义报表运行环境,才能执行报表 String envPath = "C:\\FineReport6.5\\WebReport\\WEB-INF"; FRContext.setCurrentEnv(new LocalEnv(envPath)); ResultWorkBook rworkbook = null; try{ //未执行模板工作薄 File cptfile = new File("C:\\FineReport6.5\\WebReport\\WEB-INF\\reportlets\\exportdemo.cpt"); TemplateImporter tplImp = new TemplateImporter(); WorkBook workbook = tplImp.generateTemplate(cptfile); //获取报表参数并设置值,导出内置数据集时数据集会根据参数值查询出结果从而转为内置数据集 Parameter[] parameters = workbook.getParameters(); parameters[0].setValue("China"); //定义parametermap用于执行报表,将执行后的结果工作薄保存为rworkBook java.util.Map parameterMap = new java.util.HashMap(); for (int i = 0; i < parameters.length; i++) { parameterMap.put(parameters[i].getName(),parameters[i].getValue()); } //定义输出流 FileOutputStream outputStream; //将未执行模板工作薄导出为内置数据集模板 outputStream = new FileOutputStream(new File("E:\\EmbExport.cpt")); EmbeddedTableDataExporter EmbExport = new EmbeddedTableDataExporter(); EmbExport.export(outputStream, workbook); //将模板工作薄导出模板文件,在导出前您可以编辑导入的模板工作薄,可参考报表调用章节 outputStream = new FileOutputStream(new File("E:\\TmpExport.cpt")); TemplateExporter TmpExport = new TemplateExporter(); TmpExport.export(outputStream, workbook); //将结果工作薄导出为Excel文件 outputStream = new FileOutputStream(new File("E:\\ExcelExport.xls")); ExcelExporter ExcelExport = new ExcelExporter(null); ExcelExport.export(outputStream, workbook.execute(parameterMap)); //将结果工作薄导出为Word文件 outputStream = new FileOutputStream(new File("E:\\WordExport.doc")); WordExporter WordExport = new WordExporter(); WordExport.export(outputStream, workbook.execute(parameterMap)); //将结果工作薄导出为Pdf文件 outputStream = new FileOutputStream(new File("E:\\PdfExport.pdf")); PDFExporter PdfExport = new PDFExporter(); PdfExport.export(outputStream, workbook.execute(parameterMap)); //将结果工作薄导出为Txt文件(txt文件本身不支持表格、图表等,被导出模板一般为明细表) outputStream = new FileOutputStream(new File("E:\\TxtExport.txt")); TextExporter TxtExport = new TextExporter(); TxtExport.export(outputStream, workbook.execute(parameterMap)); //将结果工作薄导出为Csv文件 outputStream = new FileOutputStream(new File("E:\\CsvExport.csv")); CSVExporter CsvExport = new CSVExporter(); CsvExport.export(outputStream, workbook.execute(parameterMap)); }catch (Exception e) { e.printStackTrace(); } } }
package com.extnds.competitive.datastructures; import org.junit.jupiter.api.Test; import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.*; class CircularListTest { @Test public void test1() { CircularList<Integer> circularList = new CircularList<>(); IntStream.range(0, 20) .boxed() .forEach(integer -> { if (integer < 10) circularList.addNodeAtStart(integer); else circularList.addNodeAtEnd(integer); }); System.out.println(circularList.prettyPrint()); assertEquals("9 8 7 6 5 4 3 2 1 0 10 11 12 13 14 15 16 17 18 19", circularList.prettyPrint()); } @Test public void test2() { CircularList<Integer> circularList = new CircularList<>(); IntStream.range(0, 20) .boxed() .forEach(integer -> { if (integer < 10) circularList.addNodeAtEnd(integer); else circularList.addNodeAtStart(integer); }); System.out.println(circularList.prettyPrint()); assertEquals("19 18 17 16 15 14 13 12 11 10 0 1 2 3 4 5 6 7 8 9", circularList.prettyPrint()); } @Test public void test3() { CircularList<Integer> circularList = new CircularList<>(); IntStream.range(0, 10) .boxed() .forEach(circularList::addNodeAtStart); System.out.println(circularList.prettyPrint()); assertEquals("9 8 7 6 5 4 3 2 1 0", circularList.prettyPrint()); } @Test public void test4() { CircularList<Integer> circularList = new CircularList<>(); IntStream.range(0, 10) .boxed() .forEach(circularList::addNodeAtEnd); System.out.println(circularList.prettyPrint()); assertEquals("0 1 2 3 4 5 6 7 8 9", circularList.prettyPrint()); } }
package roc.cjm.shapeimageview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.support.v7.widget.AppCompatImageView; import android.util.AttributeSet; /** * Created by Jiamei Cheng on 2017/7/6. */ public class ShapeImageView extends AppCompatImageView { private Paint mPaint; public static final int TYPE_CIRCLE = 1; public static final int TYPE_ROUND_RECT = 2; private static final int COLORDRAWABLE_DIMENSION = 2; private Bitmap mBmpPhoto; private Paint mBackPaint; private Paint mCirClePaint; private Paint mClearPaint; private int mShapeType = 1; private int mBottomColor = 0xffffffff; private float borderWidth = 0; private int borderColor = 0xffffffff; private float roundRadiusX = 0f; private float roundRadiusY = 0f; private RectF roundRectF = new RectF(); public ShapeImageView(Context context) { super(context); init(context); } public ShapeImageView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public ShapeImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ShapeImageView); mShapeType = a.getInteger(R.styleable.ShapeImageView_siv_shape_type, 1); borderWidth = a.getDimensionPixelSize(R.styleable.ShapeImageView_siv_border_width, 0); borderColor = a.getColor(R.styleable.ShapeImageView_siv_border_color, context.getResources().getColor(R.color.white)); mBottomColor = a.getColor(R.styleable.ShapeImageView_siv_background_color, context.getResources().getColor(R.color.white)); roundRadiusX = a.getDimensionPixelSize(R.styleable.ShapeImageView_siv_round_radius_x, 0); roundRadiusY = a.getDimensionPixelSize(R.styleable.ShapeImageView_siv_round_radius_y, 0); a.recycle(); init(context); } public void init(Context context) { mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mPaint.setARGB(255, 255, 225, 255); mBackPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBackPaint.setColor(mBottomColor); mBackPaint.setStyle(Paint.Style.FILL); mCirClePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirClePaint.setColor(borderColor); mCirClePaint.setStyle(Paint.Style.STROKE); mCirClePaint.setStrokeWidth(borderWidth); mClearPaint = new Paint(); mClearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); initializeBitmap(); } @Override public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); initializeBitmap(); } @Override public void setImageResource(@DrawableRes int resId) { super.setImageResource(resId); initializeBitmap(); } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); initializeBitmap(); } private void initializeBitmap() { mBmpPhoto = getBitmapFromDrawable(getDrawable()); setup(); } private Bitmap getBitmapFromDrawable(Drawable drawable) { if (drawable == null) { return null; } if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } try { Bitmap bitmap; if (drawable instanceof ColorDrawable) { bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, Bitmap.Config.ARGB_8888); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (Exception e) { e.printStackTrace(); return null; } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); setup(); } @Override public void setPadding(int left, int top, int right, int bottom) { super.setPadding(left, top, right, bottom); setup(); } @Override public void setPaddingRelative(int start, int top, int end, int bottom) { super.setPaddingRelative(start, top, end, bottom); setup(); } public void setup() { if (mBackPaint != null) { mBackPaint.setColor(mBottomColor); invalidate(); } } public float getRoundRadiusX() { return roundRadiusX; } public void setRoundRadiusX(float roundRadiusX) { this.roundRadiusX = roundRadiusX; invalidate(); } public float getRoundRadiusY() { return roundRadiusY; } public void setRoundRadiusY(float roundRadiusY) { this.roundRadiusY = roundRadiusY; invalidate(); } public int getmShapeType() { return mShapeType; } public void setmShapeType(int mShapeType) { this.mShapeType = mShapeType; } @Override protected void onDraw(Canvas canvas) { if (getHeight() <= 0) { return; } if (mBmpPhoto == null) { return; } Bitmap tmp = null; boolean isH = getHeight() > getWidth(); int wid = (getHeight() > getWidth() ? getWidth() : getHeight()); int rad = wid / 2; switch (mShapeType) { case TYPE_CIRCLE: Matrix matrix = new Matrix(); float rate = (wid * 1.0f / (!isH ? mBmpPhoto.getWidth() : mBmpPhoto.getWidth())); matrix.postScale(rate, rate); mBmpPhoto = Bitmap.createBitmap(mBmpPhoto, 0, 0, mBmpPhoto.getWidth(), mBmpPhoto.getHeight(), matrix, true); canvas.drawCircle(getWidth() / 2, getHeight() / 2, rad, mBackPaint); tmp = getRoundBitmap(mBottomColor, rad); matrix.reset(); matrix.postTranslate(getWidth() / 2 - rad, getHeight() / 2 - rad); canvas.drawBitmap(tmp, matrix, null); break; case TYPE_ROUND_RECT: drawScale(canvas); break; default: break; } switch (mShapeType) { case TYPE_CIRCLE: canvas.drawCircle(getWidth() / 2, getHeight() / 2, rad, mCirClePaint); break; case TYPE_ROUND_RECT: canvas.drawRoundRect(roundRectF, roundRadiusX, roundRadiusY, mCirClePaint); break; default: break; } } public void drawScale(Canvas canvas) { boolean rateTl = (((getHeight() * 1.0f) / (getWidth() * 1.0f)) > ((mBmpPhoto.getHeight() * 1.0f) / (mBmpPhoto.getWidth() * 1.0f))); Matrix matrix = new Matrix(); float rateW = 1.0f; float rateH = 1.0f; float width = getWidth() * 1.0f; float height = getHeight() * 1.0f; ScaleType scaleType = getScaleType(); if (scaleType == ScaleType.CENTER) { } else if (scaleType == ScaleType.CENTER_CROP) { rateW = width / mBmpPhoto.getWidth(); rateH = height / mBmpPhoto.getHeight(); rateH = (rateW > rateH ? rateW : rateH); rateW = rateH; } else if (scaleType == ScaleType.CENTER_INSIDE) { if(width>mBmpPhoto.getWidth() || height>mBmpPhoto.getHeight()){ rateW = (rateTl ? (width) / mBmpPhoto.getWidth() : (height) / mBmpPhoto.getHeight()); rateH = rateW; } } else if (scaleType == ScaleType.FIT_CENTER || scaleType == ScaleType.FIT_END || scaleType == ScaleType.FIT_START) { rateW = (rateTl ? (width) / mBmpPhoto.getWidth() : (height) / mBmpPhoto.getHeight()); rateH = rateW; } else if (scaleType == ScaleType.FIT_XY) { rateW = width / mBmpPhoto.getWidth(); rateH = height / mBmpPhoto.getHeight(); } matrix.postScale(rateW, rateH); mBmpPhoto = Bitmap.createBitmap(mBmpPhoto, 0, 0, mBmpPhoto.getWidth(), mBmpPhoto.getHeight(), matrix, true); matrix.reset(); if (scaleType == ScaleType.FIT_CENTER || scaleType == ScaleType.FIT_XY || scaleType == ScaleType.CENTER_CROP || scaleType == ScaleType.CENTER || scaleType == ScaleType.CENTER_INSIDE) { roundRectF.set((width - mBmpPhoto.getWidth()) / 2, (height - mBmpPhoto.getHeight()) / 2, (width + mBmpPhoto.getWidth()) / 2, (height + mBmpPhoto.getHeight()) / 2); matrix.postTranslate((width - mBmpPhoto.getWidth()) / 2, (height - mBmpPhoto.getHeight()) / 2); }else if (scaleType == ScaleType.FIT_END) { roundRectF.set(width - mBmpPhoto.getWidth(),height - mBmpPhoto.getHeight(),width,height); matrix.postTranslate((width - mBmpPhoto.getWidth()), (height - mBmpPhoto.getHeight()) ); } else if (scaleType == ScaleType.FIT_START) { roundRectF.set(0,0,mBmpPhoto.getWidth(),mBmpPhoto.getHeight()); matrix.postTranslate(0, 0); } else { roundRectF.set((width - mBmpPhoto.getWidth()) / 2, (height - mBmpPhoto.getHeight()) / 2, (width + mBmpPhoto.getWidth()) / 2, (height + mBmpPhoto.getHeight()) / 2); matrix.postTranslate((width - mBmpPhoto.getWidth()) / 2, (height - mBmpPhoto.getHeight()) / 2); } roundRectF.left = (roundRectF.left<0?0:roundRectF.left); roundRectF.top = (roundRectF.top<0?0:roundRectF.top); roundRectF.bottom = (roundRectF.bottom>height?height:roundRectF.bottom); roundRectF.right = (roundRectF.right>width?width:roundRectF.right); canvas.drawRoundRect(roundRectF, roundRadiusX, roundRadiusY, mBackPaint); Bitmap tmp = getRoundRectBitmap(roundRectF, roundRadiusX, roundRadiusY); canvas.drawBitmap(tmp, matrix, null); } public Bitmap getRoundBitmap(int color, int rad) { Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(color); int wid = mBmpPhoto.getWidth(); int hei = mBmpPhoto.getHeight(); Bitmap bmp = Bitmap.createBitmap(rad * 2, rad * 2, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); canvas.drawCircle(mBmpPhoto.getWidth() / 2, mBmpPhoto.getHeight() / 2, rad, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(mBmpPhoto, new Matrix(), paint); return bmp; } public Bitmap getRoundRectBitmap(RectF rectF, float radiusX, float radiusY) { Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColor(mBottomColor); Bitmap bmp = Bitmap.createBitmap(mBmpPhoto.getWidth(), mBmpPhoto.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); canvas.drawRoundRect(new RectF((mBmpPhoto.getWidth() - rectF.width())/2, (mBmpPhoto.getHeight() - rectF.height())/2, (mBmpPhoto.getWidth() - rectF.width())/2+rectF.width(), (mBmpPhoto.getHeight() - rectF.height())/2+rectF.height()), radiusX, radiusY, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(mBmpPhoto, new Matrix(), paint); return bmp; } }
package com.jgw.supercodeplatform.trace.pojo.zaoyangpeach; import java.util.Date; public class SortingPlace { private Integer id; private String sortingPlaceName; private Date createTime; private String organizationId; public String getOrganizationId() { return organizationId; } public void setOrganizationId(String organizationId) { this.organizationId = organizationId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSortingPlaceName() { return sortingPlaceName; } public void setSortingPlaceName(String sortingPlaceName) { this.sortingPlaceName = sortingPlaceName == null ? null : sortingPlaceName.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
import javax.swing.JFrame; /** * Display class * It will handle initializing our mainwindow display * It will create our m x n grid and draw the borders * It will handle drawing the Nodes -> (A node can be a wall (black) , visited (green), or open (white)) * It will handle drawing the shortest path after path-finding is complete (red) * it will handle clearing the board * @author Zakariya Legnain */ public class Display { // frame private JFrame frame; private int width; private int height; // 2d array of Nodes public Display(int width, int height) { this.width = width; this.height = height; this.frame = new JFrame("A-star Visualizer"); } public void run(){ this.frame.setSize(this.width, this.height); this.frame.setVisible(true); } public static void main(String[] args) { Display win = new Display(500, 500); win.run(); } }
package home_work_3.calcs.superDuper; public class TestSuper1 { public static void main(String[] args) { // CalculationLowPriority calculationLowPriority = new CalculationLowPriority(); //// CalculationMediumPriority calculationMediumPriority = new CalculationMediumPriority(); // SortedNull sort = new SortedNull(); // //// calculationMediumPriority.calculationMediumPriority(testExpression); //// System.out.println(calculationLowPriority.calculationLowPriority(testExpression)); // String[] testExpression = {null,"+","8", "-","5","+","15", "*", "2", "/", "3"};//18 // sort.sortNull(testExpression); System.out.println("Пока, все злые"); } }
package util; public interface Filter<T> { /** * Applies this filter to a given object * @param object The object to apply the filter on * @return true if the object passes the filter, false if it doesn't */ public boolean apply(T object); }
import java.io.*; import java.util.*; class occurk { public static void main(String[] args) { Scanner kb =new Scanner(System.in); int n=kb.nextInt(); int k=kb.nextInt(); if(n>0&&n<100001&&k>=0&&k<10) { String str= Integer.toString(n); String st=Integer.toString(k); int count=0; for(int i=0;i<str.length();i++) { if(str.charAt(i)==st.charAt(0)) count++; } System.out.println(count); } } }
package lixh.ireader.util; import android.util.Log; public class InjectLog { public static void PrintFunc() { PrintFunc(null); } public static void PrintFunc(String log1) { PrintFunc(log1, null); } public static void PrintFunc(String log1, String log2) { PrintFunc(log1, log2, null); } public static void PrintFunc(String log1, String log2, String log3) { StringBuffer params = new StringBuffer(); params.append("param:\u2000"); if (log1 != null) { params.append("[" + log1 + "]\n"); } if (log2 != null) { params.append("[" + log2 + "]\n"); } if (log3 != null) { params.append("[" + log3 + "]\n"); } Thread cur_thread = Thread.currentThread(); StackTraceElement stack[] = cur_thread.getStackTrace(); Log.d("InjectLog", "param:" + "[" + params.toString() + "]" + stack[3].toString() + "[" + cur_thread.getId() + "]"); } }