text
stringlengths
10
2.72M
package org.alienideology.jcord.internal.object.channel; import org.alienideology.jcord.handle.channel.IGroup; import org.alienideology.jcord.handle.client.IClient; import org.alienideology.jcord.handle.client.call.ICall; import org.alienideology.jcord.handle.managers.IGroupManager; import org.alienideology.jcord.handle.modifiers.IGroupModifier; import org.alienideology.jcord.handle.user.IUser; import org.alienideology.jcord.internal.object.client.Client; import org.alienideology.jcord.internal.object.client.call.Call; import org.alienideology.jcord.internal.object.managers.GroupManager; import org.alienideology.jcord.internal.object.modifiers.GroupModifier; import java.util.List; /** * @author AlienIdeology */ public final class Group extends MessageChannel implements IGroup { private Client client; private String name; private String icon; private String ownerId; private List<IUser> recipients; private Call currentCall; private GroupManager manager; private GroupModifier modifier; public Group(Client client, String id, String name, String icon, String ownerId, List<IUser> recipients) { super(client.getIdentity(), id, Type.GROUP_DM); this.client = client; this.name = name; this.icon = icon; this.ownerId = ownerId; this.recipients = recipients; this.manager = new GroupManager(this); this.modifier = new GroupModifier(this); } @Override public IClient getClient() { return client; } @Override public IGroupManager getManager() { return manager; } @Override public IGroupModifier getModifier() { return modifier; } @Override public String getName() { return name; } @Override public String getIconHash() { return icon; } @Override public IUser getOwner() { return recipients.stream() .filter(r -> r.getId().equals(ownerId)).findFirst().orElse(client.getProfile()); } @Override public List<IUser> getRecipients() { return recipients; } @Override public ICall getCurrentCall() { return currentCall; } public void setName(String name) { this.name = name; } public void setIcon(String icon) { this.icon = icon; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public void setCurrentCall(Call currentCall) { this.currentCall = currentCall; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Group)) return false; if (!super.equals(o)) return false; Group group = (Group) o; if (!client.equals(group.client)) return false; if (name != null ? !name.equals(group.name) : group.name != null) return false; return ownerId.equals(group.ownerId); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + client.hashCode(); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + ownerId.hashCode(); return result; } @Override public String toString() { return "Group{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", ownerId='" + ownerId + '\'' + ", recipients=" + recipients + '}'; } }
package fr.cgi.heritage; public class Application { public static void main( String[] args ) { Oiseau oiseau = new Oiseau( "Titi" ); oiseau.presenteToi(); oiseau.chante(); // oiseau.faitLaRoue(); Paon paon = new Paon( 9 ); paon.presenteToi(); paon.chante(); paon.faitLaRoue(); Kiwi kiwi = new Kiwi(); kiwi.presenteToi(); kiwi.chante(); Rossignol rossignol = new Rossignol(); rossignol.presenteToi(); rossignol.chante(); Perroquet perroquet = new Perroquet( "Jaco", "mille sabords" ); perroquet.presenteToi(); perroquet.chante(); } }
package len; public class vocount { String St="Pooja Garg"; int vowels=0; public void Vowe() { for(int i=0;i<=St.length()-1;i++) { char St1=St.charAt(i); if( St1 == 'a'|| St1=='o') {++vowels; } else {System.out.println(" "); }} System.out.println("No of vowels"+vowels); } public static void main(String[] args) {vocount oo=new vocount(); oo.Vowe(); // TODO Auto-generated method stub } }
package com.pkjiao.friends.mm.utils; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.DataOutputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.InterruptedIOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ActivityManager; import android.content.ComponentName; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory.Options; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Environment; import android.os.ParcelFileDescriptor; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.FloatMath; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import com.pkjiao.friends.mm.R; import com.pkjiao.friends.mm.adapter.ChatMsgViewAdapter.IMsgViewType; import com.pkjiao.friends.mm.base.ChatMsgItem; import com.pkjiao.friends.mm.base.CommentsItem; import com.pkjiao.friends.mm.base.ContactsInfo; import com.pkjiao.friends.mm.base.ImagesItem; import com.pkjiao.friends.mm.base.NoticesItem; import com.pkjiao.friends.mm.base.ReplysItem; import com.pkjiao.friends.mm.common.CommonDataStructure; import com.pkjiao.friends.mm.common.CommonDataStructure.DownloadCommentsEntry; import com.pkjiao.friends.mm.common.CommonDataStructure.UploadReplysResultEntry; import com.pkjiao.friends.mm.database.MarrySocialDBHelper; public class Utils { private static final String TAG = "MarrySocialUtils"; public static int mThumbPhotoWidth = 720; public static int mCropCenterThumbPhotoWidth = 200; public static int mTinyCropCenterThumbPhotoWidth = 100; private static final int TIME_OUT = 100 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; public static boolean isActiveNetWorkAvailable(Context context) { ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isAvailable()) { return true; } else { return false; } } public static boolean isGpsEnabled(Context context) { LocationManager lm = ((LocationManager) context .getSystemService(Context.LOCATION_SERVICE)); List<String> accessibleProviders = lm.getProviders(true); return accessibleProviders != null && accessibleProviders.size() > 0; } public static boolean isWifiEnabled(Context context) { ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); TelephonyManager telManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); return ((connManager.getActiveNetworkInfo() != null && connManager .getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || telManager .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS); } public static boolean is3Grd(Context context) { ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { return true; } return false; } public static boolean isWifi(Context context) { ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { return true; } return false; } public Bitmap getRoundedCornerBitmap(Context context, float ratio) { Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.person_default_pic); Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); canvas.drawRoundRect(rectF, bitmap.getWidth() / ratio, bitmap.getHeight() / ratio, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } public static Bitmap createWidgetBitmap(Bitmap bitmap, int rotation) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); float scale; if (((rotation / 90) & 1) == 0) { scale = Math.max((float) mThumbPhotoWidth / w, (float) mCropCenterThumbPhotoWidth / h); } else { scale = Math.max((float) mThumbPhotoWidth / h, (float) mCropCenterThumbPhotoWidth / w); } Bitmap target = Bitmap.createBitmap(mThumbPhotoWidth, mCropCenterThumbPhotoWidth, Config.ARGB_8888); Canvas canvas = new Canvas(target); canvas.translate(mThumbPhotoWidth / 2, mCropCenterThumbPhotoWidth / 2); canvas.rotate(rotation); canvas.scale(scale, scale); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); canvas.drawBitmap(bitmap, -w / 2, -h / 2, paint); bitmap.recycle(); bitmap = null; return target; } public static void hideSoftInputMethod(View view) { InputMethodManager ime = (InputMethodManager) view.getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); if (ime.isActive()) { ime.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0); } } public static void showSoftInputMethod(View view) { InputMethodManager ime = (InputMethodManager) view.getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); // if (!ime.isActive()) { ime.showSoftInput(view, InputMethodManager.SHOW_FORCED); // } } public static Bitmap resizeAndCropCenter(Bitmap bitmap, int size, boolean recycle) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); if (w == size && h == size) return bitmap; // scale the image so that the shorter side equals to the target; // the longer side will be center-cropped. float scale = (float) size / Math.min(w, h); Bitmap target = Bitmap.createBitmap(size, size, getConfig(bitmap)); int width = Math.round(scale * bitmap.getWidth()); int height = Math.round(scale * bitmap.getHeight()); Canvas canvas = new Canvas(target); canvas.translate((size - width) / 2f, (size - height) / 2f); canvas.scale(scale, scale); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); canvas.drawBitmap(bitmap, 0, 0, paint); if (recycle) bitmap.recycle(); return target; } public static Bitmap cropImages(Bitmap bitmap, int cropWidth, int cropHeight, boolean recycle) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); if (w == cropWidth && h == cropHeight) return bitmap; // scale the image so that the shorter side equals to the target; // the longer side will be center-cropped. float scale = (float) Math.max((float) cropWidth / w, (float) cropHeight / h); Bitmap target = Bitmap.createBitmap(cropWidth, cropHeight, getConfig(bitmap)); int width = Math.round(scale * bitmap.getWidth()); int height = Math.round(scale * bitmap.getHeight()); Canvas canvas = new Canvas(target); canvas.translate((cropWidth - width) / 2f, (cropHeight - height) / 2f); canvas.scale(scale, scale); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); canvas.drawBitmap(bitmap, 0, 0, paint); if (recycle) bitmap.recycle(); return target; } public static void recycleSilently(Bitmap bitmap) { if (bitmap == null) return; try { bitmap.recycle(); } catch (Throwable t) { Log.w(TAG, "unable recycle bitmap", t); } } public static Bitmap rotateBitmap(Bitmap source, int rotation, boolean recycle) { if (rotation == 0) return source; int w = source.getWidth(); int h = source.getHeight(); Matrix m = new Matrix(); m.postRotate(rotation); Bitmap bitmap = Bitmap.createBitmap(source, 0, 0, w, h, m, true); if (recycle) source.recycle(); return bitmap; } private static Bitmap.Config getConfig(Bitmap bitmap) { Bitmap.Config config = bitmap.getConfig(); if (config == null) { config = Bitmap.Config.ARGB_8888; } return config; } public static Bitmap decodeThumbnail(String filePath, Options options, int targetSize) { FileInputStream fis = null; try { fis = new FileInputStream(filePath); FileDescriptor fd = fis.getFD(); return decodeThumbnail(fd, options, targetSize); } catch (Exception ex) { Log.w(TAG, ex); return null; } finally { Utils.closeSilently(fis); } } public static Bitmap decodeThumbnail(FileDescriptor fd, Options options, int targetSize) { if (options == null) options = new Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fd, null, options); int w = options.outWidth; int h = options.outHeight; // We center-crop the original image as it's micro thumbnail. In this // case, // we want to make sure the shorter side >= "targetSize". float scale = (float) targetSize / Math.min(w, h); options.inSampleSize = computeSampleSizeLarger(scale); // For an extremely wide image, e.g. 300x30000, we may got OOM when // decoding // it for TYPE_MICROTHUMBNAIL. So we add a max number of pixels limit // here. final int MAX_PIXEL_COUNT = 640000; // 400 x 1600 if ((w / options.inSampleSize) * (h / options.inSampleSize) > MAX_PIXEL_COUNT) { options.inSampleSize = computeSampleSize(FloatMath .sqrt((float) MAX_PIXEL_COUNT / (w * h))); } options.inJustDecodeBounds = false; Bitmap result = BitmapFactory.decodeFileDescriptor(fd, null, options); if (result == null) return null; // We need to resize down if the decoder does not support inSampleSize // (For example, GIF images) scale = (float) targetSize / (Math.min(result.getWidth(), result.getHeight())); if (scale <= 0.5) result = resizeBitmapByScale(result, scale, true); return ensureGLCompatibleBitmap(result); } public static void closeSilently(ParcelFileDescriptor fd) { try { if (fd != null) fd.close(); } catch (Throwable t) { Log.w(TAG, "fail to close", t); } } public static void closeSilently(Closeable c) { if (c == null) return; try { c.close(); } catch (Throwable t) { Log.w(TAG, "close fail", t); } } // Find the min x that 1 / x >= scale public static int computeSampleSizeLarger(float scale) { int initialSize = (int) FloatMath.floor(1f / scale); if (initialSize <= 1) return 1; return initialSize <= 8 ? Utils.prevPowerOf2(initialSize) : initialSize / 8 * 8; } // Returns the previous power of two. // Returns the input if it is already power of 2. // Throws IllegalArgumentException if the input is <= 0 public static int prevPowerOf2(int n) { if (n <= 0) throw new IllegalArgumentException(); return Integer.highestOneBit(n); } // Find the max x that 1 / x <= scale. public static int computeSampleSize(float scale) { Utils.assertTrue(scale > 0); int initialSize = Math.max(1, (int) FloatMath.ceil(1 / scale)); return initialSize <= 8 ? Utils.nextPowerOf2(initialSize) : (initialSize + 7) / 8 * 8; } // Returns the next power of two. // Returns the input if it is already power of 2. // Throws IllegalArgumentException if the input is <= 0 or // the answer overflows. public static int nextPowerOf2(int n) { if (n <= 0 || n > (1 << 30)) throw new IllegalArgumentException("n is invalid: " + n); n -= 1; n |= n >> 16; n |= n >> 8; n |= n >> 4; n |= n >> 2; n |= n >> 1; return n + 1; } // Throws AssertionError if the input is false. public static void assertTrue(boolean cond) { if (!cond) { throw new AssertionError(); } } public static Bitmap resizeBitmapByScale(Bitmap bitmap, float scale, boolean recycle) { int width = Math.round(bitmap.getWidth() * scale); int height = Math.round(bitmap.getHeight() * scale); if (width == bitmap.getWidth() && height == bitmap.getHeight()) return bitmap; Bitmap target = Bitmap.createBitmap(width, height, getConfig(bitmap)); Canvas canvas = new Canvas(target); canvas.scale(scale, scale); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); canvas.drawBitmap(bitmap, 0, 0, paint); if (recycle) bitmap.recycle(); return target; } // TODO: This function should not be called directly from // DecodeUtils.requestDecode(...), since we don't have the knowledge // if the bitmap will be uploaded to GL. public static Bitmap ensureGLCompatibleBitmap(Bitmap bitmap) { if (bitmap == null || bitmap.getConfig() != null) return bitmap; Bitmap newBitmap = bitmap.copy(Config.ARGB_8888, false); bitmap.recycle(); return newBitmap; } public static byte[] Bitmap2Bytes(Bitmap bitmap) { ByteArrayOutputStream output = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 80, output); return output.toByteArray(); } public static CommonDataStructure.UploadImageResultEntry uploadImageFile( String requestURL, String filePath, String fileName, String uid, String tid, int pos) { Bitmap bitmap = decodeThumbnail(filePath, null, mThumbPhotoWidth); HashMap<String, String> params = new HashMap<String, String>(); params.put("uid", uid); params.put("tid", tid); params.put("pos", String.valueOf(pos)); return uploadBitmapFile(requestURL, bitmap, fileName, params); } public static CommonDataStructure.UploadImageResultEntry uploadBitmapFile( String requestURL, Bitmap bitmap, String fileName, HashMap<String, String> params) { HttpURLConnection connection = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--"; String LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 CommonDataStructure.UploadImageResultEntry resultEntry = new CommonDataStructure.UploadImageResultEntry(); try { URL url = new URL(requestURL); connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(TIME_OUT); connection.setConnectTimeout(TIME_OUT); connection.setDoInput(true); // 允许输入流 connection.setDoOutput(true); // 允许输出流 connection.setUseCaches(false); // 不允许使用缓存 connection.setRequestMethod("POST"); // 请求方式 connection.setRequestProperty("Charset", CHARSET); // 设置编码 connection.setRequestProperty("connection", "keep-alive"); connection.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (bitmap != null) { /** * 当bitmap不为空,把bitmap包装并且上传 */ DataOutputStream dos = new DataOutputStream( connection.getOutputStream()); StringBuffer sb = new StringBuffer(); // 首先组拼文本类型的参数 for (HashMap.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END); sb.append("Content-Transfer-Encoding: 8bit" + LINE_END); sb.append(LINE_END); sb.append(entry.getValue()); sb.append(LINE_END); } // 上传图片内容 sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"upfile\"; filename=\"" + fileName + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); byte[] bytes = Bitmap2Bytes(bitmap); dos.write(bytes); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END) .getBytes(); dos.write(end_data); dos.flush(); dos.close(); BufferedReader inputReader = new BufferedReader( new InputStreamReader(connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } inputReader.close(); Log.e(TAG, "nannan response = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return resultEntry; } JSONObject respData = response.getJSONObject("data"); int pos = respData.getInt("pos"); String photoId = respData.getString("pid"); String orginal = respData.getString("scale"); String small = respData.getString("small"); String big = respData.getString("big"); resultEntry.result = true; resultEntry.photoId = photoId; resultEntry.pos = pos; resultEntry.orgUrl = orginal; resultEntry.smallThumbUrl = small; resultEntry.bigThumbUrl = big; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return resultEntry; } public static CommonDataStructure.UploadHeadPicResultEntry uploadHeadPicBitmap( String requestURL, String uid, Bitmap bitmap, String bitmapName) { HttpURLConnection connection = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--"; String LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 CommonDataStructure.UploadHeadPicResultEntry resultEntry = new CommonDataStructure.UploadHeadPicResultEntry(); try { URL url = new URL(requestURL); connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(TIME_OUT); connection.setConnectTimeout(TIME_OUT); connection.setDoInput(true); // 允许输入流 connection.setDoOutput(true); // 允许输出流 connection.setUseCaches(false); // 不允许使用缓存 connection.setRequestMethod("POST"); // 请求方式 connection.setRequestProperty("Charset", CHARSET); // 设置编码 connection.setRequestProperty("connection", "keep-alive"); connection.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (bitmap != null) { /** * 当bitmap不为空,把bitmap包装并且上传 */ DataOutputStream dos = new DataOutputStream( connection.getOutputStream()); StringBuffer sb = new StringBuffer(); // 首先组拼文本类型的参数 sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); sb.append("Content-Disposition: form-data; name=\"" + "uid" + "\"" + LINE_END); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END); sb.append("Content-Transfer-Encoding: 8bit" + LINE_END); sb.append(LINE_END); sb.append(uid); sb.append(LINE_END); // 上传图片内容 sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"upfile\"; filename=\"" + bitmapName + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); byte[] bytes = Bitmap2Bytes(bitmap); dos.write(bytes); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END) .getBytes(); dos.write(end_data); dos.flush(); dos.close(); BufferedReader inputReader = new BufferedReader( new InputStreamReader(connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } inputReader.close(); Log.e(TAG, "nannan response = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return resultEntry; } JSONObject respData = response.getJSONObject("data"); String orginal = respData.getString("url"); String bigThumb = respData.getString("bigurl"); String smallThumb = respData.getString("smallurl"); resultEntry.uid = uid; resultEntry.orgUrl = orginal; resultEntry.bigThumbUrl = bigThumb; resultEntry.smallThumbUrl = smallThumb; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return resultEntry; } public static boolean uploadHeaderBackground(String RequestURL, String uId, String picnum) { boolean resultCode = false; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return resultCode; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return resultCode; connection.setDoOutput(true); connection.setDoInput(true); connection.setConnectTimeout(TIME_OUT); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject commentContent = new JSONObject(); commentContent.put(CommonDataStructure.UID, uId); commentContent.put(CommonDataStructure.BACKGROUD_PIC_NUM, picnum); String content = "jsondata=" + URLEncoder.encode(commentContent.toString(), "UTF-8"); Log.e(TAG, "nannan commentContent = " + commentContent.toString()); Log.e(TAG, "nannan content = " + content); if (content == null) return resultCode; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString()); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return resultCode; } resultCode = response.getBoolean("data"); inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return resultCode; } public static String uploadCommentContentFile(String RequestURL, String uId, String contents) { String resultCode = null; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return resultCode; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return resultCode; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject commentContent = new JSONObject(); commentContent.put(CommonDataStructure.UID, uId); commentContent.put(CommonDataStructure.COMMENT_CONTENT, contents); String content = "jsondata=" + URLEncoder.encode(commentContent.toString(), "UTF-8"); Log.e(TAG, "nannan commentContent = " + commentContent.toString()); Log.e(TAG, "nannan content = " + content); if (content == null) return resultCode; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString()); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return resultCode; } JSONObject respData = response.getJSONObject("data"); resultCode = respData.getString("tid"); inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return resultCode; } public static boolean uploadBravoFile(String RequestURL, String uId, String commentId) { Log.e(TAG, "nannan uploadBravoFile "); boolean resultCode = false; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return resultCode; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return resultCode; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject bravoContent = new JSONObject(); bravoContent.put(CommonDataStructure.UID, uId); bravoContent.put(CommonDataStructure.COMMENT_ID, commentId); String content = "jsondata=" + URLEncoder.encode(bravoContent.toString(), "UTF-8"); Log.e(TAG, "nannan bravoContent = " + bravoContent.toString()); Log.e(TAG, "nannan content = " + content); if (content == null) return resultCode; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString()); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return resultCode; } resultCode = "true".equalsIgnoreCase(response.getString("data")); inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return resultCode; } public static boolean deleteBravoFileFromCloud(String RequestURL, String uId, String commentId) { Log.e(TAG, "nannan deleteBravoFileFromCloud "); boolean resultCode = false; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return resultCode; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return resultCode; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject bravoContent = new JSONObject(); bravoContent.put(CommonDataStructure.UID, uId); bravoContent.put(CommonDataStructure.COMMENT_ID, commentId); String content = "jsondata=" + URLEncoder.encode(bravoContent.toString(), "UTF-8"); Log.e(TAG, "nannan bravoContent = " + bravoContent.toString()); Log.e(TAG, "nannan content = " + content); if (content == null) return resultCode; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString()); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return resultCode; } resultCode = "true".equalsIgnoreCase(response.getString("data")); inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return resultCode; } public static UploadReplysResultEntry uploadReplyFile(String RequestURL, String uId, String commentId, String reply) { Log.e(TAG, "nannan uploadReplyFile "); UploadReplysResultEntry result = new UploadReplysResultEntry(); URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return result; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return result; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject replyContent = new JSONObject(); replyContent.put(CommonDataStructure.UID, uId); replyContent.put(CommonDataStructure.COMMENT_ID, commentId); replyContent.put(CommonDataStructure.COMMENT_CONTENT, reply); String content = "jsondata=" + URLEncoder.encode(replyContent.toString(), "UTF-8"); Log.e(TAG, "nannan replyContent = " + replyContent.toString()); Log.e(TAG, "nannan content = " + content); if (content == null) return result; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString()); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return result; } JSONObject respData = response.getJSONObject("data"); String replyId = respData.getString("rid"); String addTime = respData.getString("addtime"); result.uId = uId; result.commentId = commentId; result.replyId = replyId; result.addTime = addTime; inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return result; } public static String getHttpToken(String RequestURL, String uId) { String resultCode = null; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; BufferedReader inputReader = null; OutputStreamWriter outputWriter = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return resultCode; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return resultCode; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write("uid=" + uId); Log.e(TAG, "uid = " + uId); outputWriter.flush(); outputWriter.close(); // outputStream = new // DataOutputStream(connection.getOutputStream()); // JSONObject token = new JSONObject(); // token.put(CommonDataStructure.UID, uId); // // String content = "jsondata=" // + URLEncoder.encode(token.toString(), "UTF-8"); // Log.e(TAG, "nannan commentContent = " + token.toString()); // Log.e(TAG, "nannan content = " + content); // if (content == null) // return resultCode; // // outputStream.writeBytes(content); // outputStream.flush(); // outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } inputReader.close(); Log.e(TAG, "nannan line = " + resp.toString()); JSONObject response = new JSONObject(resp.toString()); resultCode = response.getString("token"); if (resultCode != null) { return resultCode; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return resultCode; } public static boolean isHttpTokenValid(String RequestURL, String uId, String token) { boolean resultCode = false; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return resultCode; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return resultCode; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write("uid=" + uId + "&token=" + token); Log.e(TAG, "uid = " + uId); Log.e(TAG, "token = " + token); outputWriter.flush(); outputWriter.close(); // outputStream = new // DataOutputStream(connection.getOutputStream()); // JSONObject tokenEntry = new JSONObject(); // tokenEntry.put(CommonDataStructure.UID, uId); // tokenEntry.put(CommonDataStructure.TOKEN, token); // // String content = "jsondata=" // + URLEncoder.encode(tokenEntry.toString(), "UTF-8"); // Log.e(TAG, "nannan commentContent = " + tokenEntry.toString()); // Log.e(TAG, "nannan content = " + content); // if (content == null) // return resultCode; // // outputStream.writeBytes(content); // outputStream.flush(); // outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } inputReader.close(); Log.e(TAG, "nannan line = " + resp.toString()); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return resultCode; } String data = response.getString("data"); if ("true".equalsIgnoreCase(data)) { resultCode = true; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return resultCode; } public static String getAddedTimeTitle(Context context, String time) { Long just_now = System.currentTimeMillis() / 1000; Long added_time = Long.valueOf(time); int timeSpaces = (int) (just_now - added_time); if (0 <= timeSpaces && timeSpaces < CommonDataStructure.TIME_FIVE_MINUTES_BEFORE) { return context.getString(R.string.time_just_now); } else if (timeSpaces < CommonDataStructure.TIME_TEN_MINUTES_BEFORE) { return context.getString(R.string.time_five_seconds_before); } else if (timeSpaces < CommonDataStructure.TIME_FIFTEEN_MINUTES_BEFORE) { return context.getString(R.string.time_ten_seconds_before); } else if (timeSpaces < CommonDataStructure.TIME_THIRTY_MINUTES_BEFORE) { return context.getString(R.string.time_fifteen_seconds_before); } else if (timeSpaces < CommonDataStructure.TIME_ONE_HOUR_BEFORE) { return context.getString(R.string.time_thirty_seconds_before); } else if (timeSpaces < CommonDataStructure.TIME_TWO_HOURS_BEFORE) { return context.getString(R.string.time_one_hour_before); } else if (timeSpaces < CommonDataStructure.TIME_THREE_HOURS_BEFORE) { return context.getString(R.string.time_two_hours_before); } else if (timeSpaces < CommonDataStructure.TIME_FIVE_HOURS_BEFORE) { return context.getString(R.string.time_three_hours_before); } else if (timeSpaces < CommonDataStructure.TIME_ONE_DAY_BEFORE) { return context.getString(R.string.time_five_hours_before); } else if (timeSpaces < CommonDataStructure.TIME_TWO_DAY_BEFORE) { return context.getString(R.string.time_one_day_before); } else { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date curDate = new Date(added_time * 1000); return formatter.format(curDate); } } public static ArrayList<CommentsItem> downloadCommentsWithReplyList( String RequestURL, DownloadCommentsEntry entry, String indirects) { Log.e(TAG, "nannan downloadCommentsList 4444444444"); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; ArrayList<CommentsItem> commentItems = new ArrayList<CommentsItem>(); try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject commentContent = new JSONObject(); commentContent.put("uid", "3"); commentContent.put("indirectuids", indirects); // commentContent.put("datetime", entry.addedTime); String content = null; content = "jsondata=" + URLEncoder.encode(commentContent.toString(), "UTF-8"); if (content == null) return null; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan resp 555555555555 = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return null; } JSONArray respData = response.getJSONArray("data"); for (int index = 0; index < respData.length(); index++) { JSONObject comment = respData.getJSONObject(index); CommentsItem commentItem = new CommentsItem(); commentItem.setUid(comment.getString("uid")); commentItem.setCommentId(comment.getString("tid")); commentItem.setAddTime(comment.getString("addtime")); commentItem.setContents(comment.getString("content")); commentItem.setRealName(comment.getString("fullname")); commentItem.setPhotoCount(Integer.valueOf(comment .getString("pics"))); int replyCount = Integer.valueOf(comment.getString("replies")); ArrayList<ReplysItem> replys = new ArrayList<ReplysItem>(); if (replyCount > 0) { JSONArray replyLists = comment.getJSONArray("replies_info"); for (int pointer = 0; pointer < replyLists.length(); pointer++) { JSONObject item = replyLists.getJSONObject(pointer); ReplysItem reply = new ReplysItem(); reply.setCommentId(item.getString("tid")); reply.setReplyContents(item.getString("content")); reply.setNickname(item.getString("fullname")); reply.setUid(item.getString("tid")); reply.setReplyId(item.getString("rid")); reply.setReplyTime(item.getString("addtime")); replys.add(reply); } } commentItem.setReplyLists(replys); commentItems.add(commentItem); } reader.close(); return commentItems; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } public static ArrayList<NoticesItem> downloadNoticesList(String RequestURL, String uId, String timeStamp, int noticeType) { Log.e(TAG, "nannan downloadNoticesList noticeType = " + noticeType); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; ArrayList<NoticesItem> noticeItems = new ArrayList<NoticesItem>(); try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject noticeContent = new JSONObject(); noticeContent.put("uid", uId); noticeContent.put("noticetype", noticeType); noticeContent.put("timestamp", timeStamp); Log.e(TAG, "nannan noticeContent = " + noticeContent.toString()); String content = null; content = "jsondata=" + URLEncoder.encode(noticeContent.toString(), "UTF-8"); if (content == null) return null; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan downloadNoticesList resp = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return null; } JSONArray respData = response.getJSONArray("data"); for (int index = 0; index < respData.length(); index++) { JSONObject notice = respData.getJSONObject(index); String noticeId = notice.getString("lid"); String uid = notice.getString("uid"); String fromUid = notice.getString("fromuid"); String timeLine = notice.getString("timeline"); int type = Integer.valueOf(notice.getString("noticetype")); String commentId = notice.getString("tid"); int isReceived = Integer.valueOf(notice.getString("recived")); NoticesItem item = new NoticesItem(); item.setNoticeId(noticeId); item.setUid(uid); item.setFromUid(fromUid); item.setTimeLine(timeLine); item.setNoticeType(type); item.setCommentId(commentId); item.setIsReceived(isReceived); noticeItems.add(item); } reader.close(); return noticeItems; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } public static ArrayList<NoticesItem> downloadBravosList(String RequestURL, String uId, String commentIds) { Log.e(TAG, "nannan downloadBravosList"); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; ArrayList<NoticesItem> noticeItems = new ArrayList<NoticesItem>(); try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject bravoContent = new JSONObject(); bravoContent.put(CommonDataStructure.UID, uId); bravoContent.put(CommonDataStructure.COMMENT_ID, commentIds); Log.e(TAG, "nannan noticeContent = " + bravoContent.toString()); String content = null; content = "jsondata=" + URLEncoder.encode(bravoContent.toString(), "UTF-8"); if (content == null) return null; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } // Log.e(TAG, "nannan resp 555555555555 = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return null; } JSONArray respData = response.getJSONArray("data"); for (int index = 0; index < respData.length(); index++) { JSONObject notice = respData.getJSONObject(index); String noticeId = notice.getString("lid"); String uid = notice.getString("uid"); String fromUid = notice.getString("fromuid"); String timeLine = notice.getString("timeline"); int type = Integer.valueOf(notice.getString("noticetype")); String commentId = notice.getString("tid"); int isReceived = Integer.valueOf(notice.getString("recived")); NoticesItem item = new NoticesItem(); item.setNoticeId(noticeId); item.setUid(uid); item.setFromUid(fromUid); item.setTimeLine(timeLine); item.setNoticeType(type); item.setCommentId(commentId); item.setIsReceived(isReceived); noticeItems.add(item); } reader.close(); return noticeItems; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } public static ArrayList<NoticesItem> downloadMyselfNoticesList( String RequestURL, String uId, String timeStamp, int noticeType) { Log.e(TAG, "nannan downloadNoticesList"); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; ArrayList<NoticesItem> noticeItems = new ArrayList<NoticesItem>(); try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject noticeContent = new JSONObject(); noticeContent.put("uid", uId); noticeContent.put("noticetype", noticeType); noticeContent.put("timestamp", timeStamp); Log.e(TAG, "nannan noticeContent = " + noticeContent.toString()); String content = null; content = "jsondata=" + URLEncoder.encode(noticeContent.toString(), "UTF-8"); if (content == null) return null; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan resp 555555555555 = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return null; } JSONArray respData = response.getJSONArray("data"); for (int index = 0; index < respData.length(); index++) { JSONObject notice = respData.getJSONObject(index); String noticeId = notice.getString("iid"); String uid = notice.getString("uid"); String timeLine = notice.getString("addtime"); int type = Integer.valueOf(notice.getString("logtype")); String commentId = notice.getString("tid"); NoticesItem item = new NoticesItem(); item.setNoticeId(noticeId); item.setUid(uid); item.setFromUid(uid); item.setTimeLine(timeLine); item.setNoticeType(type); item.setCommentId(commentId); noticeItems.add(item); } reader.close(); return noticeItems; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } public static ArrayList<ContactsInfo> downloadInDirectFriendsList( String RequestURL, String uId, String timeStamp) { Log.e(TAG, "nannan downloadInDirectFriendsList "); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; ArrayList<ContactsInfo> contactsList = new ArrayList<ContactsInfo>(); try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject contactContent = new JSONObject(); contactContent.put("uid", uId); contactContent.put("timestamp", timeStamp); String content = null; content = "jsondata=" + URLEncoder.encode(contactContent.toString(), "UTF-8"); if (content == null) return null; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan resp 555555555555 = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return null; } JSONArray respData = response.getJSONArray("data"); for (int index = 0; index < respData.length(); index++) { JSONObject contactsInfo = respData.getJSONObject(index); String inDirectId = contactsInfo.getString("indirectid"); String fromDirectUid = contactsInfo.getString("fromdirectuid"); String[] fromDirectUids = fromDirectUid.split(","); int directFriendsCount = fromDirectUids.length; JSONObject fromDirectName = contactsInfo .getJSONObject("fromdirectname"); String firstDirectName = fromDirectName .getString(fromDirectUids[0]); StringBuffer directFriends = new StringBuffer(); for (int point = 0; point < directFriendsCount; point++) { directFriends.append( fromDirectName.getString(fromDirectUids[point])) .append(" "); } JSONObject userinfo = contactsInfo.getJSONObject("userinfo"); String uid = userinfo.getString("uid"); String phoneNum = userinfo.getString("phone"); String nickname = userinfo.getString("nickname"); String realname = userinfo.getString("realname"); int avatar = Integer.valueOf(userinfo.getString("avatar")); int gender = Integer.valueOf(userinfo.getString("gender")); int astro = Integer.valueOf(userinfo.getString("astro")); int hobby = Integer.valueOf(userinfo.getString("hobby")); String headerbkg = userinfo.getString("systembackground"); String introduce = userinfo.getString("intro"); ContactsInfo contactItem = new ContactsInfo(); contactItem.setUid(uid); contactItem.setPhoneNum(phoneNum); contactItem.setNickName(nickname); contactItem.setRealName(realname); contactItem.setHeadPic(avatar); contactItem.setGender(gender); contactItem.setAstro(astro); contactItem.setHobby(hobby); contactItem.setIntroduce(introduce); contactItem.setIndirectId(inDirectId); contactItem.setFirstDirectFriend(firstDirectName); contactItem.setDirectFriends(directFriends.toString()); contactItem.setDirectFriendsCount(directFriendsCount); contactItem.setHeaderBkgIndex(headerbkg); contactsList.add(contactItem); } reader.close(); return contactsList; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } public static ContactsInfo downloadUserInfo(String RequestURL, String uId) { Log.e(TAG, "nannan downloadUserInfo "); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; ContactsInfo contact = new ContactsInfo(); try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject contactContent = new JSONObject(); contactContent.put("uid", uId); String content = null; content = "jsondata=" + URLEncoder.encode(contactContent.toString(), "UTF-8"); if (content == null) return null; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan resp 555555555555 = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return null; } JSONObject respData = response.getJSONObject("data"); String uid = respData.getString("uid"); String phoneNum = respData.getString("phone"); String nickname = respData.getString("nickname"); String realname = respData.getString("realname"); int avatar = Integer.valueOf(respData.getString("avatar")); int gender = Integer.valueOf(respData.getString("gender")); int astro = Integer.valueOf(respData.getString("astro")); int hobby = Integer.valueOf(respData.getString("hobby")); String headerbkg = respData.getString("systembackground"); String intruduce = respData.getString("intro"); String profession = respData.getString("profession"); contact.setUid(uid); contact.setPhoneNum(phoneNum); contact.setNickName(nickname); contact.setRealName(realname); contact.setHeadPic(avatar); contact.setGender(gender); contact.setAstro(astro); contact.setHobby(hobby); contact.setIndirectId("-1"); contact.setFirstDirectFriend(nickname); contact.setDirectFriends(nickname); contact.setDirectFriendsCount(0); contact.setHeaderBkgIndex(headerbkg); contact.setIntroduce(intruduce); contact.setProfession(profession); reader.close(); return contact; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } public static ArrayList<ReplysItem> downloadReplysList(String RequestURL, String uId, String commentId, String indirectIds, String timeStamp) { Log.e(TAG, "nannan downloadReplysList"); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; ArrayList<ReplysItem> replyItems = new ArrayList<ReplysItem>(); try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject replyContent = new JSONObject(); replyContent.put("uid", uId); replyContent.put("tid", commentId); replyContent.put("indirectuids", indirectIds); replyContent.put("datetime", timeStamp); String content = null; content = "jsondata=" + URLEncoder.encode(replyContent.toString(), "UTF-8"); if (content == null) return null; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } // Log.e(TAG, "nannan resp 555555555555 = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return null; } JSONArray respData = response.getJSONArray("data"); for (int index = 0; index < respData.length(); index++) { JSONObject reply = respData.getJSONObject(index); String replyid = reply.getString("rid"); String commentid = reply.getString("tid"); String uid = reply.getString("uid"); String replycontent = reply.getString("content"); String addtime = reply.getString("addtime"); String bucketId = String.valueOf(addtime.hashCode()); String nickname = reply.getString("fullname"); ReplysItem item = new ReplysItem(); item.setReplyId(replyid); item.setCommentId(commentid); item.setUid(uid); item.setReplyContents(replycontent); item.setReplyTime(addtime); item.setNickname(nickname); item.setBucketId(bucketId); replyItems.add(item); } reader.close(); return replyItems; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } public static ArrayList<CommentsItem> downloadCommentsList( String RequestURL, String uid, String indirectid, String tid, String count, String timestamp) { Log.e(TAG, "nannan downloadCommentsList 4444444444"); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; ArrayList<CommentsItem> commentItems = new ArrayList<CommentsItem>(); try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject commentContent = new JSONObject(); commentContent.put("uid", uid); commentContent.put("indirectuids", indirectid); commentContent.put("tid", tid); commentContent.put("count", count); commentContent.put("datetime", timestamp); String content = null; content = "jsondata=" + URLEncoder.encode(commentContent.toString(), "UTF-8"); if (content == null) return null; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan resp 555555555555 = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return null; } JSONArray respData = response.getJSONArray("data"); for (int index = 0; index < respData.length(); index++) { JSONObject comment = respData.getJSONObject(index); CommentsItem commentItem = new CommentsItem(); commentItem.setUid(comment.getString("uid")); commentItem.setCommentId(comment.getString("tid")); commentItem.setAddTime(comment.getString("addtime")); commentItem.setContents(comment.getString("content")); commentItem.setRealName(comment.getString("fullname")); commentItem.setNickName(comment.getString("fullname")); int photoCount = Integer.valueOf(comment.getString("pics")); commentItem.setPhotoCount(photoCount); if (photoCount > 0) { ArrayList<ImagesItem> images = new ArrayList<ImagesItem>(); JSONObject picsInfo = comment.getJSONObject("pics_info"); Iterator<String> iterator = picsInfo.keys(); while (iterator.hasNext()) { ImagesItem image = new ImagesItem(); image.setUid(comment.getString("uid")); image.setCommentId(comment.getString("tid")); image.setAddTime(comment.getString("addtime")); image.setBucketId(String.valueOf(comment.getString( "addtime").hashCode())); String position = iterator.next(); image.setPhotoPosition(position); JSONObject info = picsInfo.getJSONObject(position); String pid = info.getString("pid"); String type = info.getString("ext"); image.setPhotoId(pid); image.setPhotoType(type); image.setPhotoName(comment.getString("tid") + "_" + position); image.setPhotoRemoteOrgPath(CommonDataStructure.REMOTE_ORG_PHOTO_PATH + comment.getString("tid") + "_" + position + "." + type); image.setPhotoRemoteSmallThumbPath(CommonDataStructure.REMOTE_SMALL_THUMB_PHOTO_PATH + comment.getString("tid") + "_" + position + "." + type); image.setPhotoRemoteBigThumbPath(CommonDataStructure.REMOTE_BIG_THUMB_PHOTO_PATH + comment.getString("tid") + "_" + position + "." + type); images.add(image); } commentItem.setImages(images); } commentItems.add(commentItem); } reader.close(); return commentItems; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } public static void showMesage(Context context, int resId) { Toast.makeText(context, resId, Toast.LENGTH_SHORT).show(); } public static File getCachedImageFile(String imageUri, String cacheFilePath) { File imageFile = null; try { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { String imageName = getImageName(imageUri); File cacheDir = new File(cacheFilePath); if (!cacheDir.exists()) { cacheDir.mkdirs(); File nomedia = new File(cacheDir, ".nomedia"); nomedia.createNewFile(); } imageFile = new File(cacheDir, imageName); if (imageFile.isFile() && imageFile.exists()) { imageFile.delete(); } Log.i(TAG, "exists:" + imageFile.exists() + ", cacheDir:" + cacheDir + ", imageName:" + imageName); } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "getCacheFileError:" + e.getMessage()); } return imageFile; } public static String getImageName(String path) { int index = path.lastIndexOf(File.separator); return path.substring(index + 1); } public static File downloadImageAndCache(String RequestURL, String cacheFilePath) { URL postUrl = null; HttpURLConnection connection = null; File imageFile = getCachedImageFile(RequestURL, cacheFilePath); try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); BufferedOutputStream output = null; output = new BufferedOutputStream(new FileOutputStream(imageFile)); Log.e(TAG, "write file to " + imageFile.getAbsolutePath()); byte[] buf = new byte[1024]; int len = 0; // cache the image to local while ((len = input.read(buf)) > 0) { output.write(buf, 0, len); } input.close(); output.close(); } catch (IOException exp) { exp.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return imageFile; } public static Bitmap downloadHeadPicBitmap(String RequestURL) { URL postUrl = null; HttpURLConnection connection = null; Bitmap headPicBitmap = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); headPicBitmap = ImageUtils.inputStreamToBitmap(input); input.close(); } catch (Exception exp) { exp.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return headPicBitmap; } public static String uploadChatMsg(String RequestURL, String fromUid, String toUid, String chatContent) { Log.e(TAG, "nannan uploadChatMsg "); String chatTime = ""; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return chatTime; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return chatTime; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject chatMsg = new JSONObject(); chatMsg.put(CommonDataStructure.UID, fromUid); chatMsg.put(CommonDataStructure.TOUID, toUid); chatMsg.put(CommonDataStructure.COMMENT_CONTENT, chatContent); String content = "jsondata=" + URLEncoder.encode(chatMsg.toString(), "UTF-8"); Log.e(TAG, "nannan chatMsg = " + chatMsg.toString()); Log.e(TAG, "nannan content = " + content); if (content == null) return chatTime; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString() + "#################"); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return chatTime; } chatTime = response.getString("data"); inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return chatTime; } public static String registerUserInfo(String RequestURL, String phoneNum, String password, String macAddr) { Log.e(TAG, "nannan registerUserInfo "); String result = ""; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return result; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return result; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject chatMsg = new JSONObject(); chatMsg.put(CommonDataStructure.PHONE, phoneNum); chatMsg.put(CommonDataStructure.PASSWORD, password); chatMsg.put(CommonDataStructure.MAC, macAddr); String content = "jsondata=" + URLEncoder.encode(chatMsg.toString(), "UTF-8"); Log.e(TAG, "nannan content = " + content); if (content == null) return result; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString() + "#################"); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return result; } result = response.getJSONObject("data").getString("uid"); inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return result; } public static String loginSystem(String RequestURL, String phoneNum, String password, String macAddr) { Log.e(TAG, "nannan loginSystem "); String result = ""; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return result; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return result; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject chatMsg = new JSONObject(); chatMsg.put(CommonDataStructure.PHONE, phoneNum); chatMsg.put(CommonDataStructure.PASSWORD, password); chatMsg.put(CommonDataStructure.MAC, macAddr); String content = "jsondata=" + URLEncoder.encode(chatMsg.toString(), "UTF-8"); Log.e(TAG, "nannan content = " + content); if (content == null) return result; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString() + "#################"); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return result; } result = response.getJSONObject("data").getString("uid"); inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return result; } public static String updateUserInfo(String RequestURL, String uid, String nickname, int gender, int astro, int hobby, String intro, String profession) { Log.e(TAG, "nannan updateUserInfo "); String result = ""; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return result; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return result; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject chatMsg = new JSONObject(); chatMsg.put(CommonDataStructure.UID, uid); chatMsg.put(CommonDataStructure.NICKNAME, nickname); chatMsg.put(CommonDataStructure.GENDER, String.valueOf(gender)); chatMsg.put(CommonDataStructure.ASTRO, String.valueOf(astro)); chatMsg.put(CommonDataStructure.HOBBY, String.valueOf(hobby)); chatMsg.put(CommonDataStructure.INTRODUCE, intro); chatMsg.put(CommonDataStructure.PROFESSION, profession); String content = "jsondata=" + URLEncoder.encode(chatMsg.toString(), "UTF-8"); Log.e(TAG, "nannan content = " + content); if (content == null) return result; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString() + "#################"); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return result; } result = response.getJSONObject("data").getString("uid"); inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return result; } public static void waitWithoutInterrupt(Object object) { try { object.wait(); } catch (InterruptedException e) { Log.w(TAG, "unexpected interrupt: " + object); } } public static boolean handleInterrruptedException(Throwable e) { // A helper to deal with the interrupt exception // If an interrupt detected, we will setup the bit again. if (e instanceof InterruptedIOException || e instanceof InterruptedException) { Thread.currentThread().interrupt(); return true; } return false; } public static ChatMsgItem downloadChatMsg(String RequestURL, String uId) { Log.e(TAG, "nannan downloadChatMsg"); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; ChatMsgItem chatItems = new ChatMsgItem(); try { postUrl = new URL(RequestURL); if (postUrl == null) return null; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return null; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject replyContent = new JSONObject(); replyContent.put("uid", uId); String content = null; content = "jsondata=" + URLEncoder.encode(replyContent.toString(), "UTF-8"); if (content == null) return null; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan resp 555555555555 = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return null; } JSONObject reply = response.getJSONObject("data"); String fromUid = reply.getString("from"); String toUid = reply.getString("to"); String chatmsg = reply.getString("content"); String chattime = reply.getString("timeline"); String chatId = toUid + "_" + fromUid; chatItems.setUid(uId); chatItems.setFromUid(fromUid); chatItems.setToUid(toUid); chatItems.setMsgType(IMsgViewType.IMVT_COM_MSG); chatItems.setChatContent(chatmsg); chatItems.setChatId(chatId); chatItems.setAddedTime(chattime); chatItems .setCurrentStatus(MarrySocialDBHelper.DOWNLOAD_FROM_CLOUD_SUCCESS); reader.close(); return chatItems; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } public static String getPhoneNumber(Context context) { TelephonyManager mTelephonyMgr = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); return mTelephonyMgr.getLine1Number(); } public static boolean isMobilePhoneNum(String mobiles) { /* * 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188 * 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通) * 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9 */ String telRegex = "[1][3578]\\d{9}";// "[1]"代表第1位为数字1,"[3578]"代表第二位可以为3、5、7、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。 if (TextUtils.isEmpty(mobiles)) return false; else return mobiles.matches(telRegex); } public static boolean isPassworkValid(String password) { return password.length() >= 6; } public static String getMacAddress(Context context) { String macAddress = ""; try { WifiManager wifiMgr = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo info = (wifiMgr == null ? null : wifiMgr .getConnectionInfo()); if (info != null) { macAddress = info.getMacAddress(); } } catch (Exception e) { e.printStackTrace(); } return macAddress; } public static ArrayList<ContactsInfo> uploadUserContacts(String RequestURL, String uid, ArrayList<ContactsInfo> contactsList) { Log.e(TAG, "nannan uploadUserContacts "); ArrayList<ContactsInfo> contactEntrys = new ArrayList<ContactsInfo>(); URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return contactEntrys; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return contactEntrys; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONArray contactList = new JSONArray(); for (ContactsInfo entry : contactsList) { JSONObject contact = new JSONObject(); contact.put(CommonDataStructure.FULLNAME, entry.getNickName()); contact.put(CommonDataStructure.PHONE, entry.getPhoneNum()); contact.put(CommonDataStructure.UID, uid); contactList.put(contact); } JSONObject contact = new JSONObject(); contact.put("contacts", contactList.toString()); String content = "jsondata=" + URLEncoder.encode(contact.toString(), "UTF-8"); Log.e(TAG, "nannan contacts = " + contactList.toString()); Log.e(TAG, "nannan content = " + content); if (content == null) return contactEntrys; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan resp = " + resp.toString() + "#################"); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return contactEntrys; } JSONObject data = response.getJSONObject("data"); Iterator<String> iterator = data.keys(); while (iterator.hasNext()) { String phone_num = iterator.next(); JSONObject result = data.getJSONObject(phone_num); String direct_id = result.getString("directid"); String direct_uid = result.getString("directuid"); String direct_name = result.getString("directname"); ContactsInfo entry = new ContactsInfo(); entry.setDirectId(direct_id); entry.setUid(direct_uid); entry.setNickName(direct_name); entry.setPhoneNum(phone_num); contactEntrys.add(entry); } inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return contactEntrys; } public static boolean updateIndirectServer(String RequestURL, String uId) { Log.e(TAG, "nannan updateIndirectServer "); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; boolean result = false; try { postUrl = new URL(RequestURL); if (postUrl == null) return result; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return result; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject contactContent = new JSONObject(); contactContent.put("uid", uId); String content = null; content = "jsondata=" + URLEncoder.encode(contactContent.toString(), "UTF-8"); if (content == null) return result; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan resp 555555555555 = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return result; } String data = response.getString("data"); result = "true".equalsIgnoreCase(data); reader.close(); return result; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return result; } public static boolean userFeedback(String RequestURL, String uId, String context) { Log.e(TAG, "nannan userFeedback "); URL postUrl = null; HttpURLConnection connection = null; DataOutputStream output = null; boolean result = false; try { postUrl = new URL(RequestURL); if (postUrl == null) return result; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return result; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStream stream = connection.getOutputStream(); output = new DataOutputStream(stream); JSONObject contactContent = new JSONObject(); contactContent.put("uid", uId); contactContent.put("content", context); String content = null; content = "jsondata=" + URLEncoder.encode(contactContent.toString(), "UTF-8"); if (content == null) return result; output.writeBytes(content); output.flush(); output.close(); BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan resp 555555555555 = " + resp); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return result; } result = true; reader.close(); return result; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return result; } public static boolean sendAuthCode(String RequestURL, String phoneNum, String macAddr, String authCode) { Log.e(TAG, "nannan sendAuthCode "); boolean resultCode = false; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return resultCode; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return resultCode; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject authCodeContent = new JSONObject(); authCodeContent.put(CommonDataStructure.PHONE, phoneNum); authCodeContent.put(CommonDataStructure.MAC, macAddr); authCodeContent.put(CommonDataStructure.AUTH_CODE, authCode); String content = "jsondata=" + URLEncoder.encode(authCodeContent.toString(), "UTF-8"); Log.e(TAG, "nannan authCodeContent = " + authCodeContent.toString()); Log.e(TAG, "nannan content = " + content); if (content == null) return resultCode; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString()); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return resultCode; } resultCode = "true".equalsIgnoreCase(response.getString("data")); inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return resultCode; } public static boolean changePassword(String RequestURL, String phoneNum, String password, String macAddr) { Log.e(TAG, "nannan changePassword "); boolean resultCode = false; URL postUrl = null; DataOutputStream outputStream = null; HttpURLConnection connection = null; OutputStreamWriter outputWriter = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return resultCode; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return resultCode; connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); outputStream = new DataOutputStream(connection.getOutputStream()); JSONObject changePasswordContent = new JSONObject(); changePasswordContent.put(CommonDataStructure.PHONE, phoneNum); changePasswordContent.put(CommonDataStructure.PASSWORD, password); changePasswordContent.put(CommonDataStructure.MAC, macAddr); String content = "jsondata=" + URLEncoder.encode(changePasswordContent.toString(), "UTF-8"); Log.e(TAG, "nannan changePasswordContent = " + changePasswordContent.toString()); Log.e(TAG, "nannan content = " + content); if (content == null) return resultCode; outputStream.writeBytes(content); outputStream.flush(); outputStream.close(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } Log.e(TAG, "nannan resp = " + resp.toString()); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return resultCode; } resultCode = true; inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return resultCode; } public static boolean isAppRunningForeground(Context context) { ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); ComponentName cn = am.getRunningTasks(1).get(0).topActivity; String currentPackageName = cn.getPackageName(); if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName())) { return true; } return false; } public static int dp2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } public static int px2dp(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } public static String getLatestAppVersion(String RequestURL) { Log.e(TAG, "nannan getLatestAppVersion "); String result = "0"; URL postUrl = null; HttpURLConnection connection = null; BufferedReader inputReader = null; try { postUrl = new URL(RequestURL); if (postUrl == null) return result; connection = (HttpURLConnection) postUrl.openConnection(); if (connection == null) return result; connection.setDoInput(true); connection.connect(); inputReader = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuffer resp = new StringBuffer(); String line = null; while ((line = inputReader.readLine()) != null) { resp.append(line); } // String line = inputReader.readLine(); // inputReader.close(); Log.e(TAG, "nannan resp = " + resp.toString() + "#################"); JSONObject response = new JSONObject(resp.toString()); String code = response.getString("code"); if (!"200".equalsIgnoreCase(code)) { return result; } result = response.getJSONObject("data").getString("patch_ver"); inputReader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return result; } }
package com.example.cse.makeupapp; import android.arch.lifecycle.LiveData; import android.content.Context; import android.os.AsyncTask; import java.util.List; public class CosRepository { private static CosmeticDao cosmeticDao; private final LiveData<List<CosmeticModel>> getAllData; public CosRepository(Context context) { CosmeticDatabase contactDatabase = CosmeticDatabase.getInstance(context); cosmeticDao = contactDatabase.movieDao(); getAllData = cosmeticDao.getfav(); } LiveData<List<CosmeticModel>> getAllData() { return getAllData; } public void insert(CosmeticModel cosmeticModel) { new InsertTask().execute(cosmeticModel); } public void delete(CosmeticModel contact) { new DeleteTask().execute(contact); } public static class InsertTask extends AsyncTask<CosmeticModel, Void, Void> { @Override protected Void doInBackground(CosmeticModel... cosmeticModels) { cosmeticDao.insertCos(cosmeticModels[0]); return null; } } public static class DeleteTask extends AsyncTask<CosmeticModel, Void, Void> { @Override protected Void doInBackground(CosmeticModel... cosmeticModels) { cosmeticDao.deleteCos(cosmeticModels[0]); return null; } } String read(String id){ return cosmeticDao.read(id); } }
package io.github.wukn.demo; import com.google.common.util.concurrent.RateLimiter; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import java.util.concurrent.TimeUnit; @SpringBootApplication public class GuavaRateLimiterDemoApplication { public static void main(String[] args) { SpringApplication.run(GuavaRateLimiterDemoApplication.class, args); } @Bean public CommandLineRunner run(ApplicationContext ctx) { return args -> { limit(); System.out.println("simulate burst request traffic"); limit2(); System.out.println("simulate burst request traffic after bucker is full"); limit3(); System.out.println("try acquire"); limit4(); }; } public void limit() { // 每秒向桶中放入5个Token final RateLimiter limiter = RateLimiter.create(5); for (int i = 0; i < 10; i++) { // 从桶中获取1个Token double waitTime = limiter.acquire(); System.out.println(waitTime); } } public void limit2() { // 每秒向桶中放入5个Token final RateLimiter limiter = RateLimiter.create(5); // 产生突发流量时,一次从桶中获取5个Token System.out.println(limiter.acquire(5)); System.out.println(limiter.acquire()); } public void limit3() throws Exception { // 每秒向桶中放入5个Token final RateLimiter limiter = RateLimiter.create(5); // 休眠1秒,让桶中被放满Token Thread.sleep(1000L); // 产生突发流量时,一次从桶中获取5个Token System.out.println(limiter.acquire(5)); System.out.println(limiter.acquire()); } public void limit4() { // 每秒向桶中放入5个Token,缓冲时间为1秒 final RateLimiter limiter = RateLimiter.create(5, 1, TimeUnit.SECONDS); // 尝试从桶中获取Token,获取不到则不等待立即返回false boolean result = limiter.tryAcquire(); if (result) { System.out.println("get token success!"); } else { System.out.println("get token failed."); } // 尝试从桶中获取Token,只等待10毫秒 result = limiter.tryAcquire(10, TimeUnit.MILLISECONDS); if (result) { System.out.println("get token success!"); } else { System.out.println("get token failed."); } } }
package ru.otus.l141.sort; import java.util.Arrays; import java.util.Comparator; /** * The algorithm belongs to the group of Divide and Conquer family of * algorithms. * This basically means that it divides the sorting problem into smaller * parts to solve. * * @param <T> the type of elements in the target array, must be Comparable. */ public class MergeSort<T extends Comparable<? super T>> { // Decides when to fork or compute directly: private static final int SORT_THRESHOLD = 32; private Comparator<T> comparator = Comparator.naturalOrder(); public MergeSort() { /* None */ } /** * TODO comments * * @param comparator */ public MergeSort(Comparator<T> comparator) { this.comparator = comparator; } /** * TODO comments * * @param array */ public void sort(T[] array) { mergeSort(array, 0, array.length-1); } private boolean indexOutOfBounds(T[] array, int index) { return index < 0 || index >= array.length; } /** * TODO comments * * @param array * @param from * @param to */ public void sort(T[] array, int from, int to) { if (indexOutOfBounds(array, from) || indexOutOfBounds(array, to)) { throw new ArrayIndexOutOfBoundsException(); } mergeSort(array, from, to); } private void insertionSort(T[] array, int from, int to) { for (int i = from+1; i <= to; ++i) { T current = array[i]; int j = i-1; while (from <= j && comparator.compare(current, array[j]) < 0) { array[j+1] = array[j--]; } array[j+1] = current; } } void mergeSort(T[] array, int from, int to) { if (from < to) { int size = to - from; if (size < SORT_THRESHOLD) { insertionSort(array, from, to); } else { int mid = from + Math.floorDiv(to - from, 2); mergeSort(array, from, mid); mergeSort(array, mid + 1, to); merge(array, from, mid, to); } } } void merge(T[] array, int from, int mid, int to) { T[] left = Arrays.copyOfRange(array, from, mid+1); T[] right = Arrays.copyOfRange(array, mid+1, to+1); int li = 0, ri = 0; while (li < left.length && ri < right.length) { if (comparator.compare(left[li], right[ri]) < 0) { array[from++] = left[li++]; } else { array[from++] = right[ri++]; } } while (li < left.length) { array[from++] = left[li++]; } while (ri < right.length) { array[from++] = right[ri++]; } } }
package com.ebupt.portal.canyon.common.listener; import com.ebupt.portal.canyon.common.enums.UpdateEnum; import com.ebupt.portal.canyon.common.util.EncryptUtil; import com.ebupt.portal.canyon.common.util.SystemConstant; import com.ebupt.portal.canyon.system.service.UserService; import com.ebupt.portal.canyon.system.vo.UserVo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 项目启动成功后初始化用户 * * @author chy * @date 2019-03-19 14:27 */ @Component @Order(1) @Slf4j public class InitUserApplicationRunner implements ApplicationRunner { private final UserService userService; @Autowired public InitUserApplicationRunner(UserService userService) { this.userService = userService; } @Value("${login.salt}") private String salt; @Override public void run(ApplicationArguments args) { UserVo userVo = new UserVo("root", EncryptUtil.md5("root" + salt + "1qaz@WSX"), "", "", "", 0); UpdateEnum result = this.userService.save(userVo, false); if (result.getCode() == SystemConstant.UPDATE_ENUM_SUCCESS) { log.info("系统第一次运行,初始化用户root,密码为1qaz@WSX,请登录后第一时间完善用户信息并修改初始密码"); } } }
package com.sdk4.boot.trace; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; import java.util.ArrayList; import java.util.List; /** * @author sh */ @Slf4j public class Eye { protected static final ThreadLocal<List<LocalContext_inner>> localStack = new ThreadLocal(); public static void startTrace(String traceId, String rpcId, String traceName) { if (traceName == null) { return; } RpcContext_inner ctx = RpcContext_inner.get(); if (ctx != null && ctx.traceId != null) { if (!ctx.traceId.equals(traceId) || !traceName.equals(ctx.traceName)) { log.warn("duplicated startTrace detected, overrided {} ({}) to {} ({})", ctx.traceId, ctx.traceName, traceId, traceName); endTrace(false); } else { return; } } try { ctx = new RpcContext_inner(traceId, rpcId); RpcContext_inner.set(ctx); ctx.startTrace(traceName); localStack.set(new ArrayList<>()); } catch (Throwable re) { log.error("startTrace error", re); } } public static void startLocal(String serviceName, String methodName) { try { RpcContext_inner ctx = RpcContext_inner.get(); if (null == ctx) { return; } RpcContext_inner cloneCtx = ctx.cloneInstance(); RpcContext_inner.set(cloneCtx); LocalContext_inner localCtx = cloneCtx.startLocal(serviceName, methodName); localStack.get().add(localCtx); } catch (Throwable re) { log.error("startLocal error", re); } } public static void endLocal() { try { RpcContext_inner ctx = RpcContext_inner.get(); if (null == ctx) { return; } ctx.endLocal(); } catch (Throwable re) { log.error("endLocal error", re); } } public static long getCost() { RpcContext_inner root = RpcContext_inner.get(); if (null == root) { return 0; } return System.currentTimeMillis() - root.getStartTime(); } public static String endTrace(boolean returnStackLog) { String stackLog = ""; try { RpcContext_inner root = RpcContext_inner.get(); if (null == root) { return ""; } while (null != root.parentRpc) { root = root.parentRpc; } root.endTrace(); if (returnStackLog) { stackLog = getStackLog(root); } commitRpcContext(root); localStack.set(null); } catch (Throwable re) { log.error("endTrace error", re); } finally { clearRpcContext(); } return stackLog; } public static void clearRpcContext() { RpcContext_inner.set(null); } public static String getStackLog(RpcContext_inner ctx) { StringBuilder logStr = new StringBuilder(); logStr.append(new DateTime(ctx.startTime).toString("[yyyy-MM-dd HH:mm:ss.SSS]")); logStr.append(ctx.getTraceName()); List<LocalContext_inner> localCtxList = localStack.get(); for (LocalContext_inner localCtx : localCtxList) { logStr.append('\n'); logStr.append(localCtx.getLocalId()); logStr.append('#'); logStr.append(localCtx.getServiceName()); logStr.append('#'); logStr.append(localCtx.getMethodName()); logStr.append('#'); logStr.append(localCtx.getCost()); logStr.append("ms"); } return logStr.toString(); } public static void commitRpcContext(RpcContext_inner ctx) { } static void commitLocalContext(LocalContext_inner ctx) { } }
package com.zemal.web.configurer; import com.zemal.web.interceptor.UserAuthInteceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { // 添加一个拦截器,连接以/admin为前缀的 url路径 registry.addInterceptor(new UserAuthInteceptor()).addPathPatterns("/chatroom/**").excludePathPatterns("/static/**"); } }
import java.util.ArrayList; public class FlippingAnImage { public static int[][] flipAndInvertImage1(int[][] image) { ArrayList<int[]> keepThis = new ArrayList<>(); int[][] res = new int[image.length][]; for (int[] im : image){ int[] newIm = new int[im.length]; int len = im.length; for (int i = 0;i< im.length;i++){ newIm[len-1] = im[i]; len--; } for (int i = 0;i< newIm.length;i++){ if (newIm[i] == 0){ newIm[i] = 1; } else { newIm[i] = 0; } } keepThis.add(newIm); } res = keepThis.toArray(new int[0][]); return res; } public static int[][] flipAndInvertImage(int[][] image) { for (int j = 0;j< image.length;j++){ int[] newIm = new int[image[j].length]; int len = image[j].length; for (int i = 0;i< image[j].length;i++){ newIm[len-1] = image[j][i]; len--; } for (int i = 0;i< newIm.length;i++){ if (newIm[i] == 0){ newIm[i] = 1; } else { newIm[i] = 0; } } image[j] = newIm; } return image; } public static void main(String[] args) { int[][] send = {{1,1,0},{1,0,1},{0,0,0}}; int[][] res = flipAndInvertImage(send); for (int[] im:res){ for (int i = 0;i< im.length;i++){ System.out.println(im[i]); } } } }
package com.joshuarichardson.dependencyinjection; import android.content.Context; import com.joshuarichardson.dependencyinjection.Modules.DatabaseEntity; import com.joshuarichardson.dependencyinjection.Modules.NameDao; import com.joshuarichardson.dependencyinjection.Modules.WellbeingDatabase; import java.util.ArrayList; import dagger.Module; import dagger.Provides; import dagger.hilt.InstallIn; import dagger.hilt.android.components.ApplicationComponent; import dagger.hilt.android.qualifiers.ApplicationContext; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; //@Module //@InstallIn(ApplicationComponent.class) //public class TestDatabaseModule { // @Provides // public WellbeingDatabase provideDatabaseService(@ApplicationContext Context context) { // WellbeingDatabase databaseMock = mock(WellbeingDatabase.class); // NameDao nameDao = mock(NameDao.class); // // ArrayList<DatabaseEntity> array = new ArrayList<>(); // array.add(new DatabaseEntity(4)); // // when(nameDao.insert(any(DatabaseEntity.class))).thenReturn(0L); // when(nameDao.getEntities()).thenReturn(array); // // when(databaseMock.nameDao()).thenReturn(nameDao); // // return databaseMock; // } //}
package com.tencent.mm.plugin.game.ui; import android.widget.ImageView; import android.widget.TextView; class i$a { public ImageView eKk; public TextView gwk; final /* synthetic */ i jVV; public TextView jVW; public TextView jVX; public TextView jVY; GameDetailRankLikeView jVZ; private i$a(i iVar) { this.jVV = iVar; } /* synthetic */ i$a(i iVar, byte b) { this(iVar); } }
package sample; public class Etudiant extends sample.Personne { private int mat; private static int matricule=0000; public String spec; public Etudiant(String nom, String prenom, Date naisssance, String specialite) { super(nom, prenom, naisssance); matricule++; mat=matricule; spec= specialite; } public Etudiant(String nom, String prenom, String jour, String mois, String anneé, String specialite) { super(nom, prenom, jour, mois, anneé); matricule++; mat=matricule; spec=specialite; } public String getSpec() { return spec; } public int getMat() { return mat; } @Override public String getNom() { return super.getNom(); } @Override public String getPrenom() { return super.getPrenom(); } @Override public Date getNaissance() { return super.getNaissance(); } @Override public String toString() { return super.toString() + " matricule=" + mat+", Section : "+spec+"\n" ; } public void afficher(){ System.out.println(this); } }
package server.model; /** * Represents a Cost Center object */ public class CostCenter { private String id; private String location; /** * Creates a cost center object * @param id The id of the cost center in the database * @param location The location of the cost center in the database */ public CostCenter(String id, String location) { this.id = id; this.location = location; } /** * Gets the id of the cost center * @return The id of the cost center */ public String getId() { return id; } /** * Gets the location of the cost center * @return The location of the cost center */ public String getLocation() { return location; } }
package com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.net; import com.amazon.opendistro.elasticsearch.performanceanalyzer.grpc.SubscribeResponse; import com.amazon.opendistro.elasticsearch.performanceanalyzer.net.GRPCConnectionManager; import com.google.common.collect.Sets; import java.util.Collections; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class SubscriptionManagerTest { private GRPCConnectionManager grpcConnectionManager; private SubscriptionManager uut; @Before public void setup() { grpcConnectionManager = new GRPCConnectionManager(true); uut = new SubscriptionManager(grpcConnectionManager); } @Test public void testAddAndGetPublishers() { String testNode = "testNode"; String ip1 = "127.0.0.1"; String ip2 = "127.0.0.2"; Assert.assertEquals(Collections.emptySet(), uut.getPublishersForNode(testNode)); uut.addPublisher(testNode, ip1); Assert.assertEquals(Sets.newHashSet(ip1), uut.getPublishersForNode(testNode)); uut.addPublisher(testNode, ip2); Assert.assertEquals(Sets.newHashSet(ip1, ip2), uut.getPublishersForNode(testNode)); } @Test public void testSubscriptionFlow() { String testNode = "testNode"; String ip1 = "127.0.0.1"; String ip2 = "127.0.0.2"; String locus = "data-node"; // Test that addSubscriber doesn't work on non-matching loci SubscribeResponse.SubscriptionStatus status = uut.addSubscriber(testNode, ip1, locus); Assert.assertEquals(SubscribeResponse.SubscriptionStatus.TAG_MISMATCH, status); Assert.assertFalse(uut.isNodeSubscribed(testNode)); // Test that addSubscriber works for matching loci uut.setCurrentLocus(locus); status = uut.addSubscriber(testNode, ip1, locus); Assert.assertEquals(SubscribeResponse.SubscriptionStatus.SUCCESS, status); Assert.assertEquals(Sets.newHashSet(ip1), uut.getSubscribersFor(testNode)); Assert.assertTrue(uut.isNodeSubscribed(testNode)); // Test that addSubscriber works on repeated calls status = uut.addSubscriber(testNode, ip2, locus); Assert.assertEquals(SubscribeResponse.SubscriptionStatus.SUCCESS, status); Assert.assertEquals(Sets.newHashSet(ip1, ip2), uut.getSubscribersFor(testNode)); Assert.assertTrue(uut.isNodeSubscribed(testNode)); // Add host connections to the grpcConnectionManager grpcConnectionManager.getClientStubForHost(ip1); Assert.assertTrue(grpcConnectionManager.getPerHostChannelMap().containsKey(ip1)); Assert.assertTrue(grpcConnectionManager.getPerHostClientStubMap().containsKey(ip1)); grpcConnectionManager.getClientStubForHost(ip2); Assert.assertTrue(grpcConnectionManager.getPerHostChannelMap().containsKey(ip2)); Assert.assertTrue(grpcConnectionManager.getPerHostClientStubMap().containsKey(ip2)); // Test that unsubscribeAndTerminateConnection always terminates a connection // TODO is this actually the behavior we intended? uut.unsubscribeAndTerminateConnection("nonExistentNode", ip1); Assert.assertFalse(grpcConnectionManager.getPerHostChannelMap().containsKey(ip1)); Assert.assertFalse(grpcConnectionManager.getPerHostClientStubMap().containsKey(ip1)); // Test that unsubscribeAndTerminateConnection properly updates the underlying map grpcConnectionManager.getClientStubForHost(ip2); uut.unsubscribeAndTerminateConnection(testNode, ip2); Assert.assertEquals(Sets.newHashSet(ip1), uut.getSubscribersFor(testNode)); Assert.assertTrue(uut.isNodeSubscribed(testNode)); Assert.assertFalse(grpcConnectionManager.getPerHostChannelMap().containsKey(ip2)); Assert.assertFalse(grpcConnectionManager.getPerHostClientStubMap().containsKey(ip2)); // Test that unsubscribeAndTerminateConnection doesn't update the underlying map for non existent addresses uut.unsubscribeAndTerminateConnection(testNode, "nonExistentAddress"); Assert.assertEquals(Sets.newHashSet(ip1), uut.getSubscribersFor(testNode)); Assert.assertTrue(uut.isNodeSubscribed(testNode)); // Test that unsubscribeAndTerminateConnection removes the node from the map once all of its subscriptions are // terminated uut.unsubscribeAndTerminateConnection(testNode, ip1); Assert.assertEquals(Collections.emptySet(), uut.getSubscribersFor(testNode)); Assert.assertFalse(uut.isNodeSubscribed(testNode)); } }
package de.zarncke.lib.coll; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * Compare in order until != 0 reached. * * @author Gunnar Zarncke * @param <T> */ public class CompositeComparator<T> implements Comparator<T> { // TODO consider replacement by Ordering.compound private final List<? extends Comparator<T>> comparators; public static <T> CompositeComparator<T> create(final List<? extends Comparator<T>> comparators) { return new CompositeComparator<T>(comparators); } public static <T> CompositeComparator<T> create(final Comparator<T>... comparators) { return new CompositeComparator<T>(Arrays.asList(comparators)); } public CompositeComparator(final List<? extends Comparator<T>> comparators) { this.comparators = comparators; } public int compare(final T o1, final T o2) { for (Comparator<T> cmp : this.comparators) { int res = cmp.compare(o1, o2); if (res != 0) { return res; } } return 0; } }
package com.eup.rxandroidsearchdemo; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.widget.SearchView; import com.eup.rxandroidsearchdemo.adapter.StudentAdapter; import com.eup.rxandroidsearchdemo.data.DataSourcev; import com.eup.rxandroidsearchdemo.databinding.ActivityMainBinding; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import javax.sql.DataSource; import butterknife.BindView; import butterknife.ButterKnife; import io.reactivex.ObservableSource; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { private ActivityMainBinding binding; private StudentAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this,R.layout.activity_main); ButterKnife.bind(this); StudentAdapter adapter = new StudentAdapter(); adapter.addStudentNames(DataSourcev.getStudentList()); binding.rvStudentList.setLayoutManager(new LinearLayoutManager(this)); binding.rvStudentList.setAdapter(adapter); initSearchFeature(adapter); } private void initSearchFeature(StudentAdapter adapter) { RxSearchObservable.fromSearchView(binding.svKey) .debounce(500, TimeUnit.MILLISECONDS) .filter(text -> !text.isEmpty()) .distinctUntilChanged() .switchMap(new Function<String, ObservableSource<ArrayList<String>>>() { @Override public ObservableSource<ArrayList<String>> apply(@NonNull String key) throws Exception { return DataSourcev.getSearchData(key); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(names -> { // adapter.removeAllNames(); adapter.addStudentNames(names); }); } }
/* * Copyright 2010-2013 Robert J. Buck * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.buck.jsql.expressions; import com.buck.jsql.Expression; import com.buck.jsql.ExpressionType; /** * Base class for all binary operators. * * @author Robert J. Buck */ public abstract class TernaryExpression extends Expression { /** * Constructor * * @param type the node type * @param op1 the first expression to evaluate * @param op2 the second expression to evaluate * @param op3 the third expression to evaluate */ protected TernaryExpression(ExpressionType type, Expression op1, Expression op2, Expression op3) { super(type); addChild(op1, 0); op1.setParent(this); addChild(op2, 1); op2.setParent(this); addChild(op3, 2); op3.setParent(this); } protected Expression getFirst() { return getChild(0); } protected Expression getSecond() { return getChild(1); } protected Expression getThird() { return getChild(2); } }
package com.bingo.code.example.design.visitor.nodesign; /** * ���˿ͻ� */ public class PersonalCustomer extends Customer{ /** * ��ϵ�绰 */ private String telephone; /** * ���� */ private int age; public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } /** * ���˿ͻ������������ķ�����ʾ��һ�� */ public void serviceRequest(){ //���˿ͻ�����ľ���������� System.out.println("�ͻ�"+this.getName()+"�����������"); } }
package assignment; import java.applet.Applet; import java.applet.AudioClip; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import processing.core.PApplet; import processing.core.PFont; import processing.core.PVector; public class MainApp extends PApplet { public int SCREEN_SIZE = 700; //Paddle Paddle paddle; PVector paddleSize = new PVector(SCREEN_SIZE/7, SCREEN_SIZE/30); float CONTRACTED_PADDLE_WIDTH = SCREEN_SIZE/7; float EXTENDED_PADDLE_WIDTH = SCREEN_SIZE/4; //The timer for the extended paddle, as well as the maximum time that it will remain extended int extendedPaddleTimer = 0, PADDLE_EXTEND_TIME = 1000; //Balls ArrayList <Ball> balls; int BALL_SIZE = SCREEN_SIZE/55; int DEFAULT_BALL_SPEED = SCREEN_SIZE/100; int HORIZANTAL_SPEED_SENSITIVITY = 8; //The minimum time before the next ball can be hit - this is to stop a glitch that allows the ball to hit two bricks at once int MINIMUM_TIME_BEFORE_NEXT_HIT = 1; boolean stickBallToPaddle = true; //Bricks ArrayList <Brick> bricks; PVector BRICK_SIZE = new PVector(SCREEN_SIZE*9/100, SCREEN_SIZE*3/100); PFont f = createFont("Arial", 20, true); int ballsLeft = 3; int currentLevel = 1; int AVAILIBLE_LEVELS = 4; boolean displayedIntroduction = false; boolean displayWinningMessage = false; boolean pauseState = false; boolean gameOverState = false; //powerups ArrayList <PowerUp> numPowerUps; final int CHANCE_OF_POWER_UP = 6; //the chance of a powerup dropping when a block is destroyed -e.g., 1 is a 100% chance, where as 2 is a 50% chance final int TYPES_OF_POWER_UPS = 2; final int POWER_UP_SIZE = SCREEN_SIZE/30; final int POWER_UP_SPEED = SCREEN_SIZE/300; int currentAmountOfBalls; public void setup() { size(SCREEN_SIZE, SCREEN_SIZE); smooth(); noCursor(); balls = new ArrayList(); paddle = new Paddle(); bricks = new ArrayList(); numPowerUps = new ArrayList(); spawnLevel(currentLevel); //Spawns the first level balls.add(new Ball(paddle.paddleLocation.x + paddleSize.x/2, paddle.paddleLocation.y - BALL_SIZE/2, 0, DEFAULT_BALL_SPEED)); //Spawns the first ball } public void draw() { background(0); AudioClip ac = getAudioClip(getDocumentBase(),"02 T-Shirt Weather.mp3"); ac.play(); for (int i = 0; i < balls.size(); i++) balls.get(i).renderBall(i); for (int i = 0; i < bricks.size(); i++) bricks.get(i).display(); for (int i = 0; i < numPowerUps.size(); i++) numPowerUps.get(i).renderPowerUp(i); paddle.display(); renderHUD(); if (balls.size() == 0) { ballsLeft--; stickBallToPaddle = true; numPowerUps.clear(); extendedPaddleTimer = 0; balls.add(new Ball(paddle.paddleLocation.x + paddleSize.x/2, paddle.paddleLocation.y - BALL_SIZE/2, 0, DEFAULT_BALL_SPEED)); } if (ballsLeft <= 0) gameOverState = true; //If there are no lives left, show the game over screen if (bricks.size() == 0 && currentLevel <=AVAILIBLE_LEVELS) { numPowerUps.clear(); balls.clear(); extendedPaddleTimer = 0; balls.add(new Ball(paddle.paddleLocation.x + paddleSize.x/2, paddle.paddleLocation.y - BALL_SIZE/2, 0, DEFAULT_BALL_SPEED)); stickBallToPaddle = true; currentLevel++; spawnLevel(currentLevel); } } class Paddle { //Class for the paddle PVector paddleLocation; Paddle() { this.paddleLocation = new PVector(SCREEN_SIZE/2, SCREEN_SIZE - paddleSize.y * 2); } void display() { //Method for rendering the paddle if (!pauseState) this.paddleLocation.x = mouseX - paddleSize.x / 2; //Extended properties of the paddle if (extendedPaddleTimer > 0) paddleSize.x = EXTENDED_PADDLE_WIDTH; else paddleSize.x = CONTRACTED_PADDLE_WIDTH; if (!pauseState) extendedPaddleTimer--; fill(255); rect(this.paddleLocation.x, this.paddleLocation.y, paddleSize.x, paddleSize.y); //Draws the paddle } } public class Ball { PVector ballLocation; PVector ballSpeed; int canNextBallBeHitTimer = 0; private int ballColor; Ball(float ballSpawnLocationX, float ballSpawnLocationY, float inputBallSpeedX, float inputBallSpeedY) { //Takes the nessessary inputs and creates a new ball with these properties this.ballLocation = new PVector(ballSpawnLocationX, ballSpawnLocationY); //Sets the inputed location to the new ball this.ballSpeed = new PVector(inputBallSpeedX, inputBallSpeedY); //Sets the speed of the ball } void renderBall(int ballNumber) { //Movement of the ball if (!pauseState) { this.ballLocation.x += this.ballSpeed.x; this.ballLocation.y += this.ballSpeed.y; } //Collision of the ball with the walls if (this.ballLocation.x < BALL_SIZE && this.ballSpeed.x < 0) this.ballSpeed.x = -this.ballSpeed.x; if (this.ballLocation.x > SCREEN_SIZE - BALL_SIZE && this.ballSpeed.x > 0) this.ballSpeed.x = -this.ballSpeed.x; if (this.ballLocation.y < BALL_SIZE && this.ballSpeed.y < 0) this.ballSpeed.y = -this.ballSpeed.y; if (this.ballLocation.y - BALL_SIZE > SCREEN_SIZE) balls.remove(ballNumber); //Collision of the ball with the paddle if (this.ballLocation.x + BALL_SIZE/2 > paddle.paddleLocation.x && this.ballLocation.x - BALL_SIZE/2 < paddle.paddleLocation.x + paddleSize.x && this.ballLocation.y + BALL_SIZE/2 > paddle.paddleLocation.y && this.ballLocation.y + BALL_SIZE/2 < paddle.paddleLocation.y + paddleSize.y && this.ballSpeed.y > 0) { if (this.ballLocation.x > paddle.paddleLocation.x + paddleSize.x/2) this.ballSpeed.x = dist(paddle.paddleLocation.x + paddleSize.x/2, 0, this.ballLocation.x, 0)/HORIZANTAL_SPEED_SENSITIVITY; else this.ballSpeed.x = -dist(paddle.paddleLocation.x + paddleSize.x/2, 0, this.ballLocation.x, 0)/HORIZANTAL_SPEED_SENSITIVITY; this.ballSpeed.y = -this.ballSpeed.y; } //Collision of the ball with a brick for (int brickNumber = 0; brickNumber < bricks.size(); brickNumber++) { if (this.ballLocation.x + BALL_SIZE/2 >= bricks.get(brickNumber).brickLocation.x && this.ballLocation.x - BALL_SIZE/2 <= bricks.get(brickNumber).brickLocation.x + BRICK_SIZE.x && this.ballLocation.y + BALL_SIZE/2 >= bricks.get(brickNumber).brickLocation.y && this.ballLocation.y - BALL_SIZE/2 <= bricks.get(brickNumber).brickLocation.y + BRICK_SIZE.y) { if ((this.ballLocation.x < bricks.get(brickNumber).brickLocation.x && this.ballSpeed.x > 0) || (this.ballLocation.x > bricks.get(brickNumber).brickLocation.x + BRICK_SIZE.x && this.ballSpeed.x < 0)) this.ballSpeed.x = -this.ballSpeed.x; if ((this.ballLocation.y < bricks.get(brickNumber).brickLocation.y && this.ballSpeed.y > 0) || (this.ballLocation.y > bricks.get(brickNumber).brickLocation.y + BRICK_SIZE.y && this.ballSpeed.y < 0)) this.ballSpeed.y = -this.ballSpeed.y; if (this.canNextBallBeHitTimer <= 0) { //If the timer allows another block to be destroyed Brick b=(Brick) bricks.get(brickNumber); b.deathcount-=1; if(b.deathcount==0) { int p=(int) random(CHANCE_OF_POWER_UP); if (p == 0) { numPowerUps.add(new PowerUp(b.brickLocation.x + BRICK_SIZE.x/2, b.brickLocation.y + BRICK_SIZE.y/2)); } bricks.remove(brickNumber); } this.canNextBallBeHitTimer = MINIMUM_TIME_BEFORE_NEXT_HIT; } } } if (stickBallToPaddle) this.ballLocation = new PVector(paddle.paddleLocation.x + paddleSize.x/2, paddle.paddleLocation.y - BALL_SIZE/2); canNextBallBeHitTimer--; fill(255); ellipse(this.ballLocation.x, this.ballLocation.y, BALL_SIZE, BALL_SIZE); } } public void mouseClicked() { //If the mouse is pressed stickBallToPaddle = false; displayedIntroduction = true; } public void keyReleased() { //If a key is released if (key == 'Q' || key == 'q') exit(); if (key == 'P' || key == 'p') pauseState = !pauseState; } void renderHUD() { //Renders the player's HUD noCursor(); textAlign(LEFT); textFont(f, SCREEN_SIZE*4/125); text("Balls Left: ", SCREEN_SIZE/100, SCREEN_SIZE/25); text("Current Level: " + currentLevel, SCREEN_SIZE/100, SCREEN_SIZE*7/80); for (int ballsToDraw = 0; ballsToDraw < ballsLeft; ballsToDraw++) ellipse(SCREEN_SIZE*2/11 + ballsToDraw * BALL_SIZE*3/2, SCREEN_SIZE/32, BALL_SIZE, BALL_SIZE); textAlign(CENTER); textFont(f, SCREEN_SIZE/50); if (!displayedIntroduction) text("Welcome to Brick Break!" + "\nTo let go of the ball, click the mouse." + "\nTo control the paddle, move the mouse." + "\nTo pause the game, press 'P'." + "\nTo quit the game, press 'Q'.", SCREEN_SIZE/2, SCREEN_SIZE*6/10); if (displayWinningMessage) text("Congratulations!" + "\nYou win!" + "\nPress 'Q' to quit the game.", SCREEN_SIZE/2, SCREEN_SIZE/2); if (pauseState) { cursor(ARROW); fill(0, 0, 0, 220); rect(0, 0, SCREEN_SIZE, SCREEN_SIZE); fill(255); textFont(f, SCREEN_SIZE*4/125); text("Game Paused", SCREEN_SIZE/2, SCREEN_SIZE/2); textFont(f, SCREEN_SIZE/50); text("Press 'P' to resume the game.", SCREEN_SIZE/2, SCREEN_SIZE*11/21); } if (gameOverState) { background(0); textFont(f, SCREEN_SIZE*4/125); text("Game Over", SCREEN_SIZE/2, SCREEN_SIZE/2); textFont(f, SCREEN_SIZE/50); text("Press 'Q' to exit the game.", SCREEN_SIZE/2, SCREEN_SIZE*11/21); } } void spawnLevel(int levelToSpawn) { switch(levelToSpawn) { case 1: //If must spawn level one for (float spawnYofBrick = SCREEN_SIZE*10/45; spawnYofBrick < SCREEN_SIZE - BRICK_SIZE.y*20; spawnYofBrick += BRICK_SIZE.y) for (float spawnXofBrick = BRICK_SIZE.x; spawnXofBrick < SCREEN_SIZE - BRICK_SIZE.x*2; spawnXofBrick += BRICK_SIZE.x) bricks.add(new Brick(spawnXofBrick, spawnYofBrick,(int) random(3)+1)); break; case 2: //If must spawn level two for (float spawnYofBrick = SCREEN_SIZE*8/45; spawnYofBrick < SCREEN_SIZE - BRICK_SIZE.y*15; spawnYofBrick += BRICK_SIZE.y) for (float spawnXofBrick = BRICK_SIZE.x; spawnXofBrick < SCREEN_SIZE - BRICK_SIZE.x*2; spawnXofBrick += BRICK_SIZE.x*2) bricks.add(new Brick(spawnXofBrick, spawnYofBrick,(int) random(3)+1)); break; case 3: //If must spawn level three for (float spawnYofBrick = SCREEN_SIZE*14/45; spawnYofBrick < SCREEN_SIZE - BRICK_SIZE.y*15; spawnYofBrick += BRICK_SIZE.y) for (float spawnXofBrick = BRICK_SIZE.x; spawnXofBrick < SCREEN_SIZE - BRICK_SIZE.x*2; spawnXofBrick += BRICK_SIZE.x) if (spawnXofBrick < SCREEN_SIZE*3/8 || spawnXofBrick > SCREEN_SIZE/2) bricks.add(new Brick(spawnXofBrick, spawnYofBrick,(int) random(3)+1)); break; case 4: //If must spawn level four for (float spawnYofBrick = SCREEN_SIZE*2/9; spawnYofBrick < SCREEN_SIZE - BRICK_SIZE.y*17; spawnYofBrick += BRICK_SIZE.y) for (float spawnXofBrick = BRICK_SIZE.x; spawnXofBrick < SCREEN_SIZE - BRICK_SIZE.x*2; spawnXofBrick += BRICK_SIZE.x) if(spawnXofBrick == BRICK_SIZE.x || spawnXofBrick >= SCREEN_SIZE - BRICK_SIZE.x*3 || spawnYofBrick == SCREEN_SIZE*2/9 || spawnYofBrick >= SCREEN_SIZE - BRICK_SIZE.y*18) bricks.add(new Brick(spawnXofBrick, spawnYofBrick,(int) random(3)+1)); break; case 5: displayWinningMessage = true; break; } } class Brick { PVector brickLocation; int deathcount; int c; Brick(float brickSpawnLocationX, float brickSpawnLocationY, int deathcount) { this.brickLocation = new PVector(brickSpawnLocationX, brickSpawnLocationY); this.deathcount=deathcount; } void display() { stroke(0); setColor(); fill(c); rect(this.brickLocation.x, this.brickLocation.y, BRICK_SIZE.x, BRICK_SIZE.y); } void setColor() { switch(deathcount) { case 1: c = color(255, 0, 0); break; case 2: c = color(0, 255, 0); break; case 3: c = color(0, 0, 255); break; } } int getDeathCount() { return deathcount; } void setDeathCount(int dcount) { deathcount = dcount; } } class PowerUp { //Class for the power ups PVector powerUpLocation; int powerUpType; PowerUp(float powerUpSpawnLocationX, float powerUpSpawnLocationY) { this.powerUpLocation = new PVector(powerUpSpawnLocationX, powerUpSpawnLocationY); this.powerUpType = ((int) random(TYPES_OF_POWER_UPS)) ; println(this.powerUpType ); } void renderPowerUp(int powerUpNumber) { fill(255); this.powerUpLocation.y += POWER_UP_SPEED; if (this.powerUpLocation.y - POWER_UP_SIZE > SCREEN_SIZE) numPowerUps.remove(powerUpNumber); //Collision with the paddle if (this.powerUpLocation.x + POWER_UP_SIZE/2 > paddle.paddleLocation.x && this.powerUpLocation.x - POWER_UP_SIZE/2 < paddle.paddleLocation.x + paddleSize.x && this.powerUpLocation.y + POWER_UP_SIZE/2 > paddle.paddleLocation.y && this.powerUpLocation.y + POWER_UP_SIZE/2 < paddle.paddleLocation.y + paddleSize.y) { switch(this.powerUpType) { case 0: //If it is a x3 power up currentAmountOfBalls = balls.size(); for (int i = 0; i < currentAmountOfBalls; i++) { balls.add(new Ball(balls.get(i).ballLocation.x, balls.get(i).ballLocation.y, balls.get(i).ballSpeed.x, -balls.get(i).ballSpeed.y)); balls.add(new Ball(balls.get(i).ballLocation.x, balls.get(i).ballLocation.y, -balls.get(i).ballSpeed.x, balls.get(i).ballSpeed.y)); balls.add(new Ball(balls.get(i).ballLocation.x, balls.get(i).ballLocation.y, -balls.get(i).ballSpeed.x, -balls.get(i).ballSpeed.y)); } break; case 1: //If it is an extended paddle power up extendedPaddleTimer = PADDLE_EXTEND_TIME; break; } numPowerUps.remove(powerUpNumber); } ellipse(this.powerUpLocation.x, this.powerUpLocation.y, POWER_UP_SIZE, POWER_UP_SIZE); fill(255); textFont(f, SCREEN_SIZE/50); switch(this.powerUpType) { case 0: //If it is a x3 Power Up fill(0); text("3", this.powerUpLocation.x - SCREEN_SIZE/800, this.powerUpLocation.y + SCREEN_SIZE*3/400); break; case 1: //If it is an extended paddle power up fill(0); text("E", this.powerUpLocation.x - SCREEN_SIZE/800, this.powerUpLocation.y + SCREEN_SIZE*3/400); break; } } } }
package br.com.conspesca.mb; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.ejb.EJB; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import br.com.conspesca.model.Peixe; import br.com.conspesca.service.PeixeService; @Named @ViewScoped public class PeixeMB extends BaseMB{ private static final long serialVersionUID = 1L; private List<Peixe> peixes; private Peixe peixe; private Date data; @EJB private PeixeService peixeService; @Override @Inject public void init() { super.init(); this.peixes = new ArrayList<>(); this.peixe = new Peixe(); this.peixes = this.peixeService.findAllPeixe(); } public Date getData() { return this.data; } public void setData(Date data) { this.data = data; } public void setPeixes(List<Peixe> peixes) { this.peixes = peixes; } public List<Peixe> getPeixes() { return this.peixes; } public void setPeixe(Peixe peixe) { this.peixe = peixe; } public Peixe getPeixe() { return this.peixe; } public String salvar() { this.peixeService.salvar(this.peixe); return "consultapeixe"; } public String criarNovo() { this.peixe = new Peixe(); return "cadastropeixe"; } public String verDetalhe(Peixe peixe) { this.peixe = peixe; return "editapeixe"; } public String remover(Peixe peixe) { this.peixeService.removePeixeByID(peixe.getIdPeixe()); return "consultapeixe"; } }
package io.x666c.glib4j.components; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Stroke; import java.util.function.Consumer; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.border.EmptyBorder; import javax.swing.plaf.basic.BasicSliderUI; public class GSlider extends JPanel { private final JSlider slider; private final JLabel label; public GSlider(String text, int start, int end, int val) { setLayout(new BorderLayout(5, 5)); setBorder(new EmptyBorder(4, 4, 2, 3)); add(label = new JLabel(text), BorderLayout.WEST); add(slider = new JSlider(start, end, val), BorderLayout.CENTER); slider.setFocusable(false); label.setFocusable(false); label.setForeground(Color.BLACK); label.setFont(new Font("Arial", Font.PLAIN, 14)); slider.setUI(new CustomSliderUI(slider)); } public void listener(Consumer<JSlider> event) { slider.addChangeListener(ev -> event.accept((JSlider) ev.getSource())); } public class CustomSliderUI extends BasicSliderUI { private static final int THUMB_RADIUS = 14; private BasicStroke stroke = new BasicStroke(4f); public CustomSliderUI(JSlider b) {super(b);} public void paint(Graphics g, JComponent c) { ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paint(g, c); } protected Dimension getThumbSize() { return new Dimension(THUMB_RADIUS + 1, THUMB_RADIUS + 1); } public void paintTrack(Graphics g) { Graphics2D g2d = (Graphics2D) g; Stroke old = g2d.getStroke(); g2d.setStroke(stroke); g2d.setPaint(new Color(0xAAAAAA)); g2d.fillOval(trackRect.x - (int)stroke.getLineWidth(), trackRect.y + trackRect.height / 2 - 1, (int)stroke.getLineWidth(), (int)stroke.getLineWidth()); g2d.drawLine(trackRect.x, trackRect.y + trackRect.height / 2, trackRect.x + trackRect.width, trackRect.y + trackRect.height / 2); g2d.fillOval(trackRect.x + trackRect.width + (int)stroke.getLineWidth() / 2, trackRect.y + trackRect.height / 2 - 1, (int)stroke.getLineWidth(), (int)stroke.getLineWidth()); g2d.setStroke(old); } public void paintThumb(Graphics gg) { Graphics2D g = (Graphics2D) gg; int x = thumbRect.x + thumbRect.width / 2 - THUMB_RADIUS / 2; int y = thumbRect.y + thumbRect.height / 2 - THUMB_RADIUS / 2; g.setColor(new Color(0xBBBBBB)); g.fillOval(x, y, THUMB_RADIUS, THUMB_RADIUS); g.setColor(new Color(0x959595)); g.setStroke(new BasicStroke(1.6f)); g.drawOval(x, y, THUMB_RADIUS, THUMB_RADIUS); } } }
package com.telyo.trainassistant.fragment; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.lidroid.xutils.BitmapUtils; import com.telyo.trainassistant.R; import com.telyo.trainassistant.entity.MyUser; import com.telyo.trainassistant.ui.AboutActivity; import com.telyo.trainassistant.ui.RegisterActivity; import com.telyo.trainassistant.ui.ServiceActivity; import com.telyo.trainassistant.ui.UserActivity; import com.telyo.trainassistant.utils.L; import com.telyo.trainassistant.utils.SharedUtils; import com.telyo.trainassistant.utils.StaticClass; import com.telyo.trainassistant.utils.StaticUtils; import com.telyo.trainassistant.views.MyDialogView; import com.tencent.connect.UserInfo; import com.tencent.connect.auth.QQToken; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.BmobUser; import cn.bmob.v3.datatype.BmobFile; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.FindListener; import cn.bmob.v3.listener.SaveListener; import cn.bmob.v3.listener.UpdateListener; import cn.bmob.v3.listener.UploadFileListener; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by Administrator on 2017/6/7. */ public class FragmentPersonal extends Fragment implements View.OnClickListener { private CircleImageView mImg_user; private Button mBtn_login; private LinearLayout mLl_service; private LinearLayout mLl_about; private LinearLayout mLl_go; private MyDialogView mMyLoginDialogView; private TextView mTv_register; private EditText mEt_user_name; private EditText mEt_user_password; private Button mBtn_dialog_login; private CheckBox mCb_is_mark; private TextView mTv_look_back; private TextView mTv_user_name; private MyDialogView mMySelectPictureDialogView; private static final int CAMERA_RESULT_CODE = 2201; private static final int PICTURE_RESULT_CODE = 2202; public static final String PHOTO_IMAGE_FILE_NAME = "fileImg.jpg"; public static final String BITMAP_IMAGE_FILE_NAME = "bitmapImg.png"; private static final int CROP_RESULT_CODE = 2208; private static final int QQ_LOGIN_RESULT_CODE = 11101; private File tempFile = null; private MyUser bmobUser; private TextView mTv_cancel; private ImageView mImg_qq; private ImageView mImg_wechat; private ImageView mImg_sina; private Tencent mTencent; private BaseUiListener mListener; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); doQQLogin(msg); } }; private void doQQLogin(Message msg) { Bundle bundle = msg.getData(); final String username = bundle.getString("openid"); final String nickname = bundle.getString("nickname"); final String headUrl = bundle.getString("headUrl"); BmobQuery<BmobUser> query = new BmobQuery<BmobUser>(); query.addWhereEqualTo("username", username); final MyDialogView dialogView = StaticUtils.showPeogress(getActivity()); dialogView.show(); query.findObjects(new FindListener<BmobUser>() { private MyUser myUser = new MyUser(); @Override public void done(List<BmobUser> object, BmobException e) { if(e==null){ L.i("查询用户成功:"+object.size()); //如果以前没有使用qq登录过 先注册后再登录 if (object.size() == 0){ myUser.setUsername(username); myUser.setPassword(username); myUser.setName(nickname); myUser.setImg_url(headUrl); myUser.signUp(new SaveListener<MyUser>() { @Override public void done(MyUser user, BmobException e) { if (e == null){ myUser.login(new SaveListener<MyUser>() { @Override public void done(MyUser myUser, BmobException e) { if (e == null){ new SharedUtils().putBoolean(getActivity(), "isLogin", true); setLoginView(isLogin()); new BitmapUtils(getActivity()).display(mImg_user,headUrl); dialogView.dismiss(); }else { dialogView.dismiss(); Toast.makeText(getActivity(), "登陆失败1" + e, Toast.LENGTH_SHORT).show(); L.i("登陆失败1" + e); } } }); }else { dialogView.dismiss(); Toast.makeText(getActivity(), "注册失败" + e, Toast.LENGTH_SHORT).show(); L.i("注册失败" + e); } } }); }else { //如果以前登录过现在就直接登录 myUser.setUsername(username); myUser.setPassword(username); myUser.login(new SaveListener<MyUser>() { @Override public void done(MyUser myUser, BmobException e) { if (e == null){ new SharedUtils().putBoolean(getActivity(), "isLogin", true); new BitmapUtils(getActivity()).display(mImg_user,headUrl); setLoginView(isLogin()); dialogView.dismiss(); }else { Toast.makeText(getActivity(), "登陆失败1" + e, Toast.LENGTH_SHORT).show(); L.i("登陆失败1" + e); } } }); } }else{ dialogView.dismiss(); L.i("更新用户信息失败:" + e.getMessage()); } } }); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_personal, container, false); initView(view); return view; } @Override public void onResume() { setLoginView(isLogin()); super.onResume(); } private void initView(View view) { mListener = new BaseUiListener(); mTencent = Tencent.createInstance(StaticClass.TENSENT_APP_ID, getActivity().getApplicationContext()); mImg_user = (CircleImageView) view.findViewById(R.id.img_user); mBtn_login = (Button) view.findViewById(R.id.btn_login); mLl_service = (LinearLayout) view.findViewById(R.id.ll_service); mLl_about = (LinearLayout) view.findViewById(R.id.ll_about); mLl_go = (LinearLayout) view.findViewById(R.id.ll_go); mTv_user_name = (TextView) view.findViewById(R.id.tv_user_name); mLl_go.setOnClickListener(this); mImg_user.setOnClickListener(this); mBtn_login.setOnClickListener(this); mLl_service.setOnClickListener(this); mLl_about.setOnClickListener(this); //判断是否存在用户、有就直接获取用户 getOldUser(); } //决定是否为登录状态 private void setLoginView(Boolean isLogin) { //登录 if (isLogin) { mBtn_login.setVisibility(View.GONE); mLl_go.setVisibility(View.VISIBLE); if (BmobUser.getCurrentUser(MyUser.class).getName().isEmpty() ) { mTv_user_name.setText(BmobUser.getCurrentUser(MyUser.class).getUsername()); } else { mTv_user_name.setText(BmobUser.getCurrentUser(MyUser.class).getName()); } mLl_go.setOnClickListener(this); //setUrlToImageView(mImg_user); mImg_user.setClickable(true); } else { //未登录 mBtn_login.setVisibility(View.VISIBLE); mLl_go.setVisibility(View.GONE); mImg_user.setImageResource(R.drawable.icon_user); mImg_user.setClickable(false); } } //相册选择头像 private void startPictureActivity() { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent,PICTURE_RESULT_CODE); mMySelectPictureDialogView.dismiss(); } //相机选择头像 private void startCameraActivity() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),PHOTO_IMAGE_FILE_NAME))); startActivityForResult(intent,CAMERA_RESULT_CODE); mMySelectPictureDialogView.dismiss(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != getActivity().RESULT_CANCELED ){ L.i(""+ requestCode + resultCode + data); switch (requestCode){ //qq 登录返回码 case QQ_LOGIN_RESULT_CODE: L.i("requestCode:"+ requestCode +"resultCode:"+ resultCode + "data:"+data); Tencent.onActivityResultData(requestCode,resultCode,data,mListener); break; //相册数据 case PICTURE_RESULT_CODE: L.i("开始裁剪!" + data); startPhotoZoom(data.getData()); break; //相机数据 case CAMERA_RESULT_CODE: tempFile = new File(Environment.getExternalStorageDirectory(),PHOTO_IMAGE_FILE_NAME); startPhotoZoom(Uri.fromFile(tempFile)); break; case CROP_RESULT_CODE: if (data != null){ L.i("设置头像"); //设置头像 setImageToView(data); //设置好了图片删除原来的文件 if (tempFile != null){ tempFile.delete(); } } break; } } } /** * 1、上传图片到bmob云端 * 2、根据用户数据获取上次保存的url * 3、通过上次保存的url删除云端数据 * 4、保存新的url * * @param file 传入的文件 并 上传图片到bmob云端 */ private void upLoadImage(final File file) { final BmobFile bmobFile = new BmobFile(file); //1、上传图片到bmob云端 bmobFile.upload(new UploadFileListener() { private String imgUrl; @Override public void done(BmobException e) { if (e == null){ Toast.makeText(getActivity(), "修改头像成功", Toast.LENGTH_SHORT).show(); if (file != null){ //删除本地多余文件 file.delete(); } //3、如果上次设置了图片,根据上次储存的Url删除服务器原来的图片 doDeleteBmobImgUrl(); //2、获取url imgUrl = bmobFile.getUrl(); //4、将Url储存在用户账号里 bmobUser.setImg_url(imgUrl); bmobUser.update(new UpdateListener() { @Override public void done(BmobException e) { if (e == null){ L.i("用户更新了imgUrl!"); setUrlToImageView(mImg_user); } } }); }else { Toast.makeText(getActivity(), "修改头像失败", Toast.LENGTH_SHORT).show(); L.i("e" + e); } } }); } //本地更改头像成功后,上传图片资源到web ,并删除web上原有的图片 private void doDeleteBmobImgUrl() { final String url = bmobUser.getImg_url().toString(); if (!url.isEmpty()) { BmobFile bmobFile = new BmobFile(); bmobFile.setUrl(url); bmobFile.delete(new UpdateListener() { @Override public void done(BmobException e) { L.i("删除文件" + e + url); } }); } } /** * * @param data */ private void setImageToView(Intent data) { Bundle bundle = data.getExtras(); if (bundle != null){ Bitmap bitmap = bundle.getParcelable("data"); //设置头像 L.i("设置bitmap显示"); mImg_user.setImageBitmap(bitmap); //将Bitmap 装转换成File 供BmobFile上传 File fileCrop = new File(Environment.getExternalStorageDirectory(),BITMAP_IMAGE_FILE_NAME); try { FileOutputStream os = new FileOutputStream(fileCrop); bitmap.compress(Bitmap.CompressFormat.PNG,10,os); os.flush(); os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //上传头像 upLoadImage(fileCrop); } } //弹出dialog 供选择以什么方式获取图片 private void toSelectPicture() { mMySelectPictureDialogView = new MyDialogView(getActivity(), WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, R.layout.dialog_select_picture, R.style.Theme_dialog, Gravity.BOTTOM); Button btn_from_camera = (Button) mMySelectPictureDialogView.findViewById(R.id.btn_from_camera); Button btn_from_picture = (Button) mMySelectPictureDialogView.findViewById(R.id.btn_from_picture); Button tv_cancel = (Button) mMySelectPictureDialogView.findViewById(R.id.tv_cancel); btn_from_camera.setOnClickListener(this); btn_from_picture.setOnClickListener(this); tv_cancel.setOnClickListener(this); mMySelectPictureDialogView.setCancelable(false); mMySelectPictureDialogView.show(); } //将获取的图片进行裁剪 private void startPhotoZoom(Uri data) { if (data == null){ return; } Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(data,"image/*"); //是否裁剪 intent.putExtra("crop","true"); //宽高比例 intent.putExtra("aspectX",1); intent.putExtra("aspectY",1); //图片质量 intent.putExtra("outputX",100); intent.putExtra("outputY",100); //是否发送数据 intent.putExtra("return-data",true); startActivityForResult(intent,CROP_RESULT_CODE); } private void tartUserActivity() { Intent intent = new Intent(); intent.setClass(getActivity(), UserActivity.class); startActivity(intent); } private void startRegisterActivity() { Intent intent = new Intent(); intent.setClass(getActivity(), RegisterActivity.class); startActivity(intent); } /** * 1、弹出dialog登录框 * 2、初始化dialog控件 */ private void login() { mMyLoginDialogView = new MyDialogView(getActivity() , WindowManager.LayoutParams.WRAP_CONTENT , WindowManager.LayoutParams.WRAP_CONTENT , R.layout.dialog_login , R.style.Theme_dialog , Gravity.CENTER); mMyLoginDialogView.setCancelable(false); mMyLoginDialogView.show(); initDialogView(); } /** * 1、获取输入框内容 * 2、判断是否为空 * 3、登录判断成功--->返回数据、失败--->Toast */ private void doLogin() { final String user_name = mEt_user_name.getText().toString(); String password = mEt_user_password.getText().toString(); if (!user_name.isEmpty() && !password.isEmpty()) { bmobUser = new MyUser(); bmobUser.setUsername(user_name); bmobUser.setPassword(password); final MyDialogView dialogView = new MyDialogView(getActivity(), WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, R.layout.dialog_progress, R.style.Theme_dialog, Gravity.CENTER); dialogView.setCancelable(false); dialogView.show(); bmobUser.login(new SaveListener<MyUser>() { @Override public void done(MyUser bmobUser, final BmobException e) { if (e == null) { Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show(); mMyLoginDialogView.dismiss(); //登录页 转变为登录状态 new SharedUtils().putBoolean(getActivity(), "isLogin", true); new SharedUtils().putString(getActivity(), "user_name", user_name); setLoginView(isLogin()); //是否记住密码 rememberPassword(mCb_is_mark.isChecked()); //下载头像 setUrlToImageView(mImg_user); dialogView.dismiss(); } else { Toast.makeText(getActivity(), "登录失败" + e, Toast.LENGTH_SHORT).show(); L.i("登录失败" + e); dialogView.dismiss(); } } }); } else { Toast.makeText(getActivity(), "用户名或者密码不为空", Toast.LENGTH_SHORT).show(); } mMyLoginDialogView.dismiss(); } //管理是否记住密码 private void rememberPassword(boolean checked) { SharedUtils sharedUtils = new SharedUtils(); if (checked) { sharedUtils.putString(getActivity(), "passWord", mEt_user_password.getText().toString()); sharedUtils.putString(getActivity(),"userName",mEt_user_name.getText().toString()); sharedUtils.putBoolean(getActivity(),"isMark",mCb_is_mark.isChecked()); } else { sharedUtils.putString(getActivity(), "passWord", ""); sharedUtils.putString(getActivity(), "userName", ""); sharedUtils.putBoolean(getActivity(),"isMark",mCb_is_mark.isChecked()); } } //2、初始化dialog控件 private void initDialogView() { mTv_register = (TextView) mMyLoginDialogView.findViewById(R.id.tv_register); mTv_cancel = (TextView) mMyLoginDialogView.findViewById(R.id.tv_login_cancel); mTv_register.setOnClickListener(this); mTv_cancel.setOnClickListener(this); mEt_user_name = (EditText) mMyLoginDialogView.findViewById(R.id.et_user_name); mEt_user_name.setText(new SharedUtils().getString(getActivity(),"userName","")); mEt_user_password = (EditText) mMyLoginDialogView.findViewById(R.id.et_user_password); mEt_user_password.setText(new SharedUtils().getString(getActivity(), "passWord","")); mBtn_dialog_login = (Button) mMyLoginDialogView.findViewById(R.id.btn_dialog_login); mBtn_dialog_login.setOnClickListener(this); mCb_is_mark = (CheckBox) mMyLoginDialogView.findViewById(R.id.cb_is_mark); mCb_is_mark.setChecked(new SharedUtils().getBoolean(getActivity(),"isMark",false)); mTv_look_back = (TextView) mMyLoginDialogView.findViewById(R.id.tv_look_back); mTv_look_back.setOnClickListener(this); mImg_qq = (ImageView) mMyLoginDialogView.findViewById(R.id.img_qq); mImg_qq.setOnClickListener(this); mImg_wechat = (ImageView) mMyLoginDialogView.findViewById(R.id.img_wechat); mImg_wechat.setOnClickListener(this); mImg_sina = (ImageView) mMyLoginDialogView.findViewById(R.id.img_sina); mImg_sina.setOnClickListener(this); } private void tartAboutActivity() { Intent intent = new Intent(); intent.setClass(getActivity(), AboutActivity.class); startActivity(intent); } private void startServiceActivity() { Intent intent = new Intent(); intent.setClass(getActivity(), ServiceActivity.class); startActivity(intent); } //保存登录状态的值 private Boolean isLogin() { return new SharedUtils().getBoolean(getActivity(), "isLogin",false); } //获取当前用户 public void getOldUser() { bmobUser = BmobUser.getCurrentUser(MyUser.class); if (bmobUser != null && isLogin()) { // 允许用户使用应用 //第一次进入判断是否为登录状态 setLoginView(isLogin()); setUrlToImageView(mImg_user); } else { //缓存用户对象为空时, 可打开用户注册界面… Toast.makeText(getActivity(), "未登录", Toast.LENGTH_SHORT).show(); setLoginView(isLogin()); } } /** * * @param urlToImageView * 首次进入 调用这个方法获取头像图片 */ public void setUrlToImageView(final CircleImageView urlToImageView) { BitmapUtils bitmapUtils = new BitmapUtils(getActivity()); String url = bmobUser.getImg_url(); L.i("当前 url为 :" + url); if (!url.isEmpty()) { bitmapUtils.display(urlToImageView,url); } return; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.img_user: //dialog 提示选择图片的来源 toSelectPicture(); break; case R.id.btn_login: login(); break; case R.id.ll_service: startServiceActivity(); break; case R.id.ll_about: tartAboutActivity(); break; case R.id.ll_go: tartUserActivity(); break; case R.id.tv_register: //注册; startRegisterActivity(); break; case R.id.btn_dialog_login: doLogin(); break; case R.id.tv_look_back: //TODO 找回密码; break; case R.id.btn_from_camera: startCameraActivity(); break; case R.id.btn_from_picture: startPictureActivity(); break; case R.id.tv_cancel: mMySelectPictureDialogView.dismiss(); break; case R.id.tv_login_cancel: mMyLoginDialogView.dismiss(); break; case R.id.img_qq: loginByQQ(); break; case R.id.img_wechat: break; case R.id.img_sina: break; } } private void loginByQQ() { // Tencent类是SDK的主要实现类,开发者可通过Tencent类访问腾讯开放的OpenAPI。 // 其中APP_ID是分配给第三方应用的appid,类型为String。 //mTencent = Tencent.createInstance(StaticClass.TENSENT_APP_ID, getActivity().getApplicationContext()); // 1.4版本:此处需新增参数,传入应用程序的全局context,可通过activity的getApplicationContext方法获取 // 初始化视图 if (!mTencent.isSessionValid()) { L.i("QQ 登录"); mTencent.login(this,"all", mListener); } mMyLoginDialogView.dismiss(); //mTencent.logout(getActivity()); } private class BaseUiListener implements IUiListener { @Override public void onComplete(Object o) { // Toast.makeText(getActivity(), ""+o.toString(), Toast.LENGTH_SHORT).show(); L.i("o.toString() :"+o.toString()); JSONObject jsonObject = (JSONObject) o; //设置openid和token,否则获取不到下面的信息 initOpenidAndToken(jsonObject); //获取QQ用户的各信息 getQQUserInfo(jsonObject); } @Override public void onError(UiError e) { L.i("onError:"+ "code:" + e.errorCode + ", msg:" + e.errorMessage + ", detail:" + e.errorDetail); } @Override public void onCancel() { L.i("onCancel"+ ""); } } private void initOpenidAndToken(JSONObject jsonObject) { try { String openid = jsonObject.getString("openid"); String token = jsonObject.getString("access_token"); String expires = jsonObject.getString("expires_in"); mTencent.setAccessToken(token, expires); mTencent.setOpenId(openid); } catch (JSONException e) { e.printStackTrace(); } } public void getQQUserInfo(final JSONObject jsonObject) { //sdk给我们提供了一个类UserInfo,这个类中封装了QQ用户的一些信息,我么可以通过这个类拿到这些信息 QQToken mQQToken = mTencent.getQQToken(); UserInfo userInfo = new UserInfo(getActivity(), mQQToken); userInfo.getUserInfo(new IUiListener() { @Override public void onComplete(final Object o) { L.i("QQUserInfo"+o.toString()); JSONObject userInfoJson = (JSONObject) o; Message msgNick = mHandler.obtainMessage(); try { String openid = jsonObject.getString("openid"); String nickname = userInfoJson.getString("nickname");//直接传递一个昵称的内容过去 String headUrl = ((JSONObject) o).getString("figureurl_qq_2"); Bundle bundle = new Bundle(); bundle.putString("headUrl",headUrl); bundle.putString("nickname",nickname); bundle.putString("openid",openid); msgNick.setData(bundle); } catch (JSONException e) { e.printStackTrace(); } mHandler.sendMessage(msgNick); } @Override public void onError(UiError uiError) { L.e("GET_QQ_INFO_ERROR"+ "获取qq用户信息错误"); Toast.makeText(getActivity(), "获取qq用户信息错误", Toast.LENGTH_SHORT).show(); } @Override public void onCancel() { L.e("GET_QQ_INFO_CANCEL"+"获取qq用户信息取消"); Toast.makeText(getActivity(), "获取qq用户信息取消", Toast.LENGTH_SHORT).show(); } } ); } }
package com.example.java8pjt.interf; public class App { public static void main(String[] args) { FooInterface fooInterface = new DefaultFoo("jeong"); System.out.println(fooInterface.getName()); fooInterface.printNameUpperCase(); FooInterface.printAnyThing(); } }
package edu.co.unal.bioing.jnukak3d.VolumeRendering.GLbase; import com.sun.opengl.util.FPSAnimator; import edu.co.unal.bioing.jnukak3d.VolumeRendering.util.GLutils; import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.media.opengl.DebugGL; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; import javax.swing.JFrame; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author jleon */ public class BaseGlViewer extends GLCanvas implements GLEventListener, MouseListener, MouseMotionListener, MouseWheelListener, KeyListener{ //opengl stuff protected GLU glu; protected FPSAnimator animator; protected int fps = 1; //misc stuff float[] background={0.9f,0.5f,0.2f,1.0f}; protected int maxTextureSize; //mouse start positions private int mouseStartX; private int mouseStartY; //rotation stuff private int rotX; private int rotY; private int windowWidth; private int windowHeight; private int lastRotX=0; private int lastRotY=0; //camera stuff private int camX=200; private int camY=200; //"Zoom" stuff protected int cameraDistance=700; protected int zoomFactor=5; protected int movementFactor=4; //render stuff private boolean running; public BaseGlViewer(int width, int height, GLCapabilities capabilities) throws UnsatisfiedLinkError{ super(capabilities); setSize(width, height); addGLEventListener(this); addMouseListener(this); addMouseMotionListener(this); addMouseWheelListener(this); addKeyListener(this); this.windowWidth=width; this.windowHeight=height; running=false; } public void startRendering(){ this.running=true; } @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode()==37) camX=camX-1*movementFactor; else if(e.getKeyCode()==38) camY=camY+1*movementFactor; else if(e.getKeyCode()==39) camX=camX+1*movementFactor; else if(e.getKeyCode()==40) camY=camY-1*movementFactor; else ; } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void mousePressed(MouseEvent e) { mouseStartX=e.getX(); mouseStartY=e.getY(); } @Override public void mouseDragged(MouseEvent e) { //System.out.println("Moving camera"); int x=e.getX(); int y=e.getY(); rotX+=(x-mouseStartX) * 180 / windowWidth; rotY+=(y-mouseStartY) * 180 / windowHeight; mouseStartX=x; mouseStartY=y; // TODO low res DIsplay here this.display(); } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height){ GL gl = drawable.getGL(); gl.glViewport(0, 0, width, height); this.windowWidth=width; this.windowHeight=height; } @Override public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { throw new UnsupportedOperationException("Changing display is not supported."); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { } @Override public void mouseWheelMoved(MouseWheelEvent e) { this.cameraDistance+=zoomFactor*e.getWheelRotation(); } @Override public void init(GLAutoDrawable drawable){ drawable.setGL(new DebugGL(drawable.getGL())); GL gl = drawable.getGL(); // Define "clear" color. gl.glClearColor(background[0],background[1],background[2],background[3]); gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST); gl.glHint(GL.GL_POLYGON_SMOOTH_HINT, GL.GL_NICEST); glu = new GLU(); // Start animator (which should be a field). animator= new FPSAnimator(this, fps); animator.start(); int[] maxTexture=new int[1]; gl.glGetIntegerv(GL.GL_MAX_3D_TEXTURE_SIZE, maxTexture, 0); this.maxTextureSize=maxTexture[0]; //System.out.println("Max 3d texture Supported size"+this.maxTextureSize); doExtraInitOperations(gl); } protected void doExtraInitOperations(GL gl){ } @Override public void display(GLAutoDrawable drawable){ if (!animator.isAnimating()) { return; } GL gl = drawable.getGL(); //clear the screen gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); setCamera(gl, glu, cameraDistance); gl.glRotated(rotX, 0, 1, 0); gl.glRotated(rotY, 1, 0, 0); if(lastRotX!=rotX || lastRotY!=rotY) doRotationStuff(); else doNoRotationStuff(); lastRotX=rotX; lastRotY=rotY; doPreBuildSceneOperations(gl); buildScene(gl); doPostBuildSceneOperations(gl); } protected void doRotationStuff(){ } protected void doNoRotationStuff(){ } public void doPreBuildSceneOperations(GL gl){ } public void doPostBuildSceneOperations(GL gl){ } //must be overriden public void buildScene(GL gl){ gl.glColor3f(0.9f, 0.5f, 0.2f); gl.glBegin(GL.GL_TRIANGLES); gl.glColor3f(1.0f, 0.0f, 0.0f); gl.glVertex3f(-20, -20, 0); gl.glColor3f(0.0f, 1.0f, 0.0f); gl.glVertex3f(20, -20, 0); gl.glColor3f(0.0f, 0.0f, 1.0f); gl.glVertex3f(0, 20, 0); gl.glEnd(); } private void setCamera(GL gl, GLU glu, float distance) { // Change to projection matrix. gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); // Perspective. float widthHeightRatio = (float) getWidth() / (float) getHeight(); glu.gluPerspective(45, widthHeightRatio, 10, 1000); glu.gluLookAt(camX, camY, distance, camX, camY, 0, 0, 1, 0); // Change back to model view matrix. gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); } public static void main (String args[]){ BaseGlViewer canvas=new BaseGlViewer(800, 500,GLutils.get8BitRGBAHardwareAceleratedCapabilities()); JFrame frame = new JFrame("Base Viewer"); frame.getContentPane().add(canvas, BorderLayout.CENTER); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); canvas.requestFocus(); } }
import java.net.*; import java.io.*; import java.util.concurrent.*; import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; public class MultiDiffusion implements Runnable{ private int numP; private String add; public MultiDiffusion(String add,int num){ this.numP = num; this.add = add; } public int getNumP(){ return this.numP; } public void setNumP(int n){ this.numP = n; } public String getAdd(){ return this.add; } public void setAdd(String a){ this.add = a; } public void run(){ try{ MulticastSocket mso=new MulticastSocket(this.numP); mso.joinGroup(InetAddress.getByName(this.add)); byte[]data=new byte[100]; DatagramPacket paquet=new DatagramPacket(data,data.length); while(true){ mso.receive(paquet); String st=new String(paquet.getData(),0,paquet.getLength()); st= st.substring(0, st.length()-3); String [] mesTab = st.split(" "); int entier = mesTab[1].length()+5; String messageEntier = st.substring(entier, st.length()); System.out.println("Message generale de la part de "+mesTab[1]+" :"+messageEntier); } }catch(Exception e){ e.printStackTrace(); } } }
package com.spring.domain.fieldview; public class Field_options { private String description; private Options[] options; public String getDescription () { return description; } public void setDescription (String description) { this.description = description; } public Options[] getOptions () { return options; } public void setOptions (Options[] options) { this.options = options; } @Override public String toString() { return "ClassPojo [description = "+description+", options = "+options+"]"; } }
package cn.edu.zucc.music.service; import cn.edu.zucc.music.model.User; import java.util.List; public interface UserService { int addUser(User user); // 注册 int deleteUser(User user); int updateUser(User user); User findById(String userId); User findByName(String userName); String findMaxId(); List<User> findAll(); }
package com.giga.entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.util.Set; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class User { @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "username") private String username; @Column(name = "password") private String password; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "user_product_cart", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "product_id") ) private Set<Product> productCart; public User(String username, String password) { this.username = username; this.password = password; } }
package generic.application; import java.util.Arrays; import java.util.Comparator; import generic.Person; public class ComparatorApp { public static void main(String[] args) { Person[] people = { new Person("Randy", "Jln. Suprapto IV"), new Person("Budi", "Jln aasd"), new Person("Felix", "Jln. Serdam"), }; Comparator<Person> comparator = new Comparator<Person>() { @Override public int compare(Person arg0, Person arg1) { return arg0.getName().compareTo(arg1.getName()); } }; Arrays.sort(people); System.out.println(Arrays.toString(people)); } }
package com.example.demo.review; import com.example.demo.review.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 javax.validation.Valid; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/reviews") public class ReviewController { @Autowired ReviewService reviewService; @GetMapping() public List<Review> getReviews() { return reviewService.retrieveReview(); } @GetMapping("/{id}") public ResponseEntity<?> getCustomer(@PathVariable Long id) { Optional<Review> review = reviewService.retrieveReview(id); if(!review.isPresent()) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(review); } @GetMapping("/search") public List<Review> getReview(@RequestParam(value = "description") String description ) { return reviewService.retrieveReview(description); } @PostMapping() public ResponseEntity<?> postReview(@Valid @RequestBody Review body) { Review review = reviewService.createReview(body); return ResponseEntity.status(HttpStatus.CREATED).body(review); } @PutMapping("/{id}") public ResponseEntity<?> putReview(@PathVariable Long id, @Valid @RequestBody Review body) { Optional<Review> review = reviewService.updateReview(id, body); if(!review.isPresent()) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().build(); } @DeleteMapping("/{id}") public ResponseEntity<?> deleteReview(@PathVariable Long id) { if(!reviewService.deleteReview(id)) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().build(); } }
import java.util.Scanner; public class Assignment4 { public static void main(String[] args){ // Allowing user to input data Scanner userInput = new Scanner(System.in); System.out.println("LAB STATUS"); System.out.println("Lab # / Computer Stations"); // 2D Array String[][] cLabs = { {"Empty","Empty","Empty","Empty","Empty"}, {"Empty","Empty","Empty","Empty","Empty","Empty"}, {"Empty","Empty","Empty","Empty"}, {"Empty","Empty","Empty"} }; // Printing the 2D Array with two loops for (int i = 0; i < cLabs.length; i++){ System.out.print(i+1 + " "); for(int j = 0; j < cLabs[i].length; j++){ System.out.print((j+1) + ":" + cLabs[i][j] + " "); } System.out.println(); } //Menu choices using a switch statment System.out.println("MAIN MENU"); System.out.println("0) Quit \n1) Simulate Login \n2) Simulate Logoff \n3) Search"); int menuChoice = userInput.nextInt(); // switch using int to make a menu choice // Switch case statment used for each menu option switch(menuChoice){ case 0: System.exit(0); // exit out the program case 1: // Using the scanner to insert data in variables System.out.println("Enter the 5 digit ID number of the user logging in:" ); String idNumber = userInput.next(); // String System.out.println("Enter the lab number the user is logging in from (1-4):"); int lNum = userInput.nextInt(); // integer System.out.println("Enter computer station number the user is logging into (1-6):"); int cStation = userInput.nextInt(); // integer /* looping through the 2D array to add the 5 digit number (idNumber) and placeing it into the correct Lab (lNum) and Computer Station (cStation) */ for(int i = 0; i < cLabs.length; i++){ System.out.print(i+1 + " "); for(int j = 0; j < cLabs[i].length; j++){ cLabs[(lNum-1)][(cStation-1)] = idNumber; System.out.print((j+1) + ":" + cLabs[i][j] + " "); } System.out.println(); } break; case 2: // Second loop used to locate and replace the (idNumber) String back to "Empty" String System.out.println("Enter the 5 digit ID number of the user to logout:"); String idNumber2 = userInput.next(); for(int i = 0; i < cLabs.length; i++){ System.out.print(i+1 + " "); for(int j = 0; j < cLabs[i].length; j++){ if(cLabs[i][j].equals(idNumber2)){ cLabs[i][j] = "Empty"; } System.out.print((j+1) + ":" + cLabs[i][j] + " "); } System.out.println(); } System.out.println("User " + idNumber2 + " is logged off"); break; case 3: // searching the array for matching id numbers using a booling expression for an If Statement System.out.println("Search for A ID Number"); String Search = userInput.next(); // ID number variable String stringToSearch = Search; // Unessary conversion boolean found = false; // boolean set to false // variable for the [i][j] coordinates int s = 0; int l = 0; // Looping through the array to see ID number equals to any of the strings in array for(int i = 0; i < cLabs.length; i++){ System.out.print(i+1 + " "); for(int j = 0; j < cLabs[i].length; j++){ if(cLabs[i][j].equals(stringToSearch)){ found = true; // If there is a match then boolean turns true l = i; // variables for the coordinates s = j; } System.out.print((j+1) + ":" + cLabs[i][j] + " "); } System.out.println(); } if(found){ // displays the array if found and boolean is true System.out.print("ID Number found"); System.out.println("ID Number: " + stringToSearch); System.out.println("At Lab: " + (l+1)); System.out.println("Station: " + (s+1)); }else { // if no match then else statment executes System.out.println("ID Number not found"); } break; default :// Must have default for case statament System.out.println("Invalid input"); break; } /* The following code is the same as above but I have added a Do.. While loop so the program will keep running until the user makes a choice of 0 and then the program will end. */ do{ // To loop the program so we can keep login on and loggin System.out.println("MAIN MENU"); System.out.println("0) Quit \n1) Simulate Login \n2) Simulate Logoff \n3) Search"); menuChoice = userInput.nextInt(); switch(menuChoice){ case 0: System.exit(0); // exit out the program case 1: // Using the scanner to insert data in variables System.out.println("Enter the 5 digit ID number of the user logging in:"); String idNumber = userInput.next(); System.out.println("Enter the lab number the user is logging in from (1-4):"); int lNum = userInput.nextInt(); System.out.println("Enter computer station number the user is logging into (1-6):"); int cStation = userInput.nextInt(); /* looping through the 2D array to add the 5 digit number and placeing it into the correct Lab and Computer Station */ for(int i = 0; i < cLabs.length; i++){ System.out.print(i+1 + " "); for(int j = 0; j < cLabs[i].length; j++){ cLabs[(lNum-1)][(cStation-1)] = idNumber; System.out.print((j+1) + ":" + cLabs[i][j] + " "); } System.out.println(); } break; case 2: System.out.println("Enter the 5 digit ID number of the user to logout:"); String idNumber2 = userInput.next(); for(int i = 0; i < cLabs.length; i++){ System.out.print(i+1 + " "); for(int j = 0; j < cLabs[i].length; j++){ if(cLabs[i][j].equals(idNumber2)){ cLabs[i][j] = "Empty"; } System.out.print((j+1) + ":" + cLabs[i][j] + " "); } System.out.println(); } System.out.println("User " + idNumber2 + " is logged off"); break; case 3: // searching the array for matching id numbers using a booling expression System.out.println("Search for A ID Number"); String Search = userInput.next(); // inputing id number String stringToSearch = Search; boolean found = false; int l = 0; int s = 0; for(int i = 0; i < cLabs.length; i++){ System.out.print(i+1 + " "); for(int j = 0; j < cLabs[i].length; j++){ if(cLabs[i][j].equals(stringToSearch)){ found = true; l = i; s = j; } System.out.print((j+1) + ":" + cLabs[i][j] + " "); } System.out.println(); } if(found){ // displays the array if found System.out.println("ID Number found"); System.out.println("ID Number:" + stringToSearch); System.out.println("At Lab:" + (l+1)); System.out.println("Station:" + (s+1)); }else { System.out.println("ID Number not found"); } break; default : System.out.println("Invalid input"); break; } }while(menuChoice !=0); } }
package com.magic; import java.util.Random; /** * com.magic * * @author jh * @date 2018/9/6 14:14 * description:对多态的理解. * 多态是运行时行为。 */ interface Animal { public void eat(); } class Dog implements Animal { @Override public void eat() { System.out.println ("dog eat bone-------111"); } } class Cat implements Animal { @Override public void eat() { System.out.println ("Cat eat aaa-------222"); } } class Sheep implements Animal { @Override public void eat() { System.out.println ("Sheep eat grass-------3333"); } } public class TestPolymorphism { public static Animal getInstance(int key) { Animal animal = null; switch (key) { case 0: animal = new Dog (); break; case 1: animal = new Cat (); break; default: animal = new Sheep (); break; } return animal; } public static void main(String[] args) { Animal animal = TestPolymorphism.getInstance (new Random ().nextInt (3)); animal.eat (); } }
package org.sbbs.app.demo.dao; import org.sbbs.app.demo.model.DictionaryItem; import org.sbbs.base.dao.BaseDao; public interface DictionaryItemDao extends BaseDao<DictionaryItem, Long> { }
/* * Copyright (C) 2019-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.mirror.importer; import com.hedera.mirror.common.domain.StreamType; import com.hedera.mirror.common.domain.entity.EntityId; import com.hedera.mirror.common.domain.entity.EntityType; import java.io.FileFilter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.function.Function; import lombok.NonNull; import lombok.Value; import lombok.extern.log4j.Log4j2; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.io.filefilter.WildcardFileFilter; @Log4j2 @Value public class FileCopier { private static final FileFilter ALL_FILTER = f -> true; private final Path from; private final Path to; private final FileFilter dirFilter; private final FileFilter fileFilter; private FileCopier( @NonNull Path from, @NonNull Path to, @NonNull FileFilter dirFilter, @NonNull FileFilter fileFilter) { this.from = from; this.to = to; this.dirFilter = dirFilter; this.fileFilter = fileFilter; } public static FileCopier create(Path from, Path to) { return new FileCopier(from, to, ALL_FILTER, ALL_FILTER); } public FileCopier from(Path source) { return new FileCopier(from.resolve(source), to, dirFilter, fileFilter); } public FileCopier from(String... source) { return from(Paths.get("", source)); } public FileCopier filterDirectories(FileFilter newDirFilter) { FileFilter andFilter = dirFilter == ALL_FILTER ? newDirFilter : f -> dirFilter.accept(f) || newDirFilter.accept(f); return new FileCopier(from, to, andFilter, fileFilter); } public FileCopier filterDirectories(String wildcardPattern) { return filterDirectories( WildcardFileFilter.builder().setWildcards(wildcardPattern).get()); } public FileCopier filterFiles(FileFilter newFileFilter) { FileFilter andFilter = fileFilter == ALL_FILTER ? newFileFilter : f -> fileFilter.accept(f) || newFileFilter.accept(f); return new FileCopier(from, to, dirFilter, andFilter); } public FileCopier filterFiles(String wildcardPattern) { return filterFiles( WildcardFileFilter.builder().setWildcards(wildcardPattern).get()); } public FileCopier to(Path target) { return new FileCopier(from, to.resolve(target), dirFilter, fileFilter); } public FileCopier to(String... target) { return to(Paths.get("", target)); } public void copy() { try { log.debug("Copying {} to {}", from, to); FileFilter combinedFilter = f -> f.isDirectory() ? dirFilter.accept(f) : fileFilter.accept(f); FileUtils.copyDirectory(from.toFile(), to.toFile(), combinedFilter); if (log.isTraceEnabled()) { try (var paths = Files.walk(to)) { paths.forEach(p -> log.trace("Moved: {}", p)); } } } catch (Exception e) { throw new RuntimeException(e); } } /** * Copy a {@code from} account ID based directory structure to the destination as a node ID based structure. * * @param destinationAdjuster adjustment to make to {@code to} path. Often {@code to} as been configured to be a * specific account ID directory stream type, such as {@code accountBalances} or * {@code recordstreams} etc. Provide a function to adjust this prior to files being * copied. If no adjustment is required, provide {@link Function.identity()} * @param network Hedera or dev/test network name, typically found in mirror node properties. */ public void copyAsNodeIdStructure(Function<Path, Path> destinationAdjuster, String network) { try { var destination = destinationAdjuster.apply(to); var networkDir = destination.resolve(network); var sourceNodeDirs = FileUtils.listFilesAndDirs(from.toFile(), TrueFileFilter.INSTANCE, null); for (var sourceNodeDir : sourceNodeDirs) { var sourceNodeDirName = sourceNodeDir.getName(); var streamTypeOpt = Arrays.stream(StreamType.values()) .filter(st -> sourceNodeDirName.startsWith(st.getNodePrefix())) .findFirst(); if (streamTypeOpt.isPresent()) { var streamType = streamTypeOpt.get(); EntityId nodeEntityId = EntityId.of( sourceNodeDirName.substring( streamType.getNodePrefix().length()), EntityType.ACCOUNT); var destinationNodeIdPath = networkDir.resolve(Path.of( String.valueOf(nodeEntityId.getShardNum()), String.valueOf(nodeEntityId.getEntityNum() - 3L), // Node ID streamType.getNodeIdBasedSuffix())); FileUtils.copyDirectory(sourceNodeDir, destinationNodeIdPath.toFile()); } } } catch (Exception e) { throw new RuntimeException(e); } } }
package kata.game_of_life; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.*; public class NeighboursTest { @Test public void shouldBeEightNeighboursInGrid() { Neighbours neighbours = new Neighbours(); List<List<String>> grid = Arrays.asList( Arrays.asList(".", "*", "*", "*", "."), Arrays.asList(".", "*", ".", "*", "."), Arrays.asList(".", "*", "*", "*", ".") ); int neighboursAmount = neighbours.getNeighbours(1, 2, grid); assertThat(neighboursAmount).isEqualTo(8); } @Test public void shouldBeNoNeighboursInGrid() { Neighbours neighbours = new Neighbours(); List<List<String>> grid = Arrays.asList( Arrays.asList(".", ".", ".", ".", "."), Arrays.asList(".", ".", ".", ".", "."), Arrays.asList(".", ".", ".", ".", ".") ); int neighboursAmount = neighbours.getNeighbours(1, 2, grid); assertThat(neighboursAmount).isEqualTo(0); } }
package edu.floridapoly.polycamsportal.util; import android.util.Log; import java.net.Authenticator; import java.net.PasswordAuthentication; public final class PolyAuthenticator extends Authenticator { public static final String API_DOMAIN = "poly-cams-scraper.herokuapp.com"; private static final String TAG = PolyAuthenticator.class.getCanonicalName(); private static PolyAuthenticator instance = new PolyAuthenticator(); private PasswordAuthentication apiAuth = null; public static PolyAuthenticator getInstance() { return instance; } /** * Set this authenticator as the default authenticator for the app. * Note: This should be done during app initialization so that any API * requests made can be authenticated. */ public static void setAsDefault() { Authenticator.setDefault(getInstance()); } /** * Globally sets the username and password for the scraper API * authentication. This must be called before any API requests are made. * * @param username Florida Poly username. * @param password Florida Poly password. */ public static void setApiAuth(String username, String password) { getInstance().apiAuth = new PasswordAuthentication( username, password.toCharArray()); } @Override protected PasswordAuthentication getPasswordAuthentication() { // Only send authentication when using HTTPS String protocol = getRequestingProtocol(); if (!protocol.equals("https")) { Log.w(TAG, "Authentication requested over protocol: " + protocol + ". " + "Authentication will only be sent over HTTPS."); return null; } // Only Basic authentication is supported String scheme = getRequestingScheme(); if (!scheme.equals("Basic")) { Log.w(TAG, "Authentication scheme not supported: " + scheme); return null; } // Only give the credentials to the API domain. Give other domains no // authentication. // if (host.equals(Resources.getSystem().getString(R.string.api_domain)) { String host = getRequestingHost(); if (host.equals(API_DOMAIN)) { return apiAuth; } else { Log.w(TAG, "Authentication requested for unknown host: " + host); return null; } } }
package de.madjosz.adventofcode.y2020; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; public class Day14 { private final List<String> program; public Day14(List<String> input) { this.program = input; } private static Pattern p = Pattern.compile("mem\\[(\\d+)\\] = (\\d+)"); public long a1() { long[] mem = new long[0xFFFF]; Mask mask = new Mask("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); for (String line : program) { if (line.startsWith("mask = ")) mask = new Mask(line.substring(7)); else { Matcher m = p.matcher(line); if (!m.find()) throw new IllegalArgumentException(line); int idx = Integer.parseInt(m.group(1)); long value = Long.parseLong(m.group(2)); mem[idx] = mask.apply(value); } } return Arrays.stream(mem).sum(); } private static class Mask { private final long and; private final long or; public Mask(String mask) { this.and = Long.parseLong(mask.replaceAll("[^0]", "1"), 2); this.or = Long.parseLong(mask.replaceAll("[^1]", "0"), 2); } public long apply(long input) { return (input & and) | or; } } public long a2() { Map<Long, Long> mem = new HashMap<>(); Mask2 mask = new Mask2("000000000000000000000000000000000000"); for (String line : program) { if (line.startsWith("mask = ")) mask = new Mask2(line.substring(7)); else { Matcher m = p.matcher(line); if (!m.find()) throw new IllegalArgumentException(line); int idx = Integer.parseInt(m.group(1)); long value = Long.parseLong(m.group(2)); for (Long address : mask.apply(idx)) mem.put(address, value); } } return mem.values().stream().mapToLong(l -> l).sum(); } private static class Mask2 { private final int[] x; private final long or; public Mask2(String mask) { int length = mask.length(); this.x = IntStream.range(0, length).filter(i -> mask.charAt(length - i - 1) == 'X').toArray(); this.or = Long.parseLong(mask.replaceAll("[^1]", "0"), 2); } public List<Long> apply(long input) { List<Long> results = new ArrayList<>(); results.add(input | or); for (int i = 0; i < x.length; ++i) { List<Long> newResults = new ArrayList<>(); for (Long l : results) { long mask = 1L << x[i]; newResults.add(l | mask); newResults.add(l & ~mask); } results = newResults; } return results; } } }
public class Asteroid { protected final int MAX_NUM = 4; protected final int ADD = 0; protected final int SUB = 1; protected final int MULT = 2; protected final int DIV = 3; protected final int EASY_DIGITS = 9; protected final int MEDIUM_DIGITS = 99; protected final int HARD_DIGITS = 999; public int answer; public int pointVal; public int[] numbers = new int[MAX_NUM]; public int operations; public Asteroid() { this.operationGenerator(); } public void operationGenerator() { int ran = (int) (Math.random() * 2); operations = ran; } public String stringOperation() { if (operations == 0) return "+"; else if (operations == 1) return "-"; else return "ERROR"; } public void doQuestion() { int num1 = numbers[0]; int num2 = numbers[1]; if (operations == ADD) answer = (num1 + num2); else if (operations == SUB) answer = (num1 - num2); } public int getAnswer() { return answer; } public boolean checkAnswer(int userAnswer) { if (userAnswer == answer) return true; else return false; } public String toString() { return "" + numbers[0] + " " + this.stringOperation() + " " + numbers[1]; } public int getPoints(){ return 0; } }
package mg.egg.eggc.compiler.egg.java; public interface IEGGMessages { public static final int id_EGG_global_var_yet_declared = 1572864; public static final int id_EGG_expected_token = 1572865; public static final int id_EGG_not_a_non_terminal = 1572866; public static final int id_EGG_attribute_yet_declared = 1572867; public static final int id_EGG_no_terminal_attribute = 1572868; public static final int id_EGG_expected_eof = 1572869; public static final int id_EGG_space_illegal_here = 1572870; public static final int id_EGG_axiom_illegal_here = 1572871; public static final int id_EGG_undefined_actions = 1572872; public static final int id_EGG_terminal_yet_declared = 1572873; public static final int id_EGG_attributes_non_initialized = 1572874; public static final int id_EGG_action_useless = 1572875; public static final int id_EGG_action_yet_declared = 1572876; public static final int id_EGG_option_error = 1572877; public static final int id_EGG_unexpected_token = 1572878; }
package com.fixit.rest.apis; import com.fixit.rest.requests.APIRequest; import com.fixit.rest.requests.APIRequestHeader; import com.fixit.rest.requests.data.TradesmenOrderRequestData; import com.fixit.rest.responses.APIResponse; import com.fixit.rest.responses.data.TradesmenOrderResponseData; import com.fixit.rest.services.OrderService; import retrofit2.Call; /** * Created by Kostyantin on 5/29/2017. */ public class OrderServiceAPI extends BaseServiceAPI { public final static String API_NAME = "services/orders"; private final OrderService mService; public OrderServiceAPI(APIRequestHeader header, OrderService orderService) { super(header); mService = orderService; } public Call<APIResponse<TradesmenOrderResponseData>> orderTradesmen(TradesmenOrderRequestData requestData) { return mService.orderTradesmen(new APIRequest<>(mHeader, requestData)); } @Override public String getApiName() { return API_NAME; } }
package random.jcip; public class LaunderThrowableTest { public static void main(String[] args) { throw launderThrowable(new Throwable()); /* Exception in thread "main" java.lang.IllegalStateException: Not unchecked at random.LaunderThrowableTest.launderThrowable(LaunderThrowableTest.java:22) at random.LaunderThrowableTest.main(LaunderThrowableTest.java:5) Caused by: java.lang.Throwable ... 1 more */ // System.out.println("unreachable"); } private static RuntimeException launderThrowable(final Throwable cause) { if (cause instanceof RuntimeException) { return (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } else { throw new IllegalStateException("Not unchecked", cause); } } }
package pack.GestureApp; import android.gesture.Gesture; class GestureHolder { private Gesture gesture; private String gestureNaam; GestureHolder(Gesture gesture, String naam){ this.gesture = gesture; this.gestureNaam = naam; } Gesture getGesture(){ return gesture; } public void setGesture(Gesture gesture){ this.gesture = gesture; } String getNaam(){ return gestureNaam; } public void setNaam(String naam){ this.gestureNaam = naam; } }
package com.jim.multipos.ui.consignment_list.presenter; import com.jim.multipos.config.scope.PerFragment; import dagger.Binds; import dagger.Module; /** * Created by Sirojiddin on 30.11.2017. */ @Module public abstract class ConsignmentListPresenterModule { @Binds @PerFragment abstract ConsignmentListPresenter provideConsignmentListPresenter(ConsignmentListPresenterImpl presenter); }
package com.eclipsesource.a; final class d extends h { private final String string; d(String str) { if (str == null) { throw new NullPointerException("string is null"); } this.string = str; } public final String toString() { return this.string; } final void a(i iVar) { iVar.aa(this.string); } public final boolean isNumber() { return true; } public final int hS() { return Integer.parseInt(this.string, 10); } public final long hT() { return Long.parseLong(this.string, 10); } public final double hU() { return Double.parseDouble(this.string); } public final int hashCode() { return this.string.hashCode(); } public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.string.equals(((d) obj).string); } }
package com.shopware.customer; import static org.assertj.core.api.Assertions.assertThat; import org.json.JSONObject; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.shopware.test.api.ApiManagement; import com.shopware.test.base.TestBase; import com.shopware.test.pages.CustomerAccountPage; import com.shopware.test.pages.CustomerRegisterPage; import com.shopware.test.pages.HomePage; import com.shopware.test.pages.ProfileEditPage; import com.shopware.test.pages.base.ActionCustomer; import com.shopware.test.pages.base.ActionValidate; import com.shopware.test.pages.base.CustomerAccountPageConstants; import com.shopware.test.pages.base.CustomerPageConstansts; import com.shopware.test.pages.base.Customer_UI; import com.shopware.test.pages.base.HomePageConstansts; import com.shopware.test.utils.DataUtils; import com.shopware.test.utils.QALogger; public class Test_04_Change_Names_Customer extends TestBase { HomePage homePage; CustomerRegisterPage customerRegisterPage; CustomerAccountPage customerAccountPage; ProfileEditPage profileEditPage; ApiManagement api; Customer_UI customerUI; int customerId; @Test(priority = 1, description = "Change customer names") public void test01() { assertThat(homePage.getTitlePage()).isEqualTo(HomePageConstansts.TITLE_NAME_PAGE); homePage.action(ActionCustomer.SIGN_IN); homePage.redirectTo("#hide-registration"); assertThat(customerRegisterPage.getBrowserTitle()).isEqualTo(CustomerPageConstansts.TITLE_NAME_PAGE); customerRegisterPage.signIn(customerUI); customerRegisterPage.redirectTo("/account"); assertThat(customerAccountPage.getBrowserTitle()).isEqualTo(CustomerAccountPageConstants.TITLE_NAME_PAGE); customerAccountPage.action(ActionCustomer.CHANGE_PROFILE); customerAccountPage.redirectTo("/account/profile"); profileEditPage.checkPageIsDisplay(); customerUI.setFirstName("John"); customerUI.setLastName("Lennon"); profileEditPage.enterFieldsProfile(customerUI); profileEditPage.action(ActionCustomer.SAVE_CHANGES_PROFILE); assertThat(ProfileEditPage.PROFILE_GREEN_ALERT_MESSAGE).isEqualTo(profileEditPage.checkAlert(ActionValidate.SAVE_NAMES_ALERT, true)); profileEditPage.action(ActionCustomer.CUSTOMER_ACCOUNT_LINK); profileEditPage.waitPageIsRedirecting("/account/profile"); String names = DataUtils.capitalize(customerUI.getSalutation())+" "+customerUI.getFirstName()+" "+customerUI.getLastName(); String profile = customerAccountPage.checkProfileDashboard(ActionValidate.NAMES_PROFILE_DASHBOARD); assertThat(profile).isEqualTo(names); profile = customerAccountPage.checkProfileDashboard(ActionValidate.EMAIL_PROFILE_DASHBOARD); assertThat(profile).isEqualTo(customerUI.getEmail()); } @BeforeClass public void beforeClass() { QALogger.setLog(this); QALogger.info( "============================ Start: '" + this.getClass().getName() + "' ============================"); homePage = new HomePage(); customerRegisterPage = new CustomerRegisterPage(); customerAccountPage = new CustomerAccountPage(); profileEditPage = new ProfileEditPage(); customerUI = new Customer_UI(); api = new ApiManagement(); JSONObject jCustomer = customerUI.converToJSON(); JSONObject jCustomerResult = api.postCustomer(jCustomer.toString()); assertThat(api.getStatusCode()).isEqualTo("201"); customerId = jCustomerResult.getJSONObject("data").getInt("id"); } @AfterClass(alwaysRun=true) public void afterClass() { try { api.deleteCustomer(String.valueOf(customerId)); QALogger.info("Status code: " + api.getStatusCode()); assertThat(api.getStatusCode()).isEqualTo("200"); } catch (Exception e) { QALogger.error("Failed", e); } QALogger.info( "============================ End: '" + this.getClass().getName() + "' ============================"); } }
package org.scottrager.appfunding; import java.util.Date; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBAdapter { public static final String KEY_EVENTID = "event_id"; public static final String KEY_USER_NAME = "user_name"; public static final String KEY_PW_HASH = "pw_hash"; public static final String KEY_COUPONID = "coupon_id"; public static final String KEY_COMPANYID = "company_id"; public static final String KEY_COMPANY_NAME = "company_name"; public static final String KEY_COUPON_DETAILS = "coupon_details"; public static final String KEY_EXP_DATE = "exp_date"; public static final String KEY_FILE_URL = "file_url"; public static final String KEY_DATE_USED = "date_used"; public static final String KEY_FAVORITE = "favorite"; public static final String KEY_RECV_SYNC = "recv_sync"; public static final String KEY_LOCATIONID = "location_id"; public static final String KEY_ADDR_LINE1 = "address_line_1"; public static final String KEY_ADDR_LINE2 = "address_line_2"; public static final String KEY_LATITUDE = "latitude"; public static final String KEY_LONGITUDE = "longitude"; public static final String TAG = "DBAdapter"; public static final String DATABASE_NAME = "MyDB"; public static final String DATABASE_COUPONS_TABLE = "coupons"; public static final String DATABASE_COMPANY_TABLE = "company"; public static final String DATABASE_LOCATIONS_TABLE = "locations"; public static final String DATABASE_EVENTS_TABLE = "events"; public static final int DATABASE_VERSION = 35; private static final String DATABASE_CREATE_1 = "create table "+DATABASE_COMPANY_TABLE +" (company_id integer primary key, " + "company_name text not null, file_url text not null);"; private static final String DATABASE_CREATE_2 = "create table "+DATABASE_COUPONS_TABLE +" (coupon_id integer primary key, " + " company_id integer, coupon_details text not null, " + " exp_date text not null, " + " favorite integer not null, " + " FOREIGN KEY (company_id) REFERENCES company(company_id));"; private static final String DATABASE_CREATE_3 = "create table "+DATABASE_LOCATIONS_TABLE +" (company_id integer, " + "location_id integer, address_line_1 text, address_line_2 text, latitude float, longitude float, " + "FOREIGN KEY (company_id) REFERENCES company(company_id) );"; private static final String DATABASE_CREATE_4 = "create table "+DATABASE_EVENTS_TABLE +" ( event_id integer not null primary key, " + " coupon_id integer not null, " + " date_used text, recv_sync text not null, " + " FOREIGN KEY (coupon_id) REFERENCES coupons(coupon_id) );"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter (Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub try { Log.d(TAG, "Executing the following sql statements to make tables:"); Log.d(TAG, DATABASE_CREATE_1); Log.d(TAG, DATABASE_CREATE_2); Log.d(TAG, DATABASE_CREATE_3); Log.d(TAG, DATABASE_CREATE_4); db.execSQL(DATABASE_CREATE_1); db.execSQL(DATABASE_CREATE_2); db.execSQL(DATABASE_CREATE_3); db.execSQL(DATABASE_CREATE_4); } catch (SQLException e) { Log.e(TAG, "Exception thrown while creating tables"); e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub Log.d(TAG, "Upgrading database version from "+oldVersion+" to " + newVersion + " which will destroy data."); db.execSQL("DROP TABLE IF EXISTS "+DATABASE_EVENTS_TABLE); db.execSQL("DROP TABLE IF EXISTS "+DATABASE_LOCATIONS_TABLE); db.execSQL("DROP TABLE IF EXISTS "+DATABASE_COUPONS_TABLE); db.execSQL("DROP TABLE IF EXISTS "+DATABASE_COMPANY_TABLE); onCreate(db); } } public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } public void close() { DBHelper.close(); } // These coupons need to go into the events table // they will point to the correct company_id values and coupon_id values // Need to check if we have public int insertCouponEvent( int event_id, int coupon_id ) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_EVENTID, event_id); initialValues.put(KEY_COUPONID, coupon_id); //initialValues.put(KEY_DATE_USED, ); initialValues.put(KEY_RECV_SYNC, "0"); return (int)db.insert(DATABASE_EVENTS_TABLE, null, initialValues); } public int insertCoupon( int coupon_id, int company_id, String coupon_details, String exp_date, int fav ) { Log.d(TAG, "Inserting coupon with coupon_id = "+coupon_id+", company_id = "+company_id+", exp_date = "+exp_date+", fav = "+fav); ContentValues initialValues = new ContentValues(); initialValues.put(KEY_COUPONID, coupon_id); initialValues.put(KEY_COMPANYID, company_id); initialValues.put(KEY_COUPON_DETAILS, coupon_details); initialValues.put(KEY_EXP_DATE, exp_date); initialValues.put(KEY_FAVORITE, fav); return (int)db.insert(DATABASE_COUPONS_TABLE, null, initialValues); } public int insertCompany( int company_id, String company_name, String file_url) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_COMPANYID, company_id); initialValues.put(KEY_COMPANY_NAME, company_name); initialValues.put(KEY_FILE_URL, file_url); return (int)db.insert(DATABASE_COMPANY_TABLE, null, initialValues); } public int insertLocation( int company_id, int location_id, String addr_line_1, String addr_line_2, double latitude, double longitude ) { Log.d(TAG, "Trying to insertLocation with company_id = "+company_id+", and location_id="+location_id+", addr_1 = " + addr_line_1 + ", addr_2 = "+addr_line_2+", lat="+latitude+", long="+longitude); ContentValues initialValues = new ContentValues(); initialValues.put(KEY_COMPANYID, company_id); initialValues.put(KEY_LOCATIONID, location_id); initialValues.put(KEY_ADDR_LINE1, addr_line_1); initialValues.put(KEY_ADDR_LINE2, addr_line_2); initialValues.put(KEY_LATITUDE, latitude); initialValues.put(KEY_LONGITUDE, longitude); int numInserted = -1; try { numInserted = (int)db.insert(DATABASE_LOCATIONS_TABLE, null, initialValues); } catch( SQLException e ) { Log.d(TAG, "SQLException:"); e.printStackTrace(); } return numInserted; } public boolean deleteCoupon( int rowId ) { long rows = db.delete(DATABASE_EVENTS_TABLE, KEY_EVENTID + "=?", new String[]{""+rowId+""}); Log.d(TAG, "number of rows deleted = "+rows); return (rows > (long)0); } public boolean markCouponSynced( int rowId ) { ContentValues newValue = new ContentValues(); newValue.put(KEY_RECV_SYNC, "1"); int numRowsAffected = db.update(DATABASE_EVENTS_TABLE, newValue, KEY_EVENTID + "=?", new String[]{""+rowId+""}); return numRowsAffected > 0; } public boolean markCouponUsed( int rowId ) { ContentValues newDateUsed = new ContentValues(); Date date = new Date(); newDateUsed.put(KEY_DATE_USED, (int)date.getTime()/1000); Log.w(TAG, "Marking Coupon with rowId = " +rowId+ " as used...date used = " + date.getTime()/1000); Log.w(BrowseCouponsActivity.POSITION_TAG, "markCouponUsed in DBAdapter: rowId = " +rowId+ ", date used = " + date.getTime()/1000); int numRowsAffected = db.update( DATABASE_EVENTS_TABLE, newDateUsed, KEY_EVENTID + "=?", new String[]{""+rowId+""}); Log.w(TAG, "Number rows affected = " +numRowsAffected); /*//For debug purposes: Cursor c = db.query(DATABASE_TABLE, new String[] {KEY_EVENTID, KEY_DATE_USED}, null, null, null, null, null); if( c.moveToFirst() ) { do { Log.w(TAG, "Row ID = "+c.getInt( c.getColumnIndex(KEY_EVENTID) ) ); Log.w(TAG, "Date Used = "+c.getInt( c.getColumnIndex(KEY_DATE_USED) ) ); }while( c.moveToNext() ); } */ return numRowsAffected > 0; } public boolean markCouponAsFavorite( int rowId ) { // need to find coupon_event in events table and get coupon_id of that coupon_event // then we can update that coupon_id's favorite value int coupon_id; Cursor cursor = db.query( DATABASE_EVENTS_TABLE, new String[] { KEY_COUPONID }, KEY_EVENTID + "=?", new String[]{String.valueOf(rowId)}, null, null, null); if( cursor.moveToFirst() ) { coupon_id = cursor.getInt(cursor.getColumnIndex(KEY_COUPONID)); } else { return false; } ContentValues newValue = new ContentValues(); newValue.put(KEY_FAVORITE, 1); Log.w(TAG, "Marking Coupon with rowId = " +rowId+ " and " +coupon_id+" as favorite"); int numRowsAffected = db.update( DATABASE_COUPONS_TABLE, newValue, KEY_COUPONID + "=?", new String[]{String.valueOf(coupon_id)} ); Log.w(TAG, "Number rows affected = " +numRowsAffected); return numRowsAffected > 0; } public boolean markCouponAsNotFavorite( int rowId ) { // need to find coupon_event in events table and get coupon_id of that coupon_event // then we can update that coupon_id's favorite value int coupon_id; Cursor cursor = db.query( DATABASE_EVENTS_TABLE, new String[] { KEY_COUPONID }, KEY_EVENTID + "=?", new String[]{String.valueOf(rowId)}, null, null, null); if( cursor.moveToFirst() ) { coupon_id = cursor.getInt(cursor.getColumnIndex(KEY_COUPONID)); } else { return false; } ContentValues newValue = new ContentValues(); newValue.put(KEY_FAVORITE, 0); Log.w(TAG, "Marking Coupon with rowId = " +rowId+ " and " +coupon_id+" as not favorite"); int numRowsAffected = db.update( DATABASE_COUPONS_TABLE, newValue, KEY_COUPONID + "=?", new String[]{String.valueOf(coupon_id)} ); Log.w(TAG, "Number rows affected = " +numRowsAffected); return numRowsAffected > 0; } public boolean deleteAllCoupons() { return db.delete( DATABASE_EVENTS_TABLE, null, null ) > 0; } // need to make a query that joins all tables public Cursor getAllUnusedCoupons() { //return db.query( DATABASE_EVENTS_TABLE, new String[] {KEY_EVENTID, KEY_COUPON_NAME, // KEY_COUPON_DETAILS, KEY_EXP_DATE, KEY_FILE_URL, KEY_DATE_USED, KEY_FAVORITE, KEY_LATITUDE, KEY_LONGITUDE}, // KEY_DATE_USED + "=?", new String[]{"0"}, null, null, null); // SELECT * FROM events, coupons, company // WHERE events.date_used IS NULL AND // events.coupon_id=coupons.coupon_id AND // coupons.company_id=company.company_id AND Cursor c1 = db.rawQuery("SELECT * FROM company", null); Log.d(TAG, "Number of companies in db = "+c1.getCount()); Cursor c2 = db.rawQuery("SELECT * FROM coupons", null); Log.d(TAG, "Number of coupons in db = "+c2.getCount()); Cursor c3 = db.rawQuery("SELECT * FROM events", null); Log.d(TAG, "Number of events in db = "+c3.getCount()); Cursor c4 = db.rawQuery("SELECT * FROM locations", null); Log.d(TAG, "Number of locations in db = "+c4.getCount()); if( c3.moveToFirst() ) { do { Log.d(TAG, "rowId = "+c3.getInt(c3.getColumnIndex(KEY_EVENTID))); }while( c3.moveToNext() ); } //String query = "SELECT * FROM events INNER JOIN coupons ON events.coupon_id=coupons.coupon_id INNER JOIN company ON coupons.company_id=company.company_id"; // String query = "SELECT * FROM events, coupons, company"; /* String query = "SELECT * FROM " + DATABASE_EVENTS_TABLE + " INNER JOIN " + DATABASE_COUPONS_TABLE + " INNER JOIN " + DATABASE_COMPANY_TABLE + "ON "+ DATABASE_EVENTS_TABLE + "." + KEY_DATE_USED + " IS NULL AND " + DATABASE_EVENTS_TABLE+"."+KEY_COUPONID+"="+DATABASE_COUPONS_TABLE+"."+KEY_COUPONID+" AND " + DATABASE_COUPONS_TABLE + "." + KEY_COMPANYID + "=" + DATABASE_COMPANY_TABLE + "." + KEY_COMPANYID +";"; */ /* String query = "SELECT * FROM events, coupons, company, locations WHERE events.date_used IS NULL " + "AND events.coupon_id=coupons.coupon_id AND coupons.company_id=company.company_id" +" AND locations.location_id=1";*/ //String query = "SELECT "+KEY_EVENTID+", "+KEY_COMPANY_NAME+", "+KEY_COUPON_DETAILS+", "+KEY_EXP_DATE+", "+KEY_FILE_URL+", "+KEY_DATE_USED String query = "SELECT * " + "FROM events, coupons, locations, company " + "WHERE events.coupon_id=coupons.coupon_id " + "AND events.date_used IS NULL " + "AND coupons.company_id=company.company_id " + "AND company.company_id=locations.company_id " +" AND locations.location_id=1"; Cursor c = db.rawQuery(query, null); Log.d(TAG, "Number of unused coupons = "+c.getCount()); /*if( c.moveToFirst() ) { do { Log.d(TAG, "rowId = "+c.getInt(c.getColumnIndex(KEY_EVENTID))); }while( c.moveToNext() ); }*/ return c; } // need to make a query that joins all tables public Cursor getAllUnusedCouponsOfCompany( String desiredCompany ) { //return db.query( DATABASE_EVENTS_TABLE, new String[] {KEY_EVENTID, KEY_COUPON_NAME, // KEY_COUPON_DETAILS, KEY_EXP_DATE, KEY_FILE_URL, KEY_DATE_USED, KEY_FAVORITE, KEY_LATITUDE, KEY_LONGITUDE}, // KEY_DATE_USED + "=? AND KEY_COUPON_NAME =?", new String[]{"0", company}, null, null, null); String query = "SELECT * " + "FROM events, coupons, locations, company " + "WHERE events.coupon_id=coupons.coupon_id " + "AND events.date_used IS NULL " + "AND coupons.company_id=company.company_id " + "AND company.company_id=locations.company_id " + "AND locations.location_id=1 " + "AND company.company_name=\""+desiredCompany+"\""; Cursor c = db.rawQuery(query, null); // SELECT * FROM events, coupons, company // String query = "SELECT * FROM " + DATABASE_EVENTS_TABLE + ", " + DATABASE_COUPONS_TABLE + ", " + DATABASE_COMPANY_TABLE // + " WHERE " + DATABASE_EVENTS_TABLE + "." + KEY_DATE_USED + " IS NULL AND " // WHERE events.date_used IS NULL AND // + DATABASE_COMPANY_TABLE + "." + KEY_COMPANY_NAME + "='" + desiredCompany + "' AND "// company.name="desiredCompany" AND // + DATABASE_EVENTS_TABLE+"."+KEY_COUPONID+"="+DATABASE_COUPONS_TABLE+"."+KEY_COUPONID+" AND " // events.coupon_id=coupons.coupon_id AND // + DATABASE_COUPONS_TABLE + "." + KEY_COMPANYID + "=" + DATABASE_COMPANY_TABLE + "." + KEY_COMPANYID +";"; // coupons.company_id=company.company_id AND Log.d(TAG, "Number of unused coupons from "+desiredCompany+" = "+c.getCount()); if( c.moveToFirst() ) { do { Log.d(TAG, "rowId = "+c.getInt(c.getColumnIndex(KEY_EVENTID))); }while( c.moveToNext() ); } return c; } // need to make a query that joins all tables ?? public Cursor getUsedCoupons() { return db.query( DATABASE_EVENTS_TABLE+", "+DATABASE_COUPONS_TABLE, new String[] {KEY_EVENTID, KEY_FAVORITE, KEY_DATE_USED}, "events.coupon_id=coupons.coupon_id AND " + KEY_DATE_USED + "!=?", new String[]{"0"}, null, null, null, null); } // need to make a query that joins all tables public Cursor getUnsyncedCoupons() { return db.query( DATABASE_EVENTS_TABLE, new String[] {KEY_EVENTID}, KEY_RECV_SYNC + "=?", new String[]{"0"}, null, null, null, null); } // this will need to do more...probably need to accept company_id as input, query that table // and then query locations database and return results...will have to decide if we should // calculate distances and limit results here (probably) or from place where call is made public Cursor getLocations() { // should we only return locations that we have coupons for? //Cursor c = db.query( DATABASE_LOCATIONS_TABLE, new String[]{"company_id", "latitude", "longitude"}, "company_id=?", new String[]{"1"}, null, null, null, null); Cursor c = db.rawQuery("SELECT * FROM locations", null); if( c == null ) Log.d(TAG, "locations query returned null"); return c; } // need to make a query that joins all tables public Cursor getCompanyNameFromId( int id ) { // choose the companies that we have unused coupons for and get all locations String query = "SELECT * " + "FROM company " + "WHERE company.company_id="+id+" "; Log.d(TAG, "Executing query: "+query); Cursor c = db.rawQuery(query, null); Log.d(TAG, "Num responses = "+c.getCount()); return c; } public int getNumCouponsFromId( int id ) { // SELECT * FROM events,company,coupons // WHERE events.coupon_id=coupons.coupon_id // AND events.date_used IS NULL // AND company.company_id=1 // AND coupons.comany_id=company.company_id String query = "SELECT * " + "FROM "+DATABASE_EVENTS_TABLE+","+DATABASE_COMPANY_TABLE+","+DATABASE_COUPONS_TABLE+" " + "WHERE "+DATABASE_EVENTS_TABLE+"."+KEY_COUPONID+"="+DATABASE_COUPONS_TABLE+"."+KEY_COUPONID+" " + "AND "+DATABASE_EVENTS_TABLE+"."+KEY_DATE_USED+" IS NULL " + "AND "+DATABASE_COMPANY_TABLE+"."+KEY_COMPANYID+"=1 " + "AND "+DATABASE_COUPONS_TABLE+"."+KEY_COMPANYID+"="+DATABASE_COMPANY_TABLE+"."+KEY_COMPANYID; Cursor c = db.rawQuery(query, null); Log.d(TAG, "In getNumCouponsFromId: companyId "+ id + " returns "+ c.getCount() +" coupons."); return c.getCount(); } public boolean couponInDatabase( int coupon_id ) { Cursor c = db.query( DATABASE_COUPONS_TABLE, new String[] {KEY_COUPONID}, KEY_COUPONID + "=?", new String[]{String.valueOf(coupon_id)}, null, null, null, null); if( c.moveToFirst() ) return true; else return false; } public boolean locationInDatabase( int company_id, int location_id ) { Cursor c = db.query( DATABASE_LOCATIONS_TABLE, new String[] {KEY_COMPANYID, KEY_LOCATIONID}, KEY_COMPANYID + "=? AND " + KEY_LOCATIONID + "=?", new String[]{String.valueOf(company_id),String.valueOf(location_id)}, null, null, null, null); if( c.moveToFirst() ) return true; else return false; } public boolean companyInDatabase( int company_id ) { Cursor c = db.query( DATABASE_COMPANY_TABLE, new String[] {KEY_COMPANYID}, KEY_COMPANYID + "=?", new String[]{String.valueOf(company_id)}, null, null, null, null); if( c.moveToFirst() ) return true; else return false; } public void deleteDatabase() { db.execSQL( "DROP TABLE IF EXISTS coupons" ); } }
package com.citisense.vidklopcic.e_smart; import android.app.Activity; import android.util.Log; import android.widget.Toast; import java.util.ArrayList; import java.util.Collections; import java.util.regex.Pattern; import app.akexorcist.bluetotohspp.library.BluetoothSPP; import app.akexorcist.bluetotohspp.library.BluetoothState; /** * Created by vidklopcic on 05/08/16. */ public class DataProvider { public interface WhUpdatedCallback { void onWhUpdate(Double wh); } public interface DataUpdateCallback { void onDataUpdate(); } private enum DPStates { DISCONNECTED, CONNECTED } private static final String DEVICE_NAME = "ecatBMS"; private static final String GET_COMMAND = "BMS_INFO"; private boolean mGetCmdAlreadySent = false; private WhUpdatedCallback mWhUpdatedCallback; private DataUpdateCallback mDataUpdateCallback; private DPStates mState = DPStates.CONNECTED; // variables from log public BluetoothSPP mDevice; private Integer mSOC = 0; private ArrayList<Double> mCellVoltages = new ArrayList<>(); private Integer mCurrent = 0; private Double mVoltage = 0d; private Double mCellMin = 0d; private Double mCellMax = 0d; private Integer mBMSTemp = 0; private Integer mCellTemp = 0; private Double mWh = 0d; private Activity mContext; public DataProvider(Activity context) { mContext = context; mDevice = new BluetoothSPP(context); initBluetooth(); startWhCalculationThread(); } public void initBluetooth() { mDevice.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() { @Override public void onDeviceConnected(String name, String address) { mState = DPStates.CONNECTED; mDevice.send(GET_COMMAND, true); Toast.makeText(mContext, "connected", Toast.LENGTH_SHORT).show(); } @Override public void onDeviceDisconnected() { mState = DPStates.DISCONNECTED; Toast.makeText(mContext, "disconnected", Toast.LENGTH_SHORT).show(); } @Override public void onDeviceConnectionFailed() { } }); mDevice.setOnDataReceivedListener(new BluetoothSPP.OnDataReceivedListener() { @Override public void onDataReceived(byte[] data, String message) { dataReceived(message); } }); mDevice.setupService(); mDevice.startService(BluetoothState.DEVICE_OTHER); mDevice.autoConnect(DEVICE_NAME); } public void setWhUpdatedCallback(WhUpdatedCallback callback) { mWhUpdatedCallback = callback; } public void setDataUpdatedCallback(DataUpdateCallback callback) { mDataUpdateCallback = callback; } public void unsetDataUpdatedCallback() { mDataUpdateCallback = null; } private void dataReceived(String message) { try { mVoltage = Integer.valueOf(message.split(Pattern.quote("voltage="))[1].split(Pattern.quote("[mV]"))[0]) / 1000.0; mCellVoltages.clear(); String[] cells = message.split(Pattern.quote("[0]="))[1].split(Pattern.quote("Ext."))[0].split(Pattern.quote("]=")); for (String cell : cells) { mCellVoltages.add(Integer.valueOf(cell.split(Pattern.quote("\n"))[0]) / 1000.0); } mCellMin = Collections.min(mCellVoltages); mCellMin = Collections.max(mCellVoltages); mCurrent = Integer.valueOf(message.split(Pattern.quote("current="))[1].split(Pattern.quote("[mA]"))[0]); mBMSTemp = Integer.valueOf(message.split(Pattern.quote("ensor[0] = "))[1].split(Pattern.quote("[C]"))[0]); mCellTemp = Integer.valueOf(message.split(Pattern.quote("ures[C]:"))[1].split(Pattern.quote(","))[0]); mSOC = Integer.valueOf(message.split(Pattern.quote("(SOC)="))[1].split(Pattern.quote("[%]"))[0]); } catch (Exception ignored) { Toast.makeText(mContext, "parsing exception", Toast.LENGTH_SHORT).show(); Log.d("DataProvider", "parsing exception (" + message + ")"); } if (mDataUpdateCallback != null) mDataUpdateCallback.onDataUpdate(); mDevice.send(GET_COMMAND, true); mGetCmdAlreadySent = true; } public void disconnectDevice() { mDevice.disconnect(); } public void connectDevice() { mDevice.autoConnect(DEVICE_NAME); } private void startWhCalculationThread() { Thread mWhCalculationThread = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if (mState == DPStates.CONNECTED) mWh += getPower() * (0.5 / 3600.0); if (mWhUpdatedCallback != null) mWhUpdatedCallback.onWhUpdate(mWh); if (mGetCmdAlreadySent) mGetCmdAlreadySent = false; else mDevice.send(GET_COMMAND, true); } } }); mWhCalculationThread.start(); } public DPStates getState() { return mState; } public Integer getSOC() { return mSOC; } public Double getCellMin() { return mCellMin; } public Double getCellMax() { return mCellMax; } public Integer getCellTemp() { return mCellTemp; } public Integer getBMSTemp() { return mBMSTemp; } public ArrayList<Double> getCells() { return mCellVoltages; } public Integer getCurent() { return mCurrent; } public double getPower() { return mCurrent * mVoltage; } public Double getVoltage() { return mVoltage; } public Double getWh() { return mWh; } public void resetWh() { mWh = 0d; } public void setWh(Double wh) { mWh = wh; if (mDataUpdateCallback != null) mDataUpdateCallback.onDataUpdate(); } }
package com.tt.miniapp.base.ui.viewwindow; import android.app.Activity; import android.app.Application; import android.content.Intent; import android.os.Bundle; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.WeakHashMap; public class ViewWindowManager { public static WeakHashMap<Activity, Integer> activityLifecycleStateMap; private static volatile boolean isInited; private static HashSet<WeakReference<ViewWindowRoot>> viewWindowContainerMap = new HashSet<WeakReference<ViewWindowRoot>>(); static { activityLifecycleStateMap = new WeakHashMap<Activity, Integer>(); } public static void dispatchActivityDestroy(Activity paramActivity) { for (WeakReference<ViewWindowRoot> weakReference : viewWindowContainerMap) { if (weakReference != null) { ViewWindowRoot viewWindowRoot = weakReference.get(); if (viewWindowRoot != null && viewWindowRoot.getActivity() == paramActivity) viewWindowRoot.dispatchOnActivityDestroy(); } } } public static void dispatchActivityPause(Activity paramActivity) { for (WeakReference<ViewWindowRoot> weakReference : viewWindowContainerMap) { if (weakReference != null) { ViewWindowRoot viewWindowRoot = weakReference.get(); if (viewWindowRoot != null && viewWindowRoot.getActivity() == paramActivity) viewWindowRoot.dispatchOnActivityPause(); } } } public static void dispatchActivityResult(Activity paramActivity, int paramInt1, int paramInt2, Intent paramIntent) { for (WeakReference<ViewWindowRoot> weakReference : viewWindowContainerMap) { if (weakReference != null) { ViewWindowRoot viewWindowRoot = weakReference.get(); if (viewWindowRoot != null && viewWindowRoot.getActivity() == paramActivity) viewWindowRoot.dispatchActivityResult(paramInt1, paramInt2, paramIntent); } } } public static void dispatchActivityResume(Activity paramActivity) { for (WeakReference<ViewWindowRoot> weakReference : viewWindowContainerMap) { if (weakReference != null) { ViewWindowRoot viewWindowRoot = weakReference.get(); if (viewWindowRoot != null && viewWindowRoot.getActivity() == paramActivity) viewWindowRoot.dispatchOnActivityResume(); } } } public static int getActivityLifecycleState(Activity paramActivity) { Integer integer = activityLifecycleStateMap.get(paramActivity); return (integer == null) ? 0 : integer.intValue(); } public static void init(Application paramApplication) { if (isInited) return; isInited = true; paramApplication.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() { public final void onActivityCreated(Activity param1Activity, Bundle param1Bundle) { ViewWindowManager.activityLifecycleStateMap.put(param1Activity, Integer.valueOf(1)); } public final void onActivityDestroyed(Activity param1Activity) { ViewWindowManager.activityLifecycleStateMap.put(param1Activity, Integer.valueOf(6)); ViewWindowManager.dispatchActivityDestroy(param1Activity); } public final void onActivityPaused(Activity param1Activity) { ViewWindowManager.activityLifecycleStateMap.put(param1Activity, Integer.valueOf(4)); ViewWindowManager.dispatchActivityPause(param1Activity); } public final void onActivityResumed(Activity param1Activity) { ViewWindowManager.activityLifecycleStateMap.put(param1Activity, Integer.valueOf(3)); ViewWindowManager.dispatchActivityResume(param1Activity); } public final void onActivitySaveInstanceState(Activity param1Activity, Bundle param1Bundle) {} public final void onActivityStarted(Activity param1Activity) { ViewWindowManager.activityLifecycleStateMap.put(param1Activity, Integer.valueOf(2)); } public final void onActivityStopped(Activity param1Activity) { ViewWindowManager.activityLifecycleStateMap.put(param1Activity, Integer.valueOf(5)); } }); } protected static void regAsViewWindowContainer(ViewWindowRoot paramViewWindowRoot) { if (isInited) { if (paramViewWindowRoot != null) { viewWindowContainerMap.add(new WeakReference<ViewWindowRoot>(paramViewWindowRoot)); return; } throw new Error("container and activity must be not null"); } throw new Error("ViewWindowManager must be inited,please use ViewWindowManager.init first"); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\bas\\ui\viewwindow\ViewWindowManager.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.tencent.mm.protocal; import com.tencent.mm.protocal.c.g; public class c$dq extends g { public c$dq() { super("launch3rdApp", "launch_3rdApp", 52, true); } }
package com.tencent.mm.plugin.card.model; import com.tencent.mm.sdk.e.e; import com.tencent.mm.sdk.e.i; public final class j extends i<i> { public static final String[] diD = new String[]{i.a(i.dhO, "CardQrCodeConfi")}; private e diF; public j(e eVar) { super(eVar, i.dhO, "CardQrCodeConfi", null); this.diF = eVar; } public final i xn(String str) { i iVar = new i(); iVar.field_card_id = str; return b(iVar, new String[0]) ? iVar : null; } }
package com.appc.report.service; import com.appc.report.model.SystemLog; /** * SystemLogService * * @version : Ver 1.0 * @author : panda * @date : 2017-9-14 */ public interface SystemLogService extends CommonService<SystemLog>{ }
package com.checkers.network.client; import java.io.IOException; /** * Created with IntelliJ IDEA. * User: forrana * Date: 13.01.14 * Time: 0:58 * To change this template use File | Settings | File Templates. */ public class GameListener implements Runnable{ NetworkClient network; protected boolean isCancel = false; ListenObjectsHandler objectsHandler = new ListenObjectsHandler(); /** * * @param net - current NetworkClient */ public GameListener(NetworkClient net){ network = net; } /** * * @return Cancel status flag. * Is work not Canceled - return false. */ public boolean isCanceled(){ return isCancel; } public void setIsCanceled(){ isCancel = !isCancel; } /** * Check isCancel flag and return step. * @return if thread work cancelled and false, if not. */ public ListenObjectsHandler getGame(){ if(isCancel) return objectsHandler; else return null; } @Override public void run() { do{ try { objectsHandler = network.listenGame(); } catch (IOException e) { System.out.println("Game listener error:"+e.getMessage()); //To change body of catch statement use File | Settings | File Templates. } }while( objectsHandler == null); network.objectsHandler = objectsHandler; try{ if(objectsHandler.getListenObjects().getGame() != null){ NetworkClient.gameH.game = objectsHandler.getListenObjects().getGame(); } }catch(Exception e){} //NetworkClient.gameH.listenObjectsHandler isCancel = true; } }
package com.s24.redjob.queue; import com.s24.redjob.worker.Execution; import com.s24.redjob.worker.Worker; import org.springframework.util.Assert; import javax.annotation.PostConstruct; /** * Default implementation of {@link Worker} for queues based on a Redis list. */ public class FifoWorker extends AbstractQueueWorker { /** * Queue dao. */ private FifoDao fifoDao; /** * Init. */ @Override @PostConstruct public void afterPropertiesSet() throws Exception { Assert.notNull(fifoDao, "Precondition violated: fifoDao != null."); super.afterPropertiesSet(); } @Override protected Execution get(long id) throws Throwable { return fifoDao.get(id); } @Override protected Execution doPollQueue(String queue) throws Throwable { return fifoDao.pop(queue, name); } @Override protected void removeInflight(String queue) throws Throwable { fifoDao.removeInflight(queue, name); } @Override protected void restoreInflight(String queue) throws Throwable { fifoDao.restoreInflight(queue, name); } @Override public void update(Execution execution) { fifoDao.update(execution); } // // Injections. // /** * Queue dao. */ public FifoDao getFifoDao() { return fifoDao; } /** * Queue dao. */ public void setFifoDao(FifoDao fifoDao) { this.fifoDao = fifoDao; } }
package Controleur; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import IHM.CreerMatch; import IHM.MainWindows; import IHM.addJoueur; public class ControleurOuvrir implements ActionListener { private MainWindows frame; private int fenetre; public ControleurOuvrir(MainWindows frame, int fenetre){ this.frame = frame; this.fenetre = fenetre; } public void actionPerformed(ActionEvent e) { if(this.fenetre == 0) {new CreerMatch(this.frame);} if(this.fenetre == 1) {new addJoueur(this.frame);} } }
package com.example.demo.service; import com.example.demo.dao.MemberRepository; import com.example.demo.member.Member; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; import java.util.Objects; import java.util.Optional; @Service public class ServiceLayer { private final MemberRepository memberRepository; @Autowired public ServiceLayer(MemberRepository memberRepository){ this.memberRepository = memberRepository; } public List<Member> getMembers(){ return memberRepository.findAll(); } public void addNewMember(Member member) { Optional<Member> memberOptional = memberRepository.findMemberByEmail(member.getEmail()); if(memberOptional.isPresent()){ throw new IllegalStateException("email taken"); } memberRepository.save(member); } public void deleteMember(Long memberId) { boolean exists = memberRepository.existsById(memberId); if(!exists){ throw new IllegalStateException("member with id " + memberId + "does not exist"); } memberRepository.deleteById(memberId); } @Transactional public void updateMember(Long memberId, String name, String email) { //simple business logoic to check if member exists Member member = memberRepository.findById(memberId).orElseThrow(() -> new IllegalStateException("member with id" + memberId + "does not exist")); if(name != null && name.length() > 0 && !Objects.equals(member.getName(), name)){ member.setName(name); } if(email != null && email.length() > 0 && !Objects.equals(member.getEmail(), email)){ Optional<Member> memberOptional = memberRepository.findMemberByEmail(email); if(memberOptional.isPresent()){ throw new IllegalStateException("Email already in use"); } member.setEmail(email); } } }
package com.tt.miniapp.shortcut.handler; import android.app.Activity; import android.content.Context; import android.os.SystemClock; import android.support.v4.content.c; import com.a; import com.storage.async.Action; import com.storage.async.Schedulers; import com.tt.miniapp.AppbrandApplicationImpl; import com.tt.miniapp.AppbrandConstant; import com.tt.miniapp.net.NetBus; import com.tt.miniapp.shortcut.ShortcutEventReporter; import com.tt.miniapp.shortcut.ShortcutPermissionUtil; import com.tt.miniapp.shortcut.ShortcutResult; import com.tt.miniapp.shortcut.ShortcutService; import com.tt.miniapp.shortcut.dialog.DialogConfig; import com.tt.miniapp.shortcut.dialog.MultiSpanView; import com.tt.miniapp.shortcut.dialog.ShortcutDialogHandler; import com.tt.miniapp.shortcut.dialog.SingleSpanView; import com.tt.miniapp.shortcut.dialog.TextSpan; import com.tt.miniapp.thread.ThreadUtil; import com.tt.miniapphost.AppBrandLogger; import com.tt.miniapphost.AppbrandContext; import com.tt.miniapphost.host.HostDependManager; import com.tt.miniapphost.language.LanguageChangeListener; import com.tt.miniapphost.language.LocaleManager; import com.tt.miniapphost.util.AppbrandUtil; import java.io.IOException; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeUnit; import okhttp3.ac; import okhttp3.ae; public class DialogHandler extends AbsHandler { public static ShortcutUrlManager sShortCutGuideManager; DialogHandler(ShortcutRequest paramShortcutRequest) { super(paramShortcutRequest); if (sShortCutGuideManager == null) sShortCutGuideManager = new ShortcutUrlManager(); } public void goSetting(Context paramContext) { ShortcutPermissionUtil.goSettingPage(paramContext); } protected ShortcutResult handleRequest() { AppbrandContext.mainHandler.postDelayed(new Runnable() { public void run() { if (((ShortcutService)AppbrandApplicationImpl.getInst().getService(ShortcutService.class)).isShowDialog()) { DialogHandler dialogHandler = DialogHandler.this; dialogHandler.showShortcutDialog(dialogHandler.mAct); } } }, 150L); return null; } public void showShortcutDialog(final Activity activity) { SingleSpanView singleSpanView = new SingleSpanView(DialogConfig.createDefaultTitle((Context)activity, activity.getString(2097742042))); List<TextSpan> list = DialogConfig.createDefaultContent((Context)activity, new String[] { activity.getString(2097742029, new Object[] { AppbrandContext.getInst().getInitParams().getHostStr(101, AppbrandUtil.getApplicationName((Context)AppbrandContext.getInst().getApplicationContext())) }), activity.getString(2097742030) }); list.add((new TextSpan.Builder()).setText(activity.getString(2097742028)).setTextColor(c.c((Context)activity, 2097348656)).setTextSize(activity.getResources().getDimension(2097414179)).setClickCallback(new DialogConfig.TextClickListener() { public void onTextClick(String param1String) { ShortcutEventReporter.reportDialogOption("learn_more"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(DialogHandler.sShortCutGuideManager.getCurrentValidUrl()); stringBuilder.append("?phoneBrand="); stringBuilder.append(ShortcutPermissionUtil.getPhoneBrand()); stringBuilder.append("&aid="); stringBuilder.append(AppbrandContext.getInst().getInitParams().getAppId()); String str = stringBuilder.toString(); HostDependManager hostDependManager = HostDependManager.getInst(); Activity activity = activity; hostDependManager.jumpToWebView((Context)activity, str, activity.getString(2097742031), false); ShortcutEventReporter.reportLearnMore(); } }).build()); ShortcutDialogHandler.showDialogByConfig(new DialogConfig(singleSpanView, new MultiSpanView(list, true, 8388611), (Context)activity, new SingleSpanView((new TextSpan.Builder()).setText(activity.getString(2097742024)).setTextColor(c.c((Context)activity, 2097348612)).setTextSize(activity.getResources().getDimension(2097414179)).build()), new SingleSpanView((new TextSpan.Builder()).setText(activity.getString(2097741933)).setTextSize(activity.getResources().getDimension(2097414179)).setTextColor(c.c((Context)activity, 2097348612)).build())), new ShortcutDialogHandler.CallBackListener() { public void cancel() { ShortcutEventReporter.reportDialogOption("back"); } public void confirm() { ShortcutEventReporter.reportDialogOption("go_configuration"); DialogHandler.this.goSetting((Context)activity); ((ShortcutService)AppbrandApplicationImpl.getInst().getService(ShortcutService.class)).setOpenSettingPage(true); } public void mobEvent() { ShortcutEventReporter.reportDialogShow(); } }); } static class ShortcutUrlManager implements LanguageChangeListener { public long latestReqeustTime; public volatile Locale mCurrrentValidLocale = Locale.ENGLISH; public ShortcutUrlManager() { if (HostDependManager.getInst().isEnableI18nNetRequest()) { LocaleManager.getInst().registerLangChangeListener(this); getLatestI18NLocaleAndVerify(); } } private void getLatestI18NLocaleAndVerify() { Locale locale = LocaleManager.getInst().getCurrentHostSetLocale(); if (locale == null) return; AppbrandConstant.OpenApi.getInst(); testUrl(a.a("https://s.ipstatp.com/fe_toutiao/helo_instruction_page/%1$s/", new Object[] { locale.getLanguage() }), locale); } private void testUrl(final String url, final Locale locale) { this.latestReqeustTime = SystemClock.elapsedRealtime(); ThreadUtil.runOnWorkThread(new Action() { public void act() { try { ac ac = (new ac.a()).b().a(url).c(); ae ae = NetBus.okHttpClient.c().a(5000L, TimeUnit.MILLISECONDS).c(5000L, TimeUnit.MILLISECONDS).b(5000L, TimeUnit.MILLISECONDS).a().a(ac).b(); if (ae == null) return; if (ae.c != 200) return; if (requestTimestamp < DialogHandler.ShortcutUrlManager.this.latestReqeustTime) return; DialogHandler.ShortcutUrlManager.this.mCurrrentValidLocale = locale; return; } catch (IOException iOException) { AppBrandLogger.e("ShortcutUrlManager", new Object[] { iOException }); return; } } }Schedulers.shortIO()); } public String getCurrentValidUrl() { if (!HostDependManager.getInst().isEnableI18nNetRequest()) { AppbrandConstant.OpenApi.getInst(); return "https://tmaportal.snssdk.com/jssdk/h5/add_to_desktop_learn_more/"; } AppbrandConstant.OpenApi.getInst(); return a.a("https://s.ipstatp.com/fe_toutiao/helo_instruction_page/%1$s/", new Object[] { this.mCurrrentValidLocale.getLanguage() }); } public void onLanguageChange() { getLatestI18NLocaleAndVerify(); } } class null implements Action { public void act() { try { ac ac = (new ac.a()).b().a(url).c(); ae ae = NetBus.okHttpClient.c().a(5000L, TimeUnit.MILLISECONDS).c(5000L, TimeUnit.MILLISECONDS).b(5000L, TimeUnit.MILLISECONDS).a().a(ac).b(); if (ae == null) return; if (ae.c != 200) return; if (requestTimestamp < this.this$0.latestReqeustTime) return; this.this$0.mCurrrentValidLocale = locale; return; } catch (IOException iOException) { AppBrandLogger.e("ShortcutUrlManager", new Object[] { iOException }); return; } } } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\shortcut\handler\DialogHandler.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.mxfit.mentix.menu3.TrainingsPackage; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import com.mxfit.mentix.menu3.GlobalValues; import com.mxfit.mentix.menu3.Utils.DatabasePremadesHelper; import com.mxfit.mentix.menu3.Utils.GetColors; import com.mxfit.mentix.menu3.MainActivity; import com.mxfit.mentix.menu3.Utils.PR; import com.mxfit.mentix.menu3.RunningPackage.PreRunChoiceActivity; import com.mxfit.mentix.menu3.PushupsPackage.TrainingUnitChoiceActivity; import com.mxfit.mentix.menu3.R; import java.util.ArrayList; import static android.app.Activity.RESULT_OK; import static com.mxfit.mentix.menu3.GlobalValues.*; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link TrainingFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link TrainingFragment#newInstance} factory method to * create an instance of this fragment. */ public class TrainingFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private static final String ARG_PARAM3 = "param3"; // TODO: Rename and change types of parameters private int mParam1; private int mParam2; private double mParam3; private TextView txtPushupDate; private TextView day; private TextView maxDay; private TextView tlevel; private LinearLayout txtPushupSets; private TextView txtSitupDate; private TextView SUday; private TextView SUmaxDay; private TextView SUtlevel; private LinearLayout txtSitupSets; private TextView txtRunningDate; private Switch SynchroSwitch; private Button buttonPushups; private Button buttonRunning; private Button buttonBoth; private TextView tvBoth1; private TextView tvBoth2; public TextView RunningDay; public TextView goal; DatabasePremadesHelper myDb; ArrayList <Integer> array; TextView [] textView; TextView [] textView2; final MainActivity activity = MainActivity.instance; private OnFragmentInteractionListener mListener; public TrainingFragment() { // Required empty public constructor } public static TrainingFragment newInstance(int param1, int param2, double param3) { TrainingFragment fragment = new TrainingFragment(); Bundle args = new Bundle(); args.putInt(ARG_PARAM1, param1); args.putInt(ARG_PARAM2, param2); args.putDouble(ARG_PARAM3, param3); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getInt(ARG_PARAM1); mParam2 = getArguments().getInt(ARG_PARAM2); mParam3 = getArguments().getDouble(ARG_PARAM3); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_training, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); myDb = new DatabasePremadesHelper(getContext()); txtPushupDate = (TextView) view.findViewById(R.id.TrainDate); day = (TextView) view.findViewById(R.id.currentDay); maxDay = (TextView) view.findViewById(R.id.txtShowMaxDays); tlevel = (TextView) view.findViewById(R.id.currentTrainingLevel); txtPushupSets = (LinearLayout)view.findViewById(R.id.fragcycle); txtSitupDate = (TextView) view.findViewById(R.id.SUTrainDate); SUday = (TextView) view.findViewById(R.id.SUcurrentDay); SUmaxDay = (TextView) view.findViewById(R.id.txtSUShowMaxDays); SUtlevel = (TextView) view.findViewById(R.id.SUcurrentTrainingLevel); txtSitupSets = (LinearLayout)view.findViewById(R.id.SUfragcycle); txtRunningDate = (TextView) view.findViewById(R.id.TrainRDate); SynchroSwitch = (Switch) view.findViewById(R.id.switch1); buttonRunning = (Button) view.findViewById(R.id.buttonRT); buttonPushups = (Button) view.findViewById(R.id.buttonPT); buttonBoth = (Button) view.findViewById(R.id.buttonBothT); goal = (TextView) view.findViewById(R.id.currentKilos); RunningDay = (TextView) view.findViewById(R.id.currentRDay); Button buttongotoPushups = (Button) view.findViewById(R.id.gotoPU); Button buttongotoSitups = (Button) view.findViewById(R.id.gotoSU); Button buttongotoRunning = (Button) view.findViewById(R.id.gotoR); tvBoth1 = (TextView) view.findViewById(R.id.viewBoth1); tvBoth2 = (TextView) view.findViewById(R.id.viewBoth2); SynchroSwitch.setChecked(Synchronised); SynchroSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Synchronised = isChecked; setSyncButtonVisibility(); } }); buttonPushups.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent Pushupschoice = new Intent(getActivity(), TrainingUnitChoiceActivity.class); Bundle bundle = new Bundle(); bundle.putString("type", "Level%"); bundle.putString("trainingType", "pushups"); Pushupschoice.putExtras(bundle); startActivityForResult(Pushupschoice, 1); } }); buttonRunning.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent Runningchoice = new Intent(getActivity(), PreRunChoiceActivity.class); startActivityForResult(Runningchoice, 2); } }); buttonBoth.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent Daychoice = new Intent(getActivity(), DayChoiceActivity.class); startActivityForResult(Daychoice, 3); } }); buttongotoPushups.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { activity.showPushups(); activity.navigationView.getMenu().getItem(2).setChecked(true); } }); buttongotoRunning.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { activity.showRunning(); activity.navigationView.getMenu().getItem(1).setChecked(true); } }); buttongotoSitups.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { activity.showSitups(); activity.navigationView.getMenu().getItem(3).setChecked(true); } }); createView(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if(resultCode == RESULT_OK) { mParam1 = GlobalValues.pushupsDay; mParam2 = pushupsTraininglevel; } } GlobalValues.saveTrainingData(); createView(); } public void createView(){ SUday.setText(""+GlobalValues.situpsDay); SUtlevel.setText(""+ GlobalValues.situpsTraininglevel); day.setText(""+GlobalValues.pushupsDay); tlevel.setText(""+ pushupsTraininglevel); if(lastSitupDate != null) { txtSitupDate.setText(lastSitupDate); } if(lastPushupDate != null) { txtPushupDate.setText(lastPushupDate); } if(lastRunDate != null) { txtRunningDate.setText(lastRunDate); } int textColor = GetColors.getFont(getContext(),activity.themeNumber); txtPushupSets.removeAllViews(); array = new PR().redo(myDb.getDayPushups(GlobalValues.pushupsDay, pushupsTraininglevel).replace('x','-')); textView = new TextView[array.size()]; for( int h = 0; h < array.size(); h++ ) { textView[h] = new TextView(getContext()); if (h != array.size()-1) textView[h].setText(""+array.get(h) + " - "); else textView[h].setText(""+array.get(h)); textView[h].setTypeface(null, Typeface.BOLD); textView[h].setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); textView[h].setGravity(Gravity.END); textView[h].setTextColor(textColor); txtPushupSets.addView(textView[h]); } array = new PR().redo(myDb.getDaySitups(GlobalValues.situpsDay, situpsTraininglevel).replace('x','-')); textView2 = new TextView[array.size()]; for( int h = 0; h < array.size(); h++ ) { textView2[h] = new TextView(getContext()); if (h != array.size()-1) textView2[h].setText(""+array.get(h) + " - "); else textView2[h].setText(""+array.get(h)); textView2[h].setTypeface(null, Typeface.BOLD); textView2[h].setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); textView2[h].setGravity(Gravity.END); textView2[h].setTextColor(textColor); txtSitupSets.addView(textView2[h]); } setSyncButtonVisibility(); maxDay.setText("/"+myDb.getHowManyPushupDays(pushupsTraininglevel)); SUmaxDay.setText("/"+myDb.getHowManyPushupDays(situpsTraininglevel)); goal.setText(""+GlobalValues.goal); RunningDay.setText(""+rday); } public void setSyncButtonVisibility(){ if(Synchronised) { buttonRunning.setVisibility(View.INVISIBLE); buttonPushups.setVisibility(View.INVISIBLE); buttonBoth.setVisibility(View.VISIBLE); tvBoth1.setVisibility(View.VISIBLE); tvBoth2.setVisibility(View.VISIBLE); } else { buttonRunning.setVisibility(View.VISIBLE); buttonPushups.setVisibility(View.VISIBLE); buttonBoth.setVisibility(View.INVISIBLE); tvBoth1.setVisibility(View.INVISIBLE); tvBoth2.setVisibility(View.INVISIBLE); } } public void onButtonPressed(int day, int TLevel, float goal) { if (mListener != null) { mListener.onFragmentInteraction(day, TLevel, goal); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(int day, int TLevel, float goal); } @Override public void onStop() { super.onStop(); } }
package com.hason.dtp.account.point.controller; import com.hason.dtp.account.point.api.PointApi; import com.hason.dtp.account.point.service.PointService; import com.hason.dtp.core.support.MediaTypes; import com.hason.dtp.core.utils.result.Result; import com.hason.dtp.core.utils.result.ResultBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; /** * 积分 Controller * * @author Huanghs * @since 2.0 * @date 2017/11/15 */ @RestController public class PointController implements PointApi { @Autowired private PointService pointService; @PostMapping(value = "/users/{userId}/points", consumes = MediaTypes.JSON) @Override public Result<?> addRegistPoint(@PathVariable Long userId) { pointService.addRegistPoint(userId, 10); return ResultBuilder.newInstance(); } }
/** * Frames e painéis referentes à base visual * do sistema. */ package tolteco.sigma.view;
package org.intellij.erlang.intention; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.util.IncorrectOperationException; import org.intellij.erlang.psi.ErlangFile; import org.intellij.erlang.psi.ErlangFunction; import org.intellij.erlang.psi.impl.ErlangPsiImplUtil; import org.intellij.erlang.quickfixes.ErlangGenerateSpecFix; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ErlangGenerateSpecIntention extends ErlangBaseNamedElementIntention { public ErlangGenerateSpecIntention() { super(ErlangGenerateSpecFix.NAME, ErlangGenerateSpecFix.NAME); } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { if (!(file instanceof ErlangFile)) return false; ErlangFunction function = findFunction(file, editor.getCaretModel().getOffset()); if (function == null) return false; return ErlangPsiImplUtil.getSpecification(function) == null; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { if (!(file instanceof ErlangFile)) { throw new IncorrectOperationException("Only applicable to Erlang files."); } ErlangFunction function = findFunction(file, editor.getCaretModel().getOffset()); if (function == null) { throw new IncorrectOperationException("Cursor should be placed on Erlang function."); } if (ErlangPsiImplUtil.getSpecification(function) != null) { throw new IncorrectOperationException("Specification for this function already exists."); } ErlangGenerateSpecFix.generateSpec(editor, function); } @Nullable private static ErlangFunction findFunction(PsiFile file, int offset) { return findElement(file, offset, ErlangFunction.class); } }
package ga.islandcrawl.building; import ga.islandcrawl.form.Animation.Smoke; import ga.islandcrawl.form.BuildingSite; import ga.islandcrawl.map.O; import ga.islandcrawl.object.Interactive; import ga.islandcrawl.object.Tag; import ga.islandcrawl.state.Animation; /** * Created by Ga on 7/10/2015. */ public class Building extends Constructor implements Interactive { public Building(String seed) { super(seed,new BuildingSite()); setDepth(9, 15); state.setStat("health", 10); menuSelected(seed); tag.add(Tag.Combustible); } public void hit(float dmg, O from){ super.hit(dmg, from); if (state.getRawStat("health").getPercentage() < .5f) state.addEffect("Smoke", new Animation(new Smoke(), -1)); } @Override protected void clear(){ super.clear(); die(); } }
package Files; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; public class Syntax { public static void main(String[] args) throws Exception { Properties obj = new Properties(); FileInputStream fin = new FileInputStream("C:\\Users\\QAP18\\git\\mahesh\\Mahesh\\src\\Files\\paziz.properties"); FileOutputStream fout = new FileOutputStream("E:\\Softwares\\mxl.xlsx"); obj.load(fin); String strURl = obj.getProperty("URL"); String strUN = obj.getProperty("UserName"); String strPWD = obj.getProperty("Password"); System.out.println(strURl+ " "+strUN+ " "+strPWD); System.setProperty("webdriver.chrome.driver", "E:\\Selenium Softwares\\chromedriver.exe"); ChromeDriver cd = new ChromeDriver(); cd.get(strURl); cd.findElement(By.name("txtUserName")).sendKeys(strUN); cd.findElement(By.name("txtPassword")).sendKeys(strPWD); cd.findElement(By.name("Submit")).click(); cd.findElement(By.linkText("Logout")).click(); cd.close(); cd.quit(); } }
import java.io.FileReader; import java.io.FileWriter; import java.util.Scanner; public class Version1 { public void replace() throws Exception { FileReader fileR = new FileReader("./src/logdet15-08-12.log"); FileWriter fileW = new FileWriter("./src/logdet15-08-12 - измененный1.log"); Scanner scan = new Scanner(fileR); try { System.out.println("Начало записи версия - 1..."); while (scan.hasNextLine()) { String str = scan.nextLine(); fileW.write(str.replaceAll("0", "null") + "\n"); } System.out.println("Изменненый файл записан!"); } catch (Exception e) { System.out.println(e.getMessage()); } finally { try { scan.close(); fileR.close(); fileW.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } } }
package zoo; public class Mammal extends Animal { public Mammal(String name){ super.name = name; super.isPredator = true; super.age = 2; } @Override public String breed() { return "livebearer"; } }
package ua.project.protester.repository; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import ua.project.protester.model.Role; import ua.project.protester.utils.RoleRowMapper; import java.util.*; @PropertySource("classpath:queries/role.properties") @Repository @RequiredArgsConstructor public class RoleRepository implements CrudRepository<Role> { private final NamedParameterJdbcTemplate namedJdbcTemplate; private final Environment environment; private final RoleRowMapper roleRowMapper; @Override public int save(Role entity) { return 0; } @Override public Optional<Role> findById(Long id) { try { Map<String, Object> namedParams = new HashMap<>(); namedParams.put("role_id", id); return Optional.ofNullable(namedJdbcTemplate.queryForObject(environment.getProperty("findRoleById"), namedParams, roleRowMapper)); } catch (EmptyResultDataAccessException e) { return Optional.empty(); } } @Override public List<Role> findAll() { return namedJdbcTemplate.query(Objects.requireNonNull(environment.getProperty("findAllRoles")), roleRowMapper); } @Override public void update(Role entity) { } @Override public void delete(Role entity) { } public Optional<Role> findRoleByName(String name) { try { Map<String, Object> namedParams = new HashMap<>(); namedParams.put("role_name", name); return Optional.ofNullable(namedJdbcTemplate.queryForObject(Objects.requireNonNull(environment.getProperty("findRoleByName")), namedParams, roleRowMapper)); } catch (EmptyResultDataAccessException e) { return Optional.empty(); } } }
package com.kush.lib.expressions.clauses; import java.util.Collection; import com.kush.lib.expressions.Expression; public interface InExpression extends Expression { Expression getTarget(); Collection<Expression> getInExpressions(); }
package com.javakg.stroistat.service.impl; public class RegisteringServiceImpl { }
package com.meep.challenge.dto; import java.math.BigDecimal; public class VehicleDTO { private String id; private String name; private Double x; private Double y; private String licencePlate; private Integer range; private Double batteryLevel; private Integer seats; private String model; private String resourceImageId; private BigDecimal pricePerMinuteParking; private BigDecimal pricePerMinuteDriving; private Boolean realTimeData; private String engineType; private String resourceType; private Integer companyZoneId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getX() { return x; } public void setX(Double x) { this.x = x; } public Double getY() { return y; } public void setY(Double y) { this.y = y; } public String getLicencePlate() { return licencePlate; } public void setLicencePlate(String licencePlate) { this.licencePlate = licencePlate; } public Integer getRange() { return range; } public void setRange(Integer range) { this.range = range; } public Double getBatteryLevel() { return batteryLevel; } public void setBatteryLevel(Double batteryLevel) { this.batteryLevel = batteryLevel; } public Integer getSeats() { return seats; } public void setSeats(Integer seats) { this.seats = seats; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getResourceImageId() { return resourceImageId; } public void setResourceImageId(String resourceImageId) { this.resourceImageId = resourceImageId; } public BigDecimal getPricePerMinuteParking() { return pricePerMinuteParking; } public void setPricePerMinuteParking(BigDecimal pricePerMinuteParking) { this.pricePerMinuteParking = pricePerMinuteParking; } public BigDecimal getPricePerMinuteDriving() { return pricePerMinuteDriving; } public void setPricePerMinuteDriving(BigDecimal pricePerMinuteDriving) { this.pricePerMinuteDriving = pricePerMinuteDriving; } public Boolean getRealTimeData() { return realTimeData; } public void setRealTimeData(Boolean realTimeData) { this.realTimeData = realTimeData; } public String getEngineType() { return engineType; } public void setEngineType(String engineType) { this.engineType = engineType; } public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } public Integer getCompanyZoneId() { return companyZoneId; } public void setCompanyZoneId(Integer companyZoneId) { this.companyZoneId = companyZoneId; } }
package com.jiuzhe.app.hotel.service; import java.util.List; public interface RedisService { public String getResult(String redisKey, String sql); }
package com.tencent.mm.ui.conversation; import android.content.Context; import android.content.res.ColorStateList; import android.database.Cursor; import android.database.MergeCursor; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.format.Time; import android.text.style.ForegroundColorSpan; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.g.a.rn; import com.tencent.mm.model.au; import com.tencent.mm.model.s; import com.tencent.mm.modelvoice.n; import com.tencent.mm.pluginsdk.f.h; import com.tencent.mm.pluginsdk.ui.d.j; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.e.l; import com.tencent.mm.sdk.e.m; import com.tencent.mm.sdk.e.m.b; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.al; import com.tencent.mm.sdk.platformtools.w; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.storage.ai; import com.tencent.mm.storage.bl; import com.tencent.mm.ui.base.MMSlideDelView; import com.tencent.mm.ui.base.MMSlideDelView$c; import com.tencent.mm.ui.base.MMSlideDelView.f; import com.tencent.mm.ui.base.MMSlideDelView.g; import com.tencent.mm.ui.base.NoMeasuredTextView; import com.tencent.mm.ui.r; import com.tencent.mm.ui.r.a; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; public class d extends r<ai> implements b { private static long uoj = 2000; private String eIQ; private boolean eMT = false; protected List<String> gRN = null; protected g hkN; protected MMSlideDelView$c hkO; protected f hkP; protected com.tencent.mm.ui.base.MMSlideDelView.d hkQ = MMSlideDelView.getItemStatusCallBack(); boolean nNk = false; private float tEh = -1.0f; protected float tEi = -1.0f; private float tEj = -1.0f; private ColorStateList[] tEk = new ColorStateList[5]; HashMap<String, d> tEl; private boolean unU = true; private f unV; private com.tencent.mm.pluginsdk.ui.d unW; private boolean unX = false; private boolean unY = false; private boolean unZ = false; private boolean uoa = false; private c uob; private c uoc = null; private b uod = null; public String uoe = ""; final e uof = new e(this); private final int uog; private final int uoh; private a uoi; private boolean uok = false; private al uol = new al(au.Em().lnJ.getLooper(), new 1(this), false); public d(Context context, a aVar) { super(context, new ai()); this.tlG = aVar; this.tEk[0] = com.tencent.mm.bp.a.ac(context, R.e.hint_text_color); this.tEk[1] = com.tencent.mm.bp.a.ac(context, R.e.mm_list_textcolor_unread); this.tEk[3] = com.tencent.mm.bp.a.ac(context, R.e.normal_text_color); this.tEk[2] = com.tencent.mm.bp.a.ac(context, R.e.mm_list_textcolor_three); this.tEk[2] = com.tencent.mm.bp.a.ac(context, R.e.mm_list_textcolor_three); this.tEk[4] = com.tencent.mm.bp.a.ac(context, R.e.light_text_color); this.tEl = new HashMap(); if (com.tencent.mm.bp.a.fi(context)) { this.uoh = context.getResources().getDimensionPixelSize(R.f.ConversationTimeBiggerWidth); this.uog = context.getResources().getDimensionPixelSize(R.f.ConversationTimeSmallWidth); } else { this.uoh = context.getResources().getDimensionPixelSize(R.f.ConversationTimeBigWidth); this.uog = context.getResources().getDimensionPixelSize(R.f.ConversationTimeSmallerWidth); } this.tEh = (float) com.tencent.mm.bp.a.ad(context, R.f.NormalTextSize); this.tEi = (float) com.tencent.mm.bp.a.ad(context, R.f.HintTextSize); this.tEj = (float) com.tencent.mm.bp.a.ad(context, R.f.SmallestTextSize); } public final void setPerformItemClickListener(g gVar) { this.hkN = gVar; } public final void a(f fVar) { this.hkP = fVar; } public final void setGetViewPositionCallback(MMSlideDelView$c mMSlideDelView$c) { this.hkO = mMSlideDelView$c; } public void detach() { } private CharSequence h(ai aiVar) { if (aiVar.field_status == 1) { return this.context.getString(R.l.main_sending); } return aiVar.field_conversationTime == Long.MAX_VALUE ? "" : h.c(this.context, aiVar.field_conversationTime, true); } protected final void WS() { WT(); } public final void onPause() { if (this.hkQ != null) { this.hkQ.aYl(); } this.unX = false; } private void cyH() { if (this.tEl != null) { for (Entry value : this.tEl.entrySet()) { ((d) value.getValue()).uop = null; } } } public final void onResume() { boolean z = true; x.i("MicroMsg.ConversationAdapter", "dkpno onResume mIsFront:%b mNeedReCreate:%b mChangedBackground:%b mContactBackground:%b", new Object[]{Boolean.valueOf(this.unX), Boolean.valueOf(this.unZ), Boolean.valueOf(this.unY), Boolean.valueOf(this.uoa)}); this.unX = true; Time time = new Time(); time.setToNow(); String charSequence = com.tencent.mm.pluginsdk.f.g.a("MM/dd", time).toString(); if (this.uoe.equals(charSequence)) { z = false; } this.uoe = charSequence; if (z) { cyH(); } if (this.unZ && this.uod != null) { this.unZ = false; } if (this.unY || this.uoa) { super.a(null, null); this.unY = false; this.uoa = false; } } public final void onDestroy() { this.uol.SO(); this.uod = null; this.uob = null; if (this.tEl != null) { this.tEl.clear(); this.tEl = null; } aYc(); this.tlG = null; detach(); } public void WT() { x.i("MicroMsg.ConversationAdapter", "dkpno resetCursor search:%b", new Object[]{Boolean.valueOf(this.eMT)}); if (this.eMT) { Cursor[] cursorArr = new Cursor[2]; cursorArr[0] = au.HU().dAb.a(s.dAN, this.gRN, this.eIQ); List arrayList = new ArrayList(); List arrayList2 = new ArrayList(); if (this.gRN != null && this.gRN.size() > 0) { arrayList.addAll(this.gRN); } while (cursorArr[0].moveToNext()) { try { String string = cursorArr[0].getString(cursorArr[0].getColumnIndex("username")); arrayList.add(string); if (!string.endsWith("@chatroom")) { arrayList2.add(string); } x.d("MicroMsg.ConversationAdapter", "block user " + string); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.ConversationAdapter", e, "", new Object[0]); } } arrayList.add("officialaccounts"); arrayList.add("helper_entry"); cursorArr[1] = au.HU().dAc.b(this.eIQ, "@micromsg.with.all.biz.qq.com", arrayList, arrayList2); setCursor(new MergeCursor(cursorArr)); } else { au.HU(); setCursor(com.tencent.mm.model.c.FW().a(s.dAN, this.gRN, com.tencent.mm.m.a.dhR, false)); } if (!(this.unV == null || this.eIQ == null)) { getCursor().getCount(); } super.notifyDataSetChanged(); } public View getView(int i, View view, ViewGroup viewGroup) { View inflate; g gVar; int i2; d dVar; ai aiVar = (ai) getItem(i); String str = aiVar.field_username; e eVar = this.uof; eVar.talker = str; eVar.guS = null; eVar.uoB = null; eVar.initialized = false; if (!com.tencent.mm.platformtools.ai.oW(str)) { eVar.initialized = true; } this.uoi = new a(this, (byte) 0); if (view == null) { g gVar2 = new g(); if (com.tencent.mm.bp.a.fi(this.context)) { inflate = View.inflate(this.context, R.i.conversation_item_large, null); } else { inflate = View.inflate(this.context, R.i.conversation_item, null); } gVar2.eCl = (ImageView) inflate.findViewById(R.h.avatar_iv); com.tencent.mm.pluginsdk.ui.a.b.a(gVar2.eCl, str); com.tencent.mm.pluginsdk.ui.a aVar = (com.tencent.mm.pluginsdk.ui.a) gVar2.eCl.getDrawable(); if (this.unW != null) { this.unW.a(aVar); } gVar2.tEp = (NoMeasuredTextView) inflate.findViewById(R.h.nickname_tv); gVar2.uoC = (NoMeasuredTextView) inflate.findViewById(R.h.source_tv); gVar2.tEq = (NoMeasuredTextView) inflate.findViewById(R.h.update_time_tv); gVar2.tEr = (NoMeasuredTextView) inflate.findViewById(R.h.last_msg_tv); gVar2.hkV = (TextView) inflate.findViewById(R.h.tipcnt_tv); gVar2.hkV.setBackgroundResource(com.tencent.mm.ui.tools.r.hd(this.context)); gVar2.tEs = (ImageView) inflate.findViewById(R.h.image_mute); gVar2.tEu = inflate.findViewById(R.h.avatar_prospect_iv); gVar2.tEt = (ImageView) inflate.findViewById(R.h.talkroom_iv); gVar2.uoD = (ImageView) inflate.findViewById(R.h.location_share_iv); inflate.setTag(gVar2); gVar2.tEr.setTextSize(0, this.tEi); gVar2.tEq.setTextSize(0, this.tEj); gVar2.tEp.setTextSize(0, this.tEh); gVar2.uoC.setTextSize(0, this.tEi); gVar2.tEr.setTextColor(this.tEk[0]); gVar2.tEq.setTextColor(this.tEk[4]); gVar2.tEp.setTextColor(this.tEk[3]); gVar2.uoC.setTextColor(this.tEk[0]); gVar2.tEr.setShouldEllipsize(true); gVar2.tEq.setShouldEllipsize(false); gVar2.tEp.setShouldEllipsize(true); gVar2.uoC.setShouldEllipsize(true); gVar2.tEq.setGravity(5); gVar = gVar2; } else { gVar = (g) view.getTag(); inflate = view; } d dVar2 = (d) this.tEl.get(str); if (dVar2 == null) { String str2; d dVar3 = new d(this, (byte) 0); eVar = this.uof; if (eVar.initialized && eVar.guS == null) { au.HU(); eVar.guS = com.tencent.mm.model.c.FR().Yg(eVar.talker); } ab abVar = eVar.guS; if (abVar != null) { dVar3.uot = abVar.csS; dVar3.uos = (int) abVar.dhP; } else { dVar3.uot = -1; dVar3.uos = -1; } dVar3.uox = abVar != null; boolean z = abVar != null && abVar.BE(); dVar3.uoz = z; z = abVar != null && abVar.csI == 0; dVar3.uoy = z; dVar3.qpi = s.fq(str); z = dVar3.qpi && dVar3.uoy && aiVar.field_unReadCount > 0; dVar3.uow = z; dVar3.hER = 0; if (wW(aiVar.field_msgType) == 34 && aiVar.field_isSend == 0 && !com.tencent.mm.platformtools.ai.oW(aiVar.field_content)) { str2 = aiVar.field_content; if (str.equals("qmessage") || str.equals("floatbottle")) { String[] split = str2.split(":"); if (split != null && split.length > 3) { str2 = split[1] + ":" + split[2] + ":" + split[3]; } } if (!new n(str2).enG) { dVar3.hER = 1; } } str2 = com.tencent.mm.model.r.a(abVar, str, dVar3.qpi); if (dVar3.qpi && str2 == null) { dVar3.nickName = this.context.getString(R.l.chatting_roominfo_noname); } else { dVar3.nickName = j.a(this.context, com.tencent.mm.model.r.a(abVar, str, dVar3.qpi), gVar.tEp.getTextSize()); } dVar3.uop = h(aiVar); dVar3.uoq = a(aiVar, (int) gVar.tEr.getTextSize(), dVar3.uow); dVar3.uoA = aiVar.field_attrflag; switch (aiVar.field_status) { case 0: i2 = -1; break; case 1: i2 = R.k.msg_state_sending; break; case 2: i2 = -1; break; case 5: i2 = R.k.msg_state_failed; break; default: i2 = -1; break; } dVar3.uor = i2; dVar3.uou = s.a(aiVar); au.HU(); dVar3.tEm = com.tencent.mm.model.c.FW().g(aiVar); z = abVar != null && abVar.BD(); dVar3.uov = z; dVar3.qBs = w.chL(); this.tEl.put(str, dVar3); dVar = dVar3; } else { dVar = dVar2; } if (dVar.uop == null) { dVar.uop = h(aiVar); } if (dVar.uow || s.hE(aiVar.field_parentRef)) { gVar.tEr.setTextColor(this.tEk[0]); } else { gVar.tEr.setTextColor(this.tEk[dVar.hER]); } com.tencent.mm.booter.notification.a.h.fz(gVar.tEr.getWidth()); com.tencent.mm.booter.notification.a.h.fA((int) gVar.tEr.getTextSize()); com.tencent.mm.booter.notification.a.h.a(gVar.tEr.getPaint()); if (str.toLowerCase().endsWith("@t.qq.com")) { gVar.tEp.setCompoundRightDrawablesWithIntrinsicBounds(R.g.icon_tencent_weibo); gVar.tEp.setDrawRightDrawable(true); } else { gVar.tEp.setDrawRightDrawable(false); } i2 = dVar.uor; if (i2 != -1) { gVar.tEr.setCompoundLeftDrawablesWithIntrinsicBounds(i2); gVar.tEr.setDrawLeftDrawable(true); } else { gVar.tEr.setDrawLeftDrawable(false); } gVar.tEp.setText(dVar.nickName); gVar.uoC.setVisibility(8); LayoutParams layoutParams = gVar.tEq.getLayoutParams(); if (dVar.uop.length() > 9) { if (layoutParams.width != this.uoh) { layoutParams.width = this.uoh; gVar.tEq.setLayoutParams(layoutParams); } } else if (layoutParams.width != this.uog) { layoutParams.width = this.uog; gVar.tEq.setLayoutParams(layoutParams); } x.v("MicroMsg.ConversationAdapter", "layout update time width %d", new Object[]{Integer.valueOf(layoutParams.width)}); gVar.tEq.setText(dVar.uop); gVar.tEr.setText(dVar.uoq); if (dVar.qpi && dVar.uoy) { gVar.tEs.setVisibility(0); } else if (dVar.uov) { gVar.tEs.setVisibility(0); } else { gVar.tEs.setVisibility(8); } com.tencent.mm.pluginsdk.ui.a.b.a(gVar.eCl, str); if (this.unU) { if (aiVar == null || gVar == null || dVar == null) { x.w("MicroMsg.ConversationAdapter", "handle show tip cnt, but conversation or viewholder is null"); } else { gVar.hkV.setVisibility(4); gVar.tEu.setVisibility(4); if (s.hE(aiVar.field_username)) { gVar.tEu.setVisibility(aiVar.field_unReadCount > 0 ? 0 : 4); gVar.tEp.setTextColor(this.tEk[3]); } else { NoMeasuredTextView noMeasuredTextView = gVar.tEp; ColorStateList colorStateList = (dVar.uox && dVar.uot == 1) ? this.tEk[2] : this.tEk[3]; noMeasuredTextView.setTextColor(colorStateList); if (!dVar.uox || dVar.uos == 0) { x.w("MicroMsg.ConversationAdapter", "handle show tip count, but talker is null"); } else if (s.hE(aiVar.field_parentRef)) { gVar.tEu.setVisibility(aiVar.field_unReadCount > 0 ? 0 : 4); } else if (dVar.uov && dVar.uoz) { gVar.tEu.setVisibility(aiVar.field_unReadCount > 0 ? 0 : 4); } else if (dVar.qpi && dVar.uoy) { gVar.tEu.setVisibility(aiVar.field_unReadCount > 0 ? 0 : 4); } else { i2 = aiVar.field_unReadCount; if (i2 > 99) { gVar.hkV.setText(R.l.unread_count_overt_100); gVar.hkV.setVisibility(0); } else if (i2 > 0) { gVar.hkV.setText(aiVar.field_unReadCount); gVar.hkV.setVisibility(0); } this.uoi.uon = i2; } } } } if (!dVar.uou && dVar.tEm && au.HX()) { au.HU(); com.tencent.mm.model.c.FW().f(aiVar); } if (!dVar.tEm || aiVar.field_conversationTime == -1) { inflate.findViewById(R.h.conversation_item_ll).setBackgroundResource(R.g.comm_list_item_selector); } else { inflate.findViewById(R.h.conversation_item_ll).setBackgroundResource(R.g.comm_item_highlight_selector); } com.tencent.mm.bg.d.cfH(); rn rnVar = new rn(); rnVar.ccn.ccp = true; com.tencent.mm.sdk.b.a.sFg.m(rnVar); if (!(0 == com.tencent.mm.plugin.messenger.foundation.a.a.a.a(aiVar, 7, 0) || aiVar.field_username.equals(rnVar.cco.ccr))) { aiVar.at(com.tencent.mm.plugin.messenger.foundation.a.a.a.a(aiVar, 6, aiVar.field_conversationTime)); au.HU(); com.tencent.mm.model.c.FW().a(aiVar, aiVar.field_username); } if (com.tencent.mm.ax.g.elf == null || !com.tencent.mm.ax.g.elf.nq(aiVar.field_username)) { gVar.tEt.setVisibility(8); } else { gVar.tEt.setVisibility(0); if (aiVar.field_username.equals(rnVar.cco.ccr)) { gVar.tEt.setImageResource(R.k.talk_room_mic_speaking); } else { gVar.tEt.setImageResource(R.k.talk_room_mic_idle); } } if (com.tencent.mm.ay.d.elh == null || !com.tencent.mm.ay.d.elh.nt(aiVar.field_username)) { gVar.uoD.setVisibility(8); } else { gVar.uoD.setVisibility(0); } this.uoi.content = String.valueOf(dVar.uoq); this.uoi.bgn = String.valueOf(dVar.nickName); this.uoi.uoo = String.valueOf(dVar.uop); a aVar2 = this.uoi; com.tencent.mm.ui.a.a.a.cqX().a(inflate, aVar2.bgn, aVar2.uon, aVar2.uoo, aVar2.content); a(str, gVar); a(aiVar, dVar.tEm, i, false); return inflate; } protected void a(String str, g gVar) { } protected void a(ai aiVar, boolean z, int i, boolean z2) { } private static int wW(String str) { int i = 1; if (str == null || str.length() <= 0) { return i; } try { return Integer.valueOf(str).intValue(); } catch (NumberFormatException e) { return i; } } private CharSequence a(ai aiVar, int i, boolean z) { CharSequence replace; if (com.tencent.mm.platformtools.ai.oW(aiVar.field_editingMsg) || (aiVar.field_atCount > 0 && aiVar.field_unReadCount > 0)) { CharSequence charSequence = aiVar.field_digest; if (charSequence != null && charSequence.startsWith("<img src=\"original_label.png\"/> ")) { return new SpannableString(j.c(this.context, charSequence, (float) i)); } int i2; String str; String str2 = aiVar.field_username; if (str2.equals("qqmail")) { au.HU(); if (com.tencent.mm.platformtools.ai.f((Integer) com.tencent.mm.model.c.DT().get(17, null)) == 1) { i2 = 1; } else { i2 = 0; } if (i2 == 0) { return this.context.getString(R.l.settings_plugins_disable); } } if (str2.equals("tmessage")) { au.HU(); bl Hg = com.tencent.mm.model.c.FZ().Hg("@t.qq.com"); if (Hg == null || !Hg.isEnable()) { i2 = 0; } else { i2 = 1; } if (i2 == 0) { return this.context.getString(R.l.settings_plugins_disable); } } if (aiVar.field_msgType != null && (aiVar.field_msgType.equals("47") || aiVar.field_msgType.equals("1048625"))) { str2 = aaf(aiVar.field_digest); str = ""; if (str2 != null) { return "[" + str2 + "]"; } if (aiVar.field_digest != null && aiVar.field_digest.contains(":")) { str = aiVar.field_digest.substring(0, aiVar.field_digest.indexOf(":")); str2 = aaf(aiVar.field_digest.substring(aiVar.field_digest.indexOf(":") + 1).replace(" ", "")); if (str2 != null) { str2 = "[" + str2 + "]"; return com.tencent.mm.platformtools.ai.oW(str) ? str2 : str + ": " + str2; } } str2 = this.context.getString(R.l.app_emoji); aiVar.ed(com.tencent.mm.platformtools.ai.oW(str) ? str2 : str + ": " + str2); } if (!com.tencent.mm.platformtools.ai.oW(aiVar.field_digest)) { if (com.tencent.mm.platformtools.ai.oW(aiVar.field_digestUser)) { str = aiVar.field_digest; } else { str = (aiVar.field_isSend == 0 && s.fq(aiVar.field_username)) ? com.tencent.mm.model.r.getDisplayName(aiVar.field_digestUser, aiVar.field_username) : com.tencent.mm.model.r.gT(aiVar.field_digestUser); try { str = String.format(aiVar.field_digest, new Object[]{str}); } catch (Exception e) { } } replace = str.replace(10, ' '); if (aiVar.field_atCount > 0 || aiVar.field_unReadCount <= 0) { if (!z && aiVar.field_unReadCount > 1) { replace = this.context.getString(R.l.main_conversation_chatroom_unread_digest, new Object[]{Integer.valueOf(aiVar.field_unReadCount), replace}); } else if (aiVar.field_unReadCount > 1 && s.hE(aiVar.field_parentRef)) { replace = this.context.getString(R.l.main_conversation_chatroom_unread_digest, new Object[]{Integer.valueOf(aiVar.field_unReadCount), replace}); } return j.a(this.context, replace, i); } SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(this.context.getString(R.l.main_conversation_chatroom_at_hint)); spannableStringBuilder.setSpan(new ForegroundColorSpan(-5569532), 0, spannableStringBuilder.length(), 33); spannableStringBuilder.append(" ").append(j.a(this.context, replace, i)); return spannableStringBuilder; } str = com.tencent.mm.booter.notification.a.h.a(aiVar.field_isSend, aiVar.field_username, aiVar.field_content, wW(aiVar.field_msgType), this.context); replace = str.replace(10, ' '); if (aiVar.field_atCount > 0) { } if (!z) { } replace = this.context.getString(R.l.main_conversation_chatroom_unread_digest, new Object[]{Integer.valueOf(aiVar.field_unReadCount), replace}); return j.a(this.context, replace, i); } replace = new SpannableStringBuilder(this.context.getString(R.l.main_conversation_last_editing_msg_prefix)); replace.setSpan(new ForegroundColorSpan(-5569532), 0, replace.length(), 33); replace.append(" ").append(j.a(this.context, aiVar.field_editingMsg, i)); return replace; } private static String aaf(String str) { if (str == null || str.length() != 32) { return null; } return ((com.tencent.mm.plugin.emoji.b.c) com.tencent.mm.kernel.g.n(com.tencent.mm.plugin.emoji.b.c.class)).getEmojiMgr().zf(str); } public final void a(int i, m mVar, Object obj) { if (obj == null || !(obj instanceof String)) { x.e("MicroMsg.ConversationAdapter", "onNotifyChange obj not String event:%d stg:%s obj:%s", new Object[]{Integer.valueOf(i), mVar, obj}); return; } a((String) obj, null); } public final void a(String str, l lVar) { x.i("MicroMsg.ConversationAdapter", "dkpno onNotifyChange mIsFront:%b mChangedBackground:%b event:%s", new Object[]{Boolean.valueOf(this.unX), Boolean.valueOf(this.unY), str}); if (!(com.tencent.mm.platformtools.ai.oW(str) || this.tEl == null)) { this.tEl.remove(str); } if (this.unX) { x.d("MicroMsg.ConversationAdapter", "dkpno postTryNotify needNotify:%b timerStopped:%b", new Object[]{Boolean.valueOf(this.uok), Boolean.valueOf(this.uol.ciq())}); this.uok = true; if (this.uol.ciq()) { cyI(); return; } return; } this.unY = true; } private void cyI() { ah.A(new 2(this)); } }
/* * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with SAP Hybris. */ package com.cnk.travelogix.product.common.core.interceptors; import de.hybris.platform.servicelayer.interceptor.InterceptorContext; import de.hybris.platform.servicelayer.interceptor.PrepareInterceptor; import de.hybris.platform.servicelayer.model.ModelService; import javax.annotation.Resource; import com.cnk.travelogix.product.common.core.model.AccommodationModel; import com.cnk.travelogix.product.common.core.service.AccommodationProductService; /** * AccommodationPrepareInterceptor to generated commonProductId. */ public class AccommodationProductPrepareInterceptor implements PrepareInterceptor<AccommodationModel> { private AccommodationProductService companyProductIdService; @Resource private ModelService modelService; @Override public void onPrepare(final AccommodationModel accommodationModel, final InterceptorContext ctx) { if (ctx.isNew(accommodationModel)) { companyProductIdService.generateCompanyProductId(accommodationModel); } } /** * @return the companyProductIdService */ public AccommodationProductService getCompanyProductIdService() { return companyProductIdService; } /** * @param companyProductIdService * the companyProductIdService to set */ public void setCompanyProductIdService(final AccommodationProductService companyProductIdService) { this.companyProductIdService = companyProductIdService; } }
package com.nexters; import java.util.Scanner; /** * Created by soyoon on 2016. 4. 8.. */ public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int nTestCase = scan.nextInt(); if(nTestCase <= 0) return; for(int i = 0 ; i< nTestCase ; i++) { int n = scan.nextInt(); if(n<=0) return; int[] pre = new int[n]; int[] in = new int[n]; for( int j=0 ; j<n ; j++) { pre[j] = scan.nextInt(); } for( int j=0 ; j<n ; j++) { in[j] = scan.nextInt(); } new Main().print(pre, in); } } public void print(int[] pre, int[] in) { if(pre.length == 0) return; int root = pre[0]; for(int i=0; i<in.length ; i++) { if(root == in[i]) { int[] leftChildPre = arrayCopy(pre, 1, i); int[] leftChildIn = arrayCopy(in, 0, i); int[] rightChildPre = arrayCopy(pre, i+1, in.length-i-1); int[] rightChildIn = arrayCopy(in, i+1,in.length-i-1); print(leftChildPre, leftChildIn); print(rightChildPre, rightChildIn); System.out.print(root + " "); } } } public int[] arrayCopy(int[] input, int i, int length) { int[] result = new int[length]; for(int k=0; k<length; k++, i++) { result[k] = input[i]; } return result; } }
package edu.iit.cs445.StateParking.Objects; public class NullVisitor implements Visitor{ private static NullVisitor instance = null; private NullVisitor() {} public static Visitor getinstance() { if(instance == null) instance = new NullVisitor(); return instance; } @Override public int getVid() { return -1; } @Override public String getName() { return null; } @Override public String getEmail() { return null; } @Override public boolean KeywordMatch(String keyword) { return false; } @Override public boolean isNull() { return true; } }
package edu.kit.informatik; import java.util.ArrayList; import java.util.Arrays; /** * A user crated Query. * A Query consists of a command and zero or more parameters. * All Queries must be closed using finish() after reading them. * * @author Michael Hendlich * @version 2.0 */ public class Query { //-------------------------------------------------------------// private static final String ERR_QUERY_EMPTY = "query is empty."; private static final String ERR_INVALID_COMMAND = "invalid command."; private static final String ERR_NOT_STRING = "expected letter-only string at parameter index "; private static final String ERR_NOT_INT = "expected integer at parameter index "; private static final String ERR_NO_SPACES = "only one space between command and parameters allowed (if needed)."; private static final String ERR_NOT_ENOUGH_PARAMETERS = "not enough parameters given."; private static final String ERR_TOO_MANY_PARAMETERS = "too many parameters given."; private static final String ERR_QUERY_ENDS_WITH_SEMICOLON = "query ends with ; (not allowed)."; //-------------------------------------------------------------// private Command command; private ArrayList<String> parameters; private int nextParameter; /** * Creates a query by parsing a user input line. * * @param line The user input line * @throws IllegalInputException Gets thrown if the syntax or command of the line is invalid. */ public Query(String line) throws IllegalInputException { if (line == null || line.equals("")) { throw new IllegalInputFormatException(ERR_QUERY_EMPTY); } if (line.endsWith(";")) { throw new IllegalInputTokenException(ERR_QUERY_ENDS_WITH_SEMICOLON); } String[] split = line.split(" ", -1); // split into command and arguments if (split.length > 2 || line.endsWith(" ")) { // too many spaces throw new IllegalInputFormatException(ERR_NO_SPACES); } String commandString = split[0]; command = validateCommand(commandString); // find command enum if (split.length > 1) { parseParameters(split[1]); } else { parseParameters(null); } } // parsed parameters private void parseParameters(String line) { parameters = new ArrayList<>(); if (line != null && !line.equals("")) { String[] params = line.split(";", -1); // split parameters and add them to list parameters.addAll(Arrays.asList(params)); } nextParameter = 0; } // finds the Command enum of the given string. Returns null if invalid private Command validateCommand(String commandString) throws IllegalInputTokenException { if (!commandString.matches("[a-z]+")) { // only allow lowercase letters throw new IllegalInputTokenException(ERR_INVALID_COMMAND); } try { return Command.valueOf(commandString.toUpperCase()); // convert to uppercase to be able to user valueOf } catch (IllegalArgumentException ex) { // nothing found throw new IllegalInputTokenException(ERR_INVALID_COMMAND); } } /** * Returns the next argument as a non-numeric String. * * @return The argument as lowercase non-numeric String * @throws IllegalInputException Gets thrown if the argument isn't a non-numeric string */ public String getNextParamAsString() throws IllegalInputException { String s; try { s = parameters.get(nextParameter); } catch (IndexOutOfBoundsException ex) { // not enough parameters given throw new IllegalInputFormatException(ERR_NOT_ENOUGH_PARAMETERS); } if (s == null || s.equals("")) { // should never happen throw new IllegalInputFormatException(ERR_QUERY_EMPTY); } if (!s.matches("[A-Za-z]+")) { throw new IllegalInputTokenException(ERR_NOT_STRING + nextParameter + "."); } nextParameter++; return s.toLowerCase(); } /** * Returns the next argument as an integer. * * @return The argument as integer * @throws IllegalInputException Gets thrown if the argument can't be represented as an integer */ public int getNextParamAsInt() throws IllegalInputException { String s; try { s = parameters.get(nextParameter); } catch (IndexOutOfBoundsException ex) { // not enough parameters given throw new IllegalInputFormatException(ERR_NOT_ENOUGH_PARAMETERS); } if (s == null || s.equals("")) { // should never happen throw new IllegalInputFormatException(ERR_QUERY_EMPTY); } int i; try { i = Integer.parseInt(s); } catch (NumberFormatException ex) { // isn't an integer throw new IllegalInputTokenException(ERR_NOT_INT + nextParameter + "."); } nextParameter++; return i; } /** * Checks if there are unused parameters left. * * @throws IllegalInputFormatException Gets thrown if there are unused parameters left */ public void close() throws IllegalInputFormatException { if (parameters.size() > nextParameter) { throw new IllegalInputFormatException(ERR_TOO_MANY_PARAMETERS); } } /** * Returns the command. * * @return The command */ public Command getCommand() { return command; } /** * Returns an ArrayList of the raw String parameters. * * @return The raw parameters */ public ArrayList<String> getParameters() { return new ArrayList<>(parameters); } // autogenerated toString for debugging @Override public String toString() { final StringBuilder sb = new StringBuilder("Query{"); sb.append("command=").append(command); sb.append(", parameters=").append(parameters); sb.append('}'); return sb.toString(); } }
/** * */ package restaurante; import java.io.Serializable; /** * @author Gabriel Alves * @author Joao Carlos * @author Melissa Diniz * @author Thais Nicoly */ public class Pedidos implements Serializable{ private static final long serialVersionUID = 1L; private String nome; private double preco; /** * @param nome * @param preco */ public Pedidos(String nome, double preco) { this.nome = nome; this.preco = preco; } /** * @return the nome */ public String getNome() { return nome; } /** * @return the preco */ public double getPreco() { return preco; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Pedidos [nome=" + nome + ", preco=" + preco + "]"; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((nome == null) ? 0 : nome.hashCode()); return result; } /* * (non-Javadoc) * * Dois pedidos sao iguais se possuirem o mesmo nome */ @Override public boolean equals(Object obj) { if (!(obj instanceof Pedidos)) return false; Pedidos other = (Pedidos) obj; if (getNome().equals(other.getNome())) { return true; } return false; } }
package com.yuecheng.yue.ui.fragment.impl; import android.net.Uri; import android.os.Bundle; import com.yuecheng.yue.R; import com.yuecheng.yue.base.YUE_BaseLazyFragment; import io.rong.imkit.fragment.ConversationListFragment; import io.rong.imlib.model.Conversation; /** * Created by administraot on 2017/11/21. */ public class YUE_ConversationListFragment extends YUE_BaseLazyFragment { @Override protected void onCreateViewLazy(Bundle savedInstanceState) { super.onCreateViewLazy(savedInstanceState); setContentView(R.layout.fragment_conversationlist_layout); init(); } private void init() { ConversationListFragment fragment = (ConversationListFragment) getChildFragmentManager().findFragmentById(R.id.conversationlist); Uri uri = Uri.parse("rong://" + getActivity().getApplicationInfo().packageName).buildUpon() .appendPath("conversationlist") .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话非聚合显示 .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "true")//设置群组会话聚合显示 .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "false")//设置讨论组会话非聚合显示 .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "false")//设置系统会话非聚合显示 .build(); fragment.setUri(uri); } }
package com.tencent.mm.pluginsdk.cmd; class b$a { String cfF; int qyt; a qyu; b$a() { } }
package com.amazon.dp; import java.util.HashMap; import java.util.Map; public class CoinChange { /** * with given v1 v2 v3.....Vn coins make a sum/change of P where v1 = 1 * C(P) = min i 1->n {C(P-vi} +1 */ static int P =15; int[] coins = {1,5}; Map<Integer,Integer> result = new HashMap<Integer,Integer>(); public static void main(String[] args) { System.out.println(new CoinChange().change(P)); } public int change(int changeP){ if(result.get(changeP)!=null) return result.get(changeP); System.out.println("called C("+changeP+")"); if(changeP==0) return 0; int min = Integer.MAX_VALUE; for(int i =0;i<=coins.length-1;i++){ int changeVal = changeP-coins[i]; if(changeVal < 0 ) continue; if (!result.containsKey(changeVal)) result.put(changeVal, change(changeVal) ); System.out.println(String.format("For %s calculated C(%s)=%s",changeP,changeVal, result.get(changeVal))); min = Math.min(min,result.get(changeVal)); } return min+1; } }
package com.smxknife.java2.thread.interrupt; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2019/9/19 */ public class ThreadInterruptBlockedEnable implements Runnable { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { // 这样处理,可以让线程中断后无法继续执行 System.out.println(Thread.currentThread().getName() + " | is running" ); try { TimeUnit.SECONDS.sleep(3); // 线程会阻塞在这里 } catch (InterruptedException e) { System.out.println("在阻塞处接收到中断请求"); e.printStackTrace(); // 方式一: //break; // 通过主动break,让线程终止 // 方式二: Thread.currentThread().interrupt(); // 再次调用Interrupt,为什么会出现这种情况,因为阻塞方法在收到Interrupt之后会解除阻塞,然后再次调用Interrupt会将状态消除 // 所以这里再次调用就可以正确的获取状态 } } } }
/** * SearchByFieldPanel.java * * Skarpetis Dimitris 2016, all rights reserved. */ package dskarpetis.elibrary.ui.search; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.PropertyModel; import dskarpetis.elibrary.domain.Book; import dskarpetis.elibrary.init.AppInjector; import dskarpetis.elibrary.service.book.BookService; import dskarpetis.elibrary.service.user.UserService; import dskarpetis.elibrary.ui.search.SearchByFieldData.SearchEnum; /** * Class that defines the SearchByFieldPanel component * * * @author dskarpetis */ public class SearchByFieldPanel extends Panel { private static final long serialVersionUID = 1L; // Define String KEYS for the component declaration <span wicket:id="KEY"> // to HTML file private static final String FORM_KEY = "search-by-field-form"; private static final String SEARCH_INPUT_KEY = "searchField"; private static final String SEARCH_OPTIONS_KEY = "searchEnum"; private static final String FEEDBACK_KEY = "feedback"; private static final String SUBMIT_KEY = "submit"; /** * This is a detachable model for {@link UserService} instance, since we do * not want this to be serialized during page versioning. */ private IModel<BookService> serviceModel = new LoadableDetachableModel<BookService>() { private static final long serialVersionUID = 1L; @Override protected BookService load() { return AppInjector.get().getInstance(BookService.class); } }; /** * Results of book searching. */ @SuppressWarnings("unused") private final IModel<ArrayList<Book>> bookSearchResults; /** * @param id * @param formModel * @param bookSearchResults */ public SearchByFieldPanel(String id, final IModel<SearchByFieldData> formModel, IModel<ArrayList<Book>> bookSearchResults) { super(id, formModel); this.bookSearchResults = bookSearchResults; // Form component final Form<SearchByFieldData> form = new Form<SearchByFieldData>(FORM_KEY); // add form component to the parent panel component add(form); // bind UserLoginData class properties with form component form.setDefaultModel(formModel); final TextField<String> searchField = (TextField<String>) new TextField<String>(SEARCH_INPUT_KEY).setRequired(true); DropDownChoice<SearchEnum> searchEnum = (DropDownChoice<SearchEnum>) new DropDownChoice<>(SEARCH_OPTIONS_KEY, getSearchOptions()) .setNullValid(true).setRequired(true); FeedbackPanel feedbackPanel = new FeedbackPanel(FEEDBACK_KEY); queue(searchField, searchEnum, feedbackPanel); queue(new Button(SUBMIT_KEY) { private static final long serialVersionUID = 1L; public void onSubmit() { bookSearchResults.setObject(searchBooksBy(formModel.getObject())); } }); } /** * @return Arrays.asList(SearchEnum.values().toString()) */ public List<SearchEnum> getSearchOptions() { return Arrays.asList(SearchEnum.values()); } private ArrayList<Book> searchBooksBy(SearchByFieldData data) { BookService service = serviceModel.getObject(); return (ArrayList<Book>) service.searchBooksBy(data.getSearchField(), data.getSearchEnum().toString()); } }
//import java.io.*; //import java.util.ArrayList; // //public class TestAdministrator { // private static final Option help = new Option("h", "help", "List a summary of all options and their arguments."); // private static final Option verbose = new Option("v", "verbose", "Enable verbose output."); // private static final Option banner = new Option("b" , "banner", "Print the application's banner."); // // public static void main(String args[]) throws IOException { // // Creating the banner... // IBanner testBanner = new Banner("Test Admin","1.2","2003-2020","Michel de Champlain"); // // // Creating the option table and adding all the valid options... // IOptionTable optionTable = new OptionTable(); // optionTable.add(help); // optionTable.add(verbose); // optionTable.add(banner); // // // Creating the administrator... // IAdministrator admin = new Administrator(args,"TestAdministrator [ -h | -b | -v ]", optionTable); // // // Parsing options and arguments... // admin.administer(); // // IOptionTable options = admin.getOptions(); // // // Checking valid options have been enabled... // if (options.get("help").isEnabled()) { // admin.usage(); // } else if (options.get("banner").isEnabled()) { // System.out.println(testBanner); // } // // // Executing... and print five stars (*****) if the verbose option is enabled. // ArrayList<String> arguments = admin.getArguments(); // for (String argName : arguments) { // doSomethingOn(argName); // if (options.get("verbose").isEnabled()) { // System.out.println("*****"); // } // } // } // public static void doSomethingOn(String filename) { // System.out.println("Do an action on this file '" + filename + "'..."); // } //}
package com.example.dllo.notestudio.DemoAllImage.glide; import android.animation.ObjectAnimator; import android.content.Context; import android.content.pm.PackageInfo; import android.graphics.Color; import android.media.Image; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.Priority; import com.bumptech.glide.request.animation.ViewPropertyAnimation; import com.example.dllo.notestudio.R; import jp.wasabeef.glide.transformations.*; import jp.wasabeef.glide.transformations.CropCircleTransformation; /** * Created by dllo on 16/11/26. */ public class DemoAllImageGlideAdapter extends BaseAdapter { private String[] data; private Context context; public DemoAllImageGlideAdapter(Context context) { this.context = context; } public void setData(String[] data) { this.data = data; notifyDataSetChanged(); } @Override public int getCount() { return data.length; } @Override public Object getItem(int i) { return data[i]; } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder holder = null; if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.demo_all_iamge_glide_ls_item, viewGroup, false); holder = new ViewHolder(view); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } //自定义获取网络图片方法 initGlide(holder, i); return view; } //自定义获取网络图片方法方法 private void initGlide(ViewHolder holder, int i) { ViewPropertyAnimation.Animator animationObject = new ViewPropertyAnimation.Animator() { @Override public void animate(View view) { // 设置旋转 //ObjectAnimator fadeAnim = ObjectAnimator.ofFloat(view , "rotation" ,0,180,0 ,180,0,180,0); // 设置透明度 //ObjectAnimator fadeAnim = ObjectAnimator.ofFloat(view , "alpha" ,0,1,0 ,1,0,1,0,1); // 设置翻转 //ObjectAnimator fadeAnim = ObjectAnimator.ofFloat(view , "rotationX" ,0,270,0 ,270,0,270,0); //ObjectAnimator fadeAnim = ObjectAnimator.ofFloat(view , "rotation" ,0,270,0 ,270,0,270,0); // 设置平移 ObjectAnimator fadeAnim = ObjectAnimator.ofFloat(view, "translationX", 0, 270, 0, 270, 0, 270, 0); // 设置拉伸 //ObjectAnimator fadeAnim = ObjectAnimator.ofFloat(view , "scaleX" ,0,3,1 ,0,3,2,1); fadeAnim.setDuration(3000); fadeAnim.start(); } }; Glide.with(context).load(data[i]) //设置未加载出来时的图片 .placeholder(R.mipmap.ic_launcher) //设置报错是出现的图片 .error(R.mipmap.ic_launcher) //设置动画 .animate(animationObject) //设置优先级 .priority(Priority.HIGH) //缩略图??? .thumbnail(0.5f) //画圆形图片的方法 只有Glide能用 要用到依赖 .bitmapTransform(new CropCircleTransformation(context)) .into(holder.iv); } class ViewHolder { private ImageView iv; public ViewHolder(View view) { iv = (ImageView) view.findViewById(R.id.demo_all_iamge_iv_glide); } } }
/* * Copyright 2008 Kjetil Valstadsve * * 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 vanadis.core.lang; /** * String utilities. */ public final class Strings { /** * True for {@link #isEmpty(String) empty} and all-whitespace strings. * * @param string String * @return True if {@link #isEmpty(String) empty} or all-whitespace */ public static boolean isBlank(String string) { return isEmpty(string) || string.trim().length() == 0; } /** * True for null and zero-length strings. * * @param string String * @return True if null or zero-length */ public static boolean isEmpty(String string) { return string == null || string.length() == 0; } /** * True for objects that are null or zero-length strings. * * @param object Object * @return True if null or a zero-length string */ public static boolean isEmptyString(Object object) { return object == null || object instanceof String && isEmpty((String) object); } /** * True for objects that are {@link #isEmpty(String) empty} and all-whitespace strings. * * @param object Object * @return True if {@link #isEmpty(String) empty} string or all-whitespace string */ public static boolean isBlankString(Object object) { return object instanceof String && isBlank((String) object); } public static String neitherNullNorEmpty(Object string) { return isEmptyString(string) ? null : string.toString(); } public static String trim(Object string) { return isEmptyString(string) ? null : string.toString().trim(); } private Strings() { } }
package proparaproj1; import java.text.NumberFormat; class Customer implements Comparable<Customer>{ private String name; protected int[] orders; private int totalBill; //Customer constructor public Customer(){} public Customer(String n,int[] order_in){ name = n; orders = new int[5]; orders=order_in; totalBill = 0; } //method for calculate total bill protected void calculateBill(Product[] products){ for(int i=0;i<5;i++){ totalBill+=orders[i]*products[i].giveprice(); } } public int compareTo(Customer other){ if(this.totalBill>other.totalBill) return -1; else if(this.totalBill<other.totalBill)return 1; else return 0; } protected void printcorrection(){ System.out.printf("Correction : %-8s %-3d %-3d %-3d %-3d %-3d\n\n",name,orders[0],orders[1],orders[2],orders[3],orders[4]); } protected void print(){ NumberFormat changeformat; changeformat = NumberFormat.getInstance(); System.out.printf("%-8s total bill : %10s\n",name,changeformat.format(totalBill)); } }
package com.my.wyatth.instagramphotoviewer; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.content.Context; import android.widget.TextView; import android.widget.ImageView; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by wyatth on 14/11/14. */ public class InstgramPhotosAdapter extends ArrayAdapter<InstgramPhoto>{ public InstgramPhotosAdapter(Context context, List<InstgramPhoto> photos) { super(context, android.R.layout.simple_list_item_1, photos); } @Override public View getView(int position, View ConvertView, ViewGroup parent) { InstgramPhoto p = getItem(position); if(ConvertView == null) { ConvertView = LayoutInflater.from(getContext()).inflate(R.layout.item_photo, parent, false); } TextView tvCaption = (TextView) ConvertView.findViewById(R.id.tvCaption); TextView tvLikeCount = (TextView) ConvertView.findViewById(R.id.tvLike); TextView tvUsername = (TextView) ConvertView.findViewById(R.id.tvUsername); ImageView img = (ImageView) ConvertView.findViewById(R.id.imagePhoto); ImageView profileImg = (ImageView) ConvertView.findViewById(R.id.profilePhoto); tvCaption.setText(p.caption); tvUsername.setText(p.username); tvLikeCount.setText("Like: " + p.likeCount); img.setImageResource(0); Picasso.with(getContext()).load(p.imageUrl).into(img); Picasso.with(getContext()).load(p.userProfile).into(profileImg); return ConvertView; } }
package com.yuecheng.yue.ui.activity.impl; import android.app.Activity; import android.graphics.Rect; import android.os.Bundle; import android.os.Handler; import android.os.PersistableBundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBar; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.malinskiy.superrecyclerview.OnMoreListener; import com.malinskiy.superrecyclerview.SuperRecyclerView; import com.yuecheng.yue.R; import com.yuecheng.yue.base.YUE_BaseActivitySlideBack; import com.yuecheng.yue.ui.activity.YUE_IFriendCircleView; import com.yuecheng.yue.ui.adapter.YUE_CircleAdapter; import com.yuecheng.yue.ui.bean.CircleItem; import com.yuecheng.yue.ui.bean.CommentConfig; import com.yuecheng.yue.ui.bean.CommentItem; import com.yuecheng.yue.ui.bean.FavortItem; import com.yuecheng.yue.ui.presenter.YUE_FriendCircleViewPresenter; import com.yuecheng.yue.util.CommonUtils; import com.yuecheng.yue.util.YUE_LogUtils; import com.yuecheng.yue.util.YUE_SharedPreferencesUtils; import com.yuecheng.yue.util.YUE_ToastUtils; import com.yuecheng.yue.util.anim.ViewAnimationUtils; import com.yuecheng.yue.widget.EmojiEditText.fragment.EmotionMainFragment; import com.yuecheng.yue.widget.EmojiEditText.utils.DisplayUtils; import com.yuecheng.yue.widget.circle.CommentListView; import com.yuecheng.yue.widget.picloadlib.PhotoPickActivity; import com.yuecheng.yue.widget.selector.YUE_BackResUtils; import java.util.List; import io.rong.imageloader.core.ImageLoader; /** * Created by administraot on 2017/11/25. */ public class YUE_FriendCircleActivity extends YUE_BaseActivitySlideBack implements YUE_IFriendCircleView, View.OnClickListener { private String TAG = getClass().getSimpleName(); private SuperRecyclerView mRecyclerView; private YUE_FriendCircleViewPresenter mPresenter; private final static int TYPE_PULLREFRESH = 1; private final static int TYPE_UPLOADREFRESH = 2; private SwipeRefreshLayout.OnRefreshListener refreshListener; private LinearLayout edittextbody; private CommentConfig commentConfig; private LinearLayoutManager layoutManager; private int selectCircleItemH; private int selectCommentItemOffset; private RelativeLayout bodyLayout; private int currentKeyboardH; private int screenHeight; private int editTextBodyHeight; private Toolbar mToolBar; private EmotionMainFragment mEmojiEditextView; private YUE_CircleAdapter mAdapter; private View mView; private static int mRememberPosition; private int emotion_map_type; @Override protected int getContentViewLayoutID() { return R.layout.activity_friendcircle_layout; } @Override protected void initViewsAndEvents() { mPresenter = new YUE_FriendCircleViewPresenter(this, this); initToolBar(); initViews(); initDataEvents(); } @Override public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { outState.putInt("currentPosition", mRecyclerView.getVerticalScrollbarPosition()); super.onSaveInstanceState(outState, outPersistentState); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_publish, menu); return super.onCreateOptionsMenu(menu); } @Override protected void onDestroy() { YUE_LogUtils.d(TAG, "onDestroy" + mRememberPosition); if (layoutManager != null) mRememberPosition = layoutManager.findFirstVisibleItemPosition(); super.onDestroy(); } /** * 功能操作 */ private void initDataEvents() { layoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(layoutManager); //添加分割线 DividerItemDecoration d = new DividerItemDecoration( mContext, DividerItemDecoration.VERTICAL); d.setDrawable(YUE_BackResUtils.getInstance(mContext).getDividerItemDrawable()); mRecyclerView.addItemDecoration(d); // mRecyclerView.addItemDecoration( new DivItemDecoration(2, true)); mRecyclerView.getMoreProgressView().getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT; mRecyclerView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (edittextbody.getVisibility() == View.VISIBLE) { updateEditTextBodyVisible(View.GONE, null); return true; } return false; } }); refreshListener = new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { mPresenter.loadData(TYPE_PULLREFRESH); } }, 2000); } }; //设置刷新事件 mRecyclerView.setRefreshListener(refreshListener); //设置滚动监听,滚动过程中停止加载.停止滚动后开始加载 mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE) { ImageLoader.getInstance().resume(); // Glide.with(MainActivity.this).resumeRequests(); } else { ImageLoader.getInstance().pause(); // Glide.with(MainActivity.this).pauseRequests(); } } }); //设置适配器 mAdapter = mPresenter.getAdapter(); mRecyclerView.setAdapter(mAdapter); //加载数据 mPresenter.loadData(TYPE_PULLREFRESH); // 创建评论框 initEmotionMainFragment(); //添加监听 mEmojiEditextView.addOnSendClickListener(new EmotionMainFragment.onSendClickListener() { @Override public void sendClick() { //发布评论 String content = mEmojiEditextView.getTextValue().trim(); if (TextUtils.isEmpty(content)) { YUE_ToastUtils.showmessage("什么都没说呢。。。,,ԾㅂԾ," + "," + ""); ViewAnimationUtils.shake(mEmojiEditextView.getSendBtn(), true); return; } mPresenter.addComment(content, commentConfig); updateEditTextBodyVisible(View.GONE, null); } }); //获取表情map类型,主要用于后面将文本转换成表情显示 // emotion_map_type = mEmojiEditextView.getEmotionMapType(); //不便于获取,存sp // YUE_SharedPreferencesUtils.setParam(mContext,"emotion_map_type",emotion_map_type); if (mRememberPosition > 0) layoutManager.scrollToPosition(mRememberPosition); setViewTreeObserver(); } private void initEmotionMainFragment() { //构建传递参数 Bundle bundle = new Bundle(); //绑定主内容编辑框 bundle.putBoolean(EmotionMainFragment.BIND_TO_EDITTEXT, true); //隐藏控件 bundle.putBoolean(EmotionMainFragment.HIDE_BAR_EDITTEXT_AND_BTN, false); //替换fragment //创建修改实例 mEmojiEditextView = EmotionMainFragment.newInstance(EmotionMainFragment.class, bundle); mEmojiEditextView.bindToContentView(mView); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whatever is in thefragment_container view with this fragment, // and add the transaction to the backstack transaction.replace(R.id.fl_emotionview_main, mEmojiEditextView); transaction.addToBackStack(null); //提交修改 transaction.commit(); } private void setViewTreeObserver() { bodyLayout = (RelativeLayout) findViewById(R.id.bodyLayout); final ViewTreeObserver swipeRefreshLayoutVTO = bodyLayout.getViewTreeObserver(); swipeRefreshLayoutVTO.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect r = new Rect(); bodyLayout.getWindowVisibleDisplayFrame(r); int statusBarH = getStatusBarHeight();//状态栏高度 int screenH = bodyLayout.getRootView().getHeight(); if (r.top != statusBarH) { //在这个demo中r.top代表的是状态栏高度,在沉浸式状态栏时r.top=0,通过getStatusBarHeight获取状态栏高度 r.top = statusBarH; } int keyboardH = screenH - (r.bottom - r.top); YUE_LogUtils.d(TAG, "screenH= " + screenH + " &keyboardH = " + keyboardH + " &r.bottom=" + r .bottom + " &top=" + r.top + " &statusBarH=" + statusBarH); if (keyboardH == currentKeyboardH) {//有变化时才处理,否则会陷入死循环 return; } currentKeyboardH = keyboardH; screenHeight = screenH;//应用屏幕的高度 editTextBodyHeight = edittextbody.getHeight(); if (keyboardH < 150) {//说明是隐藏键盘的情况 // updateEditTextBodyVisible(View.GONE, null); return; } //偏移listview if (layoutManager != null && commentConfig != null) { // layoutManager.scrollToPositionWithOffset(commentConfig.circlePosition + // mAdapter.HEADVIEW_SIZE, 0); layoutManager.scrollToPositionWithOffset(commentConfig.circlePosition + mAdapter.HEADVIEW_SIZE, getListviewOffset(commentConfig)); } } }); } private int getListviewOffset(CommentConfig commentConfig) { if (commentConfig == null) return 0; //这里如果你的listview上面还有其它占高度的控件,则需要减去该控件高度,listview的headview除外。 //int listviewOffset = mScreenHeight - mSelectCircleItemH - mCurrentKeyboardH - mEditTextBodyHeight; int listviewOffset = screenHeight - selectCircleItemH - currentKeyboardH - mToolBar.getHeight() - DisplayUtils.dp2px(mContext, 48); if (commentConfig.commentType == CommentConfig.Type.REPLY) { //回复评论的情况 listviewOffset = listviewOffset + selectCommentItemOffset; } YUE_LogUtils.i(TAG, "listviewOffset : " + listviewOffset); return listviewOffset; } /** * 获取状态栏高度 * * @return */ private int getStatusBarHeight() { int result = 0; int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = getResources().getDimensionPixelSize(resourceId); } return result; } /** * 初始化控件 */ private void initViews() { mRecyclerView = findView(R.id.recycler); edittextbody = (LinearLayout) findViewById(R.id.editTextBodyLl); mView = findView(R.id.mview); } /** * 初始化工具栏 */ private void initToolBar() { mToolBar = findView(R.id.toolbar); setSupportActionBar(mToolBar); ActionBar ab = getSupportActionBar(); //使能app bar的导航功能 if (ab != null) { ab.setDisplayShowTitleEnabled(false);//不使用系统的title ab.setDisplayHomeAsUpEnabled(true); } mToolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_send: startActivity(PhotoPickActivity.class); break; } return true; } }); } /** * 点击事件 * * @param view */ @Override public void onClick(View view) { switch (view.getId()) { } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if (edittextbody != null && edittextbody.getVisibility() == View.VISIBLE) { //edittextbody.setVisibility(View.GONE); updateEditTextBodyVisible(View.GONE, null); return true; } else { finish(); return true; } } return super.onKeyDown(keyCode, event); } /** * 返回按钮监听 */ @Override public void onBackPressed() { /** * 判断是否拦截返回键操作 */ if (!mEmojiEditextView.isInterceptBackPress()) { super.onBackPressed(); } super.onBackPressed(); } @Override public FragmentManager getSupportFManager() { return getSupportFragmentManager(); } @Override public void update2loadData(int loadType, List<CircleItem> datas) { if (loadType == TYPE_PULLREFRESH) { mRecyclerView.setRefreshing(false); mAdapter.setDatas(datas); } else if (loadType == TYPE_UPLOADREFRESH) { mAdapter.getDatas().addAll(datas); } mAdapter.notifyDataSetChanged(); if (mAdapter.getDatas().size() < 45 + mAdapter.HEADVIEW_SIZE) { mRecyclerView.setupMoreListener(new OnMoreListener() { @Override public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) { new Handler().postDelayed(new Runnable() { @Override public void run() { mPresenter.loadData(TYPE_UPLOADREFRESH); } }, 2000); } }, 1); } else { mRecyclerView.removeMoreListener(); mRecyclerView.hideMoreProgress(); } } @Override public void update2DeleteCircle(String circleId) { List<CircleItem> circleItems = mAdapter.getDatas(); for (int i = 0; i < circleItems.size(); i++) { if (circleId.equals(circleItems.get(i).getId())) { circleItems.remove(i); mAdapter.notifyDataSetChanged(); //circleAdapter.notifyItemRemoved(i+1); return; } } } @Override public void update2DeleteComment(int circlePosition, String commentItemId) { CircleItem item = (CircleItem) mAdapter.getDatas().get(circlePosition); List<CommentItem> items = item.getComments(); for (int i = 0; i < items.size(); i++) { if (commentItemId.equals(items.get(i).getId())) { items.remove(i); // mAdapter.notifyDataSetChanged(); mAdapter.notifyItemChanged(circlePosition+1,"fuck"); return; } } } //弹出评论框 @Override public void updateEditTextBodyVisible(int visible, CommentConfig commentConfig) { this.commentConfig = commentConfig; edittextbody.setVisibility(visible); measureCircleItemHighAndCommentItemOffset(commentConfig); if (View.VISIBLE == visible) { mEmojiEditextView.setEditextFocusable(true); // mEmojiEditextView.setEditextTextRequestFocus(); //如果是回复别人,则输入框显示提示 回复某人 if (commentConfig.commentType==CommentConfig.Type.REPLY&&commentConfig.replyUser .getName()!=null&&!commentConfig.replyUser.getName().equals("")) mEmojiEditextView.setEditextHint("回复:"+commentConfig.replyUser.getName()); //如果是自己发起评论,则输入框显示 发布评论, if (commentConfig.commentType==CommentConfig.Type.PUBLIC) mEmojiEditextView.setEditextHint("发布评论:"); //如果表情框是弹出的话 则先关掉表情框,在弹出软键盘.否则直接弹出软键盘; mEmojiEditextView.isShowEmojiCloseItThenShowSoftInput(); } else if (View.GONE == visible) { //隐藏键盘 mEmojiEditextView.setEditextText(""); CommonUtils.hideSoftInput(YUE_FriendCircleActivity.this,mEmojiEditextView.getEditext()); } } private void measureCircleItemHighAndCommentItemOffset(CommentConfig commentConfig) { if (commentConfig == null) return; int firstPosition = layoutManager.findFirstVisibleItemPosition(); //只能返回当前可见区域(列表可滚动)的子项 View selectCircleItem = layoutManager.getChildAt(commentConfig.circlePosition + YUE_CircleAdapter.HEADVIEW_SIZE - firstPosition); if (selectCircleItem != null) { selectCircleItemH = selectCircleItem.getHeight(); } if (commentConfig.commentType == CommentConfig.Type.REPLY) { //回复评论的情况 CommentListView commentLv = (CommentListView) selectCircleItem.findViewById(R.id.commentList); if (commentLv != null) { //找到要回复的评论view,计算出该view距离所属动态底部的距离 View selectCommentItem = commentLv.getChildAt(commentConfig.commentPosition); if (selectCommentItem != null) { //选择的commentItem距选择的CircleItem底部的距离 selectCommentItemOffset = 0; View parentView = selectCommentItem; do { int subItemBottom = parentView.getBottom(); parentView = (View) parentView.getParent(); if (parentView != null) { selectCommentItemOffset += (parentView.getHeight() - subItemBottom); } } while (parentView != null && parentView != selectCircleItem); } } } } @Override public void update2AddFavorite(int circlePosition, FavortItem addItem) { if (addItem != null) { CircleItem item = (CircleItem) mAdapter.getDatas().get(circlePosition); item.getFavorters().add(addItem); // mAdapter.notifyDataSetChanged(); mAdapter.notifyItemChanged(circlePosition+1,"fuck"); } } @Override public void update2DeleteFavort(int circlePosition, String favortId) { CircleItem item = (CircleItem) mAdapter.getDatas().get(circlePosition); List<FavortItem> items = item.getFavorters(); for (int i = 0; i < items.size(); i++) { if (favortId.equals(items.get(i).getId())) { items.remove(i); // mAdapter.notifyDataSetChanged(); mAdapter.notifyItemChanged(circlePosition+1,"fuck"); return; } } } @Override public void update2AddComment(int circlePosition, CommentItem addItem) { if (addItem != null) { CircleItem item = (CircleItem) mAdapter.getDatas().get(circlePosition); item.getComments().add(addItem); // mAdapter.notifyDataSetChanged(); mAdapter.notifyItemChanged(circlePosition+1,"fuck"); } //清空评论文本 mEmojiEditextView.setEditextText(""); } }
package com.gtfs.action; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import org.apache.log4j.Logger; import org.primefaces.context.RequestContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.gtfs.bean.AgentRlns; import com.gtfs.bean.GenericBusinessTxn; import com.gtfs.bean.LicApplBocMapping; import com.gtfs.bean.LicInsuredAddressMapping; import com.gtfs.bean.LicNomineeDtls; import com.gtfs.bean.LicPolicyDtls; import com.gtfs.bean.LicPolicyMst; import com.gtfs.bean.LicReqBocMapping; import com.gtfs.service.interfaces.LicApplBocMappingService; import com.gtfs.service.interfaces.LicInsuredAddressMappingService; import com.gtfs.service.interfaces.LicNomineeDtlsService; import com.gtfs.service.interfaces.LicPolicyMstService; import com.gtfs.service.interfaces.LicReqBocMappingService; @Component @Scope("session") public class OblRejectToApprovalAction implements Serializable { private Logger log = Logger.getLogger(OblRejectToApprovalAction.class); @Autowired private LoginAction loginAction; @Autowired private LicPolicyMstService licPolicyMstService; @Autowired private LicReqBocMappingService licReqBocMappingService; @Autowired private LicApplBocMappingService licApplBocMappingService; @Autowired private LicInsuredAddressMappingService licInsuredAddressMappingService; @Autowired private LicNomineeDtlsService licNomineeDtlsService; private Boolean renderedList; private Boolean renderedRejectedList; private Date fromDate; private Date toDate; private String applicantName; private Double premium; private Double sumAssured; private Long term; private String applicationNo; private String policyNo; private String proposalNo; private List<LicPolicyMst> licPolicyMsts = new ArrayList<LicPolicyMst>(); private List<LicPolicyMst> selectedLicPolicyMsts = new ArrayList<LicPolicyMst>(); private List<LicReqBocMapping> licReqBocMappings = new ArrayList<LicReqBocMapping>(); private LicPolicyMst licPolicyMst; private LicPolicyMst licPolicyMstDialog; public void save(){ try{ Date now = new Date(); licPolicyMst.setAcceptDate(null); licPolicyMst.setDeleteFlag("N"); licPolicyMst.setModalPrem(null); licPolicyMst.setModifiedBy(loginAction.getUserList().get(0).getUserid()); licPolicyMst.setModifiedDate(now); licPolicyMst.setPolicyNo(null); licPolicyMst.setPolicyStatus(null); licPolicyMst.setProposalNo(null); licPolicyMst.setRiskStartDate(null); licPolicyMst.setBondFlag("N"); licPolicyMst.setDispatchDate(null); licPolicyMst.setDispatchNo(null); licPolicyMst.setFprFlag("N"); licPolicyMst.setRemarks(null); licPolicyMst.setSentHub(null); licPolicyMst.setPicBranchMst(null); licPolicyMst.setAgentMst(null); licPolicyMst.getLicOblApplicationMst().setDeleteFlag("N"); licPolicyMst.getLicOblApplicationMst().setModifiedBy(loginAction.getUserList().get(0).getUserid()); licPolicyMst.getLicOblApplicationMst().setModifiedDate(now); licPolicyMst.getLicOblApplicationMst().getLicBusinessTxn().setDeleteFlag("N"); licPolicyMst.getLicOblApplicationMst().getLicBusinessTxn().setModifiedBy(loginAction.getUserList().get(0).getUserid()); licPolicyMst.getLicOblApplicationMst().getLicBusinessTxn().setModifiedDate(now); licPolicyMst.getLicOblApplicationMst().getLicBusinessTxn().setTransStatus("D"); licPolicyMst.getLicOblApplicationMst().getLicBusinessTxn().setTransDate(now); licPolicyMst.getLicOblApplicationMst().getLicBusinessTxn().setTransferFlag("N"); licPolicyMst.getLicOblApplicationMst().getLicBusinessTxn().setTransferFlag(null); licPolicyMst.getLicOblApplicationMst().getLicBusinessTxn().getLicPaymentMst().setDeleteFlag("N"); licPolicyMst.getLicOblApplicationMst().getLicBusinessTxn().getLicPaymentMst().setModifiedBy(loginAction.getUserList().get(0).getUserid()); licPolicyMst.getLicOblApplicationMst().getLicBusinessTxn().getLicPaymentMst().setModifiedDate(now); Boolean status = licPolicyMstService.update(licPolicyMst); if (status) { refresh(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success : ", "Policy Updatation Successful")); } else { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error : ", "Policy Updatation Unsuccessful")); } }catch(Exception e){ log.info("OblApprovalAction goToWelcomePage Error : ", e); } } public void search(){ try{ if(licPolicyMsts!=null){ licPolicyMsts.clear(); } if(selectedLicPolicyMsts != null){ selectedLicPolicyMsts.clear(); } licPolicyMsts = licPolicyMstService.findApplicationForRejectedEntry(fromDate, toDate, applicantName, premium, sumAssured, term, applicationNo, policyNo, proposalNo, loginAction.findHubForProcess("OBL")); renderedList = true; }catch(Exception e){ log.info("OblApprovalAction search Error : ", e); } } public void showDetail(LicPolicyMst licPolicyMst){ licReqBocMappings = licReqBocMappingService.findReqBocMappingByApplication(licPolicyMst.getLicOblApplicationMst().getId()); List<LicApplBocMapping> licApplBocMappings = licApplBocMappingService.findBocMappingByApplication(licPolicyMst.getLicOblApplicationMst().getId()); List<LicInsuredAddressMapping> licInsuredAddressMappings = licInsuredAddressMappingService.findAddressDtlsByInsuredDtls(licPolicyMst.getLicOblApplicationMst().getLicInsuredDtls()); List<LicNomineeDtls> LicNomineeDtlses = licNomineeDtlsService.findNomineeDtlsByApplication(licPolicyMst.getLicOblApplicationMst()); licPolicyMst.getLicOblApplicationMst().setLicApplBocMappings(licApplBocMappings); licPolicyMst.getLicOblApplicationMst().getLicInsuredDtls().setLicInsuredAddressMappings(licInsuredAddressMappings); licPolicyMst.getLicOblApplicationMst().setLicNomineeDtlses(LicNomineeDtlses); licPolicyMstDialog = licPolicyMst; RequestContext.getCurrentInstance().openDialog("oblRejectToApprovalDialog"); } public void select(LicPolicyMst licPolicyMst){ try{ selectedLicPolicyMsts.add(licPolicyMst); this.licPolicyMst = licPolicyMst; renderedList = false; renderedRejectedList = true; }catch(Exception e){ log.info("OblApprovalAction select Error : ", e); } } public void refresh(){ if(licPolicyMsts!=null){ licPolicyMsts.clear(); } if(selectedLicPolicyMsts!=null){ selectedLicPolicyMsts.clear(); } renderedList = false; renderedRejectedList = false; } public String onLoad(){ refresh(); return "/licHubActivity/oblRejectToApproval.xhtml"; } public Boolean getRenderedRejectedList() { return renderedRejectedList; } public void setRenderedRejectedList(Boolean renderedRejectedList) { this.renderedRejectedList = renderedRejectedList; } public Date getFromDate() { return fromDate; } public void setFromDate(Date fromDate) { this.fromDate = fromDate; } public Date getToDate() { return toDate; } public void setToDate(Date toDate) { this.toDate = toDate; } public String getApplicantName() { return applicantName; } public void setApplicantName(String applicantName) { this.applicantName = applicantName; } public Double getPremium() { return premium; } public void setPremium(Double premium) { this.premium = premium; } public Double getSumAssured() { return sumAssured; } public void setSumAssured(Double sumAssured) { this.sumAssured = sumAssured; } public Long getTerm() { return term; } public void setTerm(Long term) { this.term = term; } public String getApplicationNo() { return applicationNo; } public void setApplicationNo(String applicationNo) { this.applicationNo = applicationNo; } public String getPolicyNo() { return policyNo; } public void setPolicyNo(String policyNo) { this.policyNo = policyNo; } public String getProposalNo() { return proposalNo; } public void setProposalNo(String proposalNo) { this.proposalNo = proposalNo; } public Boolean getRenderedList() { return renderedList; } public void setRenderedList(Boolean renderedList) { this.renderedList = renderedList; } public List<LicPolicyMst> getLicPolicyMsts() { return licPolicyMsts; } public void setLicPolicyMsts(List<LicPolicyMst> licPolicyMsts) { this.licPolicyMsts = licPolicyMsts; } public List<LicPolicyMst> getSelectedLicPolicyMsts() { return selectedLicPolicyMsts; } public void setSelectedLicPolicyMsts(List<LicPolicyMst> selectedLicPolicyMsts) { this.selectedLicPolicyMsts = selectedLicPolicyMsts; } public List<LicReqBocMapping> getLicReqBocMappings() { return licReqBocMappings; } public void setLicReqBocMappings(List<LicReqBocMapping> licReqBocMappings) { this.licReqBocMappings = licReqBocMappings; } public LicPolicyMst getLicPolicyMstDialog() { return licPolicyMstDialog; } public void setLicPolicyMstDialog(LicPolicyMst licPolicyMstDialog) { this.licPolicyMstDialog = licPolicyMstDialog; } public LicPolicyMst getLicPolicyMst() { return licPolicyMst; } public void setLicPolicyMst(LicPolicyMst licPolicyMst) { this.licPolicyMst = licPolicyMst; } }
package com.example.hospitalmanagementapp; import android.os.Bundle; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.CardView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class fragment_prescription extends Fragment { public fragment_prescription() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_prescription, container, false); BottomNavigationView navigation = rootView.findViewById(R.id.navigation); CardView cardView = rootView.findViewById(R.id.card1); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.flContainer, new CatExample()); transaction.addToBackStack(null); transaction.commit(); } }); return rootView; } // public void moveFragment(View v){ // FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction(); // transaction.replace(R.id.flContainer, new grid()); // transaction.addToBackStack(null); // transaction.commit(); // } }
package April.ElgunAZE; import java.util.HashSet; import java.util.Set; public class AllSetEXam { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("ablm"); set.add("aba"); set.add("ciyelek"); set.add("yemis"); /* set.stream().filter(n -> n.equals("armud")).forEach(each -> System.out.println(each)); Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { String str = iterator.next(); if (str.equals("armud")) { System.out.println(str); } } */ set.stream().filter(each -> each.length()>0).sorted().forEach(each -> System.out.println(each)); // //set.stream().filter(n-> n.length() > 3).forEach(n -> System.out.println(n)); // List<String> list2 = set.stream().filter(n-> n.length()>3).collect(Collectors.toList()); // System.out.println(list2); } }
package view.scale; import structure.Pair; import java.util.Map; /** * Created by Matthew on 10/4/2017. */ public interface Scaler { Pair<Double, Double> getScaleRange(Map<Double, Double> function); }
package com.smclaughlin.tps.services; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.smclaughlin.tps.IntegrationTest; import com.smclaughlin.tps.entities.AccountDetails; import com.smclaughlin.tps.service.IAccountDetailsService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; /** * Created by sineadmclaughlin on 29/11/2016. */ public class AccountDetailsServiceTest extends IntegrationTest{ @Autowired IAccountDetailsService accountDetailsService; @Test @DatabaseSetup("/test_db/services/accountDetailsService/beforeTestGetAccountDetailsByUUID.xml") @DatabaseTearDown public void testGetAccountDetailsByUUID() throws Exception{ AccountDetails ac = createTestAccountDetail(); ac.setId(1L); ac.setAccountName("facebook"); ac.setAccountWebsite("facebook.com"); ac.setUsername("admin@test.com"); ac.setPasswordHash("password"); ac.setPasswordSalt("password"); ac.setUuid("38a5639e-d041-4793-bfce-bccf81016e38"); AccountDetails serviceResult = accountDetailsService.getAccountDetailsByUUID("38a5639e-d041-4793-bfce-bccf81016e38"); assertThat(serviceResult, equalTo(ac)); } @Test @DatabaseSetup("/test_db/services/accountDetailsService/beforeTestGetListAccountDetails.xml") @DatabaseTearDown public void testGetListAccountDetails() throws Exception{ AccountDetails ac = createTestAccountDetail(); ac.setId(1L); ac.setAccountName("facebook"); ac.setAccountWebsite("facebook.com"); ac.setUsername("admin@test.com"); ac.setPasswordHash("password"); ac.setPasswordSalt("password"); ac.setUuid("38a5639e-d041-4793-bfce-bccf81016e38"); List<AccountDetails> serviceResult = accountDetailsService.returnListOfAccountDetails(); assertThat(serviceResult.size(), equalTo(2)); assertThat(serviceResult, hasItem(ac)); } @Test @DatabaseSetup("/test_db/services/accountDetailsService/beforeTestSaveAccountDetails.xml") @ExpectedDatabase("/test_db/services/accountDetailsService/afterTestSaveAccountDetails.xml") @DatabaseTearDown public void testSaveAccountDetails() throws Exception{ AccountDetails accountDetails = accountDetailsService.getAccountDetailsByUUID("38a5639e-d041-4793-bfce-bccf81016e38"); accountDetails.setPasswordHash("password1"); AccountDetails serviceResult = accountDetailsService.saveAccountDetails(accountDetails); assertThat(serviceResult, equalTo(accountDetails)); } @Test @DatabaseSetup("/test_db/services/accountDetailsService/beforeTestCreateNewAccountDetails.xml") @ExpectedDatabase("/test_db/services/accountDetailsService/afterTestCreateNewAccountDetails.xml") @DatabaseTearDown public void testCreateNewAccountDetails() throws Exception{ AccountDetails accountDetails = createTestAccountDetail(); accountDetailsService.createNewAccountDetails(accountDetails); } }
package com.catnap.core.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Meta-annotation (annotations used on other annotations) * used for marking all annotations that are * part of Catnap package. Can be used for recognizing all * Catnap annotations generically, and in future also for * passing other generic annotation configuration. * * @author gwhit7 */ @Target({ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface CatnapAnnotation { //Noop }
package com.google.android.exoplayer2.g; import android.graphics.Point; import android.text.TextUtils; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.g.e.a; import com.google.android.exoplayer2.i.t; import com.google.android.exoplayer2.s; import com.google.android.exoplayer2.source.l; import com.google.android.exoplayer2.source.m; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.concurrent.atomic.AtomicReference; public final class b extends d { private static final int[] azX = new int[0]; private final a azY; private final AtomicReference<b> azZ; public static final class b { public final String aAa; public final String aAb; public final int aAc; public final int aAd; public final int aAe; public final boolean aAf; public final boolean aAg; public final boolean aAh; public final boolean aAi; public final boolean aAj; public final int viewportHeight; public final int viewportWidth; public b() { this((byte) 0); } private b(byte b) { this.aAa = null; this.aAb = null; this.aAh = false; this.aAi = true; this.aAc = Integer.MAX_VALUE; this.aAd = Integer.MAX_VALUE; this.aAe = Integer.MAX_VALUE; this.aAf = true; this.aAj = true; this.viewportWidth = Integer.MAX_VALUE; this.viewportHeight = Integer.MAX_VALUE; this.aAg = true; } public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } b bVar = (b) obj; if (this.aAh == bVar.aAh && this.aAi == bVar.aAi && this.aAc == bVar.aAc && this.aAd == bVar.aAd && this.aAf == bVar.aAf && this.aAj == bVar.aAj && this.aAg == bVar.aAg && this.viewportWidth == bVar.viewportWidth && this.viewportHeight == bVar.viewportHeight && this.aAe == bVar.aAe && TextUtils.equals(this.aAa, bVar.aAa) && TextUtils.equals(this.aAb, bVar.aAb)) { return true; } return false; } public final int hashCode() { int i; int i2 = 1; int hashCode = ((this.aAh ? 1 : 0) + (((this.aAa.hashCode() * 31) + this.aAb.hashCode()) * 31)) * 31; if (this.aAi) { i = 1; } else { i = 0; } hashCode = (((((((i + hashCode) * 31) + this.aAc) * 31) + this.aAd) * 31) + this.aAe) * 31; if (this.aAf) { i = 1; } else { i = 0; } hashCode = (i + hashCode) * 31; if (this.aAj) { i = 1; } else { i = 0; } i = (i + hashCode) * 31; if (!this.aAg) { i2 = 0; } return ((((i + i2) * 31) + this.viewportWidth) * 31) + this.viewportHeight; } } public b() { this((byte) 0); } private b(byte b) { this.azY = null; this.azZ = new AtomicReference(new b()); } protected final e[] a(s[] sVarArr, m[] mVarArr, int[][][] iArr) { int i; int i2; int length = sVarArr.length; e[] eVarArr = new e[length]; b bVar = (b) this.azZ.get(); Object obj = null; int i3 = 0; while (true) { int i4 = i3; if (i4 >= length) { break; } if (2 == sVarArr[i4].getTrackType()) { if (obj == null) { s sVar = sVarArr[i4]; m mVar = mVarArr[i4]; int[][] iArr2 = iArr[i4]; a aVar = this.azY; e eVar = null; if (aVar != null) { int i5 = bVar.aAi ? 24 : 16; Object obj2 = (!bVar.aAh || (sVar.iw() & i5) == 0) ? null : 1; i = 0; while (true) { int i6 = i; if (i6 >= mVar.length) { eVar = null; break; } int[] iArr3; l lVar = mVar.asI[i6]; int[] iArr4 = iArr2[i6]; int i7 = bVar.aAc; int i8 = bVar.aAd; int i9 = bVar.aAe; i2 = bVar.viewportWidth; int i10 = bVar.viewportHeight; boolean z = bVar.aAg; if (lVar.length < 2) { iArr3 = azX; } else { List a = a(lVar, i2, i10, z); if (a.size() < 2) { iArr3 = azX; } else { String str; String str2 = null; if (obj2 == null) { HashSet hashSet = new HashSet(); int i11 = 0; int i12 = 0; while (i12 < a.size()) { int a2; str = lVar.asb[((Integer) a.get(i12)).intValue()].adW; if (hashSet.add(str)) { a2 = a(lVar, iArr4, i5, str, i7, i8, i9, a); if (a2 > i11) { i12++; i11 = a2; str2 = str; } } a2 = i11; str = str2; i12++; i11 = a2; str2 = str; } str = str2; } else { str = null; } b(lVar, iArr4, i5, str, i7, i8, i9, a); iArr3 = a.size() < 2 ? azX : t.q(a); } } if (iArr3.length > 0) { eVar = aVar.lJ(); break; } i = i6 + 1; } } if (eVar == null) { eVar = a(mVar, iArr2, bVar); } eVarArr[i4] = eVar; obj = eVarArr[i4] != null ? 1 : null; } if (mVarArr[i4].length > 0) { i3 = 1; } else { i3 = 0; } i3 |= 0; } else { i3 = 0; } i4++; } Object obj3 = null; Object obj4 = null; i = 0; while (true) { i2 = i; if (i2 >= length) { return eVarArr; } switch (sVarArr[i2].getTrackType()) { case 1: if (obj3 != null) { break; } eVarArr[i2] = a(mVarArr[i2], iArr[i2], bVar, null != null ? null : this.azY); obj3 = eVarArr[i2] != null ? 1 : null; break; case 2: break; case 3: if (obj4 != null) { break; } eVarArr[i2] = b(mVarArr[i2], iArr[i2], bVar); obj4 = eVarArr[i2] != null ? 1 : null; break; default: eVarArr[i2] = c(mVarArr[i2], iArr[i2], bVar); break; } i = i2 + 1; } } private static int a(l lVar, int[] iArr, int i, String str, int i2, int i3, int i4, List<Integer> list) { int i5 = 0; int i6 = 0; while (true) { int i7 = i6; int i8 = i5; if (i7 >= list.size()) { return i8; } i5 = ((Integer) list.get(i7)).intValue(); if (a(lVar.asb[i5], str, iArr[i5], i, i2, i3, i4)) { i5 = i8 + 1; } else { i5 = i8; } i6 = i7 + 1; } } private static void b(l lVar, int[] iArr, int i, String str, int i2, int i3, int i4, List<Integer> list) { for (int size = list.size() - 1; size >= 0; size--) { int intValue = ((Integer) list.get(size)).intValue(); if (!a(lVar.asb[intValue], str, iArr[intValue], i, i2, i3, i4)) { list.remove(size); } } } private static boolean a(Format format, String str, int i, int i2, int i3, int i4, int i5) { if (!r(i, false) || (i & i2) == 0) { return false; } if (str != null && !t.i(format.adW, str)) { return false; } if (format.width != -1 && format.width > i3) { return false; } if (format.height != -1 && format.height > i4) { return false; } if (format.bitrate == -1 || format.bitrate <= i5) { return true; } return false; } private static e a(m mVar, int[][] iArr, b bVar) { l lVar = null; int i = 0; int i2 = 0; int i3 = -1; int i4 = -1; int i5 = 0; while (true) { int i6 = i5; if (i6 >= mVar.length) { break; } l lVar2 = mVar.asI[i6]; List a = a(lVar2, bVar.viewportWidth, bVar.viewportHeight, bVar.aAg); int[] iArr2 = iArr[i6]; for (int i7 = 0; i7 < lVar2.length; i7++) { if (r(iArr2[i7], bVar.aAj)) { Format format = lVar2.asb[i7]; Object obj = (!a.contains(Integer.valueOf(i7)) || ((format.width != -1 && format.width > bVar.aAc) || ((format.height != -1 && format.height > bVar.aAd) || (format.bitrate != -1 && format.bitrate > bVar.aAe)))) ? null : 1; if (obj != null || bVar.aAf) { i5 = obj != null ? 2 : 1; boolean r = r(iArr2[i7], false); if (r) { i5 += 1000; } Object obj2 = i5 > i2 ? 1 : null; if (i5 == i2) { int au; if (format.iP() != i4) { au = au(format.iP(), i4); } else { au = au(format.bitrate, i3); } obj2 = (!r || obj == null) ? au < 0 ? 1 : null : au > 0 ? 1 : null; } if (obj2 != null) { i3 = format.bitrate; i4 = format.iP(); i2 = i5; i = i7; lVar = lVar2; } } } } i5 = i6 + 1; } return lVar == null ? null : new c(lVar, i); } private static int au(int i, int i2) { return i == -1 ? i2 == -1 ? 0 : -1 : i2 == -1 ? 1 : i - i2; } private static e a(m mVar, int[][] iArr, b bVar, a aVar) { int i; l lVar; int[] iArr2; int i2; int i3; int i4 = -1; int i5 = -1; int i6 = 0; for (i = 0; i < mVar.length; i++) { lVar = mVar.asI[i]; iArr2 = iArr[i]; for (i2 = 0; i2 < lVar.length; i2++) { if (r(iArr2[i2], bVar.aAj)) { Format format = lVar.asb[i2]; int i7 = iArr2[i2]; String str = bVar.aAa; Object obj = (format.ael & 1) != 0 ? 1 : null; i3 = a(format, str) ? obj != null ? 4 : 3 : obj != null ? 2 : 1; if (r(i7, false)) { i3 += 1000; } if (i3 > i6) { i6 = i3; i5 = i2; i4 = i; } } } } if (i4 == -1) { return null; } lVar = mVar.asI[i4]; if (aVar != null) { int[] iArr3; iArr2 = iArr[i4]; boolean z = bVar.aAh; i2 = 0; a aVar2 = null; HashSet hashSet = new HashSet(); i3 = 0; while (i3 < lVar.length) { Format format2 = lVar.asb[i3]; a aVar3 = new a(format2.aeg, format2.sampleRate, z ? null : format2.adW); if (hashSet.add(aVar3)) { i4 = a(lVar, iArr2, aVar3); if (i4 > i2) { i3++; aVar2 = aVar3; i2 = i4; } } aVar3 = aVar2; i4 = i2; i3++; aVar2 = aVar3; i2 = i4; } if (i2 > 1) { int[] iArr4 = new int[i2]; i4 = 0; for (i = 0; i < lVar.length; i++) { if (a(lVar.asb[i], iArr2[i], aVar2)) { i2 = i4 + 1; iArr4[i4] = i; i4 = i2; } } iArr3 = iArr4; } else { iArr3 = azX; } if (iArr3.length > 0) { return aVar.lJ(); } } return new c(lVar, i5); } private static int a(l lVar, int[] iArr, a aVar) { int i = 0; int i2 = 0; while (true) { int i3 = i; if (i2 >= lVar.length) { return i3; } if (a(lVar.asb[i2], iArr[i2], aVar)) { i = i3 + 1; } else { i = i3; } i2++; } } private static boolean a(Format format, int i, a aVar) { if (!r(i, false) || format.aeg != aVar.aeg || format.sampleRate != aVar.sampleRate) { return false; } if (aVar.mimeType == null || TextUtils.equals(aVar.mimeType, format.adW)) { return true; } return false; } private static e b(m mVar, int[][] iArr, b bVar) { l lVar = null; int i = 0; int i2 = 0; int i3 = 0; while (true) { int i4 = i3; if (i4 >= mVar.length) { break; } l lVar2 = mVar.asI[i4]; int[] iArr2 = iArr[i4]; for (int i5 = 0; i5 < lVar2.length; i5++) { if (r(iArr2[i5], bVar.aAj)) { Format format = lVar2.asb[i5]; Object obj = (format.ael & 1) != 0 ? 1 : null; Object obj2 = (format.ael & 2) != 0 ? 1 : null; if (a(format, bVar.aAb)) { if (obj != null) { i3 = 6; } else if (obj2 == null) { i3 = 5; } else { i3 = 4; } } else if (obj != null) { i3 = 3; } else if (obj2 != null) { if (a(format, bVar.aAa)) { i3 = 2; } else { i3 = 1; } } if (r(iArr2[i5], false)) { i3 += 1000; } if (i3 > i2) { i2 = i3; i = i5; lVar = lVar2; } } } i3 = i4 + 1; } return lVar == null ? null : new c(lVar, i); } private static e c(m mVar, int[][] iArr, b bVar) { boolean z = false; int i = 0; l lVar = null; for (int i2 = 0; i2 < mVar.length; i2++) { l lVar2 = mVar.asI[i2]; int[] iArr2 = iArr[i2]; int i3 = 0; while (i3 < lVar2.length) { boolean z2; if (r(iArr2[i3], bVar.aAj)) { if ((lVar2.asb[i3].ael & 1) != 0) { z2 = true; } else { z2 = false; } if (z2) { z2 = true; } else { z2 = true; } if (r(iArr2[i3], false)) { z2 += 1000; } if (z2 > z) { i = i3; lVar = lVar2; i3++; z = z2; } } z2 = z; i3++; z = z2; } } if (lVar == null) { return null; } return new c(lVar, i); } private static boolean r(int i, boolean z) { int i2 = i & 7; return i2 == 4 || (z && i2 == 3); } private static boolean a(Format format, String str) { return str != null && TextUtils.equals(str, t.aB(format.aem)); } private static List<Integer> a(l lVar, int i, int i2, boolean z) { int i3; ArrayList arrayList = new ArrayList(lVar.length); for (i3 = 0; i3 < lVar.length; i3++) { arrayList.add(Integer.valueOf(i3)); } if (i == Integer.MAX_VALUE || i2 == Integer.MAX_VALUE) { return arrayList; } int i4 = Integer.MAX_VALUE; for (i3 = 0; i3 < lVar.length; i3++) { Format format = lVar.asb[i3]; if (format.width > 0 && format.height > 0) { int i5; int i6; int i7 = format.width; int i8 = format.height; if (z) { Object obj; Object obj2; if (i7 > i8) { obj = 1; } else { obj = null; } if (i > i2) { obj2 = 1; } else { obj2 = null; } if (obj != obj2) { Point point; i5 = i; i6 = i2; if (i7 * i5 < i8 * i6) { point = new Point(i6, t.aw(i6 * i8, i7)); } else { point = new Point(t.aw(i5 * i7, i8), i5); } i5 = format.width * format.height; if (format.width >= ((int) (((float) point.x) * 0.98f)) && format.height >= ((int) (((float) point.y) * 0.98f)) && i5 < i4) { i4 = i5; } } } i5 = i2; i6 = i; if (i7 * i5 < i8 * i6) { point = new Point(t.aw(i5 * i7, i8), i5); } else { point = new Point(i6, t.aw(i6 * i8, i7)); } i5 = format.width * format.height; i4 = i5; } } if (i4 != Integer.MAX_VALUE) { for (int size = arrayList.size() - 1; size >= 0; size--) { i3 = lVar.asb[((Integer) arrayList.get(size)).intValue()].iP(); if (i3 == -1 || i3 > i4) { arrayList.remove(size); } } } return arrayList; } }
package com.rawls.ai; public class GoalieAI implements iPlayerAI{ }
package myproject.game.mappers; import myproject.game.models.dto.GameDto; import myproject.game.models.entities.Game; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; import java.util.List; @Mapper public interface GameMapper { GameMapper INSTANCE = Mappers.getMapper(GameMapper.class); Game gameDtoToGame (GameDto gameDto); GameDto gameToGameDto (Game game); List<Game> gameDtosToGames (List<GameDto> gameDtos); List<GameDto> gamesToGameDtos (List<Game> games); }
package models.grid; import java.awt.Dimension; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Random; import models.Point; import models.rules.Rule; import sun.reflect.generics.reflectiveObjects.NotImplementedException; /** * A class to contain all the cells, hold them in spatial relation to each other, and use the rules to update them as * the simulation requires. * @author Weston * */ public class GridModel implements Iterable<Cell>{ private Cell[][] myGrid; private Rule myRules; private int myCellSides; private int myTicks; private Map<Integer, Map<String, Double>> myStateInfo; //NOTE: there is no public/private/protected qualifier in front of this constructor, because // this constructor should only be called from GridFactory GridModel(Collection<Cell> cells, Dimension dimension, Rule rule, int cellSides, Map<Integer, Map<String, Double>> aStateInfo){ myGrid = constructGrid(cells, dimension); myRules = rule; myCellSides = cellSides; myTicks = 0; myStateInfo = aStateInfo; } /** * A method to randomly change the state of a cell * @param aCell */ public void randomlyChangeCellState(Cell aCell) { int randomStateId = getRandomStateId(); CellState newState = new CellState(randomStateId, myStateInfo.get(randomStateId)); aCell.setCurrentState(newState); } public double getParameter() { return myRules.getParameter(); } public void updateParameter(double aPercentage) { myRules.updateParameter(aPercentage); } private int getRandomStateId() { Random random = new Random(); int randomIndex = random.nextInt(myStateInfo.keySet().size()); ArrayList<Integer> stateIds = new ArrayList<Integer>(myStateInfo.keySet()); return stateIds.get(randomIndex); } /** * * @param cells * @param dimension * @return a 2D array that contains the cells, organized by their location. */ private Cell[][] constructGrid(Iterable<Cell> cells, Dimension dimension){ myGrid = new Cell[(int) dimension.getWidth()][(int) dimension.getHeight()]; for (Cell c: cells) { int row = c.getLocation().getX(); int col = c.getLocation().getY(); myGrid[row][col] = c; } return myGrid; } /** * Calculate the next state of each cell in the grid, then update all their states. * @return */ public void nextTick(){ calculateAllNextStates(); for (int i = 0; i < myGrid.length; i++){ for (int j = 0; j < myGrid[0].length; j++){ myGrid[i][j].tick(); } } myTicks++; } /** * Calculate a next state for each cell using the given rules */ private void calculateAllNextStates() { myRules.calculateAndSetNextStates(this); } /** * @return A collection of all the cells contained on the grid. */ public Collection<Cell> getAllCells(){ ArrayList<Cell> result = new ArrayList<Cell>(); for (int i = 0; i < myGrid.length; i++){ for (int j = 0; j < myGrid[0].length; j++){ result.add(myGrid[i][j]); } } return result; } /** * Should no longer be needed * @return the number of sides each cell has */ public int getCellSides(){ return myCellSides; } /** * @return number of ticks elapsed since the start of the simulation. */ public int getTick(){ return myTicks; } /** * Not yet implemented. * @return a map from cell state IDs to that state's percentage on the grid. */ public Map<Integer, Double> percentages(){ throw new NotImplementedException(); } /** * An iterator so that a for each loop can be called on GridModel * @author Weston * */ private class GridIterator implements Iterator<Cell>{ Cell[][] myGrid; int currX; int currY; int maxX; int maxY; public GridIterator(Cell[][] grid){ myGrid = grid; maxX = grid.length; maxY = grid[0].length; currX = 0; currY = 0; } private void updateCurrent(){ currX++; if (currX >= maxX){ currX = 0; currY++; } } @Override public boolean hasNext() { return (currX < maxX && currY < maxY); } @Override public Cell next() { if (hasNext()){ int x = currX; int y = currY; updateCurrent(); return myGrid[x][y]; } return null; } } @Override public Iterator<Cell> iterator() { return new GridIterator(myGrid); } /** * Converts an array of Points points to an array of cells. Entries may be null if the Points are not on the grid. * @param points * @return array of cells */ private Cell[] pointsToCells(Point[] points){ Cell[] result = new Cell[points.length]; for (int i = 0; i < points.length; i++){ result[i] = getCell(points[i]); } return result; } /** * * @param c * @return the cells that occupy the spaces Cell c says are it's neighbors */ public Cell[] getNeighbors(Cell c){ return pointsToCells(c.getNeighbors()); } /** * * @param c * @param angleStart * @param angleRange * @return the cells that occupy the spaces Cell c says are it's neighbors in a direction towards angleStart within an arc of size 2*angleRange. */ public Cell[] getDirectedNeighbors(Cell c, double angleStart, double angleRange){ return pointsToCells(c.getDirectedNeighbors(angleStart, angleRange)); } /** * * @param c * @param angle * @return the cells that occupy the space Cell c says are is its neighbor in a direction closest to angle */ public Cell getDirectedNeighbor(Cell c, double angle){ return getCell(c.getDirectedNeighbor(angle)); } /** * * @param p * @return true iff Point p falls inside the grid */ public boolean inGrid(Point p){ return ( p.getX() >= 0 && p.getY() >= 0 && p.getX() < myGrid.length && p.getY() < myGrid[0].length ); } /** * @param p * @return the cell at Point p if p is in the grid, or null otherwise. */ public Cell getCell(Point p){ if (inGrid(p)){ return myGrid[p.getX()][p.getY()]; } else { return null; } } /** * * @return the grid's dimensions */ public Point getDimensions(){ return new Point(myGrid.length, myGrid[0].length); } /** * * @param x * @param y * @return the cell at point (x, y) */ public Cell getCell(int x, int y){ return getCell(new Point(x, y)); } }
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.operators; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Observer; import rx.Subscriber; import rx.functions.Func1; import rx.observables.GroupedObservable; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; public class OperatorPivotTest { @Test public void testPivotEvenAndOdd() throws InterruptedException { Observable<GroupedObservable<Boolean, Integer>> o1 = Observable.range(1, 10).groupBy(modKeySelector).subscribeOn(Schedulers.newThread()); Observable<GroupedObservable<Boolean, Integer>> o2 = Observable.range(11, 10).groupBy(modKeySelector).subscribeOn(Schedulers.newThread()); Observable<GroupedObservable<String, GroupedObservable<Boolean, Integer>>> groups = Observable.from(GroupedObservable.from("o1", o1), GroupedObservable.from("o2", o2)); Observable<GroupedObservable<Boolean, GroupedObservable<String, Integer>>> pivoted = Observable.pivot(groups); final AtomicInteger count = new AtomicInteger(); final CountDownLatch latch = new CountDownLatch(1); pivoted.flatMap(new Func1<GroupedObservable<Boolean, GroupedObservable<String, Integer>>, Observable<String>>() { @Override public Observable<String> call(final GroupedObservable<Boolean, GroupedObservable<String, Integer>> outerGroup) { return outerGroup.flatMap(new Func1<GroupedObservable<String, Integer>, Observable<String>>() { @Override public Observable<String> call(final GroupedObservable<String, Integer> innerGroup) { return innerGroup.map(new Func1<Integer, String>() { @Override public String call(Integer i) { return (outerGroup.getKey() ? "Even" : "Odd ") + " => from source: " + outerGroup.getKey() + "." + innerGroup.getKey() + " Value: " + i + " Thread: " + Thread.currentThread(); } }); } }); } }).subscribe(new Observer<String>() { @Override public void onCompleted() { System.out.println("============> OnCompleted"); System.out.println("-------------------------------------------------------------------------------------"); latch.countDown(); } @Override public void onError(Throwable e) { System.out.println("============> Error: " + e); System.out.println("-------------------------------------------------------------------------------------"); latch.countDown(); } @Override public void onNext(String t) { System.out.println("============> OnNext: " + t); count.incrementAndGet(); } }); if (!latch.await(800, TimeUnit.MILLISECONDS)) { System.out.println("xxxxxxxxxxxxxxxxxx> TIMED OUT <xxxxxxxxxxxxxxxxxxxx"); System.out.println("Received count: " + count.get()); fail("Timed Out"); } System.out.println("Received count: " + count.get()); assertEquals(20, count.get()); } /** * The Parent and Inner must be unsubscribed, otherwise it will keep waiting for more. * * Unsubscribing from pivot is not a very easy (or typical) thing ... but it sort of works. * * It's NOT easy to understand though, and easy to end up with far more data consumed than expected, because pivot by definition * is inverting the data so we can not unsubscribe from the parent until all children are done since the top key becomes the leaf once pivoted. */ @Test public void testUnsubscribeFromGroups() throws InterruptedException { AtomicInteger counter1 = new AtomicInteger(); AtomicInteger counter2 = new AtomicInteger(); Observable<GroupedObservable<Boolean, Integer>> o1 = getSource(2000, counter1).subscribeOn(Schedulers.newThread()).groupBy(modKeySelector); Observable<GroupedObservable<Boolean, Integer>> o2 = getSource(4000, counter2).subscribeOn(Schedulers.newThread()).groupBy(modKeySelector); Observable<GroupedObservable<String, GroupedObservable<Boolean, Integer>>> groups = Observable.from(GroupedObservable.from("o1", o1), GroupedObservable.from("o2", o2)); Observable<GroupedObservable<Boolean, GroupedObservable<String, Integer>>> pivoted = Observable.pivot(groups); TestSubscriber<String> ts = new TestSubscriber<String>(); pivoted.take(2).flatMap(new Func1<GroupedObservable<Boolean, GroupedObservable<String, Integer>>, Observable<String>>() { @Override public Observable<String> call(final GroupedObservable<Boolean, GroupedObservable<String, Integer>> outerGroup) { return outerGroup.flatMap(new Func1<GroupedObservable<String, Integer>, Observable<String>>() { @Override public Observable<String> call(final GroupedObservable<String, Integer> innerGroup) { return innerGroup.take(10).map(new Func1<Integer, String>() { @Override public String call(Integer i) { return (outerGroup.getKey() ? "Even" : "Odd ") + " => from source: " + innerGroup.getKey() + " Value: " + i; } }); } }); } }).subscribe(ts); ts.awaitTerminalEvent(); System.out.println("onNext [" + ts.getOnNextEvents().size() + "]: " + ts.getOnNextEvents()); assertEquals(40, ts.getOnNextEvents().size()); // 2 (o1 + o2) + 2 (odd + even) * take(10) on each int c1 = counter1.get(); int c2 = counter2.get(); System.out.println("Counter1: " + c1); System.out.println("Counter2: " + c2); Thread.sleep(200); System.out.println("Counter1: " + counter1.get()); System.out.println("Counter2: " + counter2.get()); // after time it should be same if unsubscribed assertEquals(c1, counter1.get(), 1); // delta of 1 for race to unsubscribe assertEquals(c2, counter2.get(), 1); // delta of 1 for race to unsubscribe assertTrue(counter1.get() < 50000); // should be much smaller (< 1000) but this will be non-deterministic assertTrue(counter2.get() < 50000); // should be much smaller (< 1000) but this will be non-deterministic } /** * The pivot operator does not need to add any serialization but this is confirming the expected behavior. * * It does not need serializing as it never merges groups, it just re-arranges them. * * For example, a simple 2-stream case with odd/even: * * Observable<GroupedObservable<Boolean, Integer>> o1 = Observable.range(1, 10).groupBy(modKeySelector).subscribeOn(Schedulers.newThread()); // thread 1 * Observable<GroupedObservable<Boolean, Integer>> o2 = Observable.range(11, 10).groupBy(modKeySelector).subscribeOn(Schedulers.newThread()); // thread 2 * Observable<GroupedObservable<String, GroupedObservable<Boolean, Integer>>> groups = Observable.from(GroupedObservable.from("o1", o1), GroupedObservable.from("o2", o2)); * Observable<GroupedObservable<Boolean, GroupedObservable<String, Integer>>> pivoted = Observable.pivot(groups); * * ============> OnNext: Odd => from source: false.o1 Value: 1 Thread: Thread[RxNewThreadScheduler-1,5,main] * ============> OnNext: Even => from source: true.o2 Value: 12 Thread: Thread[RxNewThreadScheduler-2,5,main] * ============> OnNext: Even => from source: true.o1 Value: 2 Thread: Thread[RxNewThreadScheduler-1,5,main] * ============> OnNext: Odd => from source: false.o2 Value: 11 Thread: Thread[RxNewThreadScheduler-2,5,main] * ============> OnNext: Odd => from source: false.o2 Value: 13 Thread: Thread[RxNewThreadScheduler-2,5,main] * ============> OnNext: Odd => from source: false.o2 Value: 15 Thread: Thread[RxNewThreadScheduler-2,5,main] * ============> OnNext: Odd => from source: false.o2 Value: 17 Thread: Thread[RxNewThreadScheduler-2,5,main] * ============> OnNext: Even => from source: true.o2 Value: 14 Thread: Thread[RxNewThreadScheduler-2,5,main] * ============> OnNext: Odd => from source: false.o1 Value: 3 Thread: Thread[RxNewThreadScheduler-1,5,main] * ============> OnNext: Odd => from source: false.o1 Value: 5 Thread: Thread[RxNewThreadScheduler-1,5,main] * ============> OnNext: Odd => from source: false.o1 Value: 7 Thread: Thread[RxNewThreadScheduler-1,5,main] * ============> OnNext: Odd => from source: false.o1 Value: 9 Thread: Thread[RxNewThreadScheduler-1,5,main] * ============> OnNext: Even => from source: true.o2 Value: 16 Thread: Thread[RxNewThreadScheduler-2,5,main] * ============> OnNext: Even => from source: true.o2 Value: 18 Thread: Thread[RxNewThreadScheduler-2,5,main] * ============> OnNext: Odd => from source: false.o2 Value: 19 Thread: Thread[RxNewThreadScheduler-2,5,main] * ============> OnNext: Even => from source: true.o1 Value: 4 Thread: Thread[RxNewThreadScheduler-1,5,main] * ============> OnNext: Even => from source: true.o1 Value: 6 Thread: Thread[RxNewThreadScheduler-1,5,main] * ============> OnNext: Even => from source: true.o1 Value: 8 Thread: Thread[RxNewThreadScheduler-1,5,main] * ============> OnNext: Even => from source: true.o1 Value: 10 Thread: Thread[RxNewThreadScheduler-1,5,main] * ============> OnNext: Even => from source: true.o2 Value: 20 Thread: Thread[RxNewThreadScheduler-2,5,main] * ============> OnCompleted * * This starts as: * * => Observable<GroupedObservable<String, GroupedObservable<Boolean, Integer>>>: * * o1.odd: 1, 3, 5, 7, 9 on Thread 1 * o1.even: 2, 4, 6, 8, 10 on Thread 1 * o2.odd: 11, 13, 15, 17, 19 on Thread 2 * o2.even: 12, 14, 16, 18, 20 on Thread 2 * * It pivots to become: * * => Observable<GroupedObservable<Boolean, GroupedObservable<String, Integer>>>: * * odd.o1: 1, 3, 5, 7, 9 on Thread 1 * odd.o2: 11, 13, 15, 17, 19 on Thread 2 * even.o1: 2, 4, 6, 8, 10 on Thread 1 * even.o2: 12, 14, 16, 18, 20 on Thread 2 * * Then a subsequent step can merge them if desired and add serialization, such as merge(even.o1, even.o2) to become a serialized "even" */ @Test public void testConcurrencyAndSerialization() throws InterruptedException { final AtomicInteger maxOuterConcurrency = new AtomicInteger(); final AtomicInteger maxGroupConcurrency = new AtomicInteger(); Observable<GroupedObservable<Boolean, Integer>> o1 = getSource(2000).subscribeOn(Schedulers.newThread()).groupBy(modKeySelector); Observable<GroupedObservable<Boolean, Integer>> o2 = getSource(4000).subscribeOn(Schedulers.newThread()).groupBy(modKeySelector); Observable<GroupedObservable<Boolean, Integer>> o3 = getSource(6000).subscribeOn(Schedulers.newThread()).groupBy(modKeySelector); Observable<GroupedObservable<Boolean, Integer>> o4 = getSource(8000).subscribeOn(Schedulers.newThread()).groupBy(modKeySelector); Observable<GroupedObservable<String, GroupedObservable<Boolean, Integer>>> groups = Observable.from(GroupedObservable.from("o1", o1), GroupedObservable.from("o2", o2), GroupedObservable.from("o3", o3), GroupedObservable.from("o4", o4)); Observable<GroupedObservable<Boolean, GroupedObservable<String, Integer>>> pivoted = Observable.pivot(groups); TestSubscriber<String> ts = new TestSubscriber<String>(); pivoted.take(2).flatMap(new Func1<GroupedObservable<Boolean, GroupedObservable<String, Integer>>, Observable<String>>() { final AtomicInteger outerThreads = new AtomicInteger(); @Override public Observable<String> call(final GroupedObservable<Boolean, GroupedObservable<String, Integer>> outerGroup) { return outerGroup.flatMap(new Func1<GroupedObservable<String, Integer>, Observable<String>>() { @Override public Observable<String> call(final GroupedObservable<String, Integer> innerGroup) { final AtomicInteger threadsPerGroup = new AtomicInteger(); return innerGroup.take(100).map(new Func1<Integer, String>() { @Override public String call(Integer i) { int outerThreadCount = outerThreads.incrementAndGet(); setMaxConcurrency(maxOuterConcurrency, outerThreadCount); int innerThreadCount = threadsPerGroup.incrementAndGet(); setMaxConcurrency(maxGroupConcurrency, innerThreadCount); if (innerThreadCount > 1) { System.err.println("more than 1 thread for this group [" + innerGroup.getKey() + "]: " + innerThreadCount + " (before)"); throw new RuntimeException("more than 1 thread for this group [" + innerGroup.getKey() + "]: " + innerThreadCount + " (before)"); } try { return (outerGroup.getKey() ? "Even" : "Odd ") + " => from source: " + innerGroup.getKey() + " Value: " + i; } finally { int outerThreadCountAfter = outerThreads.decrementAndGet(); setMaxConcurrency(maxOuterConcurrency, outerThreadCountAfter); int innerThreadCountAfter = threadsPerGroup.decrementAndGet(); setMaxConcurrency(maxGroupConcurrency, innerThreadCountAfter); if (innerThreadCountAfter > 0) { System.err.println("more than 1 thread for this group [" + innerGroup.getKey() + "]: " + innerThreadCount + " (after)"); throw new RuntimeException("more than 1 thread for this group [" + innerGroup.getKey() + "]: " + innerThreadCountAfter + " (after)"); } } } private void setMaxConcurrency(final AtomicInteger maxOuterConcurrency, int outerThreadCount) { int max = maxOuterConcurrency.get(); if (outerThreadCount > max) { maxOuterConcurrency.compareAndSet(max, outerThreadCount); } } }); } }); } }).subscribe(ts); ts.awaitTerminalEvent(); System.out.println("onNext [" + ts.getOnNextEvents().size() + "]: " + ts.getOnNextEvents()); if (Runtime.getRuntime().availableProcessors() >= 4) { System.out.println("max outer concurrency: " + maxOuterConcurrency.get()); assertTrue(maxOuterConcurrency.get() > 1); // should be 4 since we have 4 threads and cores running but setting at just > 1 as this is non-deterministic } System.out.println("max group concurrency: " + maxGroupConcurrency.get()); assertTrue(maxGroupConcurrency.get() == 1); // should always be 1 assertEquals(800, ts.getOnNextEvents().size()); } private static Observable<Integer> getSource(final int start) { return getSource(start, new AtomicInteger()); } private static Observable<Integer> getSource(final int start, final AtomicInteger counter) { return Observable.create(new OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> s) { for (int i = start; i < 1000000; i++) { if (s.isUnsubscribed()) { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> unsubscribed so quitting in source: " + start); return; } counter.incrementAndGet(); s.onNext(i); try { // slow it down so it's not just emitting it all into a buffer (merge) Thread.sleep(1); } catch (InterruptedException e) { } } s.onCompleted(); } }); } final static Func1<Integer, Boolean> modKeySelector = new Func1<Integer, Boolean>() { @Override public Boolean call(Integer i) { return i % 2 == 0; } }; }
import java.util.Scanner; public class FindTheLargestNumber { public static void main(String[] args) { Scanner input = new Scanner(System.in); int counter = 5; int number; int largest; System.out.println("Enter number"); largest = input.nextInt(); for (int i = 1; i <= counter; i++) { System.out.println("Enter number"); number = input.nextInt(); if (number > largest) largest = number; } System.out.println("The largest number found so far is " + largest); } }