text
stringlengths
10
2.72M
package org.maven.ide.eclipse.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubMonitor; import org.maven.ide.eclipse.authentication.IAuthService; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.FluentCaseInsensitiveStringsMap; import com.ning.http.client.HttpResponseBodyPart; import com.ning.http.client.HttpResponseHeaders; import com.ning.http.client.HttpResponseStatus; public class HttpPublisher extends HttpBaseSupport { /** * Uploads a file to the specified URL. * * @param file The file to upload, must not be {@code null}. * @param url The destination for the uploaded file, must not be {@code null}. * @param monitor The monitor to notify of transfer progress, may be {@code null}. * @param monitorSubtaskName The text to be displayed by the monitor. * @param authService The authenticator service used to query credentials to access protected resources, may be * {@code null}. * @param proxyService The proxy service used to select a proxy that is applicable for the resource, may be * {@code null}. * @param timeoutInMilliseconds Timeout in milliseconds. If null, it will use the default timeout. * @return The server response, can be empty but never {@code null}. * @throws IOException If the resource could not be uploaded. * @throws TransferException If the server rejected the resource. */ public ServerResponse putFile( final RequestEntity file, final URI url, final IProgressMonitor monitor, String monitorSubtaskName, final IAuthService authService, final IProxyService proxyService, Integer timeoutInMilliseconds ) throws IOException { return doDataExchange( file, url, monitor, monitorSubtaskName, authService, proxyService, timeoutInMilliseconds, true, "PUT" ); } public ServerResponse delete( final URI url, final IProgressMonitor monitor, String monitorSubtaskName, final IAuthService authService, final IProxyService proxyService, Integer timeoutInMilliseconds ) throws IOException { return doDataExchange( null /* file */, url, monitor, monitorSubtaskName, authService, proxyService, timeoutInMilliseconds, true, "DELETE" ); } private ServerResponse doDataExchange( final RequestEntity file, final URI uri, final IProgressMonitor monitor, String monitorSubtaskName, final IAuthService authService, final IProxyService proxyService, Integer timeoutInMilliseconds, boolean statusException, String httpMethod ) throws IOException { AsyncHttpClientConfig.Builder confBuilder = init( uri, authService, proxyService, timeoutInMilliseconds ); AsyncHttpClientConfig conf = confBuilder.build(); AsyncHttpClient httpClient = new AsyncHttpClient( conf ); try { FluentCaseInsensitiveStringsMap headers = new FluentCaseInsensitiveStringsMap(); BoundRequestBuilder requestBuilder = null; String url = uri.toString(); if ( "PUT".equals( httpMethod ) ) { requestBuilder = httpClient.preparePut( url ); } else if ( "POST".equals( httpMethod ) ) { requestBuilder = httpClient.preparePost( url ); } else if ( "DELETE".equals( httpMethod ) ) { requestBuilder = httpClient.prepareDelete( url ); } else if ( "HEAD".equals( httpMethod ) ) { requestBuilder = httpClient.prepareHead( url ); } else { throw new RuntimeException( "Support for http method '" + httpMethod + "' not implemented." ); } requestBuilder.setRealm( realm ).setProxyServer( proxyServer ); PushAsyncHandler handler = null; if ( file != null ) { InputStream is = file.getContent(); MonitoredInputStream mis = new MonitoredInputStream( is, SubMonitor.convert( monitor ) ); if ( monitorSubtaskName == null ) { monitorSubtaskName = "Uploading file " + file.getName(); } mis.setName( monitorSubtaskName ); mis.setLength( (int) file.getContentLength() ); headers.add( "Content-Length", Long.toString( file.getContentLength() ) ); if ( file.getContentType() != null ) { headers.add( "Content-Type", file.getContentType() ); } requestBuilder.setBody( mis ); } handler = new PushAsyncHandler( monitor, "Receiving response" ); // What's this for? (from previous Jetty code) // httpClient.registerListener( "org.eclipse.jetty.client.webdav.WebdavListener" ); requestBuilder.setHeaders( headers ); IOException unknownException = null; Future<String> future = requestBuilder.execute( handler ); try { future.get(); } catch ( InterruptedException e ) { throw new IOException( "Transfer was interrupted" ); } catch ( ExecutionException e ) { /* * Delay throwing this exception, as exceptions from the server get caught here and we don't need to * wrap them up. Handler already knows about them. */ unknownException = (IOException) new IOException().initCause( e ); } Throwable exception = handler.getException(); if ( exception != null ) { if ( exception instanceof IOException ) { throw (IOException) exception; } throw (IOException) new IOException( exception.getMessage() ).initCause( exception ); } if ( unknownException != null ) { throw unknownException; } ServerResponse response = new ServerResponse( handler.getResponseStatus(), handler.getResponseContentBytes(), handler.getEncoding() ); if ( statusException ) { int status = handler.getResponseStatus(); switch ( status ) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_ACCEPTED: case HttpURLConnection.HTTP_NO_CONTENT: break; case HttpURLConnection.HTTP_UNAUTHORIZED: throw new UnauthorizedException( "HTTP status code " + status + ": Unauthorized: " + uri ); case HttpURLConnection.HTTP_FORBIDDEN: throw new ForbiddenException( "HTTP status code " + status + ": Forbidden: " + uri ); case HttpURLConnection.HTTP_NOT_FOUND: throw new NotFoundException( "HTTP status code " + status + ": Not Found: " + uri ); default: throw new TransferException( "HTTP status code " + status + ": " + uri, response, null ); } } return response; } finally { httpClient.close(); } } private final class PushAsyncHandler extends BaseAsyncHandler { private final MonitoredOutputStream mos; private Throwable exception; private ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 ); private int responseStatus; private PushAsyncHandler( IProgressMonitor monitor, String taskName ) { this.mos = new MonitoredOutputStream( baos, monitor ); mos.setName( taskName ); } public byte[] getResponseContentBytes() { return baos.toByteArray(); } public int getResponseStatus() { return responseStatus; } public Throwable getException() { return exception; } @Override public void onThrowable( Throwable t ) { super.onThrowable( t ); error( t ); } @Override public STATE onBodyPartReceived( HttpResponseBodyPart bodyPart ) throws Exception { STATE retval = super.onBodyPartReceived( bodyPart ); bodyPart.writeTo( mos ); return retval; } @Override public STATE onStatusReceived( HttpResponseStatus responseStatus ) throws Exception { this.responseStatus = responseStatus.getStatusCode(); return handleStatus( responseStatus ); } @Override public STATE onHeadersReceived( HttpResponseHeaders headers ) throws Exception { return super.onHeadersReceived( headers ); } @Override public String onCompleted() throws Exception { return ""; } private void error( Throwable e ) { exception = e; } } /* * public int waitForDone( IProgressMonitor monitor, String monitorTaskName ) throws InterruptedException { if ( * monitor == null ) { return waitForDone(); } synchronized ( this ) { boolean monitorStarted = false; int totalWork * = 100; int worked = 0; IProgressMonitor subMonitor = null; while ( !isDone( getStatus() ) ) { this.wait( 100 ); * if ( getStatus() == HttpExchange.STATUS_WAITING_FOR_RESPONSE ) { if ( !monitorStarted ) { worked = 0; * monitorStarted = true; subMonitor = SubMonitor.convert( monitor, monitorTaskName, totalWork ); } worked++; * subMonitor.worked( 1 ); if ( worked == totalWork ) { // Force the monitor progress to restart monitorStarted = * false; } } } } return getStatus(); } */ public ServerResponse postFile( final RequestEntity file, final URI url, final IProgressMonitor monitor, String monitorSubtaskName, final IAuthService authService, final IProxyService proxyService, Integer timeoutInMilliseconds ) throws IOException { return doDataExchange( file, url, monitor, monitorSubtaskName, authService, proxyService, timeoutInMilliseconds, true, "POST" ); } public ServerResponse headFile( final URI url, final IProgressMonitor monitor, String monitorSubtaskName, final IAuthService authService, final IProxyService proxyService, Integer timeoutInMilliseconds ) throws IOException { return doDataExchange( null, url, monitor, monitorSubtaskName, authService, proxyService, timeoutInMilliseconds, false, "HEAD" ); } }
package com.rs.game.player.content; import com.rs.game.World; import com.rs.game.player.Player; import java.util.Random; public class Tips { public static int stringId = -1; private static String strings [] = { "<col=000000><shad=8000FF> Remember: Christmas crackers DO NOT always give the holder the Partyhat.</col>", "<col=000000><shad=8000FF> Slayer is a great way to level up your combat, and earn a few coins.</col>", "<col=000000><shad=8000FF> Please Register on our Forums by typing ::forums, Thank you.</col>", "<col=000000><shad=8000FF> Server Main Owner = Cryptic/wonfa.</col>", "<col=000000><shad=8000FF> Reminder: SpecX V4 always has daily updates!</col>", "<col=000000><shad=8000FF> Abyssal Demon Now Drops ~Lite WEAPONS~ </col>", "<col=000000><shad=8000FF> Mercenay Mage now drops drygore's!</col>", "<col=000000><shad=8000FF> Ice wings & Master Spirit shield coming soon!</col>", "<col=000000><shad=8000FF> Want to have more Events? Invite your friends over NOW!</col>", "<col=000000><shad=8000FF> NEW UPDATE: ALL SKILLS IS NOW 120, MAX CB = 169! </col>", "<col=000000><shad=8000FF> If you may any suggestions about our server, please post them on Forums!</col>", "<col=000000><shad=8000FF> Corporeal Beast is a Un-safe Area - WARNING - </col>", "<col=000000><shad=8000FF> Donate only to Cryptic and no one else! </col>", "<col=000000><shad=8000FF> Drop Party at 20+ Players, Invite your friends over now! </col>", "<col=000000><shad=8000FF> Type ::ticket and wait for our staff members to assist you! </col>", "<col=000000><shad=8000FF> You can help the server by donating for the vps!</col>", "<col=000000><shad=8000FF> The total amount of donations we've made since beginning: $0.00 USD </col>", //"<col=000000><shad=FF0000> PEOPLE WHO AREN'T LOYAL TO ETERNITY-RSPS DON'T DONATE!</col>", "<col=000000><shad=8000FF> SpecX V4 RSPS WE DO NOT DO REFUNDS!/col>", }; public static int Random() { int random = 0; Random rand = new Random(); random = rand.nextInt(strings.length); return random; } public static void Run() { int r = Random(); stringId = r; for (Player p : World.getPlayers()) { if (p == null) continue; if (!p.isTipsOff()) { p.getPackets().sendGameMessage("<img=5><col=000000><shad=8000FF>[Server message]</col>" + strings[r]); } } } }
package creational.design.pattern.singleton.enumThreadSafe; import creational.design.pattern.singleton.enumThreadSafe.Database; public enum DatabaseInstance { INSTANCE; public Database getDatabase() { return this.database; } public void setDatabase(Database database) { this.database = database; } private Database database; }
package primitives; /** * class Vactor is the basic class representing a vector that start from the beginning. * * @author Rina and Tamar * */ public class Vector { /** * Vector values */ Point3D _head; /** * Vector constructor receiving a Vector values by Coordinate * * @param x Coordinate value * @param y Coordinate value * @param z Coordinate value */ // public Vector(Coordinate x, Coordinate y, Coordinate z) // { // _head = new Point3D(x,y,z); // if(_head.equals(Point3D.ZERO)) // { // throw new IllegalArgumentException("Illegal vector zero"); // } // } /** * Vector constructor receiving a Vector values by double * * @param x double value * @param y double value * @param z double value */ public Vector(double x, double y, double z) { _head = new Point3D(x,y,z); if(_head.equals(Point3D.ZERO)) { throw new IllegalArgumentException("Illegal vector zero"); } } /** * Vector constructor receiving a Vector value by Point3D * * @param Point3D value */ public Vector(Point3D head) { if(head.equals(Point3D.ZERO)) { throw new IllegalArgumentException("Illegal vector zero"); } _head = new Point3D(head); } /** * Copy constructor for Vector * * @param Vector value */ public Vector(Vector other) { _head = new Point3D(other._head); } /** * Vector value getter * * @return x Vector value */ public double getX() { return _head.getX(); } /** * Vector value getter * * @return y Vector value */ public double getY() { return _head.getY(); } /** * Vector value getter * * @return z Vector value */ public double getZ() { return _head.getZ(); } /** * Calculate vector subtraction * * @param Vector * @return Vector - result */ public Vector subtract(Vector other) { Vector newV = new Vector(_head); newV = newV._head.subtract(other._head); return newV; } /** * Calculate a vector connection * * @param Vector * @return Vector - result */ public Vector add(Vector other) { Vector newV =new Vector(_head.add(other)); if(newV._head == Point3D.ZERO) throw new IllegalArgumentException("Illegal vector zero"); return newV; } /** * Calculate vector multiplier in scalar * * @param number * @return Vector result */ public Vector scale(double num) { Vector newV = new Vector(new Point3D(_head._x._coord * num,_head._y._coord * num,_head._z._coord * num)); return newV; } /** * Calculate scalar multiplication * * @param Vector * @return number - result */ public double dotProduct(Vector other) { double result = _head._x._coord*other._head._x._coord + _head._y._coord*other._head._y._coord + _head._z._coord*other._head._z._coord; return result; } /** * Calculate a vector multiplication * * @param Vector * @return Vector - result */ public Vector crossProduct(Vector other) { Vector newV = new Vector(new Point3D(_head._y._coord * other._head._z._coord - _head._z._coord * other._head._y._coord,_head._z._coord * other._head._x._coord - _head._x._coord * other._head._z._coord,_head._x._coord * other._head._y._coord - _head._y._coord * other._head._x._coord)); return newV; } /** * Calculate the vector length per second * * @return number - result */ public double lengthSquared() { double temp = _head._x._coord * _head._x._coord + _head._y._coord * _head._y._coord + _head._z._coord * _head._z._coord; return temp; } /** * Calculate the vector length * * @return number - result */ public double length() { return Math.sqrt(lengthSquared()); } /** * Calculate Normalization Vector * * @return Vector - result */ public Vector normalize() { _head = scale(1/length())._head; return this; } public Vector normalized() { Vector newV = new Vector(_head); return newV.normalize(); } /*************** Admin *****************/ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Vector)) return false; Vector temp = (Vector)obj; if(_head.equals(temp._head)) return true; return false; } @Override public String toString() { return "" + _head.toString(); } }
package com.shopify.tracking; import java.util.Date; import lombok.Data; @Data public class TrackingData { private String masterCode; private String[] masterCodeList; private int[] orderIdxList; private int shopIdx; private int orderIdx; private String orderName; private String combineCode; private int selectSender; private String sellerName; private String sellerPhone; private String sellerCountryCode; private String sellerCountry; private String sellerCity; private String sellerProvince; private String sellerZipCode; private String sellerAddr1; private String sellerAddr2; private String sellerAddr1Ename; private String sellerAddr2Ename; private String buyerFirstname; private String buyerLastname; private String buyerPhone; private String buyerEmail; private String buyerCountryCode; private String buyerCountry; private String buyerCity; private String buyerProvince; private String buyerProvinceCode; private String buyerZipCode; private String buyerAddr1; private String buyerAddr2; private int selectBox; private int boxLength; private int boxWidth; private int boxHeight; private String boxUnit; private String boxWeight; private String weightUnit; private double totalWeight; private String totalWeightUnit; private String boxType; private String state; private String stateDate; private String stateStr; private String stateStrCss; private String paymentCode; private String deliveryCompany; private String origin; private float weight; private String weightStr; private String totalPriceCurrency; private String orderCourier; private String sellerPhone01; private String sellerPhone02; private String sellerPhone03; private String sellerPhone04; private String buyerPhone01; private String buyerPhone02; private String buyerPhone03; private String buyerPhone04; private String localCode; private Date regDate; private String regDateStr; private int rankPrice; private int payment; private int paymentVat; private int paymentTotal; private int quantity; private String rankPriceStr; private String paymentStr; private String paymentTotalStr; private String boxSize; private String[] boxSizeList; private String quantityStr; private int deliveryAmount; private String deliveryAmountStr; private String shopName; private String combineYn; private String ckBox; private String userLang; //페이징관련 param private int currentPage; private int startRow; private int pageSize; private int totalPageNum; private int pageBlockSize; //검색관련 param private String searchState; private String searchDateStart; private String searchDateEnd; private String searchType; private String searchWord; private String email; private String goods; private String goodsCode; private String goodsCodeList; private int goodsCnt; private String invoice; private String courier; private String courierStr; private String courierChk; private String courierCompany; private String courierCompanyChk; private String orderCode; private String orderDate; private String payState; private String payMethod; // paypal, bank private String payMethodSetting; // 어드민에서 tb_seller->pay_method 셋팅값: 1 페이팔, 2 무통장, 3: 모두 private String payWeight; private String pickupServiceCode; private String locationId; private String locale; private double orderPrice; private String orderPriceStr; private String customerName; private String consigneeName; private String consigneeTel; private String consigneeCpno; private String consigneeZipcode; private String consigneeAddr1; private String consigneeAddr2; private String shippingLineName; private String shippingLineCode; private String charge_id; private String chargeId; private String id; //이행관련 param private String fulId; private String fulOrderId; private String fulStatus; private String fulTrackingCompany; private String fulTrackingNumber; }
package com.lbsp.promotion.entity.base; import java.util.List; public class BaseInsertAllEntity extends BaseEntity{ private String key; private List<String> values; public BaseInsertAllEntity(String table, String key, List<String> values) { super(table); this.key = key; this.values = values; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public List<String> getValues() { return values; } public void setValues(List<String> values) { this.values = values; } }
package HuaWei; import java.util.Scanner; public class DNA序列字串GC的比率 { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()){ String DNA = in.next(); int length = in.nextInt(); System.out.println(findMaxGC(DNA, length)); } } public static String findMaxGC(String DNA,int length){ int l = DNA.length(); int max =0; int index=0; for (int i = 0; i+length <=l; i++) { String subString = DNA.substring(i,i+length); int count =0; for (int j = 0; j < length; j++) { char thec = subString.charAt(j); if (thec=='G'||thec=='C') { count++; } } if (count>max) { max=count; index=i; } } if (max==0) { return "无GC"; }else { return DNA.substring(index,index+length); } } }
package com.weixin.tool.common; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import java.io.*; import java.net.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.util.Map; /** * http工具类 * Created by White on 2017/2/27. */ public class HttpUtil { private static Logger log = LoggerFactory.getLogger(HttpUtil.class); private final static String REQUEST_GET = "GET"; private final static String REQUEST_POST = "POST"; private final static String CODING_UTF_8 = "UTF-8"; private final static int CONN_TIMEOUT = 30000; private final static int READ_TOMEOUT = 30000; // 获取SSLSocketFactory private static SSLSocketFactory getSSLSocketFactory() { SSLSocketFactory ssf = null; try { // 设置SSLContext SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, new TrustManager[] { new MyX509TrustManager() }, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 ssf = sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return ssf; } // 微信请求调用 public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; try { // 获取SSLSocketFactory SSLSocketFactory ssf = getSSLSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if (REQUEST_GET.equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 当有数据需要提交时 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意编码格式,防止中文乱码 outputStream.write(outputStr.getBytes(CODING_UTF_8)); outputStream.close(); } // 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, CODING_UTF_8); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuffer buffer = new StringBuffer(); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { log.error("Weixin server connection timed out."); } catch (Exception e) { log.error("https request error:{}", e); } return jsonObject; } // 百度翻译 聚合菜谱 第三方API请求调用 // 百度翻译:http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4 // 聚合菜谱:http://apis.juhe.cn/cook/query?key=&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10&pn=3 public static JSONObject httRequestTo3API(String requestUrl, Map<String, String> params, String method) { JSONObject jsonObject = null; try { // 获取SSLSocketFactory SSLSocketFactory ssf = getSSLSocketFactory(); if(method==null || method.equals(REQUEST_GET)){ requestUrl = requestUrl+"?"+urlencode(params); } URL url = new URL(requestUrl); HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); if (httpUrlConn instanceof HttpsURLConnection) { ((HttpsURLConnection) httpUrlConn).setSSLSocketFactory(ssf); } if(method==null || method.equals(REQUEST_GET)){ httpUrlConn.setRequestMethod(REQUEST_GET); }else{ httpUrlConn.setRequestMethod(REQUEST_POST); httpUrlConn.setDoOutput(true); } httpUrlConn.setUseCaches(false); httpUrlConn.setConnectTimeout(CONN_TIMEOUT); httpUrlConn.setReadTimeout(READ_TOMEOUT); httpUrlConn.setInstanceFollowRedirects(false); httpUrlConn.connect(); if (params!= null && method.equals(REQUEST_POST)) { try { DataOutputStream out = new DataOutputStream(httpUrlConn.getOutputStream()); out.writeBytes(urlencode(params)); } catch (Exception e) { // TODO: handle exception } } InputStream is = httpUrlConn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, CODING_UTF_8)); StringBuffer buffer = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { buffer.append(line); } jsonObject = JSONObject.fromObject(buffer.toString()); close(br); // 关闭数据流 close(is); // 关闭数据流 httpUrlConn.disconnect(); // 断开连接 } catch (IOException e) { e.printStackTrace(); } return jsonObject; } // 关闭流封装 protected static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } } // 将map型转为请求参数型 // 例如:a=xxx&b=xxx&... public static String urlencode(Map<String,String> data) { StringBuilder sb = new StringBuilder(); for (Map.Entry i : data.entrySet()) { try { // 将拼接的字符串做UTF-8编码 sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } System.out.println(sb.toString()); return sb.toString(); } }
package itri.io.emulator.parameter; /** * Name of an operation's target file. */ public class FileName { private String unformattedFileName; public FileName(String fileName) { unformattedFileName = fileName; } public String getFileName() { return unformattedFileName; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof FileName) { FileName fn = (FileName) obj; return fn.unformattedFileName.equals(this.unformattedFileName); } return false; } @Override public int hashCode() { return unformattedFileName.hashCode(); } @Override public String toString() { return unformattedFileName; } }
package com.tencent.adas; public class ADASWrapper { static String TAG = "TXADASService"; static { try { System.loadLibrary("kneron_adas_car"); System.loadLibrary("kneron_adas_lane"); System.loadLibrary("TXADASService"); } catch (UnsatisfiedLinkError e) { e.printStackTrace(); } } final int maxResult = 128; CarDistance[] mTempCarDistance = new CarDistance[maxResult]; Lane[] mTempLane = new Lane[maxResult]; public native int init(int width, int height, float side, float upper, float lower); public native int uninit(); public native int carDetectNative(CarDistance[] result, long elapsedRealtimeNanos, byte[] frame); public native int LaneDetectNative(Lane[] result, long elapsedRealtimeNanos, byte[] frame); public CarDistance[] carDetect(long elapsedRealtimeNanos, byte[] frame) { CarDistance[] result = null; int count = carDetectNative(mTempCarDistance, elapsedRealtimeNanos, frame); if (count > 0) { result = new CarDistance[count]; java.lang.System.arraycopy(mTempCarDistance, 0, result, 0, count); } return result; }; public Lane[] LaneDetect(byte[] frame, int bufLen) { Lane[] result = null; int count = LaneDetectNative(mTempLane, 0, frame); if (count > 0) { result = new Lane[count]; java.lang.System.arraycopy(mTempLane, 0, result, 0, count); } return result; } }
package com.ojas.rpo.security.transfer; public class UsersList { public java.util.List<UserListTransfer> getList() { return list; } public void setList(java.util.List<UserListTransfer> list) { this.list = list; } public Integer getTotalPages() { return totalPages; } public void setTotalPages(Integer totalPages) { this.totalPages = totalPages; } public Integer getTotalRecords() { return totalRecords; } public void setTotalRecords(Integer totalRecords) { this.totalRecords = totalRecords; } java.util.List<UserListTransfer> list; Integer totalPages; Integer totalRecords; }
package com.example.zhubangshopingtest1.home.fragment; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.alibaba.fastjson.JSON; import com.example.zhubangshopingtest1.MainActivity; import com.example.zhubangshopingtest1.R; import com.example.zhubangshopingtest1.base.BaseFragment; import com.example.zhubangshopingtest1.home.ErweimaActivity; import com.example.zhubangshopingtest1.home.adater.HomeFragmentAdapter; import com.example.zhubangshopingtest1.home.bean.ResultBeanData; import com.example.zhubangshopingtest1.utils.Constants; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import java.io.IOException; import okhttp3.Call; import okhttp3.Response; public class HomeFragment extends BaseFragment { private static final String TAG = HomeFragment.class.getSimpleName(); private RecyclerView rvHome; private ImageView ib_top; private TextView tv_search_home; private TextView ErWeiMa; private TextView SaoMa; private ResultBeanData.ResultBean resultBean; private HomeFragmentAdapter adapter; @Override public View initView() { Log.e(TAG, "主页视图被初始化了"); View view = View.inflate(mContext, R.layout.fragment_home, null); rvHome = (RecyclerView) view.findViewById(R.id.rv_home); ib_top = (ImageView) view.findViewById(R.id.ib_top); ErWeiMa = (TextView) view.findViewById(R.id.ErWeiMa); tv_search_home = (TextView) view.findViewById(R.id.tv_search_home); SaoMa = (TextView) view.findViewById(R.id.SaoMa); //设置图标点击回到顶部事件 initListener(); return view; } @Override public void initData() { super.initData(); getDataFromNet(); //联网请求数据; } private void getDataFromNet(){ String url = Constants.HOME_URL; // String url = "http://100.64.242.6:8080/zhubang/json/HOME_URL.json"; //数据请求成功; //使用真机测试时,需要连接在同一个网络,并且关闭防火墙 OkHttpUtils .get() .url(url) .build() .execute(new StringCallback() { @Override public String parseNetworkResponse(Response response, int id) throws IOException { return super.parseNetworkResponse(response, id); } /*请求失败时回调*/ @Override public void onError(Call call, Exception e, int id) { Log.e(TAG, "请求错误 "+e.getMessage()); AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); dialog.setTitle("404"); dialog.setMessage("服务器请求失败,请查看网络连接"); dialog.setCancelable(false); //点击屏幕或返回键dialog不消失 dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); dialog.show(); } /*联网成功时回调*/ @Override public void onResponse(String response, int id) { Log.e(TAG, "数据请求成功" ); processData(response); } private void processData(String json) { ResultBeanData resultBeanData = JSON.parseObject(json, ResultBeanData.class); resultBean = resultBeanData.getResult(); //测试解析用的 Log.e(TAG, "解析数据 "+resultBean.getHot_info().get(0).getName() ); if (resultBean != null){ Log.e(TAG, "有数据,进行数据解析中……"); //有数据; //设置适配器; adapter = new HomeFragmentAdapter(mContext ,resultBean); rvHome.setAdapter(adapter); GridLayoutManager manager = new GridLayoutManager(mContext,1); //设置跨度大小的监听,用于回到顶部,当recommend模块显示时,进行显示; manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { ib_top.setVisibility(View.VISIBLE); // if (position <= 2) { // ib_top.setVisibility(View.GONE); // } else { // ib_top.setVisibility(View.VISIBLE); // } //只能返回 1 return 1; } }); //设置布局管理者 rvHome.setLayoutManager(manager); }else { //没有数据,弹出提示; Log.e(TAG, "processData: 没有数据"); } } }); } private void initListener() { //置顶的监听 ib_top.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //回到顶部 rvHome.scrollToPosition(0); } }); //搜素的监听 tv_search_home.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(mContext, "搜索", Toast.LENGTH_SHORT).show(); } }); //二维码的监听 ErWeiMa.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ErweimaActivity.class); startActivity(intent); Toast.makeText(mContext, "弹出二维码", Toast.LENGTH_SHORT).show(); } }); //扫码的监听 SaoMa.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(mContext, "打开相机", Toast.LENGTH_SHORT).show(); } }); } }
import java.util.*; public class JavaCollectionsOne{ public static void main(String[] args){ ArrayList<Integer> firstList = new ArrayList<Integer>(); firstList.add(1); firstList.add(2); firstList.add(3); Iterator iterator = firstList.iterator(); while(iterator.hasNext()){ System.out.print(iterator.next() + " "); } } }
package com.elepy.exceptions; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class ElepyErrorMessage extends RuntimeException { private final String message; private final int status; @JsonCreator public ElepyErrorMessage(@JsonProperty("message") String message, @JsonProperty("status") int status) { super(message); this.message = message; this.status = status; } public ElepyErrorMessage(String message, int status, Throwable cause) { super(message, cause); this.message = message; this.status = status; } @Override public String getMessage() { return message; } public int getStatus() { return status; } }
package com.mrhan.util; import java.util.ArrayList; import java.util.List; public class CodeRuntimeTest { private long time = System.currentTimeMillis(); private static volatile boolean ISHIDDED = false; private static volatile List<String> createObjs = new ArrayList<>(); private static boolean isShowOne = true;//是否显示单行信息 public static boolean isIsShowOne() { return isShowOne; } public static void setIsShowOne(boolean isShowOne) { CodeRuntimeTest.isShowOne = isShowOne; } /** * 创建显示 * * @return */ private static String cratedShow() { Throwable throwable = new Throwable(); StackTraceElement[] trace = throwable.getStackTrace(); // 下标为0的元素是上一行语句的信息, 下标为1的才是调用printLine的地方的信息 StackTraceElement tmp = trace[2]; StringBuilder sb = new StringBuilder(); long t = System.currentTimeMillis(); for (int i = 2; i < trace.length; i++) { tmp = trace[i]; sb.append(tmp.getFileName()).append(".").append(tmp.getMethodName()).append("(").append(tmp.getFileName()).append(":").append(tmp.getLineNumber()).append(") \n\t"); if (isShowOne) { break; } } return sb.toString(); } public CodeRuntimeTest() { createObjs.add(cratedShow()); } // private static /** * 显示时间差,显示当前代码的行数 * * @param msg */ public void showTimeMsg(String msg) { if (ISHIDDED) { return; } Throwable throwable = new Throwable(); StackTraceElement[] trace = throwable.getStackTrace(); // 下标为0的元素是上一行语句的信息, 下标为1的才是调用printLine的地方的信息 StackTraceElement tmp = trace[1]; StringBuilder sb = new StringBuilder(msg); long t = System.currentTimeMillis(); sb.append(cratedShow()); sb.append(" [ ").append((t - time)).append("ms ] "); System.out.println(sb); time = t; } /** * 锁定时间 * * @return */ public long lockTime() { time = System.currentTimeMillis(); return time; } /** * 显示创建当前对象的位置 */ public static void showCreateThisObjPoint() { for (String s : createObjs) System.out.println(s); } public static void show() { ISHIDDED = false; } public static void hidden() { ISHIDDED = true; } public static boolean isState() { return ISHIDDED; } }
package cartas; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import org.junit.jupiter.api.Test; public class Test_Cartas { @Test public void testCartas() { Cartas cartas = new Cartas(); ArrayList<String> listaCartas = cartas.repartidor(4, 3); assertEquals(3, listaCartas.size(), "the carts were not dealed"); } }
package Lesson3.FactoryMethod; public class DevApp { public static void main(String[] args) { DeveloperFactory developerFactory = createDeveloperBySpeciality("java"); Developer developer = developerFactory.cerateDeveloper(); developer.writeCode(); } static DeveloperFactory createDeveloperBySpeciality(String speciality){ if (speciality.equalsIgnoreCase("java")){ return new JavaDeveloperFactory(); } else if (speciality.equalsIgnoreCase("c++")){ return new CppDeveloperFactory(); }else { throw new RuntimeException(speciality + "is unknown speciality."); } } } interface Developer { void writeCode(); } interface DeveloperFactory { Developer cerateDeveloper(); } class JavaDeveloperFactory implements DeveloperFactory{ @Override public Developer cerateDeveloper() { return new JavaDeveloper(); } } class CppDeveloperFactory implements DeveloperFactory{ @Override public Developer cerateDeveloper() { return new CppDeveloper(); } } class JavaDeveloper implements Developer { @Override public void writeCode() { System.out.println("JavaDeveloper writs java code..."); } } class CppDeveloper implements Developer{ @Override public void writeCode() { System.out.println("C++ developer writs c++ code..."); } }
//--------------------------------------------------------------------- // //--------------------------------------------------------------------- public class ExprSTO extends STO { //---------------------------------------------------------------- // //---------------------------------------------------------------- public ExprSTO (String strName) { super (strName); // You may want to change the isModifiable and isAddressable // fields as necessary } public ExprSTO (String strName, Type typ) { super (strName, typ); // You may want to change the isModifiable and isAddressable // fields as necessary } //---------------------------------------------------------------- // //---------------------------------------------------------------- public boolean isExpr () { return true; } public void setUnderName ( String name ) { underName = name; } public String getUnderName () { return this.underName; } private String underName = null; }
package com.example.demo.Bootstrap_Flight; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import com.example.demo.repository_Flights.PassengerRepository; import com.example.demo.repository_Flights.ReservationRepository; import com.example.demo.Model_Flights.Flight; import com.example.demo.Model_Flights.Passenger; import com.example.demo.Model_Flights.Reservation; import com.example.demo.repository_Flights.FlightRepository; @Component public class DevJpaBootStrap implements ApplicationListener<ContextRefreshedEvent> { private PassengerRepository passengerRepository; private FlightRepository flightRepository; private ReservationRepository reservationRepository; public DevJpaBootStrap(PassengerRepository passengerRepository, FlightRepository flightRepository, ReservationRepository reservationRepository) { super(); this.passengerRepository = passengerRepository; this.flightRepository = flightRepository; this.reservationRepository = reservationRepository; } @Override public void onApplicationEvent(ContextRefreshedEvent event) { // TODO Auto-generated method stub init(); } private void init() { // TODO Auto-generated method stub Passenger passenger=new Passenger("Arun","Kumar","Sengal,Karur"); Flight flight=new Flight("Trichy", "Bangalore"); passengerRepository.save(passenger); flightRepository.save(flight); } }
import java.util.*; import java.io.*; import backend.*; import utils.*; public class LoginState extends WareState{ private static final int CLIENT_LOGIN = 0; private static final int CLERK_LOGIN = 1; private static final int MANAGER_LOGIN = 2; private static final int HELP = 3; private static final int EXIT = 4; private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static LoginState instance; private LoginState() { super(); } public static LoginState instance() { if (instance == null) { instance = new LoginState(); } return instance; } public void help() { System.out.println("\nEnter a number between " + CLIENT_LOGIN + " and " + EXIT + " as explained below:"); System.out.println(CLIENT_LOGIN + " to login as a client"); System.out.println(CLERK_LOGIN + " to login as a clerk"); System.out.println(MANAGER_LOGIN + " to login as a manager"); System.out.println("\n" + HELP + " for help"); System.out.println(EXIT + " to exit"); } public int getCommand() { do { try { int value = Integer.parseInt(InputUtils.getToken("Enter command:" )); if (value <= EXIT && value >= CLIENT_LOGIN) { return value; } } catch (NumberFormatException nfe) { System.out.println("Enter a number"); } } while (true); } private void client(){ SecuritySystem ss = new SecuritySystem(); String user = InputUtils.getToken("Please input the client username: "); if (Warehouse.instance().getClientById(user) != null){ String pass = InputUtils.getToken("Please input the client password: "); if (ss.verifyPassword(user, pass)) { (WareContext.instance()).setLogin(WareContext.IsClient); (WareContext.instance()).setUser(user.toString()); (WareContext.instance()).changeState(0); } else { System.out.println("Invalid client password."); } } else { System.out.println("Invalid client username."); } } private void clerk(){ SecuritySystem ss = new SecuritySystem(); String clerk = InputUtils.getToken("Please input the clerk username: "); if (clerk.equals("clerk")) { String pass = InputUtils.getToken("Please input the clerk password: "); if (ss.verifyPassword(clerk, pass)){ (WareContext.instance()).setLogin(WareContext.IsClerk); (WareContext.instance()).setUser("clerk"); (WareContext.instance()).changeState(1); } else { System.out.println("Invalid clerk password."); } } else { System.out.println("Invalid clerk username."); } } private void manager(){ SecuritySystem ss = new SecuritySystem(); String manager = InputUtils.getToken("Please input the manager username: "); if (manager.equals("manager")) { String pass = InputUtils.getToken("Please input the manager password: "); if (ss.verifyPassword(manager, pass)){ (WareContext.instance()).setLogin(WareContext.IsManager); (WareContext.instance()).setUser("manager"); (WareContext.instance()).changeState(2); } else { System.out.println("Invalid manager password."); } } else { System.out.println("Invalid manager username."); } } public void process() { int command; help(); while ((command = getCommand()) != EXIT) { switch (command) { case HELP: help(); break; case CLIENT_LOGIN: client(); break; case CLERK_LOGIN: clerk(); break; case MANAGER_LOGIN: manager(); break; default: System.out.println("Invalid choice"); } help(); } (WareContext.instance()).changeState(3); // exit } public void run() { process(); } }
package codewarsestd; public class StringSort { //https://www.codewars.com/kata/two-to-one/train/java public static String longest(String s1, String s2) { String saida = ""; String top = s1 + s2; for (char i = 'a'; i <= 'z'; i++) { if (top.contains(i + "")) { saida += i; } } return saida; } public static void main(String[] args) { System.out.println(longest("asasdffad", "sdacjuh")); } }
package com.org.review.service; import java.util.List; import java.util.Optional; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.org.review.exception.ReviewNotFoundException; import com.org.review.model.Review; import com.org.review.repository.IReviewRepository; @Component public class ReviewServiceImpl implements IReviewService { @Autowired IReviewRepository reviewRepository; @Override public List<Review> getReviews(int productId) { return reviewRepository.findByProductId(productId); } @Override public void addReview(int productId, Review review) { review.setProductId(productId); reviewRepository.save(review); } @Override @Transactional public void updateReview(Review review, int reviewId) throws ReviewNotFoundException { Optional<Review> reviewInDb = reviewRepository.findById(reviewId); if (!reviewInDb.isPresent()) throw new ReviewNotFoundException(reviewId); review.setId(reviewId); reviewRepository.updateReview(review.getId(), review.getRating(), review.getComments()); } @Override public void deleteReview(int reviewId) throws ReviewNotFoundException { Optional<Review> reviewInDb = reviewRepository.findById(reviewId); if (!reviewInDb.isPresent()) throw new ReviewNotFoundException(reviewId); reviewRepository.deleteById(reviewId); } // @Override // public Review getSpecificReview(int id) throws ReviewNotFoundException { // Optional<Review> reviewInDb = reviewRepository.findById(id); // if (!reviewInDb.isPresent()) // throw new ReviewNotFoundException(id); // System.out.println(reviewInDb.get()); // return reviewInDb.get(); // } }
package com.zitiger.plugin.xdkt.json.action; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.util.PsiTreeUtil; import com.zitiger.plugin.xdkt.javadoc.action.JavadocsGenerateAction; import com.zitiger.plugin.xdkt.json.generator.JsonGenerator; import java.util.List; public class JsonGeneratorFileAction extends AnAction { private static final Logger LOGGER = Logger.getInstance(JavadocsGenerateAction.class); /** * Action performed. * * @param e the Event */ @Override public void actionPerformed(AnActionEvent e) { PsiClass psiClass = getPsiClass(e); if (psiClass != null) { JsonGenerator jsonGenerator = new JsonGenerator(); jsonGenerator.generate(e.getProject(), psiClass); } } private PsiClass getPsiClass(AnActionEvent e) { final PsiFile file = DataKeys.PSI_FILE.getData(e.getDataContext()); DataContext dataContext = e.getDataContext(); final Project project = CommonDataKeys.PROJECT.getData(dataContext); final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext); PsiClass psiClass = null; if (file != null) { psiClass = getPsiClass(file); } if (psiClass == null && project != null && files != null) { psiClass = getPsiClass(files, project); } return psiClass; } private PsiClass getPsiClass(VirtualFile[] files, Project project) { for (VirtualFile virtualFile : files) { if (virtualFile.isDirectory()) { return getPsiClass(virtualFile.getChildren(), project); } else { PsiFile file = convertToPsiFile(virtualFile, project); if (file != null && JavaFileType.INSTANCE.equals(file.getFileType())) { return getPsiClass(file); } } } return null; } private PsiFile convertToPsiFile(VirtualFile file, Project project) { PsiManager manager = PsiManager.getInstance(project); return manager.findFile(file); } @Override public void update(AnActionEvent event) { Presentation presentation = event.getPresentation(); presentation.setEnabled(false); if (getPsiClass(event) != null) { presentation.setEnabled(true); } } /** * Gets the classes. * * @param element the Element * @return the Classes */ private PsiClass getPsiClass(PsiElement element) { List<PsiClass> classElements = PsiTreeUtil.getChildrenOfTypeAsList(element, PsiClass.class); if (classElements.isEmpty()) { return null; } else { return classElements.get(0); } } }
package com.encore.spring.service; import java.sql.SQLException; import com.encore.spring.vo.MemberVO; public interface MemberService { MemberVO loginCheck(MemberVO vo) throws SQLException; void add(MemberVO vo) throws Exception; }
package view; import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class View extends JPanel{ private static final long serialVersionUID = 371809822400072039L; protected JTextArea textArea; private final static String newline = "\n"; private String displayContext = ""; public View() { super(new BorderLayout()); textArea = new JTextArea(20,30); textArea.setEditable(false); JScrollPane scrollPane = new JScrollPane(textArea); add(scrollPane, BorderLayout.CENTER); } public void displayInfo(String newContext){ displayContext = newContext + newline; textArea.append(displayContext); textArea.setCaretPosition(textArea.getDocument().getLength()); } // @Override // public void actionPerformed(ActionEvent e) { // textArea.append(displayContext); // textArea.setCaretPosition(textArea.getDocument().getLength()); // } }
package com.smartcity.commonbase.widget.pagestatus; import android.view.View; /** * Author: YuJunKui * Time:2017/12/15 15:28 * Tips: */ public interface OnNoLoginClickListener { void OnNoLoginClick(View v); }
package com.example.finalproject; public class User { String userid; String catName; String aomtNum; String dateIp; public User() { } public User(String userid, String catName, String aomtNum, String dateIp) { this.userid = userid; this.catName = catName; this.aomtNum = aomtNum; this.dateIp = dateIp; } public String getUserid() { return userid; } public String getCatName() { return catName; } public String getAomtNum() { return aomtNum; } public String getDateIp() { return dateIp; } }
package com.nv95.ficbook; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class GrammarTestActivity extends Activity { private ProgressBar progressBar; private TextView textView; private RadioGroup radioGroup; private Button nextButton; private String question_id; private FbSession session; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.grammar_test); session = new FbSession(this); if (Build.VERSION.SDK_INT>=11)try{this.getActionBar().setDisplayHomeAsUpEnabled(true);}catch (NullPointerException ignored){} progressBar = (ProgressBar) findViewById(R.id.progressBar); textView = (TextView) findViewById(R.id.textView); radioGroup = (RadioGroup) findViewById(R.id.radioGroup); nextButton = (Button) findViewById(R.id.button_next); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { nextButton.setEnabled(true); } }); nextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try{ String aid = (String) findViewById(radioGroup.getCheckedRadioButtonId()).getTag(); new answerTask().execute("answer" ,aid); }catch (Exception e){ } } }); new AlertDialog.Builder(GrammarTestActivity.this) .setCancelable(true) .setPositiveButton("Продолжить", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { new answerTask().execute(); } }) .setNegativeButton("Начать заново",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { new answerTask().execute("answer","","start","start"); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { GrammarTestActivity.this.finish(); } }) .create().show(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } private class answerTask extends AsyncTask<String,Void,JSONObject>{ ProgressDialog pd; private answerTask() { pd = new ProgressDialog(GrammarTestActivity.this); pd.setCancelable(false); pd.setMessage(getString(R.string.str_loading)); } @Override protected JSONObject doInBackground(String... strings) { try { return new JSONObject(session.postAjax("http://mobile.ficbook.net/ajax/grammar_test/test", (strings.length==0?null:strings))); } catch (JSONException e) { return null; } } @Override protected void onPreExecute() { super.onPreExecute(); pd.show(); } @Override protected void onPostExecute(JSONObject jsonObject) { super.onPostExecute(jsonObject); JSONObject t; JSONArray a; RadioButton rb; try { if ((jsonObject==null)){ pd.dismiss(); Toast.makeText(GrammarTestActivity.this,"Невозможно пройти тест", Toast.LENGTH_SHORT).show(); return; } if (!jsonObject.getString("type").equals("new_question")){ pd.dismiss(); String s = jsonObject.getString("type"); if (s.equals("begin")){ new AlertDialog.Builder(GrammarTestActivity.this) .setTitle(R.string.title_grammar_test) .setCancelable(false) .setMessage("Вы можете пройти тест снова через " + jsonObject.getString("retake_after") + " дней.") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { GrammarTestActivity.this.finish(); } }) .setIcon(android.R.drawable.ic_dialog_info) .create().show(); }else if (s.equals("end")){ new AlertDialog.Builder(GrammarTestActivity.this) .setTitle(R.string.title_grammar_test) .setCancelable(false) .setMessage("Тест завершён. Ваш результат: " + jsonObject.getString("result")+"%") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { GrammarTestActivity.this.finish(); } }) .setIcon(android.R.drawable.ic_dialog_info) .create().show(); } return; } t = jsonObject.getJSONObject("question"); textView.setText(t.getString("question")); question_id = t.getString("id"); a = jsonObject.getJSONArray("answers"); radioGroup.removeAllViews(); for (int i=0;i<a.length();i++){ t = a.getJSONObject(i); rb = new RadioButton(GrammarTestActivity.this); rb.setText(t.getString("answer")); rb.setTag(t.getString("id")); radioGroup.addView(rb); } nextButton.setEnabled(false); int c = 0; a = jsonObject.getJSONArray("progress_bar"); for (int i=0;i<a.length();i++){ t = a.getJSONObject(i); if (t.getBoolean("completed")) c++; } progressBar.setProgress(c); } catch (JSONException e) { e.printStackTrace(); } pd.dismiss(); } } }
package com.osce.vo.user.role; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; import java.util.Date; @Setter @Getter @ToString public class PfRoleVo implements Serializable { private static final long serialVersionUID = 3352454116018853943L; private Long roleId; // 角色ID private String code; // 角色编码 private String name; // 角色名称 private String resume; // 角色描述 private int state; // 是否有效(0-有效 1-无效) /** * 角色级别,1最大,依次权限减小 */ private int level; private String operator; // 创建人 private Date gmtCreate; // 创建时间 private boolean checked; // 是否拥有某权限 }
package com.levislv.statistics.fully.navigationbar.view; import android.os.Bundle; import android.view.MenuItem; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentManager; import androidx.viewpager.widget.ViewPager; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.levislv.statistics.R; import com.levislv.statistics.fully.navigationbar.adapter.NavigationBarPagerAdapter; import com.levislv.statistics.fully.navigationbar.view.base.BaseTabFragment; import com.levislv.statisticssdk.plugin.annotation.StatisticsPage; import java.util.List; @StatisticsPage( type = StatisticsPage.Type.ACTIVITY, id = R.layout.activity_navigationbar, name = "导航栏页", data = "{'pageKey0':'pageValue0', 'pageKey01':'pageValue1', 'pageKey02':'pageValue2'}" ) public class NavigationBarActivity extends FragmentActivity { private BottomNavigationView navigationBar; private ViewPager viewPager; private long exitTime; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_navigationbar); navigationBar = findViewById(R.id.navigation_bar); viewPager = findViewById(R.id.view_pager); navigationBar.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.item_member: viewPager.setCurrentItem(0); return true; case R.id.item_message: viewPager.setCurrentItem(1); return true; case R.id.item_feedback: viewPager.setCurrentItem(2); return true; default: break; } return false; } }); NavigationBarPagerAdapter pagerAdapter = new NavigationBarPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(pagerAdapter); viewPager.setOffscreenPageLimit(pagerAdapter.getCount()); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { navigationBar.getMenu().getItem(position).setChecked(true); } @Override public void onPageScrollStateChanged(int state) { } }); } @Override public void onBackPressed() { List<Fragment> fragments = getSupportFragmentManager().getFragments(); Fragment fragment = fragments.get(viewPager.getCurrentItem()); if (fragment instanceof BaseTabFragment) { FragmentManager childFragmentManager = fragment.getChildFragmentManager(); if (childFragmentManager.getBackStackEntryCount() != 0) { childFragmentManager.popBackStack(); return; } } long exitTime = System.currentTimeMillis(); if (exitTime - this.exitTime < 1000L) { super.onBackPressed(); } else { this.exitTime = exitTime; Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show(); } } }
package algebra; public class Algebra { public static void main(String[] args) { // TODO code application logic here ejercicio al=new ejercicio(); al.algebra(); } }
//package sandbox; // //import java.io.File; //import java.io.FileInputStream; //import java.io.FileOutputStream; //import java.io.IOException; //import java.nio.file.Files; //import java.nio.file.Path; //import java.nio.file.Paths; //import java.util.List; //import java.util.zip.ZipEntry; //import java.util.zip.ZipOutputStream; // ///** // * mstodo: Header // * // * @author Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com // * <br> // * Date: 8/1/18 // */ //public class WarBuilder { // // mstodo webapp resources pointed by properties // // public static File build(List<String> classesDirs, List<File> classpathJars) throws IOException { // File war = File.createTempFile("temp-tt-war", ".war"); // mstodo better path // try (FileOutputStream fos = new FileOutputStream(war); // ZipOutputStream out = new ZipOutputStream(fos)) { // // WarBuilder builder = new WarBuilder(out, classesDirs, classpathJars); // builder.build(); // } // System.out.println("built " + war.getAbsolutePath()); // return war; // } // // private final ZipOutputStream output; // private final List<String> classesDirs; // private final List<File> jars; // // private WarBuilder(ZipOutputStream output, List<String> classesDirs, List<File> jars) { // this.output = output; // this.classesDirs = classesDirs; // this.jars = jars; // } // // private void build() { // classesDirs.forEach(this::addClassesToWar); // addWebAppResourcesToWar(); // jars.stream() // .filter(this::notJdkJar) // .forEach(this::addJarToWar); // } // // private boolean notJdkJar(File file) { // // mstodo test it! // return !file.getAbsolutePath().contains(System.getProperty("java.home")); // } // // private void addClassesToWar(String directory) { // File classesDirectory = new File(directory); // if (!classesDirectory.isDirectory()) { // throw new RuntimeException("Invalid classes directory on classpath: " + directory); // } // addClassesToWar(classesDirectory); // } // // private void addWebAppResourcesToWar() { // try { // Path webappPath = Paths.get("src", "main", "webapp"); // if (!webappPath.toFile().exists()) { // return; // } // Files.walk(webappPath) // .forEach(this::addWebappResourceToWar); // } catch (IOException e) { // throw new RuntimeException("Unable to get webapp dir"); // } // } // // private void addJarToWar(File file) { // String jarName = file.getName(); // try { // writeFileToZip(file, "WEB-INF/lib/" + jarName); // mstodo: test on windows // } catch (IOException e) { // throw new RuntimeException("Failed to add jar " + file.getAbsolutePath() + " to war", e); // } // } // // private void addWebappResourceToWar(Path path) { // File file = path.toFile(); // if (file.isFile()) { // try { // String projectDir = Paths.get("src", "main", "webapp").toFile().getAbsolutePath(); // // mstodo test on windows! // // String fileName = file.getAbsolutePath().replace(projectDir, ""); // System.out.println("filename: "+ fileName + ", abs path: " + file.getAbsolutePath() + ", to replace from it: " + Paths.get(".").toFile().getAbsolutePath()); // writeFileToZip(file, fileName); // } catch (IOException e) { // throw new RuntimeException("Unable to add file: " + path.toAbsolutePath() + " from webapp to the war", e); // } // } // } // // private void addClassesToWar(File classesDirectory) { // try { // Files.walk(classesDirectory.toPath()) // .map(Path::toFile) // .filter(File::isFile) // .forEach(file -> addClassToWar(file, classesDirectory)); // } catch (IOException e) { // throw new RuntimeException("Failed to add classes to war", e); // } // } // // private void addClassToWar(File file, File classesDirectory) { // try { // String filePath = file.getAbsolutePath(); // String name = filePath.replaceFirst(classesDirectory.getAbsolutePath(), ""); // name = name.replaceAll("^/", ""); // name = name.replaceAll("^\\\\", ""); // mstodo test it on windows // name = "/WEB-INF/classes/" + name; // writeFileToZip(file, name); // } catch (IOException e) { // throw new RuntimeException("Failed to add file " + file.getAbsolutePath() + " to war", e); // } // } // // private void writeFileToZip(File file, String name) throws IOException { // ZipEntry entry = new ZipEntry(name); // output.putNextEntry(entry); // try (FileInputStream input = new FileInputStream(file)) { // byte[] buffer = new byte[4096]; // int length; // while ((length = input.read(buffer)) >= 0) { // output.write(buffer, 0, length); // } // } // output.closeEntry(); // } //}
package Âå¹È; import java.util.Scanner; public class Âå¹È1055 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String str=sc.next(); String str1=str; str=str.replace("-", ""); int sum=0; for(int i=0;i<str.length()-1;i++) { sum+=Integer.parseInt(String.valueOf(str.charAt(i)))*(i+1); } if(sum%11==10) { if(str1.charAt(str1.length()-1)=='X') { System.out.println("Right"); }else { System.out.println(str1.substring(0, str1.length()-1)+"X"); } }else { if(str1.charAt(str1.length()-1)=='X'||sum%11!=Integer.parseInt(String.valueOf(str.charAt(str.length()-1)))) { System.out.println(str1.substring(0, str1.length()-1)+sum%11); }else { System.out.println("Right"); } } } } }
package hr.fer.tel.tihana; import hr.fer.tel.tihana.R; import java.io.IOException; import java.net.URL; import java.util.Calendar; import java.util.List; import java.util.Locale; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.Intent; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; public class RezervirajMeActivity extends Activity implements OnClickListener { Button bMyAcc, bCenterList, bAboutUs, bSport, bDate, bTime, bSearch; TextView tvSport, tvDate, tvTime, tvLocation, tvTemp; Dialog dialog; MySportDialog myDialog; LocationManager lm; Context con = this; private int mYear, mMonth, mDay, mHour, mMinute; static final boolean useCelsius = true; static final int DATE_DIALOG_ID = 0, TIME_DIALOG_ID = 1, SPORT_DIALOG_ID = 2; String name, towers, city = ""; double lat = 0; double longi = 0; String adresaKorisnika = null; List<String> infoCentra = null; List<String> info = null; String distance = null; int i = 0, j = 0; private void resetSearchData() { SearchData.mjesto = city; SearchData.sport = "n"; setTimeDate(); String monthString, dayString; int a = mMonth + 1; if (a < 10) monthString = "0" + a; else monthString = "" + a; if (mDay < 10) dayString = "0" + mDay; else dayString = "" + mDay; SearchData.datum = "" + mYear + "-" + monthString + "-" + dayString; SearchData.vrijeme = "" + pad(mHour) + ":" + pad(mMinute); SearchData.tipObjekta = "n"; SearchData.centarZaOpceInformacijeString = ""; getForecast(1); tvTime.setText(""); tvDate.setText(new StringBuilder().append(mDay).append(".") .append(mMonth + 1).append(".").append(mYear).append(".")); tvSport.setText("Svi sportovi"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mainscreen); System.setProperty("org.joda.time.DateTimeZone.Provider", "org.joda.time.tz.UTCProvider"); setVariables(); resetSearchData(); setTimeDate(); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // ako se pokrece na telefonu sve zakomentirat /* * city = "Zagreb"; SearchData.setMjesto(city); adresaKorisnika = * "Unska 3 Zagreb"; tvLocation.setText(adresaKorisnika); */ lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, networkLocationListener); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100000, 0, gpsLocationListener); getForecast(1); } // metode za vremensku prognozu public void getForecast(int num) { URL url; String s = null; if (city.equals("")) SearchData.setTipObjekta("n"); else { try { String requestURL = String.format( "http://www.google.com/ig/api?weather=%s", Uri.encode(city)); url = new URL(requestURL.replace(" ", "%20")); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); GoogleWeatherHandler gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); InputSource inStream = new InputSource(url.openStream()); inStream.setEncoding("ISO-8859-1"); xr.parse(inStream); WeatherSet ws = gwh.getWeatherSet(); UpdateWeatherInfo uwi = new UpdateWeatherInfo(); if (num == 1) { s = uwi.updateWeatherInfo(ws.getWeatherForecastConditions() .get(0)); tvTemp.setText(s); } else if (num == 2) { s = uwi.updateWeatherInfo(ws.getWeatherForecastConditions() .get(1)); tvTemp.setText(s); } else if (num == 3) { s = uwi.updateWeatherInfo(ws.getWeatherForecastConditions() .get(2)); tvTemp.setText(s); } else if (num == 4) { s = uwi.updateWeatherInfo(ws.getWeatherForecastConditions() .get(3)); tvTemp.setText(s); } } catch (Exception e) { Log.e("WeatherForecaster", "WeatherQueryError", e); } } } private void getAddress() { Geocoder gcd = new Geocoder(con, Locale.getDefault()); List<Address> addresses = null; try { addresses = gcd.getFromLocation(lat, longi, 1); } catch (IOException e) { e.printStackTrace(); } if (addresses.size() > 0) { adresaKorisnika = addresses.get(0).getAddressLine(0).toString(); city = addresses.get(0).getLocality(); getForecast(1); adresaKorisnika = adresaKorisnika + " " + city; tvLocation.setText(adresaKorisnika); String upitInfo = String .format("http://novo.rezervirajme.hr/mobile/info_o_centru.php?mjesto=%s", Uri.encode(city)); String odgovor1 = (String) Json.GetJSONResponse(upitInfo); infoCentra = JsonImenaCentara.GetInfo(odgovor1); for (int y = 2; y < infoCentra.size(); y += 3) { String pom = infoCentra.get(y).replace(" ", "+"); String upitUdaljenost = String .format("https://maps.googleapis.com/maps/api/distancematrix/json?origins=%s&destinations=%s+%s&mode=driving&language=hr&sensor=true", Uri.encode(adresaKorisnika), Uri.encode(pom), Uri.encode(city)); System.out.println(upitUdaljenost); String odgovor2 = (String) Json.GetJSONResponse(upitUdaljenost); distance = JsonImenaCentara.GetDistance(odgovor2, infoCentra .get(y - 1).toString()); } } } @Override protected void onPause() { super.onPause(); lm.removeUpdates(networkLocationListener); lm.removeUpdates(gpsLocationListener); } @Override protected void onResume() { super.onResume(); resetSearchData(); } @Override protected void onStop() { super.onStop(); lm.removeUpdates(networkLocationListener); lm.removeUpdates(gpsLocationListener); } // metode za date i time dijaloge, stavlja trenutno vrijeme u dijalog private void setTimeDate() { // get vrijeme i datum final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); mHour = c.get(Calendar.HOUR_OF_DAY); mMinute = c.get(Calendar.MINUTE); } private void updateDisplayTime() { final Calendar c = Calendar.getInstance(); int tYear = c.get(Calendar.YEAR); int tMonth = c.get(Calendar.MONTH); int tDay = c.get(Calendar.DAY_OF_MONTH); int tHour = c.get(Calendar.HOUR_OF_DAY); int tMinute = c.get(Calendar.MINUTE); if ((mHour < tHour && mYear == tYear && mMonth == tMonth && mDay == tDay) || (mHour == tHour && mMinute < tMinute && mYear == tYear && mMonth == tMonth && mDay == tDay)) { tvTime.setText("Krivo vrijeme"); bSearch.setVisibility(View.INVISIBLE); } else if ((mYear < tYear) || (mYear == tYear && mMonth < tMonth) || (mYear == tYear && mMonth == tMonth && mDay < tDay)) { tvTime.setText(new StringBuilder().append(pad(mHour)).append(":") .append(pad(mMinute))); bSearch.setVisibility(View.INVISIBLE); } else { tvTime.setText(new StringBuilder().append(pad(mHour)).append(":") .append(pad(mMinute))); bSearch.setVisibility(View.VISIBLE); } } private static String pad(int c) { if (c >= 10) return String.valueOf(c); else return "0" + String.valueOf(c); } private void updateDisplayDate() { final Calendar c = Calendar.getInstance(); int tYear = c.get(Calendar.YEAR); int tMonth = c.get(Calendar.MONTH); int tDay = c.get(Calendar.DAY_OF_MONTH); int tHour = c.get(Calendar.HOUR_OF_DAY); int tMinute = c.get(Calendar.MINUTE); if ((mYear < tYear) || (mYear == tYear && mMonth < tMonth) || (mYear == tYear && mMonth == tMonth && mDay < tDay)) { if (!tvTime.equals("")) { tvTime.setText(new StringBuilder().append(pad(mHour)) .append(":").append(pad(mMinute))); SearchData.setVrijeme(tvTime.getText().toString()); } tvDate.setText("Krivi datum"); bSearch.setVisibility(View.INVISIBLE); } else if ((mYear == tYear && mMonth == tMonth && mDay == tDay && mHour < tHour) || (mYear == tYear && mMonth == tMonth && mDay == tDay && mHour == tHour && mMinute < tMinute)) { tvTime.setText("Krivo vrijeme"); bSearch.setVisibility(View.INVISIBLE); tvDate.setText(new StringBuilder().append(mDay).append(".") .append(mMonth + 1).append(".").append(mYear).append(".")); if (mMonth <= 8) { SearchData.setDatum((new StringBuilder().append(mYear) .append("-").append("0").append(mMonth + 1).append("-") .append(mDay)).toString()); } else { SearchData.setDatum((new StringBuilder().append(mYear) .append("-").append(mMonth + 1).append("-") .append(mDay)).toString()); } // trazi prognozu za današnji datum if ((mMonth + 1) == 11 || (mMonth + 1) == 12 || (mMonth + 1) == 1 || (mMonth + 1) == 2 || (mMonth + 1) == 3) SearchData.setTipObjekta("balon"); else getForecast(1); } else { SearchData.vrijeme = "n"; if (!tvTime.getText().toString().equals("")) { tvTime.setText(new StringBuilder().append(pad(mHour)) .append(":").append(pad(mMinute))); SearchData.setVrijeme(tvTime.getText().toString()); } tvDate.setText(new StringBuilder().append(mDay).append(".") .append(mMonth + 1).append(".").append(mYear).append(".")); if (mMonth <= 8) { SearchData.setDatum((new StringBuilder().append(mYear) .append("-").append("0").append(mMonth + 1).append("-") .append(mDay)).toString()); } else { SearchData.setDatum((new StringBuilder().append(mYear) .append("-").append(mMonth + 1).append("-") .append(mDay)).toString()); } bSearch.setVisibility(View.VISIBLE); // trazi prognozu if ((mMonth + 1) == 11 || (mMonth + 1) == 12 || (mMonth + 1) == 1 || (mMonth + 1) == 2 || (mMonth + 1) == 3) { SearchData.setTipObjekta("balon"); } else { LocalDate fromDate = new LocalDate(); String date = mYear + "-" + (mMonth + 1) + "-" + mDay; DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime lDate = fmt.parseDateTime(date); Days day = Days.daysBetween(fromDate.toDateTimeAtCurrentTime(), lDate); if (fromDate.getYear() == lDate.getYear() && fromDate.getMonthOfYear() == lDate.getMonthOfYear() && fromDate.getDayOfMonth() == lDate.getDayOfMonth()) { getForecast(1); if (tvTime.getText().toString().equals("")) SearchData.vrijeme = "" + pad(mHour) + ":" + pad(mMinute); } else if (day.toString().equals("P0D")) { getForecast(2); } else if (day.toString().equals("P1D")) { getForecast(3); } else if (day.toString().equals("P2D")) { getForecast(4); } else { tvTemp.setText(""); SearchData.setTipObjekta("n"); } } } } private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { if (minute == 0) { mMinute = 00; mHour = hourOfDay; } else { mMinute = 00; mHour = hourOfDay + 1; } tvTime.setVisibility(View.VISIBLE); updateDisplayTime(); SearchData.setVrijeme(tvTime.getText().toString()); } }; private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; updateDisplayDate(); } }; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); case TIME_DIALOG_ID: return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, true); } return null; } // inicijalizacija varijabli private void setVariables() { bMyAcc = (Button) findViewById(R.id.bMyAcc); bCenterList = (Button) findViewById(R.id.bList); bAboutUs = (Button) findViewById(R.id.bAboutUs); bSport = (Button) findViewById(R.id.bSport); bDate = (Button) findViewById(R.id.bDate); bTime = (Button) findViewById(R.id.bTime); tvSport = (TextView) findViewById(R.id.tvSport); tvDate = (TextView) findViewById(R.id.tvDate); tvTime = (TextView) findViewById(R.id.tvTime); bSearch = (Button) findViewById(R.id.bSearch); tvLocation = (TextView) findViewById(R.id.tvLocation); tvTemp = (TextView) findViewById(R.id.tvTemp); bMyAcc.setOnClickListener(this); bSearch.setOnClickListener(this); bCenterList.setOnClickListener(this); bAboutUs.setOnClickListener(this); myDialog = new MySportDialog(this, "", new OnReadyListener()); bDate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(DATE_DIALOG_ID); } }); bTime.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(TIME_DIALOG_ID); } }); bSport.setOnClickListener(new OnClickListener() { public void onClick(View v) { myDialog.show(); } }); } // onClick za tri gumba izbornika + Search public void onClick(View v) { switch (v.getId()) { case R.id.bList: Intent openListOfCenters = new Intent( "android.intent.action.POPISCENTARA"); startActivity(openListOfCenters); break; case R.id.bAboutUs: Intent openAboutUs = new Intent("android.intent.action.ONAMA"); startActivity(openAboutUs); break; case R.id.bMyAcc: Intent openMyAcc = new Intent( "android.intent.action.POPISREZERVACIJA"); startActivity(openMyAcc); break; case R.id.bSearch: Intent openPrikazPonude = new Intent( "android.intent.action.PRIKAZPONUDE"); startActivity(openPrikazPonude); break; } } // metoda za SportDialog private class OnReadyListener implements MySportDialog.ReadyListener { public void ready(String name) { tvSport.setText(name); bSearch.setVisibility(View.VISIBLE); } } private final LocationListener gpsLocationListener = new LocationListener() { // METODE ZA LOKACIJU public void onLocationChanged(Location location) { lm.removeUpdates(gpsLocationListener); lat = location.getLatitude(); longi = location.getLongitude(); getAddress(); if (i == 0) { SearchData.setMjesto(city); i++; } } public void onProviderDisabled(String provider) { Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show(); } public void onProviderEnabled(String provider) { Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show(); } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }; private final LocationListener networkLocationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { Toast.makeText(getApplicationContext(), "Network Provider Enabled", Toast.LENGTH_SHORT).show(); } @Override public void onProviderDisabled(String provider) { Toast.makeText(getApplicationContext(), "Network Provider Disabled", Toast.LENGTH_SHORT).show(); } @Override public void onLocationChanged(Location location) { lat = location.getLatitude(); longi = location.getLongitude(); getAddress(); if (i == 0) { SearchData.setMjesto(city); i++; } } }; }
package com.ibm.ive.tools.japt.reduction.xta; import com.ibm.ive.tools.japt.reduction.ClassSet; import com.ibm.ive.tools.japt.reduction.SimpleTreeSet; import com.ibm.ive.tools.japt.reduction.ClassSet.ClassIterator; import com.ibm.jikesbt.BT_Class; import com.ibm.jikesbt.BT_ClassVector; import com.ibm.jikesbt.BT_HashedClassVector; /** * @author sfoley * * A throwing propagator is a special kind of propagator. Those objects propagated, which have been "thrown", are never * accessible to the method in question. Instread the method is used as a conduit to other methods. * <p> * Consider it as follows: <br> * If there are three propagators: a, b,c<b> * a propagates to b which propagates to c, and c throws an object o, * then that object o might land in a, with b acting as the throwing propagator from c to a, * although the object o is never actually propagated in the normal sense, making itself accessible to b. * */ abstract class ThrowingPropagator extends Propagator { private BT_ClassVector propagatedThrownObjects; private SimpleTreeSet allPropagatedThrownObjects; private static final short requiresThrowingRepropagation = 0x10; public ThrowingPropagator(Clazz declaringClass) { super(declaringClass); } public ThrowingPropagator(Clazz declaringClass, BT_HashedClassVector propagatedObjects, ClassSet allPropagatedObjects) { super(declaringClass, propagatedObjects, allPropagatedObjects); } public String getState() { return super.getState() + "New thrown objects to pass: " + + ((propagatedThrownObjects == null) ? 0 : propagatedThrownObjects.size()) + ((propagatedThrownObjects == null) ? "\n" : ":\n" + getListMembers(propagatedThrownObjects) + '\n') + "Thrown objects previously passed: " + ((allPropagatedThrownObjects == null) ? 0 : allPropagatedThrownObjects.size()) + "\n" ; } void scheduleThrowingRepropagation() { flags |= requiresThrowingRepropagation; } protected void addThrownPropagatedObject(BT_Class objectType) { //trace("adding thrown " + objectType); if(propagatedThrownObjects == null) { propagatedThrownObjects = new BT_ClassVector(); //BT_HashedClassVector? propagatedThrownObjects.addElement(objectType); return; } propagatedThrownObjects.addUnique(objectType); } boolean isThrownPropagated(BT_Class objectType) { return allPropagatedThrownObjects != null && allPropagatedThrownObjects.contains(objectType); } boolean hasThrownPropagated() { return allPropagatedThrownObjects != null && !allPropagatedThrownObjects.isEmpty(); } abstract void propagateThrownObjectToAllTargets(BT_Class objectType); abstract void propagateThrownObjectToNewTargets(BT_Class objectType); /* * Overriding methods: */ protected void propagateObjects() { super.propagateObjects(); if(propagatedThrownObjects == null) { return; } if(allPropagatedThrownObjects == null) { allPropagatedThrownObjects = new SimpleTreeSet(); } for(int i=0; i<propagatedThrownObjects.size(); i++) { BT_Class propagatedObject = propagatedThrownObjects.elementAt(i); propagateThrownObjectToAllTargets(propagatedObject); allPropagatedThrownObjects.add(propagatedObject); } propagatedThrownObjects.removeAllElements(); } protected void repropagateObjects() { if(super.requiresRepropagation()) { super.repropagateObjects(); } if((flags & requiresThrowingRepropagation) != 0) { ClassIterator it = allPropagatedThrownObjects.iterator(); while(it.hasNext()) { BT_Class object = it.next(); propagateThrownObjectToNewTargets(object); } flags &= ~requiresThrowingRepropagation; } } protected boolean requiresRepropagation() { return ((flags & requiresThrowingRepropagation) != 0) || super.requiresRepropagation(); } protected boolean somethingNewToPropagate() { return super.somethingNewToPropagate() || (propagatedThrownObjects != null && propagatedThrownObjects.size() > 0); } }
package GUI.AdminView; import Interface.OperationGUIFactory; import Interface.OperationGUIInterface; import Interface.RecyclingStation; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class StationUserInterface extends JFrame implements ActionListener { OperationGUIFactory guiFactory = new OperationGUIFactory(); String operations[] = {"Select Operation", "Add/Edit RCM", "Track RCM Status", "Update RCM", "View Statistics", "Remove RCM", "Empty RCM", "Activate RCM", "Deactivate RCM"}; final JComboBox operationMenu = new JComboBox(operations); RecyclingStation recyclingStation; JPanel displayPanel; JPanel selectedPanel = new JPanel(); private Container container; public StationUserInterface(RecyclingStation recyclingStation) { this.recyclingStation = recyclingStation; setContainer(); getDisplayPanel(); setOperationPanel(); } private void setOperationPanel() { displayPanel.setPreferredSize(new Dimension(150, 150)); container.add(displayPanel, BorderLayout.CENTER); setVisible(true); operationMenu.addActionListener(e -> { String data = "" + operationMenu.getItemAt(operationMenu.getSelectedIndex()); performOperation(data); }); } private void setContainer() { setForeground(Color.CYAN); setFont(new Font("Dialog", Font.ROMAN_BASELINE, 15)); setTitle("Eco Recycle System (Admin View)"); setPreferredSize(new Dimension(700, 500)); container = getContentPane(); container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); } void performOperation(String selectedOperation) { if (selectedOperation.equalsIgnoreCase("Select Operation")) { selectedPanel.removeAll(); selectedPanel.repaint(); } else { selectedPanel.removeAll(); selectedPanel.setVisible(false); OperationGUIInterface operationUI = guiFactory.createUserInterface(selectedOperation, recyclingStation); selectedPanel = operationUI.getPanel(); container.add(selectedPanel); selectedPanel.revalidate(); selectedPanel.repaint(); selectedPanel.setVisible(true); pack(); setLocationRelativeTo(null); } } private void getDisplayPanel() { displayPanel = new JPanel(); JLabel header = new JLabel("<html>Welcome to Recycling Station!<br/>Please select an option to proceed<br/></html>", SwingConstants.CENTER); header.setIcon(null); header.setForeground(Color.pink); header.setFont(new Font("Serif", Font.PLAIN, 25)); operationMenu.setBounds(50, 100, 100, 25); displayPanel.add(header); displayPanel.setBorder(BorderFactory.createLineBorder(Color.gray)); displayPanel.add(operationMenu); pack(); setLocationRelativeTo(null); } @Override public void actionPerformed(ActionEvent e) { String data = "" + operationMenu.getItemAt(operationMenu.getSelectedIndex()); performOperation(data); } }
package it.unical.asd.group6.computerSparePartsCompany.controller; import it.unical.asd.group6.computerSparePartsCompany.core.services.implemented.CustomerServiceImpl; import it.unical.asd.group6.computerSparePartsCompany.core.services.implemented.ReviewServiceImpl; import it.unical.asd.group6.computerSparePartsCompany.data.dto.ReviewDTO; import it.unical.asd.group6.computerSparePartsCompany.data.entities.Customer; import it.unical.asd.group6.computerSparePartsCompany.data.entities.Review; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/review") @CrossOrigin(origins = "*", allowedHeaders = "*") public class ReviewController { @Autowired private ReviewServiceImpl reviewService; @Autowired private CustomerServiceImpl customerService; @GetMapping("/prova") public ResponseEntity<Boolean>stampa() { return ResponseEntity.ok(true); } @GetMapping("/byText") public ResponseEntity<Review>get(@RequestParam String text) { Review r = reviewService.getByTesto(text); return ResponseEntity.ok(r); } @GetMapping("/all") public ResponseEntity<List<ReviewDTO>>getAll() { return ResponseEntity.ok(reviewService.getAll()); } @GetMapping("/all-by-customer") public ResponseEntity<List<ReviewDTO>>getAllByCustomer(@RequestParam String username) { return ResponseEntity.ok(reviewService.getAllByCustomer(customerService.getCustomerEntityByUsername(username).get())); } @GetMapping("/all-by-brand-and-model") public ResponseEntity<List<ReviewDTO>>getAllByCustomer(@RequestParam String brand,@RequestParam String model) { return ResponseEntity.ok(reviewService.getAllByBrandAndModel(brand,model)); } @DeleteMapping("/delete") public ResponseEntity<Boolean>delete(@RequestParam String username,@RequestParam String title,@RequestParam String text,@RequestParam String brand,@RequestParam String model) { /*questo perchè non possono esistere due recensioni dello stesso utente che abbiamo stesso titolo e testo per uno stesso prodotto*/ /*questo deve essere completato*/ Customer c = customerService.getCustomerEntityByUsername(username).get(); Optional<Review> r = reviewService.getAllByCustomerAndTitleAndTextAndBrandAndModel(c,title,text,brand,model); if(r.isPresent()) { reviewService.delete(r.get()); return ResponseEntity.ok(true); } return ResponseEntity.ok(false); } @GetMapping("/by-brand-and-model") public ResponseEntity<List<ReviewDTO>> getAllByBrandAndModel(@RequestParam String brand,@RequestParam String model) { return ResponseEntity.ok(reviewService.getAllByBrandAndModel(brand,model)); } @PostMapping("/add") //** c public ResponseEntity<Boolean> add(@RequestParam String username, @RequestParam String password, @RequestParam String brand, @RequestParam String model, @RequestParam String title, @RequestParam String text,@RequestParam String rate) { if(!customerService.checkLogin(username,password)) { throw new ResponseStatusException(HttpStatus.FORBIDDEN); } /*un utente u non può aggiungere due recensioni allo stesso prodotto*/ /*il concetto di recensione si estende alla descrizione totale di tutti gli acquisti e non di un singolo*/ Customer c = customerService.getCustomerEntityByUsername(username).get(); /*esiste sicuramente*/ /*se non esiste gia una recensione per quel prodotto allora */ Optional<Review> r = reviewService.getByCustomerAndBrandAndModel(c,brand,model); if(r.isPresent()) return ResponseEntity.ok(false); /*ha gia messo una recensione per quel prodotto*/ else { Review review = new Review(); review.setBrand(brand); review.setCustomer(c); review.setModel(model); review.setTitle(title); review.setText(text); review.setRate(Long.parseLong(rate)); reviewService.addReview(review); } return ResponseEntity.ok(true); } @DeleteMapping("/delete-all") public ResponseEntity<Boolean> deleteAll() { List<Review> reviews = reviewService.getAllAsEntity(); for(int i = 0; i<reviews.size(); i++) { reviewService.delete(reviews.get(i)); } return ResponseEntity.ok(true); } @GetMapping("/all-by-filters") public ResponseEntity<List<ReviewDTO>>getByFilters(@RequestParam(required = false)String username,@RequestParam(required = false)String rate,@RequestParam String brand,@RequestParam String model) { Long r = null; if(rate != null) r = Long.parseLong(rate); return ResponseEntity.ok(reviewService.findByFilters(username,r,brand,model)); } }
package com.mindviewinc.chapter11.exercise; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import net.mindview.util.TextFile; public class Ex22 { public static void main(String[] args) { List<String> words = new ArrayList<String>(); Set<Word> set = null; words.addAll(new TextFile( "src/com/mindviewinc/chapter11/sample/collection/SetOperations.java", "\\W+")); Collections.sort(words, String.CASE_INSENSITIVE_ORDER); set = countWords(words); } private static Set countWords(List<String> words) { Set<Word> set = new TreeSet<Word>(); Map<String, Integer> map = new LinkedHashMap<String, Integer>(); for (String word : words) { if (map.containsKey(word)) { map.put(word, map.get(word) != null ? map.get(word) + 1 : 1); } } return null; } } class Word{ private String wordName; private int wordCount; public Word(){ } public Word(String wordName, int wordCount) { this.wordName = wordName; this.wordCount = wordCount; } }
import java.util.Scanner; import java.util.Arrays; public class Campionato{ private Squadra[] sqd_Campionato; private ArrayMultiCapacitivo classificaCampionato; // Costruttori public Campionato(int totale_Squadre){ sqd_Campionato = new Squadra[totale_Squadre]; classificaCampionato = new ArrayMultiCapacitivo(totale_Squadre); } public void setCampionato(){ for(int i=0; i<sqd_Campionato.length; i++){ Scanner in = new Scanner(System.in); System.out.println("Inserisci il nome della squadra: "); String s = in.nextLine(); sqd_Campionato[i] = new Squadra(s, 0, 0); } /* Inizializza array avversari delle varie squadre lunghezza array = sqd_Campionato.length - 1; avversari tutti tranne la squadra per cui l'inizializzo !! DA CONTROLLARE CHE RISPETTA I PUNTI SOPRA CITATI !! */ int cont = 0; for(int i=0; i<sqd_Campionato.length; i++){ String[] strTemp = new String[sqd_Campionato.length-1]; Squadra varTemp = sqd_Campionato[cont]; sqd_Campionato[cont] = sqd_Campionato[0]; sqd_Campionato[0] = sqd_Campionato[cont]; for(int j=1; j < sqd_Campionato.length; j++) {strTemp[j-1] = sqd_Campionato[j].getString();} sqd_Campionato[cont].setDifferenzaCanestri(strTemp.length, strTemp); } for(int i = 0; i < sqd_Campionato.length; i++){ classificaStagione.setElement(i,sqd_Campionato[i].get_Pnt_Classifica(),sqd_Campionato[i].getString()); } } // Metodi privati /* Ritorna il valore piu` grande di interi tra i due passati Utilizzo per trovare la differenza di punti in classifica, differenza canestri e la differenza di punti segnati in campionato tra due squadre. */ private static int confrontoMaggiore(int n1, int n2){ if(n1 > n2) {return n1;} else {return n2;} } private static void ordineArrayInteri(int[] interi){ int[] n = new int[interi.length]; n = Arrays.sort(interi); for(int i=0; i<interi.length; i++){ for(int j=n.length; i>0; i--) {interi[i] = n[j];} } } // Metodi ausiliari public int get_Num_Squadre(){ return sqd_Campionato.length; } //Ritorna una squadra in base al nome entrante // input: String "un nome di una squadra" public Squadra get_Squadra(String una_Squadra){ int i = 0; for( ; i<sqd_Campionato.length; i++){ if(sqd_Campionato[i].getString().equals(una_Squadra)) {break;} } return sqd_Campionato[i]; } public String getString(){ String s = ""; for(int i=0; i<sqd_Campionato.length; i++){ s = sqd_Campionato[i].getString() + "\n"; System.out.print(s); } return s; } // Creare un metodo di ordinamento a valori crescenti /* Metodo di ordinameto: 1^ confronto dei valori di punti in classifica (se pari:) 2^ confronto della differenza punti (dalla fase di ritorno in poi) 3^ confronto dei punti segnati 4^ confronto dei punti subiti (chi ne ha subiti meno sale) break */ //private boh.... /* Funzione da utilizzare quando viene inserito il risulato di una partita giocata cosi si aggiorna automaticamente la classifica. */ public void aggiornaCampionato(Squadra unaSquadra){ int i = 0; int indice = 0; for( ; i<sqd_Campionato.length; i++){ if(classificaCampionato.getArrayString()[i].equals(unaSquadra)) {indice = i;} } classificaCampionato.setElementInt(indice, unaSquadra.get_Pnt_Classifica()); } }
import java.util.ArrayList; public class cart { static int totalValue; static ArrayList<book> cart1; public cart() { cart1=new ArrayList<book>(); totalValue=0; //cart cart1=new cart(A); } public int getProductCount() { return cart1.size(); } public static void addBook(book myBook) { cart1.add(myBook); totalValue=0; for(int i=0;i<cart1.size();i++) { totalValue+=(cart1.get(i).price *cart1.get(i).quantity); } } }
package commands; import exceptions.DukeException; import processor.DukeProcessor; import tasks.Task; import java.util.List; /** * Finds a task using the keyword entered. */ public class CommandFind implements Command { /** * Finds a task in the list using the keyword entered as input. * * @param processor The instantiated DukeProcessor object. * @param args The arguments as entered by the user. */ public String execute(DukeProcessor processor, String args) throws DukeException { String[] argsArray = args.split(" ", 2); String searchString = argsArray[1]; List<Task> tasksList = processor.getTaskList().getTasksContaining(searchString); String tasksListString = ""; for (Task task : tasksList) { tasksListString += task.toString() + "\n"; } String output = String.format("%s\n%s\n", String.format("We've found the following tasks related to your " + "search (\"%s\"):", searchString), tasksListString); return output; } }
package com.emily.framework.quartz.config; import org.springframework.context.annotation.ConditionContext; import org.springframework.context.annotation.ConfigurationCondition; import org.springframework.core.type.AnnotatedTypeMetadata; /** * @program: spring-parent * @description: * @create: 2020/09/30 */ public class EmilyCondition implements ConfigurationCondition { @Override public ConfigurationPhase getConfigurationPhase() { return ConfigurationPhase.PARSE_CONFIGURATION; } @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { boolean containBeanA = context.getBeanFactory().containsBean("beanA"); return containBeanA; } }
import ij.IJ; import ij.ImagePlus; import ij.plugin.filter.PlugInFilter; import ij.process.*; import java.awt.*; import lj.LJPrefs; /** License Statement * Copyright 2016 Lasse Wollatz * * 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. **/ /*** Fill_Holes_Manual_3D * fills holes in a mask. * * - Select a mask * - Use Fill 3D tool to fill in the outside in gray * - The function will then set all black voxel to white and * all gray voxel to black * * @author Lasse Wollatz * * @see <a href="http://imagej.net/Flood_Fill(3D)">Flood_Fill(3D)</a> ***/ public class Fill_Holes_Manual_3D implements PlugInFilter { /** plugin's name **/ public static final String PLUGIN_NAME = LJPrefs.PLUGIN_NAME; /** plugin's current version **/ public static final String PLUGIN_VERSION = LJPrefs.VERSION; //public static final String IMPLEMENTATION_VERSION = LungJ_.class.getPackage().getImplementationVersion(); private boolean previewing = false; private FloatProcessor previewEdm; private double globMin = 0; private double globMax = 1; /** defines what type of images this filter can be applied to **/ private int flags = DOES_8G|DOES_16|DOES_32|DOES_STACKS|PARALLELIZE_STACKS|FINAL_PROCESSING; //KEEP_PREVIEW /*** setup * * @param arg String * @param imp ImagePlus * * @return int * * @see LJPrefs#getMinMax ***/ public int setup(String arg, ImagePlus imp) { /** generate error message for older versions: **/ if (IJ.versionLessThan("1.48n")) return DONE; if (imp == null){ return DONE; } if (arg == "final"){ }else{ float[] minmax = new float[2]; minmax = LJPrefs.getMinMax(imp); globMin = (double)minmax[0]; globMax = (double)minmax[1]; } return flags; } /*** run * * @param ip ImageProcessor ***/ public void run(ImageProcessor ip) { FloatProcessor floatIP; int width = ip.getWidth(); int height = ip.getHeight(); if (previewing && previewEdm!=null) { floatIP = previewEdm; } else { floatIP = new FloatProcessor(width, height, (float[])ip.convertToFloat().getPixels()); //if (floatIP==null) return; //interrupted during preview? previewEdm = floatIP; } float[] fPixels = (float[])floatIP.getPixels(); Rectangle roiRect = ip.getRoi(); if (ip.getBitDepth() == 8) { byte[] bPixels = (byte[])ip.getPixels(); for (int y=roiRect.y; y<roiRect.y+roiRect.height; y++) for (int x=roiRect.x, p=x+y*width; x<roiRect.x+roiRect.width; x++,p++) if (fPixels[p] == (float)255) bPixels[p] = (byte)255; else if(fPixels[p] == (float)0) bPixels[p] = (byte)255; else bPixels[p] = (byte)0; }else if (ip.getBitDepth() == 16) { short[] bPixels = (short[])ip.getPixels(); double tmin = globMin; double tmax = globMax; for (int y=roiRect.y; y<roiRect.y+roiRect.height; y++) for (int x=roiRect.x, p=x+y*width; x<roiRect.x+roiRect.width; x++,p++) if (fPixels[p] == (float)tmax) bPixels[p] = (short)tmax; else if (fPixels[p] == (float)tmin) bPixels[p] = (short)tmax; else bPixels[p] = (short)tmin; }else if (ip.getBitDepth() == 32) { float[] bPixels = (float[])ip.getPixels(); double tmin = globMin; double tmax = globMax; for (int y=roiRect.y; y<roiRect.y+roiRect.height; y++) for (int x=roiRect.x, p=x+y*width; x<roiRect.x+roiRect.width; x++,p++) if (fPixels[p] == (float)tmax) bPixels[p] = (float)tmax; else if (fPixels[p] == (float)tmin) bPixels[p] = (float)tmax; else bPixels[p] = (float)tmin; } return; } /*** setNPasses * This method is called by ImageJ to set the number of calls to * run(ip) corresponding to 100% of the progress bar. No progress bar * here. * * @param nPasses int ***/ public void setNPasses(int nPasses) { } }
package com.example.serpentcs.room_sample.entity; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; /** * Created by serpentcs on 30/12/17. */ @Entity(tableName = "details") public class Details { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(name = "name") private String name; @ColumnInfo(name = "emailOrUsername") private String username; @ColumnInfo(name = "password") private String password; public Details(String name, String username, String password) { this.name = name; this.username = username; this.password = password; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package com.epam.rymasheuski.userCatalogue.web; import java.util.List; import org.springframework.data.crossstore.ChangeSetPersister.NotFoundException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.epam.rymasheuski.userCatalogue.domain.User; import com.epam.rymasheuski.userCatalogue.services.UsersService; @RestController @RequestMapping("/rest/users") public class UsersController { private UsersService usersService; public UsersController(UsersService usersService) { this.usersService = usersService; } @GetMapping @ResponseStatus(HttpStatus.OK) public List<User> findAll() { return usersService.findAll(); } @GetMapping("/{id}") @ResponseStatus(HttpStatus.OK) public User find(@PathVariable int id) { return usersService.findById(id); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public int create(@RequestBody User user) { return usersService.save(user); } @PutMapping("/{id}") @ResponseStatus(HttpStatus.OK) public int updateAgent(@RequestBody User user, @PathVariable int id) throws NotFoundException { return usersService.update(id, user); } }
package com.links.gaurav.lnotes; /** * Created by Gaurav on 1/3/2018. */ import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.bitmap.CenterCrop; import com.bumptech.glide.request.RequestOptions; import com.woxthebox.draglistview.DragItemAdapter; import java.util.ArrayList; import data.entry; class ItemAdapter extends DragItemAdapter<entry, ItemAdapter.ViewHolder> { private int mLayoutId; private int mGrabHandleId; private boolean mDragOnLongPress; public boolean mIsMultiSelect=false; private Context mContext; private entry data[]; private Dbhandler dbhandler; ItemAdapter(ArrayList< entry> list, int layoutId, int grabHandleId, boolean dragOnLongPress, Context context) { mLayoutId = layoutId; mGrabHandleId = grabHandleId; mDragOnLongPress = dragOnLongPress; mContext=context; dbhandler=new Dbhandler(mContext,null,null,1); refreshData(); setItemList(list); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(mLayoutId, parent, false); return new ViewHolder(view); } public void refreshData(){ data=new entry[dbhandler.rCount()]; for(int i=0;i<dbhandler.rCount();i++) data[i]=dbhandler.getresult(i); } @Override public void onBindViewHolder(ViewHolder holder, int position) { super.onBindViewHolder(holder, position); if(mContext.getClass()==MainActivity.class){ holder.mTextView.setText(data[holder.getAdapterPosition()].getName()); holder.mDateTime.setText(data[holder.getAdapterPosition()].getDateTime()); holder.mPages.setText("Pages: "+data[holder.getAdapterPosition()].get_sc().length); Glide.with(mContext).load(data[holder.getAdapterPosition()].get_sc()[0]).apply(RequestOptions.bitmapTransform(new CenterCrop())).into(holder.mImageView); }else { holder.mDateTime.setText(mItemList.get(position).getDateTime()); holder.mPages.setText("Pages: "+mItemList.get(holder.getAdapterPosition()).get_sc().length); holder.mTextView.setText(mItemList.get(position).getName()); Glide.with(mContext).load(mItemList.get(holder.getAdapterPosition()).get_sc()[0]).apply(RequestOptions.bitmapTransform(new CenterCrop())).into(holder.mImageView); }holder.itemView.setTag(mItemList.get(position)); if(mIsMultiSelect) { holder.mGrabHandle.setVisibility(View.GONE); holder.checkBox.setVisibility(View.VISIBLE); if(((MainActivity) mContext).multiSelectList.contains(holder.getAdapterPosition())) holder.checkBox.setChecked(true); else holder.checkBox.setChecked(false); }else { holder.mGrabHandle.setVisibility(View.VISIBLE); holder.checkBox.setVisibility(View.GONE); } } @Override public long getUniqueItemId(int position) { return mItemList.get(position).get_id(); } class ViewHolder extends DragItemAdapter.ViewHolder { ImageView mImageView,mGrabHandle; TextView mTextView,mDateTime,mPages; CheckBox checkBox; ViewHolder(final View itemView) { super(itemView, mGrabHandleId, mDragOnLongPress); /*if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) itemView.findViewById(R.id.item_layout).setForeground(mContext.getDrawable(R.drawable.shadow_item)); else itemView.findViewById(R.id.dragView_listView).setVisibility(View.VISIBLE);*/ if(mContext.getClass()==ScanForEntries.class) itemView.findViewById(mGrabHandleId).setVisibility(View.GONE); checkBox=itemView.findViewById(R.id.multiSelectcheckBox); mTextView=(TextView)itemView.findViewById(R.id.text_listItem); mDateTime=itemView.findViewById(R.id.dateTime_listItem); mPages=itemView.findViewById(R.id.pages_listItem); mGrabHandle=itemView.findViewById(mGrabHandleId); mImageView = (ImageView) itemView.findViewById(R.id.imageView_listItem); if(!mIsMultiSelect) checkBox.setVisibility(View.GONE); int width = Resources.getSystem().getDisplayMetrics().widthPixels; int height= Resources.getSystem().getDisplayMetrics().heightPixels; if(width>height) width=height; mImageView.setLayoutParams(new LinearLayout.LayoutParams(width/3,width/3)); mImageView.setBackground(ContextCompat.getDrawable(mContext,R.drawable.border)); mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER); } @Override public void onItemClicked(View view) { Intent intent = new Intent(mContext, View_Entry.class); if(mContext.getClass()==MainActivity.class){ if(mIsMultiSelect){ view.findViewById(R.id.multiSelectcheckBox).setVisibility(View.VISIBLE); ((MainActivity)mContext).multi_select(getAdapterPosition()); }else if(!((MainActivity)mContext).getmIsClicked()){ ((MainActivity) mContext).onChangeLayout(); intent.putExtra("ID", getAdapterPosition()); mContext.startActivity(intent); } }else{ intent.putExtra("ID", ((entry)view.getTag()).get_id());//As the Matched images are Sorted w.r.t its matched keyp and position not matched.. mContext.startActivity(intent); } } @Override public boolean onItemLongClicked(View view) { if(mContext.getClass()==MainActivity.class){ if(!mIsMultiSelect) { mIsMultiSelect = true; ((MainActivity) mContext).SetMultiToolbar(); } ((MainActivity) mContext).multi_select(getAdapterPosition()); } return true; } } }
package com.example.adi.escuelaapp.DAO; import android.app.ProgressDialog; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.example.adi.escuelaapp.Entidades.Categoria; import com.example.adi.escuelaapp.Entidades.Credencial; import com.example.adi.escuelaapp.Entidades.Materia; import com.example.adi.escuelaapp.Entidades.Usuario; import com.example.adi.escuelaapp.Recursos.Constantes; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Adi on 16/06/2018. */ public class MateriaDAO { private static MateriaDAO dao; private ProgressDialog progressDialog; public MateriaDAO() { } public static MateriaDAO getInstance() { if (dao == null){ dao = new MateriaDAO(); } return dao; } public void getListaMaterias(Context context, final DAO.OnResultadoListaConsulta<Materia>listaConsulta){ progressDialog = new ProgressDialog(context); progressDialog.setMessage("Espere por favor..."); progressDialog.setCancelable(false); progressDialog.show(); String url = Constantes.HOST+Constantes.CARPETA_DAO+"Main/listaMaterias.php"; PeticionHTTP.GET get = new PeticionHTTP.GET(context,url); get.getResponseString(new PeticionHTTP.OnConsultaListener<String>() { @Override public void onSuccess(String respuesta) { if (progressDialog.isShowing()){ progressDialog.dismiss(); } try { JSONArray array = new JSONArray(respuesta); if (array.length() > 0){ List<Materia> lista = new ArrayList<Materia>(); for (int i = 0; i < array.length(); i++){ Log.i("ciclo",String.valueOf(i)); //Armamos la lista de objetos de tipo Materia JSONObject object = array.getJSONObject(i); Materia materia = new Materia(Integer.parseInt(object.getString("id")),object.getString("clave"), object.getString("nombre"),Boolean.parseBoolean("activo")); lista.add(materia); } //regresamos d emanera asincrona la lista listaConsulta.consultaSuccess(lista); }else{ listaConsulta.consultaSuccess(null); } } catch (JSONException e) { e.printStackTrace(); listaConsulta.consultaSuccess(null); } } @Override public void onFailed(String error, int respuestaHTTP) { if (progressDialog.isShowing()){ progressDialog.dismiss(); } listaConsulta.consultaFailed(error,respuestaHTTP); } }); } public void getRegistrarMaterias(Context context, final String clave, final String nombre, final DAO.OnResultadoConsulta resultado) { //inicia el progress dialog progressDialog = new ProgressDialog(context); progressDialog.setMessage("Espere por favor..."); progressDialog.setCancelable(false); progressDialog.show(); //Se crea la ruta del archivo de registrar materia String url = Constantes.HOST + Constantes.CARPETA_DAO + "Main/agregarMaterias.php"; //Creacion del Map Map<String, String> params = new HashMap<>(); params.put("clave", clave); params.put("nombre", nombre); PeticionHTTP.POST post = PeticionHTTP.POST.getInstance(context, url, params); post.getResponse(new PeticionHTTP.OnConsultaListener<String>() { @Override public void onSuccess(String respuesta) { Log.i("RESPUESTA", respuesta); if (progressDialog.isShowing()) { progressDialog.dismiss(); } Materia materia = new Materia(); resultado.consultaSuccess(materia); } @Override public void onFailed(String error, int respuestaHTTP) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } Log.i("error", error); } }); } }
package org.roy.kata16.external; import org.roy.kata16.entity.PackingSlip; public interface ShippingService { void ship(PackingSlip packingSlip); }
package model; import com.opencsv.bean.CsvBindByPosition; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter @AllArgsConstructor public class CustomerCSV { @CsvBindByPosition(position = 0) private String name; @CsvBindByPosition(position = 1) private String surname; @CsvBindByPosition(position = 2) private int age; }
package org.ubiquity.bytecode; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.ubiquity.CollectionFactory; import org.ubiquity.Copier; import org.ubiquity.logging.Logger; import org.ubiquity.logging.impl.JdkLogging; import org.ubiquity.util.CopierKey; import org.ubiquity.util.DefaultCollectionFactory; import java.util.concurrent.ExecutionException; /** * Class storing the different copiers, making all copiers available to other copiers. * <br /> * * Date: 17/04/12 * Time: 09:33 * * @author françois LAROCHE */ public final class CopyContext { private final UbiquityClassLoader loader = new UbiquityClassLoader(); private final LoadingCache<CopierKey<?,?>, Copier<?,?>> cache; private final Logger logger; private CollectionFactory factory; public CopyContext() { this.cache = CacheBuilder.newBuilder() .build(new CacheLoader<CopierKey<?,?>,Copier<?, ?>>(){ @Override public Copier<?, ?> load(CopierKey<?, ?> copierKey) throws Exception { String className = BytecodeStringUtils.createCopierClassName(copierKey); byte[] copier = CopierGenerator.createCopier(copierKey, className); return loader.registerCopier(copier, className, CopyContext.this); } }); this.factory = DefaultCollectionFactory.INSTANCE; this.logger = JdkLogging.getJdkLoggerFactory().getLogger(CopyContext.class); this.cache.put(CopierKey.newKey(Object.class, Object.class), new DefaultCopier(this)); } public final <T, U> Copier<T,U> getCopier(final CopierKey<T, U> key) { try { @SuppressWarnings("unchecked") Copier<T, U> copier = (Copier<T,U>) cache.get(key); return copier; } catch (ExecutionException e) { logger.error("Unable to create copier : ", e); throw new IllegalStateException("Unable to create copier", e); } } public final <T, U> void registerCopier(CopierKey<T,U> key, Copier<T,U> copier) { this.cache.put(key, copier); } public final CollectionFactory getFactory() { return factory; } public final void setFactory(CollectionFactory factory) { this.factory = factory; } }
package com.java.tut.test; public enum AppParameterCLI { WIDTH("w", "width", true, "set the width"), HEIGHT("h", "heigth", true, "set the height"), DEBUG("d", "debug", true, "set debug level"), HELP("?", "help", false, "show help"); final String shortname; final String name; final boolean hasArgs; final String description; AppParameterCLI( final String shortname, final String name, final boolean hasArgs, final String description) { this.shortname = shortname; this.name = name; this.hasArgs = hasArgs; this.description = description; } }
package com.prashanth.sunvalley.Controller; import com.prashanth.sunvalley.Model.LocationDTO; import com.prashanth.sunvalley.Model.LocationListDTO; import com.prashanth.sunvalley.Model.StudentDTO; import com.prashanth.sunvalley.service.LocationService; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/locations") public class LocationController { private final LocationService locationService; public LocationController(LocationService locationService) { this.locationService = locationService; } @GetMapping @ResponseStatus(HttpStatus.OK) public LocationListDTO getAllLocations(){ return new LocationListDTO(locationService.getAllLocations()); } @GetMapping("/{id}") @ResponseStatus(HttpStatus.OK) public LocationDTO getLocationById(@PathVariable Long id){ return locationService.getLocationById(id); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public LocationDTO createLocation(@RequestBody LocationDTO locationDTO){ return locationService.createLocation(locationDTO); } @PutMapping("/{id}") @ResponseStatus(HttpStatus.OK) public LocationDTO updateLocationById(@PathVariable Long id, @RequestBody LocationDTO locationDTO){ return locationService.updateLocation(id,locationDTO); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.OK) public void deleteLocationById(@PathVariable Long id){ locationService.deleteLocationById(id); } @GetMapping("/{id}/students") @ResponseStatus(HttpStatus.OK) public List<StudentDTO> getAllStudentsByLocationId(@PathVariable Long id){ return locationService.getAllStudentsOfLocationById(id); } }
package com.tencent.mm.plugin.location.ui.impl; import android.app.Activity; import android.location.LocationManager; import android.os.Bundle; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.tencent.mm.model.q; import com.tencent.mm.modelgeo.c; import com.tencent.mm.plugin.location.model.LocationInfo; import com.tencent.mm.plugin.location.model.l; import com.tencent.mm.plugin.location.model.o; import com.tencent.mm.plugin.location.model.o.b; import com.tencent.mm.plugin.location.ui.MyLocationButton; import com.tencent.mm.plugin.location.ui.ShareHeader; import com.tencent.mm.plugin.location.ui.TipSayingWidget; import com.tencent.mm.plugin.location.ui.VolumeMeter; import com.tencent.mm.plugin.location.ui.i; import com.tencent.mm.plugin.location.ui.k; import com.tencent.mm.plugin.location.ui.l.a; import com.tencent.mm.plugin.location.ui.m; import com.tencent.mm.plugin.location.ui.m$a; import com.tencent.mm.plugin.location.ui.n; import com.tencent.mm.plugin.map.a$h; import com.tencent.mm.plugin.map.a.e; import com.tencent.mm.plugin.r.d; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.apj; import com.tencent.mm.protocal.c.bbe; import com.tencent.mm.protocal.c.bfv; import com.tencent.mm.protocal.c.btp; import com.tencent.mm.protocal.c.bxg; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.widget.a.c$a; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public final class g extends i implements a { private com.tencent.mm.modelgeo.a.a cXs = new 4(this); private View kFL; private m$a kHi = new m$a() { }; private Button kJI; MyLocationButton kJJ; private TipSayingWidget kJK; m kJL; o kJM = l.aZi(); com.tencent.mm.plugin.location.ui.l kJN; k kJO; private i kJP; private c kJQ = c.OB(); private ShareHeader kJR; private String kJS; private long kJT = 0; private long kJU = 0; private b kJV = new 2(this); private o.a kJW = new o.a() { public final void aZt() { g gVar = g.this; c$a c_a = new c$a(gVar.activity); c_a.Gr(a$h.track_timeout); c_a.Gt(a$h.app_ok).a(new 9(gVar)); c_a.anj().show(); } }; private HashMap<String, bxg> kJX = new HashMap(); private WakeLock wakeLock; static /* synthetic */ void a(g gVar, bfv bfv) { com.tencent.mm.plugin.location.a.a aVar; bxg bxg; x.d("MicroMsg.ShareMapUI", "refreshSuccess, timeout = %b", new Object[]{Boolean.valueOf(gVar.kJM.bBc)}); List<bxg> list = bfv.sgY; List<bxg> linkedList = new LinkedList(); com.tencent.mm.plugin.location.a.a FM = l.aZj().FM(gVar.kDN); if (FM == null) { FM = new com.tencent.mm.plugin.location.a.a(); FM.latitude = -1000.0d; FM.longitude = -1000.0d; aVar = FM; } else { aVar = FM; } LinkedList linkedList2 = new LinkedList(); for (bxg bxg2 : list) { linkedList2.add(bxg2.rdS); } if (!linkedList2.contains(q.GF())) { linkedList2.add(q.GF()); } l.aZj().a(gVar.kDN, linkedList2, aVar.latitude, aVar.longitude, aVar.kCs, "", ""); for (bxg bxg22 : list) { if (Math.abs(bxg22.stK.rji) > 180.0d || Math.abs(bxg22.stK.rjj) > 90.0d) { bxg bxg3 = (bxg) gVar.kJX.get(bxg22.rdS); if (bxg3 != null) { linkedList.add(bxg3); x.i("MicroMsg.ShareMapUI", "error from server get latlng %s %f %f and use old one %f %f", new Object[]{bxg22.rdS, Double.valueOf(bxg22.stK.rjj), Double.valueOf(bxg22.stK.rji), Double.valueOf(bxg3.stK.rjj), Double.valueOf(bxg3.stK.rji)}); } else { x.i("MicroMsg.ShareMapUI", "error from server get latlng %s %f %f cannot user old one", new Object[]{bxg22.rdS, Double.valueOf(bxg22.stK.rjj), Double.valueOf(bxg22.stK.rji)}); } } else { linkedList.add(bxg22); } } gVar.kJX.clear(); for (bxg bxg222 : linkedList) { gVar.kJX.put(bxg222.rdS, bxg222); } int size = linkedList.size(); ArrayList arrayList = new ArrayList(); arrayList.add(q.GF()); if (size >= 0) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("refreshSuccess, count = " + size); size = 0; while (true) { int i = size; if (i >= linkedList.size()) { break; } bxg222 = (bxg) linkedList.get(i); stringBuilder.append("[" + bxg222.rdS + " ] "); stringBuilder.append(bxg222.stK.sds + " "); stringBuilder.append(bxg222.stK.rjj + " "); stringBuilder.append(bxg222.stK.rji + " "); arrayList.add(bxg222.rdS); size = i + 1; } x.v("MicroMsg.ShareMapUI", "refreshSuccess TrackRoom num: " + stringBuilder.toString()); if (gVar.kJL != null) { gVar.kJL.bt(linkedList); } } if (gVar.kJL.kGX) { m mVar = gVar.kJL; btp btp = bfv.sgZ; if (mVar.kHa == null) { mVar.kHa = new btp(); } if (btp != null) { x.d("MicroMsg.TrackPointViewMgrImpl", "set trackitem " + btp.rjj + " " + btp.rji); mVar.kHa.sbw = btp.sbw; mVar.kHa.rjj = btp.rjj; mVar.kHa.rji = btp.rji; } } gVar.kJP.D(arrayList); } public final boolean aZX() { return true; } public g(Activity activity) { super(activity); } public final void onCreate(Bundle bundle) { super.onCreate(bundle); x.i("MicroMsg.ShareMapUI", "onCreate"); this.kJT = System.currentTimeMillis(); } final void aZW() { super.aZW(); this.wakeLock = ((PowerManager) this.activity.getSystemService("power")).newWakeLock(26, "Track Lock"); if (this.kKt != null) { n nVar = this.kKt; nVar.kHG.setVisibility(4); nVar.isVisible = false; } findViewById(e.header_bar).setVisibility(8); this.kJJ = (MyLocationButton) findViewById(e.locate_to_my_position); this.kJJ.setProgressBar(this.kHR.kEZ); this.kJJ.aZy(); this.kJJ.setOnClickListener(new OnClickListener() { public final void onClick(View view) { g.this.kJJ.aZy(); g.this.kJL.kHb = true; g.this.kJL.a(g.this.kHR.kEZ); g.this.kJL.gj(false); h.mEJ.h(10997, new Object[]{"6", "", Integer.valueOf(0), Integer.valueOf(0)}); } }); this.kFL = findViewById(e.header_avatar_area); this.kJR = (ShareHeader) findViewById(e.share_header); this.kJR.setVisibility(0); this.kJP = new i(this.activity, this.kJR.getHeaderBar(), this.kFL, this.kDN, this.kHR.kEZ); this.kJP.kFR = new 6(this); this.kJM.kDP = this.kJW; if (this.kJL == null) { this.kJL = new m(this.activity, this.kHR.kEZ, true); } this.kJL.kHi = this.kHi; this.kJL.kGW = false; this.kJN = new com.tencent.mm.plugin.location.ui.l(this.activity, this); this.kJK = (TipSayingWidget) findViewById(e.saying_tips); this.kJI = (Button) findViewById(e.share_speak); this.kJI.setVisibility(0); this.kJO = new k(this.activity, this.kJI); this.kJO.kGF = this.kJP; this.kJR.setOnLeftClickListener(new 7(this)); this.kJR.setOnRightClickListener(new 8(this)); ((LocationManager) this.activity.getSystemService("location")).isProviderEnabled("gps"); o oVar = this.kJM; LocationInfo locationInfo = this.kHP; oVar.kDS = System.currentTimeMillis(); oVar.dMm = c.OB(); oVar.dMm.b(oVar.cXs, true); if (oVar.kDF == null) { oVar.kDF = l.aZk(); } oVar.kDF.a(oVar.kDU); if (locationInfo != null) { oVar.kDJ = locationInfo; } if (oVar.bTv) { x.i("MicorMsg.TrackRefreshManager", "start location " + oVar.kDJ.kCw + " " + oVar.kDJ.kCx); } else { oVar.kDH = 1; oVar.kDI = new bxg(); oVar.kDI.stK = new bbe(); oVar.kDI.stK.rjj = -1000.0d; oVar.kDI.stK.rji = -1000.0d; x.i("MicorMsg.TrackRefreshManager", "start location imp " + oVar.kDJ.kCw + " " + oVar.kDJ.kCx); com.tencent.mm.kernel.g.DF().a(492, oVar); com.tencent.mm.kernel.g.DF().a(490, oVar); com.tencent.mm.kernel.g.DF().a(491, oVar); oVar.bBc = false; oVar.bTv = true; } o oVar2 = this.kJM; b bVar = this.kJV; Iterator it = oVar2.kDG.iterator(); while (it.hasNext()) { WeakReference weakReference = (WeakReference) it.next(); if (weakReference != null && weakReference.get() != null && ((b) weakReference.get()).equals(bVar)) { break; } } oVar2.kDG.add(new WeakReference(bVar)); this.kJS = this.activity.getIntent().getStringExtra("fromWhereShare"); x.d("MicroMsg.ShareMapUI", "fromWhere=%s", new Object[]{this.kJS}); if (this.kJM.aZn()) { x.i("MicroMsg.ShareMapUI", "has join"); this.kJL.gk(true); this.kJO.aZI(); return; } int i; String GF; com.tencent.mm.plugin.location.model.a.b bVar2; o oVar3 = this.kJM; String str = this.kDN; if (!bi.oW(this.kJS)) { if (this.kJS.equals("fromBanner")) { i = 0; } else if (!this.kJS.equals("fromPluginLocation")) { if (this.kJS.equals("fromPluginTalk")) { i = 2; } else if (this.kJS.equals("fromTrackButton")) { i = 3; } else if (this.kJS.equals("fromMessage")) { i = 4; } } x.i("MicorMsg.TrackRefreshManager", "track join %s", new Object[]{str}); oVar3.kDN = str; GF = q.GF(); GF = str.contains("@chatroom") ? str : GF.compareTo(str) > 0 ? str + GF : GF + str; bVar2 = new com.tencent.mm.plugin.location.model.a.b(GF); ((apj) bVar2.diG.dID.dIL).otY = i; com.tencent.mm.kernel.g.DF().a(bVar2, 0); } i = 1; x.i("MicorMsg.TrackRefreshManager", "track join %s", new Object[]{str}); oVar3.kDN = str; GF = q.GF(); if (str.contains("@chatroom")) { } bVar2 = new com.tencent.mm.plugin.location.model.a.b(GF); ((apj) bVar2.diG.dID.dIL).otY = i; com.tencent.mm.kernel.g.DF().a(bVar2, 0); } public final void onResume() { boolean z; x.i("MicroMsg.ShareMapUI", "resume"); super.onResume(); this.wakeLock.acquire(); o oVar = this.kJM; x.d("MicorMsg.TrackRefreshManager", "resume isPuase:" + oVar.kDL); if (oVar.kDL) { oVar.kDS = System.currentTimeMillis(); oVar.dMm.a(oVar.cXs); oVar.kDF.a(oVar.kDU); } oVar.kDL = false; oVar.aZo(); oVar = this.kJM; d dVar = this.kHR.kEZ; oVar.kDH = oVar.kDM; x.d("MicorMsg.TrackRefreshManager", "resumeStatus upload_status " + oVar.kDH + " %f %f %d ", new Object[]{Double.valueOf(oVar.kCw), Double.valueOf(oVar.kCx), Integer.valueOf(oVar.kCy)}); if (oVar.kCw == -1000.0d || oVar.kCx == -1000.0d || oVar.kCy == -1) { z = false; } else { dVar.getIController().setCenter(oVar.kCw, oVar.kCx); dVar.getIController().setZoom(oVar.kCy); z = true; } if (z) { this.kJJ.setAnimToSelf(false); this.kJJ.aZz(); this.kJL.kHb = false; this.kJL.kGV = true; } oVar = this.kJM; d dVar2 = this.kHR.kEZ; if (oVar.kDQ != -1) { dVar2.getIController().setZoom(oVar.kDQ); } if (this.kJQ != null) { this.kJQ.a(this.cXs); } if (this.kJL != null) { this.kJL.onResume(); } } public final void onPause() { x.i("MicroMsg.ShareMapUI", "pause"); super.onPause(); this.wakeLock.release(); o oVar = this.kJM; x.d("MicorMsg.TrackRefreshManager", "pause isShared:" + oVar.kDK); if (!oVar.kDK) { oVar.dMm.c(oVar.cXs); oVar.kDF.b(oVar.kDU); oVar.kDL = true; oVar.kDR = true; } oVar = this.kJM; d dVar = this.kHR.kEZ; oVar.kDM = oVar.kDH; oVar.kDH = 0; x.d("MicorMsg.TrackRefreshManager", "saveStatus pause_save_upload_status: " + oVar.kDM); if (oVar.aZs()) { oVar.kCw = (((double) dVar.getMapCenterX()) * 1.0d) / 1000000.0d; oVar.kCx = (((double) dVar.getMapCenterY()) * 1.0d) / 1000000.0d; oVar.kCy = dVar.getZoom(); } h.mEJ.h(10997, new Object[]{"17", Integer.valueOf(0), Integer.valueOf(0), Long.valueOf(System.currentTimeMillis() - this.kJT)}); this.kJT = System.currentTimeMillis(); if (this.kJQ != null) { this.kJQ.c(this.cXs); } if (this.kJL != null) { this.kJL.onPause(); } } public final void onDestroy() { super.onDestroy(); o oVar = this.kJM; b bVar = this.kJV; Iterator it = oVar.kDG.iterator(); while (it.hasNext()) { WeakReference weakReference = (WeakReference) it.next(); if (weakReference != null && weakReference.get() != null && ((b) weakReference.get()).equals(bVar)) { oVar.kDG.remove(weakReference); break; } } this.kJM.kDP = null; if (this.kJO != null) { k kVar = this.kJO; kVar.kGE.b(kVar); VolumeMeter volumeMeter = kVar.kGr; volumeMeter.kHk = true; volumeMeter.dRn = false; if (volumeMeter.kHo != null) { volumeMeter.kHo.getLooper().quit(); volumeMeter.kHo = null; } } if (this.kJL != null) { this.kJL.destroy(); } if (this.kJJ != null) { c.OB().c(this.kJJ.cXs); } x.i("MicroMsg.ShareMapUI", "onDestory"); } public final void gi(boolean z) { } protected final void aZV() { super.aZV(); } public final void aZN() { this.kJM.kDQ = this.kHR.kEZ.getZoom(); this.activity.finish(); } private void bah() { YC(); this.kJL.gk(false); this.kJM.stop(); this.kJM.rP(3); k.aZL(); this.kJM.kDQ = this.kHR.kEZ.getZoom(); this.activity.finish(); } public final void aZO() { this.kJL.gk(false); this.kJM.stop(); this.kJM.rP(0); k.aZL(); this.activity.finish(); } public final void rS(int i) { if (i == 0) { h.mEJ.h(10997, new Object[]{"8", "", Integer.valueOf(0), Integer.valueOf(0)}); bah(); } else if (i == 1) { h.mEJ.h(10997, new Object[]{"8", "", Integer.valueOf(0), Integer.valueOf(0)}); bah(); } else if (i == 2) { bah(); } } public final void aZP() { btp btp = this.kJL.kHa; if (btp != null) { LocationInfo locationInfo = this.kHP; locationInfo.kCz = btp.sbw; locationInfo.kCx = btp.rji; locationInfo.kCw = btp.rjj; if (TextUtils.isEmpty(btp.sbw)) { this.kKt.setText(""); } else { this.kKt.setText(btp.sbw); } this.kKt.b(this.kHP); n nVar = this.kKt; nVar.mViewManager.updateViewLayout(nVar.kHF, nVar.kCw, nVar.kCx, false); if (nVar.kHI) { nVar.mViewManager.showInfoWindowByView(nVar.kHF); } this.kHR.kEZ.getIController().animateTo(this.kHP.kCw, this.kHP.kCx); } } public final void onBackPressed() { h.mEJ.h(10997, new Object[]{"11", Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)}); this.kJN.aZM(); } public final boolean dispatchKeyEvent(KeyEvent keyEvent) { return super.dispatchKeyEvent(keyEvent); } public final void bai() { super.bai(); if (this.kJL != null) { this.kJL.kHb = false; this.kJL.gj(false); this.kJJ.aZz(); } } protected final void baj() { super.baj(); h.mEJ.h(10997, new Object[]{"1", "", Integer.valueOf(0), Integer.valueOf(0)}); } }
package com.tfjybj.integral.model; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.ToString; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.Date; /** * @author 崔晓鸿 * @since 2019年9月13日17:49:17 */ @Data @Accessors(chain = true) @ToString(callSuper = true) public class IntegralPluginlMonthModel implements Serializable { /** * 创建时间create_time */ @JsonFormat( pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8" ) @ApiModelProperty(value = "创建时间create_time") private Date createTime; /** * 自由加分 */ @ApiModelProperty(value = "自由加分") private int free; /** * 活动 */ @ApiModelProperty(value = "活动") private int activity; /** * 头脑风暴 */ @ApiModelProperty(value = "头脑风暴") private int sumIncome; /** * 钉钉 */ @ApiModelProperty(value = "钉钉") private int brainstorm; /** * 游戏 */ @ApiModelProperty(value = "游戏") private int dingtalk; /** * 今目标 */ @ApiModelProperty(value = "今目标") private int game; /** * 积分系统 */ @ApiModelProperty(value = "积分系统") private int jingoal; /** * 图书馆 */ @ApiModelProperty(value = "图书馆") private int kernel; /** * 抽奖 */ @ApiModelProperty(value = "抽奖") private int library; /** * 总收入 */ @ApiModelProperty(value = "总收入") private int lottery; /** * 蓝墨云班课 */ @ApiModelProperty(value = "蓝墨云班课") private int mosoteach; /** * 绩效考评 */ @ApiModelProperty(value = "绩效考评") private int performance; /** * 番茄 */ @ApiModelProperty(value = "番茄") private int tomato; /** * 培养计划 */ @ApiModelProperty(value = "培养计划") private int training; /** * 禅道 */ @ApiModelProperty(value = "禅道") private int zentao; }
package org.sbbs.app.demo.model; /** org.sbbs.app.demo.model.DemoSysDbLog */ import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.sbbs.base.model.BaseObject; /** * @author Administrator */ @Entity @Table( name = "t_demo_syslog" ) public class DemoSysDbLog extends BaseObject{ /** * */ private static final long serialVersionUID = 5966415593642727205L; private Long logId; private String logMsg; private String operator; private Date logTime; @Id @GeneratedValue( strategy = GenerationType.AUTO ) public Long getLogId() { return logId; } public void setLogId( Long logId ) { this.logId = logId; } @Column( name = "logMsg", length = 500, nullable = false ) public String getLogMsg() { return logMsg; } public void setLogMsg( String logMsg ) { this.logMsg = logMsg; } @Column( name = "operator", length = 50, nullable = false ) public String getOperator() { return operator; } public void setOperator( String operator ) { this.operator = operator; } @Temporal( TemporalType.TIMESTAMP ) @Column( name = "logTime", length = 19, nullable = false ) public Date getLogTime() { return logTime; } /** * @param logTime */ public void setLogTime( Date logTime ) { this.logTime = logTime; } @Override public String toString() { return "DemoSysDbLog [logId=" + logId + ", logMsg=" + logMsg + ", operator=" + operator + ", logTime=" + logTime + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( ( logId == null ) ? 0 : logId.hashCode() ); result = prime * result + ( ( logMsg == null ) ? 0 : logMsg.hashCode() ); result = prime * result + ( ( logTime == null ) ? 0 : logTime.hashCode() ); result = prime * result + ( ( operator == null ) ? 0 : operator.hashCode() ); return result; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; DemoSysDbLog other = (DemoSysDbLog) obj; if ( logId == null ) { if ( other.logId != null ) return false; } else if ( !logId.equals( other.logId ) ) return false; if ( logMsg == null ) { if ( other.logMsg != null ) return false; } else if ( !logMsg.equals( other.logMsg ) ) return false; if ( logTime == null ) { if ( other.logTime != null ) return false; } else if ( !logTime.equals( other.logTime ) ) return false; if ( operator == null ) { if ( other.operator != null ) return false; } else if ( !operator.equals( other.operator ) ) return false; return true; } }
import java.applet.Applet; import java.applet.AudioClip; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.EventQueue; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.ImageIcon; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JProgressBar; import javax.swing.Timer; import javax.swing.border.TitledBorder; import org.omg.CORBA_2_3.portable.OutputStream; import java.awt.Color; public class dds1 extends JFrame implements Runnable, MouseListener, ActionListener { private JPanel contentPane; private Cursor c1,c2; private Thread t; private JLabel img[]; private JLabel lsore; private int score=0; private AudioClip a1; public AudioClip a2; private JMenuItem mntmNewMenuItem,mntmOff; private JMenuItem menuItem; private Timer timer; private JProgressBar progressBar; private boolean threadstarted=false; private Score []sc; private File file; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { dds1 frame = new dds1(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } static class Score implements Serializable{ String id; int score; Score(){ id="匿名"; score=0; } } /** * Create the frame. */ public dds1() { setAlwaysOnTop(true); setTitle("\u6253\u5730\u9F20\u6E38\u620F"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 300, 500, 538); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnNewMenu = new JMenu("\u83DC\u5355"); menuBar.add(mnNewMenu); menuItem = new JMenuItem("\u5F00\u59CB"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(threadstarted==false) { t.start(); threadstarted=true; } else { t.resume(); } timer.start(); menuItem.setEnabled(false); progressBar.setString(null); } }); mnNewMenu.add(menuItem); JMenuItem menuItem_1 = new JMenuItem("\u505C\u6B62"); menuItem_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { t.suspend(); timer.stop(); } }); mnNewMenu.add(menuItem_1); JMenuItem menuItem_2 = new JMenuItem("\u7EE7\u7EED"); menuItem_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { t.resume(); timer.start(); } }); mnNewMenu.add(menuItem_2); JMenuItem menuItem_3 = new JMenuItem("\u9000\u51FA"); menuItem_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); mnNewMenu.add(menuItem_3); JMenu mnNewMenu_1 = new JMenu("\u97F3\u4E50\u63A7\u5236"); menuBar.add(mnNewMenu_1); mntmNewMenuItem = new JMenuItem("On"); mntmNewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { a2.loop(); mntmNewMenuItem.setEnabled(false); mntmOff.setEnabled(true); } }); mnNewMenu_1.add(mntmNewMenuItem); mntmOff = new JMenuItem("Off"); mntmOff.setEnabled(false); mntmOff.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { a2.stop(); mntmOff.setEnabled(false); mntmNewMenuItem.setEnabled(true); } }); mnNewMenu_1.add(mntmOff); JMenuItem menuItem_5 = new JMenuItem("\u9009\u62E9\u80CC\u666F\u97F3\u4E50"); menuItem_5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { mChoose mc=new mChoose(dds1.this); mc.setModal(true); mc.setLocation(200,200); mc.show(); } }); mnNewMenu_1.add(menuItem_5); JMenu mnNewMenu_2 = new JMenu("\u5E2E\u52A9"); menuBar.add(mnNewMenu_2); JMenuItem menuItem_4 = new JMenuItem("\u82F1\u96C4\u699C"); menuItem_4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Hero heros=new Hero(); for(int i=0;i<sc.length;i++) { heros.taheros.append("英雄大名:"+sc[i].id+" 成绩"+sc[i].score+"\n"); } heros.setModal(true); heros.show(); } }); mnNewMenu_2.add(menuItem_4); JMenuItem menuItem_6 = new JMenuItem("\u5173\u4E8E"); menuItem_6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myAbout myAbout=new myAbout(); myAbout.setModal(true); myAbout.setLocation(200, 200); myAbout.show(); } }); mnNewMenu_2.add(menuItem_6); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel img1 = new JLabel(""); img1.setIcon(new ImageIcon(this.getClass().getResource("mouse.png"))); img1.setBounds(337, 241, 63, 67); contentPane.add(img1); JLabel img2 = new JLabel(""); img2.setIcon(new ImageIcon(this.getClass().getResource("mouse.png"))); img2.setBounds(99, 323, 63, 67); contentPane.add(img2); JLabel img3 = new JLabel(""); img3.setIcon(new ImageIcon(this.getClass().getResource("mouse.png"))); img3.setBounds(190, 346, 63, 67); contentPane.add(img3); JLabel img4 = new JLabel(""); img4.setIcon(new ImageIcon(this.getClass().getResource("mouse.png"))); img4.setBounds(390, 287, 63, 67); contentPane.add(img4); JLabel img5 = new JLabel(""); img5.setIcon(new ImageIcon(this.getClass().getResource("mouse.png"))); img5.setBounds(359, 358, 63, 67); contentPane.add(img5); JLabel img6 = new JLabel(""); img6.setIcon(new ImageIcon(this.getClass().getResource("mouse.png"))); img6.setBounds(242, 404, 63, 67); contentPane.add(img6); JLabel img7 = new JLabel(""); img7.setIcon(new ImageIcon(this.getClass().getResource("mouse.png"))); img7.setBounds(252, 289, 63, 67); contentPane.add(img7); JLabel img8 = new JLabel(""); img8.setIcon(new ImageIcon(this.getClass().getResource("mouse.png"))); img8.setBounds(242, 252, 63, 67); contentPane.add(img8); lsore = new JLabel("\u60A8\u7684\u5F97\u5206\u662F0\u5206"); lsore.setBounds(32, 21, 146, 15); contentPane.add(lsore); progressBar = new JProgressBar(); progressBar.setMaximum(10); progressBar.setBorder(new TitledBorder(null, "\u6E38\u620F\u8FDB\u5EA6", TitledBorder.CENTER, TitledBorder.ABOVE_TOP, null, Color.RED)); progressBar.setStringPainted(true); progressBar.setBounds(32, 49, 146, 35); contentPane.add(progressBar); JLabel background = new JLabel(""); background.setIcon(new ImageIcon(this.getClass().getResource("background.jpg"))); background.setBounds(0, 0, 500, 500); contentPane.add(background); img=new JLabel[8]; img[0]=img1; img[1]=img2; img[2]=img3; img[3]=img4; img[4]=img5; img[5]=img6; img[6]=img7; img[7]=img8; for(int i=0;i<8;i++) { img[i].setVisible(false); img[i].addMouseListener(this); } c1=Toolkit.getDefaultToolkit().createCustomCursor(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("icon.png")), new Point(20,20),"c1"); c2=Toolkit.getDefaultToolkit().createCustomCursor(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("icon1.png")), new Point(20,20),"c2"); a1=Applet.newAudioClip(this.getClass().getResource("响声.wav")); a2=Applet.newAudioClip(this.getClass().getResource("背景音乐.wav")); t=new Thread(this); //t.start(); timer=new Timer(1000,this); file=new File(".\\hero.data"); if(!file.exists()) { try { file.createNewFile(); sc=new Score[6]; for(int i=0;i<sc.length;i++) sc[i]=new Score(); FileOutputStream os=new FileOutputStream(file); ObjectOutputStream oos=new ObjectOutputStream(os); oos.writeObject(sc); oos.close(); os.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { FileInputStream is; try { is = new FileInputStream(file); ObjectInputStream ois=new ObjectInputStream(is); sc=(Score[])(ois.readObject()); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } @Override public void run() { // TODO Auto-generated method stub while(true){ try { Thread.sleep(800); int index=(int)(Math.random()*8); if(!img[index].isShowing()) { img[index].setVisible(true); Thread.sleep(800); img[index].setVisible(false); } } catch (InterruptedException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub a1.play(); JLabel l=(JLabel)(e.getSource()); if(l.isShowing()) { l.setVisible(false); lsore.setText("你的得分是"+(++score)+"分"); t.interrupt(); } } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub this.setCursor(c1); } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub this.setCursor(c2); } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub int value=progressBar.getValue(); if(value<10) progressBar.setValue(++value); else { JOptionPane.showMessageDialog(this,"游戏结束,得分是:"+score,"提示",JOptionPane.WARNING_MESSAGE); menuItem.setEnabled(true); timer.stop(); t.suspend(); boolean findhero=false; int heroid=0; for(int i=0;i<sc.length;i++) { if(score>sc[i].score) { findhero=true; heroid=i; break; } } if(findhero) { for(int j=sc.length-1;j<heroid;j--) { sc[j].id=sc[j-1].id; sc[j].score=sc[j-1].score; } sc[heroid].id="匿名"; sc[heroid].score=score; String heroname=JOptionPane.showInputDialog("请留下您的大名:"); if(heroname!=null)sc[heroid].id=heroname; OutputStream os = null; ObjectOutputStream oos; try { oos = new ObjectOutputStream(os); oos.writeObject(sc); oos.close(); os.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } score=0; progressBar.setValue(0); progressBar.setString("游戏结束了"); } } }
package pojo; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import db.DBConn; import entity.Student; public class Apply { public Apply() { }; // 申请教室的方法 public String applyroom(String week, String day, String time, String room, String duomeiti, String purpose, long sid) { String result = ""; ResultSet rs = null; Connection con = null; PreparedStatement pre = null; DBConn conns = new DBConn(); con = conns.getConnection(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String createtime = df.format(new Date()); try { pre = con .prepareStatement("Select occupancy from classroomoccupancy WHERE week='" + week + "'&&day='" + day + "'&&time='" + time + "'&&room='" + room + "'"); System.out.println(pre); rs = pre.executeQuery(); String occupancy = ""; while (rs.next()) { occupancy = rs.getString("occupancy"); } if (occupancy.equals("是")) { return "该教室已被占用"; } pre = con .prepareStatement("INSERT INTO `apply`(`room`, `week`, `day`, `time`, `sid`, `duomeiti`, `purpose`, `applytime`, `result`) VALUES('" + room + "','" + week + "','" + day + "','" + time + "'," + sid + ",'" + duomeiti + "','" + purpose + "','" + createtime + "','" + "待审核" + "')"); System.out.println(pre); pre.executeUpdate(); return "申请成功"; } catch (SQLException e) { e.printStackTrace(); } finally { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } return "申请失败"; } // 返回个人申请的个数 public String pagenumber(long sid) { String result = ""; ResultSet rs = null; Connection con = null; PreparedStatement pre = null; DBConn conns = new DBConn(); con = conns.getConnection(); try { pre = con .prepareStatement("Select count(applyid) from apply WHERE sid=" + sid); System.out.println(pre); rs = pre.executeQuery(); int count = 0; while (rs.next()) { count = rs.getInt("count(applyid)"); } int pagenumber = count / 8 + 1; System.out.println("pagenumber=" + pagenumber); result = result + "<ul>"; for (int i = 1; i <= pagenumber; i++) { result = result + "<li><a href=\"javascript:void(0)\" onclick=\"showapply(" + i + ")\">" + i + "</a></li>"; } result = result + "</ul><script src=\"../js/applyajax.js\"></script> "; return result; } catch (SQLException e) { e.printStackTrace(); } finally { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } return ""; } // 显示个人申请 public String showapply(int page, long sid) { String result = ""; ResultSet rs = null; Connection con = null; PreparedStatement pre = null; DBConn conns = new DBConn(); con = conns.getConnection(); try { pre = con .prepareStatement("Select room,week,day,time,result from apply WHERE sid=" + sid + " order by applytime desc limit " + (page - 1) * 8 + "," + 8); System.out.println(pre); rs = pre.executeQuery(); while (rs.next()) { if (null == rs.getString("room")) { return ""; } result = result + "<p id=\"applyitemp\">对" + rs.getString("room") + rs.getString("week") + rs.getString("day") + rs.getString("time") + "的申请"; if (rs.getString("result").equals("待审核")) { result = result + "正在审核"; } else if (rs.getString("result").equals("通过")) { result = result + "成功"; } else if (rs.getString("result").equals("不通过")) { result = result + "失败"; } result = result + "</p>"; } return result; } catch (SQLException e) { e.printStackTrace(); return ""; } finally { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
package com.cg.digi.model; public class WindowsDistribution { private String windowsdistributiondetailsid; private String windowsid; private String version; private String rate; private String status; private String createdby; private String creationtime; private String modifiedby; private String modifiedtime; public WindowsDistribution() { super(); } public WindowsDistribution(String windowsdistributiondetailsid, String windowsid, String version, String rate, String status, String createdby, String creationtime, String modifiedby, String modifiedtime) { super(); this.windowsdistributiondetailsid = windowsdistributiondetailsid; this.windowsid = windowsid; this.version = version; this.rate = rate; this.status = status; this.createdby = createdby; this.creationtime = creationtime; this.modifiedby = modifiedby; this.modifiedtime = modifiedtime; } public String getWindowsdistributiondetailsid() { return windowsdistributiondetailsid; } public void setWindowsdistributiondetailsid(String windowsdistributiondetailsid) { this.windowsdistributiondetailsid = windowsdistributiondetailsid; } public String getWindowsid() { return windowsid; } public void setWindowsid(String windowsid) { this.windowsid = windowsid; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getRate() { return rate; } public void setRate(String rate) { this.rate = rate; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCreatedby() { return createdby; } public void setCreatedby(String createdby) { this.createdby = createdby; } public String getCreationtime() { return creationtime; } public void setCreationtime(String creationtime) { this.creationtime = creationtime; } public String getModifiedby() { return modifiedby; } public void setModifiedby(String modifiedby) { this.modifiedby = modifiedby; } public String getModifiedtime() { return modifiedtime; } public void setModifiedtime(String modifiedtime) { this.modifiedtime = modifiedtime; } @Override public String toString() { return "WindowsDistribution [windowsdistributiondetailsid=" + windowsdistributiondetailsid + ", windowsid=" + windowsid + ", version=" + version + ", rate=" + rate + ", status=" + status + ", createdby=" + createdby + ", creationtime=" + creationtime + ", modifiedby=" + modifiedby + ", modifiedtime=" + modifiedtime + "]"; } }
/* * Copyright © 2019 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.dom.builder.shared; /** Builds an video element. */ public interface VideoBuilder extends MediaBuilder<VideoBuilder> { /** * Sets the height of the element. * * @param height the height, in pixels */ VideoBuilder height(int height); /** * Sets the poster URL. * * @param url the poster image URL */ VideoBuilder poster(String url); /** * Sets the width of the element. * * @param width the width, in pixels */ VideoBuilder width(int width); }
package com.gmail.ivanytskyy.vitaliy.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; /* * Simple JavaBean domain object representing a scheduleItem * @author Vitaliy Ivanytskyy */ @Entity @Table(name = "schedule_items") public class ScheduleItem { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @ManyToOne @JoinColumn(name = "group_id", referencedColumnName = "id") private Group group; @NotNull @ManyToOne @JoinColumn(name = "lecturer_id", referencedColumnName = "id") private Lecturer lecturer; @NotNull @ManyToOne @JoinColumn(name = "classroom_id", referencedColumnName = "id") private Classroom classroom; @NotNull @ManyToOne @JoinColumn(name = "subject_id", referencedColumnName = "id") private Subject subject; @NotNull @ManyToOne @JoinColumn(name = "lesson_interval_id", referencedColumnName = "id") private LessonInterval lessonInterval; @NotNull @ManyToOne @JoinColumn(name = "schedule_id", referencedColumnName = "id") private Schedule schedule; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } public Lecturer getLecturer() { return lecturer; } public void setLecturer(Lecturer lecturer) { this.lecturer = lecturer; } public Classroom getClassroom() { return classroom; } public void setClassroom(Classroom classroom) { this.classroom = classroom; } public Subject getSubject() { return subject; } public void setSubject(Subject subject) { this.subject = subject; } public LessonInterval getLessonInterval() { return lessonInterval; } public void setLessonInterval(LessonInterval lessonInterval) { this.lessonInterval = lessonInterval; } public Schedule getSchedule() { return schedule; } public void setSchedule(Schedule schedule) { this.schedule = schedule; } }
package com.supconit.kqfx.web.fxzf.search.daos.Impl; import hc.base.domains.Pageable; import hc.orm.AbstractBasicDaoImpl; import java.util.List; import org.springframework.stereotype.Repository; import com.supconit.kqfx.web.fxzf.search.daos.FxzfStaticDao; import com.supconit.kqfx.web.fxzf.search.entities.FxzfStatic; /** * * @author JNJ * @time 2016年12月8日10:14:49 * */ @Repository public class FxzfStaticDaoImpl extends AbstractBasicDaoImpl<FxzfStatic, String> implements FxzfStaticDao { private static final String NAMESPACE = FxzfStatic.class.getName(); @Override public Pageable<FxzfStatic> findByPager(Pageable<FxzfStatic> pager, FxzfStatic condition) { return findByPager(pager, "selectPager", "countPager", condition); } @Override protected String getNamespace() { return NAMESPACE; } @Override public void batchInsert(List<FxzfStatic> fxzfList) { insert("batchInsert", fxzfList); } @Override public void checkFxzfMessage(FxzfStatic condition) { update("checkFxzfMessage", condition); } @Override public FxzfStatic getById(String id) { return super.getById(id); } @Override public int getOverLoadStatusCount(FxzfStatic fxzfStatic) { return selectOne("getOverLoadStatusCount", fxzfStatic); } @Override public int getIllegalLevelCount(FxzfStatic fxzfStatic) { return selectOne("getIllegalLevelCount", fxzfStatic); } @Override public Pageable<FxzfStatic> findByPagerDetail(Pageable<FxzfStatic> pager, FxzfStatic condition) { return findByPager(pager, "selectPagerDetail", "countPagerDetail", condition); } @Override public Integer getCountByCondition(FxzfStatic fxzfStatic) { return selectOne("getCountByCondition", fxzfStatic); } @Override public Integer getOverLoadCount(FxzfStatic fxzfStatic) { return selectOne("getOverLoadCount", fxzfStatic); } @Override public void deleteById(String id) { delete("deleteById", id); } @Override public List<FxzfStatic> getFxzfToTransport() { return selectList("getFxzfToTransport"); } @Override public void upDateFxzftransport(FxzfStatic fxzfStatic) { update("upDateFxzftransport", fxzfStatic); } }
package com.jt.manage.controller; import java.io.File; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.jt.common.vo.PicUploadResult; import com.jt.manage.service.FileService; @Controller public class FileController { @Autowired private FileService fileServce; //实现文件上传入门案例 @RequestMapping("/file") public String file(MultipartFile fileImage) throws IllegalStateException, IOException{ //1.判断文件夹是否存在 File fileDir = new File("E:/jt-upload"); if(!fileDir.exists()) { //判断文件夹是否存在 fileDir.mkdirs();//创建文件夹 } //abc.jpg 获取图片名称 String fileName = fileImage.getOriginalFilename(); //实现文件上传 fileImage.transferTo(new File("E:/jt-upload/"+fileName)); //使用重定向技术 return "redirect:/file.jsp"; //转发 //return "forword:/file.jsp"; } //实现文件的上传 @RequestMapping("/pic/upload") @ResponseBody public PicUploadResult uploadFile(MultipartFile uploadFile) { return fileServce.uploadFile(uploadFile); } }
package com.example.wanderlust.ui.home; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.nfc.Tag; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.wanderlust.BlogView; import com.example.wanderlust.Adapters.BlogAdapter; import com.example.wanderlust.DatabaseHelper.DbInstance; import com.example.wanderlust.Doa.BlogObject; import com.example.wanderlust.MainActivity; import com.example.wanderlust.R; import com.example.wanderlust.ui.auth.Login; import java.util.ArrayList; public class HomeFragment extends Fragment { private HomeViewModel homeViewModel; private RecyclerView recycleCards; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class); View root = inflater.inflate(R.layout.fragment_home, container, false); recycleCards = (RecyclerView) root.findViewById(R.id.recycle_cards); final DbInstance dbHelper = new DbInstance(getActivity()); final ArrayList<BlogObject> blogData = dbHelper.getAllBlogData(); if(blogData != null){ for(int i=0; i<blogData.size(); i++){ Log.i("Tag: "+i, blogData.get(i).getBlogId()); Log.i("Tag: "+i, blogData.get(i).getBlogTitle()); Log.i("Tag: "+i, blogData.get(i).getBlogText()); Log.i("Tag: "+i, blogData.get(i).getBlogLocation()); Log.i("Tag: "+i, blogData.get(i).getBlogReviews()); } recycleCards.setAdapter(new BlogAdapter(blogData,new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(getActivity(), BlogView.class); startActivity(i); } })); recycleCards.setLayoutManager(new LinearLayoutManager(getContext())); } // blogData.clear(); // blogData.addAll(dbHelper.getAllBlogData()); return root; } }
package com.quizcore.quizapp.model.entity; import lombok.Data; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import org.hibernate.annotations.UpdateTimestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.time.LocalDateTime; import java.util.UUID; @Entity @Data public class Quiz { @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") @Column(name = "id", updatable = false, nullable = false) @Type(type="uuid-char") public UUID id; @Column @Type(type="uuid-char") UUID partnerId; @Column String title; @Column String description; @Column String instructions; @Column int level; @Column String subject; @Column String category; @Column String questions; @Column int duration; @Column double payment; @Column String type; @Column int correctMarks; @Column int incorrectMarks; @Column int passingCriteria; @Column(columnDefinition = "TINYINT(1) DEFAULT 0") int videoRequired; @Column(columnDefinition = "TINYINT(1) DEFAULT 0") int paymentRequired; @CreationTimestamp LocalDateTime createdAt; @UpdateTimestamp LocalDateTime updatedAt; public int getPassingCriteria() { return passingCriteria; } public void setPassingCriteria(int passingCriteria) { this.passingCriteria = passingCriteria; } public Quiz() { } public Quiz(String title, String description, String instructions, int level, String subject, String category, int duration, double payment, String type, int correctMarks, int incorrectMarks) { this.title = title; this.description = description; this.instructions = instructions; this.level = level; this.subject = subject; this.category = category; this.duration = duration; this.payment = payment; this.type = type; this.correctMarks = correctMarks; this.incorrectMarks = incorrectMarks; } public int getCorrectMarks() { return correctMarks; } public void setCorrectMarks(int correctMarks) { this.correctMarks = correctMarks; } public int getIncorrectMarks() { return incorrectMarks; } public void setIncorrectMarks(int incorrectMarks) { this.incorrectMarks = incorrectMarks; } public String getType() { return type; } public void setType(String type) { this.type = type; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public UUID getPartnerId() { return partnerId; } public void setPartnerId(UUID partnerId) { this.partnerId = partnerId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getInstructions() { return instructions; } public void setInstructions(String instructions) { this.instructions = instructions; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getQuestions() { return questions; } public void setQuestions(String questions) { this.questions = questions; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public double getPayment() { return payment; } public void setPayment(double payment) { this.payment = payment; } }
package org.maven.ide.eclipse.ui.common.editor.internal; import org.eclipse.osgi.util.NLS; public class Messages extends NLS { private static final String BUNDLE_NAME = "org.maven.ide.eclipse.ui.common.editor.internal.messages"; //$NON-NLS-1$ public static String abstractFileEditor_errorOpeningEditor; public static String abstractFileEditor_fileChanged_message; public static String abstractFileEditor_fileChanged_title; public static String abstractFileEditor_fileDeleted_message; public static String abstractFileEditor_fileDeleted_title; public static String abstractFileEditor_noDocumentProvider; static { // initialize resource bundle NLS.initializeMessages( BUNDLE_NAME, Messages.class ); } private Messages() { } }
package day27_for_loop_examples; public class ReadStringPortion { public static void main(String[] args) { String list = "cat,car,black cat,red car"; // int i = 0; // System.out.println(list.substring(0,i+3)); // i++; // System.out.println(list.substring(i,i+3)); // System.out.println(list.substring(i,i+3)); // System.out.println(list.substring(i,i+3)); // System.out.println(list.substring(i,i+3)); for(int i= 0; i< list.length()-2; i++){ System.out.println(list.substring(i,i +3)); //if statement, if list substring(i,i+3) equals"cat" or "car" -> print car or cat found String part =list.substring(i,i+3); System.out.println("part = "+ part); if(part.equals("cat") ||part.equals("car")){ System.out.println("Car or Cat found"); } } } }
package com.company; public class Rectangle { private Point corner; private int width,length; public Rectangle(Point corner, int width, int length) { this.corner = corner; this.width = width; this.length = length; } public Point getRightCorner(){ Point MyPoint = new Point(this.corner.getX(),this.corner.getY()); MyPoint.setX(MyPoint.getX()+ this.length); // System.out.println("my X "+MyPoint.getX()+" " + this.length); MyPoint.setY(MyPoint.getY() + this.width); // System.out.println("my y "+MyPoint.getY()); return MyPoint; } public void Operation1(){ this.corner.setX(corner.getX()+1); }; public Point getCorner() { return corner; } public void setCorner(Point corner) { this.corner = corner; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } @Override public String toString() { return "("+corner.getX()+","+corner.getX()+ ")"+","+"Dimensions"+"["+width+","+length+"]"; } }
package controller; import android.util.Log; import android.widget.TextView; import com.weatherandroid.cc.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.URL; import java.sql.Date; import java.util.HashMap; import Tools.SignTools; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Created by Administrator on 2018/3/27. */ public class WeatherController { public static String url = new String("https://free-api.heweather.com/s6/weather/"); private OkHttpClient client = new OkHttpClient(); JSONArray ThreeDay = null; /** * 请求未来3天数据 */ public String GetThreeDays(String city) throws IOException { String apiname = "forecast"; String urlapi = url+apiname; HashMap<String,String> params = new HashMap<String,String>(); params.put("location",city); params.put("username", SignTools.userId); long ts = System.currentTimeMillis(); params.put("t",ts+""); String sign = SignTools.getSignature(params,SignTools.Key); params.put("sign",sign); // urlapi = urlapi+"?location="+city+"&username="+params.get("username")+"&t="+params.get("t")+"&sign="+params.get("sign"); urlapi = urlapi+"?location="+city+"&key="+SignTools.Key; return urlapi; } public String GetNow(String city) { String apiname = "now"; String urlapi = url + apiname; urlapi = urlapi + "?location=" + city + "&key=" + SignTools.Key; return urlapi; } public String GetLifeStyle(String city){ String apiname = "lifestyle"; String urlapi = url + apiname; urlapi = urlapi + "?location=" + city + "&key=" + SignTools.Key; return urlapi; } }
/** * Author: obullxl@gmail.com * Copyright (c) 2004-2014 All Rights Reserved. */ package com.github.obullxl.lang.timer; import java.util.Date; import org.slf4j.Logger; import com.github.obullxl.lang.timer.TickTimer; import com.github.obullxl.lang.utils.DateUtils; import com.github.obullxl.lang.utils.LogUtils; /** * 调度处理基类 * * @author obullxl@gmail.com * @version $Id: AbstractTickTimer.java, V1.0.1 2014年5月31日 上午11:08:28 $ */ public abstract class AbstractTickTimer implements TickTimer { public static final Logger logger = LogUtils.get(); /** 执行时间间隔(秒) */ private long refresh; /** 最近执行时间 */ private Date execTime; /** * 定时器触发 * * @see com.github.obullxl.lang.timer.TickTimer#tick() */ public final void tick() { Date now = new Date(); // 检查是否需要执行 if (!this.isMustExecute(now)) { return; } long start = now.getTime(); String clazz = this.getClass().getSimpleName(); boolean rtn = false; try { LogUtils.updateLogID(); logger.warn("[定时调度]-开始执行[{}]业务操作[{}].", this.refresh, clazz); // 业务操作 rtn = this.doTask(now); } finally { logger.warn("[定时调度]-业务操作[{}]执行完成[{}], 耗时[{}]ms.", new Object[] { clazz, rtn, (System.currentTimeMillis() - start) }); LogUtils.removeLogID(); } } /** * 执行任务 */ public abstract boolean doTask(Date now); /** * 进行业务操作检测 */ private boolean isMustExecute(Date now) { if (this.execTime == null) { this.execTime = DateUtils.toDateDW("1988-08-08"); } if (now.getTime() - this.execTime.getTime() >= this.refresh) { this.execTime.setTime(now.getTime()); return true; } return false; } // ~~~~~~~~~~~~~ 依赖注入 ~~~~~~~~~~~~~~~ // public void setRefresh(long refresh) { this.refresh = refresh; } }
package com.example.c_t_t_s; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.developer.kalert.KAlertDialog; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class LogIn extends AppCompatActivity{ //Declare all variables public EditText userEmail , userPassword; public Button loginButton; public TextView createAccount, aboutUs ,forgetPass; FirebaseAuth mFirebaseAuth; private FirebaseAuth.AuthStateListener mFireAuthStateListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_in); //Get variables values userEmail = findViewById(R.id.userEmail); userPassword = findViewById(R.id.userPassword); loginButton = findViewById(R.id.loginButton); createAccount = findViewById(R.id.createAccount); forgetPass = findViewById(R.id.forgetPassword); aboutUs = findViewById(R.id.aboutUs); //Connect to firebase mFirebaseAuth = FirebaseAuth.getInstance(); //Auto login if email is verified and signed in before FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { if(mFirebaseAuth.getCurrentUser().isEmailVerified()){ Intent i = new Intent(LogIn.this,MainActivity.class); startActivity(i); } } loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //get values form screen String email = userEmail.getText().toString(); String pwd = userPassword.getText().toString(); //check that the information entered are valid if(email.isEmpty() && pwd.isEmpty()) { new KAlertDialog(LogIn.this, KAlertDialog.ERROR_TYPE) .setTitleText("Fields are Empty!").confirmButtonColor(R.color.darkBlue) .show(); userEmail.requestFocus(); userPassword.requestFocus(); }else if(email.isEmpty()){ userEmail.setError("Please Enter Email"); userEmail.requestFocus(); }else if (!email.contains("@")){ userEmail.setError("Incorrect Email"); userEmail.requestFocus(); }else if(pwd.isEmpty()){ userPassword.setError("Please Enter Password"); userPassword.requestFocus(); }else{ mFirebaseAuth.signInWithEmailAndPassword(email,pwd).addOnCompleteListener(LogIn.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(!task.isSuccessful()){ new KAlertDialog(LogIn.this, KAlertDialog.ERROR_TYPE) .setTitleText("Account Login failed!").setContentText("Check your Login information or Create Account").confirmButtonColor(R.color.darkBlue) .show(); }else{ //checking that email is verified if(mFirebaseAuth.getCurrentUser().isEmailVerified()){ Intent i = new Intent(LogIn.this,MainActivity.class); startActivity(i); }else{ new KAlertDialog(LogIn.this, KAlertDialog.ERROR_TYPE) .setTitleText("Please Verify your Email!").confirmButtonColor(R.color.darkBlue) .show(); } } } }); } } }); //Redirect to aboutUs Screen aboutUs.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(LogIn.this, About_us.class); startActivity(i); } }); //Redirect to createAccount Screen createAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(LogIn.this, CreateAcount.class); startActivity(i); } }); //Redirect to forgetPass Screen forgetPass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(LogIn.this, ForgetPass.class); startActivity(i); } }); } }
/* * 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 Core; /** * * @author dygyb */ public class Monton { private int numFichas; private Ficha[] montonFichas; public Monton(int numFichas, Ficha[] montonFichas) { this.numFichas = numFichas; this.montonFichas = montonFichas; } public void rellenarMonton() { montonFichas = new Ficha[28]; int ficha = 0; for (int i = 0; i < 28; i++) { for (int j = 0; j < 10; j++) { switch (i) { case 0: for (int k = 0; k < 7; k++) { montonFichas[ficha].setNumIzquierda(i); montonFichas[ficha].setNumDerecha(j); ficha++; }break; case 1:for (int k = 1; k < 6; k++) { montonFichas[ficha].setNumIzquierda(i); montonFichas[ficha].setNumDerecha(j); ficha++; }break; case 2:for (int k = 2; k < 6; k++) { montonFichas[ficha].setNumIzquierda(i); montonFichas[ficha].setNumDerecha(j); ficha++; }break; case 3: for (int k = 3; k < 6; k++) { montonFichas[ficha].setNumIzquierda(i); montonFichas[ficha].setNumDerecha(j); ficha++; }break; case 4: for (int k = 4; k < 6; k++) { montonFichas[ficha].setNumIzquierda(i); montonFichas[ficha].setNumDerecha(j); ficha++; }break; case 5: for (int k = 5; k < 6; k++) { montonFichas[ficha].setNumIzquierda(i); montonFichas[ficha].setNumDerecha(j); ficha++; }break; } } } montonFichas[28].setNumIzquierda(6); montonFichas[28].setNumDerecha(6); } public int getNumFichas() { return numFichas; } }
package py.com.progweb.redsanitaria.rest; import py.com.progweb.redsanitaria.ejb.HistorialClinicoDAO; import py.com.progweb.redsanitaria.model.HistorialClinico; import javax.inject.Inject; import javax.ws.rs.*; import java.util.List; @Path(value = "/historialclinico") public class HistorialClinicoREST { @Inject private HistorialClinicoDAO historialClinicoDAO; @POST @Consumes(value = "application/json") public void create(HistorialClinico historialClinico){ historialClinicoDAO.agregar(historialClinico); } @PUT @Consumes("application/json") public void edit(@QueryParam("ci") String ci, @QueryParam("nombre") String nombre) { historialClinicoDAO.modificar(ci,nombre); } @DELETE @Path("{codhistorial}") public void remove(@PathParam("codhistorial") Integer codhistorial) { historialClinicoDAO.borrar(codhistorial); } @GET @Produces("application/json") public List<HistorialClinico> findAll() { return historialClinicoDAO.listar(); } }
package com.gideas.ui.home.user; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.gideas.AppInfo; import com.gideas.MainActivity; import com.gideas.R; import com.gideas.login.Login; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.squareup.picasso.Picasso; import com.theartofdev.edmodo.cropper.CropImage; import java.util.HashMap; import de.hdodenhof.circleimageview.CircleImageView; public class UserProfile extends AppCompatActivity { private Button UpdateAccoutSettings; private TextView back; private EditText userStatus; private TextView userName, header; private EditText inputUserName; private CircleImageView userProfileImage; private String currentUserID; private FirebaseAuth mAuth; private DatabaseReference RootRef; private static final int GalleryPick = 1; private StorageReference UserProfileImagesRef; private ProgressDialog loadingBar; private boolean firstLogIn; private Dialog dialog; private Button logout; private TextView x_back; @Override protected void onCreate(Bundle savedInstanceState) { if (AppInfo.nightModeState) setTheme(R.style.NightAppTheme); else setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_profile); mAuth = FirebaseAuth.getInstance(); currentUserID = mAuth.getCurrentUser().getUid(); RootRef = FirebaseDatabase.getInstance().getReference(); UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images"); UpdateAccoutSettings = findViewById(R.id.update_settings_button); userName = findViewById(R.id.user_name); userStatus = findViewById(R.id.set_profile_status); userProfileImage = findViewById(R.id.set_profile_image); loadingBar = new ProgressDialog(this); inputUserName = findViewById(R.id.input_user_name); header = findViewById(R.id.profile_header); back = findViewById(R.id.back_to_menu_from_profile); inputUserName.setVisibility(View.GONE); userName.setVisibility(View.VISIBLE); back.setVisibility(View.VISIBLE); UpdateAccoutSettings.setText("Сохранить"); UpdateAccoutSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UpdateSettings(); } }); LoadUserData(); userProfileImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent gallery = new Intent(); gallery.setAction(Intent.ACTION_GET_CONTENT); gallery.setType("image/*"); startActivityForResult(gallery,GalleryPick); } }); } @Override protected void onStart() { super.onStart(); header.setText("Профиль"); if (getIntent().getBooleanExtra("FirstLogin", false)) { inputUserName.setVisibility(View.VISIBLE); userName.setVisibility(View.GONE); back.setVisibility(View.GONE); firstLogIn = true; UpdateAccoutSettings.setText("Завершить регистрацию"); header.setText("Регистрация"); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode==GalleryPick && resultCode==RESULT_OK && data!=null) { Uri ImageUri = data.getData(); CropImage.activity(ImageUri) .setAspectRatio(1, 1) .start(this); } if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { loadingBar.setTitle("Set Profile Image"); loadingBar.setMessage("Please wait, your profile image is updating..."); loadingBar.setCanceledOnTouchOutside(false); loadingBar.show(); Uri resultUri=result.getUri();//This contains the cropped image final StorageReference filePath=UserProfileImagesRef.child(currentUserID+".jpg"); UploadTask uploadTask=filePath.putFile(resultUri); Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()) { throw task.getException(); } // Continue with the task to get the download URL return filePath.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()) { Uri downloadUri = task.getResult(); Toast.makeText(UserProfile.this, "Successfully uploaded!!!", Toast.LENGTH_SHORT).show(); if (downloadUri != null) { String downloadUrl = downloadUri.toString(); RootRef.child("Users").child(currentUserID).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { loadingBar.dismiss(); if(!task.isSuccessful()){ String error=task.getException().toString(); Toast.makeText(UserProfile.this,"Error : "+error,Toast.LENGTH_LONG).show(); }else{ } } }); } } else { // Handle failures // ... Toast.makeText(UserProfile.this,"Error",Toast.LENGTH_LONG).show(); loadingBar.dismiss(); } } }); } } } private void LoadUserData() { RootRef.child("Users").child(currentUserID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(dataSnapshot.exists() && dataSnapshot.hasChild("name") && dataSnapshot.hasChild("status") && dataSnapshot.hasChild("image")) { userName.setText(dataSnapshot.child("name").getValue().toString()); inputUserName.setText(dataSnapshot.child("name").getValue().toString()); userStatus.setText(dataSnapshot.child("status").getValue().toString()); String retrieveProfileImage = dataSnapshot.child("image").getValue().toString(); Picasso.get().load(retrieveProfileImage).into(userProfileImage); //ui.ava = dataSnapshot.child("image").getValue().toString(); } else if (dataSnapshot.exists() && dataSnapshot.hasChild("name") && dataSnapshot.hasChild("status") ){ userName.setText(dataSnapshot.child("name").getValue().toString()); userStatus.setText(dataSnapshot.child("status").getValue().toString()); } else if (firstLogIn == true && dataSnapshot.exists() && dataSnapshot.hasChild("image")) { String retrieveProfileImage = dataSnapshot.child("image").getValue().toString(); Picasso.get().load(retrieveProfileImage).into(userProfileImage); } else { } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void UpdateSettings() { String setUserName = inputUserName.getText().toString(); String setUserStatus = userStatus.getText().toString(); if(TextUtils.isEmpty(setUserStatus)) { setUserStatus = " "; } if(TextUtils.isEmpty(setUserName)) { Toast.makeText(this, "Введите имя", Toast.LENGTH_SHORT).show(); } else { HashMap<String, String>profile = new HashMap<>(); profile.put("uid", currentUserID); profile.put("name", setUserName); profile.put("status",setUserStatus); RootRef.child("Users").child(currentUserID).setValue(profile).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) Toast.makeText(UserProfile.this, "Успешно!", Toast.LENGTH_SHORT).show(); else { String ex = task.getException().getMessage(); Toast.makeText(UserProfile.this, "Ошибка "+ex, Toast.LENGTH_SHORT).show(); } } }); if(firstLogIn) { Intent g = new Intent(UserProfile.this, MainActivity.class); g.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK); g.putExtra("FirstLogin", true); startActivity(g); finish(); } } } public void BackToMenu(View view) { super.onBackPressed(); finish(); } public void SignOut(View view) { dialog = new Dialog(this); dialog.setContentView(R.layout.logout_card); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); logout = dialog.findViewById(R.id.logout); x_back = dialog.findViewById(R.id.logout_x); x_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAuth.signOut(); Intent g = new Intent(UserProfile.this, Login.class); g.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(g); finish(); } }); dialog.show(); } }
package com.safeandsound.app.safeandsound.view; import android.content.Intent; import android.graphics.Color; import android.icu.text.DateFormat; import android.icu.text.SimpleDateFormat; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.widget.TextView; import android.widget.Toast; import com.safeandsound.app.safeandsound.model.AppConfig; import com.safeandsound.app.safeandsound.controller.ConnectionFeed; import com.safeandsound.app.safeandsound.controller.ExceptionHandler; import com.safeandsound.app.safeandsound.R; import com.safeandsound.app.safeandsound.model.database.SQLiteHandler; import com.safeandsound.app.safeandsound.controller.SessionManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.HashMap; import java.util.concurrent.ExecutionException; /** * Created by louisapabst, Dominic on 16.04.17. */ public class WindowActivity extends FragmentActivity { private SQLiteHandler db; private SessionManager session; private String result; private int value; private String room; private long timestamp; private static int oldValue = 10; private static String oldDate; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this)); setContentView(R.layout.window); // session manager session = new SessionManager(getApplicationContext()); //Android interne Datenbank db = new SQLiteHandler(getApplicationContext()); if (!session.isLoggedIn()) { logout(); } showWindowData(); } public void showWindowData(){ try { URL urlObj = new URL(AppConfig.URL_WINDOW); result = new ConnectionFeed().execute(urlObj.toString()).get(); }catch (MalformedURLException e){ e.printStackTrace(); }catch (InterruptedException e){ e.printStackTrace(); }catch (ExecutionException e){ e.printStackTrace(); } try{ //JSONObject jsonResponse = new JSONObject(re); JSONArray jsonMainNode = new JSONArray(result); for(int i = 0; i < jsonMainNode.length(); i++){ JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); value = jsonChildNode.optInt("value"); room = jsonChildNode.optString("room"); timestamp = jsonChildNode.optLong("timestamp"); } } catch (JSONException e){ Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show(); } TextView roomStatus = (TextView)findViewById(R.id.windowStatusOutput); TextView roomName = (TextView)findViewById(R.id.windowText); roomName.setText(room); if(value == 1){ roomStatus.setText(R.string.windowClosed); roomStatus.setTextColor(Color.RED); }else if(value == 0){ roomStatus.setText(R.string.windowOpen); roomStatus.setTextColor(Color.GREEN); }else{ roomStatus.setText(""); } if(oldValue != value){ showLastStatusChanged(timestamp); oldValue = value; } TextView lastStatusChange = (TextView)findViewById(R.id.lastChangeOutput); lastStatusChange.setText(oldDate); } public void showLastStatusChanged(Long timestamp){ DateFormat sdf = new SimpleDateFormat("dd.MM.yy HH:mm:ss"); Date netDate = (new Date(timestamp)); String dateFormatted = sdf.format(netDate).toString(); oldDate = dateFormatted.toString(); } @Override public void onBackPressed() { super.onBackPressed(); this.finish(); } /* public void addWindow(View view){ //Damit die hinzugefügten Elemente persistent werden SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Set<String> imageViewSet = prefs.getStringSet("saved_imageViews",null); Set<String> textViewSet = prefs.getStringSet("saved_textViews",null); Set<String> layoutSet = prefs.getStringSet("saved_layouts",null); if(imageViewSet == null){ imageViewSet = new HashSet<String>(); } if(textViewSet == null){ textViewSet = new HashSet<String>(); } if(layoutSet == null){ layoutSet = new HashSet<String>(); } //Umrechnung von gewünschten dip zu pixels des Handys int dip70 = 70; int dip2 = 2; DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); final float scale = metrics.density; int pixels70 = (int) (dip70 * scale + 0.5f); int pixels2 = (int) (dip2 * scale + 0.5f); //Initialisierung des LinearLayouts des neuen Windows LinearLayout linearLayout = new LinearLayout(this); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.setBackgroundColor(Color.RED); LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,pixels70); LLParams.setMargins(pixels2, pixels2, pixels2, pixels2); linearLayout.setLayoutParams(LLParams); layoutSet.add("LinearLayout"); //Initialisierung des ImageView mit WindowActivity-Icon des neuen Windows ImageView imageView = new ImageView(this); imageView.setBackgroundColor(Color.WHITE); imageView.setImageResource(R.drawable.ic_window); LinearLayout.LayoutParams IVParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f); imageView.setLayoutParams(IVParams); imageViewSet.add("ImageView_WindowIcon"); //Initialisierung des TextView mit Area/Sensor Name des neuen Windows TextView textView_WindowName = new TextView(this); textView_WindowName.setBackgroundColor(Color.WHITE); textView_WindowName.setTextSize(16); textView_WindowName.setThenText("Elternschlafzimmer"); textView_WindowName.setGravity(Gravity.CENTER | Gravity.LEFT); LinearLayout.LayoutParams TVParams = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT, 3f); textView_WindowName.setLayoutParams(TVParams); textViewSet.add("TextView_SensorName"); // id="@+id/oxygenText", gravity="center_vertical|left", textAlignment="gravity" /> //Initialisierung des TextView mit Sensor Status des neuen Windows TextView textView_WindowStatus = new TextView(this); textView_WindowStatus.setBackgroundColor(Color.WHITE); textView_WindowStatus.setTextSize(16); textView_WindowStatus.setThenText("open"); textView_WindowStatus.setGravity(Gravity.CENTER | Gravity.RIGHT); textView_WindowStatus.setLayoutParams(TVParams); textViewSet.add("TextView_SensorStatus"); //layout_width="0dip", layout_height="match_parent", layout_weight="3", // id="@+id/oxygenOutputText" //Initialisierung des ImageView mit NextPage-Icon des neuen Windows ImageView imageView_Arrow = new ImageView(this); imageView_Arrow.setBackgroundColor(Color.WHITE); imageView_Arrow.setImageResource(R.drawable.ic_next_page); imageView_Arrow.setLayoutParams(IVParams); imageViewSet.add("ImageView_NextPageIcon"); //layout_weight="1" //Hinzufügen des LinearLayouts, den zwei TextViews und den zwei ImageViews zu dem default // erstellten LinearLayouts windowButtonLayout LinearLayout ll = (LinearLayout)findViewById(R.id.windowButtonLayout); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); ll.addView(linearLayout); linearLayout.addView(imageView); linearLayout.addView(textView_WindowName); linearLayout.addView(textView_WindowStatus); linearLayout.addView(imageView_Arrow); prefs.edit().putStringSet("saved_imageViews", imageViewSet).commit(); prefs.edit().putStringSet("saved_textViews", textViewSet).commit(); prefs.edit().putStringSet("saved_layouts", layoutSet).commit(); }*/ //Meldet den aktuellen Nutzer ab private void logout() { session.setLogin(false); HashMap<String, String> user = db.getUserDetails(); db.logOutUser(user.get("user_id")); // Zur LogInActivity Activity zurück springen Intent intent = new Intent(WindowActivity.this, LogInActivity.class); startActivity(intent); } }
package com.tencent.mm.modelcdntran; class c$5 implements Runnable { final /* synthetic */ c dPb; final /* synthetic */ int dPc; final /* synthetic */ i dPd; c$5(c cVar, int i, i iVar) { this.dPb = cVar; this.dPc = i; this.dPd = iVar; } public final void run() { if (this.dPc != -1) { this.dPb.dOX.put(this.dPd.field_mediaId, Integer.valueOf(this.dPc)); } this.dPb.dOU.add(this.dPd.field_mediaId); this.dPb.dOV.put(this.dPd.field_mediaId, this.dPd); this.dPb.bH(false); } public final String toString() { return super.toString() + "|addRecvTask"; } }
package com.tt.miniapp.manager.basebundle; import android.app.Application; import android.content.Context; import android.text.TextUtils; import com.tt.miniapp.event.BaseBundleEventHelper; import com.tt.miniapphost.AppBrandLogger; import com.tt.miniapphost.AppbrandContext; import com.tt.miniapphost.util.AppbrandUtil; import com.tt.miniapphost.util.CharacterUtils; import com.tt.miniapphost.util.IOUtils; import java.io.File; import java.io.IOException; import java.util.Iterator; import org.json.JSONException; import org.json.JSONObject; public class BaseBundleFileManager { private static boolean checkFileComplete(String paramString, File paramFile, BaseBundleEventHelper.BaseBundleEvent paramBaseBundleEvent) { JSONObject jSONObject; File file1; File file2 = new File(paramFile, "jssdkcheck.json"); boolean bool = file2.exists(); boolean bool1 = false; if (!bool) return false; String str = IOUtils.readString(file2.getAbsolutePath(), "utf-8"); file2 = null; bool = true; try { JSONObject jSONObject1 = new JSONObject(str); jSONObject = jSONObject1; } catch (JSONException jSONException) { StringBuilder stringBuilder1 = new StringBuilder(); stringBuilder1.append((String)jSONObject); stringBuilder1.append("check file json is invalid"); paramBaseBundleEvent.appendLog(stringBuilder1.toString()); bool = false; file1 = file2; } if (bool) { Iterator<String> iterator = file1.keys(); while (iterator.hasNext()) { str = iterator.next(); long l = file1.optLong(str); if (!checkFileLength(paramFile.getAbsolutePath(), str, l)) { bool = bool1; break; } } } StringBuilder stringBuilder = new StringBuilder("check file folder result: "); stringBuilder.append(bool); paramBaseBundleEvent.appendLog(stringBuilder.toString()); return bool; } private static boolean checkFileLength(String paramString1, String paramString2, long paramLong) { File file = new File(paramString1, paramString2); return !file.exists() ? false : ((file.length() == paramLong)); } public static File getBundleFolderFile(Context paramContext, String paramString) { File file = new File(AppbrandUtil.getAppbrandBaseFile(paramContext).getAbsolutePath(), paramString); if (!file.exists()) file.mkdir(); return file; } public static File getBundleServiceFile(Context paramContext, String paramString) { File file = getBundleFolderFile(paramContext, paramString); if (!file.exists()) file.mkdir(); file = new File(file, "__dev__"); if (!file.exists()) file.mkdir(); return file; } public static int getBundleVersion(Context paramContext, String paramString) { try { return Integer.valueOf(IOUtils.readString((new File(getBundleServiceFile(paramContext, paramString), "basebundlecheck")).getAbsolutePath(), "utf-8")).intValue(); } catch (Exception exception) { AppBrandLogger.e("BaseBundleFileManager", new Object[] { exception }); return -1; } } public static File getLatestBaseBundleFile() { return new File(AppbrandUtil.getAppServiceDir((Context)AppbrandContext.getInst().getApplicationContext()), "latest_basebundle_version"); } public static long getLatestBaseBundleVersion() { try { File file = getLatestBaseBundleFile(); if (!file.exists()) return -1L; String str = IOUtils.readString(file.getAbsolutePath(), "utf-8"); return TextUtils.isEmpty(str) ? -1L : Long.valueOf(CharacterUtils.replaceBlank(str)).longValue(); } catch (Exception exception) { AppBrandLogger.e("BaseBundleFileManager", new Object[] { exception }); return -1L; } } public static File getTempBundleFolderFile(Context paramContext, String paramString) { File file = new File(AppbrandUtil.getAppbrandBaseFile(paramContext).getAbsolutePath(), paramString); if (!file.exists()) file.mkdir(); return file; } public static File getTempBundleServiceFile(Context paramContext, String paramString) { File file = getTempBundleFolderFile(paramContext, paramString); if (!file.exists()) file.mkdir(); file = new File(file, "__dev__"); if (!file.exists()) file.mkdir(); return file; } public static File getTempBundleZipFile(Context paramContext, String paramString) { File file = getTempBundleFolderFile(paramContext, paramString); if (!file.exists()) file.mkdir(); file = new File(file, "__dev__.zip"); if (!file.exists()) try { file.createNewFile(); return file; } catch (IOException iOException) { AppBrandLogger.e("BaseBundleFileManager", new Object[] { iOException }); } return file; } public static long renameFileToBaseBundle(Context paramContext, long paramLong, String paramString, boolean paramBoolean, BaseBundleEventHelper.BaseBundleEvent paramBaseBundleEvent) { // Byte code: // 0: ldc com/tt/miniapp/manager/basebundle/BaseBundleFileManager // 2: monitorenter // 3: invokestatic getLatestBaseBundleVersion : ()J // 6: lload_1 // 7: lcmp // 8: iflt -> 28 // 11: iload #4 // 13: ifne -> 28 // 16: aload #5 // 18: ldc 'current baseBundle version bigger or equals than baseBundle version' // 20: invokevirtual appendLog : (Ljava/lang/String;)V // 23: ldc com/tt/miniapp/manager/basebundle/BaseBundleFileManager // 25: monitorexit // 26: lconst_0 // 27: lreturn // 28: aload_0 // 29: aload_3 // 30: invokestatic getBundleFolderFile : (Landroid/content/Context;Ljava/lang/String;)Ljava/io/File; // 33: astore #8 // 35: new java/io/File // 38: dup // 39: aload_0 // 40: invokestatic getAppServiceDir : (Landroid/content/Context;)Ljava/io/File; // 43: lload_1 // 44: invokestatic convertVersionCodeToStr : (J)Ljava/lang/String; // 47: invokespecial <init> : (Ljava/io/File;Ljava/lang/String;)V // 50: astore_0 // 51: aload #5 // 53: ldc 'start rename folder to __dev__' // 55: invokevirtual appendLog : (Ljava/lang/String;)V // 58: aload_0 // 59: invokevirtual exists : ()Z // 62: ifne -> 70 // 65: aload_0 // 66: invokevirtual mkdirs : ()Z // 69: pop // 70: new java/io/File // 73: dup // 74: aload #8 // 76: ldc '__dev__' // 78: invokespecial <init> : (Ljava/io/File;Ljava/lang/String;)V // 81: aload_0 // 82: invokevirtual renameTo : (Ljava/io/File;)Z // 85: istore #6 // 87: goto -> 100 // 90: aload #5 // 92: ldc 'rename folder fail to __dev__' // 94: invokevirtual appendLog : (Ljava/lang/String;)V // 97: iconst_0 // 98: istore #6 // 100: iload #6 // 102: istore #7 // 104: iload #6 // 106: ifeq -> 127 // 109: iload #6 // 111: istore #7 // 113: iload #4 // 115: ifne -> 127 // 118: aload_3 // 119: aload_0 // 120: aload #5 // 122: invokestatic checkFileComplete : (Ljava/lang/String;Ljava/io/File;Lcom/tt/miniapp/event/BaseBundleEventHelper$BaseBundleEvent;)Z // 125: istore #7 // 127: iload #7 // 129: ifne -> 144 // 132: aload #5 // 134: ldc 'rename folder fail' // 136: invokevirtual appendLog : (Ljava/lang/String;)V // 139: ldc com/tt/miniapp/manager/basebundle/BaseBundleFileManager // 141: monitorexit // 142: lconst_0 // 143: lreturn // 144: aload #5 // 146: ldc 'rename folder success' // 148: invokevirtual appendLog : (Ljava/lang/String;)V // 151: ldc com/tt/miniapp/manager/basebundle/BaseBundleFileManager // 153: monitorexit // 154: lload_1 // 155: lreturn // 156: astore_0 // 157: ldc com/tt/miniapp/manager/basebundle/BaseBundleFileManager // 159: monitorexit // 160: aload_0 // 161: athrow // 162: astore #8 // 164: goto -> 90 // Exception table: // from to target type // 3 11 156 finally // 16 23 156 finally // 28 58 156 finally // 58 70 162 finally // 70 87 162 finally // 90 97 156 finally // 118 127 156 finally // 132 139 156 finally // 144 151 156 finally } private static void tryUnzipBaseBundle(BaseBundleEventHelper.BaseBundleEvent paramBaseBundleEvent, String paramString1, String paramString2, File paramFile) { try { StringBuilder stringBuilder = new StringBuilder("unzip"); stringBuilder.append(paramString1); paramBaseBundleEvent.appendLog(stringBuilder.toString()); IOUtils.unZipFolder(paramFile.getAbsolutePath(), paramString2); return; } catch (Exception exception) { AppBrandLogger.e("BaseBundleFileManager", new Object[] { "unzip exception", exception }); StringBuilder stringBuilder = new StringBuilder("retry unzip fail"); stringBuilder.append(paramString1); paramBaseBundleEvent.appendLog(stringBuilder.toString()); return; } } public static long unZipAssetsBundle(Context paramContext, String paramString1, String paramString2, BaseBundleEventHelper.BaseBundleEvent paramBaseBundleEvent, boolean paramBoolean) { File file = getTempBundleZipFile(paramContext, paramString2); try { paramBaseBundleEvent.appendLog("start copy buildIn baseBundle to temp dir"); IOUtils.copyAssets(paramContext, paramString1, file.getAbsolutePath()); if (file.exists()) { long l = unZipFileToBundle(paramContext, file, "buildin_bundle", paramBoolean, paramBaseBundleEvent); IOUtils.delete(getTempBundleFolderFile(paramContext, "buildin_bundle")); paramBaseBundleEvent.appendLog("delete temp baseBundle dir"); return l; } IOUtils.delete(getTempBundleFolderFile(paramContext, "buildin_bundle")); paramBaseBundleEvent.appendLog("delete temp baseBundle dir"); } catch (Exception exception) { AppBrandLogger.e("BaseBundleFileManager", new Object[] { exception }); paramBaseBundleEvent.appendLog("unZipBuildInBaseBundle exception", exception); IOUtils.delete(getTempBundleFolderFile(paramContext, "buildin_bundle")); paramBaseBundleEvent.appendLog("delete temp baseBundle dir"); } finally {} return 0L; } public static long unZipFileToBundle(Context paramContext, File paramFile, String paramString, boolean paramBoolean, BaseBundleEventHelper.BaseBundleEvent paramBaseBundleEvent) { // Byte code: // 0: ldc com/tt/miniapp/manager/basebundle/BaseBundleFileManager // 2: monitorenter // 3: aload_1 // 4: invokevirtual exists : ()Z // 7: istore #6 // 9: iload #6 // 11: ifne -> 19 // 14: ldc com/tt/miniapp/manager/basebundle/BaseBundleFileManager // 16: monitorexit // 17: lconst_0 // 18: lreturn // 19: aload_0 // 20: aload_2 // 21: invokestatic getBundleFolderFile : (Landroid/content/Context;Ljava/lang/String;)Ljava/io/File; // 24: astore #10 // 26: new java/lang/StringBuilder // 29: dup // 30: ldc_w 'start unzip' // 33: invokespecial <init> : (Ljava/lang/String;)V // 36: astore #11 // 38: aload #11 // 40: aload_2 // 41: invokevirtual append : (Ljava/lang/String;)Ljava/lang/StringBuilder; // 44: pop // 45: aload #4 // 47: aload #11 // 49: invokevirtual toString : ()Ljava/lang/String; // 52: invokevirtual appendLog : (Ljava/lang/String;)V // 55: aload #4 // 57: aload_2 // 58: aload #10 // 60: invokevirtual getAbsolutePath : ()Ljava/lang/String; // 63: aload_1 // 64: invokestatic tryUnzipBaseBundle : (Lcom/tt/miniapp/event/BaseBundleEventHelper$BaseBundleEvent;Ljava/lang/String;Ljava/lang/String;Ljava/io/File;)V // 67: iload_3 // 68: ifne -> 328 // 71: aload_2 // 72: new java/io/File // 75: dup // 76: aload #10 // 78: ldc '__dev__' // 80: invokespecial <init> : (Ljava/io/File;Ljava/lang/String;)V // 83: aload #4 // 85: invokestatic checkFileComplete : (Ljava/lang/String;Ljava/io/File;Lcom/tt/miniapp/event/BaseBundleEventHelper$BaseBundleEvent;)Z // 88: istore #7 // 90: iload #7 // 92: istore #6 // 94: iload #7 // 96: ifne -> 161 // 99: iconst_0 // 100: istore #5 // 102: iload #7 // 104: istore #6 // 106: iload #5 // 108: iconst_3 // 109: if_icmpgt -> 161 // 112: iload #7 // 114: istore #6 // 116: iload #7 // 118: ifne -> 161 // 121: aload #4 // 123: aload_2 // 124: aload #10 // 126: invokevirtual getAbsolutePath : ()Ljava/lang/String; // 129: aload_1 // 130: invokestatic tryUnzipBaseBundle : (Lcom/tt/miniapp/event/BaseBundleEventHelper$BaseBundleEvent;Ljava/lang/String;Ljava/lang/String;Ljava/io/File;)V // 133: aload_2 // 134: new java/io/File // 137: dup // 138: aload #10 // 140: ldc '__dev__' // 142: invokespecial <init> : (Ljava/io/File;Ljava/lang/String;)V // 145: aload #4 // 147: invokestatic checkFileComplete : (Ljava/lang/String;Ljava/io/File;Lcom/tt/miniapp/event/BaseBundleEventHelper$BaseBundleEvent;)Z // 150: istore #7 // 152: iload #5 // 154: iconst_1 // 155: iadd // 156: istore #5 // 158: goto -> 102 // 161: iload #6 // 163: ifne -> 207 // 166: new java/lang/StringBuilder // 169: dup // 170: invokespecial <init> : ()V // 173: astore_0 // 174: aload_0 // 175: aload_2 // 176: invokevirtual append : (Ljava/lang/String;)Ljava/lang/StringBuilder; // 179: pop // 180: aload_0 // 181: ldc_w 'clear dir' // 184: invokevirtual append : (Ljava/lang/String;)Ljava/lang/StringBuilder; // 187: pop // 188: aload #4 // 190: aload_0 // 191: invokevirtual toString : ()Ljava/lang/String; // 194: invokevirtual appendLog : (Ljava/lang/String;)V // 197: aload #10 // 199: invokestatic clearDir : (Ljava/io/File;)V // 202: ldc com/tt/miniapp/manager/basebundle/BaseBundleFileManager // 204: monitorexit // 205: lconst_0 // 206: lreturn // 207: new java/lang/StringBuilder // 210: dup // 211: invokespecial <init> : ()V // 214: astore #10 // 216: aload #10 // 218: aload_2 // 219: invokevirtual append : (Ljava/lang/String;)Ljava/lang/StringBuilder; // 222: pop // 223: aload #10 // 225: ldc_w 'baseBundle unzip success' // 228: invokevirtual append : (Ljava/lang/String;)Ljava/lang/StringBuilder; // 231: pop // 232: aload #4 // 234: aload #10 // 236: invokevirtual toString : ()Ljava/lang/String; // 239: invokevirtual appendLog : (Ljava/lang/String;)V // 242: aload_0 // 243: aload_2 // 244: invokestatic getBundleVersion : (Landroid/content/Context;Ljava/lang/String;)I // 247: i2l // 248: lstore #8 // 250: new java/lang/StringBuilder // 253: dup // 254: invokespecial <init> : ()V // 257: astore #10 // 259: aload #10 // 261: aload_2 // 262: invokevirtual append : (Ljava/lang/String;)Ljava/lang/StringBuilder; // 265: pop // 266: aload #10 // 268: ldc_w 'get version:' // 271: invokevirtual append : (Ljava/lang/String;)Ljava/lang/StringBuilder; // 274: pop // 275: aload #10 // 277: lload #8 // 279: invokevirtual append : (J)Ljava/lang/StringBuilder; // 282: pop // 283: aload #4 // 285: aload #10 // 287: invokevirtual toString : ()Ljava/lang/String; // 290: invokevirtual appendLog : (Ljava/lang/String;)V // 293: aload_0 // 294: lload #8 // 296: aload_2 // 297: iload_3 // 298: aload #4 // 300: invokestatic renameFileToBaseBundle : (Landroid/content/Context;JLjava/lang/String;ZLcom/tt/miniapp/event/BaseBundleEventHelper$BaseBundleEvent;)J // 303: lstore #8 // 305: aload_1 // 306: invokevirtual delete : ()Z // 309: pop // 310: ldc com/tt/miniapp/manager/basebundle/BaseBundleFileManager // 312: monitorexit // 313: lload #8 // 315: lreturn // 316: astore_0 // 317: ldc com/tt/miniapp/manager/basebundle/BaseBundleFileManager // 319: monitorexit // 320: goto -> 325 // 323: aload_0 // 324: athrow // 325: goto -> 323 // 328: iconst_1 // 329: istore #6 // 331: goto -> 161 // Exception table: // from to target type // 3 9 316 finally // 19 67 316 finally // 71 90 316 finally // 121 152 316 finally // 166 202 316 finally // 207 310 316 finally } public static void updateLatestBaseBundleFile(Context paramContext, long paramLong) { Application application; Context context = paramContext; if (paramContext == null) { application = AppbrandContext.getInst().getApplicationContext(); StringBuilder stringBuilder1 = new StringBuilder("AppbrandContext:"); stringBuilder1.append(application); AppBrandLogger.d("BaseBundleFileManager", new Object[] { stringBuilder1.toString() }); } File file = getLatestBaseBundleFile(); StringBuilder stringBuilder = new StringBuilder("context:"); stringBuilder.append(application); AppBrandLogger.d("BaseBundleFileManager", new Object[] { stringBuilder.toString() }); if (application != null) try { String str = file.getAbsolutePath(); StringBuilder stringBuilder1 = new StringBuilder(); stringBuilder1.append(paramLong); IOUtils.writeStringToFile(str, stringBuilder1.toString(), "UTF-8"); return; } catch (Exception exception) { return; } } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\manager\basebundle\BaseBundleFileManager.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
import java.awt.image.SampleModel; import java.util.concurrent.CompletionException; import static java.lang.System.exit; import static java.lang.System.out; public class Povocoder { // Processing SEQUENCE size (100 msec with 44100Hz samplerate) final static int SEQUENCE = StdAudio.SAMPLE_RATE/10; // Overlapping size (20 msec) final static int OVERLAP = SEQUENCE/5 ; // Best OVERLAP offset seeking window (15 msec) final static int SEEK_WINDOW = 3*OVERLAP/4; public static void main(String[] args) { if (args.length < 2) { System.out.println("usage: povocoder input.wav freqScale\n"); exit(1); } try { String wavInFile = args[0]; double freqScale = Double.valueOf(args[1]); String outputFile= wavInFile.split("\\.")[0] + "_" + freqScale +"_"; // Open input .wav file double[] inputWav = StdAudio.read(wavInFile); // Resample test double[] newPitchWav = resample(inputWav, freqScale); StdAudio.save(outputFile+"Resampled.wav", newPitchWav); // Simple dilatation double[] outputWav = vocodeSimple(newPitchWav, 1.0/freqScale); StdAudio.save(outputFile+"Simple.wav", outputWav); // Simple dilatation with overlaping outputWav = vocodeSimpleOver(newPitchWav, 1.0/freqScale); StdAudio.save(outputFile+"SimpleOver.wav", outputWav); // Simple dilatation with overlaping and maximum cross correlation search //outputWav = vocodeSimpleOverCross(newPitchWav, 1.0/freqScale); //StdAudio.save(outputFile+"SimpleOverCross.wav", outputWav); //joue(outputWav); // Some echo above all //double[] outputWav = echo(outputWav, 1000, 0.7); //StdAudio.save(outputFile+"SimpleOverCrossEcho.wav", outputWav); } catch (Exception e) { System.out.println("Error: "+ e.toString()); } } static double[] resample(double[] input,double freqScale) { double scale =1; if( freqScale > 1) { scale = (freqScale - 1)/freqScale; scale = 1 - scale; } if( freqScale < 1) { scale = (freqScale + 1)/freqScale; scale = 1 - scale; if(scale < 0) { scale *= -1; } } System.out.println("freqScale: "+freqScale); System.out.println("scale:"+ scale); int iOut = 0; double counter = 0; for (int i=0; i< input.length; i++) { while(counter > 1) { iOut++; counter-=1; } counter += scale; } double[] output = new double[iOut+1]; System.out.println("input.length: "+input.length); System.out.println("iOut+1: "+ (iOut+1)); System.out.println("input.length / 44100: "+ (input.length / StdAudio.SAMPLE_RATE)); System.out.println("(iOut+1) / 44100: "+ ((iOut+1) / StdAudio.SAMPLE_RATE)); counter=0; iOut = 0; for (int i=0; i< input.length; i++) { while(counter > 1) { output[iOut] = input[i]; counter-=1; iOut++; } counter += scale; } System.out.println(""); System.out.println(""); System.out.println(""); return output; } static double map(double x, double in_min, double in_max, double out_min, double out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } public static double[] fadeIn(double[] input) { int maxI = input.length; for (int i = 0 ; i < maxI ; i++) { double multiplier = map(i, 0, maxI, 0.0, 1.0); input[i] = input[i] * multiplier; } return input; } public static double[] fadeOut(double[] input) { int maxI = input.length; for (int i = 0 ; i < maxI ; i++) { double multiplier = map(i, 0, maxI, 1.0, 0.0); input[i] = input[i] * multiplier; } return input; } public static double[] vocodeSimple(double[] input, double timeScale){ // double seqDuration = 0.01; //ms int seqSize = SEQUENCE;//(int)(StdAudio.SAMPLE_RATE * seqDuration); int jumpSize = (int)(seqSize * timeScale); double ratio = (double)jumpSize / (double)seqSize; System.out.println("ratio: "+ ratio); System.out.println("seqSize len: "+ ((double)seqSize / StdAudio.SAMPLE_RATE )); System.out.println("jumpSize len: "+ ((double)jumpSize / StdAudio.SAMPLE_RATE )); int length = (int)((seqSize) * (input.length / jumpSize)); System.out.println("input.length / 44100: "+ (input.length / StdAudio.SAMPLE_RATE)); System.out.println("length / 44100: "+ (length / StdAudio.SAMPLE_RATE)); double[] output = new double[length]; if(ratio > 1) { int i2 = 0; for (int i = 0; i < length; i+=seqSize) { for (int j = 0; j < seqSize; j++) { output[i+j] = input[ Math.min(i2+j,input.length-1) ]; } i2+= jumpSize; } return output; } else if (ratio < 1) { int i2 = 0; for (int i = 0; i < length; i+=seqSize) { for (int j = 0; j < seqSize; j++) { output[i+j] = input[ Math.min(i2+j,input.length-1) ]; } int left = jumpSize - seqSize; for (int j = 0; j < left; j++) { output[i+j+seqSize] = input[ Math.min(i2+j+seqSize,input.length-1) ]; } i2+= jumpSize; } return output; } else { return output; } } static double[] vocodeSimpleOver(double[] input, double timeScale){ int seqSize = SEQUENCE; //(int)(StdAudio.SAMPLE_RATE * seqDuration); int fadeSize = OVERLAP; //(int)(StdAudio.SAMPLE_RATE * fadeDuration); int jumpSize = (int)(seqSize * timeScale); int length = (int)((seqSize - fadeSize) * (input.length / jumpSize)); double[] output = new double[length]; if(timeScale > 1) { int i2 = 0; double[] fade = new double[fadeSize]; for (int i = 0; i < length; i += seqSize - fadeSize) { //Pour chaque séquence du fichier // -------------------------------Fade In------------------------------ double[] fade2 = new double[fadeSize]; for (int j = 0; j < fade2.length; j++) { //On rempli le tableau des valeurs a fade fade2[j] = input[Math.min(i2 + j, input.length-1)]; } fade2 = fadeIn(fade2); //On applique l'effet double[] newFade = new double[fadeSize]; for (int j = 0; j < fadeSize; j++) { // On mixe les deux valeurs double balance = map(j, 0, fadeSize, 0., 1.); newFade[j] = (fade[j] * (1-balance) + fade2[j] * balance) / 2; //System.out.println(Double.toString(fade[j]) + " -- " + Double.toString(fade2[j]) + " -- " + Double.toString((fade[j] + fade2[j]) / 2)); //newFade[j] = (fade[j] + fade2[j]) / 2; } for (int j = 0; j < fadeSize; j++) { //On remplace les valeurs dans le son final output[i+j] = newFade[j]; } // -------------------------------Milieu------------------------------ for (int j = fadeSize; j < seqSize - fadeSize; j++) { //Pour chaque valeur dans la séquence output[i+j] = input[Math.min(i2 + j + fadeSize, input.length-1)]; //Min dans le cas ou on dépasse la fin du tableau } // -------------------------------Fade Out------------------------------ for (int j = 0; j < fadeSize; j++) { //On rempli le tableau des valeurs a fade fade[j] = input[Math.min(i2 + j + seqSize - fadeSize, input.length-1)]; } fade = fadeOut(fade); //On applique l'effet i2 += jumpSize; //On jump } return output; } else if (timeScale < 1) { return output; } else { return output; } } static double[] echo(double[] input, double delayMS, double attn) { if(attn <= 0) { return input; } int padding = StdAudio.SAMPLE_RATE * (int)delayMS / 1000; int outputLenght = input.length + padding; double[] output = new double[outputLenght]; System.out.println("Echo output len: "+ outputLenght); //Peut pas faire output = input car sa copie aussi la taille for (int i=0;i<input.length; i++) { output[i] = input[i]; } for (int i=0; i< input.length; i++ ) { int o = i+padding; //Math.min(i+padding , output.length-1); output[o] = (output[o] + input[i] * attn) / 2; } return output; } }
package com.zaeem.mychat; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class StartActivity extends AppCompatActivity { @OnClick(R.id.StartActivity_create_account_bt) public void create_account(View v){ Intent intent = new Intent(this,RegisterActivity.class); startActivity(intent); } @OnClick(R.id.StartActivity_Already_Account_bt) public void Already_accoutn(View v){ Intent intent = new Intent(this,LoginActivity.class); startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start); ButterKnife.bind(this); } }
package com.example.covid_19; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.ProgressDialog; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.EditText; import android.widget.SearchView; import android.widget.Toast; import com.example.covid_19.model.CountriesItem; import com.example.covid_19.model.Response; import com.example.covid_19.retrofit.RetrofitCOnfig; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; public class MainActivity extends AppCompatActivity { List<CountriesItem> datacovid=new ArrayList<>(); RecyclerView recicle; private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recicle=findViewById(R.id.recyclerView); // Model contoh=new Model(); // contoh.setCountry("Indonesia"); // contoh.setBaruSembuh("100"); // contoh.setTotalSembuh("8900"); // contoh.setKematianBaru("10"); // contoh.setTotalMennggal("19800"); // contoh.setKonfirmasiTebaru("10"); // contoh.setTotalKonfirmasi("1889900"); // contoh.setTanggal("22-11-2020"); // // // for (int i = 0; i < 20; i++) { // datacovid.add(contoh); // } Log.d(TAG, "data"+ R.id.id_baru_sembuh); getDataOnline(); recicle.setAdapter(new adaptercovid(MainActivity.this,datacovid)); recicle.setLayoutManager(new LinearLayoutManager(MainActivity.this)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_beranda,menu); MenuItem item=menu.findItem(R.id.id_cari); // SearchView searchView=(SearchView) item.getActionView(); // searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { // @Override // public boolean onQueryTextSubmit(String query) { // return false; // } // // @Override // public boolean onQueryTextChange(String newText) { // return false; // } // }); return super.onCreateOptionsMenu(menu); } private void getDataOnline() { final ProgressDialog progress=new ProgressDialog(MainActivity.this); progress.setMessage("Tunggu Sebentar..."); progress.show(); Call<Response>request= RetrofitCOnfig.getApiservice().ambildata(""); request.enqueue(new Callback<Response>() { @Override public void onResponse(Call<Response> call, retrofit2.Response<Response> response) { progress.dismiss(); if (response.isSuccessful()){ datacovid=response.body().getCountries(); recicle.setAdapter(new adaptercovid(MainActivity.this,datacovid)); }else { Toast.makeText(MainActivity.this, "Gagal Memuat", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Response> call, Throwable t) { Toast.makeText(MainActivity.this, "Ada kesalahan "+t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }
package com.tencent.mm.plugin.mall.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.bg.d; import com.tencent.mm.model.q; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.s.c; import com.tencent.mm.storage.aa.a; import com.tencent.mm.wallet_core.ui.e; class MallIndexUI$7 implements OnClickListener { final /* synthetic */ MallIndexUI lab; MallIndexUI$7(MallIndexUI mallIndexUI) { this.lab = mallIndexUI; } public final void onClick(View view) { MallIndexUI mallIndexUI = this.lab; if (q.GS()) { d.A(mallIndexUI, "wallet_payu", ".bind.ui.WalletPayUBankcardManageUI"); } else { d.A(mallIndexUI, "wallet", ".bind.ui.WalletBankcardManageUI"); } e.He(5); h.mEJ.h(14419, new Object[]{this.lab.fMk, Integer.valueOf(3)}); c.Cp().c(a.sYd, a.sYe); } }
package com.TelRan.course.model; public class BoardData { private String name; public BoardData setBoardName(String name) { this.name = name; return this; } public String getName() { return name; } }
package com.jlgproject.model.newDebt; /** * @author 王锋 on 2017/8/12. */ public class OneLevel { private String name; private String image; private String id; private String pId; public OneLevel(String name, String image, String id) { this.name = name; this.image = image; this.id = id; } public OneLevel(String name, String image, String id, String pId) { this.name = name; this.image = image; this.id = id; this.pId = pId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getpId() { return pId; } public void setpId(String pId) { this.pId = pId; } }
package co.nos.noswallet.network.nosModel; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import co.nos.noswallet.persistance.currency.CryptoCurrency; import co.nos.noswallet.util.Extensions; public class GetAccountHistoryRequest implements Serializable { @SerializedName("action") public String action = "get_account_history"; @SerializedName("currency") public String currency; @SerializedName("account") public String account; @SerializedName("account_number") public String account_number; @SerializedName("block") public String block; public GetAccountHistoryRequest(String account, String block, CryptoCurrency cryptoCurrency) { this.account = account; this.block = block; this.currency = cryptoCurrency.getCurrencyCode(); } @Override public String toString() { return Extensions.GSON.toJson(this); } }
package com.example.mingle; import java.util.Set; import org.json.JSONException; import org.json.JSONObject; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; public class GcmIntentService extends IntentService { public static int NOTIFICATION_ID = -1; private NotificationManager mNotificationManager; NotificationCompat.Builder builder; static final String TAG = "GCM Demo"; public GcmIntentService() { super("GcmIntentService"); } @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { Log.i(TAG, "Error: " + extras.toString()); //Maybe show error message? } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { Log.i(TAG, "Deleted: " + extras.toString()); //Maybe show error message? // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { Log.i(TAG, "Received: " + extras.toString()); String send_uid = extras.getString("send_uid"); MingleApplication app = ((MingleApplication)this.getApplicationContext()); //If socket is not connected, then update chat list with GCM msg, //and reconnect the socket for further use. if(!app.isSocketOn()) { JSONObject msg_obj = new JSONObject(); Set<String> keys = extras.keySet(); for (String key : keys) { try { msg_obj.put(key, extras.getString(key)); } catch(JSONException e) { e.printStackTrace(); } } app.handleIncomingMsg(msg_obj); //Connect the socket app.socketHelper.connectSocket(); } //If the user is looking at the chat room now, we need not show notification. if(!app.getMingleUser(send_uid).isInChat()) sendNotification(extras); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); } // Put the message into a notification and post it. // This is just one simple example of what you might choose to do with // a GCM message. private void sendNotification(Bundle data) { mNotificationManager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE); Intent chat_intent = new Intent(this, ChatroomActivity.class); chat_intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); chat_intent.putExtra(ChatroomActivity.USER_UID, data.getString("send_uid")); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, chat_intent, PendingIntent.FLAG_UPDATE_CURRENT); CharSequence tickerTxt = (CharSequence)("Mingle: " + data.getString("msg")); builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("Mingle") .setContentText(data.getString("msg")) .setTicker(tickerTxt) .setDefaults(Notification.DEFAULT_ALL) .setAutoCancel(true); builder.setContentIntent(contentIntent); NOTIFICATION_ID = (NOTIFICATION_ID + 1) % 10; mNotificationManager.notify(NOTIFICATION_ID, builder.build()); } }
package com.smxknife.spring.manual.service.impl; import com.google.gson.Gson; import com.smxknife.spring.manual.annotation.Service; import com.smxknife.spring.manual.model.User; import com.smxknife.spring.manual.service.UserService; /** * @author smxknife * 2019/12/30 */ @Service public class UserServiceImpl implements UserService { @Override public String getUser(String name) { Gson gson = new Gson(); return gson.toJson(new User(name, 11)); } }
package edu.byu.cs.superasteroids.model; /** * Created by Azulius on 2/24/16. */ public class MovingObject extends PositionedObject { }
/* * Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved. */ package net.snowflake.client.core; class SSDPubKey { private static final String pem_key_dep1 = null; private static final String pem_key_dep2 = null; static String getPublicKeyInternal(String dep) { if (dep.equals("dep1")) { return pem_key_dep1; } else { return pem_key_dep2; } } }
/* * 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 bridge; import composite.RasporedDana; import composite.RasporedElement; import prototype.Emisija; import composite.KomponentaRasporeda; import java.time.LocalTime; /** * * @author Ana */ public abstract class DodavanjeEmisija { protected boolean provjeriVremenskaPreklapanja(LocalTime pocetakPrograma, LocalTime krajPrograma, LocalTime pocetakEmisije, Integer trajanjeMinute, RasporedDana dan) { LocalTime krajEmisije = pocetakEmisije.plusMinutes(trajanjeMinute); if (pocetakEmisije.compareTo(pocetakPrograma) < 0 || krajEmisije.compareTo(krajPrograma) > 0) { return true; } for (KomponentaRasporeda k : dan.getChildren()) { RasporedElement element = (RasporedElement) k; Emisija e = element.getEmisija(); LocalTime pocetak = element.getPocetak(); Integer trajanje = e.getTrajanje(); LocalTime kraj = pocetak.plusMinutes(trajanje); if (provjeriPreklapanje(pocetakEmisije, krajEmisije, pocetak, kraj)) { return true; } } if (pocetakEmisije.plusMinutes(trajanjeMinute).compareTo(pocetakPrograma) <= 0) { return true; } return false; } protected boolean provjeriPreklapanje(LocalTime pocetakEmisije, LocalTime krajEmisije, LocalTime pocetak, LocalTime kraj) { if (pocetakEmisije.compareTo(pocetak) >= 0 && pocetakEmisije.compareTo(kraj) < 0) { return true; } if (krajEmisije.compareTo(pocetak) > 0 && krajEmisije.compareTo(kraj) < 0) { return true; } return false; } protected LocalTime nadiVrijemeZaEmisiju(LocalTime pocetakPrograma, LocalTime krajPrograma, RasporedDana sveEmisijeDana, Integer trajanjeMinute) { LocalTime vrati = null; if (sveEmisijeDana.getChildren().isEmpty()) { vrati = pocetakPrograma; } else { LocalTime pocetakEmisije = pocetakPrograma; int index = 0; for (KomponentaRasporeda komponenta : sveEmisijeDana.getChildren()) { LocalTime krajEmisije = pocetakEmisije.plusMinutes(trajanjeMinute); RasporedElement prikaz = (RasporedElement) komponenta; Emisija trenutnaEmisija = prikaz.getEmisija(); LocalTime pocetakTrenutne = prikaz.getPocetak(); LocalTime krajTrenutne = pocetakTrenutne.plusMinutes(trenutnaEmisija.getTrajanje()); if (!provjeriPreklapanje(pocetakEmisije, krajEmisije, pocetakTrenutne, krajTrenutne)) { KomponentaRasporeda iduciZapis = sveEmisijeDana.getChildren().get(index + 1); RasporedElement iduci = (RasporedElement) iduciZapis; Emisija iducaEmisija = iduci.getEmisija(); LocalTime pocetakIduce = iduci.getPocetak(); LocalTime krajIduce = pocetakIduce.plusMinutes(iducaEmisija.getTrajanje()); if (!provjeriPreklapanje(pocetakEmisije, krajEmisije, pocetakIduce, krajIduce)) { vrati = pocetakEmisije; break; } } pocetakEmisije = krajTrenutne; if (pocetakEmisije.plusMinutes(trajanjeMinute).compareTo(pocetakPrograma) <= 0 || pocetakEmisije.plusMinutes(trajanjeMinute).compareTo(krajPrograma) > 0) { System.out.println("Prelazi ponoc"); vrati = null; break; } index++; } } return vrati; } }
package br.usp.memoriavirtual.controle; import java.io.Serializable; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.servlet.http.HttpServletRequest; import br.usp.memoriavirtual.modelo.entidades.Acesso; import br.usp.memoriavirtual.modelo.entidades.Usuario; import br.usp.memoriavirtual.modelo.fachadas.ModeloException; import br.usp.memoriavirtual.modelo.fachadas.remoto.CadastrarUsuarioRemote; import br.usp.memoriavirtual.modelo.fachadas.remoto.MemoriaVirtualRemote; import br.usp.memoriavirtual.utils.MensagensDeErro; import br.usp.memoriavirtual.utils.ValidacoesDeCampos; public class CadastrarUsuarioMB implements Serializable { /** * */ private static final long serialVersionUID = 2202578392589624271L; @EJB private MemoriaVirtualRemote memoriaVirtualEJB; @EJB private CadastrarUsuarioRemote cadastrarUsuarioEJB; private String id = ""; private String email = ""; private String nomeCompleto = ""; private String telefone = ""; private String senha = ""; private String confirmacaoSenha = ""; private Usuario convite = null; public CadastrarUsuarioMB() { } @PostConstruct public void inicializar() { HttpServletRequest request = (HttpServletRequest) FacesContext .getCurrentInstance().getExternalContext().getRequest(); Usuario convite = (Usuario) request.getSession() .getAttribute("usuario"); this.convite = convite; this.email = convite.getEmail(); } public String completarCadastro() { this.validateId(); this.validateEmail(); this.validateNomeCompleto(); this.validateTelefone(); this.validateSenha(); this.validateConfirmacaoSenha(); Usuario usuario = new Usuario(this.id, this.email, this.nomeCompleto, this.telefone, this.senha); if (!FacesContext.getCurrentInstance().getMessages().hasNext()) { String validacaoConvite = this.convite.getId(); try { cadastrarUsuarioEJB.cadastrarUsuario(usuario, validacaoConvite); } catch (ModeloException e) { usuario = null; MensagensDeErro .getErrorMessage("convite_invalido", "resultado"); } catch (RuntimeException e) { usuario = null; MensagensDeErro.getErrorMessage("erro_cadastramento", "resultado"); } if (usuario != null) { usuario = usuario.clone(); HttpServletRequest request = (HttpServletRequest) FacesContext .getCurrentInstance().getExternalContext().getRequest(); request.getSession().setAttribute("usuario", usuario); /* * Coloca a lista de acessos do usuario no sessao para ser * utilizados na verificação antes de renderizar o menu. */ List<Acesso> listaAcessos = memoriaVirtualEJB .listarAcessos(usuario); request.getSession().setAttribute("acessos", listaAcessos); } this.id = ""; this.email = ""; this.nomeCompleto = ""; this.telefone = ""; this.senha = ""; this.confirmacaoSenha = ""; this.convite = null; MensagensDeErro.getSucessMessage("cadastro_concluido", "resultado"); } return "falhou"; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void validateId(AjaxBehaviorEvent event) { this.validateId(); } public void validateId() { if (this.id.equals("")) { String[] argumentos = { "id" }; MensagensDeErro.getErrorMessage("campo_vazio", argumentos, "validacaoId"); } else if (this.id.length() < 4) { String[] argumentos = { "id", "id_minimo" }; MensagensDeErro.getErrorMessage("tamanho_minimo", argumentos, "validacaoId"); } else if (!memoriaVirtualEJB .verificarDisponibilidadeIdUsuario(this.id)) { String[] argumentos = { "id" }; MensagensDeErro.getErrorMessage("ja_cadastrado", argumentos, "validacaoId"); } } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public void validateEmail(AjaxBehaviorEvent event) { this.validateEmail(); } public void validateEmail() { if (this.email.equals("")) { String[] argumentos = { "email" }; MensagensDeErro.getErrorMessage("campo_vazio", argumentos, "validacaoEmail"); } else if (!ValidacoesDeCampos.validarFormatoEmail(this.email)) { String[] argumentos = { "email" }; MensagensDeErro.getErrorMessage("formato_invalido", argumentos, "validacaoEmail"); } else if (!memoriaVirtualEJB.verificarDisponibilidadeEmail(this.email) && !this.email.equals(this.convite.getEmail())) { String[] argumentos = { "email" }; MensagensDeErro.getErrorMessage("ja_cadastrado", argumentos, "validacaoEmail"); } } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public void validateSenha(AjaxBehaviorEvent event) { this.validateSenha(); } public void validateSenha() { if (this.senha.equals("")) { String[] argumentos = { "senha" }; MensagensDeErro.getErrorMessage("campo_vazio", argumentos, "validacaoSenha"); } else if (this.senha.length() < 6) { String[] argumentos = { "senha", "senha_minima" }; MensagensDeErro.getErrorMessage("tamanho_minimo", argumentos, "validacaoSenha"); } } public String getNomeCompleto() { return nomeCompleto; } public void setNomeCompleto(String nomeCompleto) { this.nomeCompleto = nomeCompleto; } public void validateNomeCompleto(AjaxBehaviorEvent event) { this.validateNomeCompleto(); } public void validateNomeCompleto() { if (this.nomeCompleto.equals("")) { String[] argumentos = { "nome_completo" }; MensagensDeErro.getErrorMessage("campo_vazio", argumentos, "validacaoNomeCompleto"); } } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public void validateTelefone(AjaxBehaviorEvent event) { this.validateTelefone(); } public void validateTelefone() { if (this.telefone.equals("")) { String[] argumentos = { "telefone" }; MensagensDeErro.getErrorMessage("campo_vazio", argumentos, "validacaoTelefone"); } else if (!ValidacoesDeCampos.validarFormatoTelefone(this.telefone)) { String[] argumentos = { "telefone" }; MensagensDeErro.getErrorMessage("formato_invalido", argumentos, "validacaoTelefone"); } } public String getConfirmacaoSenha() { return confirmacaoSenha; } public void setConfirmacaoSenha(String confirmacaoSenha) { this.confirmacaoSenha = confirmacaoSenha; } public void validateConfirmacaoSenha(AjaxBehaviorEvent event) { this.validateConfirmacaoSenha(); } public void validateConfirmacaoSenha() { if (confirmacaoSenha.equals("")) { String[] argumentos = { "confirmacao_senha" }; MensagensDeErro.getErrorMessage("campo_vazio", argumentos, "validacaoConfirmacaoSenha"); } else if (!this.confirmacaoSenha.equals(this.senha)) { String[] argumentos = { "confirmacao_senha", "senha" }; MensagensDeErro.getErrorMessage("confirmacao_errado", argumentos, "validacaoConfirmacaoSenha"); } } }
package com.jingb.application.newslistdemo; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.jingb.application.R; import java.util.ArrayList; import java.util.List; public class NewsTitleFragment extends Fragment implements AdapterView.OnItemClickListener { private ListView newsTitleListView; private List<News> newsList; private NewsAdapter newsAdapter; private boolean isTwoPanel; int i = 1; @Override public void onAttach(Context context) { super.onAttach(context); newsList = getNews(); newsAdapter = new NewsAdapter(context, R.layout.news_item, newsList); } @Override public void onAttach(Activity activity) { super.onAttach(activity); newsList = getNews(); newsAdapter = new NewsAdapter(activity, R.layout.news_item, newsList); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (getActivity().findViewById(R.id.news_content) != null) { isTwoPanel = true; } else { isTwoPanel = false; } } private List<News> getNews() { List<News> list = new ArrayList<>(); for (int i=1; i<=55; i++) { News news = new News(); news.setTitle("title" + i); news.setContent(this.content); list.add(news); } return list; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { News news = newsList.get(position); if (isTwoPanel) { NewsContentFragment newsContentFragment = (NewsContentFragment) getFragmentManager(). findFragmentById(R.id.news_content_fragment); newsContentFragment.inflateNews(news.getTitle(), news.getContent()); } else { NewsContentActivity.actionStart(getActivity(), news.getTitle(), news.getContent()); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.news_title_frag, container, false); newsTitleListView = (ListView) view.findViewById(R.id.news_title_list_view); newsTitleListView.setAdapter(newsAdapter); newsTitleListView.setOnItemClickListener(this); return view; } static String content = "粉丝名称为“Ki Aile”,是由宋仲基的“Ki”与法文的翅膀“Aile”结合,意思是当他的翅膀让他展翅高飞。1985年主演的电影《狼族少年》上映,票房突破700万观影人次,刷新了韩国爱情片的最高票房纪录。2008年出演电影《霜花店》进入演艺圈,之后在电视剧、电影、综艺主持多方发展。2009年在音乐节目Music Bank中担任主持,后在艺能节目《Running》中担任固定嘉宾(E01——E41)。2012年接拍KBS水木剧《善良的男人》,在KBS演技大赏中获得最佳男演员奖、网络人气奖及最佳情侣奖。宋仲基于2013年8月27日入伍,已于2015年5月26日退伍。退伍后选择KBS2电视剧《太阳的后裔》作为回归作品。"; }
package cn.yong.zheng.batch.util; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import cn.yong.zheng.batch.entity.BlackListDO; import cn.yong.zheng.batch.service.BlackListService; public class BlackListItemWriter implements ItemWriter<BlackListDO>{ private static final Logger logger = LoggerFactory.getLogger(BlackListItemWriter.class); @Autowired private BlackListService blackListService; @Override public void write(List<? extends BlackListDO> blackList) throws Exception { logger.info("=========黑名单入库========"); for(BlackListDO blackListDO : blackList){ //jdbcTemplate.update( INSERT_BLACKLIST, blackListDO.getId(),blackListDO.getUuid(), blackListDO.getListNameUuid(),blackListDO.getAppName(),blackListDO.getPartnerCode()); blackListService.insert(blackListDO); } } }
package pl.smilu.strategia; class CrossOver implements Aktywnosc { @Override public void aktywnosc() { System.out.println("miniecie"); } }
package com.xampy.namboo.api.payement; import android.content.Context; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; public class VolleyRequestQueueSingleton { private static VolleyRequestQueueSingleton volleyRequestQueueSingleton; private RequestQueue requestQueue; private static Context context; private VolleyRequestQueueSingleton(Context ctx){ context = ctx; requestQueue = getRequestQueue(); } public static synchronized VolleyRequestQueueSingleton getInstance(Context context){ if(volleyRequestQueueSingleton == null){ volleyRequestQueueSingleton = new VolleyRequestQueueSingleton(context); } return volleyRequestQueueSingleton; } public RequestQueue getRequestQueue() { if(requestQueue == null){ requestQueue = Volley.newRequestQueue(context.getApplicationContext()); } return requestQueue; } }
package pl.czyzycki.towerdef.menus; import pl.czyzycki.towerdef.TowerDef; import pl.czyzycki.towerdef.TowerDef.GameSound; import pl.czyzycki.towerdef.gameplay.GameplayScreen; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.ClickListener; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table; import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout; import com.esotericsoftware.tablelayout.Cell; /** * Ekran zwycięstwa. * */ public class Win extends MiniMenu { Stage stage; TowerDef game; int stars; int points; float adjustedWidth; float adjustedHeight; public Win(TowerDef game, GameplayScreen screen) { super(game.getAssetManager(), screen); this.game = game; stage = new Stage(GameplayScreen.viewportWidth, GameplayScreen.viewportHeight, true); } @Override protected Stage currentStage() { return stage; } public void show(int points, int stars) { super.show(); this.points = points; this.stars = stars; Preferences prefs = Gdx.app.getPreferences("stars"); String key = "level-"+((SelectLevelScreen)game.getSelectLevelScreen()).getSelectedLevel(); if(stars > prefs.getInteger(key,0)) prefs.putInteger(key, stars); prefs.flush(); buildScreen(); } private void buildScreen() { stage.setViewport(adjustedWidth, adjustedHeight, true); stage.clear(); Skin skin = getSkin(); Table table = new Table(skin); table.width = stage.width(); table.height = stage.height(); stage.addActor(table); TableLayout layout = table.getTableLayout(); layout.parse("* spacing:5"); LabelStyle whiteLabelStyle = skin.getStyle("white", LabelStyle.class); Label caption = new Label("Gratulacje, wygrałeś!", whiteLabelStyle); Cell<Actor> captionCell = layout.add(caption); captionCell.align("center"); layout.row(); Label earnedPoints = new Label("Zdobyłeś "+points+" punktów.", whiteLabelStyle); Cell<Actor> pointsCell = layout.add(earnedPoints); pointsCell.align("center"); pointsCell.spaceBottom(50); layout.row(); Table starsTable = new Table(skin); starsTable.width = 128*3; starsTable.height = 128; TableLayout starsLayout = starsTable.getTableLayout(); for(int j=0; j<3; j++) { Image img; if(j<stars) img = new Image(game.getAssetManager().get("layouts/star-big.png", Texture.class)); else img = new Image(game.getAssetManager().get("layouts/starslot-big.png", Texture.class)); starsLayout.add(img); } layout.add(starsTable); layout.row(); Cell<Actor> nullCell = layout.add(null); nullCell.height(100); layout.row(); Table buttonsTable = new Table(skin); buttonsTable.width = 500; buttonsTable.height = 100; TableLayout buttonsLayout = buttonsTable.getTableLayout(); buttonsLayout.parse("* spacing:5"); TextButtonStyle whiteButton = skin.getStyle("white", TextButtonStyle.class); TextButton exitButton = new TextButton("Menu", whiteButton); exitButton.setClickListener( new ClickListener() { @Override public void click(Actor actor, float x, float y ) { game.playSound(GameSound.CLICK); game.setScreen(game.getMainMenuScreen()); } } ); exitButton.width(200); buttonsLayout.add(exitButton); TextButton restartButton = new TextButton("Restartuj", whiteButton); restartButton.setClickListener( new ClickListener() { @Override public void click(Actor actor, float x, float y ) { game.playSound(GameSound.CLICK); screen.restartMap(); hide(); } } ); restartButton.width(200); buttonsLayout.add(restartButton); TextButton nextButton = new TextButton("Dalej", whiteButton); nextButton.setClickListener( new ClickListener() { @Override public void click(Actor actor, float x, float y ) { game.playSound(GameSound.CLICK); SelectLevelScreen levelScreen = (SelectLevelScreen)screen.game.getSelectLevelScreen(); levelScreen.nextLevel(); screen.loadMap("lvl"+ levelScreen.getSelectedLevel()); hide(); } } ); nextButton.width(200); buttonsLayout.add(nextButton); layout.add(buttonsTable); } public void resize(int width, int height) { float aspect = (float)width/(float)height; adjustedWidth = 480*aspect; adjustedHeight = 480; } public void dispose() { stage.dispose(); super.dispose(); } }
/* Given two strings s1 and s2, find if s2 is a rotation of s1. Example 1: s1 = "water" s2 = "terwa" Ans: true Example 2: s1 = "water" s2 = "watre" Ans: false */ /* Approach: You can do it in brute-force method, by comparing the characters and comparing their order. However, we don't need so many computations. We concatenate s1 to itself. If s2 is a rotation of s1, it will be contained in s1 + s1. If yes, return true, else false. Eg: waterwater contains the string terwa so it is true. */ public boolean isRotation(String s1, String s2) { if(s1.length() != s2.length()) return false; return (s1+s1).contains(s2); }
package android.support.design.internal; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.design.a.h; import android.support.design.a.i; import android.support.v4.view.z; import android.util.AttributeSet; import android.widget.FrameLayout; public class ScrimInsetsFrameLayout extends FrameLayout { private Drawable bH; private Rect bI; private Rect bJ; public ScrimInsetsFrameLayout(Context context, AttributeSet attributeSet) { this(context, attributeSet, 0); } public ScrimInsetsFrameLayout(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); this.bJ = new Rect(); TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, i.ScrimInsetsFrameLayout, i, h.Widget_Design_ScrimInsetsFrameLayout); this.bH = obtainStyledAttributes.getDrawable(i.ScrimInsetsFrameLayout_insetForeground); obtainStyledAttributes.recycle(); setWillNotDraw(true); z.b(this, new 1(this)); } public void draw(Canvas canvas) { super.draw(canvas); int width = getWidth(); int height = getHeight(); if (this.bI != null && this.bH != null) { int save = canvas.save(); canvas.translate((float) getScrollX(), (float) getScrollY()); this.bJ.set(0, 0, width, this.bI.top); this.bH.setBounds(this.bJ); this.bH.draw(canvas); this.bJ.set(0, height - this.bI.bottom, width, height); this.bH.setBounds(this.bJ); this.bH.draw(canvas); this.bJ.set(0, this.bI.top, this.bI.left, height - this.bI.bottom); this.bH.setBounds(this.bJ); this.bH.draw(canvas); this.bJ.set(width - this.bI.right, this.bI.top, width, height - this.bI.bottom); this.bH.setBounds(this.bJ); this.bH.draw(canvas); canvas.restoreToCount(save); } } protected void onAttachedToWindow() { super.onAttachedToWindow(); if (this.bH != null) { this.bH.setCallback(this); } } protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (this.bH != null) { this.bH.setCallback(null); } } public void c(Rect rect) { } }
package com.gmail.khanhit100896.foody.city; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.gmail.khanhit100896.foody.config.Config; import com.gmail.khanhit100896.foody.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * A simple {@link Fragment} subclass. */ public class CityFragment extends Fragment { /* * Khái báo biến cần thiết */ protected String getURL = Config.getConfig().getPathGetAllCity(); protected RecyclerView recyclerCity; protected List<City> cityList; protected CityRecyclerViewAdapter adapter; /* */ public CityFragment() { // Required empty public constructor } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_city, container, false); /* * Ánh xạ và khởi tạo biến */ this.recyclerCity = view.findViewById(R.id.recycler_city); this.cityList = new ArrayList<>(); /* */ getAllCity(getURL); return view; } /* * Hàm lấy tất cả thành phố từ CSDL */ private void getAllCity(String getURL) { RequestQueue requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getActivity())); JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, getURL, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { cityList.clear(); for (int i=0;i<response.length();i++){ try { JSONObject object = response.getJSONObject(i); cityList.add(new City( object.getInt("ID"), object.getString("CityCode"), object.getString("CityName"), object.getString("CityImage") )); } catch (JSONException e) { e.printStackTrace(); } } /* * Đổ dữ liệu lên RecyclerView */ adapter = new CityRecyclerViewAdapter(getActivity(),cityList); recyclerCity.setLayoutManager(new GridLayoutManager(getActivity(),2)); recyclerCity.setAdapter(adapter); /* */ } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); requestQueue.add(jsonArrayRequest); } }
package leti.asd.db.db_list; import java.util.*; /** * Project transportDB * Created by nikolaikobyzev on 15.10.16. */ public class ListDB extends ArrayList<DBrecord>{ @Override public void sort(Comparator<? super DBrecord> c) { for(int i = 0; i < this.size(); i++){ DBrecord temp = this.get(i); int j = i - 1; while((j >= 0) && c.compare(this.get(j),temp) > 0){ this.set(j + 1,this.get(j)); j--; } this.set(j + 1, temp); } } public int searchBin(Object value, DBRecordField field){ switch(field){ case LEVEL: return searchWrap((int)value, DBRecordField.LEVEL); case YEARS_WORK: return searchWrap((int)value, DBRecordField.YEARS_WORK); case SALARY: return searchWrap((int)value, DBRecordField.SALARY); case FULLNAME: return searchWrap((String)value); } return -1; } private int searchWrap(int key, DBRecordField field){ if (this.size() == 0) return -1; return search(key, 0, this.size(), field); } private int searchWrap(String key){ if (this.size() == 0) return -1; return search(key, 0, this.size()); } private int search(int key, int left, int right, DBRecordField field) { int mid = left + (right - left) / 2; if (left >= right) return -1; switch (field) { case LEVEL: if (this.get(left).getLevel() == key) return left; if (this.get(mid).getLevel() == key) { if (mid == left + 1) return mid; else return search(key, left, mid + 1, field); } else if (this.get(mid).getLevel() > key) return search(key, left, mid, field); else return search(key, mid + 1, right, field); case YEARS_WORK: if (this.get(left).getYears_work() == key) return left; if (this.get(mid).getYears_work() == key) { if (mid == left + 1) return mid; else return search(key, left, mid + 1, field); } else if (this.get(mid).getYears_work() > key) return search(key, left, mid, field); else return search(key, mid + 1, right, field); case SALARY: if (this.get(left).getSalary() == key) return left; if (this.get(mid).getSalary() == key) { if (mid == left + 1) return mid; else return search(key, left, mid + 1, field); } else if (this.get(mid).getSalary() > key) return search(key, left, mid, field); else return search(key, mid + 1, right, field); } return -1; } private int search(String key, int left, int right){ int mid = left + (right - left) / 2; if (left >= right) return -1; if (key.equals(this.get(left).getFullName())) return left; if (Objects.equals(this.get(left).getFullName(), key)) return left; if (Objects.equals(this.get(mid).getFullName(), key)) { if (mid == left + 1) return mid; else return search(key, left, mid + 1); } else if (this.get(mid).getFullName().compareTo(key) > 0) return search(key, left, mid); else return search(key, mid + 1, right); } }
package com.quiz.projectWilayah.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.quiz.projectWilayah.entity.ProvinsiEntity; @Repository public interface ProvinsiRepository extends JpaRepository<ProvinsiEntity, Integer> { ProvinsiEntity findByProvinsiCode(String provinsiCode); @Query(value = "select * from provinsi_entity where status = 1 and id = ?", nativeQuery = true) List<ProvinsiEntity> findProvinsiActiveById(Integer id); @Query(value = "select * from provinsi_entity where status = 1 and provinsi_code = ?", nativeQuery = true) List<ProvinsiEntity> findProvinsiActiveByCode(String provinsiCode); @Query(value = "select * from provinsi_entity where status = 1", nativeQuery = true) List<ProvinsiEntity> findAllProvinsiActive(); }
package com.lxy.JUnit; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; public class JUnit { @BeforeClass public static void beforeClass() { System.out.println("beforeClass..."); } @Before public void before() { System.out.println("before..."); } @Test public void eat() { System.out.println("eating..."); } @After public void after() { System.out.println("after..."); } @Test public void smile() { System.out.println("smiling..."); } @AfterClass public static void afterClass() { System.out.println("afterClass..."); } @Ignore public void sleep() { System.out.println("sleeping..."); } }