blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
101e82aa7cf32dfd65be358f35148f3956911fa8
Java
cwi-swat/meta-environment
/toolbus-ng-argus-viewer/src/argusviewer/view/listeners/IHighlightListener.java
UTF-8
958
2.578125
3
[]
no_license
package argusviewer.view.listeners; import toolbus.process.ProcessInstance; import toolbus.tool.ToolInstance; /** * Listener for highlight settings. * * @author J. van den Bos * @author T. Van Laer */ public interface IHighlightListener{ /** * The view is highlighting a process instance. * * @param processInstance * The highlighted process instance. */ void setHighlight(ProcessInstance processInstance); /** * The view is highlighting a tool instance. * * @param toolInstance * The highlighted tool instance. */ void setHighlight(ToolInstance toolInstance); /** * The view is highlighting a process. * * @param processName * The name of a highlighted process. */ void setHighlightByProcessName(String processName); /** * The view is highlighting a tool. * * @param toolName * The name of the highlighted tool. */ void setHighlightByToolName(String toolName); }
true
3655b50b1001f486bcfb47b98dbab22fa45e65fc
Java
TERRANZ/jbrss
/services/dms/src/main/java/ru/terra/dms/dto/DmsObjectFieldDto.java
UTF-8
2,041
2.171875
2
[]
no_license
package ru.terra.dms.dto; import java.time.LocalDateTime; public class DmsObjectFieldDto extends BaseDto { private String dmsObjectId; private String type; private String name; private Integer intVal; private Long longVal; private String strVal; private Double floatVal; private Long dateVal; private String listVal; public DmsObjectFieldDto(final String id, final LocalDateTime createDate, final LocalDateTime modifiedDate, final String dmsObjectId, final String type, final String name) { super(id, createDate, modifiedDate); this.dmsObjectId = dmsObjectId; this.type = type; this.name = name; } public String getDmsObjectId() { return dmsObjectId; } public void setDmsObjectId(final String dmsObjectId) { this.dmsObjectId = dmsObjectId; } public String getType() { return type; } public void setType(final String type) { this.type = type; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public Integer getIntVal() { return intVal; } public void setIntVal(final Integer intVal) { this.intVal = intVal; } public Long getLongVal() { return longVal; } public void setLongVal(final Long longVal) { this.longVal = longVal; } public String getStrVal() { return strVal; } public void setStrVal(final String strVal) { this.strVal = strVal; } public Double getFloatVal() { return floatVal; } public void setFloatVal(final Double floatVal) { this.floatVal = floatVal; } public Long getDateVal() { return dateVal; } public void setDateVal(final Long dateVal) { this.dateVal = dateVal; } public String getListVal() { return listVal; } public void setListVal(final String listVal) { this.listVal = listVal; } }
true
c10c2c30a97e9a60a0e5e5521ebcdc77072b5779
Java
mtjsoft/AndMBaseUtils_6.0
/src/main/java/com/huahan/hhbaseutils/HHPathUtils.java
UTF-8
1,490
2.46875
2
[]
no_license
package com.huahan.hhbaseutils; import android.content.Context; import android.os.Environment; import android.text.TextUtils; import java.io.File; public class HHPathUtils { private static HHPathUtils instance = null; private File voicePath=null; public static HHPathUtils getInstance() { if (instance == null) instance = new HHPathUtils(); return instance; } /** * 初始化路径 * @param context */ private void initDirs(Context context,String cache_dir_name) { voicePath=creatVoicePath(context, cache_dir_name); if (!voicePath.exists()) { voicePath.mkdirs(); } } /** * 创建文件 * @param context * @param cache_dir_name * @return */ private static File creatVoicePath(Context context,String cache_dir_name) { return new File(getBaseCacheDir(context, cache_dir_name), "voice/"); } /** * 根目录 * @param context * @param cache_dir_name * @return */ private static String getBaseCacheDir(Context context,String cache_dir_name) { String packageName=context.getPackageName(); String cacheDirName=cache_dir_name; if (TextUtils.isEmpty(cacheDirName)) { cacheDirName="huahan"; } if (HHSystemUtils.isSDExist()) { return Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+cacheDirName+"/"; }else { return "/data/data/"+packageName+"/"+cacheDirName+"/"; } } public File getVoicePath(Context context,String cache_dir_name) { initDirs(context, cache_dir_name); return voicePath; } }
true
e2d15c3a4946fcadcbe46705289d1edc5523cbc1
Java
ljnwork/AiNInRowGame
/app/src/main/java/com/ljn/aigame/db/LogDao.java
UTF-8
3,738
2.390625
2
[]
no_license
package com.ljn.aigame.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.ljn.aigame.domain.ReciteLog; import com.ljn.aigame.engine.BlockMatrxEngine; import com.ljn.aigame.utils.GameUtils; import java.util.ArrayList; import java.util.List; /** * Created by lijianan on 15-4-17. */ public class LogDao { private SQLiteOpenHelper helper; public LogDao(Context context) { helper = new LogDBHelper(context); } public List<ReciteLog> findAllLogs() { SQLiteDatabase db = helper.getReadableDatabase(); Cursor query = db.query(ReciteLog.TABLE_NAME, new String[]{ReciteLog.RECITE_ID, ReciteLog.RECITE_LOG, ReciteLog.WIN_TYPE}, null, null, null, null, null); List<ReciteLog> logs = new ArrayList<ReciteLog>(); while (query.moveToNext()) { int reciteId = query.getInt(0); String reciteLog = query.getString(1); int winType = query.getInt(2); logs.add(new ReciteLog(reciteId, reciteLog, winType)); } query.close(); db.close(); return logs; } /** * 获取所有分析过的数据 即掌握对手的策略 将对手赢的走法认为是自己成功的走法 * * @return */ public List<ReciteLog> findAllAnalyseXWinLogs() { SQLiteDatabase db = helper.getReadableDatabase(); Cursor query = db.query(ReciteLog.TABLE_NAME, new String[]{ReciteLog.RECITE_ID, ReciteLog.RECITE_LOG, ReciteLog.WIN_TYPE}, "win_type != ?", new String[]{String.valueOf(BlockMatrxEngine.NO_WINNER)}, null, null, null); List<ReciteLog> logs = new ArrayList<ReciteLog>(); while (query.moveToNext()) { int reciteId = query.getInt(0); String reciteLog = query.getString(1); int winType = query.getInt(2); if (winType == BlockMatrxEngine.O_WIN) { logs.add(GameUtils.getReverseReciteLog(new ReciteLog(reciteId, reciteLog, winType))); } else if (winType == BlockMatrxEngine.X_WIN) { logs.add(new ReciteLog(reciteId, reciteLog, winType)); } } query.close(); db.close(); return logs; } public List<ReciteLog> findAllXWinLogs() { SQLiteDatabase db = helper.getReadableDatabase(); Cursor query = db.query(ReciteLog.TABLE_NAME, new String[]{ReciteLog.RECITE_ID, ReciteLog.RECITE_LOG, ReciteLog.WIN_TYPE}, "win_type = ?", new String[]{String.valueOf(BlockMatrxEngine.X_WIN)}, null, null, null); List<ReciteLog> logs = new ArrayList<ReciteLog>(); while (query.moveToNext()) { int reciteId = query.getInt(0); String reciteLog = query.getString(1); int winType = query.getInt(2); logs.add(new ReciteLog(reciteId, reciteLog, winType)); } query.close(); db.close(); return logs; } public long addLog(ReciteLog log) { SQLiteDatabase db = helper.getReadableDatabase(); ContentValues values = new ContentValues(); values.put(ReciteLog.RECITE_ID, log.getReciteId()); values.put(ReciteLog.RECITE_LOG, log.getReciteLog()); values.put(ReciteLog.WIN_TYPE, log.getWinType()); long insert = db.insert(ReciteLog.TABLE_NAME, null, values); db.close(); return insert; } public int deleteAllLog() { SQLiteDatabase db = helper.getReadableDatabase(); int delete = db.delete(ReciteLog.TABLE_NAME, ReciteLog.RECITE_ID + ">= 0", null); db.close(); return delete; } }
true
95b76f5dca3af1b516d875580c3ab5347dc87de9
Java
Andreas237/AndroidPolicyAutomation
/ExtractedJars/Shopkick_com.shopkick.app/javafiles/android/support/v4/app/FrameMetricsAggregator$FrameMetricsApi24Impl.java
UTF-8
24,321
1.632813
2
[ "MIT" ]
permissive
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.v4.app; import android.app.Activity; import android.os.Handler; import android.os.HandlerThread; import android.util.SparseIntArray; import android.view.FrameMetrics; import android.view.Window; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; // Referenced classes of package android.support.v4.app: // FrameMetricsAggregator private static class FrameMetricsAggregator$FrameMetricsApi24Impl extends FrameMetricsAggregator.FrameMetricsBaseImpl { public void add(Activity activity) { if(sHandlerThread == null) //* 0 0:getstatic #56 <Field HandlerThread sHandlerThread> //* 1 3:ifnonnull 40 { sHandlerThread = new HandlerThread("FrameMetricsAggregator"); // 2 6:new #58 <Class HandlerThread> // 3 9:dup // 4 10:ldc1 #60 <String "FrameMetricsAggregator"> // 5 12:invokespecial #63 <Method void HandlerThread(String)> // 6 15:putstatic #56 <Field HandlerThread sHandlerThread> sHandlerThread.start(); // 7 18:getstatic #56 <Field HandlerThread sHandlerThread> // 8 21:invokevirtual #66 <Method void HandlerThread.start()> sHandler = new Handler(sHandlerThread.getLooper()); // 9 24:new #68 <Class Handler> // 10 27:dup // 11 28:getstatic #56 <Field HandlerThread sHandlerThread> // 12 31:invokevirtual #72 <Method android.os.Looper HandlerThread.getLooper()> // 13 34:invokespecial #75 <Method void Handler(android.os.Looper)> // 14 37:putstatic #77 <Field Handler sHandler> } for(int i = 0; i <= 8; i++) //* 15 40:iconst_0 //* 16 41:istore_2 //* 17 42:iload_2 //* 18 43:bipush 8 //* 19 45:icmpgt 87 { SparseIntArray asparseintarray[] = mMetrics; // 20 48:aload_0 // 21 49:getfield #40 <Field SparseIntArray[] mMetrics> // 22 52:astore_3 if(asparseintarray[i] == null && (mTrackingFlags & 1 << i) != 0) //* 23 53:aload_3 //* 24 54:iload_2 //* 25 55:aaload //* 26 56:ifnonnull 80 //* 27 59:aload_0 //* 28 60:getfield #52 <Field int mTrackingFlags> //* 29 63:iconst_1 //* 30 64:iload_2 //* 31 65:ishl //* 32 66:iand //* 33 67:ifeq 80 asparseintarray[i] = new SparseIntArray(); // 34 70:aload_3 // 35 71:iload_2 // 36 72:new #38 <Class SparseIntArray> // 37 75:dup // 38 76:invokespecial #78 <Method void SparseIntArray()> // 39 79:aastore } // 40 80:iload_2 // 41 81:iconst_1 // 42 82:iadd // 43 83:istore_2 //* 44 84:goto 42 activity.getWindow().addOnFrameMetricsAvailableListener(mListener, sHandler); // 45 87:aload_1 // 46 88:invokevirtual #84 <Method Window Activity.getWindow()> // 47 91:aload_0 // 48 92:getfield #50 <Field android.view.Window$OnFrameMetricsAvailableListener mListener> // 49 95:getstatic #77 <Field Handler sHandler> // 50 98:invokevirtual #90 <Method void Window.addOnFrameMetricsAvailableListener(android.view.Window$OnFrameMetricsAvailableListener, Handler)> mActivities.add(((Object) (new WeakReference(((Object) (activity)))))); // 51 101:aload_0 // 52 102:getfield #45 <Field ArrayList mActivities> // 53 105:new #92 <Class WeakReference> // 54 108:dup // 55 109:aload_1 // 56 110:invokespecial #95 <Method void WeakReference(Object)> // 57 113:invokevirtual #98 <Method boolean ArrayList.add(Object)> // 58 116:pop // 59 117:return } void addDurationItem(SparseIntArray sparseintarray, long l) { if(sparseintarray != null) //* 0 0:aload_1 //* 1 1:ifnull 36 { int i = (int)((0x7a120L + l) / 0xf4240L); // 2 4:ldc2w #101 <Long 0x7a120L> // 3 7:lload_2 // 4 8:ladd // 5 9:ldc2w #103 <Long 0xf4240L> // 6 12:ldiv // 7 13:l2i // 8 14:istore 4 if(l >= 0L) //* 9 16:lload_2 //* 10 17:lconst_0 //* 11 18:lcmp //* 12 19:iflt 36 sparseintarray.put(i, sparseintarray.get(i) + 1); // 13 22:aload_1 // 14 23:iload 4 // 15 25:aload_1 // 16 26:iload 4 // 17 28:invokevirtual #108 <Method int SparseIntArray.get(int)> // 18 31:iconst_1 // 19 32:iadd // 20 33:invokevirtual #112 <Method void SparseIntArray.put(int, int)> } // 21 36:return } public SparseIntArray[] getMetrics() { return mMetrics; // 0 0:aload_0 // 1 1:getfield #40 <Field SparseIntArray[] mMetrics> // 2 4:areturn } public SparseIntArray[] remove(Activity activity) { Iterator iterator = mActivities.iterator(); // 0 0:aload_0 // 1 1:getfield #45 <Field ArrayList mActivities> // 2 4:invokevirtual #120 <Method Iterator ArrayList.iterator()> // 3 7:astore_2 do { if(!iterator.hasNext()) break; // 4 8:aload_2 // 5 9:invokeinterface #126 <Method boolean Iterator.hasNext()> // 6 14:ifeq 44 WeakReference weakreference = (WeakReference)iterator.next(); // 7 17:aload_2 // 8 18:invokeinterface #130 <Method Object Iterator.next()> // 9 23:checkcast #92 <Class WeakReference> // 10 26:astore_3 if(weakreference.get() != activity) continue; // 11 27:aload_3 // 12 28:invokevirtual #132 <Method Object WeakReference.get()> // 13 31:aload_1 // 14 32:if_acmpne 8 mActivities.remove(((Object) (weakreference))); // 15 35:aload_0 // 16 36:getfield #45 <Field ArrayList mActivities> // 17 39:aload_3 // 18 40:invokevirtual #134 <Method boolean ArrayList.remove(Object)> // 19 43:pop break; } while(true); activity.getWindow().removeOnFrameMetricsAvailableListener(mListener); // 20 44:aload_1 // 21 45:invokevirtual #84 <Method Window Activity.getWindow()> // 22 48:aload_0 // 23 49:getfield #50 <Field android.view.Window$OnFrameMetricsAvailableListener mListener> // 24 52:invokevirtual #138 <Method void Window.removeOnFrameMetricsAvailableListener(android.view.Window$OnFrameMetricsAvailableListener)> return mMetrics; // 25 55:aload_0 // 26 56:getfield #40 <Field SparseIntArray[] mMetrics> // 27 59:areturn } public SparseIntArray[] reset() { SparseIntArray asparseintarray[] = mMetrics; // 0 0:aload_0 // 1 1:getfield #40 <Field SparseIntArray[] mMetrics> // 2 4:astore_1 mMetrics = new SparseIntArray[9]; // 3 5:aload_0 // 4 6:bipush 9 // 5 8:anewarray SparseIntArray[] // 6 11:putfield #40 <Field SparseIntArray[] mMetrics> return asparseintarray; // 7 14:aload_1 // 8 15:areturn } public SparseIntArray[] stop() { for(int i = mActivities.size() - 1; i >= 0; i--) //* 0 0:aload_0 //* 1 1:getfield #45 <Field ArrayList mActivities> //* 2 4:invokevirtual #144 <Method int ArrayList.size()> //* 3 7:iconst_1 //* 4 8:isub //* 5 9:istore_1 //* 6 10:iload_1 //* 7 11:iflt 68 { WeakReference weakreference = (WeakReference)mActivities.get(i); // 8 14:aload_0 // 9 15:getfield #45 <Field ArrayList mActivities> // 10 18:iload_1 // 11 19:invokevirtual #147 <Method Object ArrayList.get(int)> // 12 22:checkcast #92 <Class WeakReference> // 13 25:astore_2 Activity activity = (Activity)weakreference.get(); // 14 26:aload_2 // 15 27:invokevirtual #132 <Method Object WeakReference.get()> // 16 30:checkcast #80 <Class Activity> // 17 33:astore_3 if(weakreference.get() != null) //* 18 34:aload_2 //* 19 35:invokevirtual #132 <Method Object WeakReference.get()> //* 20 38:ifnull 61 { activity.getWindow().removeOnFrameMetricsAvailableListener(mListener); // 21 41:aload_3 // 22 42:invokevirtual #84 <Method Window Activity.getWindow()> // 23 45:aload_0 // 24 46:getfield #50 <Field android.view.Window$OnFrameMetricsAvailableListener mListener> // 25 49:invokevirtual #138 <Method void Window.removeOnFrameMetricsAvailableListener(android.view.Window$OnFrameMetricsAvailableListener)> mActivities.remove(i); // 26 52:aload_0 // 27 53:getfield #45 <Field ArrayList mActivities> // 28 56:iload_1 // 29 57:invokevirtual #149 <Method Object ArrayList.remove(int)> // 30 60:pop } } // 31 61:iload_1 // 32 62:iconst_1 // 33 63:isub // 34 64:istore_1 //* 35 65:goto 10 return mMetrics; // 36 68:aload_0 // 37 69:getfield #40 <Field SparseIntArray[] mMetrics> // 38 72:areturn } private static final int NANOS_PER_MS = 0xf4240; private static final int NANOS_ROUNDING_VALUE = 0x7a120; private static Handler sHandler; private static HandlerThread sHandlerThread; private ArrayList mActivities; android.view.Window.OnFrameMetricsAvailableListener mListener; SparseIntArray mMetrics[]; int mTrackingFlags; static { // 0 0:return } FrameMetricsAggregator$FrameMetricsApi24Impl(int i) { // 0 0:aload_0 // 1 1:invokespecial #36 <Method void FrameMetricsAggregator$FrameMetricsBaseImpl()> mMetrics = new SparseIntArray[9]; // 2 4:aload_0 // 3 5:bipush 9 // 4 7:anewarray SparseIntArray[] // 5 10:putfield #40 <Field SparseIntArray[] mMetrics> mActivities = new ArrayList(); // 6 13:aload_0 // 7 14:new #42 <Class ArrayList> // 8 17:dup // 9 18:invokespecial #43 <Method void ArrayList()> // 10 21:putfield #45 <Field ArrayList mActivities> mListener = new android.view.Window.OnFrameMetricsAvailableListener() { public void onFrameMetricsAvailable(Window window, FrameMetrics framemetrics, int j) { if((mTrackingFlags & 1) != 0) //* 0 0:aload_0 //* 1 1:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> //* 2 4:getfield #27 <Field int FrameMetricsAggregator$FrameMetricsApi24Impl.mTrackingFlags> //* 3 7:iconst_1 //* 4 8:iand //* 5 9:ifeq 33 { window = ((Window) (FrameMetricsAggregator.FrameMetricsApi24Impl.this)); // 6 12:aload_0 // 7 13:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> // 8 16:astore_1 ((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).addDurationItem(((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).mMetrics[0], framemetrics.getMetric(8)); // 9 17:aload_1 // 10 18:aload_1 // 11 19:getfield #31 <Field SparseIntArray[] FrameMetricsAggregator$FrameMetricsApi24Impl.mMetrics> // 12 22:iconst_0 // 13 23:aaload // 14 24:aload_2 // 15 25:bipush 8 // 16 27:invokevirtual #37 <Method long FrameMetrics.getMetric(int)> // 17 30:invokevirtual #41 <Method void FrameMetricsAggregator$FrameMetricsApi24Impl.addDurationItem(SparseIntArray, long)> } if((mTrackingFlags & 2) != 0) //* 18 33:aload_0 //* 19 34:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> //* 20 37:getfield #27 <Field int FrameMetricsAggregator$FrameMetricsApi24Impl.mTrackingFlags> //* 21 40:iconst_2 //* 22 41:iand //* 23 42:ifeq 65 { window = ((Window) (FrameMetricsAggregator.FrameMetricsApi24Impl.this)); // 24 45:aload_0 // 25 46:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> // 26 49:astore_1 ((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).addDurationItem(((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).mMetrics[1], framemetrics.getMetric(1)); // 27 50:aload_1 // 28 51:aload_1 // 29 52:getfield #31 <Field SparseIntArray[] FrameMetricsAggregator$FrameMetricsApi24Impl.mMetrics> // 30 55:iconst_1 // 31 56:aaload // 32 57:aload_2 // 33 58:iconst_1 // 34 59:invokevirtual #37 <Method long FrameMetrics.getMetric(int)> // 35 62:invokevirtual #41 <Method void FrameMetricsAggregator$FrameMetricsApi24Impl.addDurationItem(SparseIntArray, long)> } if((mTrackingFlags & 4) != 0) //* 36 65:aload_0 //* 37 66:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> //* 38 69:getfield #27 <Field int FrameMetricsAggregator$FrameMetricsApi24Impl.mTrackingFlags> //* 39 72:iconst_4 //* 40 73:iand //* 41 74:ifeq 97 { window = ((Window) (FrameMetricsAggregator.FrameMetricsApi24Impl.this)); // 42 77:aload_0 // 43 78:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> // 44 81:astore_1 ((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).addDurationItem(((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).mMetrics[2], framemetrics.getMetric(3)); // 45 82:aload_1 // 46 83:aload_1 // 47 84:getfield #31 <Field SparseIntArray[] FrameMetricsAggregator$FrameMetricsApi24Impl.mMetrics> // 48 87:iconst_2 // 49 88:aaload // 50 89:aload_2 // 51 90:iconst_3 // 52 91:invokevirtual #37 <Method long FrameMetrics.getMetric(int)> // 53 94:invokevirtual #41 <Method void FrameMetricsAggregator$FrameMetricsApi24Impl.addDurationItem(SparseIntArray, long)> } if((mTrackingFlags & 8) != 0) //* 54 97:aload_0 //* 55 98:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> //* 56 101:getfield #27 <Field int FrameMetricsAggregator$FrameMetricsApi24Impl.mTrackingFlags> //* 57 104:bipush 8 //* 58 106:iand //* 59 107:ifeq 130 { window = ((Window) (FrameMetricsAggregator.FrameMetricsApi24Impl.this)); // 60 110:aload_0 // 61 111:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> // 62 114:astore_1 ((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).addDurationItem(((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).mMetrics[3], framemetrics.getMetric(4)); // 63 115:aload_1 // 64 116:aload_1 // 65 117:getfield #31 <Field SparseIntArray[] FrameMetricsAggregator$FrameMetricsApi24Impl.mMetrics> // 66 120:iconst_3 // 67 121:aaload // 68 122:aload_2 // 69 123:iconst_4 // 70 124:invokevirtual #37 <Method long FrameMetrics.getMetric(int)> // 71 127:invokevirtual #41 <Method void FrameMetricsAggregator$FrameMetricsApi24Impl.addDurationItem(SparseIntArray, long)> } if((mTrackingFlags & 0x10) != 0) //* 72 130:aload_0 //* 73 131:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> //* 74 134:getfield #27 <Field int FrameMetricsAggregator$FrameMetricsApi24Impl.mTrackingFlags> //* 75 137:bipush 16 //* 76 139:iand //* 77 140:ifeq 163 { window = ((Window) (FrameMetricsAggregator.FrameMetricsApi24Impl.this)); // 78 143:aload_0 // 79 144:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> // 80 147:astore_1 ((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).addDurationItem(((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).mMetrics[4], framemetrics.getMetric(5)); // 81 148:aload_1 // 82 149:aload_1 // 83 150:getfield #31 <Field SparseIntArray[] FrameMetricsAggregator$FrameMetricsApi24Impl.mMetrics> // 84 153:iconst_4 // 85 154:aaload // 86 155:aload_2 // 87 156:iconst_5 // 88 157:invokevirtual #37 <Method long FrameMetrics.getMetric(int)> // 89 160:invokevirtual #41 <Method void FrameMetricsAggregator$FrameMetricsApi24Impl.addDurationItem(SparseIntArray, long)> } if((mTrackingFlags & 0x40) != 0) //* 90 163:aload_0 //* 91 164:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> //* 92 167:getfield #27 <Field int FrameMetricsAggregator$FrameMetricsApi24Impl.mTrackingFlags> //* 93 170:bipush 64 //* 94 172:iand //* 95 173:ifeq 198 { window = ((Window) (FrameMetricsAggregator.FrameMetricsApi24Impl.this)); // 96 176:aload_0 // 97 177:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> // 98 180:astore_1 ((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).addDurationItem(((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).mMetrics[6], framemetrics.getMetric(7)); // 99 181:aload_1 // 100 182:aload_1 // 101 183:getfield #31 <Field SparseIntArray[] FrameMetricsAggregator$FrameMetricsApi24Impl.mMetrics> // 102 186:bipush 6 // 103 188:aaload // 104 189:aload_2 // 105 190:bipush 7 // 106 192:invokevirtual #37 <Method long FrameMetrics.getMetric(int)> // 107 195:invokevirtual #41 <Method void FrameMetricsAggregator$FrameMetricsApi24Impl.addDurationItem(SparseIntArray, long)> } if((mTrackingFlags & 0x20) != 0) //* 108 198:aload_0 //* 109 199:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> //* 110 202:getfield #27 <Field int FrameMetricsAggregator$FrameMetricsApi24Impl.mTrackingFlags> //* 111 205:bipush 32 //* 112 207:iand //* 113 208:ifeq 232 { window = ((Window) (FrameMetricsAggregator.FrameMetricsApi24Impl.this)); // 114 211:aload_0 // 115 212:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> // 116 215:astore_1 ((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).addDurationItem(((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).mMetrics[5], framemetrics.getMetric(6)); // 117 216:aload_1 // 118 217:aload_1 // 119 218:getfield #31 <Field SparseIntArray[] FrameMetricsAggregator$FrameMetricsApi24Impl.mMetrics> // 120 221:iconst_5 // 121 222:aaload // 122 223:aload_2 // 123 224:bipush 6 // 124 226:invokevirtual #37 <Method long FrameMetrics.getMetric(int)> // 125 229:invokevirtual #41 <Method void FrameMetricsAggregator$FrameMetricsApi24Impl.addDurationItem(SparseIntArray, long)> } if((mTrackingFlags & 0x80) != 0) //* 126 232:aload_0 //* 127 233:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> //* 128 236:getfield #27 <Field int FrameMetricsAggregator$FrameMetricsApi24Impl.mTrackingFlags> //* 129 239:sipush 128 //* 130 242:iand //* 131 243:ifeq 267 { window = ((Window) (FrameMetricsAggregator.FrameMetricsApi24Impl.this)); // 132 246:aload_0 // 133 247:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> // 134 250:astore_1 ((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).addDurationItem(((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).mMetrics[7], framemetrics.getMetric(0)); // 135 251:aload_1 // 136 252:aload_1 // 137 253:getfield #31 <Field SparseIntArray[] FrameMetricsAggregator$FrameMetricsApi24Impl.mMetrics> // 138 256:bipush 7 // 139 258:aaload // 140 259:aload_2 // 141 260:iconst_0 // 142 261:invokevirtual #37 <Method long FrameMetrics.getMetric(int)> // 143 264:invokevirtual #41 <Method void FrameMetricsAggregator$FrameMetricsApi24Impl.addDurationItem(SparseIntArray, long)> } if((mTrackingFlags & 0x100) != 0) //* 144 267:aload_0 //* 145 268:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> //* 146 271:getfield #27 <Field int FrameMetricsAggregator$FrameMetricsApi24Impl.mTrackingFlags> //* 147 274:sipush 256 //* 148 277:iand //* 149 278:ifeq 302 { window = ((Window) (FrameMetricsAggregator.FrameMetricsApi24Impl.this)); // 150 281:aload_0 // 151 282:getfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> // 152 285:astore_1 ((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).addDurationItem(((FrameMetricsAggregator.FrameMetricsApi24Impl) (window)).mMetrics[8], framemetrics.getMetric(2)); // 153 286:aload_1 // 154 287:aload_1 // 155 288:getfield #31 <Field SparseIntArray[] FrameMetricsAggregator$FrameMetricsApi24Impl.mMetrics> // 156 291:bipush 8 // 157 293:aaload // 158 294:aload_2 // 159 295:iconst_2 // 160 296:invokevirtual #37 <Method long FrameMetrics.getMetric(int)> // 161 299:invokevirtual #41 <Method void FrameMetricsAggregator$FrameMetricsApi24Impl.addDurationItem(SparseIntArray, long)> } // 162 302:return } final FrameMetricsAggregator.FrameMetricsApi24Impl this$0; { this$0 = FrameMetricsAggregator.FrameMetricsApi24Impl.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #17 <Field FrameMetricsAggregator$FrameMetricsApi24Impl this$0> super(); // 3 5:aload_0 // 4 6:invokespecial #20 <Method void Object()> // 5 9:return } } ; // 11 24:aload_0 // 12 25:new #9 <Class FrameMetricsAggregator$FrameMetricsApi24Impl$1> // 13 28:dup // 14 29:aload_0 // 15 30:invokespecial #48 <Method void FrameMetricsAggregator$FrameMetricsApi24Impl$1(FrameMetricsAggregator$FrameMetricsApi24Impl)> // 16 33:putfield #50 <Field android.view.Window$OnFrameMetricsAvailableListener mListener> mTrackingFlags = i; // 17 36:aload_0 // 18 37:iload_1 // 19 38:putfield #52 <Field int mTrackingFlags> // 20 41:return } }
true
716ad9279ec48e0663ac5372d2c523c63da6f4b6
Java
JoelJosephPaul/fres
/app/src/main/java/com/example/fres/pendingrequests.java
UTF-8
5,213
1.859375
2
[]
no_license
package com.example.fres; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Iterator; public class pendingrequests extends AppCompatActivity { ListView pendreqlistview; DatabaseReference pendbikereff, bikereff,increqbikereff; ValueEventListener pendbikerefflistener; ArrayList<Bike> blist = new ArrayList<>(); String bname,mname; Bike b; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pendingrequests); Bundle bundle = getIntent().getExtras(); final String u = bundle.getString("username"); pendreqlistview = findViewById(R.id.pendreqlistview); bikereff = FirebaseDatabase.getInstance().getReference().child("Bikedata"); pendbikereff = FirebaseDatabase.getInstance().getReference().child("pendingrequest").child(u); increqbikereff = FirebaseDatabase.getInstance().getReference().child("incomingrequest"); pendbikerefflistener = pendbikereff.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();//why different implementation from incoming requests blist.clear(); while (items.hasNext()) { DataSnapshot item = items.next(); b = new Bike(); b.setBikeid(item.getKey()); bikereff.addListenerForSingleValueEvent(new ValueEventListener() {// will repeat so many times bad code, @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { b.setUsername(dataSnapshot.child(b.getBikeid()).child("username").getValue().toString()); b.setBrand(dataSnapshot.child(b.getBikeid()).child("brand").getValue().toString()); b.setModel(dataSnapshot.child(b.getBikeid()).child("model").getValue().toString()); b.setCc(Integer.parseInt(dataSnapshot.child(b.getBikeid()).child("cc").getValue().toString())); b.setYop(Integer.parseInt(dataSnapshot.child(b.getBikeid()).child("yop").getValue().toString())); b.setExtdet(dataSnapshot.child(b.getBikeid()).child("extdet").getValue().toString()); b.setAvail(Integer.parseInt(dataSnapshot.child(b.getBikeid()).child("avail").getValue().toString())); b.setRented(Integer.parseInt(dataSnapshot.child(b.getBikeid()).child("rented").getValue().toString())); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); blist.add(b); } bikelistadapter badapt = new bikelistadapter(pendingrequests.this, R.layout.bikeviewlayout, blist, 0); pendreqlistview.setAdapter(badapt); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); pendreqlistview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { //bname = blist.get(position).getPassword();//bikid //mname = incblist.get(position).getUsername();//username //pendbikereff.child(mname).child(bname).removeValue(); //increqbikereff.child(bname).child(mname).removeValue(); bname = blist.get(position).getBikeid(); pendbikereff.child(bname).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { mname = dataSnapshot.getValue().toString(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); pendbikereff.child(bname).removeValue(); increqbikereff.child(mname).child(bname).removeValue(); return false; } }); } @Override protected void onDestroy() { super.onDestroy(); pendbikereff.removeEventListener(pendbikerefflistener); } }
true
7cea5d787023417b85ba6bbf2f01b682bee4357b
Java
yongjin5184/BaekjoonAlgorithm
/src/Leetcode/PowerOfTwo.java
UTF-8
417
3.5625
4
[]
no_license
package Leetcode; public class PowerOfTwo { public static void main(String[] args) { System.out.println(isPowerOfTwo(1)); System.out.println(isPowerOfTwo(256)); System.out.println(isPowerOfTwo(1/2)); } public static boolean isPowerOfTwo(int n) { if (n <= 0) return false; if (n == 1) return true; return n % 2 == 0 ? isPowerOfTwo(n / 2) : false; } }
true
1acb8b5ea0de56fd2d6a7b9fce1b0714f7efeaab
Java
ant4ded/Anton_Dedik_JavaLab
/Task2/gift_certificates_system/core/src/main/java/com/epam/esm/core/service/InvalidEntityFieldException.java
UTF-8
660
2.140625
2
[]
no_license
package com.epam.esm.core.service; public class InvalidEntityFieldException extends Exception{ public InvalidEntityFieldException() { super(); } public InvalidEntityFieldException(String message) { super(message); } public InvalidEntityFieldException(String message, Throwable cause) { super(message, cause); } public InvalidEntityFieldException(Throwable cause) { super(cause); } protected InvalidEntityFieldException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
true
53d7afc9cfa6cfa6bd44418a4add7d6ebcd204f3
Java
tjp206/exercise_tracker_app
/server/src/main/java/com/example/exercise_tracker/exercise_tracker_app/models/UserWeight.java
UTF-8
1,059
2.484375
2
[]
no_license
package com.example.exercise_tracker.exercise_tracker_app.models; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; import java.time.LocalDate; @Entity @Table(name = "user_weights") public class UserWeight { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private double weight; private LocalDate date; @ManyToOne @JoinColumn(name="user_id", nullable = false) private User user; public UserWeight(double weight, LocalDate date, User user) { this.weight = weight; this.date = date; this.user = user; } public UserWeight() {} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public double getWeight() { return weight; } public void setWeight(Double weight) { this.weight = weight; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } }
true
9d631c1202599a92873740eb4881d4e6b038fa4d
Java
kimhan/tmp-article
/src/kshrd/miniproject/Run.java
UTF-8
3,604
3.265625
3
[]
no_license
package kshrd.miniproject; import java.io.IOException; import java.util.*; import kshrd.raw.*; public class Run { /** * article : array store all record after reading from a file * Pagination : display record in page according to number of record and max row per page * columnPerPage : display column per page */ public static ArrayList<Article> article; static int columnPerPage; /** * main method * @param args */ public static void main(String[] args) { new Run(); } /** * constructor * initialize array list to store all record from file * initialize Pagination for display all record depending on array and max row per page * initialize number of column * start switch case */ @SuppressWarnings("static-access") Run() { article = new ArrayList<Article>(); String []load = {"L", "O", "A", "D", "I", "N", "G"}; try { // addToArticle(10000002); FileMethod.readDataFromFile(); IO.print(Display.whiteSpace(45) + "+ "); for(int i=0;i<load.length;i++) { IO.print(load[i]+""); Thread.currentThread().sleep(500); } IO.println(" +"); } catch(Exception e) { e.printStackTrace(); } columnPerPage = 4; myChoice(); } /** * start switch case */ public static void myChoice() { while(IO.start) { Pagination.displayAllRecord(article); choice(); } } /** * switch case * case 1: move First * case 2: move Next * case 3: move Previous * case 4: move Last * case 5: Read a Record * case 6: Write a record * case 7: search record * case 8: update a record * case 9: delete a record * case g: go to any page * case #: set number of record per page * case 0: exit the program */ public static void choice() { Display.showMenu("<<< Menu >>>", "1:Mover First | 2:Move Next | 3:Move Previous | 4:Move Last", "5:read | 6:write | 7:search | 8:update | 9:delete | G:go to | R:set Row | C:set Column | 0:exit"); int key = IO.readChar("Make your choice: "); switch (key) { case '1': Pagination.moveFirst(article); break; case '2': Pagination.moveNext(article); break; case '3': Pagination.movePrevious(article); break; case '4': Pagination.moveLast(article); break; case '5': Manipulate.performRead(); break; case '6': Manipulate.performWrite(); break; case '7': Manipulate.search(); break; case '8': Manipulate.performUpdate(article, false); IO.println("Successfully updated my friend !!!"); IO.pressEnterContinue(); //Pagination.moveFirst(article); break; case '9': Manipulate.performDelete(article, false); IO.println("Congratulation, Record reset successfully !!!"); IO.pressEnterContinue(); break; case 'G': case 'g': Pagination.numberRecord(IO.readInt("Go to page: ", 0, Pagination.getTotalPage()), article); break; case 'r': case 'R': Pagination.recordPerPage = IO.readInt("Number of Record per page: "); Pagination.moveFirst(article); break; case 'c': case 'C': columnPerPage = IO.readInt("set Colum[2, 4]: ", 2, 4); break; case '0': IO.start = false; break; } } /** * add article to the array * @param numberOfArticle : number of article contain in array */ public void addToArticle(int numberOfArticle) { Article a = new Article(); for(int i=0;i<numberOfArticle;i++) { a.setId(i+1); article.add(article.size(), a); } FileMethod.writeDataIntoFile(article); } }
true
9582ec3c3f1ab49ebc31c2b1d1624e47545c9e77
Java
zerocool947/SpellBookManager
/src/main/java/com/poorfellow/spellbookmanager/ui/fragment/SpellDetailFragment.java
UTF-8
5,201
2.5
2
[]
no_license
package com.poorfellow.spellbookmanager.ui.fragment; import java.util.Map; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.poorfellow.spellbookmanager.R; import com.poorfellow.spellbookmanager.spell.Spell; import com.poorfellow.spellbookmanager.spell.SpellDAO; import com.poorfellow.spellbookmanager.ui.activity.SpellDetailActivity; import com.poorfellow.spellbookmanager.ui.activity.SpellListActivity; /** * A fragment representing a single Spell detail screen. This fragment is either * contained in a {@link SpellListActivity} in two-pane mode (on tablets) or a * {@link SpellDetailActivity} on handsets. */ public class SpellDetailFragment extends Fragment { /** * The fragment argument representing the item ID that this fragment * represents. */ public static final String ARG_ITEM_ID = "item_id"; /** * The dummy content this fragment is presenting. */ private Spell mSpell; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public SpellDetailFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { // Load the dummy content specified by the fragment // arguments. In a real-world scenario, use a Loader // to load content from a content provider. SpellDAO spellDAO = new SpellDAO(this.getActivity()); mSpell = spellDAO.getSpellById(getArguments().getLong(ARG_ITEM_ID)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_spell_detail, container, false); if (mSpell != null) { TextView spellDetail = (TextView) rootView.findViewById(R.id.spell_detail); spellDetail.setText(mSpell.getName() + "\n"); spellDetail.append(Html.fromHtml("<i>" + mSpell.getSchool() + " </i>")); if (mSpell.getSubschool() != null){ spellDetail.append(Html.fromHtml("<i>" + mSpell.getSubschool() + " </i>")); } if (mSpell.getDescriptor() != null) { spellDetail.append(Html.fromHtml("<i>" + mSpell.getDescriptor() + " </i>")); } spellDetail.append("\n"); spellDetail.append(Html.fromHtml("<br /><b>Level: </b>")); Map<String, Integer> levelMap = mSpell.getLevel(); String[] levelMapKeyStrings = (String[]) levelMap.keySet().toArray(new String[0]); for (int i = 0; i < levelMapKeyStrings.length; i++) { spellDetail.append(levelMapKeyStrings[i] + " " + levelMap.get(levelMapKeyStrings[i])); if (i < (levelMapKeyStrings.length - 1)) { spellDetail.append(", "); } } if (mSpell.getComponents() != null) { spellDetail.append(Html.fromHtml("<br /><b>Components: </b>" + mSpell.getComponents())); } if (mSpell.getCastingTime() != null) { spellDetail.append(Html.fromHtml("<br /><b>Casting Time: </b>" + mSpell.getCastingTime())); } if (mSpell.getTarget() != null) { spellDetail.append(Html.fromHtml("<br /><b>Target: </b>" + mSpell.getTarget())); } if (mSpell.getRange() != null) { spellDetail.append(Html.fromHtml("<br /><b>Range: </b>" + mSpell.getRange())); } if (mSpell.getEffect() != null) { spellDetail.append(Html.fromHtml("<br /><b>Effect: </b>" + mSpell.getEffect())); } if (mSpell.getArea() != null) { spellDetail.append(Html.fromHtml("<br /><b>Area: </b>" + mSpell.getArea())); } if (mSpell.getDuration() != null) { spellDetail.append(Html.fromHtml("<br /><b>Duration: </b>" + mSpell.getDuration())); } if (mSpell.getSavingThrow() != null) { spellDetail.append(Html.fromHtml("<br /><b>Saving Throw: </b>" + mSpell.getSavingThrow())); } if (mSpell.getSpellResistance() != null) { spellDetail.append(Html.fromHtml("<br /><b>Spell Resistance: </b>" + mSpell.getSpellResistance())); } spellDetail.append("\n"); Log.d("INFO", "my description is " + mSpell.getDescription()); if (mSpell.getDescription() != null) { spellDetail.append(Html.fromHtml("<br /><b>Description: </b>" + mSpell.getDescription())); } if (mSpell.getMaterialComponent() != null) { spellDetail.append(Html.fromHtml("<br /><b>Material Component: </b>" + mSpell.getMaterialComponent())); } if (mSpell.getArcMaterialComponent() != null) { spellDetail.append(Html.fromHtml("<br /><b>Arcane Material Component: </b>" + mSpell.getArcMaterialComponent())); } if (mSpell.getFocus() != null) { spellDetail.append(Html.fromHtml("<br /><b>Focus: </b>" + mSpell.getFocus())); } if (mSpell.getArcFocus() != null) { spellDetail.append(Html.fromHtml("<br /><b>Arcane Focus: </b>" + mSpell.getArcFocus())); } if (mSpell.getXpCost() != null) { spellDetail.append(Html.fromHtml("<br /><b>XP Cost</b>" + mSpell.getXpCost())); } } return rootView; } }
true
ab35e8eebd07ce5283d8171a17dd69750edc0703
Java
mish6742/p_1_skunk
/SkunkProject/src/skunk/domain/Dice.java
UTF-8
1,186
3.375
3
[]
no_license
package skunk.domain; import java.util.LinkedList; import edu.princeton.cs.introcs.StdOut; public class Dice { private final int DEFAULT_DIE_COUNT = 2; private LinkedList<Die> die; private LinkedList<Integer> lastDiceRoll; public Dice() { die = new LinkedList<>(); for (int i = 0; i < DEFAULT_DIE_COUNT; i++) { die.add(new Die()); } saveLastRoll(); } public Dice(LinkedList<LinkedList<Integer>> rollOrders) { die = new LinkedList<>(); for (int i = 0; i < rollOrders.size(); i++) { die.add(new Die(rollOrders.get(i))); } saveLastRoll(); } public LinkedList<Integer> getLastRoll() { return lastDiceRoll; } private void saveLastRoll() { lastDiceRoll = new LinkedList<>(); for (int i = 0; i < die.size(); i++) { lastDiceRoll.add(die.get(i).getLastRoll()); } } public void roll() { for (int i = 0; i < die.size(); i++) { die.get(i).roll(); } saveLastRoll(); } public String toString() { String returnString = "Dice with last roll: "; for (int i = 0; i < die.size(); i++) { returnString += ((i == 0) ? "" : " + ") + lastDiceRoll.get(i); } return returnString; }}
true
3be80c913184e6548b963a945d2c5974b5f59cc4
Java
xtz9681/designMode
/src/main/java/composite/ConcreteCompany.java
UTF-8
901
3.515625
4
[]
no_license
package composite; import java.util.ArrayList; import java.util.List; /** * desc *组合模式 * 具体枝节点 * @author xutianzhe * @Date 2018/10/9 **/ public class ConcreteCompany extends Company { private List<Company> children = new ArrayList<Company>(); public ConcreteCompany(String name) { super(name); } public void add(Company company) { children.add(company); } public void remove(Company company) { children.remove(company); } public void display(int depth) { String str = "-"; for (int i=0;i<depth;i++){ str+="-" ; } System.out.println(str + name); for (Company component:children){ component.display(depth+2); } } public void lineOfDuty() { for (Company component:children){ component.lineOfDuty(); } } }
true
e41b81a6af29cd26f51491aeb4c43e25ad1e9d60
Java
TanelOrumaa/trivia
/server/src/main/java/server/ClientConnectionBase.java
UTF-8
27,745
2.515625
3
[]
no_license
package server; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import command.*; import configuration.Configuration; import database.DatabaseConnection; import database.QuestionsDatabaseLayer; import database.TriviaSetsDatabaseLayer; import database.UsersDatabaseLayer; import exception.*; import jdk.jshell.spi.ExecutionControl; import lobby.Lobby; import lobby.LobbySerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import question.*; import triviaset.TriviaSet; import triviaset.TriviaSetDeserializerFull; import triviaset.TriviaSetSerializerFull; import triviaset.TriviaSetsSerializerBasic; import user.User; import user.UserSerializer; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.List; public class ClientConnectionBase implements Runnable { // Logger static final Logger LOG = LoggerFactory.getLogger(ClientConnectionBase.class); // Class variables related to socket and database connections. private DatabaseConnection databaseConnection; private Socket socket; private DataInputStream dataInputStream; private DataOutputStream dataOutputStream; private String hash; private String clientId; // User for this client. private User user; // Class variables related to lobby. private Lobby currentLobby; private int lastLobbyUpdateId; private TriviaSet triviaSet; private int previousQuestionIndex; public ClientConnectionBase(Socket socket, DataInputStream dataInputStream, String hash, String clientId) { this.socket = socket; this.dataInputStream = dataInputStream; this.hash = hash; this.clientId = clientId; this.lastLobbyUpdateId = 0; } @Override public void run() { try { LOG.debug(clientId + "Starting thread."); this.databaseConnection = new DatabaseConnection(); LOG.debug("Database connection established for " + clientId); try { // Create the dataoutputstream for the client. dataOutputStream = new DataOutputStream(socket.getOutputStream()); // First acknowledge that we received the hello message and assign them a unique hash. dataOutputStream.writeInt(102); dataOutputStream.writeUTF(this.hash); LOG.debug("Replied to hello message for " + clientId); int messageCode = 0; // And then accept any other incoming messages. while (messageCode != 199) { // Quit message LOG.trace("Trying to read next message from client."); // Check if there are any messages available from client. if (dataInputStream.available() == 0) { // Check if current Lobby wants to send an update to client. if (currentLobby != null && currentLobby.newUpdateAvailable(lastLobbyUpdateId)) { LOG.debug("New update available for lobby."); lastLobbyUpdateId++; LobbyUpdateBase lobbyUpdateBase = currentLobby.getLobbyUpdate(lastLobbyUpdateId); if (lobbyUpdateBase instanceof NewUserConnectedUpdate) { updateLobby((NewUserConnectedUpdate) lobbyUpdateBase); LOG.debug("Updated lobby for this client."); } else if (lobbyUpdateBase instanceof DisplayNextQuestionUpdate) { sendNextQuestionToLobbyClients((DisplayNextQuestionUpdate) lobbyUpdateBase); } else if (lobbyUpdateBase instanceof LobbyDeletedUpdate) { closeLobby((LobbyDeletedUpdate) lobbyUpdateBase); } else if (lobbyUpdateBase instanceof EveryoneAnswered) { everyoneAnswered((EveryoneAnswered) lobbyUpdateBase); } } else { // If no updates from lobby either, sleep for a small amount of time to save CPU resources. Thread.sleep(Configuration.SOCKET_POLL_INTERVAL); } } else { LOG.debug("Reading the next message from " + clientId); messageCode = dataInputStream.readInt(); LOG.debug("Received message " + messageCode + " from " + clientId); handleIncoming(messageCode); } } } catch (IOException e) { LOG.warn(clientId + "Unable to establish input/outputstreams with the client."); e.printStackTrace(); } catch (InterruptedException e) { throw new RuntimeException("Unexpected interrupt.", e); } catch (ExecutionControl.NotImplementedException e) { throw new RuntimeException("Something is not implemented yet.", e); } finally { // Close the socket and connection try { socket.close(); // Should also close both streams. databaseConnection.closeDatabaseConnection(); } catch (IOException e) { LOG.warn(clientId + "Unable to close socket."); } } } catch (SQLException e) { LOG.warn(clientId + "Unable to create database connection."); } } protected void handleIncoming(int code) throws IOException, InterruptedException, ExecutionControl.NotImplementedException { // Check that the hash matches. if (dataInputStream.readUTF().equals(this.hash)) { switch (code) { case 111: // Sync message 1 // The logic here is that the server receives the client message and immediately answers with // server time. Client receives server time and calculates ping (from 111 message send time to // 112 message receive time and finds time delta with clientTime - serverTime - ping / 2. // This sync should happen periodically, but with some sort of decent logic, so messages with // lower ping would be considered more trustworthy (so we don't overwrite the delta with more // incorrect delta). sync(); break; case 121: // Login message // The client sends a log in message with username and password. Server validates the logins and // responds with 122 for successful login or 422 for invalid login data. login(); break; case 123: // Register new user message registerUser(); break; case 131: // Connecting to lobby message. // Reads the lobby code and checks if lobby exists and if it does, can the user join the // lobby. Returns 132 if lobby exists and the user has joined it, 432 if the lobby does not // exist and 434 if the lobby is full. connectToLobby(); break; case 133: // Creating a lobby message. // Creates a new lobby and returns the lobby object to the user. createALobby(); break; case 139: // Start game for this lobby // Notifies all clients in currentLobby that game started and sends the first question id. startGameForLobby(); break; case 145: // Display next question for all players nextQuestionForPlayers(); break; case 191: removePlayerFromLobby(); break; case 201: // Request a question // The client requests a question from the server sendQuestion(); break; case 203: case 205:// User answered question checkAnswer(code == 203); break; case 211: // Fetching list of triviasets for user sendTriviasets(); break; case 213: // Fetching requested triviaset for user sendFullTriviaSet(); break; case 215: // Registering a new triviaset registerTriviaSet(); break; default: // For testing different messages. int paramsAmount = dataInputStream.readInt(); LOG.debug(clientId + " Will send " + paramsAmount + " pieces of data."); String[] params = new String[paramsAmount]; for (int i = 0; i < paramsAmount; i++) { params[i] = dataInputStream.readUTF(); } LOG.debug("Message received. Responding."); dataOutputStream.writeInt(code + 1); dataOutputStream.writeInt(paramsAmount); for (int i = paramsAmount - 1; i >= 0; i--) { dataOutputStream.writeUTF(params[i]); } // Send a request after 5 seconds. This is to test client accepting a message with origin // from server. if (code == 233) { Thread.sleep(5000); dataOutputStream.writeInt(234); dataOutputStream.writeInt(2); dataOutputStream.writeUTF("Next question."); dataOutputStream.writeUTF("Please."); } } } else { LOG.debug(clientId + "Invalid hash from client."); dataOutputStream.writeInt(404); // Invalid hash. } } private void updateLobby(NewUserConnectedUpdate update) throws IOException { LOG.debug("Updating lobby for client " + clientId); // We'll send update only if this user isn't the one who connected to the lobby. if (super.getClass() == PresenterClientConnection.class || update.getUserId() != user.getId()) { Gson gson = new GsonBuilder().registerTypeAdapter(Lobby.class, new LobbySerializer()).create(); String lobbyAsJson = gson.toJson(currentLobby); dataOutputStream.writeInt(136); // Update Lobby message dataOutputStream.writeUTF(hash); dataOutputStream.writeUTF(lobbyAsJson); LOG.debug(clientId + "received a lobby update."); // Wait for the response from client. int responseCode = dataInputStream.readInt(); if (responseCode == 137 && dataInputStream.readUTF().equals(hash)) { LOG.debug(clientId + "updated lobby successfully."); } else { LOG.error(clientId + "was unable to update lobby with error code " + responseCode); } } } private void sendNextQuestionToLobbyClients(DisplayNextQuestionUpdate update) throws IOException { LOG.debug("Sending next question message for client " + clientId); long questionId = update.getQuestionId(); dataOutputStream.writeInt(140); dataOutputStream.writeUTF(hash); dataOutputStream.writeLong(questionId); LOG.debug(clientId + "received next question message."); // Wait for the response from the client. int responseCode = dataInputStream.readInt(); if (responseCode == 141 && dataInputStream.readUTF().equals(hash)) { LOG.debug(clientId + "received next question message."); } else { LOG.error(clientId + "was not able to show next question with error code " + responseCode); } } private void createALobby() throws IOException { LOG.debug(clientId + "Sent a lobby creation message."); int triviasetId = dataInputStream.readInt(); LOG.debug("Creating a lobby for triviaset with id: " + triviasetId + " for user: " + user.getUsername()); Lobby lobby = new Lobby(triviasetId, this.user, Server.generateLobbyCode()); Server.addLobby(lobby); Gson gson = new GsonBuilder().registerTypeAdapter(Lobby.class, new LobbySerializer()).create(); String lobbyAsJson = gson.toJson(lobby); dataOutputStream.writeInt(134); // Connection to lobby successful. dataOutputStream.writeUTF(this.hash); dataOutputStream.writeUTF(lobbyAsJson); currentLobby = lobby; // Fetch triviaset. triviaSet = TriviaSetsDatabaseLayer.readFullTriviaSet(databaseConnection, currentLobby.getTriviaSetId()); LOG.debug(clientId + "Connection to lobby (" + lobby.getCode() + ") succesful."); } private void connectToLobby() throws IOException { LOG.debug(clientId + "Sent a lobby connection message."); int userSubmittedLobbyCode = dataInputStream.readInt(); try { if (Server.isLobbyAvailable(userSubmittedLobbyCode, super.getClass() == PresenterClientConnection.class)) { Lobby lobby; if (super.getClass() == PlayerClientConnection.class) { lobby = Server.addUserToLobby(this.user, userSubmittedLobbyCode); } else { lobby = Server.addPresenterToLobby(userSubmittedLobbyCode); } Gson gson = new GsonBuilder().registerTypeAdapter(Lobby.class, new LobbySerializer()).create(); String lobbyAsJson = gson.toJson(lobby); dataOutputStream.writeInt(132); // Connection to lobby successful. dataOutputStream.writeUTF(this.hash); dataOutputStream.writeUTF(lobbyAsJson); LOG.debug(clientId + "Connection to lobby (" + userSubmittedLobbyCode + ") succesful."); currentLobby = lobby; // Fetch triviaset. triviaSet = TriviaSetsDatabaseLayer.readFullTriviaSet(databaseConnection, currentLobby.getTriviaSetId()); // Updating lobby for all other clients. LOG.debug("Adding a new lobby update for lobby " + currentLobby.getCode() + ""); if (super.getClass() == PlayerClientConnection.class) { currentLobby.addNewLobbyUpdate(new NewUserConnectedUpdate(user.getId())); } } else { LOG.warn(clientId + "This lobby (" + userSubmittedLobbyCode + ") is full."); dataOutputStream.writeInt(434); // Lobby is full. dataOutputStream.writeUTF(hash); } } catch (LobbyDoesNotExistException e) { LOG.warn(clientId + "This lobby (" + userSubmittedLobbyCode + ") does not exist."); dataOutputStream.writeInt(432); // Lobby does not exist. dataOutputStream.writeUTF(hash); } } private void removePlayerFromLobby() throws IOException, ExecutionControl.NotImplementedException { LOG.debug(clientId + "wants to leave current lobby."); int userSubmittedLobbyCode = dataInputStream.readInt(); if (userSubmittedLobbyCode == currentLobby.getCode()) { if (super.getClass() != PresenterClientConnection.class) { if (currentLobby.getLobbyOwnerId() == user.getId()) { // Lobby owner is leaving. currentLobby.addNewLobbyUpdate(new LobbyDeletedUpdate(currentLobby.getCode())); Server.removeLobby(currentLobby); } else { // Some user is leaving the lobby. currentLobby.removeUserFromLobby(user); currentLobby.addNewLobbyUpdate(new NewUserConnectedUpdate(user.getId())); currentLobby = null; } } dataOutputStream.writeInt(192); dataOutputStream.writeUTF(hash); } else { throw new ExecutionControl.NotImplementedException("User trying to leave lobby which isn't current."); } } private void startGameForLobby() throws IOException { LOG.debug(clientId + "sent a start game message."); currentLobby.addNewLobbyUpdate(new DisplayNextQuestionUpdate(triviaSet.getNextQuestion(-1).getQuestionID())); previousQuestionIndex++; // Send response to client. dataOutputStream.writeInt(138); dataOutputStream.writeUTF(hash); LOG.debug("Sent response to " + clientId); } private void nextQuestionForPlayers() throws IOException { long nextQuestionId = dataInputStream.readLong(); currentLobby.addNewLobbyUpdate(new DisplayNextQuestionUpdate(nextQuestionId)); dataOutputStream.writeInt(146); dataOutputStream.writeUTF(hash); LOG.debug("Registered lobby update event to diplay next question for everyone."); } private void closeLobby(LobbyDeletedUpdate lobbyDeletedUpdate) throws IOException { LOG.debug(clientId + "will receive \"lobby closed\" message"); dataOutputStream.writeInt(194); dataOutputStream.writeUTF(hash); dataOutputStream.writeInt(lobbyDeletedUpdate.getLobbyCode()); // Read the response int incomingCode = dataInputStream.readInt(); if (incomingCode == 195) { if (dataInputStream.readUTF().equals(hash)) { if (currentLobby.getCode() == lobbyDeletedUpdate.getLobbyCode()) { currentLobby = null; } } else { LOG.error("Invalid hash from client " + clientId); } } else { LOG.error("Client response was " + incomingCode); } } private void login() throws IOException { LOG.debug(clientId + "sent a login message."); String username = dataInputStream.readUTF(); String password = dataInputStream.readUTF(); try { this.user = UsersDatabaseLayer.validateUser(databaseConnection, username, password); // Serialize the user to return it. Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserSerializer()).create(); String userAsJson = gson.toJson(user); // Acknowledge and send the user. dataOutputStream.writeInt(122); // Login successful. dataOutputStream.writeUTF(this.hash); dataOutputStream.writeUTF(userAsJson); LOG.debug("Login successful, returned user object to " + clientId); } catch (IncorrectLoginInformationException e) { LOG.warn(clientId + "Incorrect login data."); dataOutputStream.writeInt(422); // Incorrect login information. dataOutputStream.writeUTF(this.hash); } } private void registerUser() throws IOException { LOG.debug(clientId + " wants to register new user"); String username = dataInputStream.readUTF(); String password = dataInputStream.readUTF(); String nickname = dataInputStream.readUTF(); try { UsersDatabaseLayer.registerUser(databaseConnection, username, password, nickname); dataOutputStream.writeInt(124); dataOutputStream.writeUTF(this.hash); } catch (UserRegistrationError e) { LOG.warn(clientId + "Failed to register user"); dataOutputStream.writeInt(426); // User registration failed - try again dataOutputStream.writeUTF(this.hash); } catch (UserAlreadyExistsError e) { LOG.warn(clientId + "Failed to register user because username already exists in database"); dataOutputStream.writeInt(424); // User already exists error code dataOutputStream.writeUTF(this.hash); } } private void registerTriviaSet() throws IOException { LOG.debug(clientId + " wants to register new triviaset"); String triviaSetAsJson = dataInputStream.readUTF(); LOG.debug("Trivia sets as Json received: " + triviaSetAsJson); Gson gsonReceive = new GsonBuilder().registerTypeAdapter(TriviaSet.class, new TriviaSetDeserializerFull()).create(); LOG.debug("gsonReceive done"); TriviaSet triviaSet = gsonReceive.fromJson(triviaSetAsJson, TriviaSet.class); LOG.debug("triviaset done"); try { int triviaSetId = TriviaSetsDatabaseLayer.registerTriviaSet(databaseConnection, triviaSet, user.getId()); LOG.debug("Triviaset ID " + triviaSetId + " successfully registered"); LinkedHashMap<Integer, Question> questionList = triviaSet.getQuestionMap(); questionList.forEach(((integer, question) -> QuestionsDatabaseLayer.registerQuestion(databaseConnection, question, triviaSetId))); LOG.debug("Questions successfully registered."); dataOutputStream.writeInt(126); dataOutputStream.writeUTF(this.hash); } catch (AnswerRegistrationError e) { LOG.warn(clientId + "Failed to register answer"); dataOutputStream.writeInt(446); // Answer registration failed dataOutputStream.writeUTF(this.hash); } catch (QuestionRegistrationError e) { LOG.warn(clientId + "Failed to register question"); dataOutputStream.writeInt(444); // Question registration failed dataOutputStream.writeUTF(this.hash); } catch (TriviaSetRegistrationError e) { LOG.warn(clientId + "Failed to register triviaset"); dataOutputStream.writeInt(442); // Triviaset registration failed dataOutputStream.writeUTF(this.hash); } } private void sendQuestion() throws IOException { LOG.debug(clientId + " requests next question"); long previousQuestionId = dataInputStream.readLong(); if (previousQuestionId == -1) { // There was no previous question. // Return first question from trivia set. } try { // For testing TextQuestion testQuestion = new TextQuestion(AnswerType.FREEFORM, 0, false, "Nimeta riik Lõuna-Ameerikas", List.of(new Answer(2L, "Aafrika", false), new Answer(2L, "Ameerika", true)), 1000, 60); Gson gson = new GsonBuilder().registerTypeAdapter(Question.class, new QuestionSerializer()).create(); String questionAsJson = gson.toJson(testQuestion); dataOutputStream.writeInt(202); dataOutputStream.writeUTF(this.hash); dataOutputStream.writeUTF(questionAsJson); } catch (IOException e) { // TODO: FetchingQuestionFromDatabaseError or something LOG.warn(clientId + "Failed to send next question"); dataOutputStream.writeInt(436); dataOutputStream.writeUTF(this.hash); } } private void checkAnswer(boolean isFreeForm) throws IOException { LOG.debug(clientId + "sent user's answer to the question"); long questionId = dataInputStream.readLong(); String answer; if (isFreeForm) { answer = dataInputStream.readUTF(); } else { Long answerId = dataInputStream.readLong(); answer = triviaSet.getQuestionAnswer(questionId, answerId); } try { // Store user's answer boolean lastAnswer = Server.addUsersAnswerToLobby(user, currentLobby, questionId, answer); if (isFreeForm) { dataOutputStream.writeInt(204); } else { dataOutputStream.writeInt(206); } dataOutputStream.writeUTF(this.hash); if (lastAnswer) { currentLobby.addNewLobbyUpdate(new EveryoneAnswered(triviaSet.getNextQuestion(previousQuestionIndex).getQuestionID(), currentLobby.getLobbyOwnerId())); } } catch (AnswerStoringError e){ LOG.warn(clientId + "Failed to store user's answer"); dataOutputStream.writeInt(448); dataOutputStream.writeUTF(this.hash); } } private void everyoneAnswered(EveryoneAnswered everyoneAnswered) throws IOException { LOG.debug("Everyone has answered."); if (everyoneAnswered.getOwnerId() == user.getId()) { dataOutputStream.writeInt(142); dataOutputStream.writeUTF(hash); dataOutputStream.writeLong(everyoneAnswered.getNextQuestionId()); int responseCode = dataInputStream.readInt(); if (responseCode == 143) { if (!hash.equals(dataInputStream.readUTF())) { LOG.error("Invalid hash returned."); } } } } private void sendTriviasets() throws IOException { LOG.debug(clientId + "requests trivia sets."); try { List<TriviaSet> usersTriviaSets = TriviaSetsDatabaseLayer.readUsersTriviaSets(databaseConnection, user.getId()); LOG.debug("User's trivia sets successfully read from database"); Gson gson = new GsonBuilder().registerTypeAdapter(List.class, new TriviaSetsSerializerBasic()).create(); LOG.debug("Gson element done"); String serializedTriviaSetList = gson.toJson(usersTriviaSets); LOG.debug("Trivia sets serialized: " + serializedTriviaSetList); dataOutputStream.writeInt(212); dataOutputStream.writeUTF(this.hash); dataOutputStream.writeUTF(serializedTriviaSetList); } catch (TriviaSetsFetchingError e){ LOG.warn(clientId + "Failed to send trivia sets to user"); dataOutputStream.writeInt(438); dataOutputStream.writeUTF(this.hash); } } private void sendFullTriviaSet() throws IOException { LOG.debug(clientId + "requests full trivia set."); Long triviaSetId = dataInputStream.readLong(); try { TriviaSet triviaSet = TriviaSetsDatabaseLayer.readFullTriviaSet(databaseConnection, triviaSetId); LOG.debug("Successfully fetched trivia set from database"); Gson gson = new GsonBuilder().registerTypeAdapter(TriviaSet.class, new TriviaSetSerializerFull()).create(); String serializedTriviaSet = gson.toJson(triviaSet); LOG.debug("Serialized trivia set"); dataOutputStream.writeInt(214); dataOutputStream.writeUTF(this.hash); dataOutputStream.writeUTF(serializedTriviaSet); } catch (QuestionsFetchingError e){ LOG.debug("Failed to fetch questions for the requested trivia set"); dataOutputStream.writeInt(440); dataOutputStream.writeUTF(this.hash); } } private void sync() throws IOException { LOG.debug(clientId + "Sent a sync message."); long serverTime = System.currentTimeMillis(); dataOutputStream.writeInt(112); // Sync message 2 dataOutputStream.writeUTF(this.hash); dataOutputStream.writeLong(serverTime); LOG.debug("Replied to the sync message for" + clientId); } }
true
758e46e4b64cc3ba8b0234a40ff7c419a70ba6fa
Java
charlieperson/tw101-exercises
/src/main/java/com/thoughtworks/tw101/exercises/exercise7/SecretNumberGenerator.java
UTF-8
391
2.859375
3
[]
no_license
package com.thoughtworks.tw101.exercises.exercise7; import java.util.Random; public class SecretNumberGenerator { private static int number = generate(); public int getNumber() { return number; } private static int generate() { Random randomGenerator = new Random(); int randomInt = randomGenerator.nextInt(100); return randomInt; } }
true
7781a26eb0646cb751a37ad0bf98c7823d9aaeba
Java
DevangJayswal/learning-core-java
/Core Java/src/main/inheritance/multi_level/C.java
UTF-8
135
2.21875
2
[]
no_license
package main.inheritance.multi_level; public class C { int a=4; public void hello() { System.out.println("C.hello"); } }
true
eba33be0275115a8b7089e0cd059a726537433b5
Java
12-dheerajreddy/jdbctemp
/JdbcTempBasicProg/src/com/durgasoft/dao/EmployeeDaoImpl.java
UTF-8
1,214
2.421875
2
[]
no_license
package com.durgasoft.dao; import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import com.durgasoft.dto.Employee; import com.durgasoft.mapper.EmployeeRowMapper; public class EmployeeDaoImpl implements EmployeeDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public String add(Employee emp) { String status=""; try { List<Employee> emp1=jdbcTemplate.query("select * from emp1 where eno="+emp.getEno(), new EmployeeRowMapper()); if(emp1.isEmpty()==true) { int rowcount= jdbcTemplate.update("insert into emp1 values("+emp.getEno()+",'"+emp.getEname()+"',"+emp.getEsal()+",'"+emp.getEaddr()+"')"); if(rowcount==1) { status="employee inserted sucessfully"; } else { status="employee Insertion failure"; } } else { status="employee existed already"; } } catch(Exception e) { e.printStackTrace(); } return status; } @Override public Employee search(int eno) { return null; } @Override public String update(Employee emp) { return null; } @Override public String delete(int eno) { return null; } }
true
917fb8aa61ac82d35a0f08d9400b046b6d48fc02
Java
kijongjo/Nanum-project
/openkitchen/src/main/java/kr/co/openkitchen/dto/MemberDTO.java
UTF-8
1,557
1.875
2
[]
no_license
package kr.co.openkitchen.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @NoArgsConstructor @AllArgsConstructor @ToString public class MemberDTO { int mNo; String mEmail; String mPwd; String mName; String mPhone; int mBirth; int mGender; String mMainSumnail; String mRegdata; String mGrade; int enabled; public int getmNo() { return mNo; } public void setmNo(int mNo) { this.mNo = mNo; } public String getmEmail() { return mEmail; } public void setmEmail(String mEmail) { this.mEmail = mEmail; } public String getmPwd() { return mPwd; } public void setmPwd(String mPwd) { this.mPwd = mPwd; } public String getmName() { return mName; } public void setmName(String mName) { this.mName = mName; } public String getmPhone() { return mPhone; } public void setmPhone(String mPhone) { this.mPhone = mPhone; } public int getmBirth() { return mBirth; } public void setmBirth(int mBirth) { this.mBirth = mBirth; } public int getmGender() { return mGender; } public void setmGender(int mGender) { this.mGender = mGender; } public String getmMainSumnail() { return mMainSumnail; } public void setmMainSumnail(String mMainSumnail) { this.mMainSumnail = mMainSumnail; } public String getmRegdata() { return mRegdata; } public void setmRegdata(String mRegdata) { this.mRegdata = mRegdata; } public String getmGrade() { return mGrade; } public void setmGrade(String mGrade) { this.mGrade = mGrade; } }
true
6657df0d1e0ef168aee9a1881cddef33a4919304
Java
androidx/androidx
/work/work-testing/src/main/java/androidx/work/testing/package-info.java
UTF-8
1,307
1.8125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 The Android Open Source Project * * 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. */ /** * WorkManager Testing is a library for testing app code that runs using WorkManager. * <p> * This testing library provides a way to manually initialize WorkManager for tests by using * {@link androidx.work.testing.WorkManagerTestInitHelper}. Once initialized, you can use * {@link androidx.work.testing.WorkManagerTestInitHelper#getTestDriver(android.content.Context)} to * drive constraints and timing-related triggers for your background work. * <p> * For ease of testing, this library defaults to using a synchronous * {@link java.util.concurrent.Executor}; you can change this in the * {@link androidx.work.Configuration} if you wish. */ package androidx.work.testing;
true
3dbbce9bc210aa2e726e55fecc216f4aa9e82c57
Java
ivv1as/LB1
/lb1task1.java
UTF-8
1,932
3.5
4
[]
no_license
import java.util.Scanner; public class lb1task1 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int a; int flag = 0; do { System.out.println("Введите целое числовое значение а"); while(!s.hasNextInt()) { System.out.println("Введите корректные данные"); s.next(); } a = s.nextInt(); flag =1; } while (flag ==0 ) ; { Scanner z = new Scanner(System.in); int b; int flag2 =0; do { System.out.println("Введите целое числовое значение b"); while(!z.hasNextInt()) { System.out.println("Введите корректные данные"); z.next(); } b = z.nextInt(); flag2 =1; } while (flag2 == 0) ; { Scanner y = new Scanner(System.in); int c; int flag3 =0; do { System.out.println("Введите целое числовое значение c"); while(!y.hasNextInt()) { System.out.println("Введите корректные данные"); y.next(); } c = y.nextInt(); flag3 = 1; } while (flag3 ==0) ; if (c < b && c < a) { System.out.println("c наименьшее"); } if (b < a && b < c) { System.out.println("b наименьшее"); } if (a < c && a < b) { System.out.println("a наименьшее"); } }}}}
true
f913f716fed8edcddb490b5eda1efa1f16670c89
Java
SanchelliosProg/selenium.demo
/src/test/java/com/sanchellios/selenium/demo/RunCucumberTest.java
UTF-8
740
1.875
2
[]
no_license
package com.sanchellios.selenium.demo; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.AfterClass; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions( features = {"src/test/java/com/sanchellios/selenium/demo/features"}, plugin = {"pretty"} , tags = {"@jquery-select-dropdown"} ) public class RunCucumberTest { private static Logger log = LogManager.getLogger(); @AfterClass public static void closeDriver() { log.info("Going to close WebDriver via Hook"); SeleniumWebDriverContext.getInstance().getWebDriver().close(); } }
true
f7ab10c6dd4c8da67bfb109bcf2aa835019ce315
Java
yuandunew/wechatgateway-parent
/wechatgateway-rest/src/main/java/com/yuandu/wechatgateway/rest/dto/GetJSSDKSignatureParams.java
UTF-8
548
1.703125
2
[]
no_license
/** * */ package com.yuandu.wechatgateway.rest.dto; /** * ClassName: GetJSSDKSignatureParams * Function: TODO ADD FUNCTION. * date: 2016年3月21日 下午9:42:26 * 获取JSSDK签名参数 * @version * @since JDK 1.8 * @author <a href="mailto:wanghanchao@lifesense.com">davidwang * Copyright (c) 2016, lifesense.com All Rights Reserved. */ @SuppressWarnings("serial") public class GetJSSDKSignatureParams extends BaseParams { private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
true
deee69522c37dedd0a969859498d0a3b8c3f2654
Java
branotto/MySweeper
/Minesweeper/src/MineSweeper.java
UTF-8
366
2.578125
3
[]
no_license
/** * Driver for MineSweeper * @author Brandon Otto * */ public class MineSweeper { public static void main (String[ ] args) { MineField model = new MineField(); MineSweeperGUI view = new MineSweeperGUI(model); model.setObserver(view); GameController controller = new GameController(model, view); view.setVisible(true); } }
true
637d0e4366219db2d2cd76c93d2ab2fba07b592e
Java
happy6eve/AppPackager
/02_SourceCode/mvp/V1/android/TheForestCityChongqing/app/src/main/java/com/elab/forestcitychongqing/construct/adapter/AssessmentsAdapter.java
UTF-8
1,364
1.976563
2
[]
no_license
package com.elab.forestcitychongqing.construct.adapter; import android.app.Activity; import android.content.Context; import com.elab.forestcitychongqing.R; import com.elab.forestcitychongqing.common.utils.ImageBuilder; import com.elab.forestcitychongqing.construct.model.Assessment; import com.elab.forestcitychongqing.core.ui.CoreAdapter; import com.elab.forestcitychongqing.core.ui.ViewHolder; import java.util.List; /** * Created by master on 2016/12/7. */ public class AssessmentsAdapter extends CoreAdapter<Assessment.PageModelBean.ResultSetBean> { public Context mContext; public AssessmentsAdapter(Activity context, List<Assessment.PageModelBean.ResultSetBean> listDatas, int itemLayoutId) { super(context, listDatas, itemLayoutId); mContext = context; } @Override public void getSMView(int position, final ViewHolder holder, final Assessment.PageModelBean.ResultSetBean data) { holder.setText(R.id.tv_nickname, data.nickname); holder.setText(R.id.tv_content, data.content); holder.setText(R.id.tv_time, data.comment_date); holder.setAvatarImage(mContext, R.id.iv_avatar, ImageBuilder.Create(ImageBuilder.ImageType.Avator, data.customer_head, ImageBuilder.ImageSize.P160)); holder.setRatingBar(R.id.ratingview, data.level); } }
true
078c06517ed1da8d72408319126c5ad755c7e391
Java
AndrewStanton94/APSW_Group_Z
/src/main/java/jim/sums/common/facade/StaffprojectrelationshipFacade.java
UTF-8
897
2.171875
2
[]
no_license
package jim.sums.common.facade; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import jim.sums.common.db.Finalproject; import jim.sums.common.db.Staffprojectrelationship; /** * * @author Sam */ @Stateless public class StaffprojectrelationshipFacade extends AbstractFacade<Staffprojectrelationship>{ @PersistenceContext(unitName = "SUMS2011PU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public StaffprojectrelationshipFacade() { super(Staffprojectrelationship.class); } public List<Staffprojectrelationship> findByProject(Finalproject project) { Query q = em.createNamedQuery("Staffprojectrelationship.findByIdproject"); q.setParameter("finalproject", project); return q.getResultList(); } }
true
417aa0c914d5124703ed3e8835637eef454acb77
Java
xApiOrg/ibanchecker
/src/main/java/com/xapi/model/BankData.java
UTF-8
1,923
2.234375
2
[]
no_license
package com.xapi.model; public class BankData { private String bic; private String branch; private String bank; private String address; private String city; private String state; private String zip; private String phone; private String fax; private String www; private String email; private String country; private String country_iso; private String account; public BankData() { } public BankData(String bic, String branch, String bank, String address, String city, String state, String zip, String phone, String fax, String www, String email, String country, String country_iso, String account) { this.bic = bic; this.branch = branch; this.bank = bank; this.address = address; this.city = city; this.state = state; this.zip = zip; this.phone = phone; this.fax = fax; this.www = www; this.email = email; this.country = country; this.country_iso = country_iso; this.account = account; } public String getBic() { return bic; } public String getBranch() { return branch; } public String getBank() { return bank; } public String getAddress() { return address; } public String getCity() { return city; } public String getState() { return state; } public String getZip() { return zip; } public String getPhone() { return phone; } public String getFax() { return fax; } public String getWww() { return www; } public String getEmail() { return email; } public String getCountry() { return country; } public String getCountry_iso() { return country_iso; } public String getAccount() { return account; } }
true
c981d698547acca3f7967a3644a3b6e36b4077e4
Java
f3226912/gd
/gd-home-service/src/main/java/com/gudeng/commerce/gd/home/util/systemlog/MemberBaseinfoAopUtil.java
UTF-8
3,061
2.015625
2
[]
no_license
package com.gudeng.commerce.gd.home.util.systemlog; import java.net.MalformedURLException; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.caucho.hessian.client.HessianProxyFactory; import com.gudeng.commerce.gd.home.util.GdProperties; import com.gudeng.commerce.gd.authority.sysmgr.entity.SysRegisterUser; import com.gudeng.commerce.gd.customer.dto.MemberBaseinfoDTO; import com.gudeng.commerce.gd.customer.entity.MemberBaseinfoEntity; import com.gudeng.commerce.gd.supplier.entity.SystemLogEntity; import com.gudeng.commerce.gd.supplier.enums.SystemLogTypeEnum; import com.gudeng.commerce.gd.supplier.service.SystemLogService; @Aspect @Component public class MemberBaseinfoAopUtil { @Autowired public GdProperties gdProperties; private static SystemLogService systemLogService; /** * 功能描述:日志服务 * * @param * @return */ protected SystemLogService getHessianSystemLogService() throws MalformedURLException { String url = gdProperties.getSystemLogUrl(); if (systemLogService == null) { HessianProxyFactory factory = new HessianProxyFactory(); factory.setOverloadEnabled(true); systemLogService = (SystemLogService) factory.create( SystemLogService.class, url); } return systemLogService; } @AfterReturning(pointcut = "execution(* com.gudeng.commerce.gd.home.service.impl.MemberBaseinfoToolServiceImpl.updateMemberBaseinfoDTO(com.gudeng.commerce.gd.customer.dto.MemberBaseinfoDTO))") public void updateMemberBaseinfoDTO(JoinPoint jp) { Object[] objects = jp.getArgs(); MemberBaseinfoDTO memberBaseinfoDTO = (MemberBaseinfoDTO) objects[0]; try { String content = ""; if(null == memberBaseinfoDTO.getPassword() ){ content= "id为" + memberBaseinfoDTO.getMemberId() + "的用户在web端修改了个人信息,修改后,姓名为:"+ memberBaseinfoDTO.getRealName()+",手机号为:"+memberBaseinfoDTO.getMobile(); }else{ content= "id为" + memberBaseinfoDTO.getMemberId() + "的用户在web端修改了密码,修改后,密码为:"+memberBaseinfoDTO.getPassword(); } SystemLogEntity entity = new SystemLogEntity(); entity.setChennel("2"); entity.setContent(content); entity.setCreateTime(new Date()); entity.setCreateUserId(String.valueOf(memberBaseinfoDTO.getMemberId())); entity.setType(SystemLogTypeEnum.MEMBER.getKey()); entity.setOperationId(memberBaseinfoDTO.getMemberId()); getHessianSystemLogService().insertLog(entity); } catch (MalformedURLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
true
56734da1a3475752181842f3274a537cb1b67a5b
Java
autentia/randomvos
/src/main/java/com/autentia/randomvos/ExtendedRandomUtils.java
UTF-8
2,718
3.234375
3
[ "Apache-2.0" ]
permissive
package com.autentia.randomvos; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * Utility methods. */ public final class ExtendedRandomUtils { private ExtendedRandomUtils() { // Empty. } /** * Gets all fields declared by a class and its superclasses. * * @param type the class. * @return the list of fields. */ public static List<Field> getFields(final Class<?> type) { List<Field> result = new ArrayList<>(); for (Class current = type; current != Object.class; current = current.getSuperclass()) { Field[] fields = current.getDeclaredFields(); for (Field field: fields) { if (!Modifier.isFinal(field.getModifiers()) && !field.isSynthetic()) { result.add(field); } } } return result; } /** * Tries to resolve a type to a concrete class. * * @param type the type to resolve. * @return the class instance represented by the given type; null if it cannot be found. */ public static Class<?> resolve(Type type) { if (type instanceof Class) { return (Class<?>) type; } if (type instanceof ParameterizedType) { return resolve(((ParameterizedType) type).getRawType()); } // TODO: Handle GenericArrayType. return null; } /** * Changes accessibility of the given list of fields. * * @param fields a list of fields. */ public static void setAccesible(final List<Field> fields) { for (Field field: fields) { field.setAccessible(true); } } /** * Shallow copy of an instance of a class. * * @param <T> the type of the objects. * @param type the class of the objects. * @param prototype the prototype object to copy from. * @return a new instance where all fields have the same value as the prototype. */ public static <T> T copyPrototype(final Class<T> type, final T prototype) { try { T result = type.newInstance(); List<Field> fields = ExtendedRandomUtils.getFields(type); ExtendedRandomUtils.setAccesible(fields); for (Field field: fields) { field.set(result, field.get(prototype)); } return result; } catch (InstantiationException | IllegalAccessException e) { throw new IllegalArgumentException("Cannot create instance of class " + type.getName()); } } }
true
7e47655f8d78a7ea009dc6399a852615bd9d3cad
Java
zyxdSTU/LearningWord
/app/src/main/java/fragment/IOFragment.java
UTF-8
4,794
1.992188
2
[]
no_license
package fragment; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.Toast; import com.github.angads25.filepicker.controller.DialogSelectionListener; import com.github.angads25.filepicker.model.DialogConfigs; import com.github.angads25.filepicker.model.DialogProperties; import com.github.angads25.filepicker.view.FilePickerDialog; import com.leon.lfilepickerlibrary.LFilePicker; import com.leon.lfilepickerlibrary.utils.Constant; import java.io.File; import java.util.List; import activity.R; import db.DataBaseUtil; import db.LearningWordDatabaseHelper; import javabean.Instance; import javabean.Word; import util.Util; import static android.app.Activity.RESULT_OK; public class IOFragment extends Fragment { private ImageButton imageButton; private SQLiteDatabase db; int REQUESTCODE_FROM_ACTIVITY = 1000; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_io, container, false); imageButton = view.findViewById(R.id.input_image_button); SQLiteOpenHelper dbHelper = new LearningWordDatabaseHelper(getContext(), "LearningWord.db", null, 1); db = dbHelper.getWritableDatabase(); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogProperties properties = new DialogProperties(); properties.selection_mode = DialogConfigs.SINGLE_MODE; properties.selection_type = DialogConfigs.FILE_SELECT; properties.root = new File(DialogConfigs.DEFAULT_DIR); properties.error_dir = new File(DialogConfigs.DEFAULT_DIR); properties.offset = new File(DialogConfigs.DEFAULT_DIR); properties.extensions = null; FilePickerDialog dialog = new FilePickerDialog(getActivity(),properties); dialog.setTitle("Select a File"); dialog.show(); Log.d("Debug", Environment.getExternalStorageDirectory().getAbsolutePath()); dialog.setDialogSelectionListener(new DialogSelectionListener() { @Override public void onSelectedFilePaths(String[] files) { try { String element = ""; for (String fileName : files) { Log.d("Debug", fileName); List<String> lines = Util.read(fileName); for(int i = 0; i < lines.size(); i++) { element = lines.get(i).replaceAll("\r|\n", ""); String[] strArr = element.split("\t"); String Part = strArr[0]; String Chapter = strArr[1]; String Word = strArr[2]; String WordTranslation = strArr[3]; String Example = strArr[4]; String ExampleTranslation = strArr[5]; //Log.d("Debug", ExampleTranslation); String chapterName = DataBaseUtil.selectChapter(db, Part, Chapter); javabean.Word word = new Word(); word.setWord(Word); word.setWordTranslation(WordTranslation); word.setChapter(Chapter); word.setChapterName(chapterName); DataBaseUtil.insertWord(db, word); Instance instance = new Instance(word); instance.setExample(Example); instance.setExampleTranslation(ExampleTranslation); DataBaseUtil.insertInstance(db, instance); } } }catch(Exception e) { Log.d("Debug", e.getMessage()); e.printStackTrace(); } } }); } }); return view; } }
true
3db1b107607e24a999bc3adbe1f343fa25c3d5a4
Java
twang2218/material-design-toolkit
/lib/src/main/java/org/lab99/mdt/utils/Utils.java
UTF-8
965
2.671875
3
[ "Apache-2.0" ]
permissive
package org.lab99.mdt.utils; import android.content.Context; import android.util.DisplayMetrics; import android.util.TypedValue; /** * Utility class */ public final class Utils { /** * Get the pixel value from given Dip value. * * @param context The {@link Context} object. * @param dip The Dip value. * @return Return the pixel value. */ public static float getPixelFromDip(Context context, float dip) { DisplayMetrics metrics; if (context != null) { metrics = context.getResources().getDisplayMetrics(); } else { // On some devices which 'ro.sf.lcd_density' is missing, then 'sMetrics' is invalid. // In such case, just assume it's 'xhdpi', better then nothing or exception. metrics = new DisplayMetrics(); metrics.density = 2; } return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, metrics); } }
true
3b84743efba484504e73ea6ab8279e6f349c79f9
Java
Storen123/Happy-Go
/新版桃園快樂遊/2/app/src/main/java/com/example/storen123/a2/yaya4.java
UTF-8
2,256
2.46875
2
[]
no_license
package com.example.storen123.a2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Adapter; import android.widget.ListView; import java.util.ArrayList; public class yaya4 extends AppCompatActivity { ListView movie_list =null; private ArrayList<Movie>movies; private MovieAdapter adapter = null ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_yaya4); movie_list = findViewById(R.id.movie_list); movies = new ArrayList<Movie>(); movies.add(new Movie(R.mipmap.hu,"桃園虎頭山環保公園" ,"電話03-3354757", "地址:桃園市桃園區成功路三段"," 虎頭山環保公園原是桃園市的舊垃\n圾掩埋場,佔地2.5公頃,經規劃\n後打造成一座綠地公園,園區內設\n有景觀涼亭、望遠鏡,大草坪體能\n等設施,一旁有露天式咖啡可以坐\n著享用,是大桃園地區欣賞黃昏落\n日及夜景相當受歡迎的好去處,尤\n其擁有絕佳夜色美景,故有著「星\n星公園」的別稱。")); movies.add(new Movie(R.mipmap.peace1,"桃園忠烈祠暨神社文化園區" ,"電話03-3325215", "地址:桃園市桃園區成功路三段200號"," 座落於虎頭山上的桃園市忠烈祠,\n前身為日本人所建造的「桃園神社\n」,是臺灣保存最為完整的日治時\n代神社,建築風格融合了中國古代\n唐風、" + "日本風及臺灣近代風,採用\n上等台灣檜木構築,並已在民國八\n十三年經公告正式被列為國家三級\n古蹟。")); movies.add(new Movie(R.mipmap.article,"桃園藝文展演中心" ,"電話03-3170511", "地址:桃園市桃園區中正路1188號"," 2010年落成的桃園展演中心兼\n具表演藝術、展覽、娛樂等多元功\n能之現代環保綠建築,由綠野國際\n建築師事務所的許伯元建築師所設\n計,該建築曾榮獲內政部「100年公\n共建築物無障礙優良作品優等獎」。")); adapter = new MovieAdapter(this ,movies); movie_list.setAdapter(adapter); } }
true
6a2f0b02ce2dbc767a11c402f8687bbbcaa029d2
Java
dvinay/Ser-DeSerProject
/SerializableExample/src/com/source/StudentInfo.java
UTF-8
485
2.484375
2
[]
no_license
package com.source; import java.io.Serializable; public class StudentInfo implements Serializable { private static final long serialVersionUID = 1L; public String name; public int rid; public static String contact; public StudentInfo(String n, int r, String c) { this.name = n; this.rid = r; StudentInfo.setContact(c); } public static String getContact() { return contact; } public static void setContact(String contact) { StudentInfo.contact = contact; } }
true
bcb61b39c84cb75acf09c6d6628b9816b83861e5
Java
sheguohua0228/idea
/app-common/src/main/java/com/leyes/app/exceptions/MallException.java
UTF-8
576
2.421875
2
[]
no_license
package com.leyes.app.exceptions; public class MallException extends CustomException { /** * @Fields serialVersionUID : TODO */ private static final long serialVersionUID = 1000001L; public MallException() { super(); } public MallException(String message) { super(message); } public MallException(Throwable innerException){ super(innerException); } public MallException(String message,Throwable innerException){ super(message,innerException); } public MallException(String message, Object... args) { super(String.format(message, args)); } }
true
ae340668a4a0e1fb83d74f1893f77bf410d9ca36
Java
sengeiou/TaoBaoKe-3
/app/src/main/java/com/bestsoft/mvp/contract/ExtractContract.java
UTF-8
596
1.984375
2
[]
no_license
package com.bestsoft.mvp.contract; import com.bestsoft.bean.ExtractModel; import com.bestsoft.common.https.BasePresenter; import com.bestsoft.common.https.IBaseView; /** * @package: com.bestsoft.mvp.contract * @user:xhkj * @date:2018/10/29 * @description: **/ public interface ExtractContract { interface View extends IBaseView { void setUserExtract(ExtractModel models); void showError(Throwable throwable); } abstract class Presenter extends BasePresenter<View> { public abstract void getUserExtract(String user_id, String user_channel_id); } }
true
09ddb4fc740189fbc6ddf4772ca4484b7da66d42
Java
Quantum64/BungeeChatPlus
/src/main/java/com/gmail/favorlock/bungeechatplus/entities/Chatter.java
UTF-8
2,608
2.5625
3
[]
no_license
package com.gmail.favorlock.bungeechatplus.entities; import com.gmail.favorlock.bungeechatplus.config.ChatterStorage; import java.util.ArrayList; import java.util.List; public class Chatter { private final ChatterStorage storage; private final String name; private boolean verbose; private Channel activeChannel; private List<Channel> channels; private String prefix; private String suffix; public Chatter(String name, ChatterStorage storage) { this.storage = storage; this.name = name; this.activeChannel = storage.getPlugin().getChannelManager().getChannel(storage.ActiveChannel); if (this.channels == null) { this.channels = new ArrayList<Channel>(); } if (!storage.Channels.isEmpty()) { this.channels = storage.getPlugin().getChannelManager().getChannels(storage.Channels); } else { setActiveChannel(storage.getPlugin().getChannelManager().defaultChannel); } } public String getName() { return this.name; } public void setVerbose() { this.verbose = !verbose; } public void setVerbose(boolean bool) { this.verbose = bool; } public boolean getVerbose() { return this.verbose; } public boolean setActiveChannel(Channel channel) { if (!this.channels.contains(channel)) { addChannel(channel); channel.addChatter(this); } if (this.activeChannel != channel) { this.activeChannel = channel; return true; } return false; } public boolean addChannel(Channel channel) { if (!channels.contains(channel)) { channels.add(channel); channel.addChatter(this); return true; } return false; } public boolean removeChannel(Channel channel) { if (channels.contains(channel)) { channels.remove(channel); if (channel.equals(activeChannel)) { if (channels.size() > 0) { setActiveChannel(channels.get(0)); } else { setActiveChannel(storage.getPlugin().getChannelManager().defaultChannel); } } return true; } return false; } public Channel getActiveChannel() { return this.activeChannel; } public void setChannels(List<Channel> channels) { this.channels = channels; } public List<Channel> getChannels() { return this.channels; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getPrefix() { return this.prefix; } public void setSuffix(String suffix) { this.suffix = suffix; } public String getSuffix() { return this.suffix; } public ChatterStorage getChatterStorage() { return this.storage; } }
true
1b660843ea3844c00c878a03408c3580a4da859b
Java
damonchen6886/Diglett_chat_App
/src/test/java/com/neu/prattle/exceptions/ChatNotExistExceptionTest.java
UTF-8
630
2.234375
2
[]
no_license
package com.neu.prattle.exceptions; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.*; public class ChatNotExistExceptionTest { @Test public void test1() { ChatNotExistException e = new ChatNotExistException("not exist"); Assert.assertEquals("not exist", e.getMessage()); } @Test public void test2() { GroupNotExistException e = new GroupNotExistException("."); Assert.assertEquals(".", e.getMessage()); } @Test public void test3() { UserAlreadyInGroupException e = new UserAlreadyInGroupException(".."); Assert.assertEquals("..", e.getMessage()); } }
true
7077db1d6daa5466f266df037c338e95df5fd4e5
Java
ToureNPlaner/tourenplaner-android
/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/ClientSideCompute/NullGraph.java
UTF-8
1,464
2.28125
2
[]
no_license
/* * Copyright 2012 ToureNPlaner * * 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 de.uni.stuttgart.informatik.ToureNPlaner.ClientSideCompute; /** * Created with IntelliJ IDEA. * User: niklas * Date: 9/29/12 * Time: 9:22 PM * To change this template use File | Settings | File Templates. */ public class NullGraph implements SimpleGraph{ @Override public final int getDist(int edgeId) { return -1; } @Override public final int getEdgeCount() { return 0; } @Override public final int getNodeCount() { return 0; } @Override public final int getOutEdgeCount(int nodeId) { return -1; } @Override public final int getOutEdgeId(int nodeId, int edgeNum) { return -1; } @Override public final int getSource(int edgeId) { return -1; } @Override public final int getTarget(int edgeId) { return -1; } @Override public final boolean hasNode(int nodeId){ return false; } }
true
e2445a7fb0987e6c3b055155c798c584a18df6b0
Java
opticyclic/jide-examples
/examples/Demo/DemosDockableFrame.java
UTF-8
23,640
1.734375
2
[]
no_license
/* * @(#)DemosDockableFrame.java 2/5/2012 * * Copyright 2002 - 2012 JIDE Software Inc. All rights reserved. */ import com.jidesoft.action.CommandBar; import com.jidesoft.docking.DockContext; import com.jidesoft.docking.DockableFrame; import com.jidesoft.navigation.NavigationTree; import com.jidesoft.status.ProgressStatusBarItem; import com.jidesoft.swing.*; import com.jidesoft.tree.QuickTreeFilterField; import com.jidesoft.tree.TreeUtils; import com.jidesoft.utils.ProductNames; import com.jidesoft.utils.SystemInfo; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.text.Position; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.MessageFormat; import java.util.Collections; import java.util.Vector; /** */ class DemosDockableFrame extends DockableFrame { private Vector<ComparableTreeNode> _demos = new Vector<ComparableTreeNode>(); private int _order; // 0 or 1 private JideDemos _demoHolder; public Color getTabBackground() { Container parent = getParent(); if (parent != null && ((JideTabbedPane) parent).getSelectedComponent() == this) return Color.RED; return Color.GREEN; } static final String[] DEMOS = new String[]{ // Common "JideBorderLayoutDemo", "JideBoxLayoutDemo", "BorderDemo", "TitledSeparatorDemo", "JideButtonDemo", "JideSplitButtonDemo", "JideLabelDemo", "JideSplitPaneDemo", "JideTabbedPaneDemo", "JideScrollPaneDemo", "SimpleScrollPaneDemo", "MarqueePaneDemo", "TristateCheckBoxDemo", "StyledLabelDemo", "WrapStyledLabelDemo", "StyledLabelBuilderDemo", "StyledLabelPerformanceDemo", "RangeSliderDemo", "CheckBoxListDemo", "CheckBoxTreeDemo", "AutoResizingTextAreaDemo", "FolderChooserDemo", "SearchableDemo", "SearchableBarDemo", "AutoCompletionDemo", "IntelliHintsDemo", "PopupDemo", "OverlayableDemo", // Dock "DockDemo", "TwoDockDemo", "InitialLayoutDockDemo", "HeavyweightDockDemo", // Components "DocumentPaneDemo", "StatusBarDemo", "CollapsiblePaneDemo", "FloorTabbedPaneDemo", "OutlookTabbedPaneDemo", "AlertDemo", "BalloonTipDemo", "ExpandedTipDemo", "NavigationTreeDemo", "NavigationListDemo", "NavigationTableDemo", "BreadcrumbBarDemo", // Action "SampleVsnetDemo", "SampleWordDemo", "ThreeActionDemo", // Grids "JideTableDemo", "AutoResizeModeDemo", "ResizableTableDemo", "UndoableTableDemo", "TableUtilsDemo", "SortableTableDemo", "LargeSortableTableDemo", "SortableListDemo", "UndoableListDemo", "SortableComboBoxDemo", "SortableTreeDemo", "TableSortItemEditorDemo", "FilterableTableDemo", "CustomFilterDemo", "QuickFilterTableDemo", "QuickFilterListDemo", "QuickFilterCheckBoxListDemo", "QuickFilterComboBoxDemo", "QuickFilterTreeDemo", "LuceneQuickFilterTableDemo", "LuceneQuickFilterListDemo", "EditableTableHeaderDemo", "CheckBoxTableDemo", "HeaderStyleTableDemo", "StyledLabelTableHeaderDemo", "AutoFilterTableHeaderDemo", // "AutoFilterTableHeaderWithInputDemo", // remove this demo because it doesn't use the native header "AutoFilterTreeTableDemo", "ShrinkSearchableDemo", "CachedTableModelDemo", "TransposeTableModelDemo", "MarkerSupportDemo", "MarginSupportDemo", "HyperlinkCellDemo", "AbstractNavigableTableDemo", "ContextSensitiveTableDemo", "NonContiguousTableDemo", "PropertyPaneDemo", "PropertyPaneEditorContextDemo", "TradingHierarchicalTableDemo", "ProgramHierarchicalTableDemo", "HierarchicalTableDemo", "FileSystemTreeTableDemo", "GroupTableDemo", "BeanTableDemo", "DefaultSpanTableDemo", "AbstractSpanTableDemo", "AutoCellMergeTableDemo", "AbstractStyleTableDemo", "GradientStyleTableDemo", "StripesTableDemo", "CustomizedCellStyleTableDemo", "CellUnderlayOverlayDemo", "TableFlashableDemo", "CustomStyleDemo", "TableScrollPaneDemo", "TreeTableScrollPaneDemo", "TableSplitPaneDemo", "FontGroupListDemo", "IconGroupListDemo", "DualListDemo", "DualTableDemo", "TextFieldListDemo", "ExComboBoxDemo", "CalculatorDemo", "DateComboBoxDemo", "DateChooserDemo", "MonthChooserDemo", "CalendarViewerDemo", "ColorChooserDemo", "ComboBoxDemo", "DirectionChooserDemo", "DirectionPropertyPaneDemo", "ConverterDemo", "DateSpinnerDemo", "PointSpinnerDemo", "ImagePreviewListDemo", "IPTextFieldDemo", "CreditCardTextFieldDemo", // Pivot "PivotTableDemo", "CalculatedPivotTableDemo", "PivotValueProviderDemo", "CalculatedTableModelDemo", "MultipleColumnSummaryDemo", "WeightedAverageDemo", "AggregateTableDemo", // Data "PageNavigationBarDemo", "DatabaseTableModelDemo", "DatabasePageTableModelDemo", // "HibernateTableModelDemo", // "HibernatePageTableModelDemo", // Dialogs "WizardDemo", "OptionsDialogDemo", "TipsOfTheDayDemo", "ButtonPanelDemo", "BannerPanelDemo", "StandardDialogDemo", "JideOptionPaneDemo", // Shortcut "ShortcutEditorDemo", // CodeEditor "CodeEditorDemo", "CodeEditorDocumentPaneDemo", "PhpSyntaxParsingDemo", // FeedReader "FeedReaderDemo", // Dashboard "CollapsiblePaneDashboardDemo", "DockableFrameDashboardDemo", "CollapsiblePaneDashboardDocumentPaneDemo", "RegularPanelDashboardDemo", "PredefinedLayoutDashboardDemo", "TreePaletteDashboardDemo", // Charts "ConfigurableChartDemo", "PieChartDemo", "DifferentViewsDemo", "RainfallChartDemo", "TemperaturesChartDemo", "SunshineChartDemo", "CategoricalChartDemo", "ConfigurableBarChartDemo", "CubicSplinesChartDemo", "DualYAxisBarChartDemo", "InteractiveChartDemo", "LogarithmDemo", "LineChartDemo", "GradientLineFillDemo", "WithImagesChartDemo", "DynamicChartDemo", "ScatterChartDemo", "MeterDemo", "LineFittingChartDemo", "ScalabilityDemo", "CyclicalChartDemo", "BubbleChartDemo", "CandleStickDemo", "MultiChartDemo", "MarkerDemo", "StackedAreaChartDemo", "TableAdapterDemo", "ScrollableBarChartDemo", "PannableBarChartDemo", "DifferenceChartDemo", "MorphingLineDemo", "MorphingBarDemo", "NotRaphaelDemo", "ChessBoardDemo", "StepChartDemo", "SparklinesDemo", "TransparentChartDemo", "StatisticalBarsDemo", "PopulationPyramidDemo", "GroupedAndStackedDemo", "MemoryDialDemo", "ClockDemo", // Gantt Charts "GanttChartDemo", "GanttChartPaneDemo", "NumberGanttChartDemo", "ProjectGanttChartDemo", // Diff "DiffPaneDemo", "MergePaneDemo", "TableDiffPaneDemo", "TreeTableDiffPaneDemo", }; private JTree _tree; private JButton _openButton; protected QuickTreeFilterField _field; public DemosDockableFrame(String key, JideDemos demos) { super(key, DemoIconsFactory.getImageIcon(DemoIconsFactory.Frame.DEMO)); setTitle(Resource.RB.getString("Demo.demo")); _demoHolder = demos; getContext().setInitSide(DockContext.DOCK_SIDE_WEST); setPreferredSize(new Dimension(200, 200)); loadDemos(); initComponents(); setDefaultFocusComponent(_field.getTextField()); } protected JideButton createButton(Action action) { JideButton button = new JideButton(action); button.setFocusable(false); button.setRequestFocusEnabled(false); return button; } protected JideButton createToggleButton(Action action) { JideButton button = new JideToggleButton(action); button.setFocusable(false); button.setRequestFocusEnabled(false); return button; } protected JComponent createToolBar() { CommandBar toolBar = new CommandBar(); toolBar.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); toolBar.setFloatable(false); toolBar.setStretch(true); toolBar.setPaintBackground(false); toolBar.setChevronAlwaysVisible(false); JButton categoryViewButton = createToggleButton(new AbstractAction("", DemoIconsFactory.getImageIcon(DemoIconsFactory.Tree.TREE)) { private static final long serialVersionUID = 6174457687626496602L; public void actionPerformed(ActionEvent e) { _order = 0; TreeModel model = reloadTreeModel(_order); _field.setTreeModel(model); _tree.setModel(_field.getDisplayTreeModel()); _field.applyFilter(); expandAll(model); } }); categoryViewButton.setToolTipText(Resource.RB.getString("Demo.sortCategorized")); toolBar.add(categoryViewButton); JButton alphabetViewButton = createToggleButton(new AbstractAction("", DemoIconsFactory.getImageIcon(DemoIconsFactory.Tree.SORT)) { private static final long serialVersionUID = 6073930856511015109L; public void actionPerformed(ActionEvent e) { _order = 1; TreeModel model = reloadTreeModel(_order); _field.setTreeModel(model); _tree.setModel(_field.getDisplayTreeModel()); _field.applyFilter(); } }); alphabetViewButton.setToolTipText(Resource.RB.getString("Demo.sortAlphabetically")); toolBar.add(alphabetViewButton); if (_order == 0) { categoryViewButton.setSelected(true); } else { alphabetViewButton.setSelected(true); } ButtonGroup group = new ButtonGroup(); group.add(categoryViewButton); group.add(alphabetViewButton); CommandBar.Expansion expansion = new CommandBar.Expansion(); expansion.setLayout(new BorderLayout(0, 0)); expansion.add(_field); toolBar.add(expansion); return toolBar; } public void openSelectedDemo() { TreePath path = _tree.getSelectionPath(); if (path != null) { Object node = path.getLastPathComponent(); openDemo(node); } } protected void initComponents() { TreeModel model = reloadTreeModel(_order); _field = new QuickTreeFilterField() { @Override public void applyFilter() { super.applyFilter(); TreeUtils.expandAll(_tree); } }; _field.setHintText(Resource.RB.getString("Demo.filter")); _field.setMatchesLeafNodeOnly(true); _field.setHideEmptyParentNode(true); _field.setWildcardEnabled(true); _field.setTreeModel(model); _tree = SystemInfo.isJdk6Above() ? new NavigationTree(_field.getDisplayTreeModel()) { @Override public TreePath getNextMatch(String prefix, int startingRow, Position.Bias bias) { return null; } } : new JTree(_field.getDisplayTreeModel()) { @Override public TreePath getNextMatch(String prefix, int startingRow, Position.Bias bias) { return null; } }; _tree.registerKeyboardAction(new AbstractAction() { private static final long serialVersionUID = -7647825587470936818L; public void actionPerformed(ActionEvent e) { openSelectedDemo(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED); TreeSearchable searchable = SearchableUtils.installSearchable(_tree); searchable.setFromStart(false); _tree.setCellRenderer(new DemoCellRenderer()); _tree.setRootVisible(false); _tree.setShowsRootHandles(true); TreeUtils.expandAll(_tree); _tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { updateOpenButton(); } }); updateOpenButton(); _tree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) { TreePath path = _tree.getSelectionPath(); if (path != null) { Object node = path.getLastPathComponent(); openDemo(node); } } } }); JPanel panel = new JPanel(new BorderLayout(2, 2)); panel.setBorder(BorderFactory.createEmptyBorder(0, 3, 2, 3)); _tree.setBorder(BorderFactory.createEmptyBorder(0, 3, 2, 2)); panel.add(createToolBar(), BorderLayout.BEFORE_FIRST_LINE); JideScrollPane scrollPane = new JideScrollPane(_tree); scrollPane.setRequestFocusEnabled(false); panel.add(scrollPane, BorderLayout.CENTER); getContentPane().add(panel); } private void updateOpenButton() { if (_openButton == null) { return; } if (_tree.getSelectionPath() != null) { _openButton.setEnabled(true); } else { _openButton.setEnabled(false); } } private void expandAll(TreeModel model) { if (_order == 0) { for (int i = 0; i < ((ComparableTreeNode) model.getRoot()).getChildCount(); i++) { _tree.expandPath(new TreePath(new Object[]{model.getRoot(), ((ComparableTreeNode) model.getRoot()).getChildAt(i)})); } } } /** * Loads tree into TreeModel * * @param order the order * @return TreeModel */ private TreeModel reloadTreeModel(int order) { ComparableTreeNode root = new ComparableTreeNode(Resource.RB.getString("Demo.allProducts")); if (order == 0) { ComparableTreeNode nodeCommon = new ComparableTreeNode(ProductNames.PRODUCT_NAME_COMMON + Resource.RB.getString("Demo.openSource")); ComparableTreeNode nodeDock = new ComparableTreeNode(ProductNames.PRODUCT_NAME_DOCK); ComparableTreeNode nodeAction = new ComparableTreeNode(ProductNames.PRODUCT_NAME_ACTION); ComparableTreeNode nodeComponents = new ComparableTreeNode(ProductNames.PRODUCT_NAME_COMPONENTS); ComparableTreeNode nodeGrids = new ComparableTreeNode(ProductNames.PRODUCT_NAME_GRIDS); ComparableTreeNode nodeDialogs = new ComparableTreeNode(ProductNames.PRODUCT_NAME_DIALOGS); ComparableTreeNode nodeShortcut = new ComparableTreeNode(ProductNames.PRODUCT_NAME_SHORTCUT); ComparableTreeNode nodePivot = new ComparableTreeNode(ProductNames.PRODUCT_NAME_PIVOT); ComparableTreeNode nodeCodeEditor = new ComparableTreeNode(ProductNames.PRODUCT_NAME_CODE_EDITOR); ComparableTreeNode nodeFeedReader = new ComparableTreeNode(ProductNames.PRODUCT_NAME_FEEDREADER); ComparableTreeNode nodeDashboard = new ComparableTreeNode(ProductNames.PRODUCT_NAME_DASHBOARD); ComparableTreeNode nodeData = new ComparableTreeNode(ProductNames.PRODUCT_NAME_DATAGRIDS); ComparableTreeNode nodeCharts = new ComparableTreeNode(ProductNames.PRODUCT_NAME_CHARTS); ComparableTreeNode nodeGantt = new ComparableTreeNode(ProductNames.PRODUCT_NAME_GANTT_CHART); ComparableTreeNode nodeDiff = new ComparableTreeNode(ProductNames.PRODUCT_NAME_DIFF); // ComparableTreeNode nodeTreeMap = new ComparableTreeNode(ProductNames.PRODUCT_NAME_TREEMAP); root.add(nodeCommon); root.add(nodeDock); root.add(nodeAction); root.add(nodeComponents); root.add(nodeGrids); root.add(nodeDialogs); root.add(nodePivot); root.add(nodeData); root.add(nodeShortcut); root.add(nodeCodeEditor); root.add(nodeFeedReader); root.add(nodeDashboard); root.add(nodeCharts); root.add(nodeGantt); root.add(nodeDiff); // root.add(nodeTreeMap); for (ComparableTreeNode node : _demos) { if (node.getUserObject() instanceof Demo) { Demo demo = (Demo) node.getUserObject(); Object product = demo.getProduct(); if (ProductNames.PRODUCT_NAME_COMMON.equals(product)) { nodeCommon.add(node); // add to components for now } else if (ProductNames.PRODUCT_NAME_DOCK.equals(product)) { nodeDock.add(node); } else if (ProductNames.PRODUCT_NAME_ACTION.equals(product)) { nodeAction.add(node); } else if (ProductNames.PRODUCT_NAME_COMPONENTS.equals(product)) { nodeComponents.add(node); } else if (ProductNames.PRODUCT_NAME_GRIDS.equals(product)) { nodeGrids.add(node); } else if (ProductNames.PRODUCT_NAME_DIALOGS.equals(product)) { nodeDialogs.add(node); } else if (ProductNames.PRODUCT_NAME_SHORTCUT.equals(product)) { nodeShortcut.add(node); } else if (ProductNames.PRODUCT_NAME_PIVOT.equals(product)) { nodePivot.add(node); } else if (ProductNames.PRODUCT_NAME_CODE_EDITOR.equals(product)) { nodeCodeEditor.add(node); } else if (ProductNames.PRODUCT_NAME_FEEDREADER.equals(product)) { nodeFeedReader.add(node); } else if (ProductNames.PRODUCT_NAME_DASHBOARD.equals(product)) { nodeDashboard.add(node); } else if (ProductNames.PRODUCT_NAME_DATAGRIDS.equals(product)) { nodeData.add(node); } else if (ProductNames.PRODUCT_NAME_CHARTS.equals(product)) { nodeCharts.add(node); } else if (ProductNames.PRODUCT_NAME_GANTT_CHART.equals(product)) { nodeGantt.add(node); } else if (ProductNames.PRODUCT_NAME_DIFF.equals(product)) { nodeDiff.add(node); } // else if (ProductNames.PRODUCT_NAME_TREEMAP.equals(product)) { // nodeTreeMap.add(node); // } } } } else { Collections.sort(_demos); for (Object demo : _demos) { ComparableTreeNode node = (ComparableTreeNode) demo; root.add(node); } } return new DefaultTreeModel(root); } /** * Loads all demos into a list of tree nodes. */ private void loadDemos() { int loaded = 0; _demos.clear(); for (String demoClassName : DEMOS) { try { Class<?> demoClass = getClass().getClassLoader().loadClass(demoClassName); Object instance = demoClass.newInstance(); if (!(instance instanceof Demo)) { continue; } Demo demo = (Demo) instance; ComparableTreeNode demoNode = new ComparableTreeNode(demo); _demos.add(demoNode); loaded++; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } ((ProgressStatusBarItem) JideDemos.getStatusBar().getItemByName("Status")).setStatus( loaded == DEMOS.length ? MessageFormat.format(Resource.RB.getString("Demo.allDemoLoaded"), loaded) : MessageFormat.format(Resource.RB.getString("Demo.demoLoaded"), DEMOS.length, loaded)); } } private void openDemo(Object node) { Object object = ((ComparableTreeNode) node).getUserObject(); if (object instanceof Demo) { _demoHolder.openDemo(((Demo) object)); } } class ComparableTreeNode extends DefaultMutableTreeNode implements Comparable { private static final long serialVersionUID = -7121339323800524242L; public ComparableTreeNode() { } public ComparableTreeNode(Object userObject) { super(userObject); } public ComparableTreeNode(Object userObject, boolean allowsChildren) { super(userObject, allowsChildren); } public int compareTo(Object o) { return getUserObject().toString().compareTo(((ComparableTreeNode) o).getUserObject().toString()); } } }
true
f50c7cd1a895fb5f2b6d95dfea76b04f474c2c20
Java
louisewang1/cryptomoneyAPP
/QRscanTest/app/src/main/java/com/example/cryptomoney/QRNFCActivity.java
UTF-8
14,765
1.539063
2
[]
no_license
package com.example.cryptomoney; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.app.Dialog; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.nfc.FormatException; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.cryptomoney.utils.NfcUtils; import com.google.zxing.util.Constant; import com.google.zxing.util.QrCodeGenerator; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import cn.memobird.gtx.GTX; import cn.memobird.gtx.GTXScripElement; import cn.memobird.gtx.common.GTXKey; import cn.memobird.gtx.listener.OnBluetoothFindListener; import cn.memobird.gtx.listener.OnCodeListener; import cn.memobird.gtx.listener.OnImageToDitherListener; import cn.memobird.gtx.listener.OnImageToFilterListener; public class QRNFCActivity extends AppCompatActivity { // private EditText qrstring; // private Button generate; private Button search; private ImageView qrimg; private ImageButton back; private ListView lvDevices; //搜索到的设备列表 private DeviceListAdapter deviceListAdapter; private Dialog mDialog; private Button print; private Bitmap qrimage; private String base64ImageString; private List<BluetoothDevice> devices = new ArrayList<>(); private Double amount; private String address; private SharedPreferences pref; private String sk_exp; private String modulus; private String pk_exp; private String account_id; private String qrtext; private String text; private String nfctext; private NfcUtils nfcUtils; private TextView nfcstatus; private String mode; private String merchant; private String enc; private final static int REQ_LOC = 10; // final String AK = "c6a5a445dc25490183f42088f4b78ccf"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qr_nfc); amount = getIntent().getDoubleExtra("amount",0); address = getIntent().getStringExtra("address"); mode = getIntent().getStringExtra("mode"); merchant =getIntent().getStringExtra("merchant"); nfcUtils = new NfcUtils(this); // pref = PreferenceManager.getDefaultSharedPreferences(this); pref = getSharedPreferences("cryptomoneyAPP", Context.MODE_PRIVATE); // account_id = pref.getString("id",""); // pk_exp = pref.getString("pk_exp",""); sk_exp = pref.getString(address+"_skexp",""); modulus = pref.getString(address+"_modulus",""); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } // qrstring = (EditText) findViewById(R.id.qrstring); // generate = (Button) findViewById(R.id.generate); search = (Button) findViewById(R.id.search); qrimg = (ImageView) findViewById(R.id.qrimg); lvDevices = findViewById(R.id.lv_device); print = findViewById(R.id.print); nfcstatus = findViewById(R.id.nfcstatus); // qrstring.setText("&sk="+privatekey+"&addr="+address); // text = "N="+modulus+"&d="+sk_exp+"&addr="+address; if (merchant.equals("None")) { text = "N="+modulus+"&d="+sk_exp+"&addr="+address; } else { enc = getIntent().getStringExtra("enc"); text = enc; } System.out.println(text); qrtext = extractodd(text); nfctext = extracteven(text); qrimage = QrCodeGenerator.getQrCodeImage(qrtext,200,200); qrimg.setImageBitmap(qrimage); // GTX.init(getApplicationContext(), AK); //初始化 mDialog = Common.showLoadingDialog(QRNFCActivity.this); // 定义蓝牙连接列表 deviceListAdapter = new DeviceListAdapter(this, devices); lvDevices.setAdapter(deviceListAdapter); // 搜索蓝牙 search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (ContextCompat.checkSelfPermission(QRNFCActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) // 检查运行时权限 != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(QRNFCActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQ_LOC); // 申请定位权限,MUST BE FINE! }else { devices.clear(); deviceListAdapter.notifyDataSetChanged(); if (mDialog != null) mDialog.show(); //设备搜索 Log.d("QRgeneratorActivity","start searching"); GTX.searchBluetoothDevices(onBluetoothFindListener, mDialog); } } }); lvDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // tvSelectDevice.setText("选择的设备:\n" + devices.get(i).getName() + "\n" + devices.get(i).getAddress()); if (mDialog != null) mDialog.show(); // 选中设备后,开始连接该设备蓝牙 GTX.connectBluetoothDevice(onConnectListener, devices.get(i), mDialog); } }); print.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (GTX.getConnectDevice() != null) { printQR(); } else { Common.showShortToast(QRNFCActivity.this, "please connect to the printer first"); } } }); } // write in NFC @Override protected void onNewIntent(Intent intent){ super.onNewIntent(intent); try { nfcUtils.writeNFCToTag(nfctext, intent); // Log.d("NFCRWActivity","finish writing"); Common.showShortToast(this, "write to NFC successfully."); nfcstatus.setText("Status: writing successfully"); } catch (IOException e) { Common.showShortToast(this, "write to NFC failed."); // Log.d("NFCRWActivity","write to NFC failed:" + e.getMessage()); } catch (FormatException e) { Common.showShortToast(this, "write to failed."); // Log.d("NFCRWActivity","write to NFC failed:" + e.getMessage()); } } private void printQR() { GTX.doImageToDither(onDitherListener,qrimage,mDialog, Common.DEFAULT_IMAGE_WIDTH,true); // GTX.doImageToDither(qrimage,mDialog,Common.DEFAULT_IMAGE_WIDTH,true); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Log.d("QRgeneratorActivity","string: "+base64ImageString); if (base64ImageString != null && amount > 0) { List<GTXScripElement> scripElements = new ArrayList<>(); scripElements.add(new GTXScripElement(1, "mode= "+mode)); scripElements.add(new GTXScripElement(1, "amount= "+amount.toString())); scripElements.add(new GTXScripElement(1, "to merchant: "+merchant)); scripElements.add(new GTXScripElement(5, base64ImageString)); GTX.printMixing(onPrintListener, scripElements, mDialog); // GTX.printImage(onPrintListener, base64ImageString, mDialog); } } }).start(); } //图像处理结果OnImageToDitherListener private OnImageToDitherListener onDitherListener = new OnImageToDitherListener() { @Override public void returnResult(String base64ImageString, Bitmap bitmap, int taskCode) { if (taskCode == GTXKey.RESULT.COMMON_SUCCESS && base64ImageString != null) { // Log.d("QRgeneratorActivity","String in Ditherlistener: "+base64ImageString); QRNFCActivity.this.base64ImageString = base64ImageString; } else { // Log.d("QRgeneratorActivity","Dither failed"); Common.showShortToast(QRNFCActivity.this, "Error " + taskCode); } } }; public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //权限请求结果回调 if (requestCode == REQ_LOC && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d("QRgeneratorActivity","permission granted"); devices.clear(); deviceListAdapter.notifyDataSetChanged(); if (mDialog != null) mDialog.show(); GTX.searchBluetoothDevices(onBluetoothFindListener, mDialog); } else { if (mDialog != null) mDialog.cancel(); Log.d("QRgeneratorActivity","permission granted"); Common.showShortToast(this,"Permission denied"); } } // 蓝牙搜索结果回调 private OnBluetoothFindListener onBluetoothFindListener = new OnBluetoothFindListener() { @Override public void returnResult(int taskCode, BluetoothDevice bluetoothDevice, short signal) { Log.d("QRgeneratorActivity","taskcode:" +taskCode); if (mDialog != null) mDialog.cancel(); if (taskCode == GTXKey.RESULT.FIND_DEVICE_GET_ONE && bluetoothDevice != null) { //搜索到一台设备 if (bluetoothDevice.getName() != null && bluetoothDevice.getName().equals("MEMOBIRD GO")) { devices.add(bluetoothDevice); } deviceListAdapter.setDeviceList(devices); deviceListAdapter.notifyDataSetChanged(); lvDevices.setVisibility(View.VISIBLE); } else if (taskCode == GTXKey.RESULT.FIND_DEVICE_FINISH_TASK) { //搜索任务正常结束 if (devices.size() == 0) { Common.showShortToast(QRNFCActivity.this, "No MEMOBIRD device available"); } else { Common.showShortToast(QRNFCActivity.this, "device searching finished"); } } else { //其它异常 Common.showShortToast(QRNFCActivity.this, "Error " + taskCode); } } }; // 设备连接结果监听 private OnCodeListener onConnectListener = new OnCodeListener() { @Override public void returnResult(int taskCode) { if (mDialog != null) mDialog.cancel(); if (taskCode == GTXKey.RESULT.COMMON_SUCCESS) { //成功连接设备 lvDevices.setVisibility(View.GONE); Common.showShortToast(QRNFCActivity.this,"connected successfully"); if (GTX.getConnectDevice().getName().contains("G4")) { Common.DEFAULT_IMAGE_WIDTH = Common.SIZE_576; } else { Common.DEFAULT_IMAGE_WIDTH = Common.SIZE_384; } } else if (taskCode == GTXKey.RESULT.COMMON_FAIL) { Common.showShortToast(QRNFCActivity.this, "connection failed"); } else { Common.showShortToast(QRNFCActivity.this, "Error " + taskCode); } } }; // 打印结果监听 private OnCodeListener onPrintListener = new OnCodeListener() { @Override public void returnResult(int taskCode) { if (taskCode == GTXKey.RESULT.COMMON_SUCCESS) { Common.showShortToast(QRNFCActivity.this, "successfully printed"); } else { Log.d("QRgeneratorActivity","taskCode="+taskCode); Common.showShortToast(QRNFCActivity.this, "Error " + taskCode); } } }; @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); default: } return true; } public String extractodd(String text) { String oddtext = ""; for (int i=0; i<text.length();i=i+2) { oddtext +=text.charAt(i); } System.out.println(oddtext); return oddtext; } public String extracteven(String text) { String eventext = ""; for (int i=1; i<text.length();i=i+2) { eventext +=text.charAt(i); } System.out.println(eventext); return eventext; } @Override protected void onResume() { super.onResume(); // Logger.e(TAG, "onResume"); nfcUtils.enableForegroundDispatch(); } @Override protected void onPause() { super.onPause(); // Logger.e(TAG, "onPause"); nfcUtils.disableForegroundDispatch(); } protected void onDestroy() { super.onDestroy(); GTX.onDestroy(); } }
true
41e9972f5abcd3f79f9c4ada4cf83628982caa9d
Java
marcouio/utility
/src/main/java/com/molinari/utility/database/Query.java
UTF-8
1,425
2.375
2
[]
no_license
package com.molinari.utility.database; import java.sql.SQLException; import java.util.List; import java.util.Map; public class Query { public boolean update(UpdateBase updateBase) throws SQLException { return eseguiSqlFromString(updateBase.getUpdateQuery()); } public boolean update(final String tabella, final Map<String, String> campi, List<Clausola> clausole) throws SQLException { final UpdateBase updateBase = new UpdateBase(); return eseguiSqlFromString(updateBase.getUpdateQuery(tabella, campi, clausole)); } public boolean insert(InsertBase insertBase) throws SQLException { return eseguiSqlFromString(insertBase.getInsertQuery()); } public boolean insert(final String tabella, final Map<String, String> campi) throws SQLException { final InsertBase insertBase = new InsertBase(); return eseguiSqlFromString(insertBase.getInsertQuery(tabella, campi)); } public boolean delete(final DeleteBase deleteBase) throws SQLException { return eseguiSqlFromString(deleteBase.getDeleteQuery()); } public boolean delete(final String tabella, final List<Clausola> clausole) throws SQLException { final DeleteBase deleteBase = new DeleteBase(); return eseguiSqlFromString(deleteBase.getDeleteQuery(tabella, clausole)); } public boolean eseguiSqlFromString(final String comandoSql) throws SQLException { return ConnectionPool.getSingleton().executeUpdate(comandoSql) != 0; } }
true
f45f7993640b6dbe46a898e2ff7ab69b76310bcd
Java
hdarmet/funnies
/Funnies/src/com/ithaque/funnies/client/platform/gwt/impl/GWTContext2D.java
UTF-8
2,523
2.4375
2
[]
no_license
package com.ithaque.funnies.client.platform.gwt.impl; import com.google.gwt.canvas.dom.client.Context2d; import com.google.gwt.canvas.dom.client.CssColor; import com.google.gwt.canvas.dom.client.FillStrokeStyle; import com.ithaque.funnies.client.platform.gwt.Context2D; import com.ithaque.funnies.client.platform.gwt.ImageInterface; import com.ithaque.funnies.shared.basic.Color; public class GWTContext2D implements Context2D { Context2d context2d; public GWTContext2D(Context2d context2d) { this.context2d = context2d; } @Override public void setTransform(float m11, float m12, float m21, float m22, float dx, float dy) { context2d.setTransform(m11, m12, m21, m22, dx, dy); } @Override public void setGlobalAlpha(float opacity) { context2d.setGlobalAlpha(opacity); } @Override public void translate(float x, float y) { context2d.translate(x, y); } @Override public void drawImage( ImageInterface image, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { context2d.drawImage(((GWTImage)image).image, sx, sy, sw, sh, dx, dy, dw, dh); } @Override public void setLineWidth(float lineWidth) { context2d.setLineWidth(lineWidth); } @Override public void beginPath() { context2d.beginPath(); } @Override public void setLineJoin(String lineJoin) { context2d.setLineJoin(lineJoin); } @Override public void setStrokeStyle(Color color) { context2d.setStrokeStyle(getColor(color)); } @Override public void setFillStyle(Color color) { context2d.setFillStyle(getColor(color)); } FillStrokeStyle getColor(Color color) { return CssColor.make(color.getRed(), color.getGreen(), color.getBlue()); } @Override public void fill() { context2d.fill(); } @Override public void stroke() { context2d.stroke(); } @Override public void moveTo(float x, float y) { context2d.moveTo(x, y); } @Override public void lineTo(float x, float y) { context2d.lineTo(x, y); } @Override public void clip() { context2d.clip(); } @Override public void setFont(String font) { context2d.setFont(font); } @Override public void setTextBaseline(String baseline) { context2d.setTextBaseline(baseline); } @Override public void fillText(String text, float x, float y) { context2d.fillText(text, x, y); } @Override public double measureTextWidth(String text) { return context2d.measureText(text).getWidth(); } @Override public void clearRect(float x, float y, float w, float h) { context2d.clearRect(x, y, w, h); } }
true
0dcc17959b9788e7265551800f7d255b6360e860
Java
GilbertoJNJ/Jogo-das-Palavras-Embaralhadas
/Testes/TesteParImpar.java
UTF-8
384
2.15625
2
[]
no_license
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import Embaralhador.Embaralhador; import Embaralhador.ParImpar; class TesteParImpar { Embaralhador e = new ParImpar(); @Test void testRecebeuPalavraDoBancoDeDados() { assertNotNull(e.getString()); } @Test void testEmbaralhar() { assertNotEquals(e.embaralhar(),e.getString()); } }
true
56514af1f33de9305662e5ec58a0c1c63223da50
Java
Igor-developer/learning_java_6_arrays_strings
/src/com/company/Car.java
UTF-8
362
3.09375
3
[]
no_license
package com.company; public class Car extends Vehicle { public Car(String make, int speed, int fuelTankVolume) { super(make, speed, fuelTankVolume); } @Override public void fueling() { System.out.println("Автомобиль заправлен, в баке " + getFuelTankVolume() + " литров топлива!"); } }
true
6224f3733961fe2a43ab53cf18c58764ea83e965
Java
LiXuanqi/LintCode-train
/494-implement-stack-by-two-queues.java
UTF-8
741
3.6875
4
[]
no_license
public class Stack { /* * @param x: An integer * @return: nothing */ Queue<Integer> stack = new LinkedList<>(); Queue<Integer> queue = new LinkedList<>(); public void push(int x) { while (!stack.isEmpty()) { queue.offer(stack.poll()); } stack.offer(x); while (!queue.isEmpty()) { stack.offer(queue.poll()); } } /* * @return: nothing */ public void pop() { stack.poll(); } /* * @return: An integer */ public int top() { return stack.peek(); } /* * @return: True if the stack is empty */ public boolean isEmpty() { return stack.isEmpty(); } }
true
6aa0a13ae253fc305cd3342c3cde484f729a86c3
Java
didier-tp/al32_tpSpringFormateur
/src/test/java/fr/afcepf/al32/test/TestServicePersonne.java
UTF-8
1,468
2.0625
2
[]
no_license
package fr.afcepf.al32.test; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import fr.afcepf.al32.config.ServiceConfig; import fr.afcepf.al32.entity.Client; import fr.afcepf.al32.entity.Compte; import fr.afcepf.al32.entity.Personne; import fr.afcepf.al32.service.IServicePersonne; @RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration(locations= {"/springConfAnnot.xml"}) @ContextConfiguration(classes= {ServiceConfig.class}) public class TestServicePersonne { private Logger logger = LoggerFactory.getLogger(TestServicePersonne.class); @Autowired private IServicePersonne servicePersonne; //à tester @Test public void testRechercheParNum() { Personne p =servicePersonne.rechercherPersonneParNumero(2L); Assert.assertTrue(p.getNumero()==2L); logger.debug("p="+p.toString()); } @Test public void testRechercheClientAvecCompteParNum() { Client cli =servicePersonne.rechercherClientAvecComptes(3L); Assert.assertTrue(cli.getNumero()==3L); logger.debug("cli="+cli.toString()); for(Compte cpt : cli.getComptes()) { logger.debug("\t"+cpt.toString());//sans "lazy exception" ? } } }
true
eba6b75a1418814276d68a2aa5a7e2c140756384
Java
tinggu/endside_android_initialstage
/module_desk/src/main/java/com/ctfww/module/desk/datahelper/airship/RouteDeskAirship.java
UTF-8
3,793
1.914063
2
[]
no_license
package com.ctfww.module.desk.datahelper.airship; import android.text.TextUtils; import com.blankj.utilcode.util.LogUtils; import com.blankj.utilcode.util.SPStaticUtils; import com.ctfww.commonlib.datahelper.IUIDataHelperCallback; import com.ctfww.commonlib.entity.CargoToCloud; import com.ctfww.commonlib.entity.QueryCondition; import com.ctfww.module.desk.datahelper.NetworkHelper; import com.ctfww.module.desk.datahelper.dbhelper.DBHelper; import com.ctfww.module.desk.datahelper.sp.Const; import com.ctfww.module.desk.entity.RouteDesk; import org.greenrobot.eventbus.EventBus; import java.util.List; public class RouteDeskAirship { private final static String TAG = "RouteDeskAirship"; // 同步签到点上云 public static void synToCloud() { List<RouteDesk> routeDeskList = DBHelper.getInstance().getNoSynRouteDeskList(); if (routeDeskList.isEmpty()) { return; } CargoToCloud<RouteDesk> cargoToCloud = new CargoToCloud<>(routeDeskList); NetworkHelper.getInstance().synRouteDeskToCloud(cargoToCloud, new IUIDataHelperCallback() { @Override public void onSuccess(Object obj) { for (int i = 0; i < routeDeskList.size(); ++i) { RouteDesk routeDesk = routeDeskList.get(i); routeDesk.setSynTag("cloud"); DBHelper.getInstance().updateRouteDesk(routeDesk); } } @Override public void onError(int code) { LogUtils.i(TAG, "synToCloud fail: code = " + code); } }); } // 从云上同步签到点 public static void synFromCloud() { String userId = SPStaticUtils.getString(Const.USER_OPEN_ID); if (TextUtils.isEmpty(userId)) { return; } long startTime = SPStaticUtils.getLong(Const.ROUTE_DESK_SYN_TIME_STAMP_CLOUD, 0); long endTime = System.currentTimeMillis(); QueryCondition condition = new QueryCondition(); condition.setUserId(userId); condition.setStartTime(startTime); condition.setEndTime(endTime); NetworkHelper.getInstance().synRouteDeskFromCloud(condition, new IUIDataHelperCallback() { @Override public void onSuccess(Object obj) { List<RouteDesk> routeDeskList = (List<RouteDesk>)obj; if (!routeDeskList.isEmpty()) { if (updateTabByCloud(routeDeskList)) { EventBus.getDefault().post(Const.FINISH_ROUTE_DESK_SYN); } } SPStaticUtils.put(Const.ROUTE_DESK_SYN_TIME_STAMP_CLOUD, condition.getEndTime()); } @Override public void onError(int code) { LogUtils.i(TAG, "synFromCloud fail: code = " + code); } }); } private static boolean updateTabByCloud(List<RouteDesk> routeDeskList) { boolean ret = false; for (int i = 0; i < routeDeskList.size(); ++i) { RouteDesk routeDesk = routeDeskList.get(i); RouteDesk localRouteDesk = DBHelper.getInstance().getRouteDesk(routeDesk.getGroupId(), routeDesk.getRouteId(), routeDesk.getDeskId()); if (localRouteDesk == null) { routeDesk.setSynTag("cloud"); DBHelper.getInstance().addRouteDesk(routeDesk); ret = true; } else { if (localRouteDesk.getTimeStamp() < routeDesk.getTimeStamp()) { routeDesk.setSynTag("cloud"); DBHelper.getInstance().updateRouteDesk(routeDesk); ret = true; } } } return ret; } }
true
bb6cd451223daf6a4880feb8bb7846e0bb098c24
Java
hazeliao/Maskshopping
/src/main/java/mask/shop/shan/domain/OrderRepository.java
UTF-8
235
1.609375
2
[]
no_license
package mask.shop.shan.domain; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface OrderRepository extends CrudRepository<OrderList, Long> { List <OrderList> findByMask (Mask mask); }
true
eec4222965424a43017c6f14227118c56bf32a65
Java
rfontao/lpoo-2020-g74
/src/test/java/com/fleeTheRoom/TestLevel.java
UTF-8
16,798
2.515625
3
[]
no_license
package com.fleeTheRoom; import com.fleeTheRoom.controllers.commands.Command; import com.fleeTheRoom.controllers.commands.level.InteractCommand; import com.fleeTheRoom.models.Position; import com.fleeTheRoom.models.level.*; import com.fleeTheRoom.models.puzzles.PuzzleButton; import com.fleeTheRoom.models.puzzles.colorSeq.ColorSeqButton; import com.fleeTheRoom.models.puzzles.findSeq.FindSeqButton; import com.fleeTheRoom.models.puzzles.tiles.TilesPuzzleButton; import com.fleeTheRoom.view.Audio; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class TestLevel { private Level level; @Before public void InitTestLevel() { level = new Level(10, 20, 0,0); } @Test public void TestConstructor() { assertEquals(level.getWidth(), 10); assertEquals(level.getHeight(), 20); assertNotEquals(level.getDoors(), null); assertNotEquals(level.getKeys(), null); assertNotEquals(level.getWalls(), null); assertNull(level.getPlayer()); assertNotEquals(level.getObservers(), null); assertFalse(level.isFinished()); } @Test public void TestFinish() { level.finish(); assertTrue(level.isFinished()); } @Test public void TestAddObserver() { LevelObserver observerMock = Mockito.mock(LevelObserver.class); level.addObserver(observerMock); assertEquals(level.getObservers().size(), 1); } @Test public void TestNotifyObservers() { LevelObserver observerMock = Mockito.mock(LevelObserver.class); LevelObserver observerMock2 = Mockito.mock(LevelObserver.class); level.addObserver(observerMock); level.addObserver(observerMock); level.addObserver(observerMock); level.addObserver(observerMock2); level.notifyObservers(); Mockito.verify(observerMock, Mockito.times(3)).levelChanged(); Mockito.verify(observerMock2, Mockito.times(1)).levelChanged(); } @Test public void TestGetAllEntities() { List<Entity> entities = new ArrayList<>(); Wall wall1 = new Wall(5,5); Wall wall2 = new Wall(6,6); Door door1 = new Door(7,7,Key.Color.color1); Door door2 = new Door(8,8,Key.Color.color2); Key key = new Key(6,6,Key.Color.color1); Objective objective = new Objective(4,5); Player player = new Player(9,9); level.addWall(wall1); level.addWall(wall2); level.addDoor(door1); level.addDoor(door2); level.addKey(key); level.addPlayer(player); level.addObjective(objective); entities.add(player); entities.add(wall1); entities.add(wall2); entities.add(objective); entities.add(door1); entities.add(door2); entities.add(key); assertEquals(entities, level.getAllEntities()); } @Test public void TestMovePlayerToWithoutSliders() { Player player = new Player(5,5); level.addPlayer(player); level.addObjective(new Objective(8,8)); level.addKey(new Key(4,5,Key.Color.color1)); level.addWall(new Wall(5,6)); level.movePlayerTo(new Position(5,6)); assertEquals(level.getPlayer().getPosition().getX(), 5); assertEquals(level.getPlayer().getPosition().getY(), 5); } @Test public void TestMovePlayerToWithSliders() { Player player = new Player(5,5); Slider slider1 = new HorzSlider(6,5); Slider slider2 = new HorzSlider(7,5); level.addPlayer(player); level.addObjective(new Objective(9,8)); level.addWall(new Wall(10,5)); level.addSlider(slider1); level.addSlider(slider2); level.movePlayerTo(new Position(6,5)); assertEquals(level.getPlayer().getPosition().getX(), 6); assertEquals(level.getPlayer().getPosition().getY(), 5); assertEquals(slider1.getPosition().getX(), 7); assertEquals(slider1.getPosition().getY(), 5); assertEquals(slider2.getPosition().getX(), 8); assertEquals(slider2.getPosition().getY(), 5); Slider slider3 = new VertSlider(6, 6); Slider slider4 = new VertSlider(6,7); Slider slider5 = new HorzSlider(6, 9); level.addSlider(slider3); level.addSlider(slider4); level.addSlider(slider5); level.movePlayerTo(new Position(6,6)); assertEquals(level.getPlayer().getPosition().getX(), 6); assertEquals(level.getPlayer().getPosition().getY(), 6); assertEquals(slider3.getPosition().getX(), 6); assertEquals(slider3.getPosition().getY(), 7); assertEquals(slider4.getPosition().getX(), 6); assertEquals(slider4.getPosition().getY(), 8); assertEquals(slider5.getPosition().getX(), 6); assertEquals(slider5.getPosition().getY(), 9); level.movePlayerTo(new Position(6,7)); assertEquals(level.getPlayer().getPosition().getX(), 6); assertEquals(level.getPlayer().getPosition().getY(), 6); assertEquals(slider3.getPosition().getX(), 6); assertEquals(slider3.getPosition().getY(), 7); assertEquals(slider4.getPosition().getX(), 6); assertEquals(slider4.getPosition().getY(), 8); assertEquals(slider5.getPosition().getX(), 6); assertEquals(slider5.getPosition().getY(), 9); Slider slider6 = new VertSlider(6,5); level.addSlider(slider6); level.movePlayerTo(new Position(6,5)); assertEquals(level.getPlayer().getPosition().getX(), 6); assertEquals(level.getPlayer().getPosition().getY(), 5); assertEquals(slider3.getPosition().getX(), 6); assertEquals(slider3.getPosition().getY(), 7); assertEquals(slider4.getPosition().getX(), 6); assertEquals(slider4.getPosition().getY(), 8); assertEquals(slider5.getPosition().getX(), 6); assertEquals(slider5.getPosition().getY(), 9); assertEquals(slider6.getPosition().getX(), 6); assertEquals(slider6.getPosition().getY(), 4); } @Test public void TestMovePlayerToWithInteractables() { Player player = new Player(4,5); FindSeqButton button1 = new FindSeqButton(5,5, 0, PuzzleButton.STATE.NOTCLEARED); Button button2 = new Button(7,6,1); level.addPlayer(player); level.addObjective(new Objective(9,8)); level.addInteractable(button1); level.addInteractable(button2); level.movePlayerTo(new Position(5,5)); assertEquals(player.getPosition(), new Position(4,5)); button1.setState(PuzzleButton.STATE.CLEARED); level.movePlayerTo(new Position(5,5)); assertEquals(player.getPosition(), new Position(5,5)); level.movePlayerTo(new Position(7,6)); assertEquals(player.getPosition(), new Position(7,6)); level.movePlayerTo(new Position(6,6)); assertEquals(player.getPosition(), new Position(6,6)); button2.setState(Button.STATE.PRESSED); level.movePlayerTo(new Position(7,6)); assertEquals(player.getPosition(), new Position(6,6)); } @Test public void TestCheckInteractables() { Player player = new Player(9,9); Objective obj = new Objective(5,5); ColorSeqButton colorSeqButton = new ColorSeqButton(0,2,0, PuzzleButton.STATE.NOTCLEARED); FindSeqButton findSeqButton = new FindSeqButton(8,9,0, PuzzleButton.STATE.NOTCLEARED); level.addPlayer(player); level.addObjective(obj); level.addInteractable(colorSeqButton); level.addInteractable(findSeqButton); Interactable inter = level.checkInteractables(); assertTrue(inter instanceof FindSeqButton); level.movePlayerTo(new Position(6,9)); inter = level.checkInteractables(); assertNull(inter); } @Test public void TestCheckObjective() { Player player = new Player(9,9); Objective obj = new Objective(5,5); level.addPlayer(player); level.addObjective(obj); level.checkObjective(player.getPosition(), obj.getPosition()); assertFalse(level.isFinished()); assertFalse(level.isNextLevel()); player = new Player(obj.getPosition().getX(), obj.getPosition().getY()); level.addPlayer(player); level.checkObjective(player.getPosition(), obj.getPosition()); assertTrue(level.isFinished()); assertTrue(level.isNextLevel()); } @Test public void TestCheckKeys() { Player player = new Player(9, 9); Objective obj = new Objective(5, 5); Key key1 = new Key(9, 9, Key.Color.color1); Key key2 = new Key(5, 6, Key.Color.color2); level.addPlayer(player); level.addObjective(obj); level.addKey(key1); level.addKey(key2); assertEquals(0, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(0, player.getPickedKeysByColor(Key.Color.color2).size()); assertEquals(2, level.getKeys().size()); level.checkKeys(player.getPosition(), level.getKeys()); assertEquals(1, level.getKeys().size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(0, player.getPickedKeysByColor(Key.Color.color2).size()); level.checkKeys(player.getPosition(), level.getKeys()); assertEquals(1, level.getKeys().size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(0, player.getPickedKeysByColor(Key.Color.color2).size()); level.movePlayerTo(new Position(5, 6)); level.checkKeys(player.getPosition(), level.getKeys()); assertEquals(0, level.getKeys().size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color2).size()); } @Test public void TestMovePlayerDoors() { Player player = new Player(0,2); Objective obj = new Objective(9,9); Door door1 = new Door(4,2, Key.Color.color1); Door door2 = new Door(5,2, Key.Color.color2); Door door3 = new Door(6,2, Key.Color.color1); Door door4 = new Door(7,2, Key.Color.color2); Key key1 = new Key(1,2, Key.Color.color2); Key key2 = new Key(2,2, Key.Color.color1); Key key3 = new Key(3,2, Key.Color.color1); level.addPlayer(player); level.addObjective(obj); level.addDoor(door1); level.addDoor(door2); level.addDoor(door3); level.addDoor(door4); level.addKey(key1); level.addKey(key2); level.addKey(key3); assertEquals(0, player.getPickedKeys().size()); level.movePlayerTo(new Position(1,2)); assertEquals(new Position(1,2), player.getPosition()); assertEquals(1, player.getPickedKeys().size()); assertEquals(0, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color2).size()); level.movePlayerTo(new Position(2,2)); assertEquals(new Position(2,2), player.getPosition()); assertEquals(2, player.getPickedKeys().size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color2).size()); level.movePlayerTo(new Position(3,2)); assertEquals(new Position(3,2), player.getPosition()); assertEquals(3, player.getPickedKeys().size()); assertEquals(2, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color2).size()); assertEquals(4, level.getDoors().size()); level.movePlayerTo(new Position(4,2)); assertEquals(new Position(4,2), player.getPosition()); assertEquals(2, player.getPickedKeys().size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color2).size()); assertEquals(3, level.getDoors().size()); level.movePlayerTo(new Position(5,2)); assertEquals(new Position(5,2), player.getPosition()); assertEquals(1, player.getPickedKeys().size()); assertEquals(1, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(0, player.getPickedKeysByColor(Key.Color.color2).size()); assertEquals(2, level.getDoors().size()); level.movePlayerTo(new Position(6,2)); assertEquals(new Position(6,2), player.getPosition()); assertEquals(0, player.getPickedKeys().size()); assertEquals(0, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(0, player.getPickedKeysByColor(Key.Color.color2).size()); assertEquals(1, level.getDoors().size()); level.movePlayerTo(new Position(7,2)); assertEquals(new Position(6,2), player.getPosition()); assertEquals(0, player.getPickedKeys().size()); assertEquals(0, player.getPickedKeysByColor(Key.Color.color1).size()); assertEquals(0, player.getPickedKeysByColor(Key.Color.color2).size()); assertEquals(1, level.getDoors().size()); } @Test public void TestInteract() { Command cmd = new InteractCommand(level, Mockito.mock(Audio.class)); Player player = new Player(2,2); Objective obj = new Objective(5,5); ColorSeqButton colorSeqButton = Mockito.mock(ColorSeqButton.class); FindSeqButton findSeqButton = Mockito.mock(FindSeqButton.class); TilesPuzzleButton tilesPuzzleButton = Mockito.mock(TilesPuzzleButton.class); Button button = Mockito.mock(Button.class); Door buttonDoor = Mockito.mock(Door.class); Mockito.when(findSeqButton.getPosition()).thenReturn(new Position (5,5)); Mockito.when(colorSeqButton.getPosition()).thenReturn(new Position (3,2)); Mockito.when(tilesPuzzleButton.getPosition()).thenReturn(new Position (6,7)); Mockito.when(button.getPosition()).thenReturn(new Position (1,0)); Mockito.when(buttonDoor.getPosition()).thenReturn(new Position (9,9)); level.addPlayer(player); level.addObjective(obj); level.addInteractable(colorSeqButton); level.addInteractable(findSeqButton); level.addInteractable(tilesPuzzleButton); level.addInteractable(button); level.setButtonDoor(buttonDoor); cmd.execute(); Mockito.verify(findSeqButton,Mockito.times(0)).interact(); Mockito.verify(colorSeqButton,Mockito.times(1)).interact(); Mockito.verify(tilesPuzzleButton,Mockito.times(0)).interact(); Mockito.verify(button,Mockito.times(0)).interact(); level.movePlayerTo(new Position(4,5)); cmd.execute(); Mockito.verify(findSeqButton,Mockito.times(1)).interact(); Mockito.verify(colorSeqButton,Mockito.times(1)).interact(); Mockito.verify(tilesPuzzleButton,Mockito.times(0)).interact(); Mockito.verify(button,Mockito.times(0)).interact(); level.movePlayerTo(new Position(7,7)); cmd.execute(); Mockito.verify(findSeqButton,Mockito.times(1)).interact(); Mockito.verify(colorSeqButton,Mockito.times(1)).interact(); Mockito.verify(tilesPuzzleButton,Mockito.times(1)).interact(); Mockito.verify(button,Mockito.times(0)).interact(); int currentButton = level.getButtonNumber(); assertNotNull(level.getButtonDoor()); level.movePlayerTo(new Position(2,0)); cmd.execute(); Mockito.verify(findSeqButton,Mockito.times(1)).interact(); Mockito.verify(colorSeqButton,Mockito.times(1)).interact(); Mockito.verify(tilesPuzzleButton,Mockito.times(1)).interact(); Mockito.verify(button,Mockito.times(1)).interact(); assertEquals(currentButton + 1, level.getButtonNumber()); assertNull(level.getButtonDoor()); } @Test public void TestIsNear() { //TODO this doesnt have anything to do with Level Player player = new Player(0, 0); Wall wall = new Wall(1,0); assertTrue(player.isNear(wall)); assertTrue(wall.isNear(player)); wall.setPosition(new Position(2,0)); assertFalse(player.isNear(wall)); assertFalse(wall.isNear(player)); player.setPosition(new Position(3,1)); assertFalse(player.isNear(wall)); assertFalse(wall.isNear(player)); player.setPosition(new Position(2,1)); assertTrue(player.isNear(wall)); assertTrue(wall.isNear(player)); } }
true
e840366e4846f81e6f8488c3dac8bc2044c78711
Java
zdenning/Logbook
/app/src/main/java/com/murach/logbook/LogbookDB.java
UTF-8
6,363
2.78125
3
[]
no_license
package com.murach.logbook; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.sql.Time; import java.util.ArrayList; import java.util.Date; /** * Created by zacdenning on 4/20/16. */ public class LogbookDB { public static final String DB_NAME = "logbook.db"; public static final int DB_VERSION = 1; public static final String ENTRY_TABLE = "logbook"; public static final String ENTRY_ID = "_id"; public static final int ENTRY_ID_COL = 0; public static final String ENTRY_GLUCOSE = "glucose"; public static final int ENTRY_GLUCOSE_COL = 1; public static final String ENTRY_CARBS = "carbs"; public static final int ENTRY_CARBS_COL = 2; public static final String ENTRY_TIME = "datetime"; public static final int ENTRY_TIME_COL = 3; public static final String CREATE_LOG_TABLE = "CREATE TABLE " + ENTRY_TABLE + " (" + ENTRY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ENTRY_GLUCOSE + " TEXT, " + ENTRY_CARBS + " TEXT, " + ENTRY_TIME + " TEXT) "; public static final String DROP_LOG_TABLE = "DROP TABLE IF EXISTS " + ENTRY_TABLE; /** * DB Helper class */ private static class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } /** * Creates new table * @param db The SQLite database created */ public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_LOG_TABLE); } /** * When upgrading DB to new version, drop old version and run onCreate() * @param db New database * @param oldVersion Old database * @param newVersion New database */ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (newVersion > oldVersion) { db.execSQL(DROP_LOG_TABLE); onCreate(db); } } } private SQLiteDatabase db; private DBHelper dbHelper; public LogbookDB(Context context) { dbHelper = new DBHelper(context, DB_NAME, null, DB_VERSION); } private void openReadableDB() { db = dbHelper.getReadableDatabase(); } private void openWriteableDB() { db = dbHelper.getWritableDatabase(); } private void closeDB() { if (db != null) db.close(); } /** * Returns an ArrayList containing the entry objects in the database. * @return Entries in DB */ public ArrayList<Entry> getEntries() { this.openReadableDB(); Cursor cursor = db.query(ENTRY_TABLE, null,null, null, null, null, "date, time", null); ArrayList<Entry> entries = new ArrayList<Entry>(); while (cursor.moveToNext()) { entries.add(getEntryFromCursor(cursor)); } if (cursor != null) cursor.close(); this.closeDB(); return entries; } /** * Returns single entry with the specified ID * @param id The ID of the entry you want * @return The entry associated with the given ID */ public Entry getEntry(long id) { String where = ENTRY_ID + "= ?"; String[] whereArgs = { Long.toString(id) }; this.openReadableDB(); Cursor cursor = db.query(ENTRY_TABLE, null, where, whereArgs, null, null, null); cursor.moveToFirst(); Entry entry = getEntryFromCursor(cursor); if (cursor != null) cursor.close(); this.closeDB(); return entry; } /** * Gets entry based on user input * @param cursor Where the user touches the screen * @return The entry in the position touched */ public static Entry getEntryFromCursor(Cursor cursor) { if (cursor == null || cursor.getCount() == 0) { return null; } else { try { Entry entry = new Entry( cursor.getString(ENTRY_ID_COL), cursor.getString(ENTRY_GLUCOSE_COL), cursor.getString(ENTRY_CARBS_COL), cursor.getString((ENTRY_TIME_COL))); return entry; } catch(Exception e) { return null; } } } /** * Insert new entry into database * @param entry Entry object to insert * @return The row of the inserted Entry */ public long insertEntry(Entry entry) { ContentValues cv = new ContentValues(); cv.put(ENTRY_ID, entry.getEntryID()); cv.put(ENTRY_GLUCOSE, entry.getGlucose()); cv.put(ENTRY_CARBS, entry.getCarbs()); cv.put(ENTRY_TIME, entry.getTime()); this.openWriteableDB(); long rowID = db.insert(ENTRY_TABLE, null, cv); this.closeDB(); return rowID; } /** * Used for altering data in an existing entry * @param entry Entry to edit * @return Row count */ public int updateEntry(Entry entry) { ContentValues cv = new ContentValues(); cv.put(ENTRY_ID, entry.getEntryID()); cv.put(ENTRY_GLUCOSE, entry.getGlucose()); cv.put(ENTRY_CARBS, entry.getCarbs()); cv.put(ENTRY_TIME, entry.getTime().toString()); String where = ENTRY_ID + "= ?"; String[] whereArgs = { String.valueOf(entry.getEntryID()) }; this.openWriteableDB(); int rowCount = db.update(ENTRY_TABLE, cv, where, whereArgs); this.closeDB(); return rowCount; } /** * Delete entry with specified ID * @param id The ID of the entry to be deleted * @return Row count */ public int deleteEntry(Entry id) { String where = ENTRY_ID + "= ?"; String[] whereArgs = { String.valueOf(id)}; this.openWriteableDB(); int rowCount = db.delete(ENTRY_TABLE, where, whereArgs); return rowCount; } }
true
e61a343aa3bdca3930247642b830398d6c866b7e
Java
wanjiashengfo/codeGen
/src/main/java/com/xgen/geninvocation/DefaultGenInvocation.java
UTF-8
1,640
2.671875
3
[]
no_license
package com.xgen.geninvocation; import com.xgen.genconf.vo.ModuleConfModel; import com.xgen.geninvocation.state.DefaultBeginState; import com.xgen.geninvocation.state.State; import lombok.Getter; import lombok.Setter; import java.util.Observable; public class DefaultGenInvocation extends Observable implements GenInvocation{ /** * 持有一个状态对象 */ @Setter private State state = null; /** * 具体要生成的类型标志 */ @Getter private String needGenType = ""; /** * 当前被生成的模块的数据 */ @Getter private ModuleConfModel moduleConf; /** * 存放多个解析过程中的临时的内容 */ @Getter @Setter private Object tempContent = null; /** * 通知内容已经生成好了 可以出发联动 * @param obj */ public void setContentOver(Object obj){ this.setChanged(); this.notifyObservers(obj); } public DefaultGenInvocation(String needGenType,ModuleConfModel moduleConf){ this.needGenType = needGenType; this.moduleConf = moduleConf; } /** * 执行工作 在每一个state完成自己的工作之后调用 */ public void doWork(){ this.state.doWork(this); } @Override public void executeGen() { //设置generate调用流程开始需要执行的状态 state = new DefaultBeginState(); //让状态执行工作 state.doWork(this); //第一大步:调用相应的生成实现来获取生成的内容 //第二大步:把生成的内容输出出去 } }
true
73e461d9416ff294abe0ff072b64ecd65c492427
Java
bellmit/fleet-spring-boot
/spring-boot-mybatis-dynamic-sql/src/main/java/com/fleet/mybatis/dynamic/sql/dao/UserRoleDynamicSqlSupport.java
UTF-8
775
2.171875
2
[]
no_license
package com.fleet.mybatis.dynamic.sql.dao; import java.sql.JDBCType; import org.mybatis.dynamic.sql.SqlColumn; import org.mybatis.dynamic.sql.SqlTable; public final class UserRoleDynamicSqlSupport { public static final UserRole userRole = new UserRole(); /** * 用户id */ public static final SqlColumn<Integer> userId = userRole.userId; /** * 角色id */ public static final SqlColumn<Integer> roleId = userRole.roleId; public static final class UserRole extends SqlTable { public final SqlColumn<Integer> userId = column("user_id", JDBCType.INTEGER); public final SqlColumn<Integer> roleId = column("role_id", JDBCType.INTEGER); public UserRole() { super("user_role"); } } }
true
3e670b14fc82246f54f23fb4c04e3452909e3cfc
Java
RDoneux/LogSystem
/src/test/java/logger/LogStoreTest.java
UTF-8
781
2.5
2
[]
no_license
package logger; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class LogStoreTest { @Test public void shouldAddNewLogToLogStore(){ Log log = Log.get("location"); assertThat(log).isNotNull(); assertThat(log.getLocation()).isEqualTo("location.log"); } @Test public void shouldGetExistingLogFromLogStore(){ Log.get("location"); Log.get("Second Log Location"); assertThat(Log.get("location")).isNotNull(); assertThat(Log.get("Second Log Location")).isNotNull(); Log location = Log.get("location"); Log secondLog = Log.get("Second Log Location"); assertThat(location).isNotNull(); assertThat(secondLog).isNotNull(); } }
true
bb5dc4b97de90744a65a144c8fca300fddb51885
Java
neziniukas/micromanager-upstream
/plugins/Navigator/surfacesandregions/MultiPosRegion.java
UTF-8
2,605
2.671875
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package surfacesandregions; import gui.SettingsDialog; import java.awt.Point; import org.micromanager.MMStudio; /** * * @author Henry */ public class MultiPosRegion { private int centerX_, centerY_; //stored in pixel space private int overlapX_, overlapY_, rows_, cols_; private RegionManager manager_; private String name_; public MultiPosRegion(RegionManager manager, int r, int c, int cx, int cy) { manager_ = manager; name_ = manager.getNewName(); centerX_ = cx; centerY_ = cy; rows_ = r; cols_ = c; overlapX_ = SettingsDialog.getOverlapX(); overlapY_ = SettingsDialog.getOverlapY(); } public String getName() { return name_; } public void rename(String newName) { name_ = newName; manager_.updateRegionTableAndCombos(); } public double getWidth_um() { double pixelSize = MMStudio.getInstance().getCore().getPixelSizeUm(); int imageWidth = (int) MMStudio.getInstance().getCore().getImageWidth(); int pixelWidth = cols_ * (imageWidth - overlapX_) + overlapX_; return pixelSize * pixelWidth; } public double getHeight_um() { double pixelSize = MMStudio.getInstance().getCore().getPixelSizeUm(); int imageHeight = (int) MMStudio.getInstance().getCore().getImageHeight(); int pixelHeight = rows_ * (imageHeight - overlapY_) + overlapY_; return pixelSize * pixelHeight; } public void updateParams(int rows, int cols) { overlapX_ = SettingsDialog.getOverlapX(); overlapY_ = SettingsDialog.getOverlapY(); rows_ = rows; cols_ = cols; manager_.updateRegionTableAndCombos(); manager_.drawRegionOverlay(this); } public int numCols() { return cols_; } public int numRows() { return rows_; } public int overlapX() { return overlapX_; } public int overlapY() { return overlapY_; } public Point center() { return new Point(centerX_, centerY_); } public void translate(int dx, int dy) { centerX_ += dx; centerY_ += dy; manager_.drawRegionOverlay(this); } }
true
05e57df4835d5081036dbee328a31e064619ef21
Java
githeadfunk/clock_android
/app/src/main/java/com/example/jwang5/bean/Clock_list_adapter.java
UTF-8
3,045
2.328125
2
[]
no_license
package com.example.jwang5.bean; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.example.jwang5.clock_android.ClockListService; import com.example.jwang5.clock_android.ObjectSerializer; import com.example.jwang5.clock_android.R; import java.io.IOException; import java.util.ArrayList; public class Clock_list_adapter extends ArrayAdapter<clock_bean> { public Clock_list_adapter(Context context, ArrayList<clock_bean> clocks) { super(context, 0, clocks); } @Override public View getView(final int position, View convertView, ViewGroup parent) { // Get the data item for this position clock_bean clock = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.clock_row, parent, false); } // Lookup view for data population TextView time = (TextView) convertView.findViewById(R.id.time); time.setText(clock.getTime()); CheckBox cb = (CheckBox) convertView.findViewById(R.id.active); cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ClockListService cls = ClockListService.getInstance(getContext()); cls.toggleActive(position, isChecked); } }); cb.setChecked(clock.isActive()); TextView tv = (TextView) convertView.findViewById(R.id.Sunday); if (clock.getRepeat()[0]) tv.setTextColor(Color.parseColor("#C70039")); else tv.setTextColor(Color.parseColor("#000000")); tv = (TextView) convertView.findViewById(R.id.Monday); if (clock.getRepeat()[1]) tv.setTextColor(Color.parseColor("#C70039")); else tv.setTextColor(Color.parseColor("#000000")); tv = (TextView) convertView.findViewById(R.id.Tuesday); if (clock.getRepeat()[2]) tv.setTextColor(Color.parseColor("#C70039")); else tv.setTextColor(Color.parseColor("#000000")); tv = (TextView) convertView.findViewById(R.id.Wednesday); if (clock.getRepeat()[3]) tv.setTextColor(Color.parseColor("#C70039")); else tv.setTextColor(Color.parseColor("#000000")); tv = (TextView) convertView.findViewById(R.id.Thursday); if (clock.getRepeat()[4]) tv.setTextColor(Color.parseColor("#C70039")); else tv.setTextColor(Color.parseColor("#000000")); tv = (TextView) convertView.findViewById(R.id.Friday); if (clock.getRepeat()[5]) tv.setTextColor(Color.parseColor("#C70039")); else tv.setTextColor(Color.parseColor("#000000")); tv = (TextView) convertView.findViewById(R.id.Saturday); if (clock.getRepeat()[6]) tv.setTextColor(Color.parseColor("#C70039")); else tv.setTextColor(Color.parseColor("#000000")); return convertView; } }
true
e6c99e17549e533760eb34c88af52083a6aedf3e
Java
rcln/platanne
/code/erwan/dev/lipn-uima-core/src/fr/lipn/nlptools/uima/common/DocumentTextFileWriterCasConsumerAE.java
UTF-8
4,082
2.28125
2
[]
no_license
package fr.lipn.nlptools.uima.common; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.CASException; import org.apache.uima.cas.FSIterator; import org.apache.uima.examples.SourceDocumentInformation; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.resource.ResourceInitializationException; /** * * CAS Consumer component (actually in the AE style), which simply writes the document text contained in a view to a text file. * This can be useful when an AE creates a view in which some data that could be used later is written (though it can also be * extracted from the standard XMI output). * An example: several LIPN components (e.g. TreeTaggerAE) can copy the original program output into a view (see options). Thus * you can write this view to a file and then re-use the program output. * * Parameters: output directory, name of the view to write in the file, encoding, output file(s) extension. * * * @author moreau * */ public class DocumentTextFileWriterCasConsumerAE extends LipnExternalProgramGenericAnnotator { public final static String DEFAULT_EXTENSION = "txt"; File outputDir; String encoding; String extension; String viewName; private int docNum; public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); outputDir = new File((String) context.getConfigParameterValue("OutputDir")); viewName = (String) context.getConfigParameterValue("ViewName"); if (context.getConfigParameterValue("Encoding") != null) { encoding = (String) context.getConfigParameterValue("Encoding"); } else { encoding = DEFAULT_ENCODING; } if (context.getConfigParameterValue("Extension") != null) { extension = (String) context.getConfigParameterValue("Extension"); } else { extension = DEFAULT_EXTENSION; } // check / possibly create dir if (!outputDir.isDirectory() && !outputDir.mkdirs()) { throw new ResourceInitializationException(LipnExternalProgramGenericAnnotator.LIPN_MESSAGE_DIGEST, "unable_create_dir", new Object[]{outputDir.getAbsoluteFile()}); } } @Override public void process(JCas aJCas) throws AnalysisEngineProcessException { // retrieve the filename of the input file from the CAS FSIterator<Annotation> it = FSIteratorFactory.createFSIterator(aJCas, SourceDocumentInformation.type, false); File outFile = null; if (it.hasNext()) { SourceDocumentInformation fileLoc = (SourceDocumentInformation) it.next(); File inFile; try { inFile = new File(new URL(fileLoc.getUri()).getPath()); String outFileName = inFile.getName(); if (fileLoc.getOffsetInSource() > 0) { outFileName += ("_" + fileLoc.getOffsetInSource()); } outFileName += "."+ extension; outFile = new File(outputDir, outFileName); } catch (MalformedURLException e1) { // invalid URL, use default processing below } } if (outFile == null) { outFile = new File(outputDir, "doc" + docNum++ + "." + extension); } try { OutputStreamWriter output = new OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding); output.write(aJCas.getView(viewName).getDocumentText()); output.close(); } catch (UnsupportedEncodingException ee) { throw new AnalysisEngineProcessException(LIPN_MESSAGE_DIGEST, "unknown_encoding", new Object[]{encoding}, ee); } catch (CASException ce) { throw new AnalysisEngineProcessException(LIPN_MESSAGE_DIGEST, "view_not_found", new Object[]{viewName}, ce); } catch (IOException ioe) { throw new AnalysisEngineProcessException(LIPN_MESSAGE_DIGEST, "unable_write_file", new Object[]{outFile.getAbsolutePath()}, ioe); } } }
true
4eabb3daaae711306fe92e216958264c386c4277
Java
czgcampos/DSS
/Grupo13/Aplicação/src/Business/Actor.java
UTF-8
2,846
2.84375
3
[]
no_license
package Business; import Data.DespesaDAO; import java.util.ArrayList; import java.util.List; import java.util.Observable; public abstract class Actor extends Observable { private String moradaCasa; private int telemovel; private String email; private String nome; private String password; private String cargo; private DespesaDAO despesas; public Actor() { this.moradaCasa=""; this.telemovel=123456789; this.email=""; this.nome=""; this.password=""; this.cargo=""; } public Actor(String moradaCasa, int telemovel, String mail, String nome, String password, String cargo) { this.moradaCasa=moradaCasa; this.telemovel=telemovel; this.email=mail; this.nome=nome; this.password=password; this.cargo=cargo; } public Actor(Actor a2) { this(a2.getMoradaCasa(),a2.getTelemovel(),a2.getEmail(),a2.getNome(),a2.getPassword(), a2.getCargo()); } public String getCargo(){ return cargo; } public void setCargo(String cargo){ this.cargo=cargo; } public String getEmail() { return this.email; } public void setEmail(String newEmail) { this.email = newEmail; } public int getTelemovel() { return this.telemovel; } public void setTelemovel(int newTelemovel) { this.telemovel = newTelemovel; } public void setNome(String newNome) { this.nome = newNome; } public String getNome() { return this.nome; } public void setMoradaCasa(String newMorada) { this.moradaCasa = newMorada; } public String getMoradaCasa() { return this.moradaCasa; } public String getPassword() { return this.password; } public void setPassword(String newPass) { this.password = newPass; } public abstract Actor clone(); public boolean equals(Object o) { if(o == this) return true; if(o == null || o.getClass() != this.getClass()) return false; else { Actor a = (Actor) o; return (this.nome.equals(a.getNome()) && this.password.equals(a.getPassword()) && this.moradaCasa.equals(a.getMoradaCasa()) && this.telemovel==a.getTelemovel() && this.email.equals(a.getEmail()) && this.cargo.equals(a.getCargo())); } } public String toString() { StringBuilder s = new StringBuilder(); s.append("Email: ") ; s.append(this.email); s.append(" . Nome: "); s.append(this.nome); s.append(". Telemovel: "); s.append(this.telemovel); s.append(". Morada de Casa: "); s.append(this.moradaCasa); s.append(". Cargo: "); s.append(this.cargo); return s.toString(); } }
true
15f3d32308b120d2a7f53251cd2f30924a183867
Java
1835434698/videoRecording
/recordermanager/src/main/java/com/mingyuechunqiu/recordermanager/feature/main/container/RecordVideoActivity.java
UTF-8
7,603
1.90625
2
[]
no_license
package com.mingyuechunqiu.recordermanager.feature.main.container; import android.os.Bundle; import android.os.Environment; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageView; import androidx.appcompat.widget.AppCompatTextView; import android.text.TextUtils; import com.mingyuechunqiu.recordermanager.R; import com.mingyuechunqiu.recordermanager.data.bean.RecordVideoOption; import com.mingyuechunqiu.recordermanager.data.bean.RecordVideoRequestOption; import com.mingyuechunqiu.recordermanager.data.bean.RecordVideoResultInfo; import com.mingyuechunqiu.recordermanager.data.bean.RecorderOption; import com.mingyuechunqiu.recordermanager.feature.main.detail.RecordVideoFragment; import com.mingyuechunqiu.recordermanager.ui.activity.BaseRecordVideoActivity; import com.mingyuechunqiu.recordermanager.ui.widget.CircleProgressButton; import com.mingyuechunqiu.recordermanager.util.RecordPermissionUtils; import java.io.File; import java.util.List; import pub.devrel.easypermissions.EasyPermissions; import static com.mingyuechunqiu.recordermanager.data.constants.Constants.EXTRA_RECORD_VIDEO_REQUEST_OPTION; import static com.mingyuechunqiu.recordermanager.data.constants.Constants.EXTRA_RECORD_VIDEO_RESULT_INFO; import static com.mingyuechunqiu.recordermanager.data.constants.Constants.SUFFIX_MP4; /** * <pre> * author : xyj * Github : https://github.com/MingYueChunQiu * e-mail : yujie.xi@ehailuo.com * time : 2019/1/28 * desc : 录制视频Activity * 继承自AppCompatActivity * version: 1.0 * </pre> */ public class RecordVideoActivity extends BaseRecordVideoActivity implements EasyPermissions.PermissionCallbacks { private RecordVideoFragment mRecordVideoFg; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.rm_activity_record_video); if (!RecordPermissionUtils.checkRecordPermissions(this)) { finishActivity(); return; } if (getSupportFragmentManager() != null) { String filePath = getFilesDir().getAbsolutePath() + File.separator + System.currentTimeMillis() + SUFFIX_MP4; int maxDuration = 120; if (getIntent() != null) { RecordVideoRequestOption option = getIntent().getParcelableExtra(EXTRA_RECORD_VIDEO_REQUEST_OPTION); maxDuration = option == null ? 120 : option.getMaxDuration(); filePath = option == null ? null : option.getFilePath(); } if (TextUtils.isEmpty(filePath)) { File file = getExternalFilesDir(Environment.DIRECTORY_MOVIES); if (file != null) { filePath = file.getAbsolutePath() + File.separator + System.currentTimeMillis() + SUFFIX_MP4; } } RecordVideoOption option = new RecordVideoOption.Builder() .setRecorderOption(new RecorderOption.Builder() .buildDefaultVideoBean(filePath)) .setMaxDuration(maxDuration) .setOnRecordVideoListener(new RecordVideoOption.OnRecordVideoListener() { @Override public void onCompleteRecordVideo(String filePath, int videoDuration) { } @Override public void onClickConfirm(String filePath, int videoDuration) { if (getIntent() != null) { getIntent().putExtra(EXTRA_RECORD_VIDEO_RESULT_INFO, new RecordVideoResultInfo.Builder() .setDuration(videoDuration) .setFilePath(filePath) .build()); setResult(RESULT_OK, getIntent()); } finishActivity(); } @Override public void onClickCancel(String filePath, int videoDuration) { } @Override public void onClickBack() { finishActivity(); } }).build(); mRecordVideoFg = RecordVideoFragment.newInstance(option); getSupportFragmentManager().beginTransaction() .replace(R.id.fl_record_video_container, mRecordVideoFg, RecordVideoFragment.class.getSimpleName()) .commit(); } } @Override protected void onDestroy() { super.onDestroy(); if (getSupportFragmentManager() != null && mRecordVideoFg != null) { getSupportFragmentManager().beginTransaction() .remove(mRecordVideoFg) .commitAllowingStateLoss(); } mRecordVideoFg = null; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); } @Override public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) { } @Override public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) { RecordPermissionUtils.handleOnPermissionDenied(this); } /** * 获取计时控件 * * @return 返回计时AppCompatTextView */ protected AppCompatTextView getTimingView() { return mRecordVideoFg == null ? null : mRecordVideoFg.getTimingView(); } /** * 获取圆形进度按钮 * * @return 返回进度CircleProgressButton */ protected CircleProgressButton getCircleProgressButton() { return mRecordVideoFg == null ? null : mRecordVideoFg.getCircleProgressButton(); } /** * 获取翻转摄像头控件 * * @return 返回翻转摄像头AppCompatImageView */ protected AppCompatImageView getFlipCameraView() { return mRecordVideoFg == null ? null : mRecordVideoFg.getFlipCameraView(); } /** * 获取播放控件 * * @return 返回播放AppCompatImageView */ protected AppCompatImageView getPlayView() { return mRecordVideoFg == null ? null : mRecordVideoFg.getPlayView(); } /** * 获取取消控件 * * @return 返回取消AppCompatImageView */ protected AppCompatImageView getCancelView() { return mRecordVideoFg == null ? null : mRecordVideoFg.getCancelView(); } /** * 获取确认控件 * * @return 返回确认AppCompatImageView */ protected AppCompatImageView getConfirmView() { return mRecordVideoFg == null ? null : mRecordVideoFg.getConfirmView(); } /** * 获取返回控件 * * @return 返回返回AppCompatImageView */ protected AppCompatImageView getBackView() { return mRecordVideoFg == null ? null : mRecordVideoFg.getBackView(); } /** * 销毁界面 */ private void finishActivity() { finish(); overridePendingTransition(R.anim.rm_fix_stand, R.anim.rm_slide_out_bottom); } }
true
df2ef949252d16d5ad96c7c8e5df1fd40eecade7
Java
JanetLiu1102/tj_cms
/src/main/java/com/tjch/cms/exception/BusinessException.java
UTF-8
659
2.296875
2
[]
no_license
package com.tjch.cms.exception; /** * @author Dreamhai * @Date 2017/11/6 10:19 */ public class BusinessException extends Exception { private static final long serialVersionUID = -778142600038732285L; private String message; private String code; public BusinessException(String message) { this.message = message; this.code = "文件传输错误"; } public BusinessException(String code, String message) { this.code = code; this.message = message; } @Override public String getMessage() { return message; } public String getCode() { return code; } }
true
d3b746ae820d118d43be604e6a033a21448b9293
Java
lingg1011/javaa
/src/GUI/PanelPhieuNhap.java
UTF-8
39,462
1.648438
2
[]
no_license
package GUI; import BUS.chitietphieunhapBUS; import BUS.nhaccBUS; import BUS.nhanvienBUS; import BUS.phieumuontraBUS; import BUS.phieunhapBUS; import BUS.sachBUS; import DTO.chitietphieunhapDTO; import DTO.nhaccDTO; import DTO.nhanvienDTO; import DTO.phieunhapDTO; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.sun.webkit.ThemeClient; import interfaces.InChangePanelDeal; import interfaces.InDocGiaSelect; import interfaces.InNhaCCSelect; import interfaces.InNhanVienSelect; import interfaces.QueryCallBack; import java.awt.Dimension; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.jdatepicker.impl.JDatePanelImpl; import org.jdatepicker.impl.JDatePickerImpl; import org.jdatepicker.impl.UtilDateModel; import untils.CheckData; import untils.DateLabelFormatter; import untils.OutFile; import untils.cons; /** * * @author Admin */ public class PanelPhieuNhap extends javax.swing.JPanel implements QueryCallBack, InNhanVienSelect, InNhaCCSelect { DefaultTableModel dtm; ArrayList<phieunhapDTO> arr = new ArrayList<>(); JDatePickerImpl datePicker; JDatePickerImpl datePicker2; JDatePickerImpl datePickerngaynhap; UtilDateModel model = new UtilDateModel(); UtilDateModel model2 = new UtilDateModel(); UtilDateModel modelngaynhap = new UtilDateModel(); Panelchoosenhanvien panelNv; PanelNhaCC panelNcc; InChangePanelDeal inChangePanelDeal; phieunhapDTO current = new phieunhapDTO(); public PanelPhieuNhap(InChangePanelDeal inChangePanelDeal) { initComponents(); this.inChangePanelDeal = inChangePanelDeal; buttonAddnhanvien.setVisible(false); buttonAddnhacc.setVisible(false); tftongtien.setEditable(false); tfnv.setEditable(false); tfncc.setEditable(false); // jButton13.setVisible(false); panelNv = new Panelchoosenhanvien(this); panelNv.setBackground(new java.awt.Color(102, 102, 102)); panelNv.setForeground(new java.awt.Color(0, 204, 204)); panelNv.setLayout(null); panelNv.setBounds(0, 0, 1024, 768); panelNv.setVisible(false); add(panelNv); panelNcc = new PanelNhaCC(this); panelNcc.setBackground(new java.awt.Color(102, 102, 102)); panelNcc.setForeground(new java.awt.Color(0, 204, 204)); panelNcc.setLayout(null); panelNcc.setBounds(0, 0, 1024, 768); panelNcc.setVisible(false); add(panelNcc); Properties p = new Properties(); p.put("text.today", "Today"); p.put("text.month", "Month"); p.put("text.year", "Year"); JDatePanelImpl datePanel = new JDatePanelImpl(model, p); JDatePanelImpl datePane2 = new JDatePanelImpl(model2, p); JDatePanelImpl datePanengaynhap = new JDatePanelImpl(modelngaynhap, p); datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter()); // datePicker.setBounds(10, 130, 120, 25); datePicker.setBounds(50, 0, 150, 40); jPanel1.add(datePicker); datePicker2 = new JDatePickerImpl(datePane2, new DateLabelFormatter()); // datePicker2.setBounds(280, 130, 120, 25); datePicker2.setBounds(250, 0, 170, 40); jPanel1.add(datePicker2); datePickerngaynhap = new JDatePickerImpl(datePanengaynhap, new DateLabelFormatter()); // datePickerngaynhap.setBounds(767, 10, 20, 25); datePickerngaynhap.setBounds(380, 200, 33, 30); jPanel3.add(datePickerngaynhap); datePickerngaynhap.setVisible(false); datePickerngaynhap.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { Date today = new Date(); today.getTime(); if (modelngaynhap.getValue().before(today)) { tfngaynhap.setText(new SimpleDateFormat("yyyy-MM-dd").format(modelngaynhap.getValue())); } else { tfngaynhap.setText(new SimpleDateFormat("yyyy-MM-dd").format(today)); } // tfngaynhap.setText(new SimpleDateFormat("yyyy-MM-dd").format(modelngaynhap.getValue())); } }); loadPhieuNhap(); initData(); initEvent(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jButton11 = new javax.swing.JButton(); tfphieunhap = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); tfnv = new javax.swing.JTextField(); jButton4 = new javax.swing.JButton(); tfncc = new javax.swing.JTextField(); buttonAddnhanvien = new javax.swing.JButton(); buttonAddnhacc = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); tfngaynhap = new javax.swing.JTextField(); jButton5 = new javax.swing.JButton(); tftongtien = new javax.swing.JTextField(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox<>(); jTextField7 = new javax.swing.JTextField(); jButton9 = new javax.swing.JButton(); jButton13 = new javax.swing.JButton(); jButton14 = new javax.swing.JButton(); jButton15 = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); buttonThemChiTiet = new javax.swing.JButton(); jButton10 = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setPreferredSize(new java.awt.Dimension(685, 795)); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setPreferredSize(new java.awt.Dimension(685, 795)); jPanel2.setLayout(null); jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Thông tin phiếu nhập", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(0, 102, 102))); // NOI18N jPanel3.setForeground(new java.awt.Color(0, 102, 102)); jPanel3.setLayout(null); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 0, 0)); jLabel3.setText("Phiếu Nhập"); jPanel3.add(jLabel3); jLabel3.setBounds(16, 16, 223, 22); jButton11.setText("Mã Phiếu Nhập"); jPanel3.add(jButton11); jButton11.setBounds(16, 70, 130, 23); jPanel3.add(tfphieunhap); tfphieunhap.setBounds(152, 69, 212, 25); jButton2.setText("Nhân Viên"); jPanel3.add(jButton2); jButton2.setBounds(16, 113, 130, 23); jPanel3.add(tfnv); tfnv.setBounds(152, 112, 212, 25); jButton4.setText("Nhà Cung Cấp"); jPanel3.add(jButton4); jButton4.setBounds(16, 156, 130, 23); tfncc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tfnccActionPerformed(evt); } }); jPanel3.add(tfncc); tfncc.setBounds(152, 155, 212, 25); buttonAddnhanvien.setText("jButton13"); buttonAddnhanvien.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonAddnhanvienActionPerformed(evt); } }); jPanel3.add(buttonAddnhanvien); buttonAddnhanvien.setBounds(380, 110, 33, 30); buttonAddnhacc.setText("jButton13"); buttonAddnhacc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonAddnhaccActionPerformed(evt); } }); jPanel3.add(buttonAddnhacc); buttonAddnhacc.setBounds(380, 153, 33, 30); jButton3.setText("Ngày Nhập"); jPanel3.add(jButton3); jButton3.setBounds(16, 199, 130, 23); jPanel3.add(tfngaynhap); tfngaynhap.setBounds(152, 198, 212, 25); jButton5.setText("Tổng Tiền"); jPanel3.add(jButton5); jButton5.setBounds(16, 242, 130, 23); jPanel3.add(tftongtien); tftongtien.setBounds(152, 241, 212, 25); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setLayout(null); jLabel2.setText("Đến"); jPanel1.add(jLabel2); jLabel2.setBounds(210, 0, 50, 40); jLabel4.setText("Từ"); jPanel1.add(jLabel4); jLabel4.setBounds(0, 0, 40, 40); jPanel3.add(jPanel1); jPanel1.setBounds(20, 320, 420, 40); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Mã Phiếu Nhập", "Nhân Viên", "Nhà Cung Cấp", "Ngày Nhập" })); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); jPanel3.add(jComboBox1); jComboBox1.setBounds(16, 284, 96, 30); jPanel3.add(jTextField7); jTextField7.setBounds(136, 284, 228, 30); jButton9.setText("Tìm Kiếm"); jButton9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton9ActionPerformed(evt); } }); jPanel3.add(jButton9); jButton9.setBounds(370, 284, 90, 30); jButton13.setText("Xuất Excel"); jButton13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton13ActionPerformed(evt); } }); jPanel3.add(jButton13); jButton13.setBounds(20, 40, 110, 23); jButton14.setText("Xuất PDF"); jButton14.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton14ActionPerformed(evt); } }); jPanel3.add(jButton14); jButton14.setBounds(150, 30, 90, 23); jButton15.setText("Đọc Excel"); jButton15.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton15ActionPerformed(evt); } }); jPanel3.add(jButton15); jButton15.setBounds(270, 30, 100, 23); jButton1.setText("Lưu ĐTB"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel3.add(jButton1); jButton1.setBounds(390, 30, 73, 23); jPanel2.add(jPanel3); jPanel3.setBounds(0, 0, 490, 380); jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Thực hiện", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 0, 51))); // NOI18N jButton6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton6.setText("Thêm"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); jButton7.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton7.setText("Xóa"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); jButton8.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton8.setText("Sửa"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); buttonThemChiTiet.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N buttonThemChiTiet.setText("Thêm Chi Tiết"); buttonThemChiTiet.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonThemChiTietActionPerformed(evt); } }); jButton10.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton10.setText("Back"); jButton10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton10ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jButton7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(buttonThemChiTiet, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(jButton6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE) .addComponent(jButton8, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton10, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(buttonThemChiTiet, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2.add(jPanel4); jPanel4.setBounds(486, 0, 180, 380); jPanel5.setBackground(new java.awt.Color(255, 255, 255)); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Danh sách phiếu nhập", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 0, 102))); // NOI18N jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jTable1.setRowHeight(40); jTable1.setRowMargin(10); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 634, Short.MAX_VALUE) .addContainerGap()) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE) .addContainerGap()) ); jPanel2.add(jPanel5); jPanel5.setBounds(0, 386, 666, 410); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 793, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 11, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void buttonAddnhaccActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddnhaccActionPerformed jPanel2.setVisible(false); panelNcc.setVisible(true); revalidate(); }//GEN-LAST:event_buttonAddnhaccActionPerformed private void tfnccActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfnccActionPerformed }//GEN-LAST:event_tfnccActionPerformed private void buttonAddnhanvienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddnhanvienActionPerformed jPanel2.setVisible(false); panelNv.setVisible(true); revalidate(); }//GEN-LAST:event_buttonAddnhanvienActionPerformed private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed // TODO add your handling code here: jTable1.setModel(dtm); jButton10.setVisible(false); }//GEN-LAST:event_jButton10ActionPerformed private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed String[] header = {"Mã Phiếu Nhập", "Nhân Viên", "Nhà Cung Cấp", "Ngày Nhập", "Tổng Tiền"}; DefaultTableModel dtmsearch = new DefaultTableModel(header, 0); ArrayList<phieunhapDTO> s; if (jComboBox1.getSelectedItem().equals("Ngày Nhập")) { s = phieunhapBUS.timkiemphieuNM(model.getValue(), model2.getValue()); } else { if (jComboBox1.getSelectedItem().equals("Mã Phiếu Nhập")) { if (CheckData.checkNumber(jTextField7.getText().toString().trim())) { s = phieunhapBUS.timkiemPhieuNhap(String.valueOf(jComboBox1.getSelectedItem()), jTextField7.getText().toLowerCase().trim()); } else { JOptionPane.showMessageDialog(null, "Bạn phải nhập số!"); } } s = phieunhapBUS.timkiemPhieuNhap(String.valueOf(jComboBox1.getSelectedItem()), jTextField7.getText().toLowerCase().trim()); } if (s.size() != 0) { phieunhapDTO pmt = new phieunhapDTO(); for (int i = 0; i < s.size(); i++) { pmt = s.get(i); String mapn = pmt.getMaphieuphap(); String manv = pmt.getManv(); String mancc = pmt.getManhacc(); int tongtien = pmt.getTongtien(); Date ngaynhap = pmt.getNgaynhap(); // System.out.println("ngày hẹn trả" + ngayhentra); Object[] row = {mapn, nhanvienBUS.getTenNhanVien(manv), nhaccBUS.gettenNhacc(mancc), ngaynhap, tongtien}; dtmsearch.addRow(row); } jTable1.setModel(dtmsearch); setView(s.get(0)); jButton10.setVisible(true); } else { JOptionPane.showMessageDialog(null, "Không có kết quả phù hợp!"); } }//GEN-LAST:event_jButton9ActionPerformed private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox1ActionPerformed private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed if (jButton8.getText().toString().equals("Sửa")) { // buttonAddnhanvien.setVisible(true); buttonAddnhacc.setVisible(true); datePickerngaynhap.setVisible(true); // jButton13.setVisible(true); jButton8.setText("Xác nhận sửa"); buttonThemChiTiet.setVisible(true); jButton6.setVisible(false); jButton7.setVisible(false); // tfphieunhap.setEditable(false); } else { buttonAddnhanvien.setVisible(false); buttonAddnhacc.setVisible(false); datePickerngaynhap.setVisible(false); // tfphieunhap.setEditable(true); buttonThemChiTiet.setVisible(false); jButton6.setVisible(true); jButton7.setVisible(true); jButton8.setText("Sửa"); phieunhapDTO ctp = new phieunhapDTO(); ctp.setMaphieuphap(tfphieunhap.getText().trim()); ctp.setManv(current.getManv()); ctp.setManhacc(current.getManhacc()); ctp.setTongtien(Integer.parseInt(tftongtien.getText().trim())); Date date1 = null, date2 = null; try { date1 = new SimpleDateFormat("yyyy-MM-dd").parse(tfngaynhap.getText().trim()); // date2 = new SimpleDateFormat("dd/MM/yyyy").parse(jTextField5.getText().trim()); } catch (ParseException ex) { Logger.getLogger(PanelLoanSlipDetails.class.getName()).log(Level.SEVERE, null, ex); } ctp.setNgaynhap(date1); // ctp.setNgayTra(date2); phieunhapBUS.suaPhieuNhap(ctp, this); } }//GEN-LAST:event_jButton8ActionPerformed private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed // TODO add your handling code here: phieunhapBUS.xoaPhieuNhap(tfphieunhap.getText().toString().trim(), this); }//GEN-LAST:event_jButton7ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed if (jButton6.getText().toString().equals("Thêm")) { // buttonAddnhanvien.setVisible(true); buttonAddnhacc.setVisible(true); datePickerngaynhap.setVisible(true); jButton7.setVisible(false); jButton8.setVisible(false); // jButton13.setVisible(true); ArrayList<phieunhapDTO> arr = phieunhapBUS.getPhieuNhap(); tfphieunhap.setText("" + (Integer.parseInt(arr.get(arr.size() - 1).getMaphieuphap()) + 1)); jButton6.setText("Xác nhận thêm"); buttonThemChiTiet.setVisible(true); Date today = new Date(); today.getTime(); tfngaynhap.setText(new SimpleDateFormat("yyyy-MM-dd").format(today)); tfnv.setText(cons.nv.getTenNhanVien()); current.setManv(cons.nv.getMaNV()); tfncc.setText(""); tftongtien.setText(""); // jTextField5.setText(""); } else { if (tftongtien.getText().length() != 0) { buttonAddnhanvien.setVisible(false); buttonAddnhacc.setVisible(false); datePickerngaynhap.setVisible(false); buttonThemChiTiet.setVisible(false); jButton6.setText("Thêm"); jButton7.setVisible(true); jButton8.setVisible(true); phieunhapDTO ctp = new phieunhapDTO(); ctp.setMaphieuphap(tfphieunhap.getText().trim()); ctp.setManv(current.getManv()); ctp.setManhacc(current.getManhacc()); ctp.setTongtien(Integer.parseInt(tftongtien.getText().trim())); Date date1 = null, date2 = null; try { date1 = new SimpleDateFormat("yyyy-MM-dd").parse(tfngaynhap.getText().trim()); // date2 = new SimpleDateFormat("dd/MM/yyyy").parse(jTextField5.getText().trim()); } catch (ParseException ex) { Logger.getLogger(PanelLoanSlipDetails.class.getName()).log(Level.SEVERE, null, ex); } ctp.setNgaynhap(date1); // ctp.setNgayTra(date2); phieunhapBUS.themPhieuNhap(ctp, this); } else { JOptionPane.showMessageDialog(null, "Bạn cần nhập vào chi tiết phiếu nhập"); } } }//GEN-LAST:event_jButton6ActionPerformed private void buttonThemChiTietActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonThemChiTietActionPerformed // TODO add your handling code here: JFrame themchitiet = new JFrame(); themchitiet.setVisible(true); // Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // themchitiet.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2); themchitiet.setSize(1044, 768); themchitiet.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosed(java.awt.event.WindowEvent windowEvent) { // your code tftongtien.setText(chitietphieunhapBUS.getTongTien(tfphieunhap.getText().toString().trim()) + ""); } }); // themchitiet.addWindowListener(new java.awt.event.WindowAdapter() { // // @Override // public void windowClosing(java.awt.event.WindowEvent windowEvent) { // } // }); PanelChiTietPhieuNhap pb = new PanelChiTietPhieuNhap(tfphieunhap.getText().trim(), 1); pb.setBounds(0, 0, 1024, 768); themchitiet.add(pb); }//GEN-LAST:event_buttonThemChiTietActionPerformed private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed // TODO add your handling code here: try { OutFile.writeExcel(jTable1, "system\\file\\excel\\phieunhap\\", true); } catch (IOException ex) { Logger.getLogger(PanelBook.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton13ActionPerformed private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed // TODO add your handling code here: Document document = new Document(); try { // khởi tạo một PdfWriter truyền vào document và FileOutputStream PdfWriter.getInstance(document, new FileOutputStream(OutFile.createFilePDF("system\\file\\pdf\\phieunhap\\"))); // mở file để thực hiện viết document.open(); // thêm nội dung sử dụng add function document.add(new Paragraph(OutFile.removeAccent("Phiếu Nhập "))); document.add(new Paragraph(OutFile.removeAccent("Mã Phiếu Nhập: " + tfphieunhap.getText()))); document.add(new Paragraph(OutFile.removeAccent("Nhân Viên: " + tfnv.getText()))); document.add(new Paragraph(OutFile.removeAccent("Nhà Cung Cấp: " + tfncc.getText()))); document.add(new Paragraph(OutFile.removeAccent("Ngày Nhập: " + String.valueOf(tfngaynhap.getText())))); document.add(new Paragraph(OutFile.removeAccent("Danh sách các loại sách được nhập"))); PdfPTable table = new PdfPTable(3); PdfPCell header1 = new PdfPCell(new Paragraph("Ten Sach")); PdfPCell header2 = new PdfPCell(new Paragraph("So Luong")); PdfPCell header3 = new PdfPCell(new Paragraph("Đon Gia")); table.addCell(header1); table.addCell(header2); table.addCell(header3); ArrayList<chitietphieunhapDTO> ctpn = chitietphieunhapBUS.getChiTietPhieuNhap(); for (int i = 0; i < ctpn.size(); i++) { if (ctpn.get(i).getMaphieunhap().equals(tfphieunhap.getText())) { String tensach = sachBUS.getTenSach(ctpn.get(i).getMasach()); PdfPCell data1 = new PdfPCell(new Paragraph(OutFile.removeAccent(tensach))); PdfPCell data2 = new PdfPCell(new Paragraph(ctpn.get(i).getSoluong())); PdfPCell data3 = new PdfPCell(new Paragraph(ctpn.get(i).getDongia())); table.addCell(data1); table.addCell(data2); table.addCell(data3); } } document.add(table); document.add(new Paragraph("Tong tien: " + tftongtien.getText())); //Khởi tạo 3 ô header //Thêm 3 ô header vào table document.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException ex) { Logger.getLogger(PanelEmployees.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton14ActionPerformed private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton15ActionPerformed try { // TODO add your handling code here: jTable1.setModel(OutFile.readExcel("system\\database\\data\\phieunhap.xls")); jButton1.setVisible(true); } catch (IOException ex) { Logger.getLogger(PanelPhieuNhap.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton15ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed TableModel model = jTable1.getModel(); for (int i = 0; i < model.getRowCount(); i++) { phieunhapDTO pn = new phieunhapDTO(); pn.setManv(model.getValueAt(i, 1) + ""); pn.setManhacc(model.getValueAt(i, 2) + ""); try { Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(model.getValueAt(i, 3) + ""); pn.setNgaynhap(date1); } catch (ParseException ex) { Logger.getLogger(PanelPhieuNhap.class.getName()).log(Level.SEVERE, null, ex); } pn.setTongtien(Integer.parseInt(model.getValueAt(i, 4) + "")); phieunhapBUS.themPhieuNhap(pn, this); } // TODO add your handling code here: jButton1.setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buttonAddnhacc; private javax.swing.JButton buttonAddnhanvien; private javax.swing.JButton buttonThemChiTiet; private javax.swing.JButton jButton1; private javax.swing.JButton jButton10; private javax.swing.JButton jButton11; private javax.swing.JButton jButton13; private javax.swing.JButton jButton14; private javax.swing.JButton jButton15; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField7; private javax.swing.JTextField tfncc; private javax.swing.JTextField tfngaynhap; private javax.swing.JTextField tfnv; private javax.swing.JTextField tfphieunhap; private javax.swing.JTextField tftongtien; // End of variables declaration//GEN-END:variables @Override public void onSuccess() { loadPhieuNhap(); } @Override public void onFailed(String error) { } private void loadPhieuNhap() { String[] header = {"Mã Phiếu Nhập", "Nhân Viên", "Nhà Cung Cấp", "Ngày Nhập", "Tổng Tiền"}; dtm = new DefaultTableModel(header, 0); arr = phieunhapBUS.getPhieuNhap(); phieunhapDTO pmt = new phieunhapDTO(); for (int i = 0; i < arr.size(); i++) { pmt = arr.get(i); String mapp = pmt.getMaphieuphap(); String manv = pmt.getManv(); String mancc = pmt.getManhacc(); int tongtien = pmt.getTongtien(); Date ngaynhap = pmt.getNgaynhap(); // System.out.println("ngày hẹn trả" + ngayhentra); Object[] row = {mapp, nhanvienBUS.getTenNhanVien(manv), nhaccBUS.gettenNhacc(mancc), ngaynhap, tongtien}; dtm.addRow(row); } jTable1.setModel(dtm); setView(arr.get(0)); } public void setView(phieunhapDTO pmt) { if (jButton6.getText().equals("Thêm") && jButton8.getText().equals("Sửa")) { tfphieunhap.setText(pmt.getMaphieuphap() + ""); tfnv.setText(nhanvienBUS.getTenNhanVien(pmt.getManv())); tfncc.setText(nhaccBUS.gettenNhacc(pmt.getManhacc())); tfngaynhap.setText(pmt.getNgaynhap().toString()); // jTextField5.setText(pmt.getNgayTra().toString()); tftongtien.setText(pmt.getTongtien() + ""); current.setManv(pmt.getManv()); current.setManhacc(pmt.getManhacc()); } } private void initData() { tfphieunhap.setEditable(false); buttonThemChiTiet.setVisible(false); tfphieunhap.setEditable(false); tfngaynhap.setEditable(false); jButton10.setVisible(false); jPanel1.setVisible(false); jButton1.setVisible(false); // datePicker.setVisible(false); // datePicker2.setVisible(false); } private void initEvent() { jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { try { setView(arr.get(jTable1.getSelectedRow())); } catch (Exception e) { } } }); jTable1.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent mouseEvent) { JTable table = (JTable) mouseEvent.getSource(); Point point = mouseEvent.getPoint(); int row = table.rowAtPoint(point); if (mouseEvent.getClickCount() == 2 && table.getSelectedRow() != -1) { inChangePanelDeal.onChange(arr.get(jTable1.getSelectedRow()).getMaphieuphap()); } } }); jComboBox1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { jTextField7.setEnabled(false); if (jComboBox1.getSelectedItem().equals("Ngày Nhập")) { jPanel1.setVisible(true); // datePicker.setVisible(true); // datePicker2.setVisible(true); // jTextField7.setEnabled(false); return; } jTextField7.setEditable(true); // jTextField7.setEnabled(true); jPanel1.setVisible(false); // datePicker.setVisible(false); // datePicker2.setVisible(false); } }); } @Override public void nhanvien(nhanvienDTO tg) { tfnv.setText(tg.getTenNhanVien()); jPanel2.setVisible(true); panelNv.setVisible(false); current.setManv(tg.getMaNV()); } @Override public void nhacc(nhaccDTO tg) { tfncc.setText(tg.getTenncc()); jPanel2.setVisible(true); panelNcc.setVisible(false); current.setManhacc(tg.getMancc()); } }
true
a0b71be43835557161694d4893a788254a5e6459
Java
Neumann789/springboot-learn
/jode-1.1.2/output/com/javosize/actions/CatInterceptionAction.java
UTF-8
1,641
2.375
2
[]
no_license
/* CatInterceptionAction - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ package com.javosize.actions; import java.util.Iterator; import java.util.List; import com.javosize.agent.Agent; import com.javosize.agent.Interception; import com.javosize.print.TextReport; public class CatInterceptionAction extends Action { private static final long serialVersionUID = 6309038877613667056L; private String id = ""; public CatInterceptionAction(String id) { this.id = id; } public String execute() { List result = Agent.getInterceptions(); TextReport results = new TextReport(); Iterator iterator = result.iterator(); while (iterator.hasNext()) { Interception inter = (Interception) iterator.next(); if (inter.getId().equals(id)) { results.addSection("General", (new String[] { new StringBuilder().append("Id: ").append (inter.getId()).toString(), new StringBuilder().append ("ClassName RegExp: ").append (inter.getClassNameRegexp()) .toString(), new StringBuilder().append ("MethodName Regexp: ").append (inter.getMethodNameRegexp()) .toString(), new StringBuilder().append("Type: ") .append (inter.getType().toString()) .toString() })); results.addSection("Detail", (new String[] { new StringBuilder().append("src: ") .append (inter.getInterceptorCode()) .toString() })); } } return new StringBuilder().append(results.toString()).append("\n") .toString(); } }
true
7f8df3af6ca7bc5f6dedf47b66eaf31966c26e60
Java
lucigrigo/UdemyCourses
/AdvancedAlgorithmsInJavaUDEMY/algorithm/src/test/java/lucian/grigore/algorithm/suffixtrie/SuffixTrieMapTest.java
UTF-8
738
2.484375
2
[]
no_license
package lucian.grigore.algorithm.suffixtrie; import org.junit.Assert; import org.junit.Test; public class SuffixTrieMapTest { @Test public void insertTest() { SuffixTrieMap t = new SuffixTrieMap("banana"); Assert.assertNotNull(t.root.children['a']); Assert.assertNotNull(t.root.children['b']); Assert.assertNotNull(t.root.children['n']); Assert.assertNull(t.root.children['c']); Assert.assertNotNull(t.root.children['b'].children['a']); Assert.assertNull(t.root.children['b'].children['n']); Assert.assertNotNull(t.root.children['a'].children['$']); Assert.assertNotNull(t.root.children['a'].children['n']); System.out.println(t.root); } }
true
51fc22fee64fea2fe5cf8bb5c31e190ae0cc2cc3
Java
Drakoulious/rw_chat_p
/src/main/java/ru/ilonich/roswarcp/client/Parser.java
UTF-8
4,655
2.390625
2
[]
no_license
package ru.ilonich.roswarcp.client; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.ilonich.roswarcp.model.Message; import ru.ilonich.roswarcp.util.MessageDeserializer; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; public final class Parser { private static Logger LOG = LoggerFactory.getLogger(Parser.class); private static final ObjectMapper mapper; private static final String SYSTEM_TYPE = "system"; private static final Function<Message, Message> reformatSystemMessage = (message -> { Document doc = Jsoup.parse(message.getText()); if (!doc.select("span").isEmpty()) { message.setFraction(doc.select("span.user i").attr("title")); Elements clanSpan = doc.select("span.user a[href^=/clan/]"); if (!clanSpan.isEmpty()) { message.setClanId(Integer.valueOf(clanSpan.attr("href").replaceAll("/", "").substring(4))); message.setClanName(doc.select("img.clan-icon").attr("title")); } message.setNickName(doc.select("span.user a[href^=/player/]").text()); message.setLinkedPlayerId(message.getPlayerId()); //газетчик делает объявления обычно message.setPlayerId(Integer.valueOf(doc.select("span.user a[href^=/player/]").attr("href").replaceAll("/", "").substring(6))); message.setLevel(Integer.valueOf(doc.select("span.level").text().replaceAll("[^\\d]", ""))); message.setItemName(doc.select("div.objects div.padding img[src$=.png").attr("alt")); message.setItemCount(Integer.valueOf(doc.select("div.count").text().substring(1))); message.setText(doc.text()); } return message; }); static { mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); SimpleModule module = new SimpleModule(); module.addDeserializer(List.class, new MessageDeserializer()); mapper.registerModule(module); } private Parser(){ } public static List<Message> getMessagesFromChat() { if (CurrentState.getStatus() == CurrentState.State.ON) { ChatMessagesRequest request = buildChatMessagesRequest(); if (request != null) { String json = request.requestMessages(); if (json != null){ List<Message> messages = parseJson(json); if (!messages.isEmpty()){ updateCurrentState(findLastMessage(messages), request); return findSystemMessages(messages); } } } } return null; } private static List<Message> findSystemMessages(List<Message> messages) { return messages.stream() .filter( m -> m.getType().equals(SYSTEM_TYPE) && m.getPlayerId() == 131716) //убрать сообщения о банах и боях, только газетчик пишет нужное .map(reformatSystemMessage) .collect(Collectors.toList()); } private static void updateCurrentState(Message lastMessage, ChatMessagesRequest pastRequest) { CurrentState.setLastMessageId(pastRequest.getLastMessageId(), lastMessage.getId()); CurrentState.setLastMessageType(pastRequest.getType(), lastMessage.getType().equals(SYSTEM_TYPE) ? SYSTEM_TYPE : ""); } private static Message findLastMessage(List<Message> messages) { return messages.stream().max( (m1, m2) -> Integer.compare(m1.getId(), m2.getId()) ).get(); } private static List<Message> parseJson(String json) { try { return mapper.readValue(json, List.class); } catch (IOException e) { LOG.warn("Failed to parse messages json", e); } return Collections.EMPTY_LIST; } private static ChatMessagesRequest buildChatMessagesRequest() { String cookiesValue = CurrentState.getCookiesValue(); if (cookiesValue != null) { return new ChatMessagesRequest(CurrentState.getLastMessageId(), CurrentState.getLastMessageType(), cookiesValue); } else { return null; } } }
true
f687cd78e2af260c686be82dfc190c99cd319372
Java
Lefted/LunacyForge
/LunacyForge/src/main/java/us/hemdgang/autoreward/labyconnect/packets/PacketLoginStart.java
UTF-8
621
1.96875
2
[]
no_license
package us.hemdgang.autoreward.labyconnect.packets; import io.netty.buffer.ByteBuf; import us.hemdgang.autoreward.labyconnect.Packet; import us.hemdgang.autoreward.labyconnect.PacketBuf; import us.hemdgang.autoreward.labyconnect.PacketHandler; public class PacketLoginStart extends Packet{ public void read(final ByteBuf buf) { } public void write(final ByteBuf buf) { } @Override public void handle(final PacketHandler packetHandler) { } @Override public void read(final PacketBuf buf) { } @Override public void write(final PacketBuf buf) { } }
true
5dfa2376337cf57c78351696ee8c2e65f9cb0fd4
Java
Alex-st/HibernateAndLiquibase
/backend/src/main/java/com/core/domain/AbstractAdvert.java
UTF-8
1,424
2.21875
2
[]
no_license
package com.core.domain; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.util.Calendar; import java.util.Date; /** * Created by Oleksandr on 5/10/2016. */ @Getter @Setter @MappedSuperclass @NoArgsConstructor public abstract class AbstractAdvert { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DEFAULT_ADVERT_GEN") private Long id; @Column(name = "ADVERT_TEXT", nullable = false) private String text; @ManyToOne @JoinColumn(name = "AUTHOR_ID", nullable = false) private UserProfileEntity author; @Column(name = "IS_ADVERT_ACTIVE", nullable = false) private boolean isActive; @Column(name = "ADVERT_PUBLISH_DATE") @Temporal(TemporalType.DATE ) private Date publishDate; @PrePersist protected void onCreate() { publishDate = Calendar.getInstance().getTime(); } @PreUpdate protected void onUpdate() { publishDate = Calendar.getInstance().getTime(); } }
true
216d6272b568be329c7cda8a072021daac29506d
Java
jonghoxxshin/cell_society
/src/app/model/board/FireBoard.java
UTF-8
2,665
3.21875
3
[ "MIT" ]
permissive
package app.model.board; import app.model.cell.Cell; import app.model.rules.Rules; import java.util.Random; import java.util.ResourceBundle; /** * Board for Fire simulation * @author Kyle Harvey, Jaiveer Katariya, Jognho Shin */ public class FireBoard extends Board { private double growProbability; private double catchProbability; /** * Fire Board Constructor * <p> * Get catch and grow probabilities from properties file * </p> * * @param myProperties * @author Kyle Harvey, Jaiveer Katariya, Jognho Shin */ public FireBoard(ResourceBundle myProperties) { super(myProperties); growProbability = Double.parseDouble(myProperties.getString("grow_probability")); catchProbability = Double.parseDouble(myProperties.getString("probability")); } /** * Update Board * <p> * Following the rules from the rules parser update each cell on the board * to simulate the spread of fire. Grow probability is used to simulate tree * growth and catch probability to simulate fire spread if a neighboring cel * is on fire * </p> * @param rules * @return cells * @author Kyle Harvey, Jaiveer Katariya, Jognho Shin */ @Override public Cell[][] updateBoard(Rules rules) { Random generator = new Random(); double number; Cell[][] tempCells = new Cell[super.getMyHeight()][super.getMyWidth()]; for (int i = 0; i < super.getMyHeight(); i++) { for (int j = 0; j < super.getMyWidth(); j++) { Cell tempCell = super.getCells()[i][j]; number = generator.nextDouble(); int currState = tempCell.getMyState(); int nextState = tempCell.getNextState(rules, this); if (number < growProbability && currState == 0) { tempCells[i][j] = tempCell; } else if ( currState == 1) { if (tempCell.findNeighborsInState(2, tempCell.getNeighbors(),this).size() > 0 && number < catchProbability) { tempCells[i][j] = createNewCellFromSubClass(tempCell, nextState, j, i, super.getMyHeight(), super.getMyWidth(), super.getNeighborType(), -1, -1, super.getEdgeType()); } else { tempCells[i][j] = tempCell; } }else { tempCells[i][j] = createNewCellFromSubClass(tempCell, nextState, j, i, super.getMyHeight(), super.getMyWidth(), super.getNeighborType(), -1, -1, super.getEdgeType()); } } } super.setCells(tempCells); return tempCells; } }
true
8d31d2751e7cb7baf43f834ccba99cb82a8938de
Java
adamf0/bossku
/app/src/main/java/app/adam/bossku/interfaces/SimpleSearchActionsListener.java
UTF-8
228
1.640625
2
[]
no_license
package app.adam.bossku.interfaces; import app.adam.bossku.view.model.Search; public interface SimpleSearchActionsListener { void onItemClicked(Search item); void onScroll(); void error(String localizedMessage); }
true
62fb23f44a24356d23b217ecfa09667827607087
Java
StarinkFan/ControllSEIII
/src/main/java/com/software2/demo/service/LabelBLService.java
UTF-8
567
2.015625
2
[]
no_license
package com.software2.demo.service; import com.software2.demo.ResultMessage; import com.software2.demo.bean.Label; import com.software2.demo.bean.WorkTask; import java.util.List; public interface LabelBLService { public ResultMessage addLabel(Label label, int WorkTaskID); public List<Label> searchMyLabel(String userID); public ResultMessage deleteLabel(List<Integer> labelIDs,int TaskID); public ResultMessage modifyLabel(Label l); public Label getSingleLabel(int id); public List<Label> getAll(); public WorkTask getWTask(int id); }
true
815219ab03a1da6fc3395c434af6507788f1099f
Java
marianghel/tarea2
/tarea/src/Vista/FRM_Matricula.java
UTF-8
7,979
2.640625
3
[]
no_license
package Vista; import Controlador.Controlador_FRM_Matricula; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author Tata */ public class FRM_Matricula extends javax.swing.JFrame { DefaultTableModel modelo; Controlador_FRM_Matricula controlador; public FRM_Matricula(FRM_RegistroEstudiantes estudiantes, FRM_RegistroCursos cursos) { initComponents(); controlador= new Controlador_FRM_Matricula(estudiantes, cursos,this); modelo = new DefaultTableModel(); this.tbl_Matricula.setModel(modelo); colocarTitulosTabla(); colocarCodigo(); agregarEventos(); this.gUI_Botones1.estadoInicialBotones(); } public void habilitarAgregar(){ this.gUI_Botones1.habilitarNoExisteBotones(); } public void limpiarCurso(){ this.jt_Cedula.setText(""); this.jt_Sigla.setText(""); } public void estadoInicial(){ this.gUI_Botones1.estadoInicialBotones(); } public void colocarTitulosTabla(){ modelo.addColumn("Cédula"); modelo.addColumn("Nombre Estudiante"); modelo.addColumn("Sigla"); modelo.addColumn("Nombre Curso"); } public void colocarCodigo(){ this.jt_Codigo.setText(controlador.colocarCodigo()); } public void mostrarNombreEstudiante(String nombre){ this.jt_NombreE.setText(nombre); } public void mostrarNombreCurso(String nombre){ this.jt_NombreC.setText(nombre); } public int getCantidadDeCursosMatriculador(){ return modelo.getRowCount(); } public String[] getInformacionTabla(int contador){ String arreglo[]=new String [3]; arreglo[0]= this.jt_Codigo.getText(); arreglo[1]=""+this.modelo.getValueAt(contador,0);//(fila,columna) arreglo[2]=""+this.modelo.getValueAt(contador,2); return arreglo; } public void resetearInterfaz(){ colocarCodigo(); this.jt_Cedula.setText(""); this.jt_NombreE.setText(""); this.jt_Sigla.setText(""); this.jt_NombreC.setText(""); int numeroFijoDeFilaTabla=modelo.getRowCount(); for(int contador=0;contador<numeroFijoDeFilaTabla;contador++){ modelo.removeRow(contador); System.out.println("resetear interfaz"); } } public void agregarEventos(){ this.btn_Cedula.addActionListener(controlador); this.btn_Sigla.addActionListener(controlador); this.gUI_Botones1.agregarEventos(controlador); this.jb_Finalizar.addActionListener(controlador); } public void mostrarMensaje(String mensaje){ JOptionPane.showMessageDialog(null,mensaje); } public void cargarTabla(){ String arreglo[]=new String[4]; arreglo[0]=this.jt_Cedula.getText(); arreglo[1]=this.jt_NombreE.getText(); arreglo[2]=this.jt_Sigla.getText(); arreglo[3]=this.jt_NombreC.getText(); modelo.addRow(arreglo); } public String devolverCedula(){ return this.jt_Cedula.getText(); } public String devolverSigla(){ return this.jt_Sigla.getText(); } //modelo.addRow(), en un arreglo para cargar la tabla /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jl_Cedula = new javax.swing.JLabel(); jl_Nombre = new javax.swing.JLabel(); jl_Sigla = new javax.swing.JLabel(); jl_NombreC = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tbl_Matricula = new javax.swing.JTable(); jt_Cedula = new javax.swing.JTextField(); jt_NombreE = new javax.swing.JTextField(); jt_Sigla = new javax.swing.JTextField(); jt_NombreC = new javax.swing.JTextField(); btn_Cedula = new javax.swing.JButton(); btn_Sigla = new javax.swing.JButton(); jl_Codigo = new javax.swing.JLabel(); jt_Codigo = new javax.swing.JTextField(); jb_Finalizar = new javax.swing.JButton(); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jl_Cedula.setText("Cédula"); getContentPane().add(jl_Cedula, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 90, -1, -1)); jl_Nombre.setText("Nombre"); getContentPane().add(jl_Nombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 140, -1, -1)); jl_Sigla.setText("Sigla"); getContentPane().add(jl_Sigla, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 90, -1, -1)); jl_NombreC.setText("Nombre"); getContentPane().add(jl_NombreC, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 140, -1, -1)); tbl_Matricula.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(tbl_Matricula); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 190, 600, 108)); getContentPane().add(jt_Cedula, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 80, 130, 30)); jt_NombreE.setEnabled(false); getContentPane().add(jt_NombreE, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 130, 220, 30)); getContentPane().add(jt_Sigla, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 80, 110, 30)); jt_NombreC.setEnabled(false); getContentPane().add(jt_NombreC, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 130, 200, 30)); btn_Cedula.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Buscar.png"))); // NOI18N btn_Cedula.setActionCommand("Estudiantes"); getContentPane().add(btn_Cedula, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 70, -1, -1)); btn_Sigla.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Buscar.png"))); // NOI18N btn_Sigla.setActionCommand("Curso"); getContentPane().add(btn_Sigla, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 70, -1, -1)); jl_Codigo.setText("Código"); getContentPane().add(jl_Codigo, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, -1, -1)); getContentPane().add(jt_Codigo, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 30, 130, 30)); jb_Finalizar.setText("Finalizar Matricula"); getContentPane().add(jb_Finalizar, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 400, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_Cedula; private javax.swing.JButton btn_Sigla; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jb_Finalizar; private javax.swing.JLabel jl_Cedula; private javax.swing.JLabel jl_Codigo; private javax.swing.JLabel jl_Nombre; private javax.swing.JLabel jl_NombreC; private javax.swing.JLabel jl_Sigla; private javax.swing.JTextField jt_Cedula; private javax.swing.JTextField jt_Codigo; private javax.swing.JTextField jt_NombreC; private javax.swing.JTextField jt_NombreE; private javax.swing.JTextField jt_Sigla; private javax.swing.JTable tbl_Matricula; // End of variables declaration//GEN-END:variables }
true
50579fd47bcb271c731c6f9812d239dd51d1b4a4
Java
paulosoujava/faculdade
/src/br/com/senac/servlet/Exemplo05Servlet.java
WINDOWS-1252
876
2.671875
3
[]
no_license
package br.com.senac.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Exemplo3Servlet */ @WebServlet("/Servlet5") public class Exemplo05Servlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String num1 = request.getParameter("num1"); String num2 = request.getParameter("num2"); Integer num_1 = Integer.parseInt(num1); Integer num_2 = Integer.parseInt(num2); response.getWriter().println("A soma dos numeros "+ num1 +" + " + num2 +" : "+ (num_1 + num_2)); } }
true
bf8056284c28383d1ff4b30ee522b0eb9858e381
Java
Isurunath/Home-Management-System
/src/model/event/Eventnitems.java
UTF-8
1,115
2.078125
2
[]
no_license
package model.event; // Generated May 1, 2016 3:39:36 PM by Hibernate Tools 4.3.1 /** * Eventnitems generated by hbm2java */ public class Eventnitems implements java.io.Serializable { private Integer id; private String itemName; private int quantity; private int eventId; public Eventnitems() { } public Eventnitems(String itemName, int quantity, int eventId) { this.itemName = itemName; this.quantity = quantity; this.eventId = eventId; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getItemName() { return this.itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public int getQuantity() { return this.quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getEventId() { return this.eventId; } public void setEventId(int eventId) { this.eventId = eventId; } }
true
2234b258abfc872ce164c26a78f0c875c22cf28c
Java
NikolShakleva/MemoryLeak
/Week12/PicoBank.java
UTF-8
186
2.359375
2
[]
no_license
//////////////////// //PicoBank interface //////////////////// public interface PicoBank { void transfer(long amount, int source, int target); long balance(int accountNr); }
true
a249cf8efebc65f32dcd18c8720be231c7d326e8
Java
woodstock503/sas
/saccPlus/src/main/java/sas/saccplus/util/SessionBean.java
UTF-8
6,138
2
2
[]
no_license
package sas.saccplus.util; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.enterprise.context.Conversation; import javax.enterprise.context.SessionScoped; import javax.faces.event.ValueChangeEvent; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType; import sas.saccplus.model.Branch; import sas.saccplus.model.Company; import sas.saccplus.model.Department; import sas.saccplus.model.Users; import sas.saccplus.session.BranchFacade; import sas.saccplus.session.CompanyFacade; import sas.saccplus.view.LanguageBean; @Named @SessionScoped public class SessionBean implements Serializable{ /** * */ private static final long serialVersionUID = 8185878929115837596L; @PersistenceContext(type = PersistenceContextType.EXTENDED) private EntityManager entityManager; @Inject private Conversation conversation; @Inject private LanguageBean languageBean; @EJB private CompanyFacade companyFacade; @EJB private BranchFacade branchFacade; private List<Company> companyList = new ArrayList<Company>(); private List<Branch> branchList = new ArrayList<Branch>(); private List<Department> departmentList = new ArrayList<Department>(); private Users user; private PackageType packageType; private Company company = new Company(); private Branch branch = new Branch(); private String skinName; @PostConstruct public void init(){ skinName = "deepMarine"; } public String changeSkin(String skinName){ this.skinName = skinName; return "?faces-redirect=true"; } public boolean isLocal() { return !"en".equals(languageBean.getLocaleCode()); } public String selectedCompany(Company company){ try { this.company = company; genDepartmentListByCompany(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "index?faces-redirect=true"; } public String selectedBranch(Branch branch){ try { this.branch = branch; genDepartmentListByCompany(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "index?faces-redirect=true"; } public void changeCompany(ValueChangeEvent event){ try { if (!this.conversation.isTransient()) { this.conversation.end(); } Long companyId =(Long) event.getNewValue(); company = companyFacade.findById(companyId); genDepartmentListByCompany(); if(PackageType.ALL.equals(packageType)){ genBranchListByCompany(companyId); if(branchList!=null&&!branchList.isEmpty()){ branch = branchList.get(0); }else{ branch = new Branch(); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void changeBranch(ValueChangeEvent event){ try { if (!this.conversation.isTransient()) { this.conversation.end(); } branch = branchFacade.findById((Long) event.getNewValue()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String formatDate(Date date,String pattern){ SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.format(date); } public boolean showCompanyList(){ return PackageType.PROFESSIONAL.equals(packageType)||PackageType.ALL.equals(packageType); } public boolean showCompanyLabel(){ return PackageType.STANDARD.equals(packageType)||PackageType.PROFESSIONAL.equals(packageType)||PackageType.ALL.equals(packageType); } public boolean showBranch(){ return PackageType.ENTERPRISE.equals(packageType)||PackageType.ALL.equals(packageType); } @SuppressWarnings("unchecked") private void genDepartmentListByCompany() throws Exception{ try{ departmentList = entityManager.createQuery("From Department where company.id=:companyId").setParameter("companyId", company.getId()).getResultList(); Department dep = new Department(); dep.setId(-1L); dep.setDepartmentName("ทั้งหมด"); dep.setDepartmentNameEn("All"); departmentList.add(0,dep); }catch(Exception ex){ throw ex; } } private void genBranchListByCompany(Long companyId) throws Exception{ try{ branchList = branchFacade.findBranchByUser(user,companyId); }catch(Exception ex){ throw ex; } } public void paint(OutputStream stream, Object object) throws IOException { try{ if(getCompany().getLogo()!=null){ stream.write(getCompany().getLogo()); stream.close(); } }catch(Exception ex){ // ex.printStackTrace(); } } public Users getUser() { return user; } public void setUser(Users userProfile) { this.user = userProfile; } public String getSkinName() { return skinName; } public void setSkinName(String skinName) { this.skinName = skinName; } public List<Company> getCompanyList() { return companyList; } public void setCompanyList(List<Company> companyList) { this.companyList = companyList; } public List<Branch> getBranchList() { return branchList; } public void setBranchList(List<Branch> branchList) { this.branchList = branchList; } public PackageType getPackageType() { return packageType; } public void setPackageType(PackageType packageType) { this.packageType = packageType; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public Branch getBranch() { return branch; } public void setBranch(Branch branch) { this.branch = branch; } private String value; public void updateValue(String value){ this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
true
d8bd760fa3c95ff211c438d8ebd6e5a8412aa63d
Java
megha-raina90/CostBasket
/src/com/cts/execute/Executor.java
UTF-8
418
1.882813
2
[]
no_license
package com.cts.execute; import java.util.Map; import com.cts.bo.PriceCalculator; import com.cts.exception.NotValidFruitException; public class Executor { public static void main(String[] args) { PriceCalculator priceCalculator= new PriceCalculator(); try { priceCalculator.getUserInput(); } catch (NotValidFruitException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
df770177214baf0d5a3949ffb4287d556c8bfee8
Java
xxli917/demo
/app/src/main/java/com/lixiaoxue/demolxx/launchstarter/task/UnitTask.java
UTF-8
3,617
2.953125
3
[]
no_license
package com.lixiaoxue.demolxx.launchstarter.task; import me.jessyan.autosize.AutoSizeConfig; public class UnitTask extends Task { @Override public void run() { configUnits(); } /** * 注意!!! 布局时的实时预览在开发阶段是一个很重要的环节, 很多情况下 Android Studio 提供的默认预览设备并不能完全展示我们的设计图 * 所以我们就需要自己创建模拟设备, 以下链接是给大家的福利, 按照链接中的操作可以让预览效果和设计图完全一致! * * @see <a href="https://github.com/JessYanCoding/AndroidAutoSize/blob/master/README-zh.md#preview">dp、pt、in、mm 这四种单位的模拟设备创建方法</a> * <p> */ private void configUnits() { //AndroidAutoSize 默认开启对 dp 的支持, 调用 UnitsManager.setSupportDP(false); 可以关闭对 dp 的支持 //主单位 dp 和 副单位可以同时开启的原因是, 对于旧项目中已经使用了 dp 进行布局的页面的兼容 //让开发者的旧项目可以渐进式的从 dp 切换到副单位, 即新页面用副单位进行布局, 然后抽时间逐渐的将旧页面的布局单位从 dp 改为副单位 //最后将 dp 全部改为副单位后, 再使用 UnitsManager.setSupportDP(false); 将 dp 的支持关闭, 彻底隔离修改 density 所造成的不良影响 //如果项目完全使用副单位, 则可以直接以像素为单位填写 AndroidManifest 中需要填写的设计图尺寸, 不需再把像素转化为 dp //当使用者想将旧项目从主单位过渡到副单位, 或从副单位过渡到主单位时 //因为在使用主单位时, 建议在 AndroidManifest 中填写设计图的 dp 尺寸, 比如 360 * 640 //而副单位有一个特性是可以直接在 AndroidManifest 中填写设计图的 px 尺寸, 比如 1080 * 1920 //但在 AndroidManifest 中却只能填写一套设计图尺寸, 并且已经填写了主单位的设计图尺寸 //所以当项目中同时存在副单位和主单位, 并且副单位的设计图尺寸与主单位的设计图尺寸不同时, 可以通过 UnitsManager#setDesignSize() 方法配置 //如果副单位的设计图尺寸与主单位的设计图尺寸相同, 则不需要调用 UnitsManager#setDesignSize(), 框架会自动使用 AndroidManifest 中填写的设计图尺寸 // .setDesignSize(2160, 3840) //AndroidAutoSize 默认开启对 sp 的支持, 调用 UnitsManager.setSupportSP(false); 可以关闭对 sp 的支持 //如果关闭对 sp 的支持, 在布局时就应该使用副单位填写字体的尺寸 //如果开启 sp, 对其他三方库控件影响不大, 也可以不关闭对 sp 的支持, 这里我就继续开启 sp, 请自行斟酌自己的项目是否需要关闭对 sp 的支持 // .setSupportSP(false) //AndroidAutoSize 默认不支持副单位, 调用 UnitsManager#setSupportSubunits() 可选择一个自己心仪的副单位, 并开启对副单位的支持 //只能在 pt、in、mm 这三个冷门单位中选择一个作为副单位, 三个单位的适配效果其实都是一样的, 您觉的哪个单位看起顺眼就用哪个 //您选择什么单位就在 layout 文件中用什么单位进行布局, 我选择用 mm 为单位进行布局, 因为 mm 翻译为中文是妹妹的意思 AutoSizeConfig.getInstance().setCustomFragment(true); //禁止系统字体调整 AutoSizeConfig.getInstance().setExcludeFontScale(true); } }
true
1a97ec0c5154d0b7661185d3849f7fd3963a2b11
Java
SaoBing-Lee/GOF23
/src/java/example/bingbing/singleton/Client3.java
UTF-8
1,240
3.453125
3
[]
no_license
package example.bingbing.singleton; import java.util.concurrent.CountDownLatch; /** * @ClassName Client * @descripetion 测试多线程环境下单例模式的效率 * @Author liyanbing * @Date 2019-06-13 */ public class Client3 { public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); int threadNum = 10; //线程计数器 final CountDownLatch countDownLatch = new CountDownLatch(threadNum);//设置为final 这样内部类才能调用 for (int a = 0; a < threadNum; a++) { new Thread(new Runnable() {//匿名内部类 @Override public void run() { for (int i = 0; i < 10000000; i++) { // Object o = SingletonLazyLoad.getInstance(); Object o = SingletonEnum.INSTANTS; } countDownLatch.countDown();//计数器减 1 } }).start(); } countDownLatch.await();//main线程阻塞,直到计数器变为0,才会继续往下执行; long end = System.currentTimeMillis(); System.out.println("总耗时:======"+(end-start)); } }
true
f0300282d770099b0887afe7b963e09ad3c300b7
Java
DavidZhng/Swept
/app/src/main/java/com/dz/swept/WinnerAdapter.java
UTF-8
2,897
2.34375
2
[]
no_license
package com.dz.swept; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.FirebaseFirestore; import java.util.ArrayList; import java.util.Arrays; public class WinnerAdapter extends RecyclerView.Adapter<EntryViewHolder> { WinnerActivity winnerActivity; ArrayList<Entry> entryArrayList; SwipeRefreshLayout swipe; FirebaseAuth fAuth; FirebaseUser user; FirebaseFirestore fStore = FirebaseFirestore.getInstance(); View view; public ArrayList<String> alUsers; public ArrayList<Integer> alScore; public ArrayList<Integer> alScore1; public ArrayList<Integer> alScore2; public WinnerAdapter(WinnerActivity winnerActivity, ArrayList<Entry> entryArrayList) { this.winnerActivity= winnerActivity; this.entryArrayList = entryArrayList; } @NonNull @Override public EntryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { System.out.println("attempted"); Log.d("Entryadapter","first"); LayoutInflater layoutInflater = LayoutInflater.from(winnerActivity.getBaseContext()); view = layoutInflater.inflate(R.layout.activity_user_entry,parent,false); return new EntryViewHolder(view); } @Override public void onBindViewHolder(@NonNull final EntryViewHolder holder, final int position) { System.out.println("attempted"); if(entryArrayList.get(position).getStringformat().equals("formatSingleScore")){ String userEmail = entryArrayList.get(position).getStringUserEmail(); String userScore = entryArrayList.get(position).getStringSingleScore(); alUsers.add(userEmail); alScore.add(Integer.parseInt(userScore)); } if(entryArrayList.get(position).getStringformat().equals("formatScoreVsScore")){ String userEmail = entryArrayList.get(position).getStringUserEmail(); String userScore1 = entryArrayList.get(position).getStringScoreScore1(); String userScore2 = entryArrayList.get(position).getStringScoreScore2(); alUsers.add(userEmail); alScore1.add(Integer.parseInt(userScore1)); alScore2.add(Integer.parseInt(userScore2)); } } @Override public int getItemCount() { String[] arrayUser = alUsers.toArray(new String[alUsers.size()]); System.out.println("heres lies" + Arrays.toString(arrayUser)); Log.d("Entryadapter","third"); return entryArrayList.size(); } }
true
9ac17c28f482bcd5560197b5e5cb446864c94be2
Java
TakaGoto/cob_spec_routes
/src/test/java/company/PutPostTest.java
UTF-8
932
2.453125
2
[]
no_license
package company; import com.company.responders.PutPost; import org.junit.Test; import java.io.IOException; import java.util.Hashtable; import static junit.framework.Assert.assertEquals; public class PutPostTest { PutPost putPost; String htmlBody = "data = cosby\r\n"; Hashtable<String, Object> req = new Hashtable<String, Object>(); Hashtable<String, Object> resp = new Hashtable<String, Object>(); @Test public void testGetPutGetPost() throws IOException { Hashtable<String, String> body = new Hashtable<String, String>(); body.put("data", "cosby"); body.put("length", "5"); putPost = new PutPost(); req.put("Request-URI", "/form"); req.put("Method", "POST"); req.put("Body", body); resp = putPost.respond(req); String newBody = new String((byte[]) resp.get("message-body"), "UTF-8"); assertEquals(htmlBody, newBody); } }
true
9d74256e10173fc4eeda57421ac4e11e7b8dec42
Java
Stanley3/DTAServer
/src/main/java/com/dta/service/impl/NewsInfoServiceImpl.java
UTF-8
692
1.945313
2
[]
no_license
package com.dta.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dta.bean.NewsInfo; import com.dta.dao.INewsInfoDao; import com.dta.service.INewsInfoService; import com.dta.vo.NewsInfoVo; @Service public class NewsInfoServiceImpl extends BaseAllServiceImpl<NewsInfo, NewsInfoVo> implements INewsInfoService { @Resource private INewsInfoDao dao; // spring实例化NewsInfoServiceImple后回掉该方法 // @PostConstruct public void init() { // System.out.println("\n\n\n in initMethod dao is null ?" + (dao == // null)); // System.out.println("*******初始化newsInfoServiceImpl********"); super.setDao(dao); } }
true
ce08a591ba9f382cb11fb4c289af6054ecac05a1
Java
adrianazestroiu/PSSC-2018
/PROIECT TUTU MIHAELA & ZESTROIU ADRIANA/src/com/proiect/pssc/service/StudentServiceImpl.java
UTF-8
966
2.265625
2
[ "MIT" ]
permissive
package com.proiect.pssc.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.proiect.pssc.dao.StudentDAO; import com.proiect.pssc.entity.Student; @Service public class StudentServiceImpl implements StudentService { // need to inject the StudentDAO @Autowired private StudentDAO studentDAO; @Override @Transactional public List<Student> getStudents() { return studentDAO.getStudents(); } @Override @Transactional public void saveStudent(Student theStudent) { studentDAO.saveStudent(theStudent); } @Override @Transactional public Student getStudent(int theId) { return studentDAO.getStudent(theId); } @Override @Transactional public void deleteStudent(int theId) { studentDAO.deleteStudent(theId); } }
true
ae61ea980722c5ef58e1818f38fdae62c3ae6bd5
Java
JetBrains/intellij-scala-historical
/src/org/jetbrains/plugins/scala/lang/psi/stubs/elements/wrappers/IStubFileElementWrapper.java
UTF-8
1,024
2.046875
2
[ "Apache-2.0" ]
permissive
package org.jetbrains.plugins.scala.lang.psi.stubs.elements.wrappers; import com.intellij.lang.Language; import com.intellij.psi.PsiFile; import com.intellij.psi.stubs.PsiFileStub; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.tree.IStubFileElementType; import org.jetbrains.annotations.NonNls; import java.io.IOException; /** * @author ilyas */ public abstract class IStubFileElementWrapper<S extends PsiFile, T extends PsiFileStub<S>> extends IStubFileElementType<T>{ public IStubFileElementWrapper(@NonNls String debugName, Language language) { super(debugName, language); } //Dirty delegate hack to avoid problems with inheritance in Scala which doesn't allow rawtyped parameters @Override public T deserialize(StubInputStream dataStream, StubElement parentStub) throws IOException { return deserializeImpl(dataStream, parentStub); } protected abstract T deserializeImpl(StubInputStream dataStream, Object parentStub); }
true
a59462023b0973fab6ec71925829ceb92946efe0
Java
inql/CoinTrends-App
/src/main/java/inql/cointrends/services/TimeRangeService.java
UTF-8
186
1.679688
2
[]
no_license
package inql.cointrends.services; import java.util.List; public interface TimeRangeService { List<Object[]> changeTimeRange(List<Object[]> currencyData, Long start, Long end); }
true
c61258a7af4499b60d90460d75ba0537b4082293
Java
kemar1997/CST_141
/JavaChapter13/BlueJ/shapes/Shape.java
UTF-8
1,648
3.734375
4
[]
no_license
/** * The Shape abstract class definition. * All classes that extend from Shape must implement abstract method draw(). * * @author Prof. Carl B. Struck * @version Copyright (c) 2008 -- SCCC West */ public abstract class Shape extends Object { // The point where the shape draws. private int point; /** * Constructor sets point where the shape draws. * * @param point the point where the shape draws */ public Shape(int point) { setPoint(point); } /** * Sets the point where the shape draws. * * @param point the point where the shape draws */ public void setPoint(int point) { this.point = point; } /** * Returns the point where the shape draws. * * @return The point where the shape draws */ public int getPoint() { return point; } /** * Prints the statistics of a shape to the terminal window. Calls * this class's method position() to print the position of the shape. * Calls a subclass method draw() to print the dimensions of a shape * subclass object to the terminal window (demonstrates 'late binding'). */ public void printIt() { position(); draw(); System.out.println(""); } /** * Prints the position of the shape to the terminal window. */ public void position() { System.out.println( "Position at " + getPoint() ); } /** * Abstract method definition to print dimension(s) of a shape subclass * object to the terminal window. */ public abstract void draw(); }
true
e665e42341e9ac3b9f61df3bbc5bba459cf05a41
Java
cleventy/springboilerplate
/src/test/java/com/cleventy/springboilerplate/unit/ApiPublicRestTest.java
UTF-8
2,319
2.140625
2
[]
no_license
package com.cleventy.springboilerplate.unit; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; import java.net.URL; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.cleventy.springboilerplate.business.services.cos.TestCO; import com.cleventy.springboilerplate.business.services.exceptions.InstanceNotFoundException; import com.cleventy.springboilerplate.web.controller.api.ApiPublicController; import com.cleventy.springboilerplate.web.controller.api.ApiURL; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; @RunWith(SpringRunner.class) @AutoConfigureMockMvc @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") public class ApiPublicRestTest { @MockBean private ApiPublicController apiPublicController; @LocalServerPort private int port; private URL base; @Autowired private TestRestTemplate template; @Before public void setUp() throws Exception { this.base = new URL("http://localhost:" + this.port); } @Before public void init() throws InstanceNotFoundException { TestCO testCO = new TestCO("test"); when(this.apiPublicController.test()).thenReturn(ResponseEntity.ok().body(testCO)); } @Test public void getTest() throws JsonMappingException, JsonProcessingException { ResponseEntity<TestCO> response = this.template.getForEntity(this.base.toString()+ApiURL.BASE+ApiURL.TEST, TestCO.class); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); assertThat(response.getBody(), equalTo(new TestCO("test"))); } }
true
3c52176b4e4a47c13a0c4f084e5cfe01986e4929
Java
LarissaRodrigues/das-sisghe
/.svn/pristine/3c/3c52176b4e4a47c13a0c4f084e5cfe01986e4929.svn-base
UTF-8
3,054
2.921875
3
[]
no_license
package Control; import Exception.MateriaInvalidaException; import Model.Disciplina; import Model.Grade; import Model.Horario; import Model.Matricula; import Model.Turma; import java.io.IOException; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Beatriz */ public class ControleGradeTest { public ControleGradeTest() { } Turma turma1, turma2; Disciplina dis, dis2; @Before public void setUp() throws IOException, MateriaInvalidaException, Exception { System.out.println("<Executa Before>"); ArrayList<Horario> horarios = new ArrayList<Horario>(); ArrayList<Horario> horarios2 = new ArrayList<Horario>(); Horario h1 = new Horario("Segunda", "14h"); Horario h2 = new Horario("Quarta", "14h"); Horario h3 = new Horario("Terça", "08h"); Horario h4 = new Horario("Quinta", "08h"); Horario h5 = new Horario("Quinta", "18h"); horarios.add(h1); horarios.add(h2); horarios2.add(h3); horarios2.add(h4); horarios2.add(h5); turma1 = new Turma("A", horarios); turma2 = new Turma("B", horarios2); dis = new Disciplina("Calculo 2", "123", "234"); dis2 = new Disciplina("Sistema Digitais 1", "321", "432"); Control.ControleGrade.adicionar(dis, turma1); Control.ControleGrade.adicionar(dis2, turma2); Control.ControleGrade.cadastrarGrade(); } /** * Test of getInstance method, of class ControleGrade. */ @Test public void testGetInstance() { System.out.println("getInstance"); System.out.println("aaaa"); ControleGrade res = ControleGrade.getInstance(); assertNotNull(res); } /** * Test of cadastrarGrade method, of class ControleGrade. */ @Test public void testCadastrarGrade() { System.out.println("cadastrarGrade"); try { ControleGrade.cadastrarGrade(); } catch (IOException e) { fail("Erro, grade não cadastrada"); } } /** * Test of obterGrade method, of class ControleGrade. */ @Test public void testObterGrade() throws Exception { System.out.println("obterGrade"); assertNotNull(ControleGrade.getInstance().obterGrade()); } /** * Test of excluirGrade method, of class ControleGrade. */ @Test public void testExcluirGrade() throws Exception { System.out.println("exluirGrade"); assertTrue(ControleGrade.getInstance().excluirGrade()); } /** * Test of adicionar method, of class ControleGrade. */ @Test public void testAdicionar() throws MateriaInvalidaException, Exception { System.out.println("adicionar"); assertNotNull(ControleGrade.getInstance().adicionar(dis, turma1)); } }
true
202cc83c9d680a62aebc52fc47ac2685ca5cc7fa
Java
DroiTaste/ResponseTester
/app/src/main/java/rest/LikesItem.java
UTF-8
2,206
2.21875
2
[]
no_license
package rest; /** * Created by morion on 2017-01-13. */ public class LikesItem { private String category; private String following_user_uid; private String following_user_nickName; private String following_user_profile_img_thumb; private String created_at; private LikesContets[] contents; // private String bottom_flag; // private String sort; // private String contents_error; public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getFollowing_user_uid() { return following_user_uid; } public void setFollowing_user_uid(String following_user_uid) { this.following_user_uid = following_user_uid; } public String getFollowing_user_nickName() { return following_user_nickName; } public void setFollowing_user_nickName(String following_user_nickName) { this.following_user_nickName = following_user_nickName; } public String getFollowing_user_profile_img_thumb() { return following_user_profile_img_thumb; } public void setFollowing_user_profile_img_thumb(String following_user_profile_img_thumb) { this.following_user_profile_img_thumb = following_user_profile_img_thumb; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } public LikesContets[] getContents() { return contents; } public void setContents(LikesContets[] contents) { this.contents = contents; } // public String getBottom_flag() { // return bottom_flag; // } // // public void setBottom_flag(String bottom_flag) { // this.bottom_flag = bottom_flag; // } // // public String getContents_error() { // return contents_error; // } // // public void setContents_error(String contents_error) { // this.contents_error = contents_error; // } // // public String getSort() { // return sort; // } // // public void setSort(String sort) { // this.sort = sort; // } }
true
0265d135d3fe7507b1ec803eb544053217230169
Java
David-Hackro/TestAndroid
/app/src/main/java/com/hackro/tutorials/gravility/Entities/DTO/Category.java
UTF-8
917
2.3125
2
[]
no_license
package com.hackro.tutorials.gravility.Entities.DTO; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by alice on 4/2/16. */ public class Category { @SerializedName("attributes") @Expose private Attributes______ attributes; /** * No args constructor for use in serialization * */ public Category() { } /** * * @param attributes */ public Category(Attributes______ attributes) { this.attributes = attributes; } /** * * @return * The attributes */ public Attributes______ getAttributes() { return attributes; } /** * * @param attributes * The attributes */ public void setAttributes(Attributes______ attributes) { this.attributes = attributes; } public Category withAttributes(Attributes______ attributes) { this.attributes = attributes; return this; } }
true
f7d22a06b6104332ed9224fe954e0ee63409f731
Java
aaronanderson/fabric3-core
/kernel/impl/fabric3-fabric/src/test/java/org/fabric3/fabric/deployment/generator/channel/ProducerCommandGeneratorTestCase.java
UTF-8
11,989
1.695313
2
[]
no_license
/* * Fabric3 * Copyright (c) 2009-2013 Metaform Systems * * Fabric3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version, with the * following exception: * * Linking this software statically or dynamically with other * modules is making a combined work based on this software. * Thus, the terms and conditions of the GNU General Public * License cover the whole combination. * * As a special exception, the copyright holders of this software * give you permission to link this software with independent * modules to produce an executable, regardless of the license * terms of these independent modules, and to copy and distribute * the resulting executable under terms of your choice, provided * that you also meet, for each linked independent module, the * terms and conditions of the license of that module. An * independent module is a module which is not derived from or * based on this software. If you modify this software, you may * extend this exception to your version of the software, but * you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. * * Fabric3 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the * GNU General Public License along with Fabric3. * If not, see <http://www.gnu.org/licenses/>. */ package org.fabric3.fabric.deployment.generator.channel; import javax.xml.namespace.QName; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.easymock.EasyMock; import org.fabric3.fabric.deployment.command.BuildChannelCommand; import org.fabric3.fabric.deployment.command.ChannelConnectionCommand; import org.fabric3.fabric.deployment.command.DisposeChannelCommand; import org.fabric3.api.model.type.component.ComponentDefinition; import org.fabric3.api.model.type.component.ProducerDefinition; import org.fabric3.spi.deployment.generator.channel.ChannelDirection; import org.fabric3.spi.deployment.generator.channel.ConnectionGenerator; import org.fabric3.spi.model.instance.LogicalChannel; import org.fabric3.spi.model.instance.LogicalComponent; import org.fabric3.spi.model.instance.LogicalCompositeComponent; import org.fabric3.spi.model.instance.LogicalProducer; import org.fabric3.spi.model.instance.LogicalState; import org.fabric3.spi.model.physical.PhysicalChannelConnectionDefinition; import org.fabric3.spi.model.physical.PhysicalChannelDefinition; /** * */ public class ProducerCommandGeneratorTestCase extends TestCase { private static final QName DEPLOYABLE = new QName("test", "test"); private BuildChannelCommand buildChannelCommand; private DisposeChannelCommand disposeChannelCommand; public void testChannelNotFound() throws Exception { ConnectionGenerator connectionGenerator = EasyMock.createMock(ConnectionGenerator.class); ChannelCommandGenerator channelGenerator = EasyMock.createMock(ChannelCommandGenerator.class); EasyMock.replay(connectionGenerator, channelGenerator); ProducerCommandGenerator generator = new ProducerCommandGenerator(connectionGenerator, channelGenerator); LogicalCompositeComponent parent = new LogicalCompositeComponent(URI.create("domain"), null, null); URI channelUri = URI.create("ChannelNotFound"); ComponentDefinition definition = new ComponentDefinition("component"); LogicalComponent<?> component = new LogicalComponent(URI.create("component"), definition, parent); component.setDeployable(DEPLOYABLE); LogicalProducer producer = new LogicalProducer(URI.create("component#producer"), new ProducerDefinition("consumer"), component); producer.addTarget(channelUri); component.addProducer(producer); try { ChannelConnectionCommand command = generator.generate(component, true); fail(); } catch (ChannelNotFoundException e) { // expected } EasyMock.verify(connectionGenerator, channelGenerator); } public void testGenerateIncrementalAttach() throws Exception { ConnectionGenerator connectionGenerator = EasyMock.createMock(ConnectionGenerator.class); List<PhysicalChannelConnectionDefinition> list = Collections.singletonList(new PhysicalChannelConnectionDefinition(null, null, null)); EasyMock.expect(connectionGenerator.generateProducer(EasyMock.isA(LogicalProducer.class), EasyMock.isA(Map.class))).andReturn(list); ChannelCommandGenerator channelGenerator = EasyMock.createMock(ChannelCommandGenerator.class); EasyMock.expect(channelGenerator.generateBuild(EasyMock.isA(LogicalChannel.class), EasyMock.isA(QName.class), EasyMock.isA(ChannelDirection.class))).andReturn(buildChannelCommand); EasyMock.replay(connectionGenerator, channelGenerator); ProducerCommandGenerator generator = new ProducerCommandGenerator(connectionGenerator, channelGenerator); LogicalComponent<?> component = createComponent(); ChannelConnectionCommand command = generator.generate(component, true); assertNotNull(command); assertFalse(command.getAttachCommands().isEmpty()); assertTrue(command.getDetachCommands().isEmpty()); EasyMock.verify(connectionGenerator, channelGenerator); } public void testGenerateIncrementalDetach() throws Exception { ConnectionGenerator connectionGenerator = EasyMock.createMock(ConnectionGenerator.class); List<PhysicalChannelConnectionDefinition> list = Collections.singletonList(new PhysicalChannelConnectionDefinition(null, null, null)); EasyMock.expect(connectionGenerator.generateProducer(EasyMock.isA(LogicalProducer.class), EasyMock.isA(Map.class))).andReturn(list); ChannelCommandGenerator channelGenerator = EasyMock.createMock(ChannelCommandGenerator.class); EasyMock.expect(channelGenerator.generateDispose(EasyMock.isA(LogicalChannel.class), EasyMock.isA(QName.class), EasyMock.isA(ChannelDirection.class))).andReturn(disposeChannelCommand); EasyMock.replay(connectionGenerator, channelGenerator); ProducerCommandGenerator generator = new ProducerCommandGenerator(connectionGenerator, channelGenerator); LogicalComponent<?> component = createComponent(); component.setState(LogicalState.MARKED); ChannelConnectionCommand command = generator.generate(component, true); assertNotNull(command); assertFalse(command.getDetachCommands().isEmpty()); assertTrue(command.getAttachCommands().isEmpty()); EasyMock.verify(connectionGenerator, channelGenerator); } public void testGenerateFullAttach() throws Exception { ConnectionGenerator connectionGenerator = EasyMock.createMock(ConnectionGenerator.class); List<PhysicalChannelConnectionDefinition> list = Collections.singletonList(new PhysicalChannelConnectionDefinition(null, null, null)); EasyMock.expect(connectionGenerator.generateProducer(EasyMock.isA(LogicalProducer.class), EasyMock.isA(Map.class))).andReturn(list); ChannelCommandGenerator channelGenerator = EasyMock.createMock(ChannelCommandGenerator.class); EasyMock.expect(channelGenerator.generateBuild(EasyMock.isA(LogicalChannel.class), EasyMock.isA(QName.class), EasyMock.isA(ChannelDirection.class))).andReturn(buildChannelCommand); EasyMock.replay(connectionGenerator, channelGenerator); ProducerCommandGenerator generator = new ProducerCommandGenerator(connectionGenerator, channelGenerator); LogicalComponent<?> component = createComponent(); component.setState(LogicalState.PROVISIONED); ChannelConnectionCommand command = generator.generate(component, false); assertNotNull(command); assertFalse(command.getAttachCommands().isEmpty()); assertTrue(command.getDetachCommands().isEmpty()); EasyMock.verify(connectionGenerator, channelGenerator); } public void testGenerateFullDetach() throws Exception { ConnectionGenerator connectionGenerator = EasyMock.createMock(ConnectionGenerator.class); List<PhysicalChannelConnectionDefinition> list = Collections.singletonList(new PhysicalChannelConnectionDefinition(null, null, null)); EasyMock.expect(connectionGenerator.generateProducer(EasyMock.isA(LogicalProducer.class), EasyMock.isA(Map.class))).andReturn(list); ChannelCommandGenerator channelGenerator = EasyMock.createMock(ChannelCommandGenerator.class); EasyMock.expect(channelGenerator.generateDispose(EasyMock.isA(LogicalChannel.class), EasyMock.isA(QName.class), EasyMock.isA(ChannelDirection.class))).andReturn(disposeChannelCommand); EasyMock.replay(connectionGenerator, channelGenerator); ProducerCommandGenerator generator = new ProducerCommandGenerator(connectionGenerator, channelGenerator); LogicalComponent<?> component = createComponent(); component.setState(LogicalState.MARKED); ChannelConnectionCommand command = generator.generate(component, false); assertNotNull(command); assertTrue(command.getAttachCommands().isEmpty()); assertFalse(command.getDetachCommands().isEmpty()); EasyMock.verify(connectionGenerator, channelGenerator); } public void testGenerateNothingIncremental() throws Exception { ConnectionGenerator connectionGenerator = EasyMock.createMock(ConnectionGenerator.class); ChannelCommandGenerator channelGenerator = EasyMock.createMock(ChannelCommandGenerator.class); EasyMock.replay(connectionGenerator, channelGenerator); ProducerCommandGenerator generator = new ProducerCommandGenerator(connectionGenerator, channelGenerator); LogicalComponent<?> component = createComponent(); component.setState(LogicalState.PROVISIONED); assertNull(generator.generate(component, true)); EasyMock.verify(connectionGenerator, channelGenerator); } @SuppressWarnings({"unchecked"}) private LogicalComponent<?> createComponent() { LogicalCompositeComponent parent = new LogicalCompositeComponent(URI.create("domain"), null, null); URI channelUri = URI.create("channel"); LogicalChannel channel = new LogicalChannel(channelUri, null, parent); parent.addChannel(channel); ComponentDefinition definition = new ComponentDefinition("component"); LogicalComponent<?> component = new LogicalComponent(URI.create("component"), definition, parent); component.setDeployable(DEPLOYABLE); LogicalProducer producer = new LogicalProducer(URI.create("component#producer"), new ProducerDefinition("consumer"), component); producer.addTarget(channelUri); component.addProducer(producer); return component; } protected void setUp() throws Exception { PhysicalChannelDefinition definition = new PhysicalChannelDefinition(URI.create("test"), new QName("foo", "bar"), false); buildChannelCommand = new BuildChannelCommand(definition); disposeChannelCommand = new DisposeChannelCommand(definition); } }
true
c974c1126308c5a2b62b8cee0889392c370b246a
Java
317432023/la
/la-api/src/main/java/com/jeetx/controller/api/test/TeamApiTest.java
UTF-8
14,460
2.0625
2
[]
no_license
package com.jeetx.controller.api.test; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.jeetx.controller.api.ApiUtil; import com.jeetx.util.MD5Util; import com.jeetx.util.RandomUtil; import net.sf.json.JSONObject; public class TeamApiTest { private static final String VERSION = "1.0"; // private static final String USERNAME = "代理abc"; // private static final String PASSWORD = "123456"; private static final String USERNAME = "推广abc"; private static final String PASSWORD = "123456"; // private static final String USERNAME = "玩家1"; // private static final String PASSWORD = "123456"; // private static final String STATION_ID = ""; // private static final Integer DEVICE = 3; // private static final String REFERER = "http://www.411027.com/"; private static final String STATION_ID = "1"; private static final Integer DEVICE = 1; private static final String REFERER = "http://www.zz.com/"; private static final String BASE_URL = "http://127.0.0.1:8080/la-api"; public static void main(String[] args) { // promoterList(); // virtualUserList(); // playerList(); // transRecordList(); // lotteryOrderList(); // profitList(); // addSalesman(); addVirtualUser(); // disableUser(); // virtualUserRecharge(); // teamTotal(); // profitTotal(); } /**获取服务器时间*/ public static String serverTime(){ String response = null; try { Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); response = new String(client.postMethod(BASE_URL+"/api/common/serverTime", parms,REFERER,"UTF-8")); //System.out.println(response); } catch (Exception e) { e.printStackTrace(); } return response; } public static String[] getToken(){ String[] responseStr = new String[2]; String token = ""; String secretKey = ApiUtil.SECRETKEY; try { String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("password", MD5Util.MD5Encode(MD5Util.MD5Encode(PASSWORD, "utf-8").toLowerCase(),"utf-8").toLowerCase() ); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,DEVICE==3?ApiUtil.H5_SECRETKEY:ApiUtil.SECRETKEY)); String response = new String(client.postMethod(BASE_URL+"/api/common/login", parms,REFERER,"UTF-8")); //System.out.println(response); if(StringUtils.isNotBlank(response)) { token = JSONObject.fromObject(response).getJSONObject("result").getJSONObject("userInfo").getString("token"); responseStr[0] = token; if(DEVICE == 3 && JSONObject.fromObject(response).getJSONObject("result").get("secretKey")!=null) { secretKey = JSONObject.fromObject(response).getJSONObject("result").getString("secretKey"); } responseStr[1] = secretKey; } } catch (Exception e) { e.printStackTrace(); } return responseStr; } /**下级推广员列表*/ public static void promoterList(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("page", "1"); parms.put("limit", "10"); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/promoterList", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**下级虚拟号列表*/ public static void virtualUserList(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("page", "1"); parms.put("limit", "10"); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/virtualUserList", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**下级玩家列表*/ public static void playerList(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("page", "1"); parms.put("limit", "10"); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/playerList", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**团队账变列表*/ public static void transRecordList(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("status", "-1"); //parms.put("date_begin", "2018-01-01"); //parms.put("date_end", "2019-01-01"); parms.put("page", "1"); parms.put("limit", "10"); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/transRecordList", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**团队投注列表*/ public static void lotteryOrderList(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("status", "-1"); parms.put("lotteryType", "1"); parms.put("date_begin", ""); parms.put("date_end", ""); parms.put("page", "1"); parms.put("limit", "10"); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/lotteryOrderList", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**团队盈亏列表*/ public static void profitList(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("date_begin", "2019-05-01"); parms.put("date_end", "2019-06-18"); parms.put("page", "1"); parms.put("limit", "10"); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/profitList", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**新增推广号*/ public static void addSalesman(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("add_username", "推广3"); parms.put("add_password", MD5Util.MD5Encode(MD5Util.MD5Encode("123456", "utf-8").toLowerCase(),"utf-8").toLowerCase() ); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/addSalesman", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**新增虚拟号*/ public static void addVirtualUser(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("is_init_order", "1"); parms.put("card_json", "{bankName:\"中国建设银行\",cardholder:\"张三\",cardNo:\"12345678912344\",bankPlace:\"河北石家庄\",bankBranch:\"保定支行\"}"); parms.put("token",tokenArray[0]); parms.put("add_username", "虚拟abc"+RandomUtil.getRangeRandom(1, 1000)); parms.put("add_password", MD5Util.MD5Encode(MD5Util.MD5Encode("123456", "utf-8").toLowerCase(),"utf-8").toLowerCase() ); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/addVirtualUser", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**注销子账号*/ public static void disableUser(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("child_username", "虚拟21"); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/disableUser", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**虚拟号充值*/ public static void virtualUserRecharge(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("type", "1"); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("amount", "1000"); parms.put("child_username", "虚拟a"); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/virtualUserRecharge", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**团队信息统计*/ public static void teamTotal(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("date_begin", "2019-05-01"); parms.put("date_end", "2019-06-18"); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/teamTotal", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /**团队统计列表*/ public static void profitTotal(){ try { String[] tokenArray = getToken(); String timestamp = JSONObject.fromObject(serverTime()).getJSONObject("result").getString("serverTime"); Map<String,Object> parms = new HashMap<String,Object>(); ApiUtil client = new ApiUtil(); parms.put("station_id", STATION_ID); parms.put("device", DEVICE); parms.put("username", USERNAME); parms.put("token",tokenArray[0]); parms.put("date_begin", "2019-05-01"); parms.put("date_end", "2019-06-18"); parms.put("pid", "260"); parms.put("page", "1"); parms.put("limit", "10"); parms.put("timestamp", timestamp); parms.put("version", VERSION); parms.put("sign", ApiUtil.generateSign(parms,tokenArray[1])); String response = new String(client.postMethod(BASE_URL+"/api/team/profitTotal", parms,REFERER,"UTF-8")); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } }
true
62635ce77aa21fef304f8504010ad7a5682fdb90
Java
reverseengineeringer/com.grubhub.android
/src/com/amazon/insights/AmazonInsights.java
UTF-8
13,634
1.976563
2
[]
no_license
package com.amazon.insights; import android.content.Context; import com.amazon.insights.core.DefaultInsightsContext; import com.amazon.insights.core.InsightsContext; import com.amazon.insights.core.log.Logger; import com.amazon.insights.core.util.Preconditions; import com.amazon.insights.core.util.SDKInfo; import com.amazon.insights.impl.DefaultInsightsCredentials; import com.amazon.insights.impl.DefaultInsightsOptions; import com.amazon.insights.impl.DisabledAmazonInsights; import com.amazon.insights.validate.EncodingValidator; import com.amazon.insights.validate.EncryptionValidator; import com.amazon.insights.validate.FileManagerValidator; import com.amazon.insights.validate.PermissionValidator; import com.amazon.insights.validate.SHA256Validator; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public abstract class AmazonInsights { private static final DisabledAmazonInsights DISABLED_AMAZON_INSIGHTS = new DisabledAmazonInsights(); private static final String SDK_NAME = "AmazonInsightsSDK"; private static final String SDK_VERSION = "2.1.26.0"; private static final PermissionValidator accessNetworkStatePermissionValidator; private static final EncryptionValidator aesEncryptionValidator; private static final EncodingValidator encodingValidator; private static final FileManagerValidator fileManagerValidator; private static final Map<InsightsCredentials, AmazonInsights> instances; private static final PermissionValidator internetPermissionValidator; private static final Logger logger; private static final SDKInfo sdkInfo = new SDKInfo("AmazonInsightsSDK", "2.1.26.0"); private static final SHA256Validator sha256Validator; static { logger = Logger.getLogger(AmazonInsights.class); instances = new ConcurrentHashMap(); internetPermissionValidator = new PermissionValidator("android.permission.INTERNET"); accessNetworkStatePermissionValidator = new PermissionValidator("android.permission.ACCESS_NETWORK_STATE"); encodingValidator = new EncodingValidator("UTF-8"); sha256Validator = new SHA256Validator(); aesEncryptionValidator = new EncryptionValidator("ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEF", "AES"); fileManagerValidator = new FileManagerValidator(); } public static AmazonInsights getInstance(InsightsCredentials paramInsightsCredentials) throws IllegalArgumentException { try { if (instances.containsKey(paramInsightsCredentials)) { paramInsightsCredentials = (AmazonInsights)instances.get(paramInsightsCredentials); return paramInsightsCredentials; } throw new IllegalArgumentException("There was not an AmazonInsights instance registered for the credentials provided. Make sure you call newInstance before trying to retrieve the instance via getInstance"); } finally {} } static SDKInfo getSDKInfo() { return sdkInfo; } public static InsightsCredentials newCredentials(String paramString1, String paramString2) { Preconditions.checkNotNull(paramString1, "The application key provided must not be null"); Preconditions.checkNotNull(paramString2, "The private key provided must not be null"); return new DefaultInsightsCredentials(paramString1, paramString2); } public static InsightsOptions newDefaultOptions() { return new DefaultInsightsOptions(true, false); } static InsightsContext newInsightsContext(InsightsCredentials paramInsightsCredentials, Context paramContext) { return newInsightsContext(paramInsightsCredentials, paramContext, new HashMap()); } static InsightsContext newInsightsContext(InsightsCredentials paramInsightsCredentials, Context paramContext, Map<String, String> paramMap) { return DefaultInsightsContext.newInstance(paramInsightsCredentials, paramContext, sdkInfo, true, paramMap); } public static AmazonInsights newInstance(InsightsCredentials paramInsightsCredentials, Context paramContext) throws NullPointerException { try { paramInsightsCredentials = newInstance(paramInsightsCredentials, paramContext, newDefaultOptions(), null); return paramInsightsCredentials; } finally { paramInsightsCredentials = finally; throw paramInsightsCredentials; } } public static AmazonInsights newInstance(InsightsCredentials paramInsightsCredentials, Context paramContext, InsightsCallback<AmazonInsights> paramInsightsCallback) throws NullPointerException { try { paramInsightsCredentials = newInstance(paramInsightsCredentials, paramContext, newDefaultOptions(), paramInsightsCallback); return paramInsightsCredentials; } finally { paramInsightsCredentials = finally; throw paramInsightsCredentials; } } public static AmazonInsights newInstance(InsightsCredentials paramInsightsCredentials, Context paramContext, InsightsOptions paramInsightsOptions) throws NullPointerException { try { paramInsightsCredentials = newInstance(paramInsightsCredentials, paramContext, paramInsightsOptions, new HashMap(), null); return paramInsightsCredentials; } finally { paramInsightsCredentials = finally; throw paramInsightsCredentials; } } public static AmazonInsights newInstance(InsightsCredentials paramInsightsCredentials, Context paramContext, InsightsOptions paramInsightsOptions, InsightsCallback<AmazonInsights> paramInsightsCallback) throws NullPointerException { try { paramInsightsCredentials = newInstance(paramInsightsCredentials, paramContext, paramInsightsOptions, new HashMap(), paramInsightsCallback); return paramInsightsCredentials; } finally { paramInsightsCredentials = finally; throw paramInsightsCredentials; } } /* Error */ static AmazonInsights newInstance(InsightsCredentials paramInsightsCredentials, Context paramContext, InsightsOptions paramInsightsOptions, Map<String, String> paramMap, InsightsCallback<AmazonInsights> paramInsightsCallback) throws NullPointerException { // Byte code: // 0: ldc 2 // 2: monitorenter // 3: aload_0 // 4: ldc -68 // 6: invokestatic 141 com/amazon/insights/core/util/Preconditions:checkNotNull (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; // 9: pop // 10: aload_1 // 11: ldc -66 // 13: invokestatic 141 com/amazon/insights/core/util/Preconditions:checkNotNull (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; // 16: pop // 17: aload_2 // 18: ldc -64 // 20: invokestatic 141 com/amazon/insights/core/util/Preconditions:checkNotNull (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; // 23: pop // 24: getstatic 55 com/amazon/insights/AmazonInsights:instances Ljava/util/Map; // 27: aload_0 // 28: invokeinterface 121 2 0 // 33: ifeq +21 -> 54 // 36: getstatic 55 com/amazon/insights/AmazonInsights:instances Ljava/util/Map; // 39: aload_0 // 40: invokeinterface 125 2 0 // 45: checkcast 2 com/amazon/insights/AmazonInsights // 48: astore_0 // 49: ldc 2 // 51: monitorexit // 52: aload_0 // 53: areturn // 54: invokestatic 195 com/amazon/insights/core/log/Logger:tryInitialize ()V // 57: getstatic 64 com/amazon/insights/AmazonInsights:internetPermissionValidator Lcom/amazon/insights/validate/PermissionValidator; // 60: aload_1 // 61: invokevirtual 199 com/amazon/insights/validate/PermissionValidator:validate (Landroid/content/Context;)V // 64: getstatic 68 com/amazon/insights/AmazonInsights:accessNetworkStatePermissionValidator Lcom/amazon/insights/validate/PermissionValidator; // 67: aload_1 // 68: invokevirtual 199 com/amazon/insights/validate/PermissionValidator:validate (Landroid/content/Context;)V // 71: aload_0 // 72: aload_1 // 73: getstatic 41 com/amazon/insights/AmazonInsights:sdkInfo Lcom/amazon/insights/core/util/SDKInfo; // 76: aload_2 // 77: invokeinterface 205 1 0 // 82: aload_3 // 83: invokestatic 167 com/amazon/insights/core/DefaultInsightsContext:newInstance (Lcom/amazon/insights/InsightsCredentials;Landroid/content/Context;Lcom/amazon/insights/core/util/SDKInfo;ZLjava/util/Map;)Lcom/amazon/insights/core/InsightsContext; // 86: astore_0 // 87: aload_0 // 88: aload_2 // 89: aload 4 // 91: invokestatic 208 com/amazon/insights/AmazonInsights:newInstance (Lcom/amazon/insights/core/InsightsContext;Lcom/amazon/insights/InsightsOptions;Lcom/amazon/insights/InsightsCallback;)Lcom/amazon/insights/AmazonInsights; // 94: astore_0 // 95: goto -46 -> 49 // 98: astore_0 // 99: getstatic 49 com/amazon/insights/AmazonInsights:logger Lcom/amazon/insights/core/log/Logger; // 102: ldc -46 // 104: aload_0 // 105: invokevirtual 214 com/amazon/insights/core/log/Logger:deve (Ljava/lang/String;Ljava/lang/Throwable;)V // 108: new 96 com/amazon/insights/impl/DisabledAmazonInsights // 111: dup // 112: invokespecial 97 com/amazon/insights/impl/DisabledAmazonInsights:<init> ()V // 115: astore_0 // 116: goto -67 -> 49 // 119: astore_0 // 120: ldc 2 // 122: monitorexit // 123: aload_0 // 124: athrow // Local variable table: // start length slot name signature // 0 125 0 paramInsightsCredentials InsightsCredentials // 0 125 1 paramContext Context // 0 125 2 paramInsightsOptions InsightsOptions // 0 125 3 paramMap Map<String, String> // 0 125 4 paramInsightsCallback InsightsCallback<AmazonInsights> // Exception table: // from to target type // 54 87 98 java/lang/RuntimeException // 3 49 119 finally // 54 87 119 finally // 87 95 119 finally // 99 116 119 finally } static AmazonInsights newInstance(InsightsContext paramInsightsContext) { try { paramInsightsContext = newInstance(paramInsightsContext, newDefaultOptions()); return paramInsightsContext; } finally { paramInsightsContext = finally; throw paramInsightsContext; } } static AmazonInsights newInstance(InsightsContext paramInsightsContext, InsightsOptions paramInsightsOptions) { try { paramInsightsContext = newInstance(paramInsightsContext, paramInsightsOptions, null); return paramInsightsContext; } finally { paramInsightsContext = finally; throw paramInsightsContext; } } /* Error */ static AmazonInsights newInstance(InsightsContext paramInsightsContext, InsightsOptions paramInsightsOptions, InsightsCallback<AmazonInsights> paramInsightsCallback) { // Byte code: // 0: ldc 2 // 2: monitorenter // 3: aload_0 // 4: ldc -33 // 6: invokestatic 141 com/amazon/insights/core/util/Preconditions:checkNotNull (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; // 9: pop // 10: getstatic 55 com/amazon/insights/AmazonInsights:instances Ljava/util/Map; // 13: aload_0 // 14: invokeinterface 229 1 0 // 19: invokeinterface 121 2 0 // 24: ifeq +26 -> 50 // 27: getstatic 55 com/amazon/insights/AmazonInsights:instances Ljava/util/Map; // 30: aload_0 // 31: invokeinterface 229 1 0 // 36: invokeinterface 125 2 0 // 41: checkcast 2 com/amazon/insights/AmazonInsights // 44: astore_1 // 45: ldc 2 // 47: monitorexit // 48: aload_1 // 49: areturn // 50: new 231 com/amazon/insights/AmazonInsights$DefaultAmazonInsights // 53: dup // 54: aload_0 // 55: aload_1 // 56: aload_2 // 57: invokespecial 234 com/amazon/insights/AmazonInsights$DefaultAmazonInsights:<init> (Lcom/amazon/insights/core/InsightsContext;Lcom/amazon/insights/InsightsOptions;Lcom/amazon/insights/InsightsCallback;)V // 60: astore_1 // 61: getstatic 55 com/amazon/insights/AmazonInsights:instances Ljava/util/Map; // 64: aload_0 // 65: invokeinterface 229 1 0 // 70: aload_1 // 71: invokeinterface 237 3 0 // 76: pop // 77: goto -32 -> 45 // 80: astore_0 // 81: ldc 2 // 83: monitorexit // 84: aload_0 // 85: athrow // 86: astore_1 // 87: getstatic 99 com/amazon/insights/AmazonInsights:DISABLED_AMAZON_INSIGHTS Lcom/amazon/insights/impl/DisabledAmazonInsights; // 90: astore_1 // 91: goto -30 -> 61 // Local variable table: // start length slot name signature // 0 94 0 paramInsightsContext InsightsContext // 0 94 1 paramInsightsOptions InsightsOptions // 0 94 2 paramInsightsCallback InsightsCallback<AmazonInsights> // Exception table: // from to target type // 3 45 80 finally // 50 61 80 finally // 61 77 80 finally // 87 91 80 finally // 50 61 86 com/amazon/insights/impl/InitializationException } public static InsightsOptions newOptions(boolean paramBoolean1, boolean paramBoolean2) { return new DefaultInsightsOptions(paramBoolean1, paramBoolean2); } public abstract ABTestClient getABTestClient(); public abstract EventClient getEventClient(); public abstract SessionClient getSessionClient(); public abstract UserProfile getUserProfile(); } /* Location: * Qualified Name: com.amazon.insights.AmazonInsights * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
d86018c6660a017991817a00e7dedecd496c60f6
Java
tayduivn/crl-server
/src/main/java/cn/itruschina/crl/bean/domain/AuthAndCa.java
UTF-8
808
2.015625
2
[]
no_license
package cn.itruschina.crl.bean.domain; import lombok.Data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.UniqueConstraint; /** * @Author: yang_yunxiang * @Date: 2019/4/16 11:22 */ @Entity @Table(name = "auth_and_ca", uniqueConstraints = {@UniqueConstraint(columnNames = {"ca_config_id", "authorization_id"})}) @Data public class AuthAndCa extends BaseEntity { @Column(name = "ca_config_id", nullable = false) private long caConfigId; @Column(name = "authorization_id", nullable = false) private long authorizationId; public AuthAndCa() { } public AuthAndCa(long caConfigId, long authorizationId) { this.caConfigId = caConfigId; this.authorizationId = authorizationId; } }
true
b2ea4ce312e7d2faf6386c18349ba6e2a7a87ea9
Java
iorixxx/lucene-clueweb-retrieval
/src/main/java/org/clueweb09/tracks/WT09.java
UTF-8
2,934
2.3125
2
[ "Apache-2.0" ]
permissive
package org.clueweb09.tracks; import java.io.IOException; import java.nio.file.Paths; /** * 2009 Web Track topics (query field only) * http://trec.nist.gov/data/web/09/wt09.topics.queries-only */ public class WT09 extends Track { public WT09(String home) { super(home); } @Override protected void populateInfoNeeds() throws IOException { populateInfoNeedsWT(Paths.get(home, "topics-and-qrels", "topics.web.1-50.txt")); } @Override protected void populateQRelsMap() throws Exception { populateQRelsMap(Paths.get(home, "topics-and-qrels", "prels.web.1-50.txt")); } @Override protected Triple processQRelLine(String line) { String[] parts = whiteSpaceSplitter.split(line); assert parts.length == 5 : "prels file should contain five columns : " + line; int queryID = Integer.parseInt(parts[0]); String docID = parts[1]; int judge = Integer.parseInt(parts[2]); return new Triple(queryID, docID, judge); } private static final String[] wt09 = { "wt09-1:obama family tree", "wt09-2:french lick resort and casino", "wt09-3:getting organized", "wt09-4:toilet", "wt09-5:mitchell college", "wt09-6:kcs", "wt09-7:air travel information", "wt09-8:appraisals", "wt09-9:used car parts", "wt09-10:cheap internet", "wt09-11:gmat prep classes", "wt09-12:djs", "wt09-13:map", "wt09-14:dinosaurs", "wt09-15:espn sports", "wt09-16:arizona game and fish", "wt09-17:poker tournaments", "wt09-18:wedding budget calculator", "wt09-19:the current", //"wt09-20:defender", "wt09-21:volvo", "wt09-22:rick warren", "wt09-23:yahoo", "wt09-24:diversity", "wt09-25:euclid", "wt09-26:lower heart rate", "wt09-27:starbucks", "wt09-28:inuyasha", "wt09-29:ps 2 games", "wt09-30:diabetes education", "wt09-31:atari", "wt09-32:website design hosting", "wt09-33:elliptical trainer", "wt09-34:cell phones", "wt09-35:hoboken", "wt09-36:gps", "wt09-37:pampered chef", "wt09-38:dogs for adoption", "wt09-39:disneyland hotel", "wt09-40:michworks", "wt09-41:orange county convention center", "wt09-42:the music man", "wt09-43:the secret garden", "wt09-44:map of the united states", "wt09-45:solar panels", "wt09-46:alexian brothers hospital", "wt09-47:indexed annuity", "wt09-48:wilson antenna", "wt09-49:flame designs", "wt09-50:dog heat" }; }
true
dc2f3ae8187a4e24f5a9fd28001cafdbbde9e155
Java
sohamdatey/DesingPatterns
/src/main/java/com/designpattern/testing/OnDemandReport.java
UTF-8
450
2.484375
2
[]
no_license
package com.designpattern.testing; import java.util.ArrayList; import java.util.List; public class OnDemandReport { List<OnDemandReportData> OnDemandReportDatas= new ArrayList<OnDemandReportData>(); public List<OnDemandReportData> getOnDemandReportDatas() { return OnDemandReportDatas; } public void setOnDemandReportDatas(List<OnDemandReportData> onDemandReportDatas) { OnDemandReportDatas = onDemandReportDatas; } }
true
9c179fd064e6775369deb39b1f0aa59d1ba17f47
Java
Mohitkumar1998/SampleOnlineAssessmentService
/src/main/java/com/wipro/onlineAssessmentSystem/controller/loginController.java
UTF-8
6,207
2.28125
2
[]
no_license
package com.wipro.onlineAssessmentSystem.controller; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.wipro.onlineAssessmentSystem.entity.*; import com.wipro.onlineAssessmentSystem.repository.testdataRepository; import com.wipro.onlineAssessmentSystem.repository.userRepository; import com.wipro.onlineAssessmentSystem.repository.userdataRepository; @Controller @RequestMapping("/") public class loginController { @Autowired private userRepository userRepo; @Autowired private userdataRepository userdataRepo; @Autowired private testdataRepository testdataRepo; Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); @RequestMapping("/login") public ModelAndView login() { return new ModelAndView("login"); } @RequestMapping("/invalidUserPage") public ModelAndView invalidUser() { return new ModelAndView("invalidUserPage"); } @RequestMapping("/passwordErrorPage") public ModelAndView passwordError() { return new ModelAndView("passwordErrorPage"); } @RequestMapping("/register") public ModelAndView register() { return new ModelAndView("register"); } @PostMapping("/registeration/do") public ModelAndView registerNewUser(@RequestParam("email") String email, @RequestParam("firstName") String firstname, @RequestParam("lastName") String lastname, @RequestParam("password") String password) throws IOException { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); password=encoder.encode(password); user newUser = new user(email,password,"USER"); userdata newUserData = new userdata(email, firstname, lastname, "USER"); userRepo.save(newUser); userdataRepo.save(newUserData); ModelAndView registration = new ModelAndView("registerConfirmation"); registration.addObject("firstname", firstname); registration.addObject("lastname", lastname); return registration; } @RequestMapping("/userDashboard") public ModelAndView user() { return new ModelAndView("userDashboard"); } @RequestMapping("/user/springAssessment") public ModelAndView userSpringAssessment() { return new ModelAndView("springAssessment"); } @PostMapping("/user/springAssessment/test") public ModelAndView springAssessmentTest(@RequestParam("Question1") String answer1, @RequestParam("Question2") String answer2, @RequestParam("Question3") String answer3, @RequestParam("Question4") String answer4, @RequestParam("Question5" ) String answer5) { int score = 0; if(answer1.equals("J2EE App Development Framework")) { score++; } if(answer2.equals("Inversion Of Control")) { score++; } if(answer3.equals("Aspect Oriented Programming")) { score++; } if(answer4.equals("Application Context")) { score++; } if(answer5.equals("Dispatcher Servlet")) { score++; } score*=10; ModelAndView evaluationPage = new ModelAndView("evaluationPage"); String message = "Congratulations !!! You have passed !!!"; String result ="Passed"; if(score<30) { message = "Sorry !!! Better Luck Next Time !!!"; result="Failed"; } Authentication auth = SecurityContextHolder.getContext().getAuthentication(); testdata thisTestData = new testdata(auth.getName(), formatter.format(date).toString(), "Spring-L1", score, 50, result); testdataRepo.save(thisTestData); evaluationPage.addObject("msg", message); return evaluationPage; } @RequestMapping("/user/hibernateAssessment") public ModelAndView userHibernateAssessment() { return new ModelAndView("hibernateAssessment"); } @PostMapping("/user/hibernateAssessment/test") public ModelAndView hibernateAssessmentTest(@RequestParam("Question1") String answer1, @RequestParam("Question2") String answer2, @RequestParam("Question3") String answer3, @RequestParam("Question4") String answer4, @RequestParam("Question5" ) String answer5) { int score = 0; if(answer1.equals("Object Relational Mapping")) { score++; } if(answer2.equals("uni-directional & bi-directional")) { score++; } if(answer3.equals("configuration file")) { score++; } if(answer4.equals("Hibernate Query Language")) { score++; } if(answer5.equals("isolation levels")) { score++; } score*=10; ModelAndView evaluationPage = new ModelAndView("evaluationPage"); String message = "Congratulations !!! You have passed !!!"; String result="Passed"; if(score<30) { message = "Sorry !!! Better Luck Next Time !!!"; result="Failed"; } Authentication auth = SecurityContextHolder.getContext().getAuthentication(); testdata thisTestData = new testdata(auth.getName(), formatter.format(date).toString(), "Spring-L1", score, 50, result); testdataRepo.save(thisTestData); evaluationPage.addObject("msg", message); return evaluationPage; } @RequestMapping("/adminDashboard") public ModelAndView admin() { return new ModelAndView("adminDashboard"); } @RequestMapping("/admin/allCandidates") public ModelAndView adminViewAllCandidates() { ModelAndView allCandidates = new ModelAndView("viewCandidates"); List<userdata> allCandidatesList = userdataRepo.findAll(); System.out.println(allCandidatesList); allCandidates.addObject("allCandidateList", allCandidatesList); return allCandidates; } @RequestMapping("/admin/allTests") public ModelAndView adminViewAllTests() { ModelAndView allTests = new ModelAndView("viewTests"); List<testdata> allTestsList = testdataRepo.findAll(); System.out.println(allTestsList); allTests.addObject("allTestsList", allTestsList); return allTests; } }
true
7677049a8ac3e3d2aae754a0f0200699336fb942
Java
Tolriq/DmsExplorer
/mobile/src/main/java/net/mm2d/dmsexplorer/view/ServerListActivity.java
UTF-8
3,127
1.8125
2
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.view; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import net.mm2d.dmsexplorer.R; import net.mm2d.dmsexplorer.Repository; import net.mm2d.dmsexplorer.domain.model.ControlPointModel; import net.mm2d.dmsexplorer.settings.Settings; import net.mm2d.dmsexplorer.util.AttrUtils; import net.mm2d.dmsexplorer.view.base.BaseActivity; import net.mm2d.dmsexplorer.view.delegate.ServerListActivityDelegate; /** * MediaServerのサーチ、選択を行うActivity。 * * <p>アプリ起動時最初に表示されるActivity * * @author <a href="mailto:ryo@mm2d.net">大前良介 (OHMAE Ryosuke)</a> */ public class ServerListActivity extends BaseActivity { private Settings mSettings; private ControlPointModel mControlPointModel; private ServerListActivityDelegate mDelegate; public static void start(@NonNull final Context context) { final Intent intent = new Intent(context, ServerListActivity.class); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } public ServerListActivity() { super(true); } @Override protected void onCreate(@Nullable final Bundle savedInstanceState) { mSettings = Settings.get(); setTheme(mSettings.getThemeParams().getListThemeId()); super.onCreate(savedInstanceState); final Repository repository = Repository.get(); mControlPointModel = repository.getControlPointModel(); repository.getThemeModel().setThemeColor(this, AttrUtils.resolveColor(this, R.attr.colorPrimary, Color.BLACK), ContextCompat.getColor(this, R.color.defaultStatusBar)); if (savedInstanceState == null) { mControlPointModel.initialize(); } mDelegate = ServerListActivityDelegate.create(this); mDelegate.onCreate(savedInstanceState); } @Override protected void onDestroy() { super.onDestroy(); if (isFinishing()) { mControlPointModel.terminate(); } } @Override protected void updateOrientationSettings() { mSettings.getBrowseOrientation() .setRequestedOrientation(this); } @Override protected void onSaveInstanceState(@NonNull final Bundle outState) { mDelegate.prepareSaveInstanceState(); super.onSaveInstanceState(outState); mDelegate.onSaveInstanceState(outState); } @Override protected void onStart() { super.onStart(); mControlPointModel.searchStart(); mDelegate.onStart(); } @Override protected void onStop() { super.onStop(); mControlPointModel.searchStop(); } }
true
40f710fb9ac3640af9d3ad699273b50b2911cc78
Java
Arvindnerforce/Hivego
/app/src/main/java/com/chat/laptop/hivego/dashboard/navigation/RecyclerAdapterDrawer.java
UTF-8
3,566
2.109375
2
[]
no_license
package com.chat.laptop.hivego.dashboard.navigation; import android.content.Context; import android.content.Intent; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.chat.laptop.hivego.R; import java.util.Collections; import java.util.List; /** * Created by John on 9/14/2016. */ public class RecyclerAdapterDrawer extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int ALERT_DRAWER = 4; public static int selected_item = 0; private final LayoutInflater inflater; List<RowDataDrawer> data = Collections.emptyList(); Context context; private clickListner click = null; private final int NORMAL_DRAWER = 2; private Intent intent; int drawableId[]; RecyclerAdapterDrawer(Context context, List<RowDataDrawer> data) { inflater = LayoutInflater.from(context); this.data = data; this.context = context; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.row_navigation_drawer, parent, false); MyViewHolder viewHolder = new MyViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { MyViewHolder myViewHolder = (MyViewHolder) holder; /* if(position == selected_item) { myViewHolder.textView.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary)); // myViewHolder.linearLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.selected_menu_back)); //int cImage = drawableId[position]; // myViewHolder.imageView.setImageResource(cImage); } else { //myViewHolder.textView.setTextColor(ContextCompat.getColor(context, R.color.black)); myViewHolder.linearLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.white)); // myViewHolder.imageView.setImageResource(data.get(position).id); } */ myViewHolder.textView.setText(data.get(position).text); } private void showMessage(String s) { Toast.makeText(context, s, Toast.LENGTH_SHORT).show(); } @Override public int getItemCount() { Log.i("TAG2 count", data.size() + ""); return data.size(); } public void setClickListner(clickListner click) { this.click = click; } class MyViewHolder extends RecyclerView.ViewHolder { TextView textView; LinearLayout linearLayout; public MyViewHolder(final View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.textView1); linearLayout = (LinearLayout) itemView.findViewById(R.id.header); linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { click.itemClicked(itemView, getAdapterPosition()); } }); } } public interface clickListner { void itemClicked(View view, int position); } }
true
50f1b817c0ff65e13545d5889b8c9b469d8a29a3
Java
yunwei1237/ScottishFold
/src/main/java/com/tcf/editor/util/DynamicJarClassLoader.java
WINDOWS-1252
2,615
2.5625
3
[]
no_license
package com.tcf.editor.util; import java.io.IOException; import java.io.InputStream; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** ?* ̬ ?*? ?*/ public class DynamicJarClassLoader extends ClassLoader { private static Logger logger = LoggerFactory.getLogger(DynamicJarClassLoader.class); private JarFile jarFile; private ClassLoader parent; public DynamicJarClassLoader(JarFile jarFile) { super(Thread.currentThread().getContextClassLoader()); this.parent = Thread.currentThread().getContextClassLoader(); this.jarFile = jarFile; } public DynamicJarClassLoader(JarFile jarFile, ClassLoader parent) { super(parent); this.parent = parent; this.jarFile = jarFile; } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { try { Class<?> c = null; String path = name.replace('.', '/').concat(".class"); if(null != jarFile){ JarEntry entry = jarFile.getJarEntry(path); if(null != entry){ InputStream is = jarFile.getInputStream(entry); int availableLen = is.available(); int len = 0; byte[] bt1 = new byte[availableLen]; while (len < availableLen) { len += is.read(bt1, len, availableLen - len); } c = defineClass(name, bt1, 0, bt1.length); if (resolve) { resolveClass(c); } }else{ if (parent != null) { return parent.loadClass(name); } } } return c; } catch (IOException e) { throw new ClassNotFoundException("Class " + name + " not found."); } } @Override public InputStream getResourceAsStream(String name) { InputStream is = null; try { if(null != jarFile){ JarEntry entry = jarFile.getJarEntry(name); if (entry != null) { is = jarFile.getInputStream(entry); } if (is == null) { is = super.getResourceAsStream(name); } } } catch (IOException e) { logger.error(e.getMessage()); } return is; } }
true
2beb71df927b0eb6f88a39fbdc6e24c0198bc889
Java
mohammadaminha/Widgets_Package
/widgets/src/main/java/mohammadaminha/com/widgets/Date_Picker/Utils.java
UTF-8
3,577
2.234375
2
[]
no_license
/* * Copyright (C) 2013 The Android Open Source Project * * 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 mohammadaminha.com.widgets.Date_Picker; import android.animation.Keyframe; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.annotation.SuppressLint; import android.content.res.Resources; import android.os.Build; import android.util.TypedValue; import android.view.View; import mohammadaminha.com.widgets.Date_Picker.utils.PersianCalendarUtils; /** * Utility helper functions for time and date pickers. */ public class Utils { //public static final int MONDAY_BEFORE_JULIAN_EPOCH = Time.EPOCH_JULIAN_DAY - 3; private static final int PULSE_ANIMATOR_DURATION = 544; // Alpha level for time picker selection. public static final int SELECTED_ALPHA = 255; public static final int SELECTED_ALPHA_THEME_DARK = 255; // Alpha level for fully opaque. public static final int FULL_ALPHA = 255; private static boolean isJellybeanOrLater() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; } /** * Try to speak the specified text, for accessibility. Only available on JB or later. * @param text Text to announce. */ @SuppressLint("NewApi") public static void tryAccessibilityAnnounce(View view, CharSequence text) { if (isJellybeanOrLater() && view != null && text != null) { view.announceForAccessibility(text); } } public static int getDaysInMonth(int month, int year) { if (month < 6) { return 31; } else if (month < 11) { return 30; } else { if (PersianCalendarUtils.isPersianLeapYear(year)) return 30; else return 29; } } /** * Render an animator to pulsate a view in place. * @param labelToAnimate the view to pulsate. * @return The animator object. Use .start() to begin. */ public static ObjectAnimator getPulseAnimator(View labelToAnimate, float decreaseRatio, float increaseRatio) { Keyframe k0 = Keyframe.ofFloat(0f, 1f); Keyframe k1 = Keyframe.ofFloat(0.275f, decreaseRatio); Keyframe k2 = Keyframe.ofFloat(0.69f, increaseRatio); Keyframe k3 = Keyframe.ofFloat(1f, 1f); PropertyValuesHolder scaleX = PropertyValuesHolder.ofKeyframe("scaleX", k0, k1, k2, k3); PropertyValuesHolder scaleY = PropertyValuesHolder.ofKeyframe("scaleY", k0, k1, k2, k3); ObjectAnimator pulseAnimator = ObjectAnimator.ofPropertyValuesHolder(labelToAnimate, scaleX, scaleY); pulseAnimator.setDuration(PULSE_ANIMATOR_DURATION); return pulseAnimator; } /** * Convert Dp to Pixel */ @SuppressWarnings("unused") public static int dpToPx(float dp, Resources resources){ float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.getDisplayMetrics()); return (int) px; } }
true
4df928e7fe3c681e2055f072019f39cfae333890
Java
springwindyike/ad-server
/AdAdmin/src/main/cn/adwalker/model/ad/dao/impl/PlacementResBannerDaoImpl.java
UTF-8
3,195
2.078125
2
[]
no_license
package cn.adwalker.model.ad.dao.impl; import java.util.List; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import cn.adwalker.core.repository.impl.BaseDaoImpl; import cn.adwalker.model.ad.dao.IPlacementResBannerDao; import cn.adwalker.model.ad.domain.PlacementResBanner; /** * * <p> * Title: CampaignDaoImpl * </p> * <p> * Company: adwalker * </p> * * @author lichuang * @date 2013-4-2 */ @Repository("placementResBannerDao") public class PlacementResBannerDaoImpl extends BaseDaoImpl<PlacementResBanner> implements IPlacementResBannerDao { public PlacementResBannerDaoImpl() { setTableName("T_PLACEMENT_RES_BANNER"); } /** * (non-Javadoc) * <p> * Title: getByPlacement * </p> * * @param id * @return * @throws Exception * @see cn.adwalker.model.ad.dao.IPlacementResBannerDao#getByPlacement(java.lang.Long) */ @SuppressWarnings("unchecked") @Override public PlacementResBanner getByPlacement(Long id) throws Exception { PlacementResBanner entity = null; if (id != null) { List<PlacementResBanner> list = (List<PlacementResBanner>) super.findAll("select id,response_type,response_category,redirect_url,img_url_first,img_url_second,img_url_third,placement_id,weight from T_PLACEMENT_RES_BANNER where placement_id=" + id, PlacementResBanner.class); if (list != null && list.size() > 0) { entity = list.get(0); } } return entity; } /** * (non-Javadoc) * <p> * Title: saveOrUpdate * </p> * * @param resBanner * @throws Exception * @see cn.adwalker.model.ad.dao.IPlacementResBannerDao#saveOrUpdate(cn.adwalker.model.ad.domain.PlacementResBanner) */ @Override public void saveOrUpdate(PlacementResBanner banner) throws Exception { PlacementResBanner entity = this.getByPlacement(banner.getPlacement_id()); if (entity != null) { if (!StringUtils.isEmpty(banner.getImg_url_first())) { entity.setImg_url_first(banner.getImg_url_first()); } if (!StringUtils.isEmpty(banner.getImg_url_second())) { entity.setImg_url_second(banner.getImg_url_second()); } if (!StringUtils.isEmpty(banner.getImg_url_third())) { entity.setImg_url_third(banner.getImg_url_third()); } if (banner.getResponse_category() != null) { entity.setResponse_category(banner.getResponse_category()); } if (banner.getResponse_type() != null) { entity.setResponse_type(banner.getResponse_type()); } if (!StringUtils.isEmpty(banner.getRedirect_url())) { entity.setRedirect_url(banner.getRedirect_url()); } if (banner.getWeight() != null) { entity.setWeight(banner.getWeight()); } super.update(entity); } else { super.insert(banner); } } /** * (non-Javadoc) * <p> * Title: getMaxWeight * </p> * * @see cn.adwalker.model.ad.dao.IPlacementResWallScoreDao#getMaxWeight() */ @SuppressWarnings("deprecation") @Override public int getMaxWeight() { Integer integer = jdbcTemplate.queryForInt("select IFNULL(max(res.weight),0) from T_PLACEMENT_RES_BANNER res ,T_CAMPAIGN_PLACEMENT_REL rel where res.PLACEMENT_ID=rel.PLACEMENT_ID and rel.status=1", new Object[] {}); return integer.intValue(); } }
true
363dd2264800471995279e0da7b7b67db01c33d7
Java
KHikami/ProjectFiCallingDeciphered
/DialerJADXDecompile/defpackage/lo.java
UTF-8
1,102
1.945313
2
[]
no_license
package defpackage; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; /* compiled from: PG */ /* renamed from: lo */ public final class lo extends il { public static final Creator CREATOR; public int a; public Parcelable b; public ClassLoader c; public lo(Parcelable parcelable) { super(parcelable); } public final void writeToParcel(Parcel parcel, int i) { super.writeToParcel(parcel, i); parcel.writeInt(this.a); parcel.writeParcelable(this.b, i); } public final String toString() { return "FragmentPager.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " position=" + this.a + "}"; } static { CREATOR = buf.a(new lp()); } lo(Parcel parcel, ClassLoader classLoader) { super(parcel, classLoader); if (classLoader == null) { classLoader = getClass().getClassLoader(); } this.a = parcel.readInt(); this.b = parcel.readParcelable(classLoader); this.c = classLoader; } }
true
05e84b1ef09a52332937c4e1390844f3148de8d0
Java
zhhtsoft/micro-spring-cloud-examples
/microservice-consumer/src/main/java/com/zhht/cloud/controller/RibbonTestController.java
UTF-8
720
1.960938
2
[]
no_license
package com.zhht.cloud.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.zhht.cloud.entity.User; @RestController @RequestMapping("/ribbontest") public class RibbonTestController { @Autowired public RestTemplate RestTemplate; @RequestMapping("/getUserById/{id}") public User getUserInfo(@PathVariable("id") int id){ return RestTemplate.getForObject("http://microservice-provider/user/getUserById?id="+id, User.class ); } }
true