text
stringlengths
10
2.72M
package com.tt.miniapp.activity; import android.app.Activity; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.WindowManager; import android.widget.FrameLayout; import com.tt.miniapp.ImmersedStatusBarHelper; import com.tt.miniapp.manager.SnapshotManager; import com.tt.miniapp.process.AppProcessManager; import com.tt.miniapp.process.bridge.InnerMiniAppProcessBridge; import com.tt.miniapp.thread.ThreadUtil; import com.tt.miniapp.util.ActivityUtil; import com.tt.miniapp.util.BaseNavBarUtils; import com.tt.miniapp.util.DevicesUtil; import com.tt.miniapphost.AppBrandLogger; import com.tt.miniapphost.host.HostDependManager; import com.tt.miniapphost.process.callback.IpcCallback; import com.tt.miniapphost.process.data.CrossProcessDataEntity; import com.tt.miniapphost.process.helper.AsyncIpcHandler; import com.tt.miniapphost.util.DebugUtil; import com.tt.miniapphost.util.ProcessUtil; import com.tt.miniapphost.util.UIUtils; import com.tt.miniapphost.view.BaseActivity; public class OpenSchemaMiddleActivity extends BaseActivity { @Deprecated public static final String PARAMS_CLASS_NAME = "class_name"; private boolean mAddSecureFlag = false; private Runnable mAutoShowMiniAppRunnable = new Runnable() { public void run() { OpenSchemaMiddleActivity.this.tryShowMiniAppActivity(); } }; public boolean mFirstResume = true; public String mFromAppId; private boolean mFromAppInHostStack; private boolean mFromMiniGame = false; public IpcCallback mGetSnapshotIpcCallback; public String mLaunchFlag; public final Object mMeasureLock = new Object(); public boolean mMovingMiniAppActivity; public boolean mTriggerResumeWhenNewShow; public Runnable mUpdateSnapshotRunnable; private void configWindow() { if (this.mFromMiniGame) { requestWindowFeature(1); getWindow().setFlags(1024, 1024); getWindow().setSoftInputMode(16); if (DevicesUtil.hasNotchInScreen((Context)this)) DevicesUtil.setFullScreenWindowLayoutInDisplayCutout(getWindow()); if (Build.VERSION.SDK_INT >= 28) { WindowManager.LayoutParams layoutParams = getWindow().getAttributes(); layoutParams.layoutInDisplayCutoutMode = 1; getWindow().setAttributes(layoutParams); } BaseNavBarUtils.hideNavigation((Activity)this); ActivityUtil.setFullScreen((Activity)this); return; } ImmersedStatusBarHelper immersedStatusBarHelper = new ImmersedStatusBarHelper((Activity)this, new ImmersedStatusBarHelper.ImmersedStatusBarConfig()); immersedStatusBarHelper.setup(true); immersedStatusBarHelper.setUseLightStatusBarInternal(true); } private void generateSnapShotView(String paramString) { final View contentView = new View((Context)this); view.setBackgroundColor(-1); setContentView(view); view.setOnClickListener(new View.OnClickListener() { public void onClick(View param1View) { if (OpenSchemaMiddleActivity.this.mTriggerResumeWhenNewShow) { AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "点击快照视图跳回小程序页面 mFromAppId:", this.this$0.mFromAppId }); OpenSchemaMiddleActivity.this.showMiniAppActivityOnFront(); } } }); AppProcessManager.ProcessInfo processInfo = AppProcessManager.getProcessInfoByAppId(paramString); if (processInfo == null) { AppBrandLogger.e("OpenSchemaMiddleActivity", new Object[] { "获取触发 openSchema 的小程序进程信息异常" }); return; } this.mGetSnapshotIpcCallback = new IpcCallback() { public void onIpcCallback(CrossProcessDataEntity param1CrossProcessDataEntity) { AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "收到小程序进程快照回调" }); finishListenIpcCallback(); if (param1CrossProcessDataEntity != null) { String str = param1CrossProcessDataEntity.getString("snapshot"); } else { param1CrossProcessDataEntity = null; } if (TextUtils.isEmpty((CharSequence)param1CrossProcessDataEntity)) { AppBrandLogger.e("OpenSchemaMiddleActivity", new Object[] { "小程序进程快照回调中不包含快照信息" }); return; } try { if (contentView.getHeight() == 0) synchronized (OpenSchemaMiddleActivity.this.mMeasureLock) { OpenSchemaMiddleActivity.this.forceMeasureContentView(contentView); OpenSchemaMiddleActivity.this.mMeasureLock.wait(); } int i = contentView.getWidth(); int j = contentView.getHeight(); final BitmapDrawable snapshotDrawable = SnapshotManager.getSnapshotDrawableFromFile(OpenSchemaMiddleActivity.this.getResources(), (String)param1CrossProcessDataEntity, i, j); AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "生成快照视图" }); OpenSchemaMiddleActivity.this.mUpdateSnapshotRunnable = new Runnable() { public void run() { AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "设置页面快照" }); contentView.setBackground((Drawable)snapshotDrawable); } }; ThreadUtil.runOnUIThread(OpenSchemaMiddleActivity.this.mUpdateSnapshotRunnable); } catch (Exception exception) { AppBrandLogger.eWithThrowable("OpenSchemaMiddleActivity", "setSnapshotAsBackground", exception); } OpenSchemaMiddleActivity.this.mGetSnapshotIpcCallback = null; } public void onIpcConnectError() { OpenSchemaMiddleActivity.this.mGetSnapshotIpcCallback = null; } }; InnerMiniAppProcessBridge.getSnapshot(processInfo.mProcessIdentity, this.mGetSnapshotIpcCallback); } private boolean isOpenSchemaInCurrentStack() { return "currentTask".equalsIgnoreCase(this.mLaunchFlag); } private boolean isSchemaPageInHostStack() { return "newTask".equalsIgnoreCase(this.mLaunchFlag); } private boolean openSchema() { boolean bool1; boolean bool2; String str1 = getIntent().getStringExtra("schema"); String str2 = getIntent().getStringExtra("args"); AsyncIpcHandler asyncIpcHandler = ProcessUtil.generateAsyncIpcHandlerFromUri(Uri.parse(str1)); if (HostDependManager.getInst().openSchema((Context)this, str1) || HostDependManager.getInst().openSchema((Context)this, str1, str2)) { if (HostDependManager.getInst().isEnableOpenSchemaAnimation()) overridePendingTransition(UIUtils.getSlideInAnimation(), 2131034242); bool2 = true; bool1 = false; } else { bool2 = false; bool1 = true; } if (asyncIpcHandler != null) { asyncIpcHandler.callback(CrossProcessDataEntity.Builder.create().put("openSchemaResult", Boolean.valueOf(bool2)).put("openSchemaFailType", Integer.valueOf(bool1)).build()); } else { DebugUtil.outputError("OpenSchemaMiddleActivity", new Object[] { "asyncIpcHandler ==null" }); } AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "openSchema schema:", str1, "openSchemaSuccess:", Boolean.valueOf(bool2) }); return bool2; } public void finishCurrentActivity() { if (isFinishing()) return; AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "finishCurrentActivity mFromAppId:", this.mFromAppId }); if (ActivityUtil.isTaskSingleActivity((Activity)this)) { finishAndRemoveTask(); return; } finish(); } public void forceMeasureContentView(final View contentView) { AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "forceMeasureContentView" }); ThreadUtil.runOnUIThread(new Runnable() { public void run() { FrameLayout frameLayout = (FrameLayout)OpenSchemaMiddleActivity.this.getWindow().getDecorView(); contentView.measure(View.MeasureSpec.makeMeasureSpec(frameLayout.getMeasuredWidth(), -2147483648), View.MeasureSpec.makeMeasureSpec(frameLayout.getMeasuredHeight(), -2147483648)); synchronized (OpenSchemaMiddleActivity.this.mMeasureLock) { OpenSchemaMiddleActivity.this.mMeasureLock.notifyAll(); return; } } }); } public void onBackPressed() { AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "onBackPressed" }); tryShowMiniAppActivity(); } public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "onCreate" }); this.mLaunchFlag = getIntent().getStringExtra("launch_flag"); this.mFromAppId = getIntent().getStringExtra("from_app_id"); this.mFromAppInHostStack = getIntent().getBooleanExtra("is_from_app_in_host_stack", this.mFromAppInHostStack); this.mFromMiniGame = getIntent().getBooleanExtra("is_game", false); configWindow(); if (!openSchema()) { tryShowMiniAppActivity(); } else { ThreadUtil.runOnUIThread(this.mAutoShowMiniAppRunnable, 5000L); } generateSnapShotView(this.mFromAppId); } public void onDestroy() { super.onDestroy(); AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "onDestroy" }); if (this.mAddSecureFlag) getWindow().clearFlags(8192); ThreadUtil.cancelUIRunnable(this.mUpdateSnapshotRunnable); ThreadUtil.cancelUIRunnable(this.mAutoShowMiniAppRunnable); IpcCallback ipcCallback = this.mGetSnapshotIpcCallback; if (ipcCallback != null) { ipcCallback.finishListenIpcCallback(); this.mGetSnapshotIpcCallback = null; } } public void onEnterAnimationComplete() { super.onEnterAnimationComplete(); if (this.mTriggerResumeWhenNewShow) { AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "onEnterAnimationComplete tryShowMiniAppActivity mFromAppId:", this.mFromAppId }); tryShowMiniAppActivity(); } } public void onPause() { super.onPause(); AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "onPause" }); ThreadUtil.cancelUIRunnable(this.mAutoShowMiniAppRunnable); if (isSchemaPageInHostStack()) ThreadUtil.runOnUIThread(new Runnable() { public void run() { OpenSchemaMiddleActivity.this.finishCurrentActivity(); } }, 300L); } public void onResume() { super.onResume(); AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "onResume" }); if (this.mFromMiniGame) ActivityUtil.setFullScreen((Activity)this); if (this.mFirstResume) { this.mFirstResume = false; return; } this.mTriggerResumeWhenNewShow = true; getWindow().addFlags(8192); this.mAddSecureFlag = true; ThreadUtil.runOnUIThread(new Runnable() { public void run() { AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "onResume tryShowMiniAppActivity mFromAppId:", this.this$0.mFromAppId }); OpenSchemaMiddleActivity.this.tryShowMiniAppActivity(); } }500L); } public void onStop() { super.onStop(); AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "onStop" }); } public void showMiniAppActivityOnFront() { AppBrandLogger.d("OpenSchemaMiddleActivity", new Object[] { "showMiniAppActivityOnFront mFromAppId:", this.mFromAppId }); if (!isOpenSchemaInCurrentStack() && !isSchemaPageInHostStack() && !this.mFromAppInHostStack) { this.mMovingMiniAppActivity = ActivityUtil.moveMiniAppActivityToFront((Activity)this, this.mFromAppId); AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "moveMiniAppActivityToFront mFromAppId:", this.mFromAppId }); } finishCurrentActivity(); if (!this.mMovingMiniAppActivity) ActivityUtil.changeToSilentHideActivityAnimation((Activity)this); } public void tryShowMiniAppActivity() { if (this.mMovingMiniAppActivity || isFinishing()) { AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "tryShowMiniAppActivity mMovingMiniAppActivity || isFinishing()" }); return; } long l = System.currentTimeMillis(); if (ActivityUtil.isActivityAtHostStackTop((Activity)this)) showMiniAppActivityOnFront(); AppBrandLogger.i("OpenSchemaMiddleActivity", new Object[] { "tryShowMiniAppActivity duration:", Long.valueOf(System.currentTimeMillis() - l) }); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\activity\OpenSchemaMiddleActivity.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
/* * Copyright (c) 2010-2011 by Jan Stender, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.mrc.operations; import org.xtreemfs.foundation.TimeSync; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno; import org.xtreemfs.mrc.MRCRequest; import org.xtreemfs.mrc.MRCRequestDispatcher; import org.xtreemfs.mrc.UserException; import org.xtreemfs.mrc.ac.FileAccessManager; import org.xtreemfs.mrc.database.AtomicDBUpdate; import org.xtreemfs.mrc.database.StorageManager; import org.xtreemfs.mrc.database.VolumeManager; import org.xtreemfs.mrc.metadata.FileMetadata; import org.xtreemfs.mrc.utils.MRCHelper; import org.xtreemfs.mrc.utils.Path; import org.xtreemfs.mrc.utils.PathResolver; import org.xtreemfs.pbrpc.generatedinterfaces.MRC; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.setattrRequest; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.timestampResponse; /** * Sets attributes of a file. * * @author stender, bjko */ public class SetattrOperation extends MRCOperation { public SetattrOperation(MRCRequestDispatcher master) { super(master); } @Override public void startRequest(MRCRequest rq) throws Throwable { final setattrRequest rqArgs = (setattrRequest) rq.getRequestArgs(); final VolumeManager vMan = master.getVolumeManager(); final FileAccessManager faMan = master.getFileAccessManager(); validateContext(rq); Path p = new Path(rqArgs.getVolumeName(), rqArgs.getPath()); StorageManager sMan = vMan.getStorageManagerByName(p.getComp(0)); PathResolver res = new PathResolver(sMan, p); // check whether the path prefix is searchable faMan.checkSearchPermission(sMan, res, rq.getDetails().userId, rq.getDetails().superUser, rq .getDetails().groupIds); // check whether file exists res.checkIfFileDoesNotExist(); // retrieve and prepare the metadata to return FileMetadata file = res.getFile(); int time = 0; // determine which attributes to set boolean setMode = (rqArgs.getToSet() & MRC.Setattrs.SETATTR_MODE.getNumber()) == MRC.Setattrs.SETATTR_MODE .getNumber(); boolean setUID = (rqArgs.getToSet() & MRC.Setattrs.SETATTR_UID.getNumber()) == MRC.Setattrs.SETATTR_UID .getNumber(); boolean setGID = (rqArgs.getToSet() & MRC.Setattrs.SETATTR_GID.getNumber()) == MRC.Setattrs.SETATTR_GID .getNumber(); boolean setSize = (rqArgs.getToSet() & MRC.Setattrs.SETATTR_SIZE.getNumber()) == MRC.Setattrs.SETATTR_SIZE .getNumber(); boolean setAtime = (rqArgs.getToSet() & MRC.Setattrs.SETATTR_ATIME.getNumber()) == MRC.Setattrs.SETATTR_ATIME .getNumber(); boolean setCtime = (rqArgs.getToSet() & MRC.Setattrs.SETATTR_CTIME.getNumber()) == MRC.Setattrs.SETATTR_CTIME .getNumber(); boolean setMtime = (rqArgs.getToSet() & MRC.Setattrs.SETATTR_MTIME.getNumber()) == MRC.Setattrs.SETATTR_MTIME .getNumber(); boolean setAttributes = (rqArgs.getToSet() & MRC.Setattrs.SETATTR_ATTRIBUTES.getNumber()) == MRC.Setattrs.SETATTR_ATTRIBUTES .getNumber(); AtomicDBUpdate update = sMan.createAtomicDBUpdate(master, rq); // if MODE bit is set, peform 'chmod' if (setMode) { // check whether the access mode may be changed faMan.checkPrivilegedPermissions(sMan, file, rq.getDetails().userId, rq.getDetails().superUser, rq.getDetails().groupIds); // change the access mode; only bits 0-12 may be changed faMan.setPosixAccessMode(sMan, file, res.getParentDirId(), rq.getDetails().userId, rq .getDetails().groupIds, (file.getPerms() & 0xFFFFF000) | (rqArgs.getStbuf().getMode() & 0xFFF), rq.getDetails().superUser, update); // update POSIX timestamps if (time == 0) time = (int) (TimeSync.getGlobalTime() / 1000); MRCHelper.updateFileTimes(res.getParentDirId(), file, false, true, false, sMan, time, update); } // if USER_ID or GROUP_ID are set, perform 'chown' if (setUID || setGID) { // check whether the owner may be changed if (setUID) { // if a UID is supposed to be set, check if the operation needs // to be restricted to root users byte[] value = sMan.getXAttr(1, StorageManager.SYSTEM_UID, "xtreemfs." + MRCHelper.VOL_ATTR_PREFIX + ".chown_non_root"); // check permission if (value != null && new String(value).equals("true")) { faMan.checkPrivilegedPermissions(sMan, file, rq.getDetails().userId, rq.getDetails().superUser, rq.getDetails().groupIds); } else if (!rq.getDetails().superUser) throw new UserException(POSIXErrno.POSIX_ERROR_EPERM, "changing owners is restricted to superusers"); } if (setGID) { // if a GID is provided, restrict the op to a privileged // user that is either root or in the group that is supposed to // be assigned faMan.checkPrivilegedPermissions(sMan, file, rq.getDetails().userId, rq.getDetails().superUser, rq.getDetails().groupIds); if (!(rq.getDetails().superUser || rq.getDetails().groupIds.contains(rqArgs.getStbuf() .getGroupId()))) throw new UserException( POSIXErrno.POSIX_ERROR_EPERM, "changing owning groups is restricted to superusers or file owners who are in the group that is supposed to be assigned"); } // change owner and owning group file.setOwnerAndGroup(setUID ? rqArgs.getStbuf().getUserId() : file.getOwnerId(), setGID ? rqArgs .getStbuf().getGroupId() : file.getOwningGroupId()); // update POSIX timestamps if (time == 0) time = (int) (TimeSync.getGlobalTime() / 1000); MRCHelper.updateFileTimes(res.getParentDirId(), file, false, true, false, sMan, time, update); } // if SIZE bit is set, peform 'xtreemfs_updateFileSize' if (setSize) { long newFileSize = rqArgs.getStbuf().getSize(); int epochNo = rqArgs.getStbuf().getTruncateEpoch(); // only accept valid file size updates if (epochNo >= file.getEpoch()) { boolean epochChanged = epochNo > file.getEpoch(); // accept any file size in a new epoch but only larger file // sizes in // the current epoch if (epochChanged || newFileSize > file.getSize()) { long oldFileSize = file.getSize(); if (time == 0) time = (int) (TimeSync.getGlobalTime() / 1000); file.setSize(newFileSize); file.setEpoch(epochNo); file.setCtime(time); file.setMtime(time); if (epochChanged) sMan.setMetadata(file, FileMetadata.RC_METADATA, update); // update the volume size sMan.getVolumeInfo().updateVolumeSize(newFileSize - oldFileSize, update); } else if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.proc, this, "received update for outdated file size: " + newFileSize + ", current file size=" + file.getSize()); } else { if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.proc, this, "received file size update w/ outdated epoch: " + epochNo + ", current epoch=" + file.getEpoch()); } } // if ATIME, CTIME or MTIME bits are set, peform 'utimens' if (setAtime || setCtime || setMtime) { // check whether write permissions are granted to file // faMan.checkPermission("w", sMan, file, res.getParentDirId(), // rq.getDetails().userId, rq // .getDetails().superUser, rq.getDetails().groupIds); if (setAtime) file.setAtime((int) (rqArgs.getStbuf().getAtimeNs() / (long) 1e9)); if (setCtime) file.setCtime((int) (rqArgs.getStbuf().getCtimeNs() / (long) 1e9)); if (setMtime) file.setMtime((int) (rqArgs.getStbuf().getMtimeNs() / (long) 1e9)); } // if ATTRIBUTES bit is set, peform 'setattr' for Win32 attributes if (setAttributes) { // check whether write permissions are granted to the parent // directory faMan.checkPermission("w", sMan, file, res.getParentDirId(), rq.getDetails().userId, rq .getDetails().superUser, rq.getDetails().groupIds); file.setW32Attrs(rqArgs.getStbuf().getAttributes()); } if (setUID || setGID || setAttributes) sMan.setMetadata(file, FileMetadata.RC_METADATA, update); if (setAtime || setCtime || setMtime || setSize) sMan.setMetadata(file, FileMetadata.FC_METADATA, update); // set the response rq.setResponse(timestampResponse.newBuilder().setTimestampS(time).build()); update.execute(); } }
package com.parrello.tvseries.subs.ws; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import javax.jws.WebService; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Collection; import java.util.Date; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * Created by nicola on 27/11/14. */ @WebService(endpointInterface = "com.parrello.tvseries.subs.ws.OpenSubtitlesDownloaderService") public class OpenSubtitlesDownloaderServiceImplementation implements OpenSubtitlesDownloaderService { private static final String SUBS_SEARCH_URL = "http://www.opensubtitles.org/en/search/tag-"; private static final String LANG_PARAM = "/sublanguageid-"; private static final String SUBS_DOWNLOAD_URL = "http://dl.opensubtitles.org/en/download/sub/"; private static final String TMP_ZIP_FILE_NAME = "tmp.zip"; private static final String TRANSMISSION_DOWNLOADS_FOLDER = "TRANSMISSION_DOWNLOADS_FOLDER"; public OpenSubtitlesDownloaderServiceImplementation() {} @Override public void getSubtitles(String finalFileName, String language) { String id = this.getDownloadUrl(finalFileName, language); String subDownloadUrl = SUBS_DOWNLOAD_URL + id; try { System.out.println("[" + new Date(System.currentTimeMillis()) + "]: Getting subtitles for " + finalFileName + ".."); this.downloadFromUrl(new URL(subDownloadUrl), TRANSMISSION_DOWNLOADS_FOLDER + TMP_ZIP_FILE_NAME); this.unzipFunction(TRANSMISSION_DOWNLOADS_FOLDER + TMP_ZIP_FILE_NAME, TRANSMISSION_DOWNLOADS_FOLDER, finalFileName); this.deleteFiles(); } catch (IOException e) { e.printStackTrace(); } } public String getDownloadUrl(String videoFileName, String language) { String subId = null; try { String requestString = SUBS_SEARCH_URL + URLEncoder.encode(videoFileName, "UTF-8") + LANG_PARAM + language; System.out.println("[" + new Date(System.currentTimeMillis()) + "]: Sending " + requestString); Document resultPage = Jsoup.connect(requestString).get(); Elements results = resultPage.select("td.sb_star_even"); results.addAll(resultPage.select("td.sb_star_odd")); subId = results.first().id().substring(4); } catch (IOException e) { e.printStackTrace(); } return subId; } public void downloadFromUrl(URL url, String localFilename) throws IOException { InputStream is = null; FileOutputStream fos = null; try { URLConnection urlConn = url.openConnection();//connect is = urlConn.getInputStream(); //get connection inputstream fos = new FileOutputStream(localFilename); //open outputstream to local file byte[] buffer = new byte[4096]; //declare 4KB buffer int len; //while we have availble data, continue downloading and storing to local file while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } catch (Exception e) { System.out.println("[" + new Date(System.currentTimeMillis()) + "]: Download error: " + e.getMessage()); } finally { try { if (is != null) { is.close(); } } finally { if (fos != null) { fos.close(); } } } } public void unzipFunction(String pathToUpdateZip, String destinationPath, String finalFileName){ byte[] byteBuffer = new byte[1024]; try{ ZipInputStream inZip = new ZipInputStream(new FileInputStream(pathToUpdateZip)); ZipEntry inZipEntry = inZip.getNextEntry(); while(inZipEntry != null){ String fileName = inZipEntry.getName(); File unZippedFile = new File(destinationPath + File.separator + fileName); if (inZipEntry.isDirectory()){ unZippedFile.mkdirs(); }else{ new File(unZippedFile.getParent()).mkdirs(); unZippedFile.createNewFile(); FileOutputStream unZippedFileOutputStream = new FileOutputStream(unZippedFile); int length; while((length = inZip.read(byteBuffer)) > 0){ unZippedFileOutputStream.write(byteBuffer,0,length); } unZippedFileOutputStream.close(); if (!unZippedFile.getName().endsWith(".nfo")) { this.renameSubtitlesFile(unZippedFile, finalFileName); } } inZipEntry = inZip.getNextEntry(); } inZip.close(); }catch(IOException e){ e.printStackTrace(); } } public void renameSubtitlesFile(File file, String newName) { file.renameTo(new File(TRANSMISSION_DOWNLOADS_FOLDER + newName + ".srt")); } public void deleteFiles() { FileUtils.deleteQuietly(new File(TRANSMISSION_DOWNLOADS_FOLDER + TMP_ZIP_FILE_NAME)); Collection<File> nfoFiles = FileUtils.listFiles(new File(TRANSMISSION_DOWNLOADS_FOLDER), new WildcardFileFilter("*.nfo"), null); for (File nfoFile : nfoFiles) { FileUtils.deleteQuietly(nfoFile); } } }
package com.ysyt.to.response; import com.response.CommonResponse; import com.ysyt.bean.AttributeOptions; public class AttributeOptionResponse extends CommonResponse { private AttributeOptions attributeOptions; public AttributeOptions getAttributeOptions() { return attributeOptions; } public void setAttributeOptions(AttributeOptions attributeOptions) { this.attributeOptions = attributeOptions; } }
package me.mani.clhub.listener; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; /** * @author Overload * @version 1.0 */ public class EntityDamageListener implements Listener { @EventHandler public void onEntityDamage(EntityDamageEvent event) { event.setCancelled(true); if (event.getCause() == EntityDamageEvent.DamageCause.VOID) { event.getEntity().teleport(Bukkit.getWorld("world").getSpawnLocation()); } } }
package lintcode; /** * 中位数 * * @author zhoubo * @create 2017-11-02 16:26 */ public class L80 { public int median(int[] nums) { int len = nums.length; selectSort(nums); if (0 == len % 2) { return nums[len / 2 - 1]; } else { return nums[len / 2]; } } public void bubbleSort(int[] a) { int n = a.length; for (int i = 0; i < a.length; i++) { for (int j = n - i - 1; j > 0; j--) { if (a[j] < a[j - 1]) { int tmp = a[j]; a[j] = a[j - 1]; a[j - 1] = tmp; } } } for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } public void selectSort(int[] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a.length; j++) { if (a[i] < a[j]) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } } } } public void quickSort(int[] a) { int len = a.length; int i = 0; int j = len - 1; int key = a[0]; for (int k = 0; k < a.length; k++) { quickSort(a, 0, len - 1, a[k]); } } public void quickSort(int[] a, int start, int end, int key) { if (start == end) { return; } int i = start; int j = end; while (i != j) { for (; j >= start; j--) { if (a[j] < key) { int tmp = a[j]; a[j] = key; key = tmp; break; } } for (; i <= end; i++) { if (a[i] > key) { int tmp = a[i]; a[i] = key; key = tmp; break; } } } } }
import util.*; public class notepad { }
package com.sietecerouno.atlantetransportador.adapters; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.sietecerouno.atlantetransportador.R; import com.sietecerouno.atlantetransportador.manager.Manager; import com.sietecerouno.atlantetransportador.utils.CustomObj; import java.util.ArrayList; /** * Created by MAURICIO on 6/04/17. */ public class AdapterMenu extends BaseAdapter { private Context activity; private LayoutInflater inflater; private ArrayList<CustomObj> objects; public AdapterMenu(Context activity, ArrayList<CustomObj> retoObjects) { this.activity = activity; this.objects = retoObjects; } @Override public int getCount() { return objects.size(); } @Override public Object getItem(int location) { return objects.get(location); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (inflater == null) inflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView == null) convertView = inflater.inflate(R.layout.row_menu, null); TextView titulo = (TextView) convertView.findViewById(R.id.text_menu); titulo.setText(objects.get(position).name); ImageView icon = (ImageView) convertView.findViewById(R.id.icon); Glide.with(icon.getContext()) .load(objects.get(position).valueInt) .into(icon); return convertView; } }
package de.codingchallenge.model; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = SingleChoiceQuestionType.class, name = SingleChoiceQuestionType.TYPE_NAME), @JsonSubTypes.Type(value = NumberRangeQuestionType.class, name = NumberRangeQuestionType.TYPE_NAME), @JsonSubTypes.Type(value = SingleChoiceConditionalQuestionType.class, name = SingleChoiceConditionalQuestionType.TYPE_NAME), }) public interface QuestionType { String getQuestionType(); }
package com.smxknife.springboot._07_jsonserializable; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; /** * @author smxknife * 2021/8/1 */ public class StatusJsonSerializable extends JsonSerializer<Integer> { @Override public void serialize(Integer integer, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { switch (integer) { case 1: jsonGenerator.writeString("One"); break; case 2: jsonGenerator.writeString("Two"); break; default: jsonGenerator.writeString("Other"); } } }
package controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.bson.types.ObjectId; import model.Account; import model.Comment; import model.Post; @WebServlet(name = "vote", urlPatterns = { "/vote" }) public class voteController extends HttpServlet { private static final long serialVersionUID = 1L; public voteController() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); if (Account.isLogged(request.getCookies())== false) { String url = "/login"; response.sendRedirect(request.getContextPath() + url); return; } ObjectId id = new ObjectId(request.getParameter("id")); String type = request.getParameter("type"); int point = Integer.parseInt((String)request.getParameter("point")); if (type.equals("COMMENT")) { Comment.Vote(id, point); } else if (type.equals("POST")) { Post.Vote(id, point); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package mx.com.alex.crazycards.models; import android.content.Context; import android.graphics.drawable.Drawable; import java.util.ArrayList; import mx.com.alex.crazycards.R; /** * Created by mobilestudio06 on 11/08/15. */ public class OptionMenu { private Drawable ico; private String nameOption; public OptionMenu(Drawable ico, String nameOption) { this.ico = ico; this.nameOption = nameOption; } public Drawable getIco() { return ico; } public void setIco(Drawable ico) { this.ico = ico; } public String getNameOption() { return nameOption; } public void setNameOption(String nameOption) { this.nameOption = nameOption; } public static ArrayList<OptionMenu> getMenu(Context context){ ArrayList<OptionMenu> option = new ArrayList<OptionMenu>(); option.add(new OptionMenu(context.getResources().getDrawable(R.mipmap.ic_home),context.getString(R.string.menu_home))); option.add(new OptionMenu(context.getResources().getDrawable(R.mipmap.ic_home),context.getString(R.string.menu_play))); option.add(new OptionMenu(context.getResources().getDrawable(R.mipmap.ic_home),context.getString(R.string.menu_follow))); option.add(new OptionMenu(context.getResources().getDrawable(R.mipmap.ic_home),context.getString(R.string.menu_logout))); return option; } }
package bl; import android.database.sqlite.SQLiteDatabase; import org.json.simple.parser.ParseException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import library.common.clsHelper; import library.common.linkAPI; import library.common.mUserRoleData; import library.common.mconfigData; import library.dal.clsHardCode; import library.dal.enumConfigData; import library.dal.mUserRoleDA; import library.dal.mconfigDA; public class mUserRoleBL extends clsMainBL { public mUserRoleData getIntUserID() { this.db = getDb(); List<mUserRoleData> listData; mUserRoleDA _mUserRoleDA=new mUserRoleDA(db); listData=_mUserRoleDA.getAllData(db); // if (listData.size()==0){ // listData=_tUserLoginDA.getAllData(db); // } db.close(); return listData.get(0); } public List<mUserRoleData> GetAllData(){ SQLiteDatabase db=getDb(); List<mUserRoleData> listData; mUserRoleDA _mUserRoleDA=new mUserRoleDA(db); listData=_mUserRoleDA.getAllData(db); db.close(); return listData; } public List<mUserRoleData> getRole(String username) throws ParseException { SQLiteDatabase _db = getDb(); mconfigDA _mconfigDA = new mconfigDA(_db); String strVal2; mconfigData dataAPI = _mconfigDA.getData(db, enumConfigData.ApiKalbe.getidConfigData()); strVal2 = dataAPI.get_txtValue(); if (dataAPI.get_txtValue().equals("")) { strVal2 = dataAPI.get_txtDefaultValue(); } clsHelper _help = new clsHelper(); linkAPI dtlinkAPI = new linkAPI(); String txtMethod = "GetAllMWebUserRoleByUserName"; dtlinkAPI.set_txtMethod(txtMethod); dtlinkAPI.set_txtParam(username); dtlinkAPI.set_txtToken(new clsHardCode().txtTokenAPI); String strLinkAPI = dtlinkAPI.QueryString(strVal2); String JsonData; List<mUserRoleData> Listdata = new ArrayList<>(); try { JsonData = _help.ResultJsonData(_help.getHTML(strLinkAPI)); org.json.simple.JSONArray JsonArray = _help.ResultJsonArray(JsonData); Iterator i = JsonArray.iterator(); SQLiteDatabase db = getDb(); mUserRoleDA _mUserRoleDA = new mUserRoleDA(db); _mUserRoleDA.DeleteAllDataMConfig(db); while (i.hasNext()) { org.json.simple.JSONObject innerObj = (org.json.simple.JSONObject) i.next(); Long IntResult = (Long) innerObj.get("_pboolValid"); if(IntResult==1){ mUserRoleData _data = new mUserRoleData(); int index = _mUserRoleDA.getContactsCount(db) + 1; _data.set_intId(String.valueOf(index)); _data.set_intRoleId(String.valueOf(innerObj.get("IntRoleID"))); _data.set_txtUserId(String.valueOf(innerObj.get("IntUserID"))); _data.set_txtRoleName(String.valueOf(innerObj.get("TxtRoleName"))); _mUserRoleDA.SaveDataMConfig(db, _data); Listdata.add(_data); } else { mUserRoleData _data = new mUserRoleData(); _data.set_intId(String.valueOf(innerObj.get("_pboolValid"))); _data.set_intRoleId(String.valueOf(innerObj.get("IntRoleID"))); _data.set_txtUserId(String.valueOf(innerObj.get("IntUserID"))); _data.set_txtRoleName(String.valueOf(innerObj.get("_pstrMessage"))); Listdata.add(_data); } } return Listdata; } catch (Exception e) { e.printStackTrace(); } return Listdata; } // // public List<mUserRoleData> getRoleAndOutlet(String username,String versionApp) throws ParseException{ // List<mUserRoleData> Listdata=new ArrayList<mUserRoleData>(); // linkAPI dtlinkAPI=new linkAPI(); // String txtMethod="GetAllUserRoleByUserNameSalesInsentivePostData"; // JSONObject resJson = new JSONObject(); // resJson.put("username", username); // dtlinkAPI.set_txtMethod(txtMethod); // //dtlinkAPI.set_txtParam(username); // dtlinkAPI.set_txtToken(new clsHardCode().txtTokenAPI); // dtlinkAPI.set_txtVesion(versionApp); // String strLinkAPI= dtlinkAPI.QueryString(getLinkAPI()); // APIData dtAPIDATA=new APIData(); // clsHelper _clsHelper=new clsHelper(); // String JsonData= _clsHelper.pushtData(strLinkAPI,String.valueOf(resJson), Integer.valueOf(getBackGroundServiceOnline())); // org.json.simple.JSONArray JsonArray= _clsHelper.ResultJsonArray(JsonData); // Iterator i = JsonArray.iterator(); // SQLiteDatabase db=getDb(); // mUserRoleDA _mUserRoleDA=new mUserRoleDA(db); // _mUserRoleDA.DeleteAllDataMConfig(db); // // mEmployeeAreaDA _mEmployeeAreaDA = new mEmployeeAreaDA(db); // _mEmployeeAreaDA.DeleteAllDataMConfig(db); // // while (i.hasNext()) { // org.json.simple.JSONObject innerObj = (org.json.simple.JSONObject) i.next(); // // int boolValid= Integer.valueOf(String.valueOf( innerObj.get(dtAPIDATA.boolValid))); // if(boolValid == Integer.valueOf(new clsHardCode().intSuccess)){ // // org.json.simple.JSONArray JsonArray_role= _clsHelper.ResultJsonArray(String.valueOf(innerObj.get("ListMWebUserRoleAPI"))); // Iterator j = JsonArray_role.iterator(); // // while(j.hasNext()){ // org.json.simple.JSONObject innerObj_detail = (org.json.simple.JSONObject) j.next(); // mUserRoleData _data =new mUserRoleData(); // int index=_mUserRoleDA.getContactsCount(db)+1; // _data.set_intId(String.valueOf(index)); // _data.set_intRoleId(String.valueOf(innerObj_detail.get("IntRoleID"))); // _data.set_txtUserId(String.valueOf(innerObj_detail.get("IntUserID"))); // _data.set_txtRoleName(String.valueOf(innerObj_detail.get("TxtRoleName"))); // _mUserRoleDA.SaveDataMConfig(db, _data); // Listdata.add(_data); // } // // org.json.simple.JSONArray JsonArray_outlet = _clsHelper.ResultJsonArray(String.valueOf(innerObj.get("Listvw_SalesInsentive_EmployeeAreaData"))); // Iterator k = JsonArray_outlet.iterator(); // // while(k.hasNext()){ // org.json.simple.JSONObject innerObj_detail = (org.json.simple.JSONObject) k.next(); // mEmployeeAreaData _data =new mEmployeeAreaData(); // int index=_mEmployeeAreaDA.getContactsCount(db)+1; // _data.set_intID(String.valueOf(index)); // _data.set_intBranchId(String.valueOf(innerObj_detail.get("IntBranchId"))); // _data.set_intChannelId(String.valueOf(innerObj_detail.get("IntChannelId"))); // _data.set_intEmployeeId(String.valueOf(innerObj_detail.get("IntEmployeeId"))); // _data.set_intOutletId(String.valueOf(innerObj_detail.get("IntOutletId"))); // _data.set_intRayonId(String.valueOf(innerObj_detail.get("IntRayonId"))); // _data.set_intRegionId(String.valueOf(innerObj_detail.get("IntRegionId"))); // _data.set_txtBranchCode(String.valueOf(innerObj_detail.get("TxtBranchCode"))); // _data.set_txtBranchName(String.valueOf(innerObj_detail.get("TxtBranchName"))); // _data.set_txtName(String.valueOf(innerObj_detail.get("TxtName"))); // _data.set_txtNIK(String.valueOf(innerObj_detail.get("TxtNIK"))); // _data.set_txtOutletCode(String.valueOf(innerObj_detail.get("TxtOutletCode"))); // _data.set_txtOutletName(String.valueOf(innerObj_detail.get("TxtOutletName"))); // _data.set_txtRayonCode(String.valueOf(innerObj_detail.get("TxtRayonCode"))); // _data.set_txtRayonName(String.valueOf(innerObj_detail.get("TxtRayonName"))); // _data.set_txtRegionName(String.valueOf(innerObj_detail.get("TxtRegionName"))); // // //_mEmployeeAreaDA.SaveDataMConfig(db, _data); // } // } // } // return Listdata; // } }
package com.lupan.HeadFirstDesignMode.chapter4_factory.common; /** * TODO * * @author lupan * @version 2016/3/21 0021 */ public enum PizzaType { PIZZA_TYPE1("披萨1"), PIZZA_TYPE2("披萨2"), PIZZA_TYPE3("披萨3"), PIZZA_TYPE4("披萨4"); private final String value; PizzaType(String value) { this.value = value; } public String getValue() { return value; } }
package com.bowlong.objpool; import com.bowlong.util.StrBuilder; public class StrBufPool extends AbstractQueueObjPool<StrBuilder> { public static final StrBufPool POOL = new StrBufPool(); public StrBufPool() { } public StrBufPool(int num) { for (int i = 0; i < num; i++) { returnObj(createObj()); } } @Override public final StrBuilder createObj() { StrBuilder obj = new StrBuilder(); obj.pool = this; return obj; } @Override public final StrBuilder resetObj(StrBuilder obj) { obj.setLength(0); return obj; } @Override public final StrBuilder destoryObj(StrBuilder obj) { obj.setLength(0); obj.pool = null; return obj; } public static final StrBuilder borrowObject() { return POOL.borrow(); } public static final void returnObject(StrBuilder obj) { POOL.returnObj(obj); } }
package com.jp.link.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.jp.commom.result.ResultHandle; import com.jp.commom.util.UUidUtil; import com.jp.link.biz.LinkBiz; import com.jp.link.po.LinkPo; @Controller public class LinkController { @Resource private LinkBiz biz; @RequestMapping(value="/addLinkPo.do") public @ResponseBody ResultHandle addLinkPo(LinkPo po){ ResultHandle result=new ResultHandle(); if(po.getLink_id()==null||po.getLink_id().equals("")){ po.setLink_id(UUidUtil.getUUid()); } try{ int num=biz.addLinkPo(po); if(num>0){ result.setCode("0"); result.setMessage("新增成功!"); }else{ result.setCode("1"); result.setMessage("新增失败!"); } }catch (Exception e){ result.setCode("1"); result.setMessage("新增失败!"); e.printStackTrace(); } return result; } @RequestMapping(value="/deleteLinkPo.do") public @ResponseBody ResultHandle deleteLinkPo(LinkPo po){ ResultHandle result=new ResultHandle(); try{ int num=biz.deleteLinkPo(po); if(num>0){ result.setCode("0"); result.setMessage("删除成功!"); }else{ result.setCode("1"); result.setMessage("删除失败!"); } }catch (Exception e){ result.setCode("1"); result.setMessage("删除失败!"); } return result; } @RequestMapping(value="/getLinkList.do") public @ResponseBody List<LinkPo> getList(LinkPo po){ return biz.getList(po); } }
package com.example.android.notepad.memento; /** * Created by smaug(Qiuzhonghao) on 2017/5/18. * 该天习得备忘录模式,故: * 该部分参考备忘录模式 目的在于可实现笔记输入过程中的撤销。 * 源工程中已经含有撤销功能,但是只是针对于一次性撤销,即将该日记重置为打开前的状态 * 我想实现的撤销在于可以记录你的每一次“点击保存”前的状态,这样在写长文本日记的时候比较方便,不用一步推倒,重新来过。 * 代码已经完全实现,但是未整合到源工程中,先放着吧。 */ public class Memento { private String text; private int cursor; public String getText() { return text; } public void setText(String text) { this.text = text; } public int getCursor() { return cursor; } public void setCursor(int cursor) { this.cursor = cursor; } }
package yincheng.gggithub.view.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.CompoundButton; import android.widget.RadioButton; import yincheng.gggithub.R; /** * Created by yincheng on 2018/6/13/12:24. * github:luoyincheng */ public class FilterRadioButton extends CompoundButton { public FilterRadioButton(Context context) { this(context, null); } public FilterRadioButton(Context context, AttributeSet attrs) { this(context, attrs, R.attr.radioButtonStyle); } public FilterRadioButton(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public FilterRadioButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override public void toggle() { if (!isChecked()) { super.toggle(); } else { setChecked(false); } } @Override public CharSequence getAccessibilityClassName() { return RadioButton.class.getName(); } }
package processamento; public class Processamento { public static void main(String[] args) { //Exemplo1 /* int x, y; x = 5; y = 2 * x; System.out.println(x); System.out.println(y); */ //Exemplo2 /* int x; double y; x = 5; y = 2 * x; System.out.println(x); System.out.println(y); */ //Exemplo3 /* double b, B, h, area; b = 6.0; B = 8.0; h = 5.0; area = (b + B) / 2.0 * h; System.out.println(area); */ //Exemplo4 /* int a, b; double resultado; a = 5; b = 2; //resultado = a/b; //Expressao com dois números inteiros //Apresenta como resultado = 2.0 //O compilador da resultado inteiro ele trunca o resultado //para fazer com que ele apresente o resultado sem truncar //Realizamos um casting resultado = (double) a/b; //Agora o resultado é 2.5 System.out.println(resultado); */ //Exemplo5 - passando valores de tipos diferentes double a; int b; a = 5.0; //b = a; temos que realizar um cast para int senao apresenta erro b = (int) a; System.out.println(b); } }
package 数组; import java.lang.reflect.Array; import java.util.Arrays; //给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。 // //  // //示例 1: // //输入:nums1 = [1,3], nums2 = [2] //输出:2.00000 //解释:合并数组 = [1,2,3] ,中位数 2 //示例 2: // //输入:nums1 = [1,2], nums2 = [3,4] //输出:2.50000 //解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5 //示例 3: // //输入:nums1 = [0,0], nums2 = [0,0] //输出:0.00000 //示例 4: // //输入:nums1 = [], nums2 = [1] //输出:1.00000 //示例 5: // //输入:nums1 = [2], nums2 = [] //输出:2.00000 // //链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays public class FindMedianSortedArrays_04 { public static double findMedianSortedArrays(int[] nums1 ,int[] nums2) { double result ; int[] a = new int[nums1.length+nums2.length] ; int b = 0 ; for (int item : nums1) { a[b] = item; b++; } for (int value : nums2) { a[b] = value; b++; } Arrays.sort(a); int temp = a.length/2; if (a.length%2 == 0) { result = (double) (a[temp]+a[temp-1])/2; } else { result = a[temp]; } return result; } public static void main(String[] args) { int[] a ={1,3}; int[] b = {2}; System.out.println(FindMedianSortedArrays_04.findMedianSortedArrays(a, b)); } }
package com.elvarg.world.entity.combat.magic; import java.util.Optional; import com.elvarg.engine.task.Task; import com.elvarg.engine.task.TaskManager; import com.elvarg.world.entity.impl.Character; import com.elvarg.world.entity.impl.npc.NPC; import com.elvarg.world.model.Animation; import com.elvarg.world.model.Graphic; import com.elvarg.world.model.Projectile; /** * A {@link Spell} implementation used for combat related spells. * * @author lare96 */ public abstract class CombatSpell extends Spell { @Override public void startCast(Character cast, Character castOn) { int castAnimation = -1; NPC npc = cast.isNpc() ? ((NPC)cast) : null; /*if(npc != null) { if(npc.getId() == 3496 || npc.getId() == 6278 || npc.getId() == 2000 || npc.getId() == 109 || npc.getId() == 3580 || npc.getId() == 2007) { castAnimation = npc.getDefinition().getAttackAnim(); } }*/ if(castAnimation().isPresent() && castAnimation == -1) { castAnimation().ifPresent(cast::performAnimation); } else { cast.performAnimation(new Animation(castAnimation)); } // Then send the starting graphic. if(npc != null) { if(npc.getId() != 2000 && npc.getId() != 109 && npc.getId() != 3580 && npc.getId() != 2007) { startGraphic().ifPresent(cast::performGraphic); } } else { startGraphic().ifPresent(cast::performGraphic); } // Finally send the projectile after two ticks. castProjectile(cast, castOn).ifPresent(g -> { //g.sendProjectile(); TaskManager.submit(new Task(2, cast, false) { @Override public void execute() { g.sendProjectile(); this.stop(); } }); }); } public int getAttackSpeed() { int speed = 5; final CombatSpell spell = this; if(spell instanceof CombatAncientSpell) { if(spell == CombatSpells.SMOKE_RUSH.getSpell() || spell == CombatSpells.SHADOW_RUSH.getSpell() || spell == CombatSpells.BLOOD_RUSH.getSpell() || spell == CombatSpells.ICE_RUSH.getSpell() || spell == CombatSpells.SMOKE_BLITZ.getSpell() || spell == CombatSpells.SHADOW_BLITZ.getSpell() || spell == CombatSpells.BLOOD_BLITZ.getSpell() || spell == CombatSpells.ICE_BLITZ.getSpell()) { speed = 4; } } return speed; } /** * The fixed ID of the spell implementation as recognized by the protocol. * * @return the ID of the spell, or <tt>-1</tt> if there is no ID for this * spell. */ public abstract int spellId(); /** * The maximum hit an {@link Character} can deal with this spell. * * @return the maximum hit able to be dealt with this spell implementation. */ public abstract int maximumHit(); /** * The animation played when the spell is cast. * * @return the animation played when the spell is cast. */ public abstract Optional<Animation> castAnimation(); /** * The starting graphic played when the spell is cast. * * @return the starting graphic played when the spell is cast. */ public abstract Optional<Graphic> startGraphic(); /** * The projectile played when this spell is cast. * * @param cast * the entity casting the spell. * @param castOn * the entity targeted by the spell. * * @return the projectile played when this spell is cast. */ public abstract Optional<Projectile> castProjectile(Character cast, Character castOn); /** * The ending graphic played when the spell hits the victim. * * @return the ending graphic played when the spell hits the victim. */ public abstract Optional<Graphic> endGraphic(); /** * Fired when the spell hits the victim. * * @param cast * the entity casting the spell. * @param castOn * the entity targeted by the spell. * @param accurate * if the spell was accurate. * @param damage * the amount of damage inflicted by this spell. */ public abstract void finishCast(Character cast, Character castOn, boolean accurate, int damage); }
package ru.windwail.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import ru.windwail.entity.Customer; import ru.windwail.repository.CustomerRepository; import java.util.ArrayList; import java.util.Collection; import java.util.List; @RestController public class CustomerController { @Autowired CustomerRepository repository; @RequestMapping(value = "/customers", method = RequestMethod.GET, produces = "application/json") public List<Customer> customers() { List<Customer> customers = new ArrayList<>(); repository.findAll().forEach(x -> customers.add(x)); return customers; } @RequestMapping(value = "/data", method = RequestMethod.GET, produces = "application/json") public List<String> data() { List<String> data = new ArrayList<>(); data.add("This"); data.add("data"); data.add("is"); data.add("from"); data.add("server!"); return data; } }
package rhtn_homework; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class BOJ_17822_원판_돌리기 { private static StringBuilder sb = new StringBuilder(); private static int N,M,T; private static int[][] dart; private static int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}}; private static List<Pair> rmList; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); T = Integer.parseInt(st.nextToken()); dart = new int[N][M]; rmList = new ArrayList<>(); for (int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < M; j++) { dart[i][j] = Integer.parseInt(st.nextToken()); } } for (int t = 0; t < T; t++) { st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()); int d = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); rotate(x, d, k); // 2. 근접한거 서로 지우기 if(!remove()) { // 근접한게 없다면, 평균을 구해서 .. int sum =0; int cnt = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if(dart[i][j] == 0 )continue; sum+=dart[i][j]; cnt++; } } double avg = (double)sum / (double)cnt; // 3. 평균을 기준으로 수 바꿔주기 change(avg); } } // 총합 구하기 int ans =0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { ans+=dart[i][j]; } } System.out.println(ans); } private static void change(double avg) { for (int r = 0; r < N; r++) { for (int c = 0; c < M; c++) { if(dart[r][c] == 0 )continue; // 평균 보다 크면 -1, 작으면 +1 , 같으면 그대로 if(dart[r][c] > avg) dart[r][c]--; else if(dart[r][c] < avg) dart[r][c]++; } } } private static boolean remove() { for (int r = 0; r < N; r++) { for (int c = 0; c < M; c++) { if(dart[r][c] == 0 )continue; // 해당 속성의 4방향 탐색을 시행한다 for (int i = 0; i < dir.length; i++) { int nr = dir[i][0] + r; int nc = dir[i][1] + c; // 단, 같은 행에 대해서는 크기 초과일 경우, 원순환 시켜야 한다 if(nc == -1) nc = M-1; if(nc == M) nc = 0; // 인접한것을 발견하면 현재 수는 지워줘야하므로 삭제리스트에 저장 // (바로바로 안지우는 이유는 해당 수를 지워버리면, 다른수가 해당수와 비교가 어렵기 때문) if(isIn(nr) && dart[r][c] == dart[nr][nc]) { rmList.add(new Pair(r,c)); break; } } } } // 삭제 리스트가 비어있다면?, 인점 없음, change()를 수행하자 if(rmList.isEmpty()) return false; // 삭제리스트에 존재하는 모든수를 0으로 삭제 for (int i = 0; i < rmList.size(); i++) { dart[rmList.get(i).x][rmList.get(i).y] = 0; } // 비우기 rmList.clear(); return true; } // x: 회전시킬 원판의 배수 , d: 회전방향, k: 회전 횟수 private static void rotate(int x, int d, int k) { for (int i = x-1; i < dart.length; i+=x) { // 시계 방향 if(d == 0) { for (int t = 0; t < k; t++) { int[] tmp = dart[i].clone(); for (int j = 0; j < tmp.length; j++) { dart[i][j] = tmp[(j + tmp.length-1)% tmp.length]; } } }else { // 반시계 for (int t = 0; t < k; t++) { int[] tmp = dart[i].clone(); for (int j = 0; j < tmp.length; j++) { dart[i][j] = tmp[(j + 1)% tmp.length]; } } } } } public static boolean isIn(int r) { return r>=0&& r<N; } public static class Pair{ int x, y; public Pair(int x, int y) { super(); this.x = x; this.y = y; } } }
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data.hbase.manager; import org.kitesdk.data.ConcurrentSchemaModificationException; import org.kitesdk.data.DatasetException; import org.kitesdk.data.IncompatibleSchemaException; import org.kitesdk.data.SchemaNotFoundException; import org.kitesdk.data.hbase.impl.EntitySchema; import org.kitesdk.data.hbase.impl.EntitySchema.FieldMapping; import org.kitesdk.data.hbase.impl.KeyEntitySchemaParser; import org.kitesdk.data.hbase.impl.KeySchema; import org.kitesdk.data.hbase.impl.MappingType; import org.kitesdk.data.hbase.impl.SchemaManager; import org.kitesdk.data.hbase.manager.generated.ManagedSchema; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.hadoop.hbase.client.HTablePool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Default SchemaManager implementation. It uses a ManagedSchemaDao * implementation, passed in the constructor, to read schema metadata, and * persist schema metadata for schema creations and migrations. */ public class DefaultSchemaManager implements SchemaManager { private static Logger LOG = LoggerFactory .getLogger(DefaultSchemaManager.class); /** * A mapping of managed schema row keys to the managed schema entities. */ private volatile ConcurrentHashMap<String, ManagedSchema> managedSchemaMap; /** * A DAO which is used to access the managed key and entity schemas */ private ManagedSchemaDao managedSchemaDao; /** * A map of schema parsers that can be used to parse different schema types. */ private ConcurrentHashMap<String, KeyEntitySchemaParser<?, ?>> schemaParsers = new ConcurrentHashMap<String, KeyEntitySchemaParser<?, ?>>(); /** * Constructor which uses the default managed schema table name, which is * managed_schemas. * * @param tablePool * The pool of HBase tables */ public DefaultSchemaManager(HTablePool tablePool) { this(new ManagedSchemaHBaseDao(tablePool)); } public DefaultSchemaManager(HTablePool tablePool, String managedSchemaTable) { this(new ManagedSchemaHBaseDao(tablePool, managedSchemaTable)); } public DefaultSchemaManager(ManagedSchemaDao managedSchemaDao) { this.managedSchemaDao = managedSchemaDao; } @Override public boolean hasManagedSchema(String tableName, String entityName) { ManagedSchema managedSchema; try { managedSchema = getManagedSchema(tableName, entityName); } catch (SchemaNotFoundException e) { managedSchema = null; } return managedSchema != null; } @Override public KeySchema getKeySchema(String tableName, String entityName) { ManagedSchema managedSchema = getManagedSchema(tableName, entityName); KeyEntitySchemaParser<?, ?> schemaParser = getSchemaParser(managedSchema .getSchemaType()); String greatestVersionedSchema = getGreatestEntitySchemaString(managedSchema); return schemaParser.parseKeySchema(greatestVersionedSchema); } @Override public EntitySchema getEntitySchema(String tableName, String entityName) { ManagedSchema managedSchema = getManagedSchema(tableName, entityName); KeyEntitySchemaParser<?, ?> schemaParser = getSchemaParser(managedSchema .getSchemaType()); String greatestVersionedSchema = getGreatestEntitySchemaString(managedSchema); return schemaParser.parseEntitySchema(greatestVersionedSchema); } private String getGreatestEntitySchemaString(ManagedSchema managedSchema) { int greatestVersion = -1; String greatestVersionedSchema = null; for (Entry<String, String> entry : managedSchema.getEntitySchemas() .entrySet()) { int version = Integer.parseInt(entry.getKey()); if (version > greatestVersion) { greatestVersion = version; greatestVersionedSchema = entry.getValue(); } } if (greatestVersionedSchema == null) { String msg = "No schema versions for " + managedSchema.getTable() + ", " + managedSchema.getName(); LOG.error(msg); throw new SchemaNotFoundException(msg); } return greatestVersionedSchema; } @Override public EntitySchema getEntitySchema(String tableName, String entityName, int version) { ManagedSchema managedSchema = getManagedSchema(tableName, entityName); KeyEntitySchemaParser<?, ?> schemaParser = getSchemaParser(managedSchema .getSchemaType()); if (!managedSchema.getEntitySchemas().containsKey(String.valueOf(version))) { // didn't contain the schema version, refresh the schema cache and refetch // the managed schema. refreshManagedSchemaCache(tableName, entityName); managedSchema = getManagedSchema(tableName, entityName); } String schema = managedSchema.getEntitySchemas().get( String.valueOf(version)); if (schema != null) { return schemaParser.parseEntitySchema(schema); } else { String msg = "Could not find managed schema for " + tableName + ", " + entityName + ", and version " + Integer.toString(version); LOG.error(msg); throw new SchemaNotFoundException(msg); } } @Override public Map<Integer, EntitySchema> getEntitySchemas(String tableName, String entityName) { ManagedSchema managedSchema = getManagedSchema(tableName, entityName); KeyEntitySchemaParser<?, ?> schemaParser = getSchemaParser(managedSchema .getSchemaType()); Map<Integer, EntitySchema> retMap = new HashMap<Integer, EntitySchema>(); for (Entry<String, String> entry : managedSchema.getEntitySchemas() .entrySet()) { EntitySchema entitySchema = schemaParser.parseEntitySchema(entry .getValue()); retMap.put(Integer.parseInt(entry.getKey()), entitySchema); } return retMap; } @Override public int getEntityVersion(String tableName, String entityName, EntitySchema schema) { KeyEntitySchemaParser<?, ?> schemaParser = getSchemaParser(getManagedSchema( tableName, entityName).getSchemaType()); for (Entry<Integer, String> entry : getManagedSchemaVersions(tableName, entityName).entrySet()) { EntitySchema managedSchema = schemaParser.parseEntitySchema(entry .getValue()); if (schema.equals(managedSchema)) { return entry.getKey(); } } return -1; } @Override public void createSchema(String tableName, String entityName, String entitySchemaStr, String schemaParserType, String keySerDeType, String entitySerDeType) { // We want to make sure the managed schema map has as recent // a copy of the managed schema in HBase as possible. refreshManagedSchemaCache(tableName, entityName); KeyEntitySchemaParser<?, ?> schemaParser = getSchemaParser(schemaParserType); KeySchema keySchema = schemaParser.parseKeySchema(entitySchemaStr); EntitySchema entitySchema = schemaParser.parseEntitySchema(entitySchemaStr); try { ManagedSchema managedSchema = getManagedSchema(tableName, entityName); if (managedSchema != null) { throw new IncompatibleSchemaException( "Cannot create schema when one already exists"); } } catch (SchemaNotFoundException e) { // we want the schema to not be found, continue } // Validate that this schema is compatible with other schemas registered // with this same table. validateCompatibleWithTableSchemas(tableName, keySchema, entitySchema); ManagedSchema managedSchema = ManagedSchema.newBuilder() .setName(entityName).setTable(tableName) .setEntitySchemas(new HashMap<String, String>()) .setSchemaType(schemaParserType).setEntitySerDeType(entitySerDeType) .setKeySerDeType(keySerDeType).build(); // at this point, the schema is a valid migration. persist it. managedSchema.getEntitySchemas().put("0", entitySchema.getRawSchema()); if (!managedSchemaDao.save(managedSchema)) { throw new ConcurrentSchemaModificationException( "The schema has been updated concurrently."); } getManagedSchemaMap().put( getManagedSchemaMapKey(managedSchema.getTable(), managedSchema.getName()), managedSchema); } @Override public void migrateSchema(String tableName, String entityName, String newSchemaStr) { // We want to make sure the managed schema map has as recent // a copy of the managed schema in HBase as possible. refreshManagedSchemaCache(tableName, entityName); ManagedSchema managedSchema = getManagedSchema(tableName, entityName); KeyEntitySchemaParser<?, ?> schemaParser = getSchemaParser(managedSchema .getSchemaType()); // validate it's a valid avro schema by parsing it EntitySchema newEntitySchema = schemaParser.parseEntitySchema(newSchemaStr); KeySchema newKeySchema = schemaParser.parseKeySchema(newSchemaStr); // verify that the newSchema isn't a duplicate of a previous schema version. int existingVersion = getEntityVersion(tableName, entityName, newEntitySchema); if (existingVersion != -1) { throw new IncompatibleSchemaException( "Schema already exists as version: " + Integer.toString(existingVersion)); } // validate that, for each version of the schema, this schema is // compatible with those schema version. That means the field mapping // hasn't changed, and we can read old schemas, and processes that // are configured with old schemas can read new schemas. int greatestSchemaVersion = 0; for (Entry<String, String> entry : managedSchema.getEntitySchemas() .entrySet()) { int version = Integer.parseInt(entry.getKey()); if (version > greatestSchemaVersion) { greatestSchemaVersion = version; } String schemaString = entry.getValue(); KeySchema keySchema = schemaParser.parseKeySchema(schemaString); EntitySchema entitySchema = schemaParser.parseEntitySchema(schemaString); if (!newKeySchema.compatible(keySchema)) { String msg = "StorageKey fields of entity schema not compatible with version " + Integer.toString(version) + ": Old schema: " + schemaString + " New schema: " + newEntitySchema.getRawSchema(); throw new IncompatibleSchemaException(msg); } if (!newEntitySchema.compatible(entitySchema)) { String msg = "Avro schema not compatible with version " + Integer.toString(version) + ": Old schema: " + schemaString + " New schema: " + newEntitySchema.getRawSchema(); throw new IncompatibleSchemaException(msg); } } // Validate that this schema is compatible with other schemas registered // with this same table. validateCompatibleWithTableSchemas(tableName, newKeySchema, newEntitySchema); // at this point, the schema is a valid migration. persist it. managedSchema.getEntitySchemas().put( Integer.toString(greatestSchemaVersion + 1), newEntitySchema.getRawSchema()); if (!managedSchemaDao.save(managedSchema)) { throw new ConcurrentSchemaModificationException( "The schema has been updated concurrently."); } } @Override public void deleteSchema(String tableName, String entityName) { // We want to make sure the managed schema map has as recent // a copy of the managed schema in HBase as possible. refreshManagedSchemaCache(tableName, entityName); ManagedSchema managedSchema = getManagedSchema(tableName, entityName); if (!managedSchemaDao.delete(managedSchema)) { throw new ConcurrentSchemaModificationException( "The schema has been updated concurrently."); } getManagedSchemaMap().remove( getManagedSchemaMapKey(managedSchema.getTable(), managedSchema.getName())); } /** * Update the managedSchemaMap for the entry defined by tableName and * entityName. * * @param tableName * The table name of the managed schema * @param entityName * The entity name of the managed schema */ @Override public void refreshManagedSchemaCache(String tableName, String entityName) { ManagedSchema managedSchema = managedSchemaDao.getManagedSchema(tableName, entityName); if (managedSchema != null) { getManagedSchemaMap().put( getManagedSchemaMapKey(managedSchema.getTable(), managedSchema.getName()), managedSchema); } } @Override public List<String> getEntityNames(String tableName) { List<String> names = Lists.newArrayList(); for (ManagedSchema managedSchema : managedSchemaMap.values()) { if (managedSchema.getTable().equals(tableName)) { names.add(managedSchema.getName()); } } return names; } /** * Get the managedSchemaMap, lazily loading it if it hasn't been initialized * yet. Members of this class should never access the managedSchemaMap * directly, but should always access it through this method. * * @return The managedSchemaMap */ private ConcurrentHashMap<String, ManagedSchema> getManagedSchemaMap() { if (managedSchemaMap == null) { synchronized (this) { if (managedSchemaMap == null) { managedSchemaMap = new ConcurrentHashMap<String, ManagedSchema>(); populateManagedSchemaMap(); } } } return managedSchemaMap; } /** * Populate the managedSchemaMap with all of the managed schemas returned by * the managedSchemaDao. */ private void populateManagedSchemaMap() { for (ManagedSchema managedSchema : managedSchemaDao.getManagedSchemas()) { getManagedSchemaMap().put( getManagedSchemaMapKey(managedSchema.getTable(), managedSchema.getName()), managedSchema); } } /** * Get the managed schema from the managedSchemaMap, using the * getManagedSchemaMap() accessor. * * @param tableName * The table name of the managed schema * @param entityName * The entity name of the managed schema * @return The ManagedSchema instance, or null if one doesn't exist. */ private ManagedSchema getManagedSchemaFromSchemaMap(String tableName, String entityName) { return getManagedSchemaMap().get( getManagedSchemaMapKey(tableName, entityName)); } /** * Get the schema parser by its classname. This method will cache the * constructed schema parsers. * * @param schemaParserClassName * The class name of the schema parser * @return The constructed schema parser. */ @SuppressWarnings("unchecked") private KeyEntitySchemaParser<?, ?> getSchemaParser( String schemaParserClassName) { if (schemaParsers.contains(schemaParserClassName)) { return schemaParsers.get(schemaParserClassName); } else { try { Class<KeyEntitySchemaParser<?, ?>> schemaParserClass = (Class<KeyEntitySchemaParser<?, ?>>) Class .forName(schemaParserClassName); KeyEntitySchemaParser<?, ?> schemaParser = schemaParserClass .getConstructor().newInstance(); schemaParsers.putIfAbsent(schemaParserClassName, schemaParser); return schemaParser; } catch (Exception e) { throw new DatasetException( "Could not instantiate schema parser class: " + schemaParserClassName, e); } } } /** * Get a map of schema versions for a managed schemas. * * @param tableName * The table name of the managed schema. * @param entityName * The entity name of the managed schema. * @return The managed schema version map. * @throws SchemaNotFoundException * Thrown if a managed schema can't be found for the table name * entity name. */ private Map<Integer, String> getManagedSchemaVersions(String tableName, String entityName) { ManagedSchema managedSchema = getManagedSchema(tableName, entityName); Map<Integer, String> returnMap = new HashMap<Integer, String>(); for (Map.Entry<String, String> versionsEntry : managedSchema .getEntitySchemas().entrySet()) { returnMap.put(Integer.parseInt(versionsEntry.getKey()), versionsEntry.getValue()); } return returnMap; } /** * Get the ManagedSchema entity for the tableName, entityName managed schema. * * @param tableName * The table name of the managed schema. * @param entityName * The entity name of the managed schema. * @return The ManagedSchema entity * @throws SchemaNotFoundException */ private ManagedSchema getManagedSchema(String tableName, String entityName) { ManagedSchema managedSchema = getManagedSchemaFromSchemaMap(tableName, entityName); if (managedSchema == null) { refreshManagedSchemaCache(tableName, entityName); managedSchema = getManagedSchemaFromSchemaMap(tableName, entityName); if (managedSchema == null) { String msg = "Could not find managed schemas for " + tableName + ", " + entityName; throw new SchemaNotFoundException(msg); } } return managedSchema; } /** * Validate that a KeySchema and EntitySchema will be compatible with the * other schemas registered with a table. This includes making sure that the * schema doesn't overlap with columns other schemas for the table map to, and * validates that the key schemas are the same. * * If validation fails, an IncompatibleSchemaException is thrown. Otherwise, * no exception is thrown. * * @param tableName * The name of the table who's schemas we want to validate against. * @param keySchema * The KeySchema to validate against other KeySchemas registered with * this table * @param entitySchema * The EntitySchema to validate against other EntitySchemas * registered with thsi table. */ private void validateCompatibleWithTableSchemas(String tableName, KeySchema keySchema, EntitySchema entitySchema) { List<ManagedSchema> entitiesForTable = new ArrayList<ManagedSchema>(); for (Entry<String, ManagedSchema> entry : getManagedSchemaMap().entrySet()) { if (entry.getKey().startsWith(tableName + ":")) { entitiesForTable.add(entry.getValue()); } } for (ManagedSchema managedSchema : entitiesForTable) { if (!managedSchema.getName().equals(entitySchema.getName())) { KeyEntitySchemaParser<?, ?> parser = getSchemaParser(managedSchema .getSchemaType()); for (String schema : managedSchema.getEntitySchemas().values()) { EntitySchema otherEntitySchema = parser.parseEntitySchema(schema); KeySchema otherKeySchema = parser.parseKeySchema(schema); if (!keySchema.compatible(otherKeySchema)) { String msg = "StorageKey fields of schema not compatible with other schema for the table. " + "Table: " + tableName + ". Other schema: " + otherEntitySchema.getRawSchema() + " New schema: " + entitySchema.getRawSchema(); throw new IncompatibleSchemaException(msg); } if (!validateCompatibleWithTableColumns(entitySchema, otherEntitySchema)) { String msg = "Column mappings of schema not compatible with other schema for the table. " + "Table: " + tableName + ". Other schema: " + otherEntitySchema.getRawSchema() + " New schema: " + entitySchema.getRawSchema(); throw new IncompatibleSchemaException(msg); } if (!validateCompatibleWithTableOccVersion(entitySchema, otherEntitySchema)) { String msg = "OCCVersion mapping of schema not compatible with other schema for the table. " + "Only one schema in the table can have one." + "Table: " + tableName + ". Other schema: " + otherEntitySchema.getRawSchema() + " New schema: " + entitySchema.getRawSchema(); throw new IncompatibleSchemaException(msg); } } } } } /** * Validate that two schemas for a table don't overlap in columns. * * @param entitySchema1 * The first schema to compare * @param entitySchema2 * The second schema to compare * @return True if compatible, otherwise False. */ private boolean validateCompatibleWithTableColumns( EntitySchema entitySchema1, EntitySchema entitySchema2) { // Populate two collections of field mappings. One that contains all // of the column mappings, and one that contains the keyAsColumn // mappings from the first schema. These will be used to compare // against the second schema. Set<String> entitySchema1Columns = new HashSet<String>(); List<String> entitySchema1KeyAsColumns = new ArrayList<String>(); for (FieldMapping fieldMapping1 : entitySchema1.getFieldMappings()) { if (fieldMapping1.getMappingType() == MappingType.COLUMN) { entitySchema1Columns.add(fieldMapping1.getMappingValue()); } else if (fieldMapping1.getMappingType() == MappingType.KEY_AS_COLUMN) { String value = fieldMapping1.getMappingValue(); if (fieldMapping1.getPrefix() != null) { value += fieldMapping1.getPrefix(); } entitySchema1KeyAsColumns.add(value); } } // For each field mapping in the second entity schema, we want to // validate the following: // // 1. That each column mapping in it doesn't map to the same column // as a column mapping in the first schema. // // 2. That each column mapping in it doesn't "startsWith()" with a // keyAsColumn mapping in the first schema, where the keyAsColumn // mapping value is "columnfamily:prefix". // // 3. That each keyAsColumn mapping in it isn't a prefix of one of // the first schema's column mappings. // // 4. That each keyAsColumn mapping in it isn't a prefix of one fo // the first schema's keyAsColumn mappings, and one of the first // schema's mappings isn't a prefix of this schema's keyAsColumn // mappings. for (FieldMapping fieldMapping2 : entitySchema2.getFieldMappings()) { if (fieldMapping2.getMappingType() == MappingType.COLUMN) { String value = fieldMapping2.getMappingValue(); if (entitySchema1Columns.contains(value)) { LOG.warn("Field: " + fieldMapping2.getFieldName() + " has a table column conflict with a column mapped field in " + entitySchema1.getName()); return false; } for (String keyAsColumn : entitySchema1KeyAsColumns) { if (value.startsWith(keyAsColumn)) { LOG.warn("Field: " + fieldMapping2.getFieldName() + " has a table column conflict with a keyAsColumn mapped field in " + entitySchema1.getName()); return false; } } } else if (fieldMapping2.getMappingType() == MappingType.KEY_AS_COLUMN) { String entitySchema2KeyAsColumn = fieldMapping2.getMappingValue(); if (fieldMapping2.getPrefix() != null) { entitySchema2KeyAsColumn += fieldMapping2.getPrefix(); } for (String entitySchema1KeyAsColumn : entitySchema1KeyAsColumns) { if (entitySchema1KeyAsColumn.startsWith(entitySchema2KeyAsColumn)) { LOG.warn("Field " + fieldMapping2.getFieldName() + " has a table keyAsColumn conflict with a keyAsColumn mapped field in " + entitySchema1.getName()); return false; } } for (String entitySchema1Column : entitySchema1Columns) { if (entitySchema1Column.startsWith(entitySchema2KeyAsColumn)) { LOG.warn("Field " + fieldMapping2.getFieldName() + " has a table keyAsColumn conflict with a column mapped field in " + entitySchema1.getName()); return false; } } } } return true; } /** * Only one schema for a table should contain an OCCVersion field mapping. * This method will compare two schemas and return true if only one has an * OCC_VERSION field. * * @param entitySchema1 * The first schema to compare * @param entitySchema2 * The second schema to compare * @return True if compatible, otherwise False. */ private boolean validateCompatibleWithTableOccVersion( EntitySchema entitySchema1, EntitySchema entitySchema2) { boolean foundOccMapping = false; for (FieldMapping fieldMapping : entitySchema1.getFieldMappings()) { if (fieldMapping.getMappingType() == MappingType.OCC_VERSION) { foundOccMapping = true; break; } } if (foundOccMapping) { for (FieldMapping fieldMapping : entitySchema2.getFieldMappings()) { if (fieldMapping.getMappingType() == MappingType.OCC_VERSION) { LOG.warn("Field: " + fieldMapping.getFieldName() + " in schema " + entitySchema2.getName() + " conflicts with an occVersion field in " + entitySchema1.getName()); return false; } } } return true; } private String getManagedSchemaMapKey(String tableName, String entityName) { return tableName + ":" + entityName; } }
package com.rensimyl.www.mathics; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class Geometri extends AppCompatActivity { Button backGeometri, geometri1, geometri2, geometri3, geometri4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_geometri); backGeometri = findViewById(R.id.geo_back); geometri1 = findViewById(R.id.materi_geo1_go); geometri2 = findViewById(R.id.materi_geo2_go); geometri3 = findViewById(R.id.materi_geo3_go); geometri4 = findViewById(R.id.materi_geo4_go); geometri1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Geometri.this, Matgeo1.class); startActivity(intent); } }); geometri2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Geometri.this, Matgeo2.class); startActivity(intent); } }); geometri3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Geometri.this, Matgeo3.class); startActivity(intent); } }); geometri4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Geometri.this, Matgeo4.class); startActivity(intent); } }); backGeometri.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
package com.dustin.control.convert; import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * <p> Description: </p> * * @author Wangsw * @date 2017/11/23下午 09:16 * @Version 1.0.0 */ public class CustomDateConverter implements Converter<String, Date> { public Date convert(String source) { //实现 将日期串转成日期类型(格式是yyyy-MM-dd HH:mm:ss) SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { //转成直接返回 return simpleDateFormat.parse(source); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } //如果参数绑定失败返回null return null; } }
package com.lubarov.daniel.data.set; import com.lubarov.daniel.data.collection.AbstractCollection; import com.lubarov.daniel.data.function.Function; public abstract class AbstractSet<A> extends AbstractCollection<A> implements Set<A> { // Don't let implementations inherit AbstractCollection's contains, which calls getCount. // Set implementations should generally provide their own contains. @Override public abstract boolean contains(A value); @Override public int getCount(A value) { return contains(value) ? 1 : 0; } @Override public Set<A> filter(Function<? super A, Boolean> predicate) { MutableHashSet<A> result = MutableHashSet.create(); for (A element : this) if (predicate.apply(element)) result.tryAdd(element); return result; } @Override public ImmutableSet<A> toImmutable() { return ImmutableHashSet.copyOf(this); } }
package com.lingnet.vocs.action.statistics; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import com.alibaba.fastjson.JSONObject; import com.github.abel533.echarts.Legend; import com.github.abel533.echarts.axis.AxisLabel; import com.github.abel533.echarts.axis.CategoryAxis; import com.github.abel533.echarts.axis.ValueAxis; import com.github.abel533.echarts.code.Magic; import com.github.abel533.echarts.code.Symbol; import com.github.abel533.echarts.code.Tool; import com.github.abel533.echarts.code.Trigger; import com.github.abel533.echarts.data.Data; import com.github.abel533.echarts.feature.MagicType; import com.github.abel533.echarts.json.GsonUtil; import com.github.abel533.echarts.series.Bar; import com.github.abel533.echarts.series.Pie; import com.github.abel533.echarts.util.EnhancedOption; import com.lingnet.common.action.BaseAction; import com.lingnet.qxgl.entity.QxDepartment; import com.lingnet.util.JsonUtil; import com.lingnet.vocs.entity.Partner; import com.lingnet.vocs.service.statistics.TaskScoreService; /** * 现场任务及分数统计 * * @ClassName: TaskScoreAction * @Description: TODO * @author zy * @date 2017年7月27日 下午2:00:55 * */ public class TaskScoreAction extends BaseAction { private static final long serialVersionUID = 673512936107374917L; @Resource(name = "taskScoreService") private TaskScoreService taskScoreService; private String option; /** * @Title: charts * @return * @author zy * @since 2017年7月27日 V 1.0 */ public String charts() { return "charts"; } /** * @Title: getChartsData * @return * @author zy * @since 2017年7月27日 V 1.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public String getChartsData() { List<Object[]> listChartData = taskScoreService.getChartsData(key); JSONObject jo = JSONObject.parseObject(key); String radio1 = jo.getString("radio1"); // 统计口径 String caliber = jo.getString("caliber"); // 统计内容 String content = jo.getString("content"); // 图形类型 EnhancedOption op = new EnhancedOption(); if ("barline".equals(radio1)) {// 柱状图,线形图 Legend legend = new Legend(); Object[] legendArrs = null; if ("avgScore".equals(jo.get("content"))) { legendArrs = new Object[1]; legendArrs[0] = "平均分数"; op.title().text("平均分数"); } else if ("taskCount".equals(jo.get("content"))) { legendArrs = new Object[1]; legendArrs[0] = "任务数量"; op.title().text("任务数量"); } else { legendArrs = new Object[2]; legendArrs[0] = "平均分数"; legendArrs[1] = "任务数量"; op.title().text("平均分数/任务数量"); } legend.data(legendArrs); op.legend(legend); List resX = new ArrayList(); List resY1 = new ArrayList();// 平均分数或任务数量 List resY2 = new ArrayList();// 平均分数和任务数量都有的时候,是任务数量 for (int i = 0; i < listChartData.size(); ++i) { resX.add(listChartData.get(i)[0]); if (!"taskCount".equals(jo.get("content"))) { double res = Double .parseDouble(listChartData.get(i)[1] == null ? "0" : listChartData.get(i)[1].toString()); resY1.add(String.format("%.2f", res)); } else { resY1.add(listChartData.get(i)[1] == null ? "0" : listChartData.get(i)[1].toString()); } if (StringUtils.isEmpty(content)) { resY2.add(listChartData.get(i)[2] == null ? 0 : listChartData.get(i)[2]); } } op.toolbox().show(true); op.toolbox() .show(true) .feature(new MagicType(Magic.line, Magic.bar).show(true), Tool.restore, Tool.saveAsImage); op.tooltip().trigger(Trigger.axis); op.calculable(true); CategoryAxis categoryAxis = new CategoryAxis(); categoryAxis.name(getCaliberCn(caliber)).data(resX.toArray()) .axisLabel().rotate(25); op.xAxis(categoryAxis); if ("avgScore".equals(content)) { AxisLabel aLeft = new AxisLabel(); aLeft.formatter("{value} 分"); op.yAxis(new ValueAxis().name((String) legendArrs[0]) .position("left").axisLabel(aLeft).max(5).min(0)); Bar bar = new Bar(); bar.name((String) legendArrs[0]).stack((String) legendArrs[0]) .symbol(Symbol.circle).data(resY1.toArray()) .itemStyle().normal().color("#00FFFF"); bar.yAxisIndex(0); op.series(bar); } else if ("taskCount".equals(content)) { AxisLabel aRight = new AxisLabel(); aRight.formatter("{value} 次"); op.yAxis(new ValueAxis().name((String) legendArrs[0]) .position("right").axisLabel(aRight).max(15).min(0)); Bar bar2 = new Bar(); bar2.name((String) legendArrs[0]).stack((String) legendArrs[0]) .symbol(Symbol.circle).data(resY1.toArray()) .itemStyle().normal().color("#00AAAA"); bar2.yAxisIndex(0); op.series(bar2); } else { AxisLabel aLeft = new AxisLabel(); aLeft.formatter("{value} 分"); op.yAxis(new ValueAxis().name((String) legendArrs[0]) .position("left").axisLabel(aLeft).max(5).min(0)); Bar bar = new Bar(); bar.name((String) legendArrs[0]).stack((String) legendArrs[0]) .symbol(Symbol.circle).data(resY1.toArray()) .itemStyle().normal().color("#00FFFF"); bar.yAxisIndex(0); op.series(bar); AxisLabel aRight = new AxisLabel(); aRight.formatter("{value} 次"); op.yAxis(new ValueAxis().name((String) legendArrs[1]) .position("right").axisLabel(aRight).max(15).min(0)); Bar bar2 = new Bar(); bar2.name((String) legendArrs[1]).stack((String) legendArrs[1]) .symbol(Symbol.circle).data(resY2.toArray()) .itemStyle().normal().color("#00AAAA"); bar2.yAxisIndex(1); op.series(bar2); } } else if ("pie".equals(radio1)) {// 饼图 op.toolbox().show(true); op.toolbox().show(true).feature(Tool.restore, Tool.saveAsImage); op.tooltip().show(true); List resX = new ArrayList(); if (StringUtils.isEmpty(content)) { Object[] oA1 = new Object[listChartData.size()]; Object[] oA2 = new Object[listChartData.size()]; for (int i = 0; i < listChartData.size(); ++i) { resX.add(listChartData.get(i)[0]); double res = Double .parseDouble(listChartData.get(i)[1] == null ? "0" : listChartData.get(i)[1].toString()); oA1[i] = new Data((String) (listChartData.get(i)[0]), String.format("%.2f", res)); oA2[i] = new Data((String) (listChartData.get(i)[0]), listChartData.get(i)[2]); } Pie pie1 = new Pie(); Pie pie2 = new Pie(); pie1.name("平均分数"); pie2.name("任务数量"); Object[] oc1 = { "25%", "50%" }; Object[] oc2 = { "75%", "50%" }; pie1.clockWise(false).data(oA1).setCenter(oc1); pie2.clockWise(false).data(oA2).setCenter(oc2); op.series(pie1); op.series(pie2); } else { Object[] objectArrs = new Object[listChartData.size()]; for (int i = 0; i < listChartData.size(); ++i) { resX.add(listChartData.get(i)[0]); objectArrs[i] = new Data( (String) (listChartData.get(i)[0]), listChartData.get(i)[1]); } Pie pie = new Pie(); pie.name(getContentCn(content)); pie.clockWise(false).data(objectArrs); op.series(pie); } Legend legend = new Legend(); legend.data(resX); op.legend(legend); } option = GsonUtil.format(op); return ajax(Status.success, JsonUtil.Encode(option)); } /** * @Title: getGridData * @return * @author zy * @since 2017年7月27日 V 1.0 */ public String getGridData() { String companyCn = ""; try { companyCn = URLDecoder.decode(getRequest() .getParameter("companyCn"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String s = taskScoreService.getGridData(key, pager, companyCn); return ajax(Status.success, s); } private String getCaliberCn(String caliber) { if ("employee".equals(caliber)) { return "员工"; } else if ("depart".equals(caliber)) { return "部门"; } else if ("company".equals(caliber)) { return "公司"; } else { return ""; } } private String getContentCn(String content) { if ("taskCount".equals(content)) { return "任务数量"; } else if ("avgScore".equals(content)) { return "平均分数"; } else { return ""; } } /** * @Title: getDepartByPartner * @return * @author zy * @since 2017年8月2日 V 1.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public String getDepartByPartner() { String partnerId = getRequest().getParameter("partnerId"); List<QxDepartment> allDepart = taskScoreService.getList( QxDepartment.class, eq("isDeleted", "0"), eq("partnerId", partnerId)); List result = new ArrayList(); for (QxDepartment depart : allDepart) { HashMap m = new HashMap(); m.put("id", depart.getId()); m.put("name", depart.getName()); result.add(m); } return ajax(Status.success, JsonUtil.Encode(result)); } /** * @Title: getAllPartner * @return * @author zy * @since 2017年8月2日 V 1.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public String getAllPartner() { Disjunction disjun = Restrictions.disjunction(); disjun.add(eq("partnerOrCustomer", "P")); disjun.add(eq("partnerOrCustomer", "H")); disjun.add(eq("partnerOrCustomer", "C")); List<Partner> partners = taskScoreService.getListByOrder(Partner.class, Order.asc("name"), eq("isDeleted", "0"), disjun); List result = new ArrayList(); for (Partner p : partners) { HashMap m = new HashMap(); m.put("id", p.getId()); m.put("name", p.getName()); result.add(m); } return ajax(Status.success, JsonUtil.Encode(result)); } public String getOption() { return option; } public void setOption(String option) { this.option = option; } }
package ru.smartsarov.election.cik; import java.io.Serializable; import java.util.Iterator; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class UikRequest implements Serializable, Iterable<UikRequest> { private final static long serialVersionUID = 2326643019323295056L; @SerializedName("id") @Expose private String id; @SerializedName("text") @Expose private String text; @SerializedName("a_attr") @Expose private Aattr aAttr; @SerializedName("children") @Expose private Boolean children; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Aattr getAAttr() { return aAttr; } public void setAAttr(Aattr aAttr) { this.aAttr = aAttr; } public Boolean getChildren() { return children; } public void setChildren(Boolean children) { this.children = children; } @Override public Iterator<UikRequest> iterator() { // TODO Auto-generated method stub return null; } }
package br.com.drogaria.bean; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import org.apache.commons.codec.digest.DigestUtils; import br.com.drogaria.dao.FuncionarioDAO; import br.com.drogaria.domain.Funcionario; import br.com.drogaria.util.FacesUtil; @ManagedBean @SessionScoped public class AutenticacaoBean { private Funcionario funcionarioLogado; public Funcionario getFuncionarioLogado() { if(funcionarioLogado == null) { funcionarioLogado = new Funcionario(); } return funcionarioLogado; } public void setFuncionarioLogado(Funcionario funcionarioLogado) { this.funcionarioLogado = funcionarioLogado; } public void autenticar() { try { FuncionarioDAO funcionarioDAO = new FuncionarioDAO(); funcionarioLogado = funcionarioDAO.autenticar(funcionarioLogado.getCpf(), DigestUtils.md5Hex(funcionarioLogado.getSenha())); if(funcionarioLogado == null) { FacesUtil.addMsgErro("CPF e/ou senha incorretos."); }else { FacesUtil.addMsgInfo("Funcionário: "+ funcionarioLogado.getNome() +", autenticado com sucesso."); } }catch (RuntimeException ex) { FacesUtil.addMsgErro("Erro ao tentar autenticar no sistema: "+ ex.getMessage()); } } public String sair() { funcionarioLogado = null; return "/pages/autenticacao.xhtml?faces-redirect=true"; } }
class Solution { public int[] plusOne(int[] digits) { int endIndex = digits.length - 1; if(digits[endIndex] == 9){ boolean carry = true; digits[endIndex] = 0; for(int i = endIndex - 1; i >= 0; i--){ if(carry){ if(digits[i] == 9){ digits[i] = 0; carry = true; } else{ digits[i]++; carry = false; } } else break; } if(carry){ int[] sol = new int[digits.length + 1]; sol[0] = 1; for(int i = 0; i < digits.length; i++){ sol[i + 1] = digits[i]; } return sol; } return digits; } else digits[digits.length - 1]++; return digits; } }
package net.francesbagual.osgi.helloworld.impl; public class Parrot { public String repeat(String word) { return word; } }
package camel.serial; import camel.serial.model.SerialMessage; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.TooManyListenersException; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.Suspendable; import org.apache.camel.impl.DefaultConsumer; import org.apache.camel.util.URISupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Consumer starting a serial consumer which forwards data to the ledcontrol.processor. * */ public class SerialConsumer extends DefaultConsumer implements SerialPortEventListener, Suspendable { private static final Logger LOG = LoggerFactory.getLogger(SerialConsumer.class); private InputStream in; private SerialPort serialPort; private SerialEndpoint endpoint; public SerialConsumer(SerialEndpoint endpoint, Processor processor, SerialPort serialPort, InputStream in) { super(endpoint, processor); this.endpoint = endpoint; this.serialPort = serialPort; this.in = in; } @Override protected void doStart() { LOG.info("Start SerialConsumer"); if (null == serialPort) { LOG.error("No serialPort (null), can not start consumer!"); return; } try { super.doStart(); } catch (Exception e) { LOG.error("Error starting SerialConsumer", e); } try { serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); } catch (TooManyListenersException e) { LOG.error("Error: too many eventlisteners added", e);; } } // @Override // protected void doStop() { // LOG.debug("Stop SerialConsumer..."); // try { // super.doStop(); // } catch (Exception e) { // LOG.error("Error stopping SerialConsumer", e); // } // // if (serialPort != null) { // serialPort.notifyOnDataAvailable(false); // serialPort.removeEventListener(); // } // // if (in != null) { // try { // LOG.debug("Close inputstream for {}", URISupport.sanitizeUri(endpoint.getEndpointUri())); // in.close(); // } catch (IOException e) { // LOG.warn("Error closing input stream", e); // } finally { // in = null; // } // } // // try { // endpoint.stop(); // } catch (Exception e) { // LOG.error("Error stopping endpoint", e); // } // } @Override protected void doSuspend() { LOG.debug("Suspend SerialConsumer..."); try { if (serialPort != null) { serialPort.notifyOnDataAvailable(false); serialPort.removeEventListener(); } if (endpoint != null) { endpoint.serialSuspend(); } super.doSuspend(); } catch (Exception e) { LOG.error("Error suspending SerialConsumer", e); } } @Override protected void doResume() { LOG.debug("Resume SerialConsumer..."); try { endpoint.serialResume(); serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); super.doResume(); } catch (Exception e) { LOG.error("Error resuming SerialConsumer", e); } } protected void setIn(InputStream in) { this.in = in; } protected void setSerialPort(SerialPort serialPort) { this.serialPort = serialPort; } /* (non-Javadoc) * @see gnu.io.SerialPortEventListener#serialEvent(gnu.io.SerialPortEvent) */ @Override public void serialEvent(SerialPortEvent event) { String dataMessage = null; byte[] buffer = new byte[1024]; int data; try { int len = 0; // String based, read up to the first LF while ((data = in.read()) > -1) { buffer[len++] = (byte) data; if (data == 10) { break; } } // discard single CR + LF if (len == 2 && buffer[0] == 13 && buffer[1] == 10) { len = 0; } if (len > 0) { try { // copy len-2 bytes (discard CR+LF) byte[] dataReceived = Arrays.copyOfRange(buffer, 0, len-2); dataMessage = new String(dataReceived); LOG.debug("Received message! [{}]", dataMessage); } catch (Exception ex) { LOG.warn("Error interpreting data (out of sync?)"); } } if (dataMessage != null) { Exchange exchange = getEndpoint().createExchange(); exchange.setIn(new SerialMessage(dataMessage)); try { getProcessor().process(exchange); } catch (Exception e) { LOG.error("Could not delegate message to Camel ledcontrol.processor", e); } } } catch (IOException e) { LOG.error("Error receiving data", e); } } @Override public String toString() { return "SerialConsumer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]"; } }
package application; import javafx.scene.paint.Color; import java.awt.Point; import java.util.function.Function; import javafx.scene.shape.Rectangle; /** * Class to represent LED lights on the virtual board * * Intended to indicate if certain sections of the system are ready for pressure changing instructions or not * @author Joanie Davis * */ public class LED { // The label of the LED that will appear on the gui private String label; // The color of the LED if condition 1 is true private Color cond1Color; // The color of the LED if condition 2 is true private Color cond2Color; // The color of the LED if the else clause is met // if there is no else clause, can be set to null private Color elseColor; // The current color that should be displayed on the gui private Color currentColor; // A string used as a key to retrieve the value of the first condition private String cond1; // A string used as a key to retrieve the value of the second condition private String cond2; // A boolean indicating if there is a second condition that should be checked before defaulting to the else clause private boolean has2Clause; // The corresponding part of the GUI that will have its color changed based on the conditions private Rectangle gui_Rect; public LED(String label, Color cond1Color, Color cond2Color, Color elseColor, String cond1, String cond2, boolean has2Clause, Rectangle gui_Rect) { this.label = label; this.cond1Color = cond1Color; this.cond2Color = cond2Color; this.elseColor = elseColor; this.currentColor = Color.GREEN; this.cond1 = cond1; this.cond2 = cond2; this.has2Clause = has2Clause; this.gui_Rect = gui_Rect; } public String getLabel() { return label; } public Color getCurrentColor() { return currentColor; } public Color getCond1Color() { return cond1Color; } public Color getCond2Color() { return cond2Color; } public Color getElseColor() { return elseColor; } public String getCond1() { return cond1; } public String getCond2() { return cond2; } public boolean has2clause() { return has2Clause; } public void setCurrentColor(Color color) { currentColor = color; } public void update(boolean cond1, boolean cond2) { if(cond1) { setCurrentColor(cond1Color); } else if (cond2 && has2Clause) { setCurrentColor(cond2Color); } else { setCurrentColor(elseColor); } gui_Rect.setFill(currentColor); } @Override public boolean equals(Object other) { if (other == null) return false; if (other.getClass() == LED.class) { LED otherLED = (LED) other; if(( otherLED.getCond1() == cond1) && (otherLED.getCond1Color().equals(cond1Color)) && (otherLED.getCond2().equals(cond2)) && (otherLED.getCond2Color() == (cond2Color)) // This one has to be == because it could be null, and .equals does not like null && (otherLED.getElseColor().equals(elseColor)) && (otherLED.getLabel().equals(label)) && (otherLED.has2clause() == (has2Clause))) { return true; } } return false; } }
package kg.inai.equeuesystem.services; import kg.inai.equeuesystem.entities.UserRole; import kg.inai.equeuesystem.models.UserRoleModel; import java.util.List; public interface UserRoleService { UserRole create(UserRoleModel userRoleModel); List<UserRole> findAll(); UserRole update(UserRoleModel userRoleModel); UserRole getById(Long id); UserRole getUserRoleByName(String name); }
package test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import util.ParseMessage; import util.StringComparison; /** * Идея была идти не рекурсивно, а по краю дерева с помощью while. Что-то херня выходит * Одним словом, дерево то получается то же самое. Возвращаемся к Test6 * @author sansey * */ public class Test13 { public static void main(String[] args) { List<String> similarStrings = Arrays.asList(new String[]{ " {sophos_internal_id}: host gmail-smtp-in.l.google.com[64.233.164.27] said: 450-4.2.1 The user you are trying to contact is receiving mail at a rate that 450-4.2.1 prevents additional messages from being delivered. Please resend your 450-4.2.1 message at a later time. If the user is able to receive mail at that 450-4.2.1 time, your message will be delivered. For more information, please 450-4.2.1 visit 450 4.2.1 https://support.google.com/mail/answer/6592 1si9232024lfi.103 - gsmtp (in reply to RCPT TO command)", " {sophos_internal_id}: host gmail-smtp-in.l.google.com[64.233.164.27] said: 450-4.2.1 The user you are trying to contact is receiving mail at a rate that 450-4.2.1 prevents additional messages from being delivered. Please resend your 450-4.2.1 message at a later time. If the user is able to receive mail at that 450-4.2.1 time, your message will be delivered. For more information, please 450-4.2.1 visit 450 4.2.1 https://support.google.com/mail/answer/6592 jn4si9227864lbc.203 - gsmtp (in reply to RCPT TO command)", " {sophos_internal_id}: to=<su.p.e.r.v.iso.r.20.1.5.invino@gmail.com>, relay=alt1.gmail-smtp-in.l.google.com[74.125.23.26]:25, delay=264, delays=262/0/1.6/0.94, dsn=4.2.1, status=deferred (host alt1.gmail-smtp-in.l.google.com[74.125.23.26] said: 450-4.2.1 The user you are trying to contact is receiving mail at a rate that 450-4.2.1 prevents additional messages from being delivered. Please resend your 450-4.2.1 message at a later time. If the user is able to receive mail at that 450-4.2.1 time, your message will be delivered. For more information, please 450-4.2.1 visit 450 4.2.1 https://support.google.com/mail/answer/6592 r9si11244175ioi.12 - gsmtp (in reply to RCPT TO command))", // {sophos_internal_id}: ostgmail-smtp-in.l.google.com[3.1.27] said: 450-4.2.1 The user you are trying to contact is receiving mail at a rate that 450-4.2.1 prevents additional messages from being delivered. Please resend your 450-4.2.1 message at a later time. If the user is able to receive mail at that 450-4.2.1 time, your message will be delivered. For more information, please 450-4.2.1 visit 450 4.2.1 https://support.google.com/mail/answer/6592 si. - gsmtp (in reply to RCPT TO command) // {sophos_internal_id}: {&}o{&}s{&}t{&}gmail-smtp-in.l.google.com[{&}3.{&}1.{&}2{&}7{&}] said: 450-4.2.1 The user you are trying to contact is receiving mail at a rate that 450-4.2.1 prevents additional messages from being delivered. Please resend your 450-4.2.1 message at a later time. If the user is able to receive mail at that 450-4.2.1 time, your message will be delivered. For more information, please 450-4.2.1 visit 450 4.2.1 https://support.google.com/mail/answer/6592 {&}si{&}.{&} - gsmtp (in reply to RCPT TO command){&}", " {sophos_internal_id}: host gmail-smtp-in.l.google.com[173.194.71.27] said: 450-4.2.1 The user you are trying to contact is receiving mail at a rate that 450-4.2.1 prevents additional messages from being delivered. Please resend your 450-4.2.1 message at a later time. If the user is able to receive mail at that 450-4.2.1 time, your message will be delivered. For more information, please 450-4.2.1 visit 450 4.2.1 https://support.google.com/mail/answer/6592 192si9255066lfh.71 - gsmtp (in reply to RCPT TO command)", " {sophos_internal_id}: to=<su.p.e.r.v.iso.r.20.1.5.invino@gmail.com>, relay=alt1.gmail-smtp-in.l.google.com[74.125.23.26]:25, delay=624, delays=622/0.01/1.4/0.94, dsn=4.2.1, status=deferred (host alt1.gmail-smtp-in.l.google.com[74.125.23.26] said: 450-4.2.1 The user you are trying to contact is receiving mail at a rate that 450-4.2.1 prevents additional messages from being delivered. Please resend your 450-4.2.1 message at a later time. If the user is able to receive mail at that 450-4.2.1 time, your message will be delivered. For more information, please 450-4.2.1 visit 450 4.2.1 https://support.google.com/mail/answer/6592 72si20143688iob.61 - gsmtp (in reply to RCPT TO command))", " {sophos_internal_id}: host gmail-smtp-in.l.google.com[64.233.163.27] said: 450-4.2.1 The user you are trying to contact is receiving mail at a rate that 450-4.2.1 prevents additional messages from being delivered. Please resend your 450-4.2.1 message at a later time. If the user is able to receive mail at that 450-4.2.1 time, your message will be delivered. For more information, please 450-4.2.1 visit 450 4.2.1 https://support.google.com/mail/answer/6592 dx2si8644490lbc.94 - gsmtp (in reply to RCPT TO command)", " {sophos_internal_id}: to=<su.p.e.r.v.iso.r.20.1.5.invino@gmail.com>, relay=alt1.gmail-smtp-in.l.google.com[74.125.203.27]:25, delay=1345, delays=1342/0/1.3/0.94, dsn=4.2.1, status=deferred (host alt1.gmail-smtp-in.l.google.com[74.125.203.27] said: 450-4.2.1 The user you are trying to contact is receiving mail at a rate that 450-4.2.1 prevents additional messages from being delivered. Please resend your 450-4.2.1 message at a later time. If the user is able to receive mail at that 450-4.2.1 time, your message will be delivered. For more information, please 450-4.2.1 visit 450 4.2.1 https://support.google.com/mail/answer/6592 e97si20700057ioi.206 - gsmtp (in reply to RCPT TO command))" }); test(similarStrings); } private static void test(List<String> similarStrings){ String lcSubsequence = getLongestCommonSubsequenceForStringGroup(similarStrings); StringBuilder sb = new StringBuilder(); String lcSubstring = getLongestCommonSubstringForStringGroupAndLCS(similarStrings, lcSubsequence); sb.append("{&}"); sb.append(lcSubstring); sb.append("{&}"); System.out.println("current template: \""+sb+"\""); Pattern pattern = ParseMessage.buildPatternWithUnnamedPlaceholders(sb.toString()); System.out.println("matches all?: "+ matchesAll(pattern, similarStrings)); System.out.println(); ////////////////////////////////// List<String> leftSubstrings = buildLeftSubstrings(similarStrings, lcSubstring); System.out.println("current string list:"); for(String s: leftSubstrings){ System.out.println(s); } String left = getNextLeftString(leftSubstrings, lcSubstring); sb.insert(0, left); sb.insert(0, "{&}"); System.out.println("current template: \""+sb+"\""); pattern = ParseMessage.buildPatternWithUnnamedPlaceholders(sb.toString()); System.out.println("matches all?: "+ matchesAll(pattern, similarStrings)); System.out.println(); //////////////////////////// lcSubsequence = getLongestCommonSubsequenceForStringGroup(leftSubstrings); lcSubstring = getLongestCommonSubstringForStringGroupAndLCS(leftSubstrings, lcSubsequence); leftSubstrings = buildLeftSubstrings(leftSubstrings, left); System.out.println("current string list:"); for(String s: leftSubstrings){ System.out.println(s); } left = getNextLeftString(leftSubstrings, lcSubstring); sb.insert(0, left); sb.insert(0, "{&}"); System.out.println("current template: \""+sb+"\""); pattern = ParseMessage.buildPatternWithUnnamedPlaceholders(sb.toString()); System.out.println("matches all?: "+ matchesAll(pattern, similarStrings)); System.out.println(); } private static String getNextLeftString(List<String> leftSubstrings, String lcSubstring){ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } String lcSubsequence = getLongestCommonSubsequenceForStringGroup(leftSubstrings); System.out.println("current lcSubsequence: \"" + lcSubsequence + "\""); String lcSubstringHere = getLongestCommonSubstringForStringGroupAndLCS(leftSubstrings, lcSubsequence); System.out.println("current lcSubstring: \"" + lcSubstringHere + "\""); // int index; List<String> rightSubstrings = buildRightSubstrings(leftSubstrings, lcSubstringHere); for(String s: rightSubstrings){ System.out.println(s); } System.out.println(); while(true){ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } lcSubsequence = getLongestCommonSubsequenceForStringGroup(rightSubstrings); System.out.println("current lcSubsequence: \"" + lcSubsequence + "\""); lcSubstringHere = getLongestCommonSubstringForStringGroupAndLCS(rightSubstrings, lcSubsequence); System.out.println("current lcSubstring: \"" + lcSubstringHere + "\""); // int index; if(lcSubstringHere.length()==1){ break; } rightSubstrings = buildRightSubstrings(leftSubstrings, lcSubstringHere); for(String s: rightSubstrings){ System.out.println(s); } System.out.println(); } return lcSubstringHere; /* ////////////////// lcSubsequence = getLongestCommonSubsequenceForStringGroup(rightSubstrings); System.out.println("current lcSubsequence: \"" + lcSubsequence + "\""); lcSubstringHere = getLongestCommonSubstringForStringGroupAndLCS(rightSubstrings, lcSubsequence); System.out.println("current lcSubstring: \"" + lcSubstringHere + "\""); // int index; rightSubstrings = buildRightSubstrings(leftSubstrings, lcSubstringHere); for(String s: rightSubstrings){ System.out.println(s); } System.out.println(); ////////////////////////////////////// lcSubsequence = getLongestCommonSubsequenceForStringGroup(rightSubstrings); System.out.println("current lcSubsequence: \"" + lcSubsequence + "\""); lcSubstringHere = getLongestCommonSubstringForStringGroupAndLCS(rightSubstrings, lcSubsequence); System.out.println("current lcSubstring: \"" + lcSubstringHere + "\""); // int index; rightSubstrings = buildRightSubstrings(leftSubstrings, lcSubstringHere); for(String s: rightSubstrings){ System.out.println(s); } System.out.println(); ////////////////////////////////////// lcSubsequence = getLongestCommonSubsequenceForStringGroup(rightSubstrings); System.out.println("current lcSubsequence: \"" + lcSubsequence + "\""); lcSubstringHere = getLongestCommonSubstringForStringGroupAndLCS(rightSubstrings, lcSubsequence); System.out.println("current lcSubstring: \"" + lcSubstringHere + "\""); // int index; rightSubstrings = buildRightSubstrings(leftSubstrings, lcSubstringHere); for(String s: rightSubstrings){ System.out.println(s); } System.out.println(); ////////////////////////////////////// return ""; */ } ///////////////////////////////////////////////////////////////////////////////////////////// private static String getLongestCommonSubsequenceForStringGroup(List<String> similarStrings){ if(similarStrings == null || similarStrings.isEmpty()){ throw new IllegalArgumentException("similarStrings shouldn't be null or empty"); } String lcs = similarStrings.get(0); for(String s: similarStrings){ lcs = StringComparison.computeLCSubsequence(s, lcs); } return lcs; } private static String getLongestCommonSubstringForStringGroupAndLCS(List<String> similarStrings, String lcSubsequence){ String lcs = lcSubsequence; for(String s: similarStrings){ lcs = StringComparison.computeLCSubsting(s, lcs); } return lcs; } /** * Проверяет, соответствуют ли все строки в группе переданному регулярному выражению * @param pattern * @param similarStrings * @return */ private static boolean matchesAll(Pattern pattern, List<String> similarStrings){ for(String s: similarStrings){ if(!pattern.matcher(s).matches()){ System.out.println("match fails at: "+s); return false; } } return true; } private static List<String> buildLeftSubstrings(List<String> strings, String lcSubstring){ List<String> leftSubstrings = new ArrayList<String>(strings.size()); int index; for(String s: strings){ index = s.indexOf(lcSubstring); leftSubstrings.add(s.substring(0, index)); } return leftSubstrings; } private static List<String> buildRightSubstrings(List<String> strings, String lcSubstring){ List<String> rightSubstrings = new ArrayList<String>(strings.size()); int index; for(String s: strings){ index = s.indexOf(lcSubstring); index +=lcSubstring.length(); rightSubstrings.add(s.substring(index, s.length())); } return rightSubstrings; } }
package http; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import java.util.UUID; public interface MusicServer { /** * Prepares music server * @param peerId Peer ID for skyway * @param player Audio player * @param channelId Voice channel ID. * @return The URL the browser should next connect to. */ String serve(String peerId, AudioPlayer player, UUID channelId); void stop(UUID channelId); }
package com.eric.tools.ui; import javafx.scene.effect.DropShadow; import javafx.scene.image.Image; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; /** * @ClassName: UIUtils * @Description: UI工具类 * @Author: Eric * @Date: 2019/4/21 0021 * @Email: xiao_cui_vip@163.com */ public final class UIUtils { public static Image createImage( final String path ) { try ( final InputStream is = BuildTypeData.class.getClassLoader( ).getResourceAsStream( path ) ) { return new Image( is ); } catch ( final IOException e ) { LoggerFactory.getLogger( Loggers.MAIN ).warn( "Unable to load image: ", e ); } return null; } public static Font font( final int size, final FontWeight weight ) { return Font.font( "System", weight, size ); } public static Font font( final int size ) { return Font.font( "System", size ); } private static final DropShadow SHADOW_EFFECT = new DropShadow( 10, 3.0f, 3.0f, Color.YELLOW ); public static DropShadow shadowEffect( ) { return SHADOW_EFFECT; } private UIUtils( ) { throw new UnsupportedOperationException( ); } }
package leetcode; /** * @author kangkang lou */ public class Main_410 { public static void main(String[] args) { } }
package crossing.preProcessor; import crossing.preProcessor.MatchingPreProcessor.MATCHING_ACTION; import leafNode.OrderEntry; import orderBook.OrderBook; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Created by dharmeshsing on 11/07/15. */ public class MarketOrderPreProcessorTest { private MarketOrderPreProcessor marketOrderPreProcessor; @Before public void setup(){ marketOrderPreProcessor = new MarketOrderPreProcessor(); } @Test public void testBidPreProcess() throws Exception { OrderEntry orderEntry = mock(OrderEntry.class); when(orderEntry.getPrice()).thenReturn(100L); MATCHING_ACTION result = marketOrderPreProcessor.preProcess(OrderBook.SIDE.BID, orderEntry, 0, 100, 0, 100); assertEquals(MATCHING_ACTION.AGGRESS_ORDER,result); } @Test public void testOfferPreProcess() throws Exception { OrderEntry orderEntry = mock(OrderEntry.class); when(orderEntry.getPrice()).thenReturn(100L); MATCHING_ACTION result = marketOrderPreProcessor.preProcess(OrderBook.SIDE.OFFER, orderEntry, 100, 0, 100, 0); assertEquals(MATCHING_ACTION.AGGRESS_ORDER,result); } @Test public void testNoPriceSet() throws Exception { OrderEntry orderEntry = mock(OrderEntry.class); when(orderEntry.getPrice()).thenReturn(0L); MATCHING_ACTION result = marketOrderPreProcessor.preProcess(OrderBook.SIDE.BID, orderEntry, 0, 0, 0, 0); assertEquals(MATCHING_ACTION.NO_ACTION,result); } }
package it.geosolutions.fra2015.tags; import it.geosolutions.fra2015.mvc.controller.utils.ControllerServices.Profile; import it.geosolutions.fra2015.server.model.user.User; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import org.apache.log4j.Logger; /** * Tag that shows a editable text area when the user in session has the role * contained in editor attribute, and a div if it has not. * * @author Lorenzo Natali * */ /* * <select name="_fraVariable_9_1_1_" rownumber="1"><option * selected="selected">---</option> <option value="Tier 1">Tier 1</option> * <option value="Tier 2">Tier 2</option> <option value="Tier 3">Tier * 3</option></select> </div></td> */ @SuppressWarnings("serial") public class TiersEntry extends SurveyEntry{ Logger LOGGER = Logger.getLogger(this.getClass()); private static String editorStart = "<select name='"; private static String readerStart = "<div>"; private static String editorEnd = "</select>"; private static String readerend = "</div>"; private String editor = "contributor"; private String name; public int doStartTag() { try { JspWriter out = pageContext.getOut(); this.chooseMode(); String value = pageContext.getRequest().getAttribute(this.name) !=null? (String) pageContext.getRequest().getAttribute(this.name):""; int index = 0; //reverse order if("Tier 1".equals(value)) index= 3; if("Tier 2".equals(value)) index= 2; if("Tier 3".equals(value)) index= 1; //print start tag if (this.edit) { out.print(editorStart + this.name + "'>"); String[] options ={ " >---</option>", " value='Tier 3'>Tier 3</option>", " value='Tier 2'>Tier 2</option>", " value='Tier 1'>Tier 1</option>" }; String optionstring = ""; for(int i=0; i<options.length;i++){ optionstring+= "<option " + (index==i? " selected='selected '":"") + options[i]; } out.print(optionstring); } else { out.print(readerStart + value); } } catch (IOException ioe) { LOGGER.error("Error in SimpleTag: " + ioe); } return (SKIP_BODY); } public int doEndTag() throws JspException { try { JspWriter out = pageContext.getOut(); if (this.edit) { out.print(TiersEntry.editorEnd); } else { out.print(TiersEntry.readerend); } } catch (IOException ioe) { LOGGER.error("Error in SimpleTag: " + ioe); } return (SKIP_BODY); } public String getEditor() { return editor; } public void setEditor(String editor) { this.editor = editor; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
import java.sql.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CreatAcc extends JFrame { private JLabel lblUserName; private String [] TrainName= {"ACstandars","parlor class","class"}; private JLabel lblEmail; private JLabel lblPassword; private JLabel lblConfrmPass; private JLabel lblPhnNum; private JLabel lblGender; private String gender; JPanel pnl1; CreatAcc () { super("Creat Account"); pnl1=new JPanel(new GridLayout(13,1)); pnl1.setBorder(BorderFactory.createTitledBorder("Creat Account")); pnl1.setBackground(Color.GRAY); setLayout(new FlowLayout()); getContentPane().setBackground(Color.GRAY ); lblUserName =new JLabel("User Name "); TextField tu=new TextField(); tu.setColumns(20); lblUserName.setForeground(Color.blue); lblUserName.setFont(new Font("Arial", Font.ITALIC, 14)); lblEmail = new JLabel("E-mail "); TextField te=new TextField(); te.setColumns(20); lblEmail.setForeground(Color.blue); lblEmail.setFont(new Font("Arial", Font.ITALIC, 14)); lblPassword = new JLabel("Password "); JPasswordField tp=new JPasswordField(); tp.setColumns(15); lblPassword.setForeground(Color.blue); lblPassword.setFont(new Font("Arial", Font.ITALIC, 14)); lblConfrmPass =new JLabel("Confirm Your Password "); JPasswordField tc=new JPasswordField(); tc.setColumns(15); lblConfrmPass.setForeground(Color.blue); lblConfrmPass.setFont(new Font("Arial", Font.ITALIC, 14)); lblPhnNum =new JLabel("Phone Number"); TextField tphn=new TextField(); tphn.setColumns(20); lblPhnNum.setForeground(Color.blue); lblPhnNum.setFont(new Font("Arial", Font.ITALIC, 14)); lblGender =new JLabel("Gender"); lblGender.setForeground(Color.blue); lblGender.setFont(new Font("Arial", Font.ITALIC, 14)); JRadioButton rmbtn=new JRadioButton("Mail"); rmbtn.setBounds(75,50,100,30); JRadioButton rgbtn=new JRadioButton("Femail"); ButtonGroup group=new ButtonGroup(); JButton btn=new JButton(" Submit "); btn.setForeground(Color.BLUE); add(pnl1); pnl1.add(lblUserName); pnl1.add(tu); pnl1.add(lblEmail); pnl1.add(te); pnl1.add(lblPassword); pnl1.add(tp); pnl1.add(lblConfrmPass); pnl1.add(tc); pnl1.add(lblPhnNum); pnl1.add(tphn); pnl1.add(lblGender); group.add(rmbtn); group.add(rgbtn); pnl1.add(rmbtn); pnl1.add(rgbtn); add(btn); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String s1=tu.getText(); String s2=te.getText(); char[] s3=tp.getPassword(); char[] s4=tc.getPassword(); String s5=new String(s3); String s6=new String(s4); String s7=tphn.getText(); if(rmbtn.isSelected()) { gender=rmbtn.getText(); } else if(rgbtn.isSelected()) { gender=rgbtn.getText(); } if (s5.equals(s6)) { try{ Connection conn=DriverManager.getConnection("jdbc:ucanaccess://E://OOP//Railway Reservation System//Database1.accdb"); String sql="INSERT INTO Users(Name,Email,Password,PhoneNumber,Gender) VALUES(?,?,?,?,?)"; PreparedStatement rs=conn.prepareStatement(sql); rs.setString(1,s1); rs.setString(2,s2); rs.setString(3,s5); rs.setString(4,s7); rs.setString(5,gender); rs.executeUpdate(); } catch(Exception r) { System.out.println(r.getMessage()); } booking b=new booking(s1,s2,s5,s7,gender); b.setLocation(550,250); b.setSize(270,300); b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); b.setVisible(true); dispose(); } else { JOptionPane.showMessageDialog(null, "Your Password and Confirm password Field did not Match", "Error Message", JOptionPane.ERROR_MESSAGE); } } }); } }
package com.pca; import java.math.*; import a2.ab; import Jama.Matrix; public class Pca { //将原始数据标准化 public double[][] Standardlizer(double[][] x){ int n=x.length; //二维矩阵的行号 int p=x[0].length; //二维矩阵的列号 double[] average=new double[p]; //每一列的平均值 double[][] result=new double[n][p]; //标准化后的向量 double[] var=new double[p]; //方差 //取得每一列的平均值 for(int k=0;k<p;k++){ double temp=0; for(int i=0;i<n;i++){ temp+=x[i][k]; } average[k]=temp/n; } //取得方差 for(int k=0;k<p;k++){ double temp=0; for(int i=0;i<n;i++){ temp+=(x[i][k]-average[k])*(x[i][k]-average[k]); } var[k]=temp/(n-1); } //获得标准化的矩阵 for(int i=0;i<n;i++){ for(int j=0;j<p;j++){ result[i][j]=(double) ((x[i][j]-average[j])/Math.sqrt(var[j])); } } return result; } //计算样本相关系数矩阵 public double[][] CoefficientOfAssociation(double[][] x){ int n=x.length; //二维矩阵的行号 int p=x[0].length; //二维矩阵的列号 double[][] result=new double[p][p];//相关系数矩阵 for(int i=0;i<p;i++){ for(int j=0;j<p;j++){ double temp=0; for(int k=0;k<n;k++){ temp+=x[k][i]*x[k][j]; } result[i][j]=temp/(n-1); } } return result; } //计算相关系数矩阵的特征值 public double[][] FlagValue(double[][] x){ //定义一个矩阵 Matrix A = new Matrix(x); //由特征值组成的对角矩阵 Matrix B=A.eig().getD(); double[][] result=B.getArray(); return result; } //计算相关系数矩阵的特征向量 public double[][] FlagVector(double[][] x){ //定义一个矩阵 Matrix A = new Matrix(x); //由特征向量组成的对角矩阵 Matrix B=A.eig().getV(); double[][] result=B.getArray(); return result; } //假设阈值是90%,选取最大的前几个 public int[] SelectPrincipalComponent(double[][] x){ int n=x.length; //二维矩阵的行号,列号 double[] a = new double[n]; int[] result = new int[n]; int k=0; double temp = 0; int m=0; double total=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j){ a[k]=x[i][j]; } } k++; } double[] temp1=new double[a.length]; System.arraycopy(a, 0, temp1, 0, a.length); for(int i=0;i<n;i++){ temp=temp1[i]; for(int j=i;j<n;j++){ if(temp<=temp1[j]){ temp=temp1[j]; temp1[j]=temp1[i]; } temp1[i]=temp; } } for(int i=0;i<n;i++){ temp=a[i]; for(int j=0;j<n;j++){ if(a[j]>=temp){ temp=a[j]; k=j; } result[m]=k; } a[k]=-1000; m++; } for(int i=0;i<n;i++){ total+=temp1[i]; } int sum=1; temp=temp1[0]; for(int i=0;i<n;i++){ if(temp/total<=0.9){ temp+=temp1[i+1]; sum++; } } int[] end=new int[sum]; System.arraycopy(result, 0, end, 0, sum); return end; } //取得主成分 public double[][] PrincipalComponent(double[][] x,int[] y){ int n=x.length; double[][] Result=new double[n][y.length]; int k=y.length-1; for(int i=0;i<y.length;i++){ for(int j=0;j<n;j++){ Result[j][i]=x[j][y[k]]; } k--; } return Result; } }
package oop01.syntax; /* Date : Author : Description : 생성자 문법 */ /* 초기화 - 어떤 작업(현실 : job, 프로그램 : process)을 시작하기 전에 - 준비 (현실 : standby, ready)를 하게 되는데 - 이것을 프로그램에서는 초기화(initializing)라고 한다. */ /* 생성자 - 1. 값을 반환하지 않는다. 따라서 return도 없고 void도 표시하지 않는다. - 2. 생성자의 이름은 클래스의 이름과 동일하다. - 3. 생정자를 명시하지 않으면, 디폴트 생성자(파라미터가 없는)가 컴파일러에 의해 자동 생성된다. - 4. 생성자가 여러 개일 때 다른 생성자를 호출할 수 있다. 이 때 사용되는 특별한 코드가 this()를 통하여 클래스 내부의 다른 생성자를 호출한다. 단, 생성자 맨 첫 줄에서 단 한번만 호출 가능하다. - 5. 4번과 동일한 개념으로 super()로 부모의 생성자를 호출한다. */ public class No05_ConstructSyntax { }
package br.com.bytebank.banco.modelo; import br.com.bytebank.banco.exception.ValorNegativoException; public class ContaCorrente extends Conta implements Tributavel{ public ContaCorrente(int agencia, int numero) { super(agencia, numero); } @Override public void saca(double valor) throws Exception { super.saca(valor + 0.2); } public void deposita(double valor) throws Exception{ if (valor <= 0.1) { throw new ValorNegativoException("Valor do Depósito (R$ " + valor + ") é inválido, digite um número positivo"); } super.saldo += (valor - 0.1); } public double getValorImposto() { return super.saldo * 0.01; } @Override public String toString() { return "ContaCorrente, " + super.toString(); } }
package com.selfridges.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.selfridges.util.Constants; import com.selfridges.util.WebController; public class CheckOutWelcomePage { public WebDriver driver; WebController controller=WebController.getInstance(); @FindBy(linkText = Constants.continueToCheckoutAsAGuestOrANewUserButton) WebElement continueToCheckoutAsAGuestOrANewUserButton; @FindBy(xpath=Constants.email) WebElement email; @FindBy(xpath=Constants.password) WebElement password; @FindBy(xpath=Constants.userCheckOut) WebElement userCheckOut; @FindBy(xpath=Constants.signUpNow) WebElement signUpNow; public CheckOutWelcomePage(WebDriver dr){ driver = dr; } public DeliveryOptionsChooseAddressPage userCheckOut(String eml, String passwd){ email.sendKeys(eml); password.sendKeys(passwd); userCheckOut.click(); return PageFactory.initElements(driver, DeliveryOptionsChooseAddressPage.class); } public DeliveryOptionsChooseAddressPage userCheckOut(){ email.sendKeys(controller.ENV.getProperty("Email")); password.sendKeys(controller.ENV.getProperty("Password")); userCheckOut.click(); return PageFactory.initElements(driver, DeliveryOptionsChooseAddressPage.class); } public CheckoutYourDetailsTab continueToCheckoutAsAGuestOrANewUser(){ continueToCheckoutAsAGuestOrANewUserButton.click(); return PageFactory.initElements(driver, CheckoutYourDetailsTab.class); } public SignUpPage signUpNow(){ signUpNow.click(); return PageFactory.initElements(driver, SignUpPage.class); } }
package com.zhouyi.business.dto; /** * @author 李秸康 * @ClassNmae: UserInfoDto * @Description: 用户信息查询Dto * @date 2019/7/8 8:21 * @Version 1.0 **/ public class UserInfoDto { private String userCode; private String userName; private String userIdcardno; private String userPoliceno; private String userUnitCode; private String userUnitName; private String userPhone; public String getUserPhone() { return userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserIdcardno() { return userIdcardno; } public void setUserIdcardno(String userIdcardno) { this.userIdcardno = userIdcardno; } public String getUserPoliceno() { return userPoliceno; } public void setUserPoliceno(String userPoliceno) { this.userPoliceno = userPoliceno; } public String getUserUnitCode() { return userUnitCode; } public void setUserUnitCode(String userUnitCode) { this.userUnitCode = userUnitCode; } public String getUserUnitName() { return userUnitName; } public void setUserUnitName(String userUnitName) { this.userUnitName = userUnitName; } }
package cl.carlostapia.mvpdagger2template.screens.login.core; /** * Created by CarlosTapia on 12-11-17. */ public class LoginPresenter { }
package com.sysh.entity.update; import java.io.Serializable; /** * ClassName: <br/> * Function: 具体的指标项修改情况<br/> * date: 2018年06月12日 <br/> * * @author 苏积钰 * @since JDK 1.8 */ public class Sh02Model implements Serializable { private String sh005,sh006,sh007,realName; private Long sh01_id,id; public Sh02Model(String sh005, String sh006, String sh007, String realName, Long sh01_id, Long id) { this.sh005 = sh005; this.sh006 = sh006; this.sh007 = sh007; this.realName = realName; this.sh01_id = sh01_id; this.id = id; } public Sh02Model(String sh005, String sh006, String sh007, Long sh01_id, Long id) { this.sh005 = sh005; this.sh006 = sh006; this.sh007 = sh007; this.sh01_id = sh01_id; this.id = id; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public Sh02Model() { super(); } public String getSh005() { return sh005; } public void setSh005(String sh005) { this.sh005 = sh005; } public String getSh006() { return sh006; } public void setSh006(String sh006) { this.sh006 = sh006; } public String getSh007() { return sh007; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public void setSh007(String sh007) { this.sh007 = sh007; } public Long getSh01_id() { return sh01_id; } public void setSh01_id(Long sh01_id) { this.sh01_id = sh01_id; } @Override public String toString() { return "Sh02Model{" + "sh005='" + sh005 + '\'' + ", sh006='" + sh006 + '\'' + ", sh007='" + sh007 + '\'' + ", sh01_id=" + sh01_id + ", id=" + id + '}'; } }
package com.company.plugins; import Instruments.Instrument; import java.beans.ExceptionListener; import java.beans.XMLEncoder; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; public class XMLClass implements IXML { public void xmlSave(Instrument instrument) { try { FileOutputStream fos = new FileOutputStream("test.xml"); XMLEncoder coder = new XMLEncoder(fos); coder.setExceptionListener(new ExceptionListener() { @Override public void exceptionThrown(Exception e) { System.out.println("Exception: " + e.toString()); } }); coder.writeObject(instrument); coder.close(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public String readFile() throws FileNotFoundException { StringBuilder builder = new StringBuilder(); Scanner sc = new Scanner(new File("test.xml")); while(sc.hasNextLine()){ builder.append(sc.nextLine()); } return builder.toString(); } public XMLClass() { } }
package org.training.service.exception; /** * Created by nicko on 1/30/2017. */ public class ServiceException extends RuntimeException { public ServiceException() { super("Exception on service"); } public ServiceException(String message, Throwable cause) { super(message, cause); } }
package com.prashanth.sunvalley.Model; import lombok.Data; import java.math.BigDecimal; @Data class MiscFeeDTO { private String feeName; private BigDecimal feeAmount; private FeeDTO feeDTO; }
// With Ginestra - #24 public class IntegerTreeNode { private int value; private IntegerTreeNode left; private IntegerTreeNode right; public IntegerTreeNode(int newNumber) { value = newNumber; left = null; right = null; } public int getValue() { return value; } public IntegerTreeNode getRight() { return right; } public IntegerTreeNode getLeft() { return left; } public void add(int newNumber) { if (newNumber > this.value) { if (right == null) { right = new IntegerTreeNode(newNumber); } else { right.add(newNumber); } } else { if (left == null) { left = new IntegerTreeNode(newNumber); } else { left.add(newNumber); } } } public void rebalance() { int root = value; if (rightDepth() > leftDepth()) { value = right.getMin(); right.remove(value); add(root); rebalance(); } else if (leftDepth() > rightDepth()) { value = left.getMax(); left.remove(value); add(root); rebalance(); } } private int leftDepth() { if (left == null) { return 0; } else { return left.depth(); } } private int rightDepth() { if (right == null) { return 0; } else { return right.depth(); } } public void remove(int n) { if (this.value == n) { if (left == null && right == null) { this.value = 0; } else if (left == null) { this.value = right.getMin(); if (right.singleValueTree()) { right = null; } else { right.remove(right.getMin()); } } else { this.value = left.getMax(); if (left.singleValueTree()) { left = null; } else { left.remove(left.getMax()); } } } else { if (left != null) { if (left.getValue() == n && left.singleValueTree()) { left = null; } else { left.remove(n); } } if (right != null) { if (right.getValue() == n && right.singleValueTree()) { right = null; } else { right.remove(n); } } } } public boolean singleValueTree() { if (getMin() == getMax()) { return true; } else { return false; } } public void print() { System.out.println("-----"); System.out.println("Value: " + value); if ( left != null) { System.out.println("Left: " + left.getValue()); } else { System.out.println("Left: null"); } if (right != null) { System.out.println("Right: " + right.getValue()); } else { System.out.println("Right: null"); } } public boolean contains(int n) { if (n == this.value) { return true; } else if (n > this.value) { if (right == null){ return false; } else { return right.contains(n); } } else { if (left == null) { return false; } else { return left.contains(n); } } } public int getMax() { if (right == null) { return value; } else { return right.getMax(); } } public int getMin() { if (left == null) { return value; } else { return left.getMin(); } } public String toString() { if ( right == null && left == null) { return "[" + value + " L[] R[]]"; } else if ( right == null ) { return "[" + value + " L" + left.toString() + " R[]]"; } else if ( left == null) { return "[" + value + " L[] R" + right.toString() + "]"; } else { return "[" + value + " L" + left.toString() + " R" + right.toString() + "]"; } } public String toStringSimple() { if ( right == null && left == null) { return "[" + value + "]"; } else if ( right == null ) { return "[" + value + " " + left.toStringSimple() + "]"; } else if ( left == null) { return "[" + value + " " + right.toStringSimple() + "]"; } else { return "[" + value + " " + left.toStringSimple() + " " + right.toStringSimple() + "]"; } } // Sergio's method public int getDepth() { int leftDepth = 0; if (left != null) { leftDepth = left.getDepth(); } int rightDepth = 0; if (right != null) { rightDepth = right.getDepth(); } if (leftDepth > rightDepth) { return 1 + leftDepth; } else { return 1 + rightDepth; } } public int depth() { if (left == null) { if (right == null) { return 1; } else { return right.depth() + 1; } } else if (right == null) { return left.depth() + 1; } else if (left.depth() > right.depth()) { return left.depth() + 1; } else { return right.depth() + 1; } } }
package oop.snakegame; public interface GameAction { void action(Game game); }
package com.breathometer.production.firmware.programming; public class SerialNumber { public static String fromBluetoothAddress(BluetoothAddress bda) { if (bda == null) return null; byte[] _bda = bda.get(); long num = ((_bda[2] & 0x03) << 16) | (_bda[1] << 8) | (_bda[0]); byte week = (byte) ((_bda[2] & 0xFC) >> 2); byte year = _bda[3]; byte stage = _bda[4]; byte vendor = _bda[5]; char[] sn = new char[10]; sn[0] = (char) (vendor & 0x00FF); sn[1] = (char) (stage & 0x00FF); sn[2] = (char) (year & 0x00FF); sn[3] = (char) ((((week / 10) % 10) + 48) & 0x00FF); sn[4] = (char) (((week % 10) + 48) & 0x00FF); sn[5] = (char) ((((num / 10000) % 10) + 48) & 0x00FF); sn[6] = (char) ((((num / 1000) % 10) + 48) & 0x00FF); sn[7] = (char) ((((num / 100) % 10) + 48) & 0x00FF); sn[8] = (char) ((((num / 10) % 10) + 48) & 0x00FF); sn[9] = (char) (((num % 10) + 48) & 0x00FF); return new String(sn); } }
package com.tencent.mm.plugin.sns.model; public interface b$b { void LR(String str); void aS(String str, boolean z); void aT(String str, boolean z); void bxb(); }
package com.uiautomation.steps; import cucumber.api.java.Before; import jline.internal.Log; import net.serenitybdd.core.Serenity; import net.thucydides.core.ThucydidesSystemProperty; import net.thucydides.core.pages.Pages; /** * This is just a place holder class trying to do the UI automation work */ public class Hooks { //@Before public void setSessionVariables() { Serenity.setSessionVariable("Env").to("DEV"); Pages pages = new Pages(); //Read property name String url= pages.getConfiguration().getEnvironmentVariables().getProperty(ThucydidesSystemProperty.WEBDRIVER_BASE_URL.getPropertyName()); Log.info("Application URL: "+ url); //Set Property Name pages.getConfiguration().getEnvironmentVariables() .setProperty(ThucydidesSystemProperty.WEBDRIVER_BASE_URL.getPropertyName(),"http://base url place holder"); String url2= pages.getConfiguration().getEnvironmentVariables().getProperty(ThucydidesSystemProperty.WEBDRIVER_BASE_URL.getPropertyName()); Log.info("Application URL2: "+ url2); } }
package com.tencent.mm.plugin.dbbackup.a; import android.database.Cursor; import com.tencent.mm.plugin.dbbackup.a.a.c; import com.tencent.wcdb.database.SQLiteStatement; import java.util.HashMap; class a$5 implements c { final /* synthetic */ a iaS; final /* synthetic */ HashMap iaV; final /* synthetic */ int iaX; a$5(a aVar, int i, HashMap hashMap) { this.iaS = aVar; this.iaX = i; this.iaV = hashMap; } public final boolean a(Cursor cursor, SQLiteStatement sQLiteStatement) { Long l = (Long) this.iaV.get(Long.valueOf(cursor.getLong(this.iaX))); if (l != null) { sQLiteStatement.bindLong(this.iaX + 1, l.longValue()); } return true; } }
package com.example.admin.busmanagerproject; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import java.util.ArrayList; import Adapter.AdapterBusList; import DatabaseAdapter.DatabaseAdapter; import Model.*; import Model.Bus; public class Bus_List extends AppCompatActivity { String DATABASE_NAME="BusManager.sqlite"; SQLiteDatabase database; ListView listBus; ArrayList<Bus>Buslist; AdapterBusList adapterBusList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bus__list); addControl(); addEvent(); listBus.setAdapter(adapterBusList); } private void addEvent() { getBusDatabaseContext(); } private void addControl() { listBus= (ListView) findViewById(R.id.list_bus); Buslist=new ArrayList<>(); adapterBusList=new AdapterBusList(Bus_List.this,R.layout.bus_item,Buslist); } public void getBusDatabaseContext(){ database=DatabaseAdapter.initDatabase(Bus_List.this,DATABASE_NAME); Cursor cursor=database.rawQuery("SELECT * FROM Bus",null); while (cursor.moveToNext()){ int maXeBus=cursor.getInt(0); int soXeBus=cursor.getInt(1); String biensoxe=cursor.getString(2); Bus bus=new Bus(maXeBus,soXeBus,biensoxe); Buslist.add(bus); } adapterBusList.notifyDataSetChanged(); } }
package ch17.ex17_05; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class ResourceManagerTest { int SIZE = 100; ResourceManager manager; String key; @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { manager = new ResourceManager(); } @After public void tearDown() throws Exception { } @Test public void test() { Resource[] resArr = new Resource[SIZE]; for(int i = 0; i < SIZE; i++){ key = String.valueOf("str:"+i); resArr[i] = manager.getResource(key); resArr[i].use(key, new Integer(i)); key = null; } for(int i = SIZE; i < SIZE / 2; i++){ resArr[i].release(); } System.out.println("gc Run."); Runtime.getRuntime().gc(); manager.shutdown(); } }
package com.sistec.sistecstudents; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.sistec.helperClasses.MyHelperClass; import com.sistec.helperClasses.RemoteServiceUrl; import com.sistec.helperClasses.VolleySingleton; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * A simple {@link Fragment} subclass. */ public class FeeStatusFragment extends Fragment { private static String FEE_STATUS_URL = RemoteServiceUrl.SERVER_URL + RemoteServiceUrl.METHOD_NAME.FEE_STATUS; TextView firstInstPayableTV, firstInstPaidTV, firstInstDuesTV, secondInstPayableTV, secondInstPaidTV, secondInstDuesTV; TextView totalDuesTV, scholarshipTV; private Map<String, String> userStatus; private String e_no, is_login; private HomeActivity homeActivity; public FeeStatusFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_fee_status, container, false); getActivity().setTitle(R.string.title_fee_status); homeActivity = (HomeActivity) getActivity(); userStatus = homeActivity.getUserStatus(); e_no = userStatus.get("e_no"); is_login = userStatus.get("is_login"); findAllIds(rootView); getFeeStatus(); return rootView; } private void findAllIds(View view) { firstInstPayableTV = view.findViewById(R.id.first_inst_payable_TV); firstInstPaidTV = view.findViewById(R.id.first_inst_paid_TV); firstInstDuesTV = view.findViewById(R.id.first_inst_dues_TV); secondInstPayableTV = view.findViewById(R.id.second_inst_payable_TV); secondInstPaidTV = view.findViewById(R.id.second_inst_paid_TV); secondInstDuesTV = view.findViewById(R.id.second_inst_dues_TV); totalDuesTV = view.findViewById(R.id.total_dues_TV); scholarshipTV = view.findViewById(R.id.scholarship_TV); } private void getFeeStatus() { MyHelperClass.showProgress(getActivity(), "Please Wait", "We are loading your Fee status"); StringRequest stringRequest = new StringRequest(Request.Method.POST, FEE_STATUS_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject root = new JSONObject(response); String success = root.getString("success"); if (success.equals("1")) { JSONArray feeStatusArray = root.getJSONArray("fee_status"); JSONObject feeDetails = feeStatusArray.getJSONObject(0); setValuesInTextView(feeDetails); MyHelperClass.hideProgress(); } else { MyHelperClass.hideProgress(); MyHelperClass.showAlerter(homeActivity, "Error", root.getString("message"), R.drawable.ic_error_red_24dp); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.i("Error Responce", error.toString()); MyHelperClass.hideProgress(); } } ) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("e_no", e_no); params.put("is_login", is_login); return params; } }; VolleySingleton.getInstance(getContext()).addToRequestQueue(stringRequest); } private void setValuesInTextView(JSONObject feeStatusJSONObject) { try { firstInstPayableTV.setText(String.format("%.2f", feeStatusJSONObject.getDouble("f_payable"))); firstInstPaidTV.setText(String.format("%.2f", feeStatusJSONObject.getDouble("f_paid"))); firstInstDuesTV.setText(String.format("%.2f", feeStatusJSONObject.getDouble("f_due"))); secondInstPayableTV.setText(String.format("%.2f", feeStatusJSONObject.getDouble("s_payable"))); secondInstPaidTV.setText(String.format("%.2f", feeStatusJSONObject.getDouble("s_paid"))); secondInstDuesTV.setText(String.format("%.2f", feeStatusJSONObject.getDouble("s_due"))); totalDuesTV.setText(String.format("%.2f", feeStatusJSONObject.getDouble("total_due"))); scholarshipTV.setText(feeStatusJSONObject.getString("scholarship")); } catch (JSONException e) { e.printStackTrace(); } } }
package com.satya.springfeatures.exceptions; public class ServiceException extends Exception { /** * */ private static final long serialVersionUID = -2943714933607245449L; private String message; private int errorCode; public ServiceException(String message) { this.message = message; } public ServiceException(String message, int errorCode) { this.message = message; this.errorCode = errorCode; } public ServiceException(String message, int errorCode, Throwable cause) { super(cause); this.message = message; this.errorCode = errorCode; } public ServiceException(Throwable cause) { super(cause); } public ServiceException(String message, Throwable cause) { super(message, cause); } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getErrorCode() { return errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } }
package com.storybox.culturemapg; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONObject; import java.io.Serializable; /** * Created by sunghee on 2016-10-24. */ public class PlaceInfo { public String name, address, icon_path, category, show_ids, contact, introduce, photo_path; public int id, manager_id; public float coordinateX, coordinateY; public PlaceInfo(){ } public PlaceInfo(JSONObject object){ //매니저 id로 php에 접근하여 매니저 정보를 받아와 manager 변수에 넣어야함. //manager = new Manager(manager_id); //show_ids로 php에 접근하여 공연정보들을 받아와 showInfomation 배열변수에 넣어야함. try{ name = object.getString("name"); address = object.getString("address"); icon_path = object.getString("icon_path"); category = object.getString("category"); show_ids = object.getString("show_ids"); contact = object.getString("contact"); introduce = object.getString("introduce"); photo_path = object.getString("photo_path"); id = object.getInt("id"); manager_id = object.getInt("manager_id"); coordinateX = (float)object.getDouble("coordinateX"); coordinateY = (float)object.getDouble("coordinateY"); /* manager = new Manager(manager_id, context); //생성자에서 php접근 필요 String[] show_id = show_ids.split(","); showInfomation = new ShowInfomation[show_id.length]; for(int i=0; i < show_id.length; i++){ showInfomation[i] = new ShowInfomation(Integer.parseInt(show_id[i])); //생성자에서 php접근 필요 } */ }catch(Exception e){ } } }
package com.example.sidenavigationexample; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import android.content.Context; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import com.infideap.drawerbehavior.AdvanceDrawerLayout; import java.util.Timer; import java.util.TimerTask; import me.relex.circleindicator.CircleIndicator; public class MainActivity extends AppCompatActivity { // ViewPagerAdapter vp; ViewPager viewPager; CircleIndicator circleIndicator; int[] imgarr; Timer timer; int len; AdvanceDrawerLayout drawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); id(); drawerLayout.useCustomBehavior(Gravity.START); drawerLayout.setRadius(Gravity.START, 35);//set end container's corner radius (dimension) drawerLayout.setViewScale(Gravity.START, 0.9f); drawerLayout.setViewElevation(Gravity.START, 20); imgarr=new int[]{R.drawable.facebook,R.drawable.insta, R.drawable.snapchat,R.drawable.insta}; len=imgarr.length; ViewPagerAdapter adapter=new ViewPagerAdapter(MainActivity.this,imgarr); viewPager.setAdapter(adapter); circleIndicator.setViewPager(viewPager); TimerTask timerTask = new TimerTask() { @Override public void run() { viewPager.post(new Runnable() { @Override public void run() { if (viewPager.getCurrentItem() == len - 1) { viewPager.setCurrentItem(0); } else { viewPager.setCurrentItem(viewPager.getCurrentItem() + 1); } } }); } }; timer = new Timer(); timer.schedule(timerTask, 3000, 3000); } private void id() { viewPager=findViewById(R.id.pager); circleIndicator=findViewById(R.id.cir); drawerLayout=findViewById(R.id.advdrawlay); } }
package ru.carlson.characters; import ru.carlson.general.Entity; public interface Rotatable { public void rotate(Directions direction); }
package com.rile.methotels.pages.services; import com.rile.methotels.entities.Rezervacija; import com.rile.methotels.services.dao.RezervacijaDao; import java.util.ArrayList; import java.util.List; import org.apache.tapestry5.annotations.RequestParameter; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.util.TextStreamResponse; /** * * @author Stefan */ public class PaginationGridRezervacija { @Inject private RezervacijaDao rezervacijaDao; private int size = 20; Object onActivate(@RequestParameter("page") int page) { Class<?> act = null; int sizeOfAll = rezervacijaDao.getTotalRezervacija(); List<Rezervacija> lista = new ArrayList<Rezervacija>(); String response = "<table class=\"navigation\" > <th>\n" + " Ime rezervacije\n" + " </th>\n" + " "; lista = rezervacijaDao.loadAllRezervacijaFromTo(page); for (Rezervacija r : lista) { response += (" <tr>\n" + " <td> " + r.getIme() + "</td>\n" + " </tr>"); } response += "</table>"; float ceil = (float) sizeOfAll / (float) 20; int totalPageSizes = (int) Math.ceil(ceil); response += "<ul class=\"pagination\">"; for (int i = 1; i <= totalPageSizes; i++) { if (page == i) { response += ("<li class=\"callservice active\"><a href=\"#\">" + i + "</a></li>\n"); } else { response += ("<li class=\"callservice\"><a href=\"#\">" + i + "</a></li>\n"); } } response += "</ul>"; return new TextStreamResponse("text/plain", response); } }
package fr.unice.polytech.clapevents.Activities; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.ToggleButton; import fr.unice.polytech.clapevents.R; import fr.unice.polytech.clapevents.tools.DataBaseHelper; import static java.security.AccessController.getContext; public class DetailActivity extends AppCompatActivity { Bitmap bitmap; Intent intent; String newDate; boolean favorite; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionbar = getSupportActionBar(); intent = getIntent(); ( (TextView) findViewById(R.id.title)).setText(getIntent().getStringExtra("title")); ( (TextView) findViewById(R.id.price)).setText(String.valueOf(getIntent().getIntExtra("price", 0))); ( (TextView) findViewById(R.id.category)).setText(getIntent().getStringExtra("category")); String date = intent.getStringExtra("date"); String[] items = date.split("-"); int year = Integer.valueOf(items[0]); int month = Integer.valueOf(items[1]); int day = Integer.valueOf(items[2]); newDate = items[2] + "/" + items[1] + "/" + items[0]; ( (TextView) findViewById(R.id.date)).setText(newDate); ImageView image = (ImageView) findViewById(R.id.image); try{ String path = getIntent().getStringExtra("pathToPhoto"); bitmap = BitmapFactory.decodeFile(path); Log.e("Path", path); image.setImageBitmap(bitmap); }catch (Exception e){} DataBaseHelper DB = new DataBaseHelper(this); favorite = DB.isFavorite(String.valueOf(getIntent().getIntExtra("key", 0))); Log.e("favorite", String.valueOf(favorite)); ToggleButton heart2 = findViewById(R.id.heart2); heart2.setChecked(favorite); heart2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!favorite) { new DataBaseHelper(getApplicationContext()).addToFavorite(getIntent().getIntExtra("key",0)); } else { new DataBaseHelper(getApplicationContext()).deleteFromFavorite(getIntent().getIntExtra("key",0)); } } }); } public void more(View view){ Intent newIntent = new Intent(this, MoreActivity.class); newIntent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); newIntent.putExtra("key", intent.getIntExtra("key", 0)); newIntent.putExtra("title", intent.getStringExtra("title")); newIntent.putExtra("artists",intent.getStringExtra("artists")); newIntent.putExtra("category",intent.getStringExtra("category")); newIntent.putExtra("description",intent.getStringExtra("description")); newIntent.putExtra("pathToPhoto",intent.getStringExtra("pathToPhoto")); newIntent.putExtra("pathToPhoto2",intent.getStringExtra("pathToPhoto2")); newIntent.putExtra("image_path",intent.getStringExtra("image_path")); newIntent.putExtra("pathToPhoto4",intent.getStringExtra("pathToPhoto4")); newIntent.putExtra("age",intent.getIntExtra("age", 0)); startActivity(newIntent); } public void map(View view){ Intent newIntent = new Intent(this, MapsActivity.class); newIntent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); newIntent.putExtra("key", intent.getIntExtra("key", 0)); newIntent.putExtra("place", intent.getStringExtra("place")); newIntent.putExtra("address",intent.getStringExtra("address")); newIntent.putExtra("image_place",intent.getStringExtra("image_place")); startActivity(newIntent); } public void pay(View view){ Intent newIntent = new Intent(this, PayActivity.class); newIntent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); newIntent.putExtra("key", intent.getIntExtra("key", 0)); newIntent.putExtra("title", intent.getStringExtra("title")); newIntent.putExtra("date",intent.getStringExtra("date")); newIntent.putExtra("category",intent.getStringExtra("category")); newIntent.putExtra("place",intent.getStringExtra("place")); newIntent.putExtra("address",intent.getStringExtra("address")); newIntent.putExtra("price",intent.getIntExtra("price", 0)); newIntent.putExtra("age",intent.getIntExtra("age", 0)); newIntent.putExtra("pathToPhoto",intent.getStringExtra("pathToPhoto")); startActivity(newIntent); } public void calendar(View view){ Intent newIntent = new Intent(this, CalendarActivity.class); newIntent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); newIntent.putExtra("key", intent.getIntExtra("key", 0)); newIntent.putExtra("title", intent.getStringExtra("title")); newIntent.putExtra("date", newDate); newIntent.putExtra("place",intent.getStringExtra("place")); newIntent.putExtra("address",intent.getStringExtra("address")); startActivity(newIntent); } }
package tp.ia.caperucita.actions; import java.util.ArrayList; import frsf.cidisi.faia.agent.search.SearchAction; import frsf.cidisi.faia.agent.search.SearchBasedAgentState; import frsf.cidisi.faia.state.AgentState; import frsf.cidisi.faia.state.EnvironmentState; import tp.ia.caperucita.EstadoAgenteCaperucitaRoja; import tp.ia.caperucita.EstadoAmbienteCaperucitaRoja; import tp.ia.caperucita.Helper; import tp.ia.caperucita.PercepcionCaperucitaRoja; public class IrAlOeste extends SearchAction { @Override public String toString() { return "Ir al oeste"; }; @Override public Double getCost() { return null; } @Override public EnvironmentState execute(AgentState ast, EnvironmentState est) { EstadoAgenteCaperucitaRoja estadoAgenteCaperucitaRoja = (EstadoAgenteCaperucitaRoja) ast; EstadoAmbienteCaperucitaRoja estadoAmbienteCaperucitaRoja = (EstadoAmbienteCaperucitaRoja) est; int x = estadoAgenteCaperucitaRoja.getX(); int y = estadoAgenteCaperucitaRoja.getY(); ArrayList<Integer> columna = estadoAgenteCaperucitaRoja.getColumna(0); if (columna.size() <= y || y < 0) return null; ArrayList<Integer> fila = estadoAgenteCaperucitaRoja.getFila(y); /** Evalúa las precondiciones */ if (x <= 0) return null; if (fila.get(x - 1) != PercepcionCaperucitaRoja.PERCEPCION_VACIO) return null; if (Helper.enLineaDeVista(fila, x - 1, -1, PercepcionCaperucitaRoja.PERCEPCION_LOBO) != -1) return null; if (Helper.enLineaDeVista(fila, x - 1, -1, PercepcionCaperucitaRoja.PERCEPCION_DULCE) != -1) return null; /** Busca la posición anterior al arbol en su linea de vista */ int proximaColumna = Helper.enLineaDeVista(fila, x, -1, PercepcionCaperucitaRoja.PERCEPCION_ARBOL) + 1; estadoAgenteCaperucitaRoja.setX(proximaColumna); estadoAgenteCaperucitaRoja.contarCeldaVisitada(); estadoAmbienteCaperucitaRoja.setCaperucitaRojaX(proximaColumna); estadoAmbienteCaperucitaRoja.moverLobo(); return estadoAmbienteCaperucitaRoja; } @Override public SearchBasedAgentState execute(SearchBasedAgentState s) { EstadoAgenteCaperucitaRoja estadoAgenteCaperucitaRoja = (EstadoAgenteCaperucitaRoja) s; int y = estadoAgenteCaperucitaRoja.getY(); int x = estadoAgenteCaperucitaRoja.getX(); ArrayList<Integer> columna = estadoAgenteCaperucitaRoja.getColumna(0); if (columna.size() <= y || y < 0) return null; ArrayList<Integer> fila = estadoAgenteCaperucitaRoja.getFila(y); /** Evalúa las precondiciones */ if (x <= 0) return null; if (fila.get(x - 1) != PercepcionCaperucitaRoja.PERCEPCION_VACIO) return null; if (Helper.enLineaDeVista(fila, x - 1, -1, PercepcionCaperucitaRoja.PERCEPCION_LOBO) != -1) return null; if (Helper.enLineaDeVista(fila, x - 1, -1, PercepcionCaperucitaRoja.PERCEPCION_DULCE) != -1) return null; /** Busca la posición anterior al arbol en su linea de vista */ int proximaColumna = Helper.enLineaDeVista(fila, x, -1, PercepcionCaperucitaRoja.PERCEPCION_ARBOL) + 1; estadoAgenteCaperucitaRoja.setX(proximaColumna); estadoAgenteCaperucitaRoja.contarCeldaVisitada(); return estadoAgenteCaperucitaRoja; } }
package es.uma.sportjump.sjs.service.services.test.util; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import es.uma.sportjump.sjs.model.entities.Coach; import es.uma.sportjump.sjs.model.entities.Exercise; import es.uma.sportjump.sjs.model.entities.ExerciseBlock; import es.uma.sportjump.sjs.service.services.ExerciseService; @Component public class ExerciseServiceTestUtil { @Autowired ExerciseService exerciseService; public ExerciseBlock createExerciseBlock(int num, Coach coach) { //Variables String name = "bloque fuerza" + num; String type = "Fuerza" + num; String description = "Haremos hincapie en la fuerza de hombros" + num; String exerciseName1 = "15 X 50kg hombros" + num; String exerciseName2 = "10 X 40kg dorsales" + num; Exercise exercise1 = new Exercise(); exercise1.setName(exerciseName1); exercise1.setPos(1); Exercise exercise2 = new Exercise(); exercise2.setName(exerciseName2); exercise2.setPos(2); List<Exercise> exerciseList = new ArrayList<Exercise>(); exerciseList.add(exercise1); exerciseList.add(exercise2); return exerciseService.setNewExerciseBlock(name, type, description, exerciseList, coach); } public void removeExerciseBlock (ExerciseBlock exerciseBlock){ exerciseService.removeExerciseBlock(exerciseBlock); } }
package de.jmda9.core.util; import java.io.File; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; public class TestPackageUtil { private final static Logger LOGGER = LogManager.getLogger(TestPackageUtil.class); @Test public void test() { PackageUtil.directoryTreeAsPackageNames(new File("src/main/java")).forEach(LOGGER::debug);; } }
package com.tencent.mm.plugin.ac; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.tencent.map.lib.gl.model.GLIcon; import com.tencent.mm.a.e; import com.tencent.mm.ab.b; import com.tencent.mm.ab.w; import com.tencent.mm.platformtools.ab; import com.tencent.mm.plugin.ac.a.a; import com.tencent.mm.plugin.comm.a.d; import com.tencent.mm.pluginsdk.model.app.ae; import com.tencent.mm.pluginsdk.model.app.f; import com.tencent.mm.pluginsdk.model.app.i; import com.tencent.mm.protocal.c.bhy; import com.tencent.mm.protocal.c.cu; import com.tencent.mm.protocal.c.cv; import com.tencent.mm.sdk.platformtools.BackwardSupportUtil; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.x; import java.util.LinkedList; import java.util.List; class a$1 implements a { final /* synthetic */ a lNi; a$1(a aVar) { this.lNi = aVar; } public final f Jn(String str) { return a.bmf().SW(str); } public final f Jo(String str) { a.bme(); if (str == null || str.length() == 0) { return null; } List linkedList = new LinkedList(); linkedList.add(str); ae aeVar = new ae(linkedList); b.a aVar = new b.a(); aVar.dIG = new cu(); aVar.dIH = new cv(); aVar.uri = "/cgi-bin/micromsg-bin/appcenter"; aVar.dIF = 452; aVar.dII = 0; aVar.dIJ = 0; b KT = aVar.KT(); cu cuVar = (cu) KT.dID.dIL; byte[] cbx = aeVar.cbx(); if (cbx != null) { cuVar.rcT = new bhy().bq(cbx); } cuVar.hcE = 7; com.tencent.mm.ab.a.a b = w.b(KT); x.e("MicroMsg.AppInfoService", "call getAppInfoList cgi result, errType = %d, errCode = %d", new Object[]{Integer.valueOf(b.errType), Integer.valueOf(b.errCode)}); if (b.errType != 0 || b.errCode != 0) { return null; } aeVar.bg(ab.a(((cv) b.dIv).rcU)); aeVar.a(0, b.errType, b.errCode, b.Yy, KT, new byte[0]); a bmm = a.a.bmm(); if (bmm != null) { return bmm.Jn(str); } x.e("MicroMsg.AppInfoService", "getISubCorePluginBase() == null"); return null; } public final Cursor bmj() { Cursor rawQuery = a.bmf().rawQuery("select * from AppInfo where status = 5 order by modifyTime asc", new String[0]); if (rawQuery != null) { return rawQuery; } x.e("MicroMsg.AppInfoStorage", "getAppByStatus : cursor is null"); return null; } public final Cursor n(int[] iArr) { i bmf = a.bmf(); String str = "select * from AppInfo where "; for (int i = 0; i <= 0; i++) { str = str + " status = " + iArr[0]; } Cursor rawQuery = bmf.rawQuery(str + " order by status desc, modifyTime asc", new String[0]); if (rawQuery != null) { return rawQuery; } x.e("MicroMsg.AppInfoStorage", "getAppByStatus : cursor is null"); return null; } public final Bitmap a(String str, int i, float f) { a.bmf(); if (str == null || str.length() == 0) { x.e("MicroMsg.AppInfoStorage", "getIcon : invalid argument"); return null; } else if (str.equals("wx7fa037cc7dfabad5")) { return BitmapFactory.decodeResource(ad.getContext().getResources(), d.app_icon); } else { String cQ = i.cQ(str, i); if (e.cn(cQ)) { return BackwardSupportUtil.b.e(cQ, f); } x.e("MicroMsg.AppInfoStorage", "icon does not exist, iconPath = " + cQ + ", iconType = " + i); return null; } } public final void bS(String str, int i) { a.bmd().cO(str, i); } public final void Jp(String str) { a.bme().SU(str); } public final void c(f fVar) { i bmf = a.bmf(); if (fVar != null && fVar.field_status != 5) { fVar.field_status = 3; x.i("MicroMsg.AppInfoStorage", "setBlack package name = %s", new Object[]{fVar.field_packageName}); bmf.a(fVar, new String[0]); } } public final void d(f fVar) { i bmf = a.bmf(); if (fVar != null && fVar.field_status == 3) { fVar.field_status = 4; bmf.a(fVar, new String[0]); } } public final void e(f fVar) { a.bmf().a(fVar, new String[0]); } public final i bmk() { return a.bmf(); } public final void X(LinkedList<String> linkedList) { a.bme().ap(linkedList); } public final Cursor dh(int i, int i2) { return a.bmf().dh(i, i2); } public final Cursor bml() { i bmf = a.bmf(); StringBuilder stringBuilder = new StringBuilder(GLIcon.TOP); stringBuilder.append("select * from AppInfo"); stringBuilder.append(" where "); stringBuilder.append("serviceAppType > 0"); Cursor rawQuery = bmf.rawQuery(stringBuilder.toString(), new String[0]); if (rawQuery == null) { x.e("MicroMsg.AppInfoStorage", "getAllServices : cursor is null"); return null; } x.d("MicroMsg.AppInfoStorage", "getAllServices count = %d", new Object[]{Integer.valueOf(rawQuery.getCount())}); return rawQuery; } }
package com.james.pojo; import lombok.Data; import java.util.Date; @Data //订单表 public class Orders { private int oid; private String oname; private String ovehicle; private String ocolor; private Date otime; private double omoney; private int ocount; private String omaimai; }
package edunova; import javax.swing.JOptionPane; public class Zadatak6 { //Upiši dva cijela broja //ispiši //Zbroj //Razliku //Produkt //Kvocijent //Aritmetičku sredinu //zbroj kvadtara brojeva public static void main(String[] args) { int i = Integer.parseInt(JOptionPane.showInputDialog("unesite broj:")); int j = Integer.parseInt(JOptionPane.showInputDialog("unesite broj:")); System.out.println(i+j); System.out.println(i-j); System.out.println(i*j); System.out.println(i/j); System.out.println(i+j/2); System.out.println((i*i)+(j*j)); } }
package com.rackspace.sl.suite; import java.util.Arrays; import java.util.Collections; public class SortElements { public static void main(String[] args) { Integer[] arr = { 1, 23, 4, 5, 6, 40, 7, 98 }; Arrays.sort(arr, Collections.reverseOrder()); System.out.println("Elements : %s" + Arrays.toString(arr)); Arrays.sort(arr); System.out.println("Elements 111 : " + Arrays.toString(arr)); String[] strArr = { "h", "d", "u", "a", "y", "b", "m", "e" }; Arrays.sort(strArr, Collections.reverseOrder()); System.out.println("Elements strArr : %s" + Arrays.toString(strArr)); Arrays.sort(strArr); System.out.println("Elements strArr 111 : " + Arrays.toString(strArr)); } }
package se.iths.labb3; import javafx.scene.paint.Color; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import se.iths.labb3.shapes.Shapes; import static org.assertj.core.api.Assertions.assertThat; class ModelTest { Model model; @BeforeEach void setUp() { model = new Model(); } @Test void whenTryingToAddNewSquareANewSquareShouldBePutInTheList() { model.shapes.add(Shapes.squareOf(1,1,5, Color.BLACK)); assertThat(model.shapes.size()).isEqualTo(1); } @Test void whenTryingToAddNewCircleANewCircleShouldBePutInTheList() { model.shapes.add(Shapes.circleOf(2,2,10, Color.RED)); assertThat(model.shapes.size()).isEqualTo(1); } // @Test // void getSizeShouldReturnSize() { // assertThat(model.getSize()).isEqualTo(model.size); // } // @Test // void getColorShouldReturnColor() { // // } }
package com.hanbit.spring.web.controller; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller public class SecurityController { @RequestMapping(value="/signin", method=RequestMethod.GET) public String signin(HttpSession session, HttpServletResponse res) throws Exception { Boolean signedIn = (Boolean) session.getAttribute("signedIn"); if (signedIn != null && signedIn) { res.sendRedirect("/"); return null; } return "signin"; } @RequestMapping(value="/signin", method=RequestMethod.POST) public void doSignin(@RequestParam("email") String email, @RequestParam("passwd") String passwd, HttpSession session, HttpServletResponse res) throws Exception { if ("abcd@abcd.com".equals(email) && "1234".equals(passwd)) { session.setAttribute("signedIn", true); session.setAttribute("email", email); session.setAttribute("role", "USER"); res.sendRedirect("/"); } else if ("ceo@abcd.com".equals(email) && "1234".equals(passwd)) { session.setAttribute("signedIn", true); session.setAttribute("email", email); session.setAttribute("role", "CEO"); res.sendRedirect("/"); } else { res.sendRedirect("/signin?msg=wrong"); } } @RequestMapping("/signout") public void doSignout(HttpSession session, HttpServletResponse res) throws Exception { session.invalidate(); res.sendRedirect("/signin"); } }
package com.service; import com.bean.ArrangementInfo; import java.util.List; public interface ArrangementInfoService { List<ArrangementInfo> getArrangementInfo(ArrangementInfo arrangementInfo); }
package edu.mayo.cts2.framework.webapp.rest.exception; import edu.mayo.cts2.framework.model.castor.MarshallSuperClass; import edu.mayo.cts2.framework.model.service.core.types.LoggingLevel; import edu.mayo.cts2.framework.model.service.exception.CTS2Exception; import edu.mayo.cts2.framework.model.util.ModelUtils; public class StatusSettingCts2RestException extends CTS2Exception implements MarshallSuperClass { private static final long serialVersionUID = 8198403323810182068L; private int statusCode; public StatusSettingCts2RestException( String message, int statusCode){ this.statusCode = statusCode; this.setSeverity(LoggingLevel.ERROR); this.setCts2Message(ModelUtils.createOpaqueData(message)); } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } }
/* * 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 model.dao; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import model.entity.DBEntity; import model.entity.User; /** * Creator of the user object * @author Sasha */ public class UserCreator extends EntityCreator { /** * Constructor */ public UserCreator() { super(USER_TABLE, USER_ID); } /** * Insert user into the data base from the object oriented entity * * @param user user might be inserting into the data base * @throws SQLException * @throws ServerOverloadedException * @return true is user inserting was successfull and false otherwise */ public boolean insertUser(User user) throws SQLException, ServerOverloadedException { boolean flag = false; WrapperConnectionProxy wrapperConnection = null; try { wrapperConnection = CONNECTION_POOL.getConnection(); try (PreparedStatement ps = wrapperConnection. prepareStatement(SQL_FOR_USER_INSERTING)) { ps.setString(1, user.getFirstName()); ps.setString(2, user.getLastName()); ps.setString(3, user.getEmail()); ps.setString(4, user.getPassword()); ps.executeUpdate(); flag = true; } } finally { if (wrapperConnection != null) { wrapperConnection.close(); } } return flag; } /** * Update users' private information (first name, last name and email only) * @param newUser user object with new information * @return boolean true if updating was successful and false otherwise * @throws SQLException * @throws ServerOverloadedException */ public boolean updateUser(User newUser) throws SQLException, ServerOverloadedException { boolean flag = false; WrapperConnectionProxy wrapperConnection = null; try { wrapperConnection = CONNECTION_POOL.getConnection(); try (PreparedStatement ps = wrapperConnection. prepareStatement(SQL_FOR_USER_UPDATING)) { ps.setString(1, newUser.getFirstName()); ps.setString(2, newUser.getLastName()); ps.setString(3, newUser.getEmail()); ps.setInt(4, newUser.getId()); ps.executeUpdate(); flag = true; } } finally { if (wrapperConnection != null) { wrapperConnection.close(); } } return flag; } /** * Change user password * @param user user object (here admin id is required only) * @param newPassword new user password * @return true if password changing is successful and false otherwise * @throws SQLException * @throws ServerOverloadedException */ public boolean changePassword(User user, String newPassword) throws SQLException, ServerOverloadedException { boolean flag = false; WrapperConnectionProxy wrapperConnection = null; try { wrapperConnection = CONNECTION_POOL.getConnection(); try (PreparedStatement ps = wrapperConnection. prepareStatement(SQL_TO_CHANGE_PASSWORD)) { ps.setString(1, newPassword); ps.setInt(2, user.getId()); ps.executeUpdate(); flag = true; } } finally { if (wrapperConnection != null) { wrapperConnection.close(); } } return flag; } /** * Get user from DB by email * @param email user's email * @return user if such user exists or null otherwise * @throws SQLException * @throws ServerOverloadedException */ public DBEntity getUserByEmail(String email) throws SQLException, ServerOverloadedException { WrapperConnectionProxy wrapperConnection = null; try { wrapperConnection = CONNECTION_POOL.getConnection(); PreparedStatement ps = wrapperConnection.prepareStatement(SQL_FOR_USER_BY_EMAIL); ps.setString(1, email); ResultSet rs = ps.executeQuery(); if (rs.next()) { return getEntity(rs); } } finally { if (wrapperConnection != null) { wrapperConnection.close(); } } return null; } /** * Get one user by result set * * @param rs result set of sql query * @return DBEntity object * @throws SQLException */ @Override protected DBEntity getEntity(ResultSet rs) throws SQLException { int id = rs.getInt("user_id"); String firstName = rs.getString("first_name"); String lastName = rs.getString("last_name"); String email = rs.getString("email"); String password = rs.getString("password"); BigDecimal account = rs.getBigDecimal("account"); User newUser = new User(firstName, lastName, email, password); newUser.setId(id); newUser.setAccount(account); return newUser; } }
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class HashTree<HashTreeNode, E> { public class HashTreeNode<List> { private HashTreeNode<List>[] children; private List element; @SuppressWarnings("unchecked") public HashTreeNode() { this.element = null; this.children = new HashTreeNode[5]; } public List getElement() { return this.element; } public List setElement(List element) { List tbr = this.element; this.element = element; return tbr; } public HashTreeNode<List>[] getChildren() { return this.children; } } //end of HashTreeNode //start of HashTree private HashTreeNode<List> root; public HashTree() { this.root = new HashTreeNode<List>(); } public void CreateTree(List<E> datalist){ if(datalist.isEmpty()){ System.out.println("error"); } Iterator iterator=datalist.iterator(); while(iterator.hasNext()){ } } }
package ca.csf.rrr.gameobjects; import java.util.ArrayList; import java.util.List; import java.util.Random; import ca.csf.rrr.gameworld.GameRenderer; import ca.csf.rrr.gameworld.GameWorld; public class ScrollHandler { private final static int SCROLL_SPEED = 300; private final static int FIRST_BOX_GAP = 175; private final static int MIN_BOX_GAP = 300; private final static int MAX_BOX_GAP = 446; private final static int NBR_BOX = 3; private final static int POSITION_Y_SKY = 64; private final static int HEIGHT_SKY = 128; private final static int HEIGHT_MOUNTAIN = 200; private final static int MIN_BOX_SIZE = 32; private final static int MAX_BOX_SIZE = 64; private final static int SCROLL_SPEED_SKY = SCROLL_SPEED/8; private final static int SCROLL_SPEED_MOUNTAIN = SCROLL_SPEED/8; private Grass frontGrass; private Grass backGrass; private BackgroundLayer frontSky, backSky, frontMountains, backMountains; private Enemy enemy; private List<Box> boxList; private GameWorld gameWorld; public ScrollHandler(GameWorld gameWorld) { this.gameWorld = gameWorld; frontGrass = new Grass(0, GameRenderer.getHeight() - gameWorld.getGroundRect().getHeight(), GameRenderer.getWidth(), (int)gameWorld.getGroundRect().getHeight(), SCROLL_SPEED); backGrass = new Grass(frontGrass.getTailX(), GameRenderer.getHeight() - gameWorld.getGroundRect().getHeight(), GameRenderer.getWidth(), (int)gameWorld.getGroundRect().getHeight(), SCROLL_SPEED); frontSky = new BackgroundLayer(0, POSITION_Y_SKY, GameRenderer.getWidth(), HEIGHT_SKY, SCROLL_SPEED_SKY); backSky = new BackgroundLayer(frontSky.getTailX(), POSITION_Y_SKY, GameRenderer.getWidth(), HEIGHT_SKY, SCROLL_SPEED_SKY); frontMountains = new BackgroundLayer(0, HEIGHT_SKY, GameRenderer.getWidth(), HEIGHT_MOUNTAIN, SCROLL_SPEED_MOUNTAIN); backMountains = new BackgroundLayer(frontMountains.getTailX(), HEIGHT_SKY, GameRenderer.getWidth(), HEIGHT_MOUNTAIN, SCROLL_SPEED_MOUNTAIN); enemy = new Enemy(GameRenderer.getWidth(), GameRenderer.getHeight() - gameWorld.getGroundRect().getHeight() - HEIGHT_SKY, POSITION_Y_SKY, HEIGHT_SKY, SCROLL_SPEED); boxList = new ArrayList<Box>(); initBoxes(); } public BackgroundLayer getBackSky() { return backSky; } public BackgroundLayer getFrontSky() { return frontSky; } public Enemy getEnemy() { return enemy; } public BackgroundLayer getFrontMountains() { return frontMountains; } public BackgroundLayer getBackMountains() { return backMountains; } public void update(float delta) { frontGrass.update(delta); backGrass.update(delta); frontSky.update(delta); backSky.update(delta); frontMountains.update(delta); backMountains.update(delta); enemy.update(delta); int i = 0; for (Box box : boxList) { box.update(delta); Random random = new Random(); float posX = FIRST_BOX_GAP + random.nextInt(MAX_BOX_GAP); if (i == 0) { posX += boxList.get(boxList.size() - 1).getTailX(); } else { posX += boxList.get(i - 1).getTailX(); } int size = random.nextInt(MAX_BOX_SIZE - MIN_BOX_SIZE) + MIN_BOX_SIZE; if (box.isScrolledLeft()) { box.reset(posX); box.setWidth(size); box.setHeight(size); box.position.y = GameRenderer.getHeight() - gameWorld.getGroundRect().getHeight() - size; } i++; } if (frontGrass.isScrolledLeft()) { frontGrass.reset(backGrass.getTailX()); } else if (backGrass.isScrolledLeft()) { backGrass.reset(frontGrass.getTailX()); } if (frontSky.isScrolledLeft()) { frontSky.reset(backSky.getTailX()); } else if (backSky.isScrolledLeft()) { backSky.reset(frontSky.getTailX()); } if (frontMountains.isScrolledLeft()) { frontMountains.reset(backMountains.getTailX()); } else if (backMountains.isScrolledLeft()) { backMountains.reset(frontMountains.getTailX()); } } public void onRestart() { frontGrass.onRestart(0, SCROLL_SPEED); backGrass.onRestart(frontGrass.getTailX(), SCROLL_SPEED); frontSky.reset(0); backSky.reset(frontSky.getTailX()); enemy.reset(0); initBoxes(); } public Grass getFrontGrass() { return frontGrass; } public Grass getBackGrass() { return backGrass; } public List<Box> getBoxList() { return boxList; } private void initBoxes() { boxList.removeAll(boxList); Random random = new Random(); for (int i = 0; i < NBR_BOX; ++i) { int gapToAdd = random.nextInt(MIN_BOX_GAP); float posX = MAX_BOX_GAP + gapToAdd; if (i > 0) { posX = boxList.get(i - 1).getTailX() + FIRST_BOX_GAP + gapToAdd; } boxList.add(new Box(posX, GameRenderer.getHeight() - POSITION_Y_SKY, MIN_BOX_SIZE, MIN_BOX_SIZE, SCROLL_SPEED)); } } }
package domain.businessRuleType; import domain.businessRule.Definition; import java.util.ArrayList; import java.util.List; /** * Created by Unknown on 01/18/2017. */ public abstract class BusinessRuleType { private List<ITemplate> templates; private String code; private String name; private String description; private List<Operator> operators; private static List<BusinessRuleType> allRuleTypes; public BusinessRuleType(String code, String name, String description) { this.templates = new ArrayList<ITemplate>(); this.code = code; this.name = name; this.description = description; } public String getName(){ return this.name; } public List<Operator> getOperators() { return operators; } public void setOperators(List<Operator> operators){ this.operators = operators; } public abstract void validate(List<Definition> definitions); protected void addTemplate(ITemplate template){ templates.add(template); } public List<ITemplate> getTemplates() { return templates; } public static List<BusinessRuleType> getAllRuleTypes(){ return allRuleTypes; } }
package com.example.chatapp.fragments; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.chatapp.R; import com.example.chatapp.adapters.AdapterPosts; import com.example.chatapp.models.ModelPost; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class AnnouncementFragment extends Fragment { //firebase auth FirebaseAuth firebaseAuth; RecyclerView recyclerView; List<ModelPost> postList; AdapterPosts adapterPosts; public AnnouncementFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_announcement, container, false); //init firebaseAuth = FirebaseAuth.getInstance(); //recycler view and its properties recyclerView = view.findViewById(R.id.postsRecyclerView); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); //show newest post first, for this load from last layoutManager.setStackFromEnd(true); layoutManager.setReverseLayout(true); //set layout to recyclerView recyclerView.setLayoutManager(layoutManager); //init post list postList = new ArrayList<>(); loadPosts(); return view; } private void loadPosts() { //path of all posts DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts"); //get all data from this ref ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { postList.clear(); for (DataSnapshot ds : dataSnapshot.getChildren()) { ModelPost modelPost = ds.getValue(ModelPost.class); postList.add(modelPost); //adapter adapterPosts = new AdapterPosts(getActivity(), postList); //set adapter to recyclerView recyclerView.setAdapter(adapterPosts); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { //in case of error Toast.makeText(getActivity(), ""+databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } }); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { setHasOptionsMenu(true);//to show menu option in fragment super.onCreate(savedInstanceState); } }
package com.uwetrottmann.trakt5.entities; import com.uwetrottmann.trakt5.enums.Rating; import org.threeten.bp.OffsetDateTime; public class BaseRatedEntity { public OffsetDateTime rated_at; public Rating rating; }
package sim.estoque.itemmovimento; import java.util.List; import org.hibernate.Session; public class ItemMovimentoDAOHibernate implements ItemMovimentoDAO { private Session session; @Override public void salvar(ItemMovimento itemMovimento) { this.session.save(itemMovimento); } @Override public void excluir(ItemMovimento itemMovimento) { this.session.delete(itemMovimento); } @Override public void atualizar(ItemMovimento itemMovimento) { this.session.update(itemMovimento); } @Override public ItemMovimento carregar(Integer codigo) { return (ItemMovimento) this.session.get(ItemMovimento.class, codigo); } @Override public List<ItemMovimento> listar() { return this.session.createCriteria(ItemMovimento.class).list(); } public Session getSession() { return session; } public void setSession(Session session) { this.session = session; } }
package com.blackbox.starter.events; import java.io.Serializable; /** * Created by toktar. */ public abstract class CarEvent implements Serializable, ICarEvent { protected long timestamp; protected String eventId; //protected long mileage; @Override public int compareTo(Object obj) { CarEvent carEvent = (CarEvent)obj; if(carEvent.getEventId().equals(this.getEventId())) return 0; return carEvent.getTimestamp()<this.getTimestamp()?1:-1; } /*@Override public String toString() { return "timestamp=" + timestamp + ", eventId='" + eventId + '\'' + ", mileage=" + mileage; } public long getMileage() { return mileage; }*/ public String toString() { return "timestamp=" + timestamp + ", eventId='" + eventId + '\''; } public long getTimestamp() { return timestamp; } public String getEventId() { return eventId; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public void setEventId(String eventId) { this.eventId = eventId; } /*public void setMileage(long mileage) { this.mileage = mileage; }*/ public int compare(CarEvent event1, CarEvent event2) { return event1.getTimestamp()>event2.getTimestamp()?1:-1; } }
package com.nuuedscore.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.nuuedscore.domain.Site; import com.nuuedscore.repository.SiteRepository; import com.nuuedscore.service.BaseService; import com.nuuedscore.service.ISiteService; import lombok.extern.slf4j.Slf4j; /** * Site Service Implementaton * * @author PATavares * @since Feb 2021 * */ @Slf4j @Service public class SiteService extends BaseService implements ISiteService { @Autowired private SiteRepository siteRepository; @Override public List<Site> findAll() { return (List<Site>) siteRepository.findAll(); } }
package com.testing.class8; import junit.framework.TestCase; public class fibTest extends TestCase { fib ft=new fib(); public void testFib() { assertEquals(33,ft.fib(12)); } }
package com.ts.dao; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.rest.dto.Faculty; import com.rest.dto.Profile; import com.rest.dto.Review; import com.rest.dto.Submit; import com.rest.dto.Tasks; import com.ts.db.HibernateTemplate; public class ProfileDAO { private SessionFactory factory = null; private static SessionFactory sessionFactory; static { sessionFactory = new Configuration().configure().buildSessionFactory(); } public int register(Profile profile) { return HibernateTemplate.addObject(profile); } public int update(Profile profile) { int result = HibernateTemplate.updateObject(profile); return result; } public Profile getAllProfiles(int facultyId) { String query= "from Profile where facultyId=:facultyId"; Query query1 = sessionFactory.openSession().createQuery(query); query1.setParameter("facultyId",facultyId); System.out.println(facultyId); Object queryResult = query1.uniqueResult(); Profile obj = (Profile)queryResult; return obj; } }
package com.octo.api; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.octo.domain.enums.Level; import com.octo.dto.video.VideoDTO; import com.octo.holders.ApiPaths; import com.octo.services.VideoService; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(MockitoJUnitRunner.class) public class VideoControllerTest { @InjectMocks VideoController videoController; @Mock VideoService videoService; MockMvc mockMvc; @Before public void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(videoController).build(); } @Test public void getQuestionGroup_noTags_noLevel() throws Exception { List<VideoDTO> list = new ArrayList<>(); VideoDTO videoDTO = new VideoDTO(); videoDTO.setId("12345678"); videoDTO.setLevel(Level.EASY); list.add(videoDTO); when(videoService.retrieveVideosByTagAndLevel(null, null)).thenReturn(list); mockMvc.perform(get(ApiPaths.V1 + ApiPaths.VIDEOS)) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(1)); } }
package com.dinhthanhphu.rabbitmq.api; import com.dinhthanhphu.rabbitmq.config.RabbitMQConfig; import com.dinhthanhphu.rabbitmq.dto.MessageDTO; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class RabbitAPI { @Autowired private RabbitTemplate template; @PostMapping("/messages/send") public String bookOrder(@RequestBody MessageDTO messageDTO) { template.convertAndSend(RabbitMQConfig.EXCHANGE, RabbitMQConfig.ROUTING_KEY, messageDTO); return "Success !!"; } }
package package1; import java.util.StringTokenizer; import acm.program.ConsoleProgram; public class In2pJ extends ConsoleProgram{ /** *method containing all the command to be executed * */ public void run() { this.setSize(500,500);// set the window console bigger String str = readLine("Enter string: "); //read a mathematical expression from the user // we create a new tokenizer to tokenize the string entered StringTokenizer st = new StringTokenizer(str,"+-*/()",true); Queue outputQueue =new Queue(); Stack operatorStack = new Stack(); boolean error=false; // variable used to say if there is a problem String currentToken="";// the string to old the current token while(st.hasMoreTokens()){// while we have more token we continue applying the algorithm on the next token currentToken=st.nextToken(); if(isTokenNumber(currentToken)){ outputQueue.enqueue(currentToken);// if token is number then goes directly on the output queue } if(isTokenOperator(currentToken)){// if token is an operator, we put it on the stack, but before we check if //there is operator with higher precedence and if yes we enqueue them in the output queue while(!operatorStack.isStackEmpty() && isHigherPrecedence(operatorStack.peak(),currentToken)){ outputQueue.enqueue(operatorStack.pop()); } operatorStack.push(currentToken); } if(currentToken.equals("(")){ operatorStack.push(currentToken); } if(currentToken.equals(")")){ // and the stack is not empty // as long as the operator on the stack not a left parenthesis while(!operatorStack.isStackEmpty()&&!operatorStack.peak().equals("(")){ outputQueue.enqueue(operatorStack.pop()); } String temp=operatorStack.pop(); if(operatorStack.isStackEmpty()){ // handle the error of a right parenthesis missing println("Error: mismatch parenthesis!"); println("A left parenthesis is missing!"); error=true; break; } } if(!st.hasMoreTokens()){// we enqueue the rest of the operator from the operator stack while(!operatorStack.isStackEmpty()){ outputQueue.enqueue(operatorStack.pop()); if(!operatorStack.isStackEmpty()&&operatorStack.peak().equals("(")){ // handle the error of a left parenthesis missing error=true; println("Error: mismatch parenthesis!"); println("A right parenthesis is missing!"); } } } } if(!error){ println("Postfix: "+outputQueue.StringQueue()); } else if(error){ println("Error somewhere in the program!"); } } /** * method to determine if one operator has higher precedence than an other one * @param op1 operator 1 * @param op2 operator 2 * @return true when operator 1 has higher/equal precedence than operator 2, false when smaller precedence) */ private boolean isHigherPrecedence(String op1, String op2){ //integer values representing the precedence of each operator int op1value=0; int op2value=0; switch(op1){//assign a value corresponding with op1 case "+": op1value=1; break; case "-": op1value=1; break; case "*": op1value=2; break; case "/": op1value=2; break; } switch(op2){//assign value corresponding to op2 case "+": op2value=1; break; case "-": op2value=1; break; case "*": op2value=2; break; case "/": op2value=2; break; } if(op1value>=op2value){//compare the two and return the appropriate result return true; }else{ return false; } } /** * check if a token is a number * * @param token the token to be checked, in the form of a string * @return true if number false otherwise */ private boolean isTokenNumber(String token){ if(token.equals("+")||token.equals("-")||token.equals("*")||token.equals("/")||token.equals("(")||token.equals(")")){ return false; }else{ return true; } } /** * check if token is a operator * @param token the token to be checked, in the form of a string * @return true if operator false otherwise */ private boolean isTokenOperator(String token){ if(token.equals("+")||token.equals("-")||token.equals("*")||token.equals("/")){ return true; }else{ return false; } } }
package com.cloud.feign_consumer.service; import org.springframework.cloud.openfeign.FeignClient; @FeignClient("ribbon-provider") public interface RefactorHelloService extends com.cloud.hello_service_api.service.HelloService{ }
package com.mybatis.interceptor.aspect; import com.mybatis.interceptor.abstracts.BaseAspectAbstract; import com.mybatis.interceptor.annotation.OrderBy; import com.mybatis.interceptor.filterinterceptor.SQLLanguage; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import static com.mybatis.interceptor.enums.SQLEnums.ORDERBY; /** * @author yi * @ClassName DataFilterAspect * @Description TODO * @Date **/ @Component @Aspect @Order(1) public class OrderByAspect extends BaseAspectAbstract { @Pointcut("@annotation(com.mybatis.interceptor.annotation.OrderBy)") public void orderByCut() {} @Before("orderByCut()") public void orderBy(JoinPoint point) { StringBuilder orderByBuilder = new StringBuilder(" ORDER BY "); MethodSignature methodSignature = (MethodSignature)point.getSignature(); //获得对应注解 OrderBy orderBy = methodSignature.getMethod().getAnnotation(OrderBy.class); if (!StringUtils.isEmpty(orderBy)) { String sort = orderBy.isAsc() ? " asc ":" desc" ; orderByBuilder.append(orderBy.orderColumn()).append(sort); putSQL(point,ORDERBY,new SQLLanguage(orderByBuilder.toString())); } } }
package backjun.silver; import java.util.LinkedList; import java.util.Scanner; public class Main_2164_카드2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); LinkedList<Integer> queue = new LinkedList<Integer>(); for (int i = 1; i <=N; i++) { queue.add(i); } int ans = 0; int tmp; while (!queue.isEmpty()) { ans = queue.peek(); queue.poll(); if(!queue.isEmpty()) { tmp = queue.pollFirst(); queue.add(tmp); ans = queue.peek(); } } System.out.println(ans); } }
package teetech.com.g_paypro; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.TextView; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.LineChart; /** * Created by aKI on 12/03/2016. */ public class ViewPagerTransformer implements ViewPager.PageTransformer { public ViewPagerTransformer() { } @Override public void transformPage(View view, float position) { final float MIN_SCALE = 0.75f; int pageWidth = view.getWidth(); TextView txt = (TextView)view.findViewById(R.id.new_text); if (position < -1) { // [-Infinity,-1) // This page is way off-screen to the left. view.setAlpha(0); } else if (position <= 0) { // [-1,0] // Use the default slide transition when moving to the left page view.setAlpha(1); view.setTranslationX(0); view.setScaleX(1); view.setScaleY(1); //txt.setText("from view pager transformer"); //txt.invalidate(); } else if (position <= 1) { // (0,1] // Fade the page out. view.setAlpha(1 - position); // Counteract the default slide transition view.setTranslationX(pageWidth * -position); // Scale the page down (between MIN_SCALE and 1) float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)); view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); } else { // (1,+Infinity] // This page is way off-screen to the right. view.setAlpha(0); } /*float MaxAngle = 30F; if (position < -1 || position > 1) { view.setAlpha(0); // The view is offscreen. } else { view.setAlpha(1); view.setPivotY(view.getHeight() / 2); // The Y Pivot is halfway down the view. // The X pivots need to be on adjacent sides. if (position < 0) { view.setPivotX(view.getWidth()); } else { view.setPivotX(0); } view.setPivotY(MaxAngle * position); // Rotate the view. // view.FindViewById<TextView> (Resource.Id.textView1).Text = string.Format ("Position: {0}\r\nPivotX: {1}\r\nRotationY {2}", position, view.PivotX, view.RotationY); }*/ } }
public class RecursionDemo { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("enter an integer: "); int number = input.nextInt(); System.out.println("Add ten to your number."); //number = number - 10; displayAsWord(number); } //if a number is only a single digit, you can use switch //if you have multiple digit numbers, you will not be able to use switch public static void displayAsWord(int number) { //if you comment out if and else you will get the stackoverflow error if(number < 10) { System.out.print(getWordFromDigit(number)+ " "); } else { displayAsWord(number / 10); System.out.print(getWordFromDigit(number % 10) + " "); } } public static String getWordFromDigit(int digit) { String result = null; switch(digit) { case 0: result = "zero"; break; case 1: result = "one"; break; case 2: result = "two"; break; case 3: result = "three"; break; case 4: result = "four"; break; case 5: result = "five"; break; case 6: result = "six"; break; case 7: result = "seven"; break; case 8: result = "eight"; break; case 9: result = "nine"; break; default: System.out.println("Error occured"); break; } return result; } }
package language.designpatterns; /** * In fact CompositeCalendar (or any other concrete calendar) do not need to extend a common abstract type. * This is done only for convenience for the client: to be able to put them all in the same List<Calendar>, see Client. */ public class CompositeCalendar extends Calendar { GoogleCalendar gCal; OfficeCalendar oCal; public CompositeCalendar(GoogleCalendar gCal, OfficeCalendar oCal) { this.gCal = gCal; this.oCal = oCal; } void accept(Visitor v) { /* // we can either have the traversal logic for each element here: v.visitGoogleCalendar(gCal); v.visitOfficeCalendar(oCal); // and the visit this v.visitCompositeCalendar(this); */ // or leave the traversal logic on the specific Visitor v.visitCompositeCalendar(this); } }
package com.example.demo.mapper; import org.springframework.beans.BeanUtils; import com.example.demo.entity.User; import com.example.demo.model.UserDto; public class UserMapper { public static UserDto convertUsertoUserdto(User userentity,UserDto userdto) { BeanUtils.copyProperties(userentity,userdto); return userdto; } public static User convertUserDtotoUser(UserDto userdto,User userentity) { BeanUtils.copyProperties(userdto,userentity); return userentity; } }
package com.example.demo.exception; import org.springframework.beans.ConversionNotSupportedException; import org.springframework.beans.TypeMismatchException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.validation.BindException; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingPathVariableException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.context.request.async.AsyncRequestTimeoutException; import org.springframework.web.multipart.support.MissingServletRequestPartException; import org.springframework.web.servlet.NoHandlerFoundException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.util.List; import java.util.stream.Collectors; @ControllerAdvice public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { List<String> errors = ex.getBindingResult() .getFieldErrors() .stream() .map(x -> x.getField() + ": " + x.getDefaultMessage()) .collect(Collectors.toList()); return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.BAD_REQUEST, "invalid parameters", errors), HttpStatus.BAD_REQUEST); } @Override protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.METHOD_NOT_ALLOWED, "method not allowed", ex.getMessage()), HttpStatus.BAD_REQUEST); } @Override protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "unsupported media type", ex.getMessage()), HttpStatus.UNSUPPORTED_MEDIA_TYPE); } @Override protected ResponseEntity<Object> handleHttpMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.NOT_ACCEPTABLE, "Not Acceptable", ex.getMessage()), HttpStatus.NOT_ACCEPTABLE); } @Override protected ResponseEntity<Object> handleMissingPathVariable(MissingPathVariableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "missing path variable", ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } @Override protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.BAD_REQUEST, "missing servlet request", ex.getMessage()), HttpStatus.BAD_REQUEST); } @Override protected ResponseEntity<Object> handleServletRequestBindingException(ServletRequestBindingException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.BAD_REQUEST, "servlet request binding", ex.getMessage()), HttpStatus.BAD_REQUEST); } @Override protected ResponseEntity<Object> handleConversionNotSupported(ConversionNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "conversion not supported", ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } @Override protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.BAD_REQUEST, "type mismatch", ex.getMessage()), HttpStatus.BAD_REQUEST); } @Override protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.BAD_REQUEST, "http message not readable", ex.getMessage()), HttpStatus.BAD_REQUEST); } @Override protected ResponseEntity<Object> handleHttpMessageNotWritable(HttpMessageNotWritableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "http message not writable", ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } @Override protected ResponseEntity<Object> handleMissingServletRequestPart(MissingServletRequestPartException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.BAD_REQUEST, "missing servlet request part", ex.getMessage()), HttpStatus.BAD_REQUEST); } @Override protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.METHOD_NOT_ALLOWED, "method not allowed", ex.getMessage()), HttpStatus.BAD_REQUEST); } @Override protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.NOT_FOUND, "no handler found exception", ex.getMessage()), HttpStatus.BAD_REQUEST); } @Override protected ResponseEntity<Object> handleAsyncRequestTimeoutException(AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.SERVICE_UNAVAILABLE, "async request timeout exception", ex.getMessage()), HttpStatus.BAD_REQUEST); } @Override protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(new ApiErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "internal server error", ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } }