text
stringlengths
10
2.72M
package com.facebook.react.views.modal; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Build; import android.support.v4.view.u; import android.view.View; import android.view.Window; import android.view.WindowInsets; import com.facebook.react.bridge.ReactContext; public class TranslucentModalHostView extends ReactModalHostView { public TranslucentModalHostView(Context paramContext) { super(paramContext); } private boolean isDark() { Activity activity = ((ReactContext)getContext()).getCurrentActivity(); return (activity == null) ? true : (((activity.getWindow().getDecorView().getSystemUiVisibility() & 0x2000) != 0)); } public static void setStatusBarColor(Window paramWindow, int paramInt) { if (Build.VERSION.SDK_INT >= 21) { paramWindow.addFlags(-2147483648); paramWindow.setStatusBarColor(paramInt); } } public static void setStatusBarStyle(Window paramWindow, boolean paramBoolean) { if (Build.VERSION.SDK_INT >= 23) { boolean bool; View view = paramWindow.getDecorView(); if (paramBoolean) { bool = true; } else { bool = false; } view.setSystemUiVisibility(bool); } } public static void setStatusBarTranslucent(Window paramWindow, boolean paramBoolean) { if (Build.VERSION.SDK_INT >= 21) { View view = paramWindow.getDecorView(); if (paramBoolean) { view.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { public final WindowInsets onApplyWindowInsets(View param1View, WindowInsets param1WindowInsets) { WindowInsets windowInsets = param1View.onApplyWindowInsets(param1WindowInsets); return windowInsets.replaceSystemWindowInsets(windowInsets.getSystemWindowInsetLeft(), 0, windowInsets.getSystemWindowInsetRight(), windowInsets.getSystemWindowInsetBottom()); } }); } else { view.setOnApplyWindowInsetsListener(null); } u.r(view); } } protected void showOrUpdate() { super.showOrUpdate(); Dialog dialog = getDialog(); if (dialog != null) { setStatusBarTranslucent(dialog.getWindow(), true); setStatusBarColor(dialog.getWindow(), 0); if (Build.VERSION.SDK_INT >= 23) setStatusBarStyle(dialog.getWindow(), isDark()); } } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\views\modal\TranslucentModalHostView.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.bytedance.ies.bullet.kit.rn.internal; import android.text.TextUtils; import com.bytedance.ies.bullet.b.e.a.f; import com.bytedance.ies.bullet.b.e.a.h; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableMap; import com.facebook.react.module.annotations.ReactModule; import d.f.b.g; import d.f.b.l; import d.f.b.m; import d.x; import org.json.JSONException; import org.json.JSONObject; @ReactModule(name = "RNBridge") public final class RnBridgeModule extends ReactContextBaseJavaModule { public static final a Companion = new a(null); public final d.f.a.a<h> bridgeRegistryProvider; public RnBridgeModule(ReactApplicationContext paramReactApplicationContext, d.f.a.a<? extends h> parama) { super(paramReactApplicationContext); this.bridgeRegistryProvider = (d.f.a.a)parama; } @ReactMethod public final void call(String paramString, ReadableMap paramReadableMap, Callback paramCallback) { l.b(paramString, "func"); l.b(paramReadableMap, "params"); l.b(paramCallback, "callback"); if (TextUtils.isEmpty(paramString)) return; UiThreadUtil.runOnUiThread(new b(this, paramString, paramReadableMap, paramCallback)); } public final String getName() { return "RNBridge"; } public static final class a { private a() {} } static final class b implements Runnable { b(RnBridgeModule param1RnBridgeModule, String param1String, ReadableMap param1ReadableMap, Callback param1Callback) {} public final void run() { h h = (h)this.a.bridgeRegistryProvider.invoke(); if (h != null) { String str = this.b; JSONObject jSONObject = com.bytedance.ies.bullet.kit.rn.d.b.a(this.c); l.a(jSONObject, "JsonConvertHelper.reactToJSON(params)"); h.a(str, jSONObject, new f.b(this) { public final void a(int param2Int, String param2String) { l.b(param2String, "message"); WritableMap writableMap = Arguments.createMap(); writableMap.putInt("code", param2Int); writableMap.putString("message", param2String); this.a.d.invoke(new Object[] { writableMap }); } public final void a(JSONObject param2JSONObject) { l.b(param2JSONObject, "data"); try { this.a.d.invoke(new Object[] { com.bytedance.ies.bullet.kit.rn.d.b.a(param2JSONObject) }); return; } catch (JSONException jSONException) { jSONException.printStackTrace(); return; } } }new d.f.a.b<Throwable, x>(this) { }); } } } public static final class null implements f.b { null(RnBridgeModule.b param1b) {} public final void a(int param1Int, String param1String) { l.b(param1String, "message"); WritableMap writableMap = Arguments.createMap(); writableMap.putInt("code", param1Int); writableMap.putString("message", param1String); this.a.d.invoke(new Object[] { writableMap }); } public final void a(JSONObject param1JSONObject) { l.b(param1JSONObject, "data"); try { this.a.d.invoke(new Object[] { com.bytedance.ies.bullet.kit.rn.d.b.a(param1JSONObject) }); return; } catch (JSONException jSONException) { jSONException.printStackTrace(); return; } } } static final class null extends m implements d.f.a.b<Throwable, x> { null(RnBridgeModule.b param1b) { super(1); } } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\bytedance\ies\bullet\kit\rn\internal\RnBridgeModule.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.leo.pattern.threadpool; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; public class CustomRejectedExecutionHandler implements RejectedExecutionHandler{ /** * @see java.util.concurrent.ThreadPoolExecutor.AbortPolicy and so on */ @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { // 这里实现自己的策略 } }
package com.pay.schedule; import com.pay.schedule.pojo.model.ScheduleExecutionRecord; import com.pay.schedule.pojo.model.ScheduleWorkJob; import com.pay.schedule.pojo.model.dict.ScheduleExecutionState; import com.pay.schedule.service.ScheduleExecutionRecordService; import lombok.extern.slf4j.Slf4j; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Date; @RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class SchedulerTest { @Autowired private QuartzSchedulerUtils quartzSchedulerUtils; @Autowired private ScheduleExecutionRecordService scheduleExecutionRecordService; @Ignore public void testAddNewJob() throws Exception { String jobClassName = "com.pay.schedule.testJob.HelloJob"; String jobGroupName = "testGroup"; String conExpression = "*/3 * * * * ?"; ScheduleWorkJob jobHello = quartzSchedulerUtils.createScheduleJob(jobClassName,jobGroupName,conExpression); quartzSchedulerUtils.addCronJob(jobHello); Thread.sleep(10000); quartzSchedulerUtils.pauseJob(jobClassName,jobGroupName); Thread.sleep(10000); quartzSchedulerUtils.resumeJob(jobClassName,jobGroupName); Thread.sleep(10000); quartzSchedulerUtils.deleteJob(jobClassName,jobGroupName); Thread.sleep(20000); } @Ignore public void addTestNewJob() throws Exception { String jobClassName2 = "com.pay.schedule.testJob.NewJob"; String jobGroupName2 = "testGroup"; int intervaltime = 3; ScheduleWorkJob jobNew = quartzSchedulerUtils.createScheduleJob(jobClassName2,jobGroupName2,intervaltime); quartzSchedulerUtils.addSimpleJob(jobNew); Thread.sleep(10000); } @Ignore public void testToDoJob()throws Exception{ String jobClassName3 = "com.pay.schedule.testJob.PrepareWork"; String jobGroupName3 = "testGroup"; String conExpression3 = "*/5 * * * * ?"; ScheduleWorkJob workJob = quartzSchedulerUtils.createScheduleJob(jobClassName3,jobGroupName3,conExpression3); quartzSchedulerUtils.addCronJob(workJob); Thread.sleep(10000); } @Test public void insertNewExecutionLog(){ ScheduleExecutionRecord record = new ScheduleExecutionRecord(); record.setRecordId(String.valueOf(new Date().getTime())); record.setExecutionTime(1000L); record.setEndTime(new Date()); record.setExceptionMsg("没错误"); record.setExecutionState(ScheduleExecutionState.RUNNING); record.setJobGroupName("12345"); record.setJobClassName("56789"); record.setOccurTime(new Date()); // ScheduleExecutionRecordDtm recordDtm = new ScheduleExecutionRecordDtm(); // List<ConvertTypeBean> convertList = new ArrayList<>(); // convertList.add(new ConvertTypeBean(Date.class, FormatRule.formatDateRule("yyyy_MM_dd:HH_mm_ss:SSS"))); // BeanUtils.copyBeanWithRuleByType(record,recordDtm,convertList); scheduleExecutionRecordService.insertNewExecuteLog(record); record.setJobGroupName("888888"); record.setJobClassName("999999"); scheduleExecutionRecordService.saveExecuteLogResult(record); } }
package com.game.huyhoang.weirdchess; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; /** * Created by huyhoang on 13/07/2016. */ public class Player extends GameObject { private long startTime; private boolean playing; private Bitmap bitmap; private boolean moving; private Tile tile; private int score; public Player(Bitmap bitmap, Tile tile, int w, int h) { this.bitmap = bitmap; this.width = w; this.height = h; this.tile = tile; moving = false; playing = false; this.x = tile.getX() + (tile.getWidth() - width) / 2; this.y = tile.getY() + (tile.getHeight() - height) / 2; score = 0; startTime = System.nanoTime(); } public void update() { long elapsed = (System.nanoTime() - startTime) / 1000000; if (elapsed > 100) { score++; startTime = System.nanoTime(); } x = tile.getX() + (tile.getWidth() - width) / 2; y = tile.getY() + (tile.getHeight() - height) / 2; } public void moveToTile(Tile t) { tile = t; x = tile.getX() + (tile.getWidth() - width) / 2; y = tile.getY() + (tile.getHeight() - height) / 2; moving = false; } public void draw(Canvas canvas) { canvas.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), new Rect(x, y, x + GamePanel.TILE_WIDTH, y + GamePanel.TILE_HEIGHT), null); } public boolean isPlaying() { return playing; } public boolean isMoving() { return moving; } public void setPlaying(boolean b) { playing = b; } public void setMoving(boolean b) { moving = b; } public Tile getTile() { return tile; } public int getScore() { return score; } public void reset() { this.score = 0; this.startTime = 0; this.moving = false; this.playing = false; } public void setTile(Tile tile) { this.tile = tile; } public void setScore(int score) { this.score = score; } }
package app; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; /** * Class that runs our Photo Application. (Starts the UI logic in PhotosView Package). * @author Eshan Wadhwa and Vishal Patel * */ public class Photos extends Application { @Override public void start(Stage primaryStage) throws Exception{ try { Persistance.readUser(); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/PhotosView/Login.fxml")); AnchorPane root = (AnchorPane) loader.load(); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.setResizable(false); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } /* Persistance.readUser(); Parent root = FXMLLoader.load(getClass().getResource("/PhotosView/Login.fxml")); primaryStage.setTitle("Photos By: Vishal Patel and Eshan Wadhwa"); primaryStage.setScene(new Scene(root)); primaryStage.show(); */ } public static void main(String[] args) { launch(args); } }
package com.tencent.mm.plugin.appbrand.jsapi.d; import com.tencent.mm.plugin.appbrand.page.p; import com.tencent.mm.plugin.appbrand.widget.input.AppBrandInputInvokeHandler; import com.tencent.mm.plugin.appbrand.widget.input.AppBrandInputInvokeHandler.a; class c$2 implements a { final /* synthetic */ AppBrandInputInvokeHandler fQH; final /* synthetic */ c fQI; c$2(c cVar, AppBrandInputInvokeHandler appBrandInputInvokeHandler) { this.fQI = cVar; this.fQH = appBrandInputInvokeHandler; } public final void cO(boolean z) { if (z) { p kK = c.kK(this.fQH.getInputId()); if (kK != null && kK.isRunning()) { } } } }
package pl.ark.chr.buginator.data; import org.apache.commons.lang3.StringEscapeUtils; import pl.ark.chr.buginator.domain.core.Error; import pl.ark.chr.buginator.domain.core.ErrorStackTrace; import java.util.List; /** * Created by Arek on 2017-02-01. */ public class ErrorWrapper { private final static String EXCEPTION_PREFIX = "Exception"; private final static String CAUSED_BY_PREFIX = "Caused"; private Error error; private String errorStackTrace; public ErrorWrapper(Error error) { error.setRequestHeaders(StringEscapeUtils.unescapeJava(error.getRequestHeaders())); error.setRequestParams(StringEscapeUtils.unescapeJava(error.getRequestParams())); this.error = error; this.errorStackTrace = generateStackTraceString(error.getStackTrace()); } private String generateStackTraceString(List<ErrorStackTrace> stackTrace) { StringBuilder builder = new StringBuilder(300); stackTrace.forEach(t -> { if(t != null) { if (t.getStackTrace().startsWith(EXCEPTION_PREFIX) || t.getStackTrace().startsWith(CAUSED_BY_PREFIX)) { builder.append(t.getStackTrace()).append("\n"); } else { builder.append("\t").append(t.getStackTrace()).append("\n"); } } }); return builder.toString(); } public Error getError() { return error; } public String getErrorStackTrace() { return errorStackTrace; } }
package tests.contactUsTests; import libs.ConfigData; import libs.ExcelDriver; import org.junit.After; import org.junit.Assert; import org.junit.Test; import pages.ContactUsPage; import tests.ParentTest; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; public class TestCase10 extends ParentTest{ ContactUsPage contactUsPage; /** * CONSTRUCTOR for TestCase10 * @param browser * @throws MalformedURLException */ public TestCase10(String browser) throws MalformedURLException { super(browser); } @Test public void test10() throws IOException { contactUsPage = new ContactUsPage(driver); contactUsPage.openContactUsPageAndBrowser(); Assert.assertTrue("Check step1: ", contactUsPage.selectNoForHavingAccountFromDD()&& contactUsPage.selectQuestionFromDDByQuestionNum(1)&& contactUsPage.clickSendEmailButton()); Assert.assertTrue("Check result: ", contactUsPage.isPopUpErrorOnPage()); } @After public void tearDown(){ contactUsPage.closeContactUsPageAndBrowser(); } }
package com.tencent.mm.pluginsdk.model.app; import android.support.design.a$i; import com.tencent.mm.ab.b; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.ak.o; import com.tencent.mm.compatible.util.g; import com.tencent.mm.g.a.ms; import com.tencent.mm.model.au; import com.tencent.mm.model.q; import com.tencent.mm.model.s; import com.tencent.mm.modelcdntran.d; import com.tencent.mm.modelcdntran.i; import com.tencent.mm.modelcdntran.keep_SceneResult; import com.tencent.mm.network.k; import com.tencent.mm.opensdk.modelmsg.WXMediaMessage; import com.tencent.mm.platformtools.ai; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.bhy; import com.tencent.mm.protocal.c.bvm; import com.tencent.mm.protocal.c.bvn; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.bd; import com.tencent.mm.y.g.a; public final class al extends l implements k { a bGT = null; String bJK; boolean dVC = true; String dVk = ""; private i.a dVu = new 1(this); private b diG; e diJ; private boolean dlR = false; int dlT = 0; keep_SceneResult dlU; c dlW = new 2(this); private String dwq = null; private boolean qAB = true; private long qAC = -1; b qAe = null; long qAh = -1; int retCode = 0; long startTime = 0; String toUser; public al(long j, String str, String str2) { this.qAh = j; this.dwq = str; this.bJK = str2; b.a aVar = new b.a(); aVar.dIG = new bvm(); aVar.dIH = new bvn(); aVar.uri = "/cgi-bin/micromsg-bin/uploadappattach"; aVar.dIF = 220; aVar.dII = a$i.AppCompatTheme_radioButtonStyle; aVar.dIJ = 1000000105; this.diG = aVar.KT(); x.i("MicroMsg.NetSceneUploadAppAttach", "summerbig new NetSceneUploadAppAttach rowid[%d], emoticonmd5[%s], stack[%s]", new Object[]{Long.valueOf(j), str, bi.cjd()}); } public final int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; this.qAe = new b(); if (!ao.asF().b(this.qAh, this.qAe) || this.qAe == null) { x.e("MicroMsg.NetSceneUploadAppAttach", g.Ac() + " summerbig get info failed rowid:" + this.qAh); this.retCode = -10000 - g.getLine(); this.qAe = null; return -1; } else if (this.qAe.field_status != 101) { x.e("MicroMsg.NetSceneUploadAppAttach", g.Ac() + " summerbig get field_status failed rowid:" + this.qAh + " status:" + this.qAe.field_status); return -1; } else { Object obj; if (this.startTime == 0) { this.startTime = bi.VF(); this.qAC = this.qAe.field_offset; } x.i("MicroMsg.NetSceneUploadAppAttach", "summerbig doScene rowid[%d], fileFullPath[%s], totalLen[%d],isUpload[%b], isUseCdn[%b], type[%d]", new Object[]{Long.valueOf(this.qAh), this.qAe.field_fileFullPath, Long.valueOf(this.qAe.field_totalLen), Boolean.valueOf(this.qAe.field_isUpload), Integer.valueOf(this.qAe.field_isUseCdn), Long.valueOf(this.qAe.field_type)}); if (bi.oW(this.qAe.field_appId)) { x.e("MicroMsg.NetSceneUploadAppAttach", "summerbig doScene checkArgs : appId is null"); if (!(this.qAe.field_type == 8 || this.qAe.field_type == 6)) { this.retCode = -10000 - g.getLine(); return -1; } } if (this.qAe.field_type == 8 || this.qAe.field_type == 9) { x.i("MicroMsg.NetSceneUploadAppAttach", "summerbig cdntra cdn not support Emoji or voiceremind now type:%d", new Object[]{Long.valueOf(this.qAe.field_type)}); obj = null; } else { com.tencent.mm.modelcdntran.g.ND(); if (com.tencent.mm.modelcdntran.c.hz(4) || this.qAe.field_isUseCdn == 1) { au.HU(); bd dW = com.tencent.mm.model.c.FT().dW(this.qAe.field_msgInfoId); if (dW.field_msgId != this.qAe.field_msgInfoId) { x.w("MicroMsg.NetSceneUploadAppAttach", "summerbig cdntra read msg info failed msgId[%d], rowid[%d], createtime[%d], len[%d], status[%d], upload[%b], useCdn[%d], mediaId[%s]", new Object[]{Long.valueOf(this.qAe.field_msgInfoId), Long.valueOf(this.qAe.sKx), Long.valueOf(this.qAe.field_createTime), Long.valueOf(this.qAe.field_totalLen), Long.valueOf(this.qAe.field_status), Boolean.valueOf(this.qAe.field_isUpload), Integer.valueOf(this.qAe.field_isUseCdn), this.qAe.field_mediaId}); this.toUser = null; obj = null; } else { this.toUser = dW.field_talker; String str = ""; if (!bi.oW(dW.field_imgPath)) { str = o.Pf().lN(dW.field_imgPath); } int cm = com.tencent.mm.a.e.cm(str); int cm2 = com.tencent.mm.a.e.cm(this.qAe.field_fileFullPath); if (cm >= com.tencent.mm.modelcdntran.b.dOG) { x.w("MicroMsg.NetSceneUploadAppAttach", "summerbig cdntra thumb[%s][%d] Too Big Not Use CDN TRANS", new Object[]{str, Integer.valueOf(cm)}); obj = null; } else { this.dVk = d.a("upattach", this.qAe.field_createTime, dW.field_talker, this.qAh); x.w("MicroMsg.NetSceneUploadAppAttach", "summerbig cdntra genClientId field_createTime[%d], useCdnTransClientId[%s]", new Object[]{Long.valueOf(this.qAe.field_createTime), this.dVk}); if (bi.oW(this.dVk)) { x.w("MicroMsg.NetSceneUploadAppAttach", "summerbig cdntra genClientId failed not use cdn rowid:%d", new Object[]{Long.valueOf(this.qAh)}); obj = null; } else { Object obj2; i iVar = new i(); String str2 = dW.field_content; if (s.fq(dW.field_talker)) { int iA = com.tencent.mm.model.bd.iA(dW.field_content); if (iA != -1) { str2 = (dW.field_content + " ").substring(iA + 2).trim(); } } this.bGT = a.gp(bi.WT(str2)); if (this.bGT != null) { x.d("MicroMsg.NetSceneUploadAppAttach", "summerbig cdntra amc.cdnAttachUrl[%s], amc.aesKey[%s], amc.filemd5[%s], amc.type[%d]", new Object[]{this.bGT.dwD, bi.Xf(this.bGT.dwK), this.bGT.filemd5, Integer.valueOf(this.bGT.type)}); iVar.field_fileId = this.bGT.dwD; iVar.field_aesKey = this.bGT.dwK; iVar.field_filemd5 = this.bGT.filemd5; obj2 = (this.bGT.dws != 0 || this.bGT.dwo > 26214400) ? 1 : null; } else { x.i("MicroMsg.NetSceneUploadAppAttach", "summerbig cdntra parse content xml failed"); obj2 = null; } iVar.dPV = this.dVu; iVar.field_mediaId = this.dVk; iVar.field_fullpath = this.qAe.field_fileFullPath; iVar.field_thumbpath = str; iVar.field_fileType = obj2 != null ? com.tencent.mm.modelcdntran.b.dOm : com.tencent.mm.modelcdntran.b.MediaType_FILE; iVar.field_svr_signature = obj2 != null ? bi.oV(this.qAe.field_signature) : ""; iVar.field_onlycheckexist = obj2 != null ? bi.oW(this.qAe.field_signature) : false; iVar.field_fake_bigfile_signature_aeskey = this.qAe.field_fakeAeskey; iVar.field_fake_bigfile_signature = this.qAe.field_fakeSignature; iVar.field_talker = dW.field_talker; iVar.field_priority = com.tencent.mm.modelcdntran.b.dOk; iVar.field_totalLen = cm2; iVar.field_needStorage = false; iVar.field_isStreamMedia = false; iVar.field_enable_hitcheck = this.dVC; iVar.field_chattype = s.fq(dW.field_talker) ? 1 : 0; iVar.field_force_aeskeycdn = false; iVar.field_trysafecdn = true; x.i("MicroMsg.NetSceneUploadAppAttach", "summerbig cdntra checkUseCdn msgId:%d file[%s][%d] thumb[%s][%d], useCdnTransClientId[%s], fileType[%d], enable_hitcheck[%b], onlycheckexist[%b] force_aeskeycdn[%b] trysafecdn[%b] aeskey[%s], md5[%s], signature[%s], faeskey[%s], fsignature[%s]", new Object[]{Long.valueOf(this.qAe.field_msgInfoId), iVar.field_fullpath, Integer.valueOf(cm2), str, Integer.valueOf(cm), this.dVk, Integer.valueOf(iVar.field_fileType), Boolean.valueOf(iVar.field_enable_hitcheck), Boolean.valueOf(iVar.field_onlycheckexist), Boolean.valueOf(iVar.field_force_aeskeycdn), Boolean.valueOf(iVar.field_trysafecdn), bi.Xf(iVar.field_aesKey), iVar.field_filemd5, bi.Xf(iVar.field_svr_signature), bi.Xf(iVar.field_fake_bigfile_signature_aeskey), bi.Xf(iVar.field_fake_bigfile_signature)}); if (com.tencent.mm.modelcdntran.g.ND().c(iVar)) { if (this.qAe.field_isUseCdn != 1) { this.qAe.field_isUseCdn = 1; boolean c = ao.asF().c(this.qAe, new String[0]); if (!c) { x.e("MicroMsg.NetSceneUploadAppAttach", "summerbig checkUseCdn update info ret:" + c); this.retCode = -10000 - g.getLine(); this.diJ.a(3, -1, "", this); obj = null; } } x.i("MicroMsg.NetSceneUploadAppAttach", "summerbig checkUseCdn ret true useCdnTransClientId[%s]", new Object[]{this.dVk}); obj = 1; } else { x.e("MicroMsg.NetSceneUploadAppAttach", "summerbig cdntra addSendTask failed."); this.dVk = ""; obj = null; } } } } } else { r2 = new Object[2]; com.tencent.mm.modelcdntran.g.ND(); r2[0] = Boolean.valueOf(com.tencent.mm.modelcdntran.c.hz(4)); r2[1] = Integer.valueOf(this.qAe.field_isUseCdn); x.w("MicroMsg.NetSceneUploadAppAttach", "summerbig cdntra not use cdn flag:%b getCdnInfo:%d", r2); obj = null; } } if (obj != null) { x.d("MicroMsg.NetSceneUploadAppAttach", "summerbig doScene cdntra use cdn return -1 for onGYNetEnd client rowid:%d", new Object[]{Long.valueOf(this.qAh)}); return 0; } else if (this.qAe.field_netTimes > 3200) { l.fK(this.qAe.sKx); x.e("MicroMsg.NetSceneUploadAppAttach", g.Ac() + " summerbig doScene info.field_netTimes > DOSCENE_LIMIT SET ERROR! rowid:" + this.qAh); return -1; } else { b bVar = this.qAe; bVar.field_netTimes++; if (bi.oW(this.qAe.field_clientAppDataId)) { x.e("MicroMsg.NetSceneUploadAppAttach", "summerbig doScene checkArgs : clientAppDataId is null"); this.retCode = -10000 - g.getLine(); return -1; } else if (this.qAe.field_totalLen <= 0 || this.qAe.field_totalLen > 26214400) { x.e("MicroMsg.NetSceneUploadAppAttach", "summerbig doScene checkArgs : totalLen is invalid, totalLen = " + this.qAe.field_totalLen); this.retCode = -10000 - g.getLine(); if (this.qAe.field_totalLen > 26214400) { l.fK(this.qAe.sKx); } return -1; } else if (bi.oW(this.qAe.field_fileFullPath)) { x.e("MicroMsg.NetSceneUploadAppAttach", "summerbig doScene checkArgs : fileFullPath is null"); this.retCode = -10000 - g.getLine(); return -1; } else if (com.tencent.mm.a.e.cm(this.qAe.field_fileFullPath) > 26214400) { x.e("MicroMsg.NetSceneUploadAppAttach", "summerbig doScene doScene : file is too large"); l.fK(this.qAe.sKx); return -1; } else { byte[] f; if (bi.oW(this.dwq)) { f = com.tencent.mm.a.e.f(this.qAe.field_fileFullPath, (int) this.qAe.field_offset, 8192); } else { f = com.tencent.mm.a.e.f(this.qAe.field_fileFullPath, (int) this.qAe.field_offset, WXMediaMessage.THUMB_LENGTH_LIMIT); } if (bi.bC(f)) { x.e("MicroMsg.NetSceneUploadAppAttach", "summerbig doScene doScene : data is null"); this.retCode = -10000 - g.getLine(); return -1; } bvm bvm = (bvm) this.diG.dID.dIL; bvm.jQb = this.qAe.field_appId; bvm.rdn = (int) this.qAe.field_sdkVer; bvm.ssa = this.qAe.field_clientAppDataId; bvm.hcE = (int) this.qAe.field_type; bvm.hbL = q.GF(); bvm.rdV = (int) this.qAe.field_totalLen; bvm.rdW = (int) this.qAe.field_offset; if (this.dwq == null || !this.qAB) { bvm.rdX = f.length; bvm.rtW = new bhy().bq(f); if (this.dwq != null) { bvm.rwt = this.dwq; } return a(eVar, this.diG, this); } bvm.rwt = this.dwq; bvm.rdV = (int) this.qAe.field_totalLen; bvm.rdX = 0; bvm.rtW = new bhy().bq(new byte[0]); this.qAB = false; return a(eVar, this.diG, this); } } } } public final void a(int i, int i2, int i3, String str, com.tencent.mm.network.q qVar, byte[] bArr) { x.d("MicroMsg.NetSceneUploadAppAttach", "onGYNetEnd : errType = " + i2 + ", errCode = " + i3); if (i2 == 3 && i3 == -1 && !bi.oW(this.dVk)) { x.w("MicroMsg.NetSceneUploadAppAttach", "cdntra using cdn trans, wait cdn service callback! clientid:%s", new Object[]{this.dVk}); } else if (i2 == 0 && i3 == 0) { bvn bvn = (bvn) ((b) qVar).dIE.dIL; if (bvn.jQb != null && this.dwq == null && (!bvn.jQb.equals(this.qAe.field_appId) || !bvn.ssa.equals(this.qAe.field_clientAppDataId))) { x.e("MicroMsg.NetSceneUploadAppAttach", "argument is not consistent"); this.retCode = -10000 - g.getLine(); this.diJ.a(3, -1, "", this); } else if (bvn.rdV < 0 || ((long) bvn.rdV) != this.qAe.field_totalLen || bvn.rdW < 0 || ((long) bvn.rdW) > this.qAe.field_totalLen) { x.e("MicroMsg.NetSceneUploadAppAttach", "dataLen, startPos or totalLen is incorrect"); this.retCode = -10000 - g.getLine(); this.diJ.a(3, -1, "", this); } else { this.qAe.field_offset = (long) bvn.rdW; this.qAe.field_mediaSvrId = l.SX(bvn.rvP) ? bvn.rvP : ""; if (this.qAe.field_status == 105) { x.w("MicroMsg.NetSceneUploadAppAttach", "onGYNetEnd STATUS PAUSE [" + this.qAe.field_mediaSvrId + "," + this.qAe.field_offset + "] "); this.diJ.a(i2, -1, "", this); return; } if (this.qAe.field_offset == this.qAe.field_totalLen) { if (bi.oW(this.qAe.field_mediaSvrId)) { x.e("MicroMsg.NetSceneUploadAppAttach", "finish upload but mediaid == null!"); this.retCode = -10000 - g.getLine(); this.diJ.a(3, -1, "", this); l.fK(this.qAe.sKx); return; } this.qAe.field_status = 199; h.mEJ.h(10420, new Object[]{Integer.valueOf(0), Integer.valueOf(1), Long.valueOf(this.startTime), Long.valueOf(bi.VF()), Integer.valueOf(d.bL(ad.getContext())), Integer.valueOf(com.tencent.mm.modelcdntran.b.MediaType_FILE), Long.valueOf(this.qAe.field_totalLen - this.qAC)}); } boolean c = ao.asF().c(this.qAe, new String[0]); if (!c) { x.e("MicroMsg.NetSceneUploadAppAttach", "onGYNetEnd update info ret:" + c); this.retCode = -10000 - g.getLine(); d(null); this.diJ.a(3, -1, "", this); } else if (this.qAe.field_status == 199) { this.diJ.a(0, 0, "", this); } else if (a(this.dIX, this.diJ) < 0) { x.e("MicroMsg.NetSceneUploadAppAttach", "onGYNetEnd : doScene fail"); this.diJ.a(3, -1, "", this); } } } else { x.e("MicroMsg.NetSceneUploadAppAttach", "onGYNetEnd : errType = " + i2 + ", errCode = " + i3); this.retCode = -10000 - g.getLine(); if (i2 == 4) { h.mEJ.h(10420, new Object[]{Integer.valueOf(i3), Integer.valueOf(1), Long.valueOf(this.startTime), Long.valueOf(bi.VF()), Integer.valueOf(d.bL(ad.getContext())), Integer.valueOf(com.tencent.mm.modelcdntran.b.MediaType_FILE), Long.valueOf(this.qAe.field_totalLen - this.qAC)}); } this.diJ.a(i2, i3, str, this); } } protected final int Cc() { return 3200; } public final int getType() { return 220; } protected final int a(com.tencent.mm.network.q qVar) { return l.b.dJm; } final void d(keep_SceneResult keep_sceneresult) { if (this.qAe.field_type == 2) { com.tencent.mm.storage.c fJ = com.tencent.mm.model.c.c.Jx().fJ("100131"); if (fJ.isValid()) { this.dlT = ai.getInt((String) fJ.ckq().get("needUploadData"), 1); } if (!this.dlR && this.dlT != 0) { this.dlU = keep_sceneresult; this.dlR = true; ms msVar = new ms(); com.tencent.mm.sdk.b.a.sFg.b(this.dlW); msVar.bXH.filePath = this.qAe.field_fileFullPath; com.tencent.mm.sdk.b.a.sFg.m(msVar); } } } }
/* * The MIT License * * Copyright 2016 Thibault Debatty. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package be.cylab.mark.detection; import be.cylab.mark.DummySubject; import junit.framework.TestCase; import be.cylab.mark.core.DetectionAgentProfile; import be.cylab.mark.core.Event; import be.cylab.mark.core.Evidence; import java.util.Date; import java.util.LinkedList; import static junit.framework.TestCase.assertTrue; /** * Test the Frequency detector. * * To run only this test: * cd server * mvn test -Dtest=be.cylab.mark.detection.FrequencyTest * * @author Thibault Debatty */ public class FrequencyTest extends TestCase { /** * Test of run method, of class Frequency. * @throws java.lang.Throwable */ public void testFrequency1() throws Throwable { System.out.println("Frequency agent with 300 sec interval, " + "0 noise connections"); FrequencyTestClient client = new FrequencyTestClient(0, 300); testWithClient(client); assertEquals(1, client.getEvidences().size()); } public void testFrequency2() throws Throwable { System.out.println("Frequency agent with 300 sec interval, " + "1000 noise connections"); FrequencyTestClient client = new FrequencyTestClient(1000, 300); testWithClient(client); assertEquals(1, client.getEvidences().size()); } public void testFrequency3() throws Throwable { System.out.println("Frequency agent with 300 sec interval, " + "2000 noise connections"); FrequencyTestClient client = new FrequencyTestClient(2000, 300); testWithClient(client); assertEquals(1, client.getEvidences().size()); } public void testFrequency4() throws Throwable { System.out.println("Frequency agent with 1800 sec interval, " + "48 noise connections"); FrequencyTestClient client = new FrequencyTestClient(100, 1800); testWithClient(client); assertEquals(1, client.getEvidences().size()); } public void testFrequencyWithNoApt() throws Throwable { System.out.println("Frequency agent with no APT, " + "1000 noise connections"); FrequencyTestClient client = new FrequencyTestClient(1000, 86400); testWithClient(client); LinkedList<Evidence> evidences = client.getEvidences(); if (evidences.isEmpty()) { return; } assertTrue(evidences.get(0).getScore() < 0.2); } private void testWithClient(FrequencyTestClient client) throws Throwable { Frequency agent = new Frequency(); DetectionAgentProfile profile = DetectionAgentProfile.fromInputStream( getClass().getResourceAsStream("/detection.frequency.yaml")); Date date = new Date(); long now = date.getTime() / 1000; // in seconds Event event = new Event("actual.trigger", new DummySubject("foo"), now, ""); agent.analyze(event, profile, client); } }
package com.classcheck.panel; import java.awt.Cursor; import java.awt.FlowLayout; import java.awt.Font; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.table.DefaultTableModel; import org.apache.lucene.search.spell.LevensteinDistance; import com.change_vision.jude.api.inf.model.IAttribute; import com.change_vision.jude.api.inf.model.IClass; import com.change_vision.jude.api.inf.model.IComment; import com.change_vision.jude.api.inf.model.IConstraint; import com.classcheck.analyzer.source.CodeVisitor; import com.classcheck.autosource.ClassBuilder; import com.classcheck.autosource.Field; import com.classcheck.autosource.MyClass; import com.classcheck.panel.event.ClassLabelMouseAdapter; import com.classcheck.panel.event.ClickedLabel; import com.classcheck.type.ReferenceType; import com.github.javaparser.ast.body.FieldDeclaration; import com.github.javaparser.ast.body.VariableDeclarator; public class FieldComparePanel extends JPanel{ private List<IClass> javaPackage; private ClassBuilder cb; StatusBar fcpSourceStatus; private List<CodeVisitor> codeVisitorList; private HashMap<MyClass, List<JPanel>> mapPanelList; private HashMap<MyClass, CodeVisitor> codeMap; private ArrayList<JComboBox<String>> boxList; private DefaultTableModel tableModel; public FieldComparePanel(ClassBuilder cb, HashMap<MyClass, CodeVisitor> codeMap) { this.cb = cb; mapPanelList = new HashMap<MyClass, List<JPanel>>(); this.codeMap = codeMap; fcpSourceStatus = null; setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS)); setVisible(true); } public FieldComparePanel(List<IClass> javaPackage, ClassBuilder cb, List<CodeVisitor> codeVisitorList, HashMap<MyClass, CodeVisitor> codeMap) { this(cb,codeMap); this.javaPackage = javaPackage; this.codeVisitorList = codeVisitorList; for (MyClass myClass : cb.getClasslist()) { for (CodeVisitor codeVisitor : codeVisitorList) { if(myClass.getName().equals(codeVisitor.getClassName())){ codeMap.put(myClass, codeVisitor); } } mapPanelList.put(myClass, new ArrayList<JPanel>()); } } public List<CodeVisitor> getCodeVisitorList() { return codeVisitorList; } public void setCodeVisitorList(List<CodeVisitor> codeVisitorList) { this.codeVisitorList = codeVisitorList; } public Map<MyClass, CodeVisitor> getCodeMap() { return codeMap; } public Map<MyClass, List<JPanel>> getMapPanelList() { return mapPanelList; } public boolean initComponent(final MyClass myClass,boolean isAllChange){ List<JPanel> panelList = mapPanelList.get(myClass); LevensteinDistance levensteinAlgorithm = new LevensteinDistance(); //tmp double distance = 0; //最も大きかった距離 double maxDistance = 0; //最も距離が近かった文字列 String keyStr=null; List<Field> umlFieldList = myClass.getFields(); List<FieldDeclaration> codeFieldList = null; CodeVisitor codeVisitor = this.codeMap.get(myClass); JComboBox<String> fieldComboBox = null; //同じシグネチャーが選択されているかどうかを調べる this.boxList = new ArrayList<JComboBox<String>>(); boolean isSameFieldSelected = false; //ポップアップテキスト //コメントを取り除く String regex = "(?s)/\\*.*\\*/"; Pattern patern = Pattern.compile(regex); Matcher matcher; if (isAllChange) { panelList.clear(); //説明のパネルを加える //(左)astah :(右) ソースコード JPanel explainPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5)); JLabel explainLabel = new JLabel("(左)クラス図で定義したィールド : (右)ソースコードのフィールド"); explainLabel.setFont(new Font("SansSerif", Font.BOLD, 12)); explainLabel.setAlignmentX(CENTER_ALIGNMENT); explainPanel.add(explainLabel); panelList.add(explainPanel); if (codeVisitor != null){ codeFieldList = codeVisitor.getFieldList(); } for (Field umlField : umlFieldList){ matcher = patern.matcher(umlField.toString()); JLabel l = new JLabel(matcher.replaceAll("").replaceAll(";", "")); JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5)); String popToolTip_str = popToolTips_UML(umlField); l.setAlignmentX(CENTER_ALIGNMENT); l.setToolTipText(popToolTip_str); l.setCursor(new Cursor(Cursor.HAND_CURSOR)); //クラス図を表示 l.addMouseListener(new ClassLabelMouseAdapter(myClass, l, getParent(),ClickedLabel.FieldDefinition)); //ソースコードが定義されていない場合 if (codeVisitor == null) { //空のボックスを作成 fieldComboBox = new JComboBox<String>(); fieldComboBox.setToolTipText("<html>"+ "<p>"+ "対応するフィールドがありません<br>"+ "</p>"+ "</html>"); }else{ ArrayList<String> strList = new ArrayList<String>(); StringBuilder fieldDefinition_sb = new StringBuilder(); StringBuilder fieldError_sb = new StringBuilder(); int itemCount = 0; for (FieldDeclaration codeField : codeFieldList) { //型を比較するメソッドを作る(型はソースコードに依存する、また基本型の場合も考えるようにする) //ソースコードのメソッドの修飾子と //スケルトンコードの修飾子の一致 //スケルトンコードの修飾子には「public 」のようにスペースが入り込むので削除する String umlField_modify_str = umlField.getModifiers(); String codeField_modify_str = Modifier.toString(codeField.getModifiers()); boolean isCorrectModifiy = false; boolean isCorrectType = false; //初期化 fieldDefinition_sb.setLength(0); if (Modifier.toString(codeField.getModifiers()) != null) { fieldDefinition_sb.append(Modifier.toString(codeField.getModifiers())); fieldDefinition_sb.append(" "); } if (codeField.getType() != null) { fieldDefinition_sb.append(codeField.getType()); fieldDefinition_sb.append(" "); } List<VariableDeclarator> varList = codeField.getVariables(); for(int i_varList = 0;i_varList<varList.size();i_varList++){ VariableDeclarator variableDeclarator = varList.get(i_varList); fieldDefinition_sb.append(variableDeclarator.getId().getName()); if (i_varList < varList.size() - 1) { fieldDefinition_sb.append(" "); } } //最後の空白スペースを取り除く if (umlField_modify_str.endsWith(" ")) { umlField_modify_str = umlField_modify_str.substring(0, umlField_modify_str.lastIndexOf(" ")); } isCorrectModifiy = umlField_modify_str.equals(codeField_modify_str); //型一致(型はソースコードに依存する、また基本型の場合も考えるようにする) isCorrectType = new ReferenceType(this.javaPackage,this.tableModel, umlField, fieldDefinition_sb).evaluate(); if (isCorrectModifiy && isCorrectType){ strList.add(fieldDefinition_sb.toString()); itemCount++; }else{ fieldError_sb.append(codeField.toString()+"<br>"); if (isCorrectType == false) { fieldError_sb.append("=>"+"型が合っていません"+"<br>"); } if (isCorrectModifiy == false) { fieldError_sb.append("=>"+"修飾子があっていません"+"<br>"); } } } fieldComboBox = new JComboBox<String>(strList.toArray(new String[strList.size()])); //ボックスに一つも選択するアイテムがない場合はヒントを表示する用意をする if (itemCount == 0) { String tooltipText = ""; tooltipText +="<html>"; tooltipText +="<p>"; tooltipText +=fieldError_sb.toString(); tooltipText +="</p>"; tooltipText +="</html>"; fieldComboBox.setToolTipText(tooltipText); } fieldComboBox.setCursor(new Cursor(Cursor.HAND_CURSOR)); this.boxList.add(fieldComboBox); //レーベンシュタイン距離を初期化 distance = 0; maxDistance = 0; keyStr = null; for (String str : strList){ distance = levensteinAlgorithm.getDistance(umlField.toString(), str); if (maxDistance < distance) { maxDistance = distance; keyStr = str; } } fieldComboBox.setSelectedItem(keyStr); } p.add(l); p.add(fieldComboBox); panelList.add(p); } } //描画 for (JPanel panel : panelList) { add(panel); } //ツリーアイテムを押してもうまく表示されないので //常に早く表示させるよう対策 repaint(); //同じメソッドが選択されているかどうかを調べる JComboBox box_1,box_2; String strBox_1,strBox_2; Object obj; for (int i=0; i < this.boxList.size() ; i++){ box_1 = this.boxList.get(i); obj = box_1.getSelectedItem(); if (obj == null) { continue ; } strBox_1 = obj.toString(); for(int j=0; j < this.boxList.size() ; j++){ box_2 = this.boxList.get(j); obj = box_2.getSelectedItem(); if (obj == null) { continue ; } strBox_2 = obj.toString(); if (i==j) { continue ; } if (strBox_1.equals(strBox_2)) { isSameFieldSelected = true; break; } } if (isSameFieldSelected) { break; } } return isSameFieldSelected; } private String popToolTips_UML(Field umlField){ StringBuilder popSb = new StringBuilder(); //フィールドの説明を加える IComment[] comments; IConstraint[] constraints; IAttribute attr; //ポップアップテキストを加える popSb = new StringBuilder(); popSb.append("<html>"); popSb.append("<p>"); popSb.append("定義:<br>"); attr = umlField.getAttribute(); if (attr.getDefinition().length() == 0) { popSb.append("なし<br>"); }else{ String[] strs = attr.getDefinition().split("\\n", 0); for (String comment : strs) { popSb.append(comment + "<br>"); } } popSb.append("コメント:<br>"); if (attr.getComments().length == 0) { popSb.append("なし<br>"); }else{ comments = attr.getComments(); for (IComment comment : comments){ popSb.append("・"+comment.toString()+"<br>"); } } popSb.append("制約:<br>"); if (attr.getConstraints().length == 0) { popSb.append("なし<br>"); }else{ constraints = attr.getConstraints(); for (IConstraint constraint : constraints){ popSb.append("・"+constraint.toString()+"<br>"); } } popSb.append("</p>"); popSb.append("</html>"); return popSb.toString(); } /** * パネルからもステータスのテキストを変更可能にする * @param text */ public void setStatusText(String text){ fcpSourceStatus.setText(text); } public void setStatus(StatusBar fcpSourceStatus) { this.fcpSourceStatus = fcpSourceStatus; } public void setTableModel(DefaultTableModel tableModel) { this.tableModel = tableModel; } }
package cn.com.ykse.santa.service.vo; /** * Created by youyi on 2016/5/20. */ public class HistoryCodeTagVO { private Integer historyId; private String appName; private String tag; private String publishedCommit; private String operator; private String gmtOperate; public Integer getHistoryId() { return historyId; } public void setHistoryId(Integer historyId) { this.historyId = historyId; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getPublishedCommit() { return publishedCommit; } public void setPublishedCommit(String publishedCommit) { this.publishedCommit = publishedCommit; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public String getGmtOperate() { return gmtOperate; } public void setGmtOperate(String gmtOperate) { this.gmtOperate = gmtOperate; } }
/* Copyright 2019, Senjo Org. Denis Rezvyakov aka Dinya Feony Senjo. * * 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 */ package org.senjo.data; import static org.senjo.basis.Base.Illegal; import static org.senjo.basis.Helper.vandal; import org.senjo.annotation.*; import org.senjo.basis.ABasket; import org.senjo.basis.Text; import org.senjo.basis.Ticker; /** Основное назначение данного механизма — это правильные окончания слов в фразах * с переменными числами (метод {@link #form(int, String)}). * Например: «Приплыл 1 красивый лебедь», «Приплыло 5 красивых лебедей». * <p/> * Я знаю про существование проекта i18n, но мне пока нужно что-то простое, компактное * и без конфигов. * * @author Denis Rezvyakov aka Dinya Feony Senjo * @version create 2019-03-14, beta */ @SuppressWarnings("unchecked") public abstract class APhrase<This extends APhrase, Result> extends ABasket { private final StringBuilder out; private long number; protected abstract Result apply(CharSequence data); protected APhrase(int capacity) { out = new StringBuilder(capacity); } protected APhrase(StringBuilder out) { this.out = out; } public final This add(String text ) { out.append(text ); return (This)this; } public final This add(char ch ) { out.append(ch ); return (This)this; } public final This add(char ch1, char ch2) { out.append(ch1).append(ch2); return (This)this; } public final This add(long value) { out.append(value); return (This)this; } public final This hex(int value) { out.append(Integer.toHexString(value)); return (This)this; } public final This format(String format, Object ... args) { out.append(String.format(format, args)); return (This)this; } public final This div(char ch) { if (!push(Divider)) out.append(ch); return (This)this; } public final This div(char ch1, char ch2) { if (!push(Divider)) out.append(ch1).append(ch2); return (This)this; } public final This rediv() { take(Divider); return (This)this; } public final This hashName(Object target) { Text.hashName(out, target); return (This)this; } public final This put(String text) { if (text != null) out.append(text); return (This)this; } public final This put(char ch) { if (ch != '\0') out.append(ch); return (This)this; } public final This put(char ch1, char ch2) { if (ch1 != '\0') out.append(ch1); if (ch2 != '\0') out.append(ch2); return (This)this; } public final This set(long number) { this.number = number; if (number < 0) number = -number; int mod = (int)(number % 10); turn( mForm, (mod-1 & ~3) != 0 || (number%100 & ~7) == 8 ? FormPlural : mod == 1 ? FormSingle : FormDual ); return (This)this; } public final This number(long number) { set(number); add(number); return (This)this; } public final This number() { add(number); return (This)this; } public final This number(boolean spaces) { if (spaces) out.append(' '); out.append(number); if (spaces) out.append(' '); return (This)this; } private final This _form( @Nullable String single, @Nullable String dual, @Nullable String plural ) { String text; switch (mask(mForm)) { case FormSingle: text = single; break; case FormDual : text = dual ; break; case FormPlural: text = plural; break; default: throw Illegal(this, mForm); } put(text); return (This)this; } public final This form(String single, String plural) { return _form(single, plural, plural); } public final This form( @Nullable String word, @Nullable String single, @Nullable String plural) { put(word); return _form(single, plural, plural); } /** Строит числовую фразу подставляя правильное окончание слов по отношению к числу. * Число предварительно пишется методом {@link #number(long)} или тихо устанавливается * методом {@link #set(long)}. * <p/>Пример фраз: «Созрел 1 подсолнух», «Созрели 4 подсолнуха», «Созрели 300 * подсолнухов». Использование:<br/>{@code #set(21).form("Созрел", * "","и").number(true).form("подсолнух", "","а","ов").end();} * @param single — окончание слова для единственного числа; * @param dual — окончание слова для двойственного числа; * @param plural — окончание слова для множественного числа. */ public final This form( @Nullable String word, @Nullable String single, @Nullable String dual, @Nullable String plural ) { out.append(word); return _form(single, dual, plural); } /** Строит числовую фразу по формату format подставляя правильное окончание слов * по отношению к числу number. * <p/>Пример фраз: «Созрел 1 подсолнух», «Созрели 4 подсолнуха», «Созрели 300 * подсолнухов».<br/> * Использование: {@code #form(count, "Созрел[|и] [@] подсолнух[|а|ов]")} * @param number — число, по отношению к которому нужно поставить окончание; * @param format — формат определяет часть фразы с указанием всех окончаний слов. */ public final This form(long number, @NotNull String format) { int code; { long value = number >= 0 ? number : -number; int mod = (int)(value % 10); code = (mod-1 & ~3) != 0 || (value%100 & ~7) == 8 ? 2 : mod == 1 ? 0 : 1; } char[] data = vandal.disembowel(format); int start = 0, cell = 0, write = 0; boolean opened = false; for (int index = 0, stop = data.length; index != stop; ++index) { char ch = data[index]; if (opened) { switch (ch) { case ']': if (write == 0) { index = start; write = 1; } else opened = false; break; case '@': out.append(number); write = 2; break; case '|': start = index; ++cell; if (write != 0 || cell == code) ++write; break; default: if (write == 1) out.append(ch); } } else if (ch == '[') { opened = true; start = index; cell = 0; write = code == 0 ? 1 : 0; } else out.append(ch); } return (This)this; } /** Добавляет текст в зависимости от значения установленного числа. Если число * в диапазоне от min до max, то подставляет текст под индексом value-min, * иначе подставляет текст с последним индексом. */ public final This choise( @NotNull Choise mode, int min, int max, String ... texts ) { long value = number; if (min <= value&&value <= max) out.append(texts[(int)(value-min)]); else switch (mode) { case Number: number(); break; case Last : put(texts[texts.length-1]); break; default : throw Illegal(mode); } return (This)this; } public final This tick(long nano) { out.append(Ticker.toStringEx(nano)); return (This)this; } public final Result end() { return apply(out); } public final Result end(String text) { return apply(out.append(text)); } public final Result end(char ch) { return apply(out.append(ch)); } public enum Choise { Number, Last } //======== Basket : Постоянные для корзинки фруктов ======================================// protected static final int fin = ABasket.fin-3; private static final int Divider = 1<<fin+1; private static final int mForm = 3<<fin+2; private static final int FormSingle = 1<<fin+2; private static final int FormDual = 2<<fin+2; private static final int FormPlural = 3<<fin+2; }
package com.sysh.entity.helplog; import java.io.Serializable; /** * ClassName: <br/> * Function: 图片 路径存储<br/> * date: 2018年07月07日 <br/> * * @author 苏积钰 * @since JDK 1.8 */ public class HelpImageModel implements Serializable { private String id,imagePath,logId,helpNumber; public HelpImageModel(String id, String imagePath, String logId, String helpNumber) { this.id = id; this.imagePath = imagePath; this.logId = logId; this.helpNumber = helpNumber; } public HelpImageModel() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public String getLogId() { return logId; } public void setLogId(String logId) { this.logId = logId; } public String getHelpNumber() { return helpNumber; } public void setHelpNumber(String helpNumber) { this.helpNumber = helpNumber; } }
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main { public static void main(String[] args) { final JFrame frame = new JFrame("FrameDemo"); frame.setSize(new Dimension(960, 600)); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); final Label emptyLabel = new Label("Simple label"); frame.getContentPane().add(emptyLabel, BorderLayout.NORTH); Button button = new Button("Open dialog"); button.setSize(24, 80); frame.getContentPane().add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { FileDialog fileDialog = new FileDialog(frame); fileDialog.setVisible(true); String fileName = fileDialog.getFile(); if (fileName != null) { emptyLabel.setText(fileDialog.getDirectory() + fileDialog.getFile()); } } }); frame.setVisible(true); } }
package com.jim.multipos.ui.settings.print; import com.jim.multipos.core.BasePresenterImpl; import javax.inject.Inject; public class PrintPresenterImpl extends BasePresenterImpl<PrintView> implements PrintPresenter { @Inject protected PrintPresenterImpl(PrintView printView) { super(printView); } }
package com.ybg.mq.guide; import org.apache.commons.codec.binary.Base64; import com.ybg.mq.util.MD5; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; /** * Created by lindezhi on 2017/5/17. */ public class SignGuide { private static final String NEWLINE="\n"; private static final String ENCODE = "UTF-8"; public static final String HmacSHA1 = "HmacSHA1"; public static String postSign(String sk,String topic,String producerId,String body,String date) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { String signString=topic+NEWLINE+producerId+NEWLINE+ MD5.getInstance().getMD5String(body)+NEWLINE+date; return calSignature(signString.getBytes(Charset.forName(ENCODE)), sk); } public static String getSign(String sk,String topic,String consumerId,String date) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { String signString=topic+NEWLINE+consumerId+NEWLINE+date; return calSignature(signString.getBytes(Charset.forName(ENCODE)), sk); } public static String deleteSign(String sk,String topic,String consumerId,String msgHandle,String date) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { String signString = topic+NEWLINE+consumerId+NEWLINE+msgHandle+NEWLINE+date; return calSignature(signString.getBytes(Charset.forName(ENCODE)), sk); } /** * 签名的计算方式,先使用HmacSHA1编码,再使用base64编码 * java 请使用demo中自带的AuthUtil.calSignature * import com.aliyun.openservices.ons.api.impl.authority.AuthUtil; */ public static String calSignature(byte[] data,String key) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { //采用 HmacSHA1 编码 Mac e = Mac.getInstance(HmacSHA1); //key 转成二进制utf8编码 byte[] keyBytes = key.getBytes(ENCODE); e.init(new SecretKeySpec(keyBytes, HmacSHA1)); //采用 HmacSHA1 计算编码结果 byte[] sha1EncodedBytes = e.doFinal(data); //得到结果后将结果使用base64编码,编码后的结果采用utf8转换为String return new String(Base64.encodeBase64(sha1EncodedBytes), ENCODE); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package customaboutdialog; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.shape.Rectangle; /** * * @author marin */ public class FXML_CustomAboutDialogController implements Initializable { Boolean refContainerSelected = false; Boolean infoContainerSelected = false; @FXML private Label lbl_about, lbl_app_title; @FXML private ImageView btn_exit; @FXML private AnchorPane btn_updates, btn_buy_coffee; @FXML private Label lbl_licence; @FXML private Label lbl_version; @FXML private Label lbl_version_nr; @FXML private Label btn_info; @FXML private Label btn_references; @FXML private void btn_exit_clicked(MouseEvent event) { ((Node)(event.getSource())).getScene().getWindow().hide(); } @FXML private Rectangle decoration_btn_references, decoration_btn_info; @FXML private AnchorPane anc_info_container, anc_references_container; @FXML private void btn_references_entered(MouseEvent event) { decoration_btn_references.setVisible(true); } @FXML private void btn_references_exited(MouseEvent event) { if(refContainerSelected == false) decoration_btn_references.setVisible(false); } @FXML private void btn_references_clicked(MouseEvent event) { anc_references_container.setVisible(true); anc_info_container.setVisible(false); decoration_btn_references.setVisible(true); decoration_btn_info.setVisible(false); refContainerSelected = true; infoContainerSelected = false; } @FXML private void btn_info_entered(MouseEvent event) { decoration_btn_info.setVisible(true); } @FXML private void btn_info_exited(MouseEvent event) { if(infoContainerSelected == false) decoration_btn_info.setVisible(false); } @FXML private void btn_info_clicked(MouseEvent event) { anc_references_container.setVisible(false); anc_info_container.setVisible(true); decoration_btn_references.setVisible(false); decoration_btn_info.setVisible(true); refContainerSelected = false; infoContainerSelected = true; } @FXML private void btn_updates_clicked(MouseEvent event) { } @FXML private void btn_buy_coffee_clicked(MouseEvent event) { } @Override public void initialize(URL url, ResourceBundle rb) { btn_references_clicked(null); } }
package ch.springcloud.lite.core.mail; import org.springframework.beans.factory.annotation.Autowired; import lombok.Data; @Data public class EmailInfo { @Autowired Sender sender; @Autowired Receiver receiver; volatile int cpuratio = 90; volatile int memoryratio = 80; volatile int duration = 5; volatile boolean open; }
package com.WebServiceProduceCrud.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.WebServiceProduceCrud.model.Books; import com.WebServiceProduceCrud.service.BooksService; @RestController public class HomeController { @Autowired BooksService bs; @PostMapping("/books") private String saveBook(@RequestBody Books books) { bs.saveOrUpdate(books); return "Record inserted successfully"; } @GetMapping("/getAllBooks") private List<Books> getBooks() { return bs.getAllBooks(); } @GetMapping("/login/{bookid}/{bookname}") public List<Books> login(@PathVariable("bookid") int bookid, @PathVariable("bookname") String bookname) { return bs.loginCheck(bookid, bookname); } @RequestMapping(value="/edit/{bookid}", method= RequestMethod.PUT) private Books editBooks(@PathVariable("bookid") int bookid) { return bs.editBooksById(bookid); } @GetMapping("/book/{bookid}") private Books getBooks(@PathVariable("bookid") int bookid) { return bs.getBooksById(bookid); } @PutMapping("/books/") private String update(@RequestBody Books books) { bs.saveOrUpdate(books); return "Record updated succesffully"; } @DeleteMapping("/book/{bookid}") private String deleteBook(@PathVariable("bookid") int bookid) { bs.delete(bookid); return "Record deleted successfully"; } }
import java.util.*; public class First_And_Last_Index { public static void main(String args[]){ Scanner scn=new Scanner(System.in); int n=scn.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++){ a[i]=scn.nextInt(); } int k=scn.nextInt(); scn.close(); int f=first_index(a,k); int l=last_index(a,k); System.out.println(f); System.out.println(l); } public static int first_index(int a[],int k){ int lo=0,hi=a.length-1,mid,f=-1; while(lo<=hi){ mid=(lo+hi)/2; if(k==a[mid]){ hi=mid-1; f=mid; } else if(k>a[mid]){ lo=mid+1; } else{ hi=mid-1; } } return f; } public static int last_index(int a[],int k){ int lo=0,hi=a.length-1,mid,l=-1; while(lo<=hi){ mid=(lo+hi)/2; if(k==a[mid]){ lo=mid+1; l=mid; } else if(k>a[mid]){ lo=mid+1; } else{ hi=mid-1; } } return l; } }
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.s; import com.tencent.mm.sdk.platformtools.x; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; public class i { protected int backgroundColor; protected View contentView = null; public Context context; private long grJ = 0; protected int hmV; protected int hmW; protected s nDt; private int nDu = 0; private long nDv = 0; boolean nDw = false; protected ViewGroup nDx; public i(Context context, s sVar, ViewGroup viewGroup) { this.context = context; this.nDt = sVar; this.nDx = viewGroup; int[] ee = ad.ee(context); this.hmV = ee[0]; this.hmW = ee[1]; } public void a(s sVar) { s sVar2 = this.nDt; if (sVar2 != sVar) { if (sVar2 == null || !sVar2.equals(sVar)) { this.nDt = sVar; bzQ(); bzK(); } } } public final void setBackgroundColor(int i) { this.backgroundColor = i; } public final View getView() { if (this.contentView != null) { return this.contentView; } if (this.contentView == null) { int layout = getLayout(); if (layout != Integer.MAX_VALUE) { this.contentView = ((LayoutInflater) this.context.getSystemService("layout_inflater")).inflate(layout, this.nDx, false); } else { this.contentView = bzR(); if (this.contentView != null && this.contentView.getLayoutParams() == null) { this.nDx.addView(this.contentView); LayoutParams layoutParams = this.contentView.getLayoutParams(); this.nDx.removeView(this.contentView); this.contentView.setLayoutParams(layoutParams); } } if (this.contentView == null) { throw new IllegalStateException("implement getLayout() or customLayout() to get a valid root view"); } } bzM(); bzE(); bzQ(); bzK(); return this.contentView; } public final s bzT() { return this.nDt; } public void bzE() { } public View bzM() { return this.contentView; } protected void bzQ() { x.w("MicroMsg.Sns.AdLandingPageBaseComponent", "for component reuse, subclass must implement this method"); } protected int getLayout() { return Integer.MAX_VALUE; } protected View bzR() { return null; } public void bzA() { if (!this.nDw) { this.nDw = true; this.nDv = System.currentTimeMillis(); this.nDu++; } } public void bzB() { if (this.nDw) { this.nDw = false; if (this.nDv > 0) { this.grJ += System.currentTimeMillis() - this.nDv; } this.nDv = 0; } } public void W(int i, int i2, int i3) { } public void bzz() { bzB(); } public final String bzU() { return this.nDt.nAW; } public boolean r(JSONArray jSONArray) { return false; } public boolean aa(JSONObject jSONObject) { if (this.grJ == 0 || this.nDt.nBj) { return false; } try { jSONObject.put("cid", this.nDt.nAW); jSONObject.put("exposureCount", this.nDu); jSONObject.put("stayTime", this.grJ); return true; } catch (Throwable e) { x.printErrStackTrace("MicroMsg.Sns.AdLandingPageBaseComponent", e, "", new Object[0]); return false; } } protected void bzK() { ij(false); } protected final void ij(boolean z) { if (this.contentView == null) { throw new IllegalStateException("set field contentView first"); } else if (this.nDt != null) { LayoutParams layoutParams = this.contentView.getLayoutParams(); if (layoutParams != null) { if (this.nDt.nBc != 2.14748365E9f) { layoutParams.width = (int) this.nDt.nBc; } if (this.nDt.nBd != 2.14748365E9f) { layoutParams.height = (int) this.nDt.nBd; } if (z && (layoutParams instanceof MarginLayoutParams)) { ((MarginLayoutParams) layoutParams).setMargins((int) this.nDt.nBa, (int) this.nDt.nAY, (int) this.nDt.nBb, (int) this.nDt.nAZ); } int gravity; if (layoutParams instanceof LinearLayout.LayoutParams) { LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) layoutParams; gravity = getGravity(); if (gravity != 0) { layoutParams2.gravity = gravity; } else { layoutParams2.gravity = -1; } } else if (layoutParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams layoutParams3 = (FrameLayout.LayoutParams) layoutParams; gravity = getGravity(); if (gravity != 0) { layoutParams3.gravity = gravity; } else { layoutParams3.gravity = -1; } } this.contentView.setLayoutParams(layoutParams); return; } x.i("MicroMsg.Sns.AdLandingPageBaseComponent", this + " has no layoutParams in container " + this.nDx); } } private int getGravity() { int i = 0; switch (this.nDt.nBg) { case 0: i = 48; break; case 1: i = 16; break; case 2: i = 80; break; } switch (this.nDt.nBh) { case 0: return i | 3; case 1: return i | 1; case 2: return i | 5; default: return i; } } public void N(Map<String, Object> map) { } public void bzV() { } }
package com.njc.cartshopping.service; import com.njc.cartshopping.dto.OrderDto; import com.njc.cartshopping.model.Order; import com.njc.cartshopping.repository.OrderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; @Service public class OrderService { private final OrderRepository orderRepository; private final ConversionService conversionService; @Autowired private OrderService(final OrderRepository orderRepository, final ConversionService conversionService) { this.orderRepository = orderRepository; this.conversionService = conversionService; } public OrderDto makeOrder(final OrderDto orderDto) { if (orderDto.getOrderId() > 0){ throw new IllegalStateException("The order Id must be null"); } final Order order = conversionService.convert(orderDto, Order.class); return conversionService.convert(orderRepository.save(order), OrderDto.class); } public List<OrderDto> findOrder(final LocalDateTime date) { return orderRepository.findByCreateDateAfter(date).stream() .map(order -> conversionService.convert(order, OrderDto.class)) .collect(Collectors.toList()); } }
package controller; import java.io.IOException; import java.sql.SQLException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import DAO.Database; import bean.Car; import bean.Customer; import bean.Office; import bean.Reservation; /** * Servlet implementation class checkReservation */ @WebServlet("/checkReservation") public class checkReservation extends HttpServlet { private static final long serialVersionUID = 1L; Database db = new Database(); /** * @see HttpServlet#HttpServlet() */ public checkReservation() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String reference = request.getParameter("reference"); int refInt = Integer.parseInt(reference); Reservation res = null; try { res = db.getReservation(refInt); } catch (SQLException e) { System.out.println("Exception at main get reference"); } int officeId = res.getOfficeId(); Office office = null; try { office = db.getOffice(officeId); } catch (SQLException e) { System.out.println("Exception at get Office"); } Car car = null; try { car = db.getCar(res.getCarId()); } catch (SQLException e) { System.out.println("Exception at get car"); } Customer customer = null; try { customer = db.getCustomer(res.getCustId()); } catch (Exception e) { System.out.println("Exception at get customer"); } request.setAttribute("referenceCar", car); request.setAttribute("referenceOffice", office); request.setAttribute("referenceCustomer", customer); request.setAttribute("reservationRef", res); RequestDispatcher rd = request.getRequestDispatcher("checkReservation.jsp"); rd.forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } String reference = request.getParameter("reference"); String referenceClean = reference.replaceAll("/[^A-Za-z]/g", reference); int refInt = Integer.parseInt(referenceClean); Reservation res = null; try { res = db.getReservation(refInt); } catch (SQLException e) { System.out.println("Exception at main get reference"); } int officeId = res.getOfficeId(); Office office = null; try { office = db.getOffice(officeId); } catch (SQLException e) { System.out.println("Exception at get Office"); } Car car = null; try { car = db.getCar(res.getCarId()); } catch (SQLException e) { System.out.println("Exception at get car"); } Customer customer = null; try { customer = db.getCustomer(res.getCustId()); } catch (Exception e) { System.out.println("Exception at get customer"); } request.setAttribute("referenceCar", car); request.setAttribute("referenceOffice", office); request.setAttribute("referenceCustomer", customer); request.setAttribute("reservationRef", res); RequestDispatcher rd = request.getRequestDispatcher("checkReservation.jsp"); rd.forward(request, response); } }
public class Student extends Person{ protected final String id; public Student(){ //default constructor of super/parent class is automatically called id=""; } public Student(String id, String name){ super(name); //calling constructor of super class - must be first statement this.id = id; } public String getId(){ return this.id; } public String getInfo(){ return this.id + getName();//calling getName from super class. } }
package edu.calstatela.cs245.qiao.project; public class Validity { public static boolean isInt(String s){ try { Integer.valueOf(s); return true; } catch (Exception e) { return false; } } public static boolean isDouble(String s){ try { Double.valueOf(s); return true; } catch (Exception e) { return false; } } }
/* 文件流(节点流) (字节流:FileInputStream / FileOutputStream ——视频,音频,图片 (字符流:FileReader / FileWriter——文本文件.doc+.txt 缓冲流(处理流) (字节缓冲流:BufferedInputStream / BufferedOutputStream (字符缓冲流:BufferedReader / BufferedWriter * */ package IO; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.junit.Test; public class TestInputStream { /* * read()按字节读取文件,如果文件没有返回-1 * * 该输入的文件要求必须存在 * * 从硬盘存在的一个文件中,读取其内容到程序中。使用FileInputStream * 要读取的文件一定要存在。否则抛FileNotFoundException * * 问题:如果有异常抛出,该字节流可能就不关闭了,浪费内存,处理方式testInputStream2() * */ @Test public void testInputStream1() throws Exception { // 1.创建一个File对象,表明要写入的文件位置 File file = new File("hello1.txt"); FileInputStream input = new FileInputStream(file); int b = input.read(); while(b != -1) { System.out.print((char)b); b = input.read(); } input.close(); } /* * 用try-catch的方式处理异常,而不再是抛出异常就结束 * 在finally中关闭输入流,因为关闭流也有可能抛异常,再加一个try-catch * * 缺点:这个是一个一个的字节来读取,占着空间+速度很慢,将按数组的方式读取比较好(水站送水,一次送多桶,节约时间):testInputStream3 * */ @Test public void testInputStream2() { // 1.创建一个File对象,表明要写入的文件位置 FileInputStream input = null; try { File file = new File("hello1.txt"); input = new FileInputStream(file); int b = input.read(); while(b != -1) { System.out.print((char)b); b = input.read(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { input.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* * read(byte[] b)按字节的长度读取文件 * 这种 方式是编程中最可用的类型,前两种读取方式理解既可不需要使用 * * 缺点:也是字节流的缺点:不能分行来读取+不能读汉字 * * 下面写一下字节流的输出流 * */ @Test public void testInputStream3() { FileInputStream fis = null; try { File file = new File("hello1.txt"); fis = new FileInputStream(file); byte[] b = new byte[20]; int len; while((len = fis.read(b)) != -1) { System.out.print(new String(b, 0, len)); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* * FileOutputStream也是按字节写入,写入时用将自己付传用.getBytes()形式将其转换成字节的形式就可以写进去了 * * 这个输出的文件可以 不存在,写的时候自己创建 * * 缺点:再次写入的时候就会覆盖原来的内容 * * 将输入和输入字节流相结合练习:TestInputOutputStream * */ @Test public void testOnputStream3() { FileOutputStream fos = null; try { File file = new File("hello2.txt"); fos = new FileOutputStream(file); fos.write(new String("wertyujhgf").getBytes()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /*将输入和输出流相结合练习*/ @Test public void TestInputOutputStream() { long start = System.currentTimeMillis(); FileInputStream fisI = null; FileOutputStream fosO = null; try { File fileI = new File("1.wmv"); fisI = new FileInputStream(fileI); File fileO = new File("2.wmv"); fosO = new FileOutputStream(fileO); byte[] b = new byte[20]; int len; while((len = fisI.read(b)) != -1) { fosO.write(b, 0, len); // 因为b为字节数组,所以写入的时候必须长度来存,不能用fosO.write(b) } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { System.out.println("fileI的内容复制到fileO中,复制完成!!"); fisI.close(); fosO.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } long end = System.currentTimeMillis(); System.out.println("花费的时间为:" + (end - start)); // 8845 } }
package com.webcloud.func.email.fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSONObject; import com.funlib.http.HttpRequest; import com.funlib.http.request.RequestListener; import com.funlib.http.request.RequestStatus; import com.funlib.http.request.Requester; import com.funlib.json.JsonFriend; import com.webcloud.R; import com.webcloud.define.HttpUrlImpl; import com.webcloud.func.email.EmailDetailActivity; import com.webcloud.func.email.adapter.InboxListAdapter; import com.webcloud.func.email.model.EmailDetailVo; import com.webcloud.func.email.model.EmailVo; /** * 收件箱 * * @author ZhangZheng * @date 2014-01-20 */ public class InboxFragment extends Fragment implements OnClickListener{ // 收件箱列表适配器 private InboxListAdapter adapter; private List<EmailVo> dataList = new ArrayList<EmailVo>(); private EmailVo emailVo; // 底部操作菜单 private LinearLayout bottomMenuLay; private TextView mSelectAll; private TextView mMarkRead; private TextView mDelete; public void setDataList(List<EmailVo> dataList) { this.dataList = dataList; } public InboxFragment() { super(); } public void refreshData(){ Map<String, String> params = new HashMap<String, String>(); params.put("productKey", "meeting"); params.put("ecCode", "340100900686669"); params.put("mailUser", "055162681081@189.cn"); params.put("mailPassword", "62681081"); params.put("currentPage", "1"); params.put("pageSize", "10"); new Requester(getActivity()).request(requestInboxList, HttpUrlImpl.EMAIL.GET_INBOX_EMAIL, HttpUrlImpl.EMAIL.GET_INBOX_EMAIL.getUrl(), params, HttpRequest.GET, false); } RequestListener requestInboxList = new RequestListener(){ @Override public void requestStatusChanged(int statusCode, HttpUrlImpl requestId, String responseString, Map<String, String> requestParams) { if (!(requestId instanceof HttpUrlImpl.EMAIL)) { return; } // 若无需业务处理就直接返回 if (statusCode != RequestStatus.SUCCESS) { return; } try { HttpUrlImpl.EMAIL v1 = (HttpUrlImpl.EMAIL)requestId; switch (v1) { case GET_INBOX_EMAIL:// if (!TextUtils.isEmpty(responseString)) { try { JSONObject jsRoot = JsonFriend.parseJSONObject(responseString); JsonFriend<EmailVo> jsDataList = new JsonFriend<EmailVo>(EmailVo.class); String retCode = jsRoot.getString("retcode"); if ("0".equals(retCode)) { dataList.clear(); List<EmailVo> emailList = jsDataList.parseArray( jsRoot.getJSONObject("retdata").getString("mailList")); dataList.addAll(emailList); adapter.notifyDataSetChanged(); } } catch (Exception e) { e.printStackTrace(); } } break; case GET_EMAIL_DETAIL: if (!TextUtils.isEmpty(responseString)) { try { JSONObject jsRoot = JsonFriend.parseJSONObject(responseString); JsonFriend<EmailDetailVo> jsDataList = new JsonFriend<EmailDetailVo>(EmailDetailVo.class); String retCode = jsRoot.getString("retcode"); if ("0".equals(retCode)) { EmailDetailVo detialvo = jsDataList.parseObject(jsRoot.getString("message")); Intent intent = new Intent(getActivity(), EmailDetailActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("emailDetailVo",detialvo); intent.putExtras(bundle); //进入邮件详情页面 startActivity(intent); } } catch (Exception e) { e.printStackTrace(); } } break; } } catch (Exception e) { e.printStackTrace(); } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.email_inbox_fragment, container, false); ListView lvInbox = (ListView) rootView.findViewById(R.id.lvInbox); lvInbox.setOnItemClickListener(itemListener); adapter = new InboxListAdapter(getActivity(), dataList); lvInbox.setAdapter(adapter); //打开抽屉图片 ImageView ivDrawerImg = (ImageView) rootView.findViewById(R.id.ivInboxDrawerImg); ivDrawerImg.setOnClickListener(this); //编辑邮件(标记为已读,删除) ImageView ivEmailEdit = (ImageView) rootView.findViewById(R.id.ivInboxEmailEdit); ivEmailEdit.setOnClickListener(this); bottomMenuLay = (LinearLayout) rootView.findViewById(R.id.layInboxLayoutBottom); //底部菜单 mSelectAll = (TextView) rootView.findViewById(R.id.tvInboxSelectAll); mMarkRead = (TextView) rootView.findViewById(R.id.tvInboxMarkRead); mDelete = (TextView) rootView.findViewById(R.id.tvInboxDelete); mSelectAll.setOnClickListener(this); mMarkRead.setOnClickListener(this); mDelete.setOnClickListener(this); refreshData(); return rootView; } // 邮件点击事件 OnItemClickListener itemListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { emailVo = dataList.get(position); int emailId=emailVo.getId(); getEmailDetailById(emailId); } }; private void getEmailDetailById(int emailId){ Map<String, String> params = new HashMap<String, String>(); params.put("productKey", "meeting"); params.put("ecCode", "340100900686669"); params.put("messageNumber", emailId+""); params.put("filedownUrl", ""); params.put("previewUrl", ""); new Requester(getActivity()).request(requestInboxList, HttpUrlImpl.EMAIL.GET_EMAIL_DETAIL, HttpUrlImpl.EMAIL.GET_EMAIL_DETAIL.getUrl(), params, HttpRequest.GET, false); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ivInboxEmailEdit: //显示复选框 adapter.setCheckboxFlag(1); adapter.notifyDataSetChanged(); //弹出底部菜单 bottomMenuLay.setVisibility(View.VISIBLE); break; case R.id.ivInboxDrawerImg: listenter.operateDrawer(true); break; case R.id.tvInboxSelectAll: // 全选 Toast.makeText(getActivity(), "全选", Toast.LENGTH_LONG).show(); break; case R.id.tvInboxMarkRead: // 标记为已读 Toast.makeText(getActivity(), "标记为已读", Toast.LENGTH_LONG).show(); break; case R.id.tvInboxDelete: // 删除 Toast.makeText(getActivity(), "删除", Toast.LENGTH_LONG).show(); break; default: break; } } /** * 隐藏底部编辑菜单 * @return */ public boolean hiddenEdit(){ if(bottomMenuLay.getVisibility() == View.VISIBLE){ //重新适配数据并隐藏底部菜单 adapter.setCheckboxFlag(0); adapter.notifyDataSetChanged(); bottomMenuLay.setVisibility(View.GONE); return true; } return false; } private onInboxLoadedListener listenter; public interface onInboxLoadedListener{ public void onInboxLoaded(); public void operateDrawer(boolean open); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { listenter = (onInboxLoadedListener)activity; } catch (Exception e) { throw new RuntimeException(activity.toString() + "must implements onInboxLoadedListener"); } } @Override public void onDetach() { super.onDetach(); } }
package com.tencent.mm.plugin.appbrand.launching; import com.tencent.mm.plugin.appbrand.appcache.WxaPkgWrappingInfo; import com.tencent.mm.plugin.appbrand.launching.y.a; import com.tencent.mm.plugin.appbrand.q.h; import java.util.Locale; import java.util.concurrent.CountDownLatch; class y$a$1 extends n { final /* synthetic */ CountDownLatch dKv; final /* synthetic */ h fxa; final /* synthetic */ a ggt; y$a$1(a aVar, int i, h hVar, CountDownLatch countDownLatch) { this.ggt = aVar; this.fxa = hVar; this.dKv = countDownLatch; super(i); } final String akG() { return String.format(Locale.US, "Incremental %d|%d", new Object[]{Integer.valueOf(a.a(this.ggt)), Integer.valueOf(a.b(this.ggt))}); } final void c(WxaPkgWrappingInfo wxaPkgWrappingInfo) { this.fxa.value = wxaPkgWrappingInfo; this.dKv.countDown(); } }
package ModeType.Impl; import ModeType.PayType; /** * @Author: lty * @Date: 2020/11/20 14:11 */ public class CnPayTypeImpl implements PayType { public String toPay() { System.out.println("使用场内支付.."); return "使用场内支付成功"; } }
package algorithm.programmers.hash; import java.util.Arrays; public class programmers_courses30_lessons42577 { public static void main(String[] args) { String[] phone_book = { "119", "1219", "97674223", "13195524421", "9767" }; System.out.println(solution(phone_book)); } public static boolean solution(String[] phone_book) { boolean answer = true; Arrays.sort(phone_book); for (String num : phone_book) { System.out.println(num); } String compareNum = phone_book[0]; for (int i = 1; i < phone_book.length; i++) { if (compareNum.length() > phone_book[i].length()) continue; if (compareNum.equals(phone_book[i].substring(0, compareNum.length()))) { return false; } else { compareNum = phone_book[i]; } } return true; } }
package com.store.util; import java.util.UUID; public class MyUUID { public static String getId() { return UUID.randomUUID().toString().replace("-", ""); } }
package id.ac.ub.ptiik.papps.base; public class MessageSent extends Message { public MessageSent( int id, int type, String message, String sent, String received, String sender, String receiver, int status) { this.id = id; this.message = message; this.type = Message.TYPE_SENT; this.sent = sent; this.received = received; this.sender = sender; this.receiver = receiver; this.readStatus = status; } public MessageSent(String message, String sent, String sender, String receiver) { this.message = message; this.type = Message.TYPE_SENT; this.sent = sent; this.received = ""; this.sender = sender; this.receiver = receiver; this.readStatus = MessageSent.STATUS_READ; } public void setRead() { this.readStatus = STATUS_READ; } }
package niuke; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Created by likz on 2023/7/7 * * @author likz */ public class StringSimplify { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); UnionFind unionFindSet = new UnionFind(255); String inputString = br.readLine(); boolean enterBracket = false; char[] str = inputString.toCharArray(); StringBuilder targetStr = new StringBuilder(); List<Character> sameSetStr = new ArrayList<>(); List<List<Character>> list = new ArrayList<>(); // 输入数据转换处理 for (char ch : str) { if (enterBracket) { if (ch == ')') { enterBracket = false; // 若括号内有数据 if (!sameSetStr.isEmpty()) { List<Character> element = new ArrayList<>(sameSetStr); list.add(element); sameSetStr.clear(); } } else { sameSetStr.add(ch); } } else { if (ch == '(') { enterBracket = true; } else { targetStr.append(ch); } } } // 若并查集为空 if (list.isEmpty()) { out.println(targetStr); out.flush(); return; } // 构建并查集 for (List<Character> characterList : list) { if (characterList.size() > 1) { for (int i = 1; i < characterList.size(); i++){ unionFindSet.union(characterList.get(0), characterList.get(i)); } } } // 输出 if (targetStr.length() > 0) { char[] chs = targetStr.toString().toCharArray(); for (char ch : chs) { out.print((char) (unionFindSet.unionFind(ch))); } out.println(); out.flush(); } else { out.println("0"); out.flush(); } } public static class UnionFind { private int[] parent; private int[] help; public UnionFind(int n) { parent = new int[n]; help = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } } public int unionFind(int i) { int size = 0; while (parent[i] != i) { help[size++] = i; i = parent[i]; } while (size > 0) { parent[help[--size]] = i; } return i; } public void union(int x, int y) { int fx = unionFind(x); int fy = unionFind(y); if (fx != fy) { if (fx < fy) { parent[fy] = fx; } else { parent[fx] = fy; } } } } /* 示例一: 输入:()abd 输出:abd 说明:输入字符串里没有被小括号包含的子字符串为"abd",其中每个字符没有等效字符,输出为"abd" 示例二: 输入:(abd)demand(fb)()for 输出:aemanaaor 说明:等效字符集为('a','b','d','f'),输入字符串里没有被小括号包含的子字符串集合为"demandfor",将其中字符替换为字典序最小的等效字符后输出为:"aemanaaor 示例3 输入: ()happy(xyz)new(wxy)year(t) 输出: happwnewwear 说明: 等效字符集为('x','y','z','w'),输入字符串里没有被小括号包含的子字符串集合为"happynewyear”,将其中字符替换为字典序最小的等效字符后输出 为:"happwnewwear 示例四: 输入:()abcdefgAC(a)(Ab)(C) 输出:AAcdefgAC 说明:等效字符集为('a','A','b'),输入字符串里没有被小括号包含的子字符串集合为“abcdefgAC,将其中字符替换为字典序最小的等效字符后输出为:"AAcdefgAC" * */ }
/* * Copyright 2009 Kjetil Valstadsve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package vanadis.remoting; import vanadis.core.lang.EqHc; import vanadis.core.lang.Not; import vanadis.core.lang.ToString; import vanadis.services.remoting.RemotingException; import vanadis.services.remoting.TargetHandle; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.UndeclaredThrowableException; public abstract class AbstractHandler extends AbstractSessionable implements InvocationHandler { private final TargetHandle<?> handle; protected AbstractHandler(TargetHandle<?> handle) { this(null, handle); } protected AbstractHandler(Session session, TargetHandle<?> handle) { super(session); this.handle = Not.nil(handle, "handle"); } @Override public final Object invoke(Object o, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass().equals(Object.class)) { return method.invoke(this, args); } MethodCall methodCall = new MethodCall(getSession(), getHandle().getReference(), method, args); MethodCallResult result = invoke(methodCall); adoptOrVerifySession(result); return result.isReturnedNormally() ? result.getValue() : handleAbnormalReturn(methodCall, result); } private static Object handleAbnormalReturn(MethodCall call, MethodCallResult result) throws Throwable { if (!result.isTargetFound()) { throw new RemotingException(call + " failed, did not hit a target!"); } Method method = call.getMethod(); Throwable exception = result.getException(); if (exception instanceof RuntimeException || exception instanceof Error) { throw exception; } for (Class<?> allowedClass : method.getExceptionTypes()) { Class<? extends Throwable> exceptionClass = exception.getClass(); if (allowedClass.isAssignableFrom(exceptionClass)) { throw exception; } } throw new UndeclaredThrowableException(exception, method + " threw invalid exception"); } @Override public final int hashCode() { return EqHc.hc(getHandle()); } @Override public final boolean equals(Object object) { if (object == this) { return true; } else if (object == null) { return false; } else { AbstractHandler handle = EqHc.retyped(this, object); return handle != null && EqHc.eq(handle.getHandle(), handle); } } @Override public final String toString() { return ToString.of(this, getHandle()); } protected abstract MethodCallResult invoke(MethodCall methodCall); public TargetHandle<?> getHandle() { return handle; } }
package com.library.parser; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.library.domain.Author; import com.library.domain.Book; import com.library.domain.Category; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.function.Function; public class BookJsonDeserializer extends JsonDeserializer<Book> { @Override public Book deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { Book book = new Book(); JsonNode node = p.getCodec().readTree(p); JsonNode volumeInfo = node.get("volumeInfo"); // ISBN HashMap<String, String> typeIdMap = new HashMap<>(); if (volumeInfo.has("industryIdentifiers")) { JsonNode industryIdentifiers = volumeInfo.get("industryIdentifiers"); if (industryIdentifiers.isArray()) { for (final JsonNode jsonNode : industryIdentifiers) { String type = jsonNode.get("type").asText(); String value = jsonNode.get("identifier").asText(); typeIdMap.put(type, value); } } } if (typeIdMap.containsKey("ISBN_13")) { book.setIsbn(typeIdMap.get("ISBN_13")); } else { String id = node.get("id").asText(); book.setIsbn(id); } //TITLE deserializeAsSimpleField(volumeInfo, "title", JsonNode::asText).ifPresent(book::setTitle); //SUBTITLE deserializeAsSimpleField(volumeInfo, "subtitle", JsonNode::asText).ifPresent(book::setSubtitle); //PUBLISHER deserializeAsSimpleField(volumeInfo, "publisher", JsonNode::asText).ifPresent(book::setPublisher); //PUBLISHED DATE if (volumeInfo.has("publishedDate")) { String publishedDate = volumeInfo.get("publishedDate").textValue(); List<SimpleDateFormat> knownPatterns = Arrays.asList( new SimpleDateFormat("yyyy"), new SimpleDateFormat("yyyy-MM-dd") ); for (SimpleDateFormat pattern : knownPatterns) { try { Date date = pattern.parse(publishedDate); long unixTime = date.getTime(); book.setPublishedDate(unixTime); } catch (ParseException ignored) { } } } //DESCRIPTION deserializeAsSimpleField(volumeInfo, "description", JsonNode::asText).ifPresent(book::setDescription); //PAGE COUNT deserializeAsSimpleField(volumeInfo, "pageCount", JsonNode::asInt).ifPresent(book::setPageCount); //THUMBNAIL deserializeAsSimpleField(volumeInfo.get("imageLinks"), "thumbnail", JsonNode::asText).ifPresent(book::setThumbnailUrl); //LANGUAGE deserializeAsSimpleField(volumeInfo, "language", JsonNode::asText).ifPresent(book::setLanguage); //PREVIEW LINK deserializeAsSimpleField(volumeInfo, "previewLink", JsonNode::asText).ifPresent(book::setPreviewLink); //AVERAGE RATING deserializeAsSimpleField(volumeInfo, "averageRating", JsonNode::asDouble).ifPresent(book::setAverageRating); // AUTHORS if (volumeInfo.has("authors")) { JsonNode authors = volumeInfo.get("authors"); List<Author> authorsList = new ArrayList<>(); if (authors.isArray()) { for (final JsonNode jsonNode : authors) { authorsList.add(new Author(jsonNode.textValue())); } } book.setAuthors(authorsList); } //CATEGORIES if (volumeInfo.has("categories")) { JsonNode categories = volumeInfo.get("categories"); List<Category> categoryList = new ArrayList<>(); if (categories.isArray()) { for (final JsonNode jsonNode : categories) { categoryList.add(new Category(jsonNode.textValue())); } } book.setCategories(categoryList); } return book; } private <T> Optional<T> deserializeAsSimpleField(JsonNode node, String property, Function<JsonNode, T> mapper) { if (node.has(property)) { return Optional.of(mapper.apply(node.get(property))); } else { return Optional.empty(); } } }
class GreetingsA { public static void main(String[] args) { System.out.println("Szia! Hogy hivnak?"); //hosszu ekezet kerulese winfoson String name = System.console().readLine(); //console metodus, programfutas megall es beker egy sort //nev eltarolasa valtozoban System.out.println("Udv " + name + ", mi ujsag?"); } }
package com.nogago.android.maps.download; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import com.nogago.android.maps.Constants; import com.nogago.android.maps.R; import com.nogago.android.maps.download.task.readareas.Area; import com.nogago.android.maps.download.task.readareas.ReadAreasTask; import com.nogago.android.maps.plus.OsmandApplication; import com.nogago.android.maps.plus.OsmandSettings; import com.nogago.android.maps.plus.ResourceManager; import android.content.Context; import android.os.Environment; import android.preference.PreferenceActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.TextView; /** Populates the items for displaying in UI */ public class MapFileListAdapter extends BaseAdapter implements ListAdapter{ private final Context context; List<MapFile> mapFiles; public MapFileListAdapter(Context context) { this.context = context; readMapsFromDisk(); } private void readMapsFromDisk() { File dir = new File(OsmandApplication.getSettings().extendOsmandPath(ResourceManager.APP_DIR).toString()); File[] filelist = dir.listFiles(); mapFiles = new ArrayList<MapFile>(); for (int i = 0; i < filelist.length; i++) { if(filelist[i].getName().endsWith(Constants.MAP_FILE_EXTENSION)) { //Delete bad obf file if(filelist[i].length() < Constants.BAD_OBF_FILE_THRESHOLD) FileUtils.deleteQuietly(filelist[i]); else { try{ mapFiles.add(new MapFile(filelist[i])); }catch(Exception e){ //Other osmand files, ignore! } } } } } public void setMapFiles(List<MapFile> mapFiles) { this.mapFiles = mapFiles; } @Override public int getCount() { readMapsFromDisk(); if(mapFiles == null) return 0; return mapFiles.size(); } @Override public MapFile getItem(int pos) { if(mapFiles == null) return null; return mapFiles.get(pos); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // if the view has not been created yet ... if (convertView == null) { // inflate the layout LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.find_entry, parent, false); } TextView entryView = (TextView) convertView.findViewById(R.id.findcity_entry_title); // get entry title MapFile item = (MapFile) getItem(position); // set the entry title entryView.setText(getItemDisplayName(item)); return convertView; } public String getItemDisplayName(MapFile item){ String title = item.getName(); // if(item.part.compareTo("c")==0) title += " (" + context.getString(R.string.c) + ")"; if(item.part.compareTo("nw")==0) title += " (" + context.getString(R.string.nw) + ")"; if(item.part.compareTo("ne")==0) title += " (" + context.getString(R.string.ne) + ")"; if(item.part.compareTo("sw")==0) title += " (" + context.getString(R.string.sw) + ")"; if(item.part.compareTo("se")==0) title += " (" + context.getString(R.string.se) + ")"; if(item.part.compareTo("s")==0) title += " (" + context.getString(R.string.s) + ")"; if(item.part.compareTo("n")==0) title += " (" + context.getString(R.string.n) + ")"; if(item.part.compareTo("w")==0) title += " (" + context.getString(R.string.w) + ")"; if(item.part.compareTo("e")==0) title += " (" + context.getString(R.string.e) + ")"; if(item.part2.compareTo("poly")==0) title += " (" + context.getString(R.string.contour) + ")"; // if(item.part2.contains("c")) title += " (" + context.getString(R.string.contour) + ")"; return title; } public List<MapFile> getMapFiles(){ return this.mapFiles; } public Area getCityCenterArea(String cityName){ for(MapFile mapFile: mapFiles){ if(mapFile.fullName.startsWith(cityName + "-c")) return ReadAreasTask.getAreaById(mapFile.getMapId()); } return null; } public MapFile getMapFileById(int mapId){ for(MapFile mapFile: mapFiles){ if(mapFile.getMapId() == mapId){ return mapFile; } } return null; } }
package com.research.cep; import com.google.common.base.Charsets; import com.google.gson.Gson; import org.apache.commons.lang3.StringUtils; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.cep.CEP; import org.apache.flink.cep.PatternStream; import org.apache.flink.cep.functions.PatternProcessFunction; import org.apache.flink.cep.pattern.Pattern; import org.apache.flink.cep.pattern.conditions.SimpleCondition; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.datastream.DataStreamSource; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer; import org.apache.flink.streaming.connectors.kafka.KafkaDeserializationSchema; import org.apache.flink.util.Collector; import org.apache.kafka.clients.consumer.ConsumerRecord; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.stream.Collectors; /** * @fileName: CepDemo.java * @description: CepDemo.java类说明 * @author: by echo huang * @date: 2020-04-03 10:46 */ public class CepDemo { public static void main(String[] args) throws Exception { StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment(); Properties props = new Properties(); props.setProperty("bootstrap.servers", "localhost:9092"); props.setProperty("group.id", "cep"); environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); DataStreamSource<Event> dataStreamSource = environment.addSource(new FlinkKafkaConsumer<>("cep_topic", new KafkaDeserializationSchema<Event>() { @Override public boolean isEndOfStream(Event nextElement) { return Objects.isNull(nextElement); } @Override public Event deserialize(ConsumerRecord<byte[], byte[]> record) throws Exception { Gson gson = new Gson(); String message = new String(record.value(), Charsets.UTF_8); return gson.fromJson(message, Event.class); } @Override public TypeInformation<Event> getProducedType() { return TypeInformation.of(Event.class); } }, props)); dataStreamSource.assignTimestampsAndWatermarks(new Watermarks()); // OutputTag<String> outputTag = new OutputTag<>("timeout"); //定义cep模式 Pattern<Event, Event> pattern = Pattern.<Event>begin("start").where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return StringUtils.equals(value.getState(), "start"); } }).next("sign") .where(new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return value.getSign() == 10; } }).followedBy("end") .where( new SimpleCondition<Event>() { @Override public boolean filter(Event value) throws Exception { return StringUtils.equals(value.getName(), "end"); } } ).within(Time.seconds(10)); PatternStream<Event> patternStream = CEP.pattern(dataStreamSource, pattern); SingleOutputStreamOperator<String> mainStream = patternStream.process(new PatternProcessFunction<Event, String>() { @Override public void processMatch(Map<String, List<Event>> map, Context context, Collector<String> collector) throws Exception { collector.collect(map.values().stream() .flatMap(events -> events.stream().map(Event::toString)).collect(Collectors.joining(","))); } }); mainStream.print(); //超时处理 /* DataStream<String> timeOutStream = patternStream.flatSelect(outputTag, new PatternFlatTimeoutFunction<Event, String>() { //超时数据处理 @Override public void timeout(Map<String, List<Event>> map, long l, Collector<String> collector) throws Exception { String message = map.values().stream() .flatMap(events -> events.stream() .map(Event::toString)) .findFirst().orElse(""); collector.collect(message); } }, new PatternFlatSelectFunction<Event, String>() { //正常数据出炉 @Override public void flatSelect(Map<String, List<Event>> map, Collector<String> collector) throws Exception { String message = map.values().stream() .flatMap(events -> events.stream() .map(Event::toString)) .findFirst().orElse(""); collector.collect(message); } }).getSideOutput(outputTag);*/ // timeOutStream.print(); environment.execute(); } }
package com.packers.movers.commons.utils; public enum DateTimeFormat { DATE("yyyy-MM-dd"), DATE_TIME("yyyy-MM-dd'T'HH:mm:ss"); String value; DateTimeFormat(String value) { this.value = value; } public String getValue() { return value; } }
package com.dao; import com.entidades.Cliente; import java.util.List; import javax.ejb.Local; /** * * @author mertins */ @Local public interface ClienteDAOLocal { Cliente create(Cliente value); Cliente retrieve(Cliente value); void update(Cliente value); void delete(Cliente value); List<Cliente> listaTodos(); boolean valida(Cliente value); }
public class Infiltrator { int len; int wid; int x=0; int y=0; Border border; Infiltrator(int l, int w, double p) { len = l; wid = w; border = new Border(l, w, p); } public void move() { if(!border.stateOfCell(x, y+1)) { y++; } else if(x<len && !border.stateOfCell(x+1, y+1)) { x++; y++; } else if(x>0 && !border.stateOfCell(x-1, y+1)) { x--; y++; } } public int getX() { return x; } public int getY() { return y; } public boolean enteredDC(int y) { if(y>wid) return true; return false; } }
package com.qgil.pojo; import java.util.Date; public class QgilProenum { private Long id; private String proenumname; private Date create_time; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getProenumname() { return proenumname; } public void setProenumname(String proenumname) { this.proenumname = proenumname; } public Date getCreate_time() { return create_time; } public void setCreate_time(Date create_time) { this.create_time = create_time; } }
package Main; import javafx.scene.canvas.Canvas; public class ZoomCanvas extends Canvas { }
package Homework5; import java.util.Scanner; public class ReverseArrayList { public static void main(String[] args) { // TODO Auto-generated method stub //declare an array of 10 integers int[] array=new int[10]; //Invoke reverse method which returns the original list in reversed order array=reverse(array); //print the reversed list System.out.println("\nReversed Array is :"); for(int i=0;i<10;i++){ System.out.print(array[i]+" "); } } //Method to reverse the elements of the array public static int[] reverse(int[] list){ int i,j=0; int temp=0; //Create Scanner Scanner input=new Scanner(System.in); //Initialize array elements for(int p=0;p<10;p++){ list[p]=0; } //Prompts user to enter 10 integers System.out.println("Please enter 10 integers"); for(i=0;i<10;i++){ list[i]=input.nextInt(); } //print original array of 10 integers entered bu user System.out.println("Original Array is :"); for(i=0;i<10;i++){ System.out.print(list[i]+" "); } //Logic to reverse the elements of the array j=list.length-1; i=0; while(i<j){ temp=list[i]; list[i]=list[j]; list[j]=temp; i++; j--; } //Return the reversed array return list; } }
package se.kth.iv1350.pointofsale.controller; /** * Thrown when an operation fails. */ public class OperationFailedException extends Exception { /** * Creates an instance with the specified message and cause of failure * @param msg The message * @param cause The exception that caused this exception. */ public OperationFailedException(String msg, Exception cause) { super(msg,cause); } }
package CashMachine; import java.util.Scanner; public class CashMachine { static int pin = 1234; static float balance = 1000; public static void announce(Scanner scan) { System.out.println(String.format("You have £%s in your account.",balance)); if (balance == 0) { System.out.println("You're bankrupt!"); } else { System.out.println("Please enter an amount to withdraw:"); float withdrawal = scan.nextFloat(); withdraw(withdrawal, scan); } } public static void withdraw(float withdrawal, Scanner scan) { if (withdrawal>balance) { System.out.println(String.format("Insufficient funds! You cannot withdraw £%s when you have only £%s.",withdrawal,balance)); } else { balance -= withdrawal; System.out.println(String.format("You have withdrawn £%s.",withdrawal)); } announce(scan); } public static void pinPrompt(Scanner scan) { System.out.println("Please type your PIN!"); int enteredPin = scan.nextInt(); pinCheck(enteredPin,scan); } public static void pinCheck(int enteredPin, Scanner scan) { if(enteredPin==pin) { System.out.println("Correct PIN!"); announce(scan); } else { System.out.println("Wrong PIN!"); pinPrompt(scan); } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Welcome to the cash machine!"); pinPrompt(scan); } }
import javax.swing.JOptionPane; import org.jointheleague.graphical.robot.Robot; public class ObedientRobot { Robot obey = new Robot(); public static void main(String[] args) { ObedientRobot rob = new ObedientRobot(); rob.basics(); String shape = JOptionPane.showInputDialog("Do you want to draw a square, triangle, or circle?"); String color = JOptionPane.showInputDialog("What color do you want it to be: red, blue, green, or random?"); if(color.equalsIgnoreCase("red")) { rob.colorRed(); } else if(color.equalsIgnoreCase("green")) { rob.colorGreen(); } else if(color.equalsIgnoreCase("Blue")) { rob.colorBlue(); } else { rob.colorRandom(); } if(shape.equalsIgnoreCase("square")){ rob.drawSquare(); } else if(shape.equalsIgnoreCase("Triangle")) { rob.drawTriangle(); } else if(shape.equalsIgnoreCase("Circle")) { rob.drawCircle(); } else { JOptionPane.showMessageDialog(null, "I don't know that shape!"); } } void colorRed() { obey.setPenColor(255, 0, 0); } void colorBlue() { obey.setPenColor(0,0, 255); } void colorGreen() { obey.setPenColor(0,255,0); } void colorRandom() { obey.setRandomPenColor(); } void basics() { obey.penDown(); obey.setSpeed(50); } void drawTriangle() { obey.setAngle(270); for (int i = 0; i < 3; i++) { obey.move(100); obey.turn(120);} obey.hide(); } void drawSquare() { for (int i = 0; i < 4; i++) { obey.move(100); obey.turn(90);} obey.hide(); } void drawCircle() { obey.setSpeed(100); for (int i = 0; i < 360; i++) { obey.move(2); obey.turn(1); } obey.hide(); } }
package com.bl.algorithm.PrimeNumbersInGivenRange; import java.util.*; import java.io.*; public class PrimeNumbersInGivenRangeMain { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int def = 0; System.out.println("Enter the start of range "); int m = sc.nextInt(); System.out.println("Enter the end of range "); int n = sc.nextInt(); PrimeNumbersInGivenRangeBL Prime = new PrimeNumbersInGivenRangeBL(); Prime.primenumbers(m,n); } }
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program 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. // // This program 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 this program. If not, see http://www.gnu.org/licenses/. // package com.wire.bots.sdk.assets; import com.waz.model.Messages; import java.util.UUID; public class MessageText implements IGeneric { private final Messages.Text.Builder builder = Messages.Text.newBuilder(); private UUID messageId = UUID.randomUUID(); public MessageText(String text) { builder.setExpectsReadConfirmation(true); setText(text); } public MessageText setMessageId(UUID messageId) { this.messageId = messageId; return this; } public MessageText setText(String text) { builder.setContent(text); return this; } public MessageText addMention(UUID mentionUser, int offset, int len) { Messages.Mention.Builder mention = Messages.Mention.newBuilder() .setUserId(mentionUser.toString()) .setLength(len) .setStart(offset); builder.addMentions(mention); return this; } @Override public Messages.GenericMessage createGenericMsg() { return Messages.GenericMessage.newBuilder() .setMessageId(getMessageId().toString()) .setText(builder) .build(); } @Override public UUID getMessageId() { return messageId; } public Messages.Text.Builder getBuilder() { return builder; } }
package org.yuan.vita.demo; public class Hello { public void println() { System.out.println("Hello!"); } }
package com.rex.demo.study.demo.driver.stream.join; import com.rex.demo.study.demo.util.CommonUtils; import com.rex.demo.study.demo.util.FlinkUtils2; import org.apache.flink.api.common.functions.JoinFunction; import org.apache.flink.api.common.serialization.SimpleStringSchema; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple5; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor; import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows; import org.apache.flink.streaming.api.windowing.time.Time; /** * TODO InnerJoin 实例 * * @author liuzebiao * @Date 2020-2-21 16:11 */ public class InnerJoinDemo { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = FlinkUtils2.getEnv(); //设置使用 EventTime 作为时间标准 env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); //设置并行度为1,此处仅用作测试使用。因为 Kafka 为并行数据流,数据只有全部填满分区才会触发窗口操作。 env.setParallelism(1); ParameterTool parameters1 = ParameterTool.fromPropertiesFile(CommonUtils.getResourcePath("config.properties")); ParameterTool parameters2 = ParameterTool.fromPropertiesFile(CommonUtils.getResourcePath("config2.properties")); DataStream<String> leftSource = FlinkUtils2.createKafkaStream(parameters1, SimpleStringSchema.class); DataStream<String> rightSource = FlinkUtils2.createKafkaStream(parameters2, SimpleStringSchema.class); //左流,设置水位线 WaterMark SingleOutputStreamOperator<String> leftStream = leftSource.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<String>(Time.milliseconds(0)) { @Override public long extractTimestamp(String s) { String[] split = s.split(","); return Long.parseLong(split[2]); } }); SingleOutputStreamOperator<String> rightStream = rightSource.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<String>(Time.milliseconds(0)) { @Override public long extractTimestamp(String s) { String[] split = s.split(","); return Long.parseLong(split[2]); } }); //实现 Join 操作(where、equalTo、apply 中实现部分,都可以写成单独一个类) DataStream<Tuple5<String, String, String, String, String>> joinDataStream = leftStream .join(rightStream) .where(new KeySelector<String, String>() { @Override public String getKey(String value) throws Exception { String[] split = value.split(","); return split[0]; } }) .equalTo(new KeySelector<String, String>() { @Override public String getKey(String value) throws Exception { String[] split = value.split(","); return split[0]; } }) .window(TumblingEventTimeWindows.of(Time.seconds(10))) .apply(new JoinFunction<String, String, Tuple5<String, String, String, String, String>>() { @Override public Tuple5<String, String, String, String, String> join(String leftStr, String rightStr) throws Exception { String[] left = leftStr.split(","); String[] right = rightStr.split(","); return new Tuple5<>(left[0], left[1], right[1], left[2],right[2]); } }); joinDataStream.print(); env.execute("InnerJoinDemo"); } }
package com.kdp.wanandroidclient.ui.project; import com.kdp.wanandroidclient.R; import com.kdp.wanandroidclient.application.AppContext; import com.kdp.wanandroidclient.bean.Article; import com.kdp.wanandroidclient.net.callback.RxObserver; import com.kdp.wanandroidclient.net.callback.RxPageListObserver; import com.kdp.wanandroidclient.ui.core.model.impl.ProjectModel; import com.kdp.wanandroidclient.ui.core.presenter.BasePresenter; import java.util.List; public class ProjectPresenter extends BasePresenter<ProjectContract.IProjectView> implements ProjectContract.IProjectPresenter { private ProjectModel projectModel; private ProjectContract.IProjectView projectView; ProjectPresenter() { this.projectModel = new ProjectModel(); } @Override public void getProjectList() { projectView = getView(); RxPageListObserver<Article> rxPageListObserver = new RxPageListObserver<Article>(this) { @Override public void onSuccess(List<Article> mData) { projectView.setData(mData); if (projectView.getData().size() == 0){ projectView.showEmpty(); }else { projectView.showContent(); } } @Override public void onFail(int errorCode, String errorMsg) { projectView.showFail(errorMsg); } }; projectModel.getProjectList(projectView.getPage(),projectView.getCid(),rxPageListObserver); addDisposable(rxPageListObserver); } @Override public void collectArticle() { RxObserver<String> mCollectRxObserver = new RxObserver<String>(this) { @Override protected void onStart() { } @Override protected void onSuccess(String data) { projectView.collect(true, AppContext.getContext().getString(R.string.collect_success)); } @Override protected void onFail(int errorCode, String errorMsg) { view.showFail(errorMsg); } }; projectModel.collectArticle(projectView.getArticleId(), mCollectRxObserver); addDisposable(mCollectRxObserver); } @Override public void unCollectArticle() { RxObserver<String> unCollectRxObserver = new RxObserver<String>(this) { @Override protected void onStart() { } @Override protected void onSuccess(String data) { projectView.collect(false, AppContext.getContext().getString(R.string.uncollect_success)); } @Override protected void onFail(int errorCode, String errorMsg) { view.showFail(errorMsg); } }; projectModel.unCollectArticle(projectView.getArticleId(), unCollectRxObserver); addDisposable(unCollectRxObserver); } }
package com.techelevator; public class KataNumbersToWords { // still need to do logic for when number equals 20 exactly // still need to do logic for when number equals 30 exactly... and 40 and 50 and // 60 and 70 and 80 and 90 public static String convertToWord(int number) { if (number < 20) { return oneToNineteen(number); } else if (number < 100) { return twentyToNinety(number); } else if (number < 1000) { return hundred(number); } else if (number < 10000) { return thousand(number); } else if (number < 100000){ return tenThousand(number); } return null; } // 20-90 helper public static String twentyToNinety(int number) { if (number < 30) { return twenty(number); } else if (number < 40) { return thirty(number); } else if (number < 50) { return forty(number); } else if (number < 60) { return fifty(number); } else if (number < 70) { return sixty(number); } else if (number < 80) { return seventy(number); } else if (number < 90) { return eighty(number); } else if (number < 100) { return ninety(number); } return null; } // twenty helper function private static String twenty(int x) { String returnVal = ""; if (x < 30 && x > 20) { returnVal += "twenty " + oneToNineteen(x - 20); } return returnVal; } // thirty helper function private static String thirty(int x) { String returnVal = ""; if (x > 30 && x < 40) { returnVal += "thirty " + oneToNineteen(x - 30); } return returnVal; } // forty helper function private static String forty(int x) { String returnVal = ""; if (x > 40 && x < 50) { returnVal += "forty " + oneToNineteen(x - 40); } return returnVal; } // fifty helper function private static String fifty(int x) { String returnVal = ""; if (x > 50 && x < 60) { returnVal += "fifty " + oneToNineteen(x - 50); } return returnVal; } // Sixty helper private static String sixty(int x) { String returnVal = ""; if (x > 60 && x < 70) { returnVal += "sixty " + oneToNineteen(x - 60); } return returnVal; } // seventy helper function private static String seventy(int x) { String returnVal = ""; if (x > 70 && x < 80) { returnVal += "seventy " + oneToNineteen(x - 70); } return returnVal; } // eighty helper function private static String eighty(int x) { String returnVal = ""; if (x > 80 && x < 90) { returnVal += "eighty " + oneToNineteen(x - 80); } return returnVal; } // ninety helper function private static String ninety(int x) { String returnVal = ""; if (x == 90) { return "ninety"; } if (x > 90 && x < 100) { returnVal += "ninety " + oneToNineteen(x - 90); } return returnVal; } // 100 helper private static String hundred(int x) { // will give the hundereds place value int firstNumber = ((x / 10) / 10); // gives you the solo hundreds to subtract int solidHundred = firstNumber * 100; // pop the back off the hundred int tensPlaces = x - solidHundred; return oneToNineteen(firstNumber) + " hundred " + twentyToNinety(tensPlaces); } // 1000 helper private static String thousand(int x) { // will give the thousanths place value 1,000 = 1 int firstNumber = ((x / 100) / 10); // gives you the solo thousand to subtract int solidThousand = firstNumber * 1000; // pop the hundred ex 2250 = 250 int hundredsPlace = x - solidThousand; // at this point call to the hundreds helper // 1= one thousand call to the hundreds helper return oneToNineteen(firstNumber) + " thousand " + hundred(hundredsPlace); } // 10,000 helper private static String tenThousand(int x) { String returnVal = ""; //divide x by 1000 to get the tens place thousand int tenThousand = x / 1000; // 20,000 = 20 //if 10 -19 if (tenThousand < 20) { returnVal = oneToNineteen(tenThousand); } else if (tenThousand < 100) { returnVal = twentyToNinety(tenThousand); } //20,250 twenty thousand, two hundred fifty //ten * 1000 equals the solid number to subtract // 20 * 1000 = 20,000 int solidTenThousand = tenThousand * 1000; //20,250 - 20,000 = 250 int hundredsPlace = x - solidTenThousand; // return value is the tens thousands place + hundreds return returnVal + " thousand " + hundred(hundredsPlace); } // helper function private static String oneToNineteen(int integer) { switch (integer) { case 0: return "zero"; case 1: return "one"; case 2: return "two"; case 3: return "three"; case 4: return "four"; case 5: return "five"; case 6: return "six"; case 7: return "seven"; case 8: return "eight"; case 9: return "nine"; case 10: return "ten"; case 11: return "eleven"; case 12: return "twelve"; case 13: return "thirteen"; case 14: return "fourteen"; case 15: return "fifteen"; case 16: return "sixteen"; case 17: return "seventeen"; case 19: return "nineteen"; } return null; } }
package bnorm.virtual; import robocode.Bullet; public interface IBulletWave extends IVectorWave { Bullet getBullet(); }
/** * <copyright> * </copyright> * * $Id$ */ package BPMN.impl; import BPMN.BPMNDefaultFlow; import BPMN.BPMNModelElement; import BPMN.BPMNPackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Default Flow</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link BPMN.impl.BPMNDefaultFlowImpl#getFormElement <em>Form Element</em>}</li> * <li>{@link BPMN.impl.BPMNDefaultFlowImpl#getToElement <em>To Element</em>}</li> * </ul> * </p> * * @generated */ public class BPMNDefaultFlowImpl extends BPMNModelElementImpl implements BPMNDefaultFlow { /** * The cached value of the '{@link #getFormElement() <em>Form Element</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFormElement() * @generated * @ordered */ protected BPMNModelElement formElement; /** * The cached value of the '{@link #getToElement() <em>To Element</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getToElement() * @generated * @ordered */ protected BPMNModelElement toElement; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BPMNDefaultFlowImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EClass eStaticClass() { return BPMNPackage.Literals.BPMN_DEFAULT_FLOW; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BPMNModelElement getFormElement() { if (formElement != null && formElement.eIsProxy()) { InternalEObject oldFormElement = (InternalEObject)formElement; formElement = (BPMNModelElement)eResolveProxy(oldFormElement); if (formElement != oldFormElement) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, BPMNPackage.BPMN_DEFAULT_FLOW__FORM_ELEMENT, oldFormElement, formElement)); } } return formElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BPMNModelElement basicGetFormElement() { return formElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFormElement(BPMNModelElement newFormElement) { BPMNModelElement oldFormElement = formElement; formElement = newFormElement; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BPMNPackage.BPMN_DEFAULT_FLOW__FORM_ELEMENT, oldFormElement, formElement)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BPMNModelElement getToElement() { if (toElement != null && toElement.eIsProxy()) { InternalEObject oldToElement = (InternalEObject)toElement; toElement = (BPMNModelElement)eResolveProxy(oldToElement); if (toElement != oldToElement) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, BPMNPackage.BPMN_DEFAULT_FLOW__TO_ELEMENT, oldToElement, toElement)); } } return toElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BPMNModelElement basicGetToElement() { return toElement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setToElement(BPMNModelElement newToElement) { BPMNModelElement oldToElement = toElement; toElement = newToElement; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BPMNPackage.BPMN_DEFAULT_FLOW__TO_ELEMENT, oldToElement, toElement)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case BPMNPackage.BPMN_DEFAULT_FLOW__FORM_ELEMENT: if (resolve) return getFormElement(); return basicGetFormElement(); case BPMNPackage.BPMN_DEFAULT_FLOW__TO_ELEMENT: if (resolve) return getToElement(); return basicGetToElement(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void eSet(int featureID, Object newValue) { switch (featureID) { case BPMNPackage.BPMN_DEFAULT_FLOW__FORM_ELEMENT: setFormElement((BPMNModelElement)newValue); return; case BPMNPackage.BPMN_DEFAULT_FLOW__TO_ELEMENT: setToElement((BPMNModelElement)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void eUnset(int featureID) { switch (featureID) { case BPMNPackage.BPMN_DEFAULT_FLOW__FORM_ELEMENT: setFormElement((BPMNModelElement)null); return; case BPMNPackage.BPMN_DEFAULT_FLOW__TO_ELEMENT: setToElement((BPMNModelElement)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean eIsSet(int featureID) { switch (featureID) { case BPMNPackage.BPMN_DEFAULT_FLOW__FORM_ELEMENT: return formElement != null; case BPMNPackage.BPMN_DEFAULT_FLOW__TO_ELEMENT: return toElement != null; } return super.eIsSet(featureID); } } //BPMNDefaultFlowImpl
package net.sf.ardengine.shapes; import net.sf.ardengine.Core; import net.sf.ardengine.Node; import net.sf.ardengine.renderer.IDrawableImpl; public class Circle extends Node implements IShape{ /**Used by renderer to store object with additional requirements*/ protected final IShapeImpl implementation; protected float radius = 0; /** * @param centerX - X coord of center * @param centerY - Y coord of center * @param radius radius of this circle */ public Circle(float centerX, float centerY, float radius) { this.radius = radius; setX(centerX); setY(centerY); implementation = Core.renderer.createShapeImplementation(this); } @Override public float[] getCoords() { return new float[]{radius}; } @Override public ShapeType getType() { return ShapeType.CIRCLE; } /** * Changes radius of this circle * @param radius - new Radius */ public void setRadius(float radius) { this.radius = radius; implementation.coordsChanged(); } /** * @return radius of this circle */ public float getRadius() { return radius; } @Override public void draw() { implementation.draw(); } @Override public IDrawableImpl getImplementation() { return implementation; } @Override public float getWidth() { return radius*2; } @Override public float getHeight() { return radius*2; } }
import java.io.*; class CharTest { public static void main(String args[]) throws IOException { char ch; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); while(true) { System.out.print("Enter a character: "); ch=(char)br.read(); System.out.println("You entered: "); if(Character.isDigit(ch)) System.out.print("a digit"); else if(Character.isUpperCase(ch)) System.out.println("an uppercase letter"); else if(Character.isLowerCase(ch)) System.out.println("a lowercase letter"); else if(Character.isSpaceChar(ch)) System.out.println("a spacebar character"); else if(Character.isWhitespace(ch)){ System.out.println("a whitespace character"); return; } else System.out.println("Sorry! I don't know that."); br.skip(2); } } }
package sorting; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public class test { public static void main(String []args){ ArrayList<String> obj= new ArrayList<String>(); obj.add("a"); obj.add("b"); obj.add("c"); obj.add("d"); System.out.println(obj); obj.add(0,"d"); obj.add(1,"c"); obj.add(2,"b"); obj.add(3,"a"); System.out.println(obj); obj.remove(0); System.out.println(obj); String s = obj.get(2); for(int i = 0; i<obj.size(); i++){ System.out.print(obj.get(i)); } System.out.println(obj.size());//the length of arrayList Collections.sort(obj);//sort the arraylist. //display the Arraylist for(String counter : obj){ System.out.println(counter); } ArrayList<String> obj1 = new ArrayList<String>(); obj1.add("test1"); obj1.add("test2"); obj1.add("test3"); obj1.add("test4"); // addAll(collection c) Method example obj.addAll(obj1); System.out.println(obj); //insert all elements form the other Arraylist obj.addAll(3,obj1); System.out.println(obj); //sublist to arrylist and it also can sublist to List ArrayList<String>obj2 = new ArrayList<String>(obj1.subList(1,2)); System.out.println(obj2); // use object.contains() to check exists in arraylsit } }
package sec11.exam01_arrays; //구현 클래스 public class Member implements Comparable<Member> { String name; Member(String name){ this.name=name; } @Override public int compareTo(Member o) { // TODO Auto-generated method stub return name.compareTo(o.name); } }
/** * <p>Copyright: Copyright(c) 2015</p> * <p>Company: gome.com.cn</p> * <p>2015年2月27日下午6:11:22</p> * @author wangyunpeng * @version 1.0 */ package neo.ce.service.impl; import neo.ce.service.IVirtualService; /** * desc: * <p>创建人:wangyunpeng 创建日期:2015年2月27日下午6:11:22</p> * @version V1.0 */ public class VirtualServiceImpl implements IVirtualService { @Override public String hello(String name) { //用来测试方法重入了几次 System.out.println("enter method..." + System.currentTimeMillis()); System.out.println(this); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("return..." + name); return "hello : " + name; } }
package com.sharpower.action; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.opensymphony.xwork2.ActionSupport; import com.sharpower.entity.FunTroubleVariable; import com.sharpower.service.FunTroubleVariableService; public class AjaxFunTroubleVariableAction extends ActionSupport{ private static final long serialVersionUID = 1L; private FunTroubleVariable funTroubleVariable; private FunTroubleVariableService funTroubleVariableService; private String searchKey; private List<FunTroubleVariable> funTroubleVariables = new ArrayList<>(); private Map<String, Object> result = new HashMap<>(); private String ids; private int page; private int rows; public FunTroubleVariable getFunTroubleVariable() { return funTroubleVariable; } public void setFunTroubleVariable(FunTroubleVariable funTroubleVariable) { this.funTroubleVariable = funTroubleVariable; } public void setFunTroubleVariableService(FunTroubleVariableService funTroubleVariableService) { this.funTroubleVariableService = funTroubleVariableService; } public void setSearchKey(String searchKey) { this.searchKey = searchKey; } public Map<String, Object> getResult() { return result; } public List<FunTroubleVariable> getFunTroubleVariables() { return funTroubleVariables; } public void setIds(String ids) { this.ids = ids; } public void setPage(int page) { this.page = page; } public void setRows(int rows) { this.rows = rows; } public String allFunTroubleVariable(){ try { String totalHql = ""; Long total; if (searchKey==null) { funTroubleVariables = funTroubleVariableService.findAllEntitiesPaging((page-1)*rows, rows); totalHql = "SELECT count(*) From FunTroubleVariable"; total = (Long) funTroubleVariableService.uniqueResult(totalHql); }else{ String hql = "From FunTroubleVariable v WHERE v.name like ?"; funTroubleVariables = funTroubleVariableService.findEntityByHQLPaging( hql, (page-1)*rows, rows, "%"+searchKey+"%"); totalHql = "SELECT count(*) From FunTroubleVariable v WHERE v.name like ?"; total = (Long) funTroubleVariableService.uniqueResult(totalHql, "%"+searchKey+"%"); } result.put("total", total); result.put("rows", funTroubleVariables); } catch (Exception e) { e.printStackTrace(); result.put("message", e.getMessage()); } return SUCCESS; } /** * 将变量名转换为数据库存储名 * @param name plc变量名 * @return */ private String convertNameToDBname(String name){ String hql = "From FunTroubleVariable v WHERE v.name=?"; List<FunTroubleVariable> funTroubleVariables = funTroubleVariableService.findEntityByHQL(hql, name); if (name.equals("")) { return ""; } String dbName = name.replace(".", "__"); char dbNameConvertFlag; //解决数据库名称重名的问题,重复变量名添加大写字母前缀加“_”,变量名中的“.”转变为“__”. if(funTroubleVariables.size()>0){ String lastDbName=""; for (int i=funTroubleVariables.size()-1;i>=0;i--) { if (funTroubleVariables.get(i).getDbName()!=""){ lastDbName=funTroubleVariables.get(i).getDbName(); break; } } if (lastDbName=="") { return name; } char head = lastDbName.charAt(0); if(head=='_'){ dbNameConvertFlag = 'A'; }else { dbNameConvertFlag = (char)((int)head + 1); } return dbNameConvertFlag + "_" + dbName; }else { return "_" + dbName; } } public String saveOrUpdate(){ try { if (funTroubleVariable.getId()==null ) { funTroubleVariable.setDbName(this.convertNameToDBname(funTroubleVariable.getName())); }else { String updateName = funTroubleVariable.getName(); FunTroubleVariable funTroubleVariable1 = funTroubleVariableService.getEntity(this.funTroubleVariable.getId()); String oldName = funTroubleVariable1.getName(); if (updateName.equals(oldName)==false) { funTroubleVariable.setDbName(this.convertNameToDBname(funTroubleVariable.getName())); }else{ funTroubleVariable.setDbName(funTroubleVariable1.getDbName()); } } funTroubleVariableService.saveOrUpdateEntity(funTroubleVariable); result.put("message", "保存成功!"); } catch (Exception e) { e.printStackTrace(); result.put("message", e.getMessage()); } return SUCCESS; } public String delete(){ String idString[] = ids.split(","); try { for (String idStr : idString) { FunTroubleVariable variable = new FunTroubleVariable(); variable.setId(Integer.parseInt(idStr)); funTroubleVariableService.deleteEntity(variable); } result.put("message", "删除成功!"); } catch (Exception e) { e.printStackTrace(); result.put("message", e.getMessage()); } return SUCCESS; } }
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 notXX * luma <stubma@163.com> * * This program 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 2 of the License, or * (at your option) any later version. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.qq.packets.out._05; import static org.apache.commons.codec.digest.DigestUtils.md5; import java.nio.ByteBuffer; import edu.tsinghua.lumaqq.qq.QQ; import edu.tsinghua.lumaqq.qq.beans.QQUser; import edu.tsinghua.lumaqq.qq.packets.PacketParseException; import edu.tsinghua.lumaqq.qq.packets._05OutPacket; /** * <pre> * 传送数据包 * 如果传送基本信息 * 1. 头部 * 2. 未知的8字节 * 3. session id, 4字节 * 4. 未知的4字节 * 5. 后面的数据长度,2字节,不包括包尾,包括本身 * 6. 未知2字节,和5相同? * 7. 图片的md5 * 8. 文件名的md5 * 9. 文件长度,4字节 * 10. 文件名长度,2字节 * 11. 文件名 * 12. 未知的8字节 * 13. 尾部 * * 如果传送数据信息 * 1. 头部 * 2. 未知的8字节,如果不是最后一个分片,则为,0x1000000000000001,如果是,则为随机字节 * 3. session id, 4字节 * 4. 未知的4字节 * 5. 数据分片长度,2字节 * 6. 数据分片 * 7. 包尾 * * 如果是接收方,则这个包用来通知服务器开始发送表情 * 1. 头部 * 2. 未知的8字节 * 3. session id, 4字节 * 4. 未知的4字节 * 5. 后面的数据长度,2字节 * 6. 4个字节,全0 * 7. 尾部 * * 如果是接收方对文件数据的回复,则为 * 1. 头部 * 2. 未知的8字节 * 3. session id, 4字节 * 4. 未知的4字节 * 5. 后面的数据长度,2字节 * 6. 一个字节,0x02,所以5一般是0x0001 * 7. 尾部 * </pre> * * @author luma */ public class TransferPacket extends _05OutPacket { // 公用字段 private int sessionId; // 用于发送基本信息时 private byte[] md5; private int imageLength; private String fileName; // 用户发送数据时 private byte[] fragment; private boolean data; private boolean last; private boolean requestSend; private boolean dataReply; /** * @param user * @param data * true表示这是数据分片 * @param last * true表示这是最后一个数据分片 */ public TransferPacket(QQUser user, boolean data, boolean last) { super(QQ.QQ_05_CMD_TRANSFER, data ? (last ? true : false) : true, user); this.data = data; this.last = last; requestSend = true; } /** * 构造一个请求发送数据包 * * @param user */ public TransferPacket(QQUser user) { super(QQ.QQ_05_CMD_TRANSFER, false, user); requestSend = false; dataReply = false; } /** * @param buf * @param length * @param user * @throws PacketParseException */ public TransferPacket(ByteBuffer buf, int length, QQUser user) throws PacketParseException { super(buf, length, user); } @Override public String getPacketName() { return "Transfer Packet"; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.qq.packets.Packet#putBody(java.nio.ByteBuffer) */ @Override protected void putBody(ByteBuffer buf) { if(!requestSend) { // 2. 未知的8字节 buf.putLong(0x0100000000000000L); // 3. session id, 4字节 buf.putInt(sessionId); // 未知4字节 buf.putInt(0); // 后面的内容长度和内容 if(dataReply) { buf.putChar((char)0x0001); buf.put((byte)0x02); } else { buf.putChar((char)0x04); buf.putInt(0); } } else if(data) { // 2. 未知的8字节,如果不是最后一个分片,则为,0x1000000000000001,如果是,则为随机字节 if(last) buf.putLong(0x0100000000000000L); else buf.putLong(0x0100000000000001L); // 3. session id, 4字节 buf.putInt(sessionId); // 4. 未知的4字节 buf.putInt(0); // 5. 数据分片长度,2字节 buf.putChar((char)fragment.length); // 6. 数据分片 buf.put(fragment); } else { // 2. 未知的8字节 buf.putLong(0x0100000000000000L); // 3. session id, 4字节 buf.putInt(sessionId); // 4. 未知的4字节 buf.putInt(0); // 5. 后面的数据长度,2字节 buf.putChar((char)0); // 6. 未知2字节,和5相同? int pos = buf.position(); buf.putChar((char)0); // 7. 图片的md5 buf.put(md5); // 8. 文件名md5 byte[] fileNameBytes = fileName.getBytes(); buf.put(md5(fileNameBytes)); // 9. 文件长度,4字节 buf.putInt(imageLength); // 10. 文件名长度,2字节 buf.putChar((char)fileName.length()); // 11. 文件名 buf.put(fileNameBytes); // 12. 未知的8字节 buf.putLong(0); char len = (char)(buf.position() - pos); buf.putChar(pos - 2, len); buf.putChar(pos, len); } } /** * @return Returns the imageLength. */ public int getImageLength() { return imageLength; } /** * @param imageLength The imageLength to set. */ public void setImageLength(int imageLength) { this.imageLength = imageLength; } /** * @return Returns the md5. */ public byte[] getMd5() { return md5; } /** * @param md5 The md5 to set. */ public void setMd5(byte[] md5) { this.md5 = md5; } /** * @return Returns the sessionId. */ public int getSessionId() { return sessionId; } /** * @param sessionId The sessionId to set. */ public void setSessionId(int sessionId) { this.sessionId = sessionId; } /** * @return Returns the fileName. */ public String getFileName() { return fileName; } /** * @param fileName The fileName to set. */ public void setFileName(String fileName) { this.fileName = fileName; } /** * @return Returns the fragment. */ public byte[] getFragment() { return fragment; } /** * @param fragment The fragment to set. */ public void setFragment(byte[] fragment) { this.fragment = fragment; } /** * @return Returns the requestSend. */ public boolean isRequestSend() { return requestSend; } /** * @param requestSend The requestSend to set. */ public void setRequestSend(boolean requestSend) { this.requestSend = requestSend; } public boolean isDataReply() { return dataReply; } public void setDataReply(boolean dataReply) { this.dataReply = dataReply; } }
package com.ua.serg.alex.buy.any.things.services.impl; import com.ua.serg.alex.buy.any.things.dao.ProductDao; import com.ua.serg.alex.buy.any.things.model.Category; import com.ua.serg.alex.buy.any.things.model.Order; import com.ua.serg.alex.buy.any.things.model.Product; import com.ua.serg.alex.buy.any.things.model.User; import com.ua.serg.alex.buy.any.things.services.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional @Service public class ProductServiceImpl implements ProductService { @Autowired private ProductDao productDao; @Override public List<Product> findAllProduct() { return productDao.getAllProduct(); } @Override public List<Product> findProductByCategory(Category category) { return productDao.getProductByCategory(category); } @Override public List<Product> findPaginationProduct(int page, int limit) { int offset = calculateOffset(page, limit); return productDao.getProductsByLimit(offset, limit); } @Override public List<Product> findPaginationProductByCategory(Category category, int page, int limit) { int offset = calculateOffset(page, limit); return productDao.getProductsByLimitByCategory(category, offset, limit); } @Override public Product findProduct(int id) { return productDao.getProductById(id); } @Override public long countProduct() { return productDao.getCountAllProduct(); } @Override public long countProductByCategory(int categoryID) { return productDao.getCountAllProductByCategory(categoryID); } @Override public void orderProduct(Product product, User user) { productDao.addProductToOrder(product, user); } private int calculateOffset(int page, int limit) { return ((limit * page) - limit); } }
package factoryTest; import Ciphers.Cipher; import Ciphers.Impl.CesarCipher1; import Ciphers.Impl.Root_13Cipher; import exceptions.CipherNotFoundException; import factories.Factory; import factories.impl.CipherFactory; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class CipherFactoryTest { private CipherFactory factory = new CipherFactory(); private static final String MESSAGE = "Type of cipher is not recognized: "; @Test protected void ifCesarCipherInstanceReturnWithCesarTypeTest (){ Cipher cipher = factory.create(CipherFactory.CESAR); Assertions.assertTrue(cipher instanceof CesarCipher1); } @Test protected void testRoot13 (){ Cipher cipher = factory.create(CipherFactory.ROOT13); Assertions.assertTrue(cipher instanceof Root_13Cipher); } // @file.utils.Test // protected void testExceptions (){ // Cipher cipher = factory.create("qwe"); // Assertions.assertTrue(cipher instanceof Root_13Cipher); // } @Test protected void testExceptions2 (){ String unkown = "unkown"; Assertions.assertThrows(CipherNotFoundException.class, () ->factory.create(unkown), MESSAGE + unkown); } }
package eece417project; import java.io.IOException; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import java.io.IOException; import java.util.Date; import javax.servlet.http.*; @SuppressWarnings("serial") public class registerServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { //grab user inputs from the registration page String firstName = req.getParameter("fname"); String lastName = req.getParameter("lname"); String userName = req.getParameter("uname"); String password = req.getParameter("pass"); String userType = req.getParameter("userType"); Entity user = new Entity("User"); user.setProperty("firstName", firstName); user.setProperty("lastName", lastName); user.setProperty("password", password); user.setProperty("userType", userType); user.setProperty("userName", userName); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(user); resp.sendRedirect("/home.jsp"); } }
package server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; /** * This is the server class * Del av gruppuppgift DA343A * @author Gustav Frigren, Karl-Ebbe J�nsson * */ public class Server extends Thread { private Controller controller; private int port; private ThreadPoolExecutor threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(); private ServerSocket serverSocket; private Socket socket; boolean running = true; public Server(Controller controller, int port) { this.controller = controller; this.port = port; } public void stopServer(){ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } running = false; } public void run() { try { serverSocket = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); } while(running) { try { socket = serverSocket.accept(); threadPool.execute(new User(controller, socket)); } catch (IOException e) { e.printStackTrace(); } } try { serverSocket.close(); }catch (IOException e) { } } }
package logic; /** * Created by Mateusz on 15.05.2017. */ public class TennisGameInitialSettings { private static final int MAX_PLAYERS_AMOUNT = 2; private final TennisPlayer[] tennisPlayerList; public TennisGameInitialSettings(TennisPlayer firstPlayer, TennisPlayer secondPlayer) { this.tennisPlayerList = new TennisPlayer[]{firstPlayer, secondPlayer}; } TennisPlayer getFirstTennisPlayer() { return getTennisPlayer(0); } TennisPlayer getSecondTennisPlayer() { return getTennisPlayer(1); } private TennisPlayer getTennisPlayer(int index) { return tennisPlayerList[index]; } public static int getMaxPlayersAmount() { return MAX_PLAYERS_AMOUNT; } }
package pe.com.tss.bean; import java.io.Serializable; import javax.persistence.*; import org.eclipse.persistence.annotations.ReturnInsert; import java.math.BigDecimal; import java.util.Date; /** * The persistent class for the RAIL_RATE database table. * */ @Entity @Table(name = "RAIL_RATE") @NamedQuery(name = "RailRate.findAll", query = "SELECT r FROM RailRate r") public class RailRate implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "RAIL_RATE_ID") @ReturnInsert(returnOnly = true) private long railRateId; @Column(name = "CREATED_BY") private String createdBy; @Temporal(TemporalType.DATE) @Column(name = "CREATED_DATE") private Date createdDate; @Column(name = "CUSTOMER_ID") private BigDecimal customerId; @Temporal(TemporalType.DATE) @Column(name = "EFFECTIVE_DATE") private Date effectiveDate; @Column(name = "EQUIPMENT_SIZE") private String equipmentSize; @Column(name = "EQUIPMENT_TYPE") private String equipmentType; @Temporal(TemporalType.DATE) @Column(name = "EXPIRATION_DATE") private Date expirationDate; private BigDecimal fuel; @Column(name = "IS_HAZ_MAT") private String isHazMat; @Column(name = "IS_IMPORTED") private String isImported; @Column(name = "LINE_HAULCOST") private BigDecimal lineHaulcost; private BigDecimal miles; @Column(name = "RATE_TYPE") private String rateType; @Column(name = "SERVICE_LEVEL") private String serviceLevel; private String status; private String stcc; @Column(name = "TARIFF_NUMBER") private String tariffNumber; @Column(name = "TRANSIT_DAYS") private BigDecimal transitDays; @Column(name = "UPDATED_BY") private String updatedBy; @Temporal(TemporalType.DATE) @Column(name = "UPDATED_DATE") private Date updatedDate; @Column(name = "VENDOR_ID") private long vendorId; @Column(name = "ORIGIN_RAMP_ID") private long originrampid; @Column(name = "DESTINATION_RAMP_ID") private long destinationrampid; public RailRate() { } public long getRailRateId() { return this.railRateId; } public void setRailRateId(long railRateId) { this.railRateId = railRateId; } public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Date getCreatedDate() { return this.createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public BigDecimal getCustomerId() { return this.customerId; } public void setCustomerId(BigDecimal customerId) { this.customerId = customerId; } public Date getEffectiveDate() { return this.effectiveDate; } public void setEffectiveDate(Date effectiveDate) { this.effectiveDate = effectiveDate; } public String getEquipmentSize() { return this.equipmentSize; } public void setEquipmentSize(String equipmentSize) { this.equipmentSize = equipmentSize; } public String getEquipmentType() { return this.equipmentType; } public void setEquipmentType(String equipmentType) { this.equipmentType = equipmentType; } public Date getExpirationDate() { return this.expirationDate; } public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; } public BigDecimal getFuel() { return this.fuel; } public void setFuel(BigDecimal fuel) { this.fuel = fuel; } public String getIsHazMat() { return this.isHazMat; } public void setIsHazMat(String isHazMat) { this.isHazMat = isHazMat; } public String getIsImported() { return this.isImported; } public void setIsImported(String isImported) { this.isImported = isImported; } public BigDecimal getLineHaulcost() { return this.lineHaulcost; } public void setLineHaulcost(BigDecimal lineHaulcost) { this.lineHaulcost = lineHaulcost; } public BigDecimal getMiles() { return this.miles; } public void setMiles(BigDecimal miles) { this.miles = miles; } public String getRateType() { return this.rateType; } public void setRateType(String rateType) { this.rateType = rateType; } public String getServiceLevel() { return this.serviceLevel; } public void setServiceLevel(String serviceLevel) { this.serviceLevel = serviceLevel; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public String getStcc() { return this.stcc; } public void setStcc(String stcc) { this.stcc = stcc; } public String getTariffNumber() { return this.tariffNumber; } public void setTariffNumber(String tariffNumber) { this.tariffNumber = tariffNumber; } public BigDecimal getTransitDays() { return this.transitDays; } public void setTransitDays(BigDecimal transitDays) { this.transitDays = transitDays; } public String getUpdatedBy() { return this.updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedDate() { return this.updatedDate; } public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } public long getVendorId() { return this.vendorId; } public void setVendorId(long vendorId) { this.vendorId = vendorId; } public long getOriginrampid() { return originrampid; } public void setOriginrampid(long originrampid) { this.originrampid = originrampid; } public long getDestinationrampid() { return destinationrampid; } public void setDestinationrampid(long destinationrampid) { this.destinationrampid = destinationrampid; } @Override public String toString() { return "RailRate [railRateId=" + railRateId + ", createdBy=" + createdBy + ", createdDate=" + createdDate + ", customerId=" + customerId + ", effectiveDate=" + effectiveDate + ", equipmentSize=" + equipmentSize + ", equipmentType=" + equipmentType + ", expirationDate=" + expirationDate + ", fuel=" + fuel + ", isHazMat=" + isHazMat + ", isImported=" + isImported + ", lineHaulcost=" + lineHaulcost + ", miles=" + miles + ", rateType=" + rateType + ", serviceLevel=" + serviceLevel + ", status=" + status + ", stcc=" + stcc + ", tariffNumber=" + tariffNumber + ", transitDays=" + transitDays + ", updatedBy=" + updatedBy + ", updatedDate=" + updatedDate + ", vendorId=" + vendorId + ", originrampid=" + originrampid + ", destinationrampid=" + destinationrampid + "]"; } }
/* * (C) Copyright 2014,2016 Hewlett Packard Enterprise Development LP * * 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 monasca.api.infrastructure.persistence.vertica; import com.google.common.base.Splitter; import com.google.common.base.Strings; import java.sql.Timestamp; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Query; import monasca.api.domain.exception.MultipleMetricsException; import monasca.api.domain.model.measurement.Measurements; /** * Vertica utilities for building metric queries. */ final class MetricQueries { private static final Splitter BAR_SPLITTER = Splitter.on('|').omitEmptyStrings().trimResults(); private static final Splitter UNDERSCORE_SPLITTER = Splitter.on('_').omitEmptyStrings().trimResults(); private static final Splitter COMMA_SPLITTER = Splitter.on(',').omitEmptyStrings().trimResults(); static final String FIND_METRIC_DEFS_SQL = "SELECT %s TO_HEX(defDims.id) as defDimsId, def.name, dims.name as dName, dims.value AS dValue " + "FROM MonMetrics.Definitions def " + "JOIN MonMetrics.DefinitionDimensions defDims ON def.id = defDims.definition_id " // Outer join needed in case there are no dimensions for a definition. + "LEFT OUTER JOIN MonMetrics.Dimensions dims ON dims.dimension_set_id = defDims" + ".dimension_set_id " + "WHERE TO_HEX(defDims.id) in (%s) " + "ORDER BY defDims.id ASC"; static final String METRIC_DEF_SUB_SQL = "SELECT TO_HEX(defDimsSub.id) as id " + "FROM MonMetrics.Definitions as defSub " + "JOIN MonMetrics.DefinitionDimensions as defDimsSub ON defDimsSub.definition_id = defSub.id " + "%s " // possible measurements time join here + "WHERE defSub.tenant_id = :tenantId " + "%s " // metric name here + "%s " // dimension and clause here + "%s " // possible time and clause here + "GROUP BY defDimsSub.id"; private static final String MEASUREMENT_AND_CLAUSE = "AND time_stamp >= :startTime "; // start or start and end time here private static final String MEASUREMENT_JOIN = "JOIN MonMetrics.Measurements AS meas ON defDimsSub.id = meas.definition_dimensions_id"; private static final String TABLE_TO_JOIN_ON = "defDimsSub"; private MetricQueries() {} static String buildMetricDefinitionSubSql(String name, Map<String, String> dimensions, DateTime startTime, DateTime endTime) { String namePart = ""; if (name != null && !name.isEmpty()) { namePart = "AND defSub.name = :name "; } return String.format(METRIC_DEF_SUB_SQL, buildTimeJoin(startTime), namePart, buildDimensionAndClause(dimensions, TABLE_TO_JOIN_ON), buildTimeAndClause(startTime, endTime)); } static String buildDimensionAndClause(Map<String, String> dimensions, String tableToJoinName) { if (dimensions == null || dimensions.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); sb.append(" and ").append(tableToJoinName).append( ".id in ( " + "SELECT defDimsSub2.id FROM MonMetrics.Dimensions AS dimSub " + "JOIN MonMetrics.DefinitionDimensions AS defDimsSub2 " + "ON defDimsSub2.dimension_set_id = dimSub.dimension_set_id" + " WHERE ("); int i = 0; for (Iterator<Map.Entry<String, String>> it = dimensions.entrySet().iterator(); it.hasNext(); i++) { Map.Entry<String, String> entry = it.next(); sb.append("(name = :dname").append(i); String dim_value = entry.getValue(); if (!Strings.isNullOrEmpty(dim_value)) { List<String> values = BAR_SPLITTER.splitToList(dim_value); if (values.size() > 1) { sb.append(" and ( "); for (int j = 0; j < values.size(); j++) { sb.append("value = :dvalue").append(i).append('_').append(j); if (j < values.size() - 1) { sb.append(" or "); } } sb.append(")"); } else { sb.append(" and value = :dvalue").append(i); } } sb.append(")"); if (it.hasNext()) { sb.append(" or "); } } sb.append(") GROUP BY defDimsSub2.id,dimSub.dimension_set_id HAVING count(*) = ").append(dimensions.size()).append(") "); return sb.toString(); } static String buildTimeAndClause( DateTime startTime, DateTime endTime) { if (startTime == null) { return ""; } StringBuilder timeAndClause = new StringBuilder(); timeAndClause.append(MEASUREMENT_AND_CLAUSE); if (endTime != null) { timeAndClause.append("AND time_stamp <= :endTime "); } return timeAndClause.toString(); } static String buildTimeJoin(DateTime startTime) { if (startTime == null) { return ""; } return MEASUREMENT_JOIN; } static void bindDimensionsToQuery(Query<?> query, Map<String, String> dimensions) { if (dimensions != null) { int i = 0; for (Iterator<Map.Entry<String, String>> it = dimensions.entrySet().iterator(); it.hasNext(); i++) { Map.Entry<String, String> entry = it.next(); query.bind("dname" + i, entry.getKey()); if (!Strings.isNullOrEmpty(entry.getValue())) { List<String> values = BAR_SPLITTER.splitToList(entry.getValue()); if (values.size() > 1) { for (int j = 0; j < values.size(); j++) { query.bind("dvalue" + i + '_' + j, values.get(j)); } } else { query.bind("dvalue" + i, entry.getValue()); } } } } } static void bindOffsetToQuery(Query<Map<String, Object>> query, String offset) { List<String> offsets = UNDERSCORE_SPLITTER.splitToList(offset); if (offsets.size() > 1) { query.bind("offset_id", offsets.get(0)); query.bind("offset_timestamp", new Timestamp(DateTime.parse(offsets.get(1)).getMillis())); } else { query.bind("offset_timestamp", new Timestamp(DateTime.parse(offsets.get(0)).getMillis())); } } static void checkForMultipleDefinitions(Handle h, String tenantId, String name, Map<String, String> dimensions) throws MultipleMetricsException { String namePart = ""; if (name != null && !name.isEmpty()) { namePart = "AND name = :name "; } String sql = String.format(METRIC_DEF_SUB_SQL, "", namePart, buildDimensionAndClause(dimensions, TABLE_TO_JOIN_ON), "") + " limit 2"; Query<Map<String, Object>> query = h.createQuery(sql); query.bind("tenantId", tenantId); if (name != null) { query.bind("name", name); } bindDimensionsToQuery(query, dimensions); List<Map<String, Object>> rows = query.list(); if (rows.size() > 1) { throw new MultipleMetricsException(name, dimensions); } } static void addDefsToResults(Map<String, ? extends Measurements> results, Handle h, String dbHint) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String id : results.keySet()) { if (first) { sb.append("'").append(id).append("'"); first = false; } else { sb.append(',').append("'").append(id).append("'"); } } String defDimSql = String.format(MetricQueries.FIND_METRIC_DEFS_SQL, dbHint, sb.toString()); Query<Map<String, Object>> query = h.createQuery(defDimSql); List<Map<String, Object>> rows = query.list(); String currentDefDimId = null; Map<String, String> dims = null; for (Map<String, Object> row : rows) { String defDimId = (String) row.get("defDimsId"); String defName = (String) row.get("name"); String dimName = (String) row.get("dName"); String dimValue = (String) row.get("dValue"); if (defDimId != null && !defDimId.equals(currentDefDimId)) { currentDefDimId = defDimId; dims = new HashMap<>(); if (dimName != null && dimValue != null) dims.put(dimName, dimValue); results.get(defDimId).setId(defDimId); results.get(defDimId).setName(defName); results.get(defDimId).setDimensions(dims); } else { if (dimName != null && dimValue != null) dims.put(dimName, dimValue); } } } static Map<String, String> combineGroupByAndValues(List<String> groupBy, String valueStr) { List<String> values = COMMA_SPLITTER.splitToList(valueStr); Map<String, String> newDimensions = new HashMap<>(); for (int i = 0; i < groupBy.size(); i++) { newDimensions.put(groupBy.get(i), values.get(i)); } return newDimensions; } static String buildGroupByConcatString(List<String> groupBy) { if (groupBy.isEmpty() || "*".equals(groupBy.get(0))) return ""; String select = "("; for (int i = 0; i < groupBy.size(); i++) { if (i > 0) select += " || ',' || "; select += "gb" + i + ".value"; } select += ")"; return select; } static String buildGroupByCommaString(List<String> groupBy) { String result = ""; if (!groupBy.contains("*")) { for (int i = 0; i < groupBy.size(); i++) { if (i > 0) { result += ','; } result += "gb" + i + ".value"; } } return result; } static String buildGroupBySql(List<String> groupBy) { if (groupBy.isEmpty() || "*".equals(groupBy.get(0))) return ""; StringBuilder groupBySql = new StringBuilder( " JOIN MonMetrics.DefinitionDimensions as dd on dd.id = mes.definition_dimensions_id "); for (int i = 0; i < groupBy.size(); i++) { groupBySql.append("JOIN (SELECT dimension_set_id,value FROM MonMetrics.Dimensions WHERE name = "); groupBySql.append(":groupBy").append(i).append(") as gb").append(i); groupBySql.append(" ON gb").append(i).append(".dimension_set_id = dd.dimension_set_id "); } return groupBySql.toString(); } static void bindGroupBy(Query<Map<String, Object>> query, List<String> groupBy) { int i = 0; for (String value: groupBy) { query.bind("groupBy" + i, value); i++; } } }
package core; public class Vector2D { public float x; public float y; public Vector2D(float x, float y) { this.x = x; this.y = y; } public Vector2D() { this.x = 0.0f; this.y = 0.0f; } public Vector2D set(float x, float y) { this.x = x; this.y = y; return this; } public Vector2D set(Vector2D vector2D) { return this.set(vector2D.x, vector2D.y); } public Vector2D addUp(float x, float y) { this.x += x; this.y += y; return this; } public Vector2D addUp(Vector2D vector2D) { return this.addUp(vector2D.x, vector2D.y); } public Vector2D add(float x, float y) { return new Vector2D(this.x + x, this.y + y); } public Vector2D add(Vector2D vector2D) { return this.add(vector2D.x, vector2D. y); } public Vector2D subtractBy(float x, float y) { this.x -= x; this.y -= y; return this; } public Vector2D subtractBy(Vector2D vector2D) { return this.subtractBy(vector2D.x, vector2D.y); } public Vector2D subtract(float x, float y) { return new Vector2D(this.x - x, this.y - y); } public Vector2D subtract(Vector2D vector2D) { return this.subtract(vector2D.x, vector2D. y); } public Vector2D mutiply(float number) { this.x *= number; this.y *= number; return this; } public float length() { return (float) Math.sqrt(this.x * this.x + this.y * this.y); } public Vector2D clone() { return new Vector2D(this.x, this.y); } public Vector2D rotate(double angle) { double cos = Math.cos(Math.toRadians(angle)); double sin = Math.sin(Math.toRadians(angle)); return new Vector2D((float) (this.x * cos - this.y * sin), (float)(this.x * sin + this.y * cos)); } }
package com.example.dllo.notestudio.DemoExpandable; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.TextView; import com.example.dllo.notestudio.R; import java.util.ArrayList; import java.util.Date; /** * Created by dllo on 16/11/3. */ public class DemoExAdapter extends BaseExpandableListAdapter { private ArrayList<String> father; //1111 private ArrayList<ArrayList<String>> son; private Context context; public static final int TYPEFATHER = 0; public static final int TYPESON = 1; public static final int TYPECOUNT = 2; public DemoExAdapter(Context context) { this.context = context; } public DemoExAdapter setFather(ArrayList<String> father) { this.father = father; notifyDataSetChanged(); return this; } public DemoExAdapter setSon(ArrayList<ArrayList<String>> son) { this.son = son; notifyDataSetChanged(); return this; } @Override public int getGroupCount() { return father!=null&&father.size()>0?father.size():0; } //123 @Override public int getChildrenCount(int i) { return son.get(i).size(); } @Override public Object getGroup(int i) { return father.get(i); } @Override public Object getChild(int i, int i1) { return son.get(i).get(i1); } @Override public long getGroupId(int i) { return i; } @Override public long getChildId(int i, int i1) { return i1; } @Override//一般不用 public boolean hasStableIds() { return false; } @Override public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) { ViewHolderFATHER holderFATHER = null; if (view == null){ view = LayoutInflater.from(context).inflate(R.layout.demo_expandable_father,viewGroup,false); holderFATHER = new ViewHolderFATHER(view); view.setTag(holderFATHER); }else { holderFATHER = (ViewHolderFATHER) view.getTag(); } holderFATHER.tv1.setText(father.get(i)); return view; } @Override public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) { ViewHolderSon holderSon = null ; if (view==null) { view = LayoutInflater.from(context).inflate(R.layout.demo_expandable_son,viewGroup,false); holderSon = new ViewHolderSon(view); view.setTag(holderSon); }else { holderSon = (ViewHolderSon) view.getTag(); } holderSon.tv2.setText(son.get(i).get(i1)); return view; } //子列表可否被点击 @Override public boolean isChildSelectable(int i, int i1) { return true; } class ViewHolderFATHER { private TextView tv1 ; public ViewHolderFATHER(View view) { tv1 = (TextView) view.findViewById(R.id.exp_father); } } class ViewHolderSon { private TextView tv2 ; public ViewHolderSon(View view) { tv2 = (TextView) view.findViewById(R.id.exp_son); } } }
package com.github.ngoanh2n; import org.apache.commons.lang3.reflect.FieldUtils; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.annotations.*; import org.testng.internal.BaseTestMethod; import org.testng.internal.ConstructorOrMethod; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Lookup {@link WebDriver} from the current TestNG test using {@link IInvokedMethodListener}. * <ul> * <li>Step 1: Create a class that extends {@link WebDriverTestNG} * <pre>{@code * package com.company.project.impl; * * import com.github.ngoanh2n.WebDriverTestNG; * * public class MyWebDriverLookup extends WebDriverTestNG { * public WebDriver getWebDriver() { * if (iTestResult != null) { * lookupDriver(iTestResult, WebDriverTestNG.BO); * } * return driver; * } * } * }</pre> * </li> * <li>Step 2: Create a provider configuration file * <ul> * <li>Location: {@code resources/META-INF/services/}</li> * <li>Name: {@code org.junit.jupiter.api.extension.Extension}</li> * <li>Content: {@code com.company.project.impl.MyWebDriverLookup}</li> * </ul> * </li> * </ul> * * <em>Repository:</em> * <ul> * <li><em>GitHub: <a href="https://github.com/ngoanh2n/commons">ngoanh2n/commons</a></em></li> * <li><em>Maven: <a href="https://mvnrepository.com/artifact/com.github.ngoanh2n/commons-testng">com.github.ngoanh2n:commons-testng</a></em></li> * </ul> * * @author ngoanh2n * @since 2019 */ public class WebDriverTestNG implements IInvokedMethodListener { protected static final Logger log = LoggerFactory.getLogger(WebDriverTestNG.class); /** * Mark events before an invocation. */ protected static final String BE = "BE"; /** * Mark events inside an invocation. */ protected static final String BO = "BO"; /** * Mark events after an invocation. */ protected static final String AF = "AF"; /** * The test result of the current test. */ protected static ITestResult iTestResult; /** * The current {@link WebDriver} from the current TestNG test. */ protected WebDriver driver; /** * Default constructor. */ public WebDriverTestNG() { /**/ } //-------------------------------------------------------------------------------// /** * {@inheritDoc} */ @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context) { lookupDriver(testResult, BE); } /** * {@inheritDoc} */ @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context) { lookupDriver(testResult, AF); } //-------------------------------------------------------------------------------// /** * Lookup {@link WebDriver} from the current {@link ITestResult}. * * @param testResult The test result of the current test. * @param aspect Mark events before (BE) and after (AF) an invocation. Besides that there is body (BO). */ protected void lookupDriver(ITestResult testResult, String aspect) { iTestResult = testResult; Object instance = testResult.getInstance(); Class<?> clazz = instance.getClass(); Field[] fields = FieldUtils.getAllFields(clazz); for (Field field : fields) { Object value = Commons.readField(instance, field.getName()); if (value instanceof WebDriver) { driver = (WebDriver) value; break; } } BaseTestMethod cm = Commons.readField(iTestResult, "m_method"); ConstructorOrMethod com = Commons.readField(cm, "m_method"); Method method = Commons.readField(com, "m_method"); String annotation = getSignatureAnnotation(method).getSimpleName(); log.debug("{} @{} {} -> {}", aspect, annotation, method, driver); } /** * Get signature annotation of the current method is invoking. * * @param method The current method is invoking. * @return The annotation of the current method. */ protected Class<?> getSignatureAnnotation(Method method) { Class<?>[] signatures = new Class[]{ BeforeClass.class, BeforeMethod.class, Test.class, AfterClass.class, AfterMethod.class }; Annotation[] declarations = method.getDeclaredAnnotations(); for (Class<?> signature : signatures) { for (Annotation declaration : declarations) { if (signature.getName().equals(declaration.annotationType().getName())) { return signature; } } } String msg = String.format("Get signature annotation at %s", method); log.error(msg); throw new RuntimeError(msg); } //-------------------------------------------------------------------------------// /* * https://www.javatpoint.com/testng-annotations * 01. ISuiteListener.onStart * 02. ITestListener.onStart * * 03. IClassListener.onBeforeClass * * 04. IInvokedMethodListener.beforeInvocation * 05. @BeforeClass * 06. IInvokedMethodListener.afterInvocation * * 07. IInvokedMethodListener.beforeInvocation * 08. @BeforeMethod * 09. IInvokedMethodListener.afterInvocation * * 10. ITestListener.onTestStart * * 11. IInvokedMethodListener.beforeInvocation * 12. @Test * 13. IInvokedMethodListener.afterInvocation * * 14. IInvokedMethodListener.beforeInvocation * 15. @AfterMethod * 16. IInvokedMethodListener.afterInvocation * * 17. IClassListener.onAfterClass * * 18. IInvokedMethodListener.beforeInvocation * 19. @AfterClass * 20. IInvokedMethodListener.afterInvocation * * 21. ITestListener.onFinish * 22. ISuiteListener.onFinish * */ }
package com.tencent.mm.plugin.radar; import com.tencent.mm.model.ar; import com.tencent.mm.pluginsdk.b.b; import com.tencent.mm.pluginsdk.b.c; import com.tencent.mm.pluginsdk.n; public final class Plugin implements c { public final n createApplication() { return (n) new b(); } public final b getContactWidgetFactory() { return null; } public final ar createSubCore() { return (ar) new c(); } }
package com.tencent.tencentmap.mapsdk.a; import android.os.AsyncTask; import com.tencent.tencentmap.mapsdk.a.nl.a; import com.tencent.tencentmap.mapsdk.a.nl.c; import java.lang.ref.WeakReference; class nl$b extends AsyncTask<String, Void, c> { final /* synthetic */ nl a; private WeakReference<a> b; public nl$b(nl nlVar, a aVar) { this.a = nlVar; this.b = new WeakReference(aVar); } /* renamed from: a */ protected c doInBackground(String... strArr) { po a; try { a = pn.a().a(nl.b(this.a)); } catch (Throwable th) { a = null; } if (a == null) { return null; } return nl.a(this.a, a.toString()); } /* renamed from: a */ protected void onPostExecute(c cVar) { super.onPostExecute(cVar); a aVar = null; if (this.b != null) { aVar = (a) this.b.get(); } if (aVar != null) { aVar.a(cVar); } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Shot { private String reply; private int gorizont; private int vertical; private int[][] enemyBattleground; private String[] yes={"yes","ok","lf","gjgfk","hit","wounded","killed","kill","da","да","попал","ранил","убил","нуы","ага","угу","даа","ранел"}; private String[] no={"no","ytn","xuy","vbvj","missed","not","nope","nay","nix","net","nea","ne","промазал","промахнулся","мимо","мима","нет","неа","не","loser"}; private String[] blin={"Блин!","Твою ж мать!","Чйорт побери!","Я и не старался!","Ой, все!"}; private String[] ura={"Круто!","Красота!","Это хотошо!","Учись пока я жив!","Легко!","Годится!"}; boolean b =true; public Shot(int[][] enemyBattleground) throws IOException{ this.enemyBattleground=enemyBattleground; OneShot(); } private void OneShot() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (b){ gorizont = (int)(Math.random()*10); vertical = (int)(Math.random()*10); if (enemyBattleground[gorizont][vertical]==0){ System.out.println("Мой выстрел. По горизонтали: "+(gorizont+1)+", а по вертикали: "+(vertical+1)); System.out.println("Попал?"); System.out.println(""); while(b){ boolean b1=true; reply = reader.readLine(); for (int i=0; i<yes.length;i++){ if (reply.toLowerCase().equals(yes[i])){ enemyBattleground[gorizont][vertical]=1; System.out.println(""); replica(ura); System.out.println("Еще разок."); System.out.println(""); b1=false; break; } } if (b1){ for (int i =0; i<no.length;i++){ if (reply.toLowerCase().equals(no[i])){ System.out.println(""); replica(blin); System.out.println("Твой ход..."); System.out.println(""); b=false; break; } } }else break; if (b1&b) warning(); } } } } private void warning() { System.out.println("Не понял тебя, повтори еще раз."); System.out.println(""); } private void replica(String[] arr) { System.out.println(arr[(int)(Math.random()*arr.length)]); } }
package com.sagunpandey.spookyspidersmash; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import com.squareup.picasso.Picasso; public class TitleActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create full screen window getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_title); ImageView imageView = (ImageView) findViewById(R.id.titleScreen); Picasso .with(this) .load(R.drawable.titlescreen) .fit() .into(imageView); Button playButton = (Button) findViewById(R.id.buttonPlay); Button highScoreButton = (Button) findViewById(R.id.buttonHighScore); playButton.setOnClickListener(this); highScoreButton.setOnClickListener(this); } @Override public void onBackPressed() { new AlertDialog.Builder(this) .setMessage("Do you want to quit the game?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { TitleActivity.super.onBackPressed(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } @Override public void onClick(View view) { int viewId = view.getId(); switch(viewId) { case R.id.buttonPlay: Intent intent = new Intent(this, GameActivity.class); startActivity(intent); break; case R.id.buttonHighScore: Intent intent1 = new Intent(this, SettingsActivity.class); startActivity(intent1); break; } } }
package fr.lteconsulting; import java.util.Random; public class Conway implements IConway { private final int width; private final int height; private boolean board[]; public Conway( int width, int height ) { this.width = width; this.height = height; board = new boolean[width * height]; } public void initializeRandomly() { Random random = new Random(); for( int i = 0; i < width; i++ ) for( int j = 0; j < height; j++ ) board[cellIndex( i, j )] = random.nextInt( 5 ) == 0; } public void putFigure( int x, int y, String[] pattern ) { for( int p = 0; p < pattern.length; p++ ) { String line = pattern[p]; for( int i = 0; i < line.length(); i++ ) { if( x + i < 0 || x + i >= width || y + p < 0 || y + p >= height ) continue; board[cellIndex( x + i, y + p )] = line.charAt( i ) != ' '; } } } public void putFrog( int x, int y ) { putFigure( x, y, new String[] { " XXX", "XXX " } ); } public void putU( int x, int y ) { putFigure( x, y, new String[] { "XXX", "X X", "X X" } ); } public boolean getCell( int x, int y ) { if( x < 0 || x >= width || y < 0 || y >= height ) return false; return board[cellIndex( x, y )]; } @Override public void makeCellAlive( int x, int y ) { putU( x, y ); } public int getWidth() { return width; } public int getHeight() { return height; } public void display() { for( int i = 0; i < width + 2; i++ ) System.out.print( "_" ); System.out.println(); for( int j = 0; j < height; j++ ) { StringBuilder sb = new StringBuilder(); sb.append( "|" ); for( int i = 0; i < width; i++ ) sb.append( getCell( i, j ) ? "#" : " " ); sb.append( "|" ); System.out.println( sb.toString() ); } for( int i = 0; i < width + 2; i++ ) System.out.print( "_" ); System.out.println(); } public void evolve() { boolean nextBoard[] = new boolean[width * height]; for( int i = 0; i < width; i++ ) { for( int j = 0; j < height; j++ ) { int count = countAliveNeighbourCells( i, j ); if( getCell( i, j ) ) { // cell is alive nextBoard[cellIndex( i, j )] = count == 2 || count == 3; } else { nextBoard[cellIndex( i, j )] = count == 3; } } } board = nextBoard; } private int countAliveNeighbourCells( int i, int j ) { int count = 0; for( int dx = -1; dx <= 1; dx++ ) { for( int dy = -1; dy <= 1; dy++ ) { int x = i + dx; int y = j + dy; if( x == i && y == j ) continue; if( getCell( x, y ) ) count++; } } return count; } private int cellIndex( int i, int j ) { return j * height + i; } }
package com.wzjing.scan.camera; import android.graphics.ImageFormat; import android.graphics.Point; import android.hardware.Camera; import android.util.Log; import android.view.SurfaceHolder; import androidx.annotation.NonNull; import com.google.zxing.client.android.camera.CameraConfigurationUtils; import java.io.IOException; public class CameraManager implements SurfaceHolder.Callback { public static final int STATE_START = 0; public static final int STATE_STOP = 1; private Camera camera; private Point size; private Point surfaceSize; private byte[] buffer; private SurfaceHolder mHolder; private OnPreviewCallback mCb; private OnStateChangeListener mStateListener; private boolean surfaceReady = false; private boolean postOpen = false; public CameraManager(@NonNull SurfaceHolder holder) { mHolder = holder; mHolder.addCallback(this); } public void open() { if (surfaceReady) { openInternal(); } else { postOpen = true; } } private void openInternal() { camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK); Camera.Parameters params = camera.getParameters(); CameraConfigurationUtils.findBestPreviewSizeValue(params, surfaceSize); CameraConfigurationUtils.setFocus(params, true, false, false); CameraConfigurationUtils.setBarcodeSceneMode(params); CameraConfigurationUtils.setFocusArea(params); params.setPreviewFormat(ImageFormat.NV21); camera.setParameters(params); camera.setDisplayOrientation(90); size = new Point(params.getPreviewSize().width, params.getPreviewSize().height); buffer = new byte[(int) (size.x * size.y * 1.5)]; try { camera.setPreviewDisplay(mHolder); camera.startPreview(); Log.d("CameraManager", "Camera open internal"); } catch (IOException e) { e.printStackTrace(); } postOpen = false; } public void stop() { mHolder.removeCallback(this); if (camera != null) { camera.stopPreview(); camera.release(); } } public void setOnStateChangeListener(OnStateChangeListener listener) { mStateListener = listener; } public void setOnPreviewCallback(OnPreviewCallback cb) { mCb = cb; if (camera != null) { camera.setPreviewCallbackWithBuffer(((data, camera1) -> { if (mCb != null) mCb.onPreview(buffer); })); } } public void addBuffer() { camera.addCallbackBuffer(buffer); } public Point getSize() { return size; } @Override public void surfaceCreated(SurfaceHolder holder) { // Do Nothing } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { surfaceReady = true; surfaceSize = new Point(width, height); if (postOpen) openInternal(); if (mStateListener != null) mStateListener.onStateChange(STATE_START); } @Override public void surfaceDestroyed(SurfaceHolder holder) { surfaceReady = false; stop(); if (mStateListener != null) mStateListener.onStateChange(STATE_STOP); } public interface OnStateChangeListener { void onStateChange(int state); } public interface OnPreviewCallback { void onPreview(byte[] buffer); } }
package com.emn.member.action; import java.util.Map; import com.emn.common.EmnAction; import com.emn.common.SqlMapConfig; import com.emn.common.SqlMapUsableObj; import com.emn.member.model.Member; import com.opensymphony.xwork2.ActionContext; public class ChangeBasicInfoAction extends EmnAction { private String memberId; private String memberName; private String memberEmail; public String getMemberId() { return memberId; } public void setMemberId(String memeberId) { this.memberId = memeberId; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getMemberEmail() { return memberEmail; } public void setMemberEmail(String memberEmail) { this.memberEmail = memberEmail; } @Override public String execute() throws Exception{ Member param = new Member(); param.setMemberId(memberId); param.setMemberName(memberName); param.setMemberEmail(memberEmail); SqlMapConfig.updateEmn("updateMember", param); ActionContext context = ActionContext.getContext(); Map<String, Object> session = context.getSession(); Member sessionMember = (Member) session.get("member"); sessionMember.setMemberId(memberId); sessionMember.setMemberName(memberName); sessionMember.setMemberEmail(memberEmail); sessionMember.setMemberPw(""); session.put("member",sessionMember); return SUCCESS; } }
package org.example.broker.core.converter; import org.example.broker.api.domain.Client; import org.example.broker.core.entity.ClientEntity; import org.springframework.stereotype.Component; @Component public class ClientConverter { public ClientEntity toEntity(Client client) { var entity = new ClientEntity(); entity.setTopic(client.getTopic()); entity.setUrl(client.getUrl()); return entity; } public Client fromEntity(ClientEntity entity) { var client = new Client(); client.setTopic(entity.getTopic()); client.setUrl(entity.getUrl()); return client; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.magapinv.www.reportes; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporter; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.engine.util.JRLoader; import net.sf.jasperreports.view.JasperViewer; /** * * @author mario */ public class Movimiento_Articulo { private Connection conexion; public final static String URL="jdbc:postgresql://192.168.185.2:5434/inventariobd"; public final static String DRIVER="org.postgresql.Driver"; public final static String USER="postgres"; public final static String PASS="Po$tgre$123"; public Movimiento_Articulo(){ try { Class.forName(DRIVER); conexion=DriverManager.getConnection(URL,USER,PASS); } catch (Exception ex) { } } public void ejecutarReporte_Estado_Articulo(String tipo, String nombre_bodega,String nombre_recibe, int producto, String cargo_funcionario) throws IOException { try { String master="C:\\reportes\\reporte_Movimiento_funcionarios.jasper"; System.out.println("master " + master); if (master == null) { System.out.println("No encuentro el reporte"); System.exit(2); } JasperReport masterReport = null; masterReport = (JasperReport) JRLoader.loadObject(master); Map<String,Object> parametro = new HashMap<String,Object>(); //parametro.clear(); parametro.put("tipo_movimiento", tipo); parametro.put("nombre_bodega", nombre_bodega); parametro.put("nombre_recibe", nombre_recibe); parametro.put("id_mov", producto); parametro.put("logo_izq", this.getClass().getResourceAsStream("/com/magapinv/www/interfacesmagap/recursos/LOGO_MAGAP_SSTRA.png")); parametro.put("logo_der", this.getClass().getResourceAsStream("/com/magapinv/www/interfacesmagap/recursos/LOGO_SSTRA1.png")); parametro.put("cargo_fucionario", cargo_funcionario); JasperPrint jasperPrint = JasperFillManager.fillReport(masterReport, parametro, conexion); JasperViewer jviewer = new JasperViewer(jasperPrint,false); jviewer.setVisible(true); JRExporter exporter = null; exporter = new JRPdfExporter(); Date date = new Date(); DateFormat hourdateFormat = new SimpleDateFormat("HH_mm_ss_dd_MM_yyyy"); JasperExportManager.exportReportToPdfFile(jasperPrint,"C:/informes/".concat(hourdateFormat.format(date))+".pdf"); } catch (JRException ex) { Logger.getLogger(Movimiento_Articulo.class.getName()).log(Level.SEVERE, null, ex); } } public void ejecutarReporte_Funcionario_Mensual(String cedula, Date fecha, Date fecha1, String nombre_bodega,String nombre_recibe,String cargo_funcionario_mensual) throws IOException { try { String dir_current = System.getProperty("user.dir") ; String master="C:\\reportes\\reporte_Movimiento_funcionarios.jasper"; System.out.println("master " + master); if (master == null) { System.out.println("No encuentro el reporte"); System.exit(2); } JasperReport masterReport = null; masterReport = (JasperReport) JRLoader.loadObject(master); Map<String,Object> parametro = new HashMap<String,Object>(); parametro.put("cedula", cedula); parametro.put("fechain", fecha); parametro.put("fechafin", fecha1); parametro.put("logo_izq", this.getClass().getResourceAsStream("/com/magapinv/www/interfacesmagap/recursos/LOGO_MAGAP_SSTRA.png")); parametro.put("logo_der", this.getClass().getResourceAsStream("/com/magapinv/www/interfacesmagap/recursos/LOGO_SSTRA1.png")); parametro.put("nombre_bodega", nombre_bodega); parametro.put("nombre_recibe", nombre_recibe); parametro.put("cargo_funcionario_mensual", cargo_funcionario_mensual); JasperPrint jasperPrint = JasperFillManager.fillReport(masterReport, parametro, conexion); JasperViewer jviewer = new JasperViewer(jasperPrint,false); jviewer.setVisible(true); } catch (JRException ex) { Logger.getLogger(Movimiento_Articulo.class.getName()).log(Level.SEVERE, null, ex); } } public void cerrar() { try { conexion.close(); } catch (SQLException ex) { ex.printStackTrace(); } } }
module com.mycompany.casecocher { requires javafx.controls; requires javafx.fxml; requires java.base; requires javafx.graphicsEmpty; opens com.mycompany.casecocher to javafx.fxml; exports com.mycompany.casecocher; }
package LeetCode.DynamicProgramming; public class HouseRobberII { public int rob(int[] nums){ if(nums.length == 0) return 0; if(nums.length == 1) return nums[0]; int m1 = max(nums, 0, nums.length - 1); int m2 = max(nums, 1, nums.length); return Math.max(m1, m2); } public int max(int[] nums, int s, int e){ int prev1 = 0, prev2 = 0; for(int i = s; i < e; i++){ int temp = prev1; prev1 = Math.max(prev2 + nums[i], prev1); prev2 = temp; } return prev1; } public static void main(String[] args){ HouseRobberII h = new HouseRobberII(); int[] nums = {1,2,3,1}; System.out.print(h.rob(nums)); } }
package pl.cwanix.opensun.authserver.server; import org.springframework.stereotype.Component; import lombok.RequiredArgsConstructor; import pl.cwanix.opensun.authserver.server.session.AuthServerSessionManager; import pl.cwanix.opensun.commonserver.packets.SUNPacketProcessorExecutor; import pl.cwanix.opensun.commonserver.server.SUNServerChannelHandler; import pl.cwanix.opensun.commonserver.server.SUNServerChannelHandlerFactory; @Component @RequiredArgsConstructor public class AuthServerChannelHandlerFactory implements SUNServerChannelHandlerFactory { private final SUNPacketProcessorExecutor packetProcessorExecutor; private final AuthServerSessionManager sessionManager; @Override public SUNServerChannelHandler getChannelHandler() { return new AuthServerChannelHandler(packetProcessorExecutor, sessionManager); } }
public class PhonePlan { int minutesAllowed; int minutesUsed; int dataAllowed; int dataUsed; boolean planType; public PhonePlan(int a, int d, boolean p) { minutesAllowed = a; dataAllowed = d; planType = p; minutesUsed = 0; dataUsed = 0; } public PhonePlan() { minutesAllowed = 0; dataAllowed = 0; planType = false; minutesUsed = 0; dataUsed = 0; } public int getMinutesAllowed() {return minutesAllowed;} public int getMinutesUsed() {return minutesUsed;} public int getDataAllowed() {return dataAllowed;} public int getDataUsed() {return dataUsed;} public boolean isPlanType() {return planType;} public void setMinutesAllowed(int a) {minutesAllowed = a;} public void setMinutesUsed(int u) {minutesUsed = u;} public void setDataAllowed(int d) {dataAllowed = d;} public void setDataUsed(int s) {dataUsed = s;} public void setPlanType(boolean p) {planType = p;} public int getMinutesRemaining() { int minremaining; if (minutesAllowed > minutesUsed || minutesAllowed < minutesUsed) { minremaining = minutesAllowed - minutesUsed; } else { minremaining = 0; } return minremaining; } public int getDataRemaining() { int dataremanining; if (dataAllowed > dataUsed || dataAllowed < dataUsed) { dataremanining = dataAllowed - dataUsed; } else { dataremanining = 0; }return dataremanining; } public String toString() { if(planType == false){ return ("Regular (" + minutesAllowed + " minute, " + (dataAllowed/1000000f) +"GB data)" + " Monthly Plan with " + getMinutesRemaining() + " minutes remaining and " + getDataRemaining() + "KB remaining" ); }else{ return("Pay-as-you-go Plan with " + getMinutesRemaining() + " minutes and " + getDataRemaining() + "KB remaining"); } } }
package com.myapp.model; public class Player { private String id; private Board board; public boolean fireMissile(Board board, Cell cell) { return board.attack(cell); } public Player(String id, Board board) { this.id = id; this.board = board; } public String getId() { return id; } public Board getBoard() { return board; } public boolean hasLost() { return board.hasNoShipRemaining(); } }
package com.yoeki.kalpnay.hrporatal.Profile.Model.user_info; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by IACE on 27-Sep-18. */ public class User { @SerializedName("status") @Expose public String status; @SerializedName("message") @Expose public String message; @SerializedName("BasicUserInfo") @Expose public List<BasicUserInfo> basicUserInfo = null; @SerializedName("UserBankDetail") @Expose public List<UserBankDetail> userBankDetail = null; @SerializedName("UserQualification") @Expose public List<UserQualification> userQualification = null; @SerializedName("UserCertification") @Expose public List<UserCertification> userCertification = null; @SerializedName("UserDependents") @Expose public List<UserDependent> userDependents = null; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<BasicUserInfo> getBasicUserInfo() { return basicUserInfo; } public void setBasicUserInfo(List<BasicUserInfo> basicUserInfo) { this.basicUserInfo = basicUserInfo; } public List<UserBankDetail> getUserBankDetail() { return userBankDetail; } public void setUserBankDetail(List<UserBankDetail> userBankDetail) { this.userBankDetail = userBankDetail; } public List<UserQualification> getUserQualification() { return userQualification; } public void setUserQualification(List<UserQualification> userQualification) { this.userQualification = userQualification; } public List<UserCertification> getUserCertification() { return userCertification; } public void setUserCertification(List<UserCertification> userCertification) { this.userCertification = userCertification; } public List<UserDependent> getUserDependents() { return userDependents; } public void setUserDependents(List<UserDependent> userDependents) { this.userDependents = userDependents; } }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; import com.tencent.mm.plugin.appbrand.s$l; public final class ll extends a { public String bTi; public String hyz; public String knE; public String lMV; public String lMW; public String lMX; public String pnv; public String pnw; public String qwz; public String rfQ; public String rfR; public String rfX; public String rfY; public String rfZ; public String roO; public String roP; public String roQ; public String roR; public String roS; public String roT; public String roU; public String roV; public String roW; public String roX; public String roY; public String roZ; public String rpA; public long rpB; public String rpC; public String rpD; public int rpE; public int rpF; public int rpG; public String rpa; public String rpb; public String rpc; public String rpd; public int rpe; public String rpf; public String rpg; public String rph; public String rpi; public String rpj; public String rpk; public String rpl; public String rpm; public String rpn; public String rpo; public String rpp; public String rpq; public String rpr; public String rps; public String rpt; public int rpu; public int rpv; public String rpw; public String rpx; public String rpy; public String rpz; protected final int a(int i, Object... objArr) { int h; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; if (this.roO != null) { aVar.g(1, this.roO); } if (this.pnv != null) { aVar.g(2, this.pnv); } if (this.knE != null) { aVar.g(3, this.knE); } if (this.pnw != null) { aVar.g(4, this.pnw); } if (this.lMV != null) { aVar.g(5, this.lMV); } if (this.rfX != null) { aVar.g(6, this.rfX); } if (this.roP != null) { aVar.g(7, this.roP); } if (this.roQ != null) { aVar.g(8, this.roQ); } if (this.lMW != null) { aVar.g(9, this.lMW); } if (this.rfY != null) { aVar.g(10, this.rfY); } if (this.roR != null) { aVar.g(11, this.roR); } if (this.roS != null) { aVar.g(12, this.roS); } if (this.roT != null) { aVar.g(13, this.roT); } if (this.roU != null) { aVar.g(14, this.roU); } if (this.roV != null) { aVar.g(15, this.roV); } if (this.bTi != null) { aVar.g(16, this.bTi); } if (this.roW != null) { aVar.g(17, this.roW); } if (this.roX != null) { aVar.g(18, this.roX); } if (this.roY != null) { aVar.g(19, this.roY); } if (this.roZ != null) { aVar.g(20, this.roZ); } if (this.rpa != null) { aVar.g(21, this.rpa); } if (this.lMX != null) { aVar.g(22, this.lMX); } if (this.rpb != null) { aVar.g(23, this.rpb); } if (this.rpc != null) { aVar.g(24, this.rpc); } if (this.rpd != null) { aVar.g(25, this.rpd); } if (this.qwz != null) { aVar.g(26, this.qwz); } aVar.fT(27, this.rpe); if (this.rpf != null) { aVar.g(28, this.rpf); } if (this.rpg != null) { aVar.g(29, this.rpg); } if (this.rph != null) { aVar.g(30, this.rph); } if (this.rpi != null) { aVar.g(31, this.rpi); } if (this.rpj != null) { aVar.g(32, this.rpj); } if (this.rpk != null) { aVar.g(33, this.rpk); } if (this.rpl != null) { aVar.g(34, this.rpl); } if (this.rfZ != null) { aVar.g(35, this.rfZ); } if (this.rpm != null) { aVar.g(36, this.rpm); } if (this.rpn != null) { aVar.g(37, this.rpn); } if (this.rpo != null) { aVar.g(38, this.rpo); } if (this.rpp != null) { aVar.g(39, this.rpp); } if (this.rpq != null) { aVar.g(40, this.rpq); } if (this.rpr != null) { aVar.g(41, this.rpr); } if (this.rps != null) { aVar.g(42, this.rps); } if (this.rpt != null) { aVar.g(43, this.rpt); } aVar.fT(44, this.rpu); aVar.fT(45, this.rpv); if (this.rpw != null) { aVar.g(46, this.rpw); } if (this.hyz != null) { aVar.g(47, this.hyz); } if (this.rpx != null) { aVar.g(48, this.rpx); } if (this.rfQ != null) { aVar.g(49, this.rfQ); } if (this.rfR != null) { aVar.g(50, this.rfR); } if (this.rpy != null) { aVar.g(51, this.rpy); } if (this.rpz != null) { aVar.g(52, this.rpz); } if (this.rpA != null) { aVar.g(53, this.rpA); } aVar.T(54, this.rpB); if (this.rpC != null) { aVar.g(55, this.rpC); } if (this.rpD != null) { aVar.g(56, this.rpD); } aVar.fT(57, this.rpE); aVar.fT(58, this.rpF); aVar.fT(59, this.rpG); return 0; } else if (i == 1) { if (this.roO != null) { h = f.a.a.b.b.a.h(1, this.roO) + 0; } else { h = 0; } if (this.pnv != null) { h += f.a.a.b.b.a.h(2, this.pnv); } if (this.knE != null) { h += f.a.a.b.b.a.h(3, this.knE); } if (this.pnw != null) { h += f.a.a.b.b.a.h(4, this.pnw); } if (this.lMV != null) { h += f.a.a.b.b.a.h(5, this.lMV); } if (this.rfX != null) { h += f.a.a.b.b.a.h(6, this.rfX); } if (this.roP != null) { h += f.a.a.b.b.a.h(7, this.roP); } if (this.roQ != null) { h += f.a.a.b.b.a.h(8, this.roQ); } if (this.lMW != null) { h += f.a.a.b.b.a.h(9, this.lMW); } if (this.rfY != null) { h += f.a.a.b.b.a.h(10, this.rfY); } if (this.roR != null) { h += f.a.a.b.b.a.h(11, this.roR); } if (this.roS != null) { h += f.a.a.b.b.a.h(12, this.roS); } if (this.roT != null) { h += f.a.a.b.b.a.h(13, this.roT); } if (this.roU != null) { h += f.a.a.b.b.a.h(14, this.roU); } if (this.roV != null) { h += f.a.a.b.b.a.h(15, this.roV); } if (this.bTi != null) { h += f.a.a.b.b.a.h(16, this.bTi); } if (this.roW != null) { h += f.a.a.b.b.a.h(17, this.roW); } if (this.roX != null) { h += f.a.a.b.b.a.h(18, this.roX); } if (this.roY != null) { h += f.a.a.b.b.a.h(19, this.roY); } if (this.roZ != null) { h += f.a.a.b.b.a.h(20, this.roZ); } if (this.rpa != null) { h += f.a.a.b.b.a.h(21, this.rpa); } if (this.lMX != null) { h += f.a.a.b.b.a.h(22, this.lMX); } if (this.rpb != null) { h += f.a.a.b.b.a.h(23, this.rpb); } if (this.rpc != null) { h += f.a.a.b.b.a.h(24, this.rpc); } if (this.rpd != null) { h += f.a.a.b.b.a.h(25, this.rpd); } if (this.qwz != null) { h += f.a.a.b.b.a.h(26, this.qwz); } h += f.a.a.a.fQ(27, this.rpe); if (this.rpf != null) { h += f.a.a.b.b.a.h(28, this.rpf); } if (this.rpg != null) { h += f.a.a.b.b.a.h(29, this.rpg); } if (this.rph != null) { h += f.a.a.b.b.a.h(30, this.rph); } if (this.rpi != null) { h += f.a.a.b.b.a.h(31, this.rpi); } if (this.rpj != null) { h += f.a.a.b.b.a.h(32, this.rpj); } if (this.rpk != null) { h += f.a.a.b.b.a.h(33, this.rpk); } if (this.rpl != null) { h += f.a.a.b.b.a.h(34, this.rpl); } if (this.rfZ != null) { h += f.a.a.b.b.a.h(35, this.rfZ); } if (this.rpm != null) { h += f.a.a.b.b.a.h(36, this.rpm); } if (this.rpn != null) { h += f.a.a.b.b.a.h(37, this.rpn); } if (this.rpo != null) { h += f.a.a.b.b.a.h(38, this.rpo); } if (this.rpp != null) { h += f.a.a.b.b.a.h(39, this.rpp); } if (this.rpq != null) { h += f.a.a.b.b.a.h(40, this.rpq); } if (this.rpr != null) { h += f.a.a.b.b.a.h(41, this.rpr); } if (this.rps != null) { h += f.a.a.b.b.a.h(42, this.rps); } if (this.rpt != null) { h += f.a.a.b.b.a.h(43, this.rpt); } h = (h + f.a.a.a.fQ(44, this.rpu)) + f.a.a.a.fQ(45, this.rpv); if (this.rpw != null) { h += f.a.a.b.b.a.h(46, this.rpw); } if (this.hyz != null) { h += f.a.a.b.b.a.h(47, this.hyz); } if (this.rpx != null) { h += f.a.a.b.b.a.h(48, this.rpx); } if (this.rfQ != null) { h += f.a.a.b.b.a.h(49, this.rfQ); } if (this.rfR != null) { h += f.a.a.b.b.a.h(50, this.rfR); } if (this.rpy != null) { h += f.a.a.b.b.a.h(51, this.rpy); } if (this.rpz != null) { h += f.a.a.b.b.a.h(52, this.rpz); } if (this.rpA != null) { h += f.a.a.b.b.a.h(53, this.rpA); } h += f.a.a.a.S(54, this.rpB); if (this.rpC != null) { h += f.a.a.b.b.a.h(55, this.rpC); } if (this.rpD != null) { h += f.a.a.b.b.a.h(56, this.rpD); } return ((h + f.a.a.a.fQ(57, this.rpE)) + f.a.a.a.fQ(58, this.rpF)) + f.a.a.a.fQ(59, this.rpG); } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) { if (!super.a(aVar2, this, h)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; ll llVar = (ll) objArr[1]; switch (((Integer) objArr[2]).intValue()) { case 1: llVar.roO = aVar3.vHC.readString(); return 0; case 2: llVar.pnv = aVar3.vHC.readString(); return 0; case 3: llVar.knE = aVar3.vHC.readString(); return 0; case 4: llVar.pnw = aVar3.vHC.readString(); return 0; case 5: llVar.lMV = aVar3.vHC.readString(); return 0; case 6: llVar.rfX = aVar3.vHC.readString(); return 0; case 7: llVar.roP = aVar3.vHC.readString(); return 0; case 8: llVar.roQ = aVar3.vHC.readString(); return 0; case 9: llVar.lMW = aVar3.vHC.readString(); return 0; case 10: llVar.rfY = aVar3.vHC.readString(); return 0; case 11: llVar.roR = aVar3.vHC.readString(); return 0; case 12: llVar.roS = aVar3.vHC.readString(); return 0; case 13: llVar.roT = aVar3.vHC.readString(); return 0; case 14: llVar.roU = aVar3.vHC.readString(); return 0; case 15: llVar.roV = aVar3.vHC.readString(); return 0; case 16: llVar.bTi = aVar3.vHC.readString(); return 0; case 17: llVar.roW = aVar3.vHC.readString(); return 0; case 18: llVar.roX = aVar3.vHC.readString(); return 0; case 19: llVar.roY = aVar3.vHC.readString(); return 0; case 20: llVar.roZ = aVar3.vHC.readString(); return 0; case 21: llVar.rpa = aVar3.vHC.readString(); return 0; case 22: llVar.lMX = aVar3.vHC.readString(); return 0; case 23: llVar.rpb = aVar3.vHC.readString(); return 0; case 24: llVar.rpc = aVar3.vHC.readString(); return 0; case 25: llVar.rpd = aVar3.vHC.readString(); return 0; case 26: llVar.qwz = aVar3.vHC.readString(); return 0; case 27: llVar.rpe = aVar3.vHC.rY(); return 0; case s$l.AppCompatTheme_actionModeCloseButtonStyle /*28*/: llVar.rpf = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_actionModeBackground /*29*/: llVar.rpg = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_actionModeSplitBackground /*30*/: llVar.rph = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_actionModeCloseDrawable /*31*/: llVar.rpi = aVar3.vHC.readString(); return 0; case 32: llVar.rpj = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_actionModeCopyDrawable /*33*/: llVar.rpk = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_actionModePasteDrawable /*34*/: llVar.rpl = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_actionModeSelectAllDrawable /*35*/: llVar.rfZ = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_actionModeShareDrawable /*36*/: llVar.rpm = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_actionModeFindDrawable /*37*/: llVar.rpn = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_actionModeWebSearchDrawable /*38*/: llVar.rpo = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_actionModePopupWindowStyle /*39*/: llVar.rpp = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_textAppearanceLargePopupMenu /*40*/: llVar.rpq = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_textAppearanceSmallPopupMenu /*41*/: llVar.rpr = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_dialogTheme /*42*/: llVar.rps = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_dialogPreferredPadding /*43*/: llVar.rpt = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_listDividerAlertDialog /*44*/: llVar.rpu = aVar3.vHC.rY(); return 0; case s$l.AppCompatTheme_actionDropDownStyle /*45*/: llVar.rpv = aVar3.vHC.rY(); return 0; case s$l.AppCompatTheme_dropdownListPreferredItemHeight /*46*/: llVar.rpw = aVar3.vHC.readString(); return 0; case 47: llVar.hyz = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_homeAsUpIndicator /*48*/: llVar.rpx = aVar3.vHC.readString(); return 0; case 49: llVar.rfQ = aVar3.vHC.readString(); return 0; case 50: llVar.rfR = aVar3.vHC.readString(); return 0; case 51: llVar.rpy = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_selectableItemBackground /*52*/: llVar.rpz = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_selectableItemBackgroundBorderless /*53*/: llVar.rpA = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_borderlessButtonStyle /*54*/: llVar.rpB = aVar3.vHC.rZ(); return 0; case s$l.AppCompatTheme_dividerVertical /*55*/: llVar.rpC = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_dividerHorizontal /*56*/: llVar.rpD = aVar3.vHC.readString(); return 0; case s$l.AppCompatTheme_activityChooserViewStyle /*57*/: llVar.rpE = aVar3.vHC.rY(); return 0; case s$l.AppCompatTheme_toolbarStyle /*58*/: llVar.rpF = aVar3.vHC.rY(); return 0; case s$l.AppCompatTheme_toolbarNavigationButtonStyle /*59*/: llVar.rpG = aVar3.vHC.rY(); return 0; default: return -1; } } } }
package controller.command.impl; import controller.command.Command; import controller.constants.FrontConstants; import controller.constants.Messages; import controller.constants.PathJSP; import controller.exception.ServiceLayerException; import controller.service.RouteService; import controller.service.ServiceFactory; import controller.service.impl.ServiceFactoryImpl; import domain.Route; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; public class SearchCommand implements Command { private ServiceFactory serviceFactory; private RouteService routeService; public SearchCommand() { serviceFactory = ServiceFactoryImpl.getInstance(); routeService = serviceFactory.getRouteService(); } @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServiceLayerException { String departure = request.getParameter(FrontConstants.DEPARTURE_CITY); String arrival = request.getParameter(FrontConstants.ARRIVAL_CITY); if (!departure.isEmpty() && !arrival.isEmpty()) { List<Route> routes = routeService.searchByCriteria(departure, arrival); if (routes.isEmpty()) { request.setAttribute(FrontConstants.MESSAGE, Messages.NO_RESULTS_FOR_CRITERIA); return PathJSP.INDEX_PAGE; } else { request.setAttribute(FrontConstants.LIST, routes); return PathJSP.ROUTES_PAGE; } } request.setAttribute(FrontConstants.MESSAGE, Messages.INCORRECT_INPUT); return PathJSP.INDEX_PAGE; } }
package com.lfd.day0120_04_news; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; import com.lfd.day0120_04_news.adapter.NewsAdapter; import com.lfd.day0120_04_news.bean.News; import com.lfd.day0120_04_news.utils.NetUtils; public class MainActivity extends Activity { private ListView lv = null; private List<News> newsList = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.lv); new Thread(new Runnable() { @Override public void run() { newsList = NetUtils.loadData("http://10.0.2.2/news.xml"); runOnUiThread(new Runnable() { @Override public void run() { lv.setAdapter(new NewsAdapter(MainActivity.this,newsList)); } }); } }).start(); } }
package com.danvarga.msscbrewery.web.mappers; import com.danvarga.msscbrewery.domain.Beer; import com.danvarga.msscbrewery.web.model.BeerDto; import org.mapstruct.Mapper; // Set to use the custom DateMapper. @Mapper(uses = DateMapper.class) public interface BeerMapper { BeerDto beerToBeerDto(Beer beer); Beer beerDtoToBeer(BeerDto dto); }
package com.issp.ispp.entity; import java.util.*; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Pattern; import org.hibernate.annotations.ColumnDefault; import org.hibernate.validator.constraints.Length; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @Entity public class Usuario implements UserDetails { /** * */ private static final long serialVersionUID = 1L; @Id @Column(name = "user_id") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(unique = true) @Length(max=50) @NotEmpty(message = "Debes introducir un UserName") private String username; @NotEmpty(message = "Debes escribir una contraseña") @Pattern(regexp = "^(?=.{8,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$", message = "La contraseña debe tener al menos 8 caracteres,un dígito,una minúscula y una mayúscula.") private String password; @ColumnDefault(value = "true") private boolean isEnabled; @Email(message = "Debes introducir un email váildo") @NotEmpty(message = "Debes introducir un email") private String email; @OneToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) private DatosAdicionalesUsuario datosAdicionales; @Enumerated(EnumType.STRING) private Roles rol; @ColumnDefault(value = "true") private boolean TerminosAceptados; public boolean isTerminosAceptados() { return TerminosAceptados; } public void setTerminosAceptados(boolean terminosAceptados) { TerminosAceptados = terminosAceptados; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public DatosAdicionalesUsuario getDatosAdicionales() { return datosAdicionales; } public void setDatosAdicionales(DatosAdicionalesUsuario datosAdicionales) { this.datosAdicionales = datosAdicionales; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return isEnabled; } public void setEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> roles = new ArrayList<>(); roles.add(new SimpleGrantedAuthority(rol.toString())); return roles; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Roles getRol() { return rol; } public void setRol(Roles rol) { this.rol = rol; } }
package be.cylab.mark.detection; import be.cylab.mark.core.ClientWrapperInterface; import be.cylab.mark.core.DetectionAgentInterface; import be.cylab.mark.core.DetectionAgentProfile; import be.cylab.mark.core.Event; /** * Dummy detection agent, which does not try to read or write to the datastore. * Can be used to test activation, without starting a complete server. * @author Thibault Debatty */ public class DummyDetector implements DetectionAgentInterface { private static final int SLEEP_TIME = 500; @Override public void analyze( final Event event, final DetectionAgentProfile profile, final ClientWrapperInterface datastore) throws Throwable { Thread.sleep(SLEEP_TIME); } }
package ufc.br.so.services; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import ufc.br.so.memory.Page; import ufc.br.so.programs.Program; public class DateTimeService extends Program { public DateTimeService() { this.setName("datetime"); this.setSize(2); this.setDescription("datetime - get the current date and time"); } @Override public void execute() { List<Page> busyPages = this.setBusyPages(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime())); freePages(busyPages); } }
package game; import states.GameState; import states.MenuState; import states.StateManager; import java.awt.*; import java.awt.image.BufferStrategy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; // Removed the arguments from Game() and moved them directly into the GameState class, allowing change and manipulation only in the GameState class // AleksandarTanev public class Game implements Runnable { double fps = 30; double timePerTick = 1_000_000_000 / fps; double delta = 0; long now; long lastTime = System.nanoTime(); private Thread thread; private boolean isRunning; public Game() { this.isRunning = false; } private void init() { //--->>Setting the starting state to be the GameState. The starting state in the future will be changed to MenuState() // AleksandarTanev //StateManager.setState(new GameState("Tetris", 456, 553)); StateManager.setState(new MenuState()); } private void tick() { if (!InputHandler.pause) { StateManager.getState().tick(); } } private void render() { // Running the tick() and render() of the current set state - at the moment we have only the GameState active // AleksandarTanev StateManager.getState().render(); } @Override public void run() { this.init(); while (isRunning) { now = System.nanoTime(); delta += (now - lastTime) / timePerTick; lastTime = now; if (delta >= 1) { this.tick(); this.render(); delta = 0; } } this.stop(); } public synchronized void start() { if (!this.isRunning) { this.isRunning = true; this.thread = new Thread(this); this.thread.start(); } } public synchronized void stop() { if (this.isRunning) { try { this.isRunning = false; this.thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package test.springsandbox.annotations; import java.util.Random; import org.springframework.stereotype.Component; @Component public class RandomFortuneService implements FortuneService { private String[] data = { "Random 1", "Random 2", "Random 3" }; private Random random = new Random(); @Override public String getFortune() { int index = random.nextInt(data.length); return data[index] + " fortune service"; } }
package com.company.tests; import com.company.pages.BoardsPageHelper; import com.company.pages.HomePageHelper; import com.company.pages.LoginPageHelper; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class LoginTests extends TestBase { // HomePageHelper homePage; LoginPageHelper loginPage; BoardsPageHelper boardsPage; @BeforeMethod public void initTests() { // homePage = PageFactory.initElements(driver, HomePageHelper.class); loginPage = PageFactory.initElements(driver, LoginPageHelper.class); boardsPage = PageFactory.initElements(driver, BoardsPageHelper.class); homePage.waitUntilPageIsLoaded(); // wait for "Log in" is clickable ON THE HOMEPAGE loginPage .openPage() // wait for "Log in" ON THE HOMEPAGE is clickable + find and click on "Log in" .waitUntilPageIsLoaded(); // wait for "Log in" is clickable ON THE LOG IN PAGE BEFORE EMAIL & PASSWORD FIELDS FILLING } @Test public void negativeLogin() { // loginPage.fillInEmailField("romuska"); // loginPage.fillInPasswordField("gromuska"); // loginPage.submitLoginNotAtlassian(); loginPage.LoginNotAttl("romuska", "gromuska"); //this method replaces 3 methods above Assert.assertEquals(loginPage.getErrorMessage(), "There isn't an account for this username", "The error message isn't correct"); } @Test public void positiveLogin() { // loginPage.fillInEmailField(LOGIN); // loginPage.pressLoginAsAttlButton(); // loginPage.fillInPasswordAttl(PASSWORD); // loginPage.submitLoginAttl(); // press Atlassian log in button loginPage.loginAttl(LOGIN, PASSWORD); //this method replaces 4 methods above boardsPage.waitUntilPageIsLoaded(); // wait for "Boards" button is clickable Assert.assertEquals(boardsPage.getBoardsButtonName(),"Boards", "Name of the button isn't 'Boards'"); } }
package com.example.monapplicationtd3.presentation.model.view; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.example.monapplicationtd3.R; import com.example.monapplicationtd3.Singletons; import com.example.monapplicationtd3.data.PokeRepository; import com.example.monapplicationtd3.presentation.model.Natures; import com.example.monapplicationtd3.presentation.model.controller.MainController; import java.util.List; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private ListAdapter mAdapter; private RecyclerView.LayoutManager layoutManager; private MainController controller; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); controller = new MainController( this, Singletons.getGson(), Singletons.getSharedPreferences(getApplicationContext()) ); controller.onStart(); } public void showList(final List<Natures> naturesList) { recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setHasFixedSize(true); // use a linear layout manager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); recyclerView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); // define an adapter mAdapter = new ListAdapter(naturesList, new ListAdapter.OnItemClickListener() { @Override public void onItemClick(Natures item) { controller.onItemClick(item); } }); recyclerView.setAdapter(mAdapter); ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { naturesList.remove(viewHolder.getAdapterPosition()); mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition()); } }; ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); itemTouchHelper.attachToRecyclerView(recyclerView); } public void showError() { Toast.makeText(this , "API Error", Toast.LENGTH_SHORT).show(); } public void navigateToDetails(Natures natures) { Intent myIntent = new Intent(MainActivity.this, DetailActivity.class); myIntent.putExtra("naturesKey", Singletons.getGson().toJson(natures)); MainActivity.this.startActivity(myIntent); } }