blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
5b9f62ae539cab6d8e89dcb17fcb789b56c146a8
7e3838f086b7074cb415fa93bfce45bd9cd24f81
/app/src/main/java/com/chn/halo/view/smartcamera/ui/CameraActivity.java
47f69caf1050a5ab2536fbbabd6a58f3b55d548f
[]
no_license
Halo-CHN/HelloGradle
ee323716663e1a3d4b05d74bb362af7fb8790c0f
afcaca161a0b62fdb3d9d7fc767b3dcb1a33a406
refs/heads/master
2021-01-17T07:54:30.740622
2017-08-07T06:50:27
2017-08-07T06:50:27
41,188,666
1
0
null
null
null
null
UTF-8
Java
false
false
27,405
java
package com.chn.halo.view.smartcamera.ui; import android.annotation.TargetApi; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.graphics.Rect; import android.hardware.Camera; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.animation.ScaleAnimation; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; import com.chn.halo.R; import com.chn.halo.util.StringUtils; import com.chn.halo.util.ToastUtils; import com.chn.halo.view.smartcamera.App; import com.chn.halo.view.smartcamera.base.CameraBaseActivity; import com.chn.halo.view.smartcamera.core.CameraConfig; import com.chn.halo.view.smartcamera.core.CameraHelper; import com.chn.halo.view.smartcamera.util.FileUtils; import com.chn.halo.view.smartcamera.util.ImageUtils; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Description:自定义相机界面 * Version: 1.0 * Author: Halo-CHN * Email: [email protected] * Date: 15/11/12 */ public class CameraActivity extends CameraBaseActivity { private CameraHelper mCameraHelper; private Camera.Parameters parameters = null; private Camera cameraInst = null; private Bundle bundle = null; // private int photoWidth = DistanceUtil.getCameraPhotoWidth(); private int photoNumber = 4; private int photoMargin = App.getApp().dp2px(1); private float pointX, pointY; static final int FOCUS = 1; // 聚焦 static final int ZOOM = 2; // 缩放 private int mode; //0是聚焦 1是放大 private double dist; private int PHOTO_SIZE = 2000; private int mCurrentCameraId = 0; //1是前置 0是后置 private Handler handler = new Handler(); @Bind(R.id.photo_area) LinearLayout photoArea; @Bind(R.id.panel_take_photo) View takePhotoPanel; @Bind(R.id.takepicture) Button takePicture; @Bind(R.id.flashBtn) ImageView flashBtn; @Bind(R.id.change) ImageView changeBtn; @Bind(R.id.back) ImageView backBtn; @Bind(R.id.focus_index) View focusIndex; @Bind(R.id.surfaceView) SurfaceView surfaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); mCameraHelper = new CameraHelper(this); ButterKnife.bind(this); initView(); initEvent(); } private void initView() { SurfaceHolder surfaceHolder = surfaceView.getHolder(); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); surfaceHolder.setKeepScreenOn(true); surfaceView.setFocusable(true); surfaceView.setBackgroundColor(TRIM_MEMORY_BACKGROUND); surfaceView.getHolder().addCallback(new SurfaceCallback());//为SurfaceView的句柄添加一个回调函数 } private void initEvent() { //拍照 takePicture.setOnClickListener(v -> { try { cameraInst.takePicture(null, null, new MyPictureCallback()); } catch (Throwable t) { t.printStackTrace(); toast("拍照失败,请重试!", Toast.LENGTH_LONG); try { cameraInst.startPreview(); } catch (Throwable e) { } } }); //闪光灯 flashBtn.setOnClickListener(v -> turnLight(cameraInst)); //前后置摄像头切换 boolean canSwitch = false; try { canSwitch = mCameraHelper.hasFrontCamera() && mCameraHelper.hasBackCamera(); } catch (Exception e) { //获取相机信息失败 } if (!canSwitch) { changeBtn.setVisibility(View.GONE); } else { changeBtn.setOnClickListener(v -> switchCamera()); } //返回按钮 backBtn.setOnClickListener(v -> finish()); surfaceView.setOnTouchListener((v, event) -> { switch (event.getAction() & MotionEvent.ACTION_MASK) { // 主点按下 case MotionEvent.ACTION_DOWN: pointX = event.getX(); pointY = event.getY(); mode = FOCUS; break; // 副点按下 case MotionEvent.ACTION_POINTER_DOWN: dist = spacing(event); // 如果连续两点距离大于10,则判定为多点模式 if (spacing(event) > 10f) { mode = ZOOM; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mode = FOCUS; break; case MotionEvent.ACTION_MOVE: if (mode == FOCUS) { //pointFocus((int) event.getRawX(), (int) event.getRawY()); } else if (mode == ZOOM) { double newDist = spacing(event); if (newDist > 10f) { double tScale = (newDist - dist) / dist; if (tScale < 0) { tScale = tScale * 10; } addZoomIn((int) tScale); } } break; } return false; }); surfaceView.setOnClickListener(v -> { try { pointFocus((int) pointX, (int) pointY); } catch (Exception e) { e.printStackTrace(); } RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(focusIndex.getLayoutParams()); layout.setMargins((int) pointX - 60, (int) pointY - 60, 0, 0); focusIndex.setLayoutParams(layout); focusIndex.setVisibility(View.VISIBLE); ScaleAnimation sa = new ScaleAnimation(3f, 1f, 3f, 1f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f); sa.setDuration(800); focusIndex.startAnimation(sa); handler.postDelayed(() -> focusIndex.setVisibility(View.INVISIBLE), 800); }); takePhotoPanel.setOnClickListener(v -> { //doNothing 防止聚焦框出现在拍照区域 }); } /** * 两点的距离 */ private double spacing(MotionEvent event) { if (event == null) { return 0; } double x = event.getX(0) - event.getX(1); double y = event.getY(0) - event.getY(1); return Math.sqrt(x * x + y * y); } //放大缩小 int curZoomValue = 0; private void addZoomIn(int delta) { try { Camera.Parameters params = cameraInst.getParameters(); Log.d("Camera", "Is support Zoom " + params.isZoomSupported()); if (!params.isZoomSupported()) { return; } curZoomValue += delta; if (curZoomValue < 0) { curZoomValue = 0; } else if (curZoomValue > params.getMaxZoom()) { curZoomValue = params.getMaxZoom(); } if (!params.isSmoothZoomSupported()) { params.setZoom(curZoomValue); cameraInst.setParameters(params); return; } else { cameraInst.startSmoothZoom(curZoomValue); } } catch (Exception e) { e.printStackTrace(); } } //定点对焦的代码 private void pointFocus(int x, int y) { cameraInst.cancelAutoFocus(); parameters = cameraInst.getParameters(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { showPoint(x, y); } cameraInst.setParameters(parameters); autoFocus(); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void showPoint(int x, int y) { if (parameters.getMaxNumMeteringAreas() > 0) { List<Camera.Area> areas = new ArrayList<Camera.Area>(); //xy变换了 int rectY = -x * 2000 / App.getApp().getScreenWidth() + 1000; int rectX = y * 2000 / App.getApp().getScreenHeight() - 1000; int left = rectX < -900 ? -1000 : rectX - 100; int top = rectY < -900 ? -1000 : rectY - 100; int right = rectX > 900 ? 1000 : rectX + 100; int bottom = rectY > 900 ? 1000 : rectY + 100; Rect area1 = new Rect(left, top, right, bottom); areas.add(new Camera.Area(area1, 800)); parameters.setMeteringAreas(areas); } parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } private final class MyPictureCallback implements Camera.PictureCallback { @Override public void onPictureTaken(byte[] data, Camera camera) { bundle = new Bundle(); bundle.putByteArray("bytes", data); //将图片字节数据保存在bundle当中,实现数据交换 new SavePicTask(data).execute(); camera.startPreview(); // 拍完照后,重新开始预览 } } private class SavePicTask extends AsyncTask<Void, Void, String> { private byte[] data; protected void onPreExecute() { showProgressBar("处理中"); } SavePicTask(byte[] data) { this.data = data; } @Override protected String doInBackground(Void... params) { try { return saveToSDCard(data); } catch (IOException e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (StringUtils.isNotEmpty(result)) { dismissProgressBar(); toast(result, Toast.LENGTH_SHORT); // CameraManager.getInst().processPhotoItem(CameraActivity.this, // new PhotoItem(result, System.currentTimeMillis())); } else { toast("拍照失败,请稍后重试!", Toast.LENGTH_LONG); } } } /** * 将拍下来的照片存放在SD卡中 * * @param data * @throws IOException */ public String saveToSDCard(byte[] data) throws IOException { Bitmap croppedImage = ImageUtils.byteToBitmap(data); String imagePath = ImageUtils.saveToFile(CameraConfig.APP_TEMP, true, croppedImage); croppedImage.recycle(); String tempPath = imagePath; if (null != imagePath && !imagePath.equals("")) try { Bitmap tempImage = ImageUtils.getSmallBitmap(imagePath); imagePath = ImageUtils.saveToFile(CameraConfig.APP_IMAGE, true, tempImage); FileUtils.getInst().deleteTempFile(tempPath); } catch (Exception ex) { ex.printStackTrace(); } return imagePath; } /** * show Toast * * @param s * @param lengthLong */ private void toast(String s, int lengthLong) { ToastUtils.show(this, s, lengthLong); } /*SurfaceCallback*/ private final class SurfaceCallback implements SurfaceHolder.Callback { public void surfaceDestroyed(SurfaceHolder holder) { try { if (cameraInst != null) { cameraInst.stopPreview(); cameraInst.release(); cameraInst = null; } } catch (Exception e) { //相机已经关了 } } @Override public void surfaceCreated(SurfaceHolder holder) { if (null == cameraInst) { try { cameraInst = Camera.open(); cameraInst.setPreviewDisplay(holder); initCamera(); cameraInst.startPreview(); } catch (Throwable e) { e.printStackTrace(); } } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { autoFocus(); } } //实现自动对焦 private void autoFocus() { new Thread() { @Override public void run() { try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if (cameraInst == null) { return; } cameraInst.autoFocus(new Camera.AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { if (success) { initCamera();//实现相机的参数初始化 } } }); } }; } private Camera.Size adapterSize = null; private Camera.Size previewSize = null; private void initCamera() { parameters = cameraInst.getParameters(); parameters.setPictureFormat(PixelFormat.JPEG); //if (adapterSize == null) { setUpPicSize(parameters); setUpPreviewSize(parameters); //} if (adapterSize != null) { parameters.setPictureSize(adapterSize.width, adapterSize.height); } if (previewSize != null) { parameters.setPreviewSize(previewSize.width, previewSize.height); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1连续对焦 } else { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); } setDispaly(parameters, cameraInst); try { cameraInst.setParameters(parameters); } catch (Exception e) { e.printStackTrace(); } cameraInst.startPreview(); cameraInst.cancelAutoFocus();// 2如果要实现连续的自动对焦,这一句必须加上 } private void setUpPicSize(Camera.Parameters parameters) { if (adapterSize != null) { return; } else { adapterSize = findBestPictureResolution(); return; } } private void setUpPreviewSize(Camera.Parameters parameters) { if (previewSize != null) { return; } else { previewSize = findBestPreviewResolution(); } } /** * 最小预览界面的分辨率 */ private static final int MIN_PREVIEW_PIXELS = 480 * 320; /** * 最大宽高比差 */ private static final double MAX_ASPECT_DISTORTION = 0.15; private static final String TAG = "Camera"; /** * 找出最适合的预览界面分辨率 * * @return */ private Camera.Size findBestPreviewResolution() { Camera.Parameters cameraParameters = cameraInst.getParameters(); Camera.Size defaultPreviewResolution = cameraParameters.getPreviewSize(); List<Camera.Size> rawSupportedSizes = cameraParameters.getSupportedPreviewSizes(); if (rawSupportedSizes == null) { return defaultPreviewResolution; } // 按照分辨率从大到小排序 List<Camera.Size> supportedPreviewResolutions = new ArrayList<Camera.Size>(rawSupportedSizes); Collections.sort(supportedPreviewResolutions, new Comparator<Camera.Size>() { @Override public int compare(Camera.Size a, Camera.Size b) { int aPixels = a.height * a.width; int bPixels = b.height * b.width; if (bPixels < aPixels) { return -1; } if (bPixels > aPixels) { return 1; } return 0; } }); StringBuilder previewResolutionSb = new StringBuilder(); for (Camera.Size supportedPreviewResolution : supportedPreviewResolutions) { previewResolutionSb.append(supportedPreviewResolution.width).append('x').append(supportedPreviewResolution.height) .append(' '); } Log.v(TAG, "Supported preview resolutions: " + previewResolutionSb); // 移除不符合条件的分辨率 double screenAspectRatio = (double) App.getApp().getScreenWidth() / (double) App.getApp().getScreenHeight(); Iterator<Camera.Size> it = supportedPreviewResolutions.iterator(); while (it.hasNext()) { Camera.Size supportedPreviewResolution = it.next(); int width = supportedPreviewResolution.width; int height = supportedPreviewResolution.height; // 移除低于下限的分辨率,尽可能取高分辨率 if (width * height < MIN_PREVIEW_PIXELS) { it.remove(); continue; } // 在camera分辨率与屏幕分辨率宽高比不相等的情况下,找出差距最小的一组分辨率 // 由于camera的分辨率是width>height,我们设置的portrait模式中,width<height // 因此这里要先交换然preview宽高比后在比较 boolean isCandidatePortrait = width > height; int maybeFlippedWidth = isCandidatePortrait ? height : width; int maybeFlippedHeight = isCandidatePortrait ? width : height; double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight; double distortion = Math.abs(aspectRatio - screenAspectRatio); if (distortion > MAX_ASPECT_DISTORTION) { it.remove(); continue; } // 找到与屏幕分辨率完全匹配的预览界面分辨率直接返回 if (maybeFlippedWidth == App.getApp().getScreenWidth() && maybeFlippedHeight == App.getApp().getScreenHeight()) { return supportedPreviewResolution; } } // 如果没有找到合适的,并且还有候选的像素,则设置其中最大比例的,对于配置比较低的机器不太合适 if (!supportedPreviewResolutions.isEmpty()) { Camera.Size largestPreview = supportedPreviewResolutions.get(0); return largestPreview; } // 没有找到合适的,就返回默认的 return defaultPreviewResolution; } private Camera.Size findBestPictureResolution() { Camera.Parameters cameraParameters = cameraInst.getParameters(); List<Camera.Size> supportedPicResolutions = cameraParameters.getSupportedPictureSizes(); // 至少会返回一个值 StringBuilder picResolutionSb = new StringBuilder(); for (Camera.Size supportedPicResolution : supportedPicResolutions) { picResolutionSb.append(supportedPicResolution.width).append('x') .append(supportedPicResolution.height).append(" "); } Log.d(TAG, "Supported picture resolutions: " + picResolutionSb); Camera.Size defaultPictureResolution = cameraParameters.getPictureSize(); Log.d(TAG, "default picture resolution " + defaultPictureResolution.width + "x" + defaultPictureResolution.height); // 排序 List<Camera.Size> sortedSupportedPicResolutions = new ArrayList<Camera.Size>( supportedPicResolutions); Collections.sort(sortedSupportedPicResolutions, new Comparator<Camera.Size>() { @Override public int compare(Camera.Size a, Camera.Size b) { int aPixels = a.height * a.width; int bPixels = b.height * b.width; if (bPixels < aPixels) { return -1; } if (bPixels > aPixels) { return 1; } return 0; } }); // 移除不符合条件的分辨率 double screenAspectRatio = (double) App.getApp().getScreenWidth() / (double) App.getApp().getScreenHeight(); Iterator<Camera.Size> it = sortedSupportedPicResolutions.iterator(); while (it.hasNext()) { Camera.Size supportedPreviewResolution = it.next(); int width = supportedPreviewResolution.width; int height = supportedPreviewResolution.height; // 在camera分辨率与屏幕分辨率宽高比不相等的情况下,找出差距最小的一组分辨率 // 由于camera的分辨率是width>height,我们设置的portrait模式中,width<height // 因此这里要先交换然后在比较宽高比 boolean isCandidatePortrait = width > height; int maybeFlippedWidth = isCandidatePortrait ? height : width; int maybeFlippedHeight = isCandidatePortrait ? width : height; double aspectRatio = (double) maybeFlippedWidth / (double) maybeFlippedHeight; double distortion = Math.abs(aspectRatio - screenAspectRatio); if (isOrientationPortrait()) { if (distortion > MAX_ASPECT_DISTORTION) { it.remove(); continue; } } else if (isOrientationLandscape()) { if (distortion < 1 - MAX_ASPECT_DISTORTION) { it.remove(); continue; } } } // 如果没有找到合适的,并且还有候选的像素,对于照片,则取其中最大比例的,而不是选择与屏幕分辨率相同的 if (!sortedSupportedPicResolutions.isEmpty()) { return sortedSupportedPicResolutions.get(0); } // 没有找到合适的,就返回默认的 return defaultPictureResolution; } //控制图像的正确显示方向 private void setDispaly(Camera.Parameters parameters, Camera camera) { int doInt = 0; if (isOrientationLandscape()) { doInt = 0; } else if (isOrientationPortrait()) { doInt = 90; } if (Build.VERSION.SDK_INT >= 8) { setDisplayOrientation(camera, doInt); } else { parameters.setRotation(doInt); } } private boolean isOrientationLandscape() { return this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; } private boolean isOrientationPortrait() { return this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; } //实现的图像的正确显示 private void setDisplayOrientation(Camera camera, int i) { Method downPolymorphic; try { downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[]{int.class}); if (downPolymorphic != null) { downPolymorphic.invoke(camera, new Object[]{i}); } } catch (Exception e) { Log.e("Came_e", "图像出错"); } } /** * 闪光灯开关 开->关->自动 * * @param mCamera */ private void turnLight(Camera mCamera) { if (mCamera == null || mCamera.getParameters() == null || mCamera.getParameters().getSupportedFlashModes() == null) { return; } Camera.Parameters parameters = mCamera.getParameters(); String flashMode = mCamera.getParameters().getFlashMode(); List<String> supportedModes = mCamera.getParameters().getSupportedFlashModes(); if (Camera.Parameters.FLASH_MODE_OFF.equals(flashMode) && supportedModes.contains(Camera.Parameters.FLASH_MODE_ON)) {//关闭状态 parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON); mCamera.setParameters(parameters); flashBtn.setImageResource(R.drawable.camera_flash_on); } else if (Camera.Parameters.FLASH_MODE_ON.equals(flashMode)) {//开启状态 if (supportedModes.contains(Camera.Parameters.FLASH_MODE_AUTO)) { parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); flashBtn.setImageResource(R.drawable.camera_flash_auto); mCamera.setParameters(parameters); } else if (supportedModes.contains(Camera.Parameters.FLASH_MODE_OFF)) { parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); flashBtn.setImageResource(R.drawable.camera_flash_off); mCamera.setParameters(parameters); } } else if (Camera.Parameters.FLASH_MODE_AUTO.equals(flashMode) && supportedModes.contains(Camera.Parameters.FLASH_MODE_OFF)) { parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); mCamera.setParameters(parameters); flashBtn.setImageResource(R.drawable.camera_flash_off); } } //切换前后置摄像头 private void switchCamera() { mCurrentCameraId = (mCurrentCameraId + 1) % mCameraHelper.getNumberOfCameras(); releaseCamera(); Log.d("DDDD", "DDDD----mCurrentCameraId" + mCurrentCameraId); setUpCamera(mCurrentCameraId); } private void releaseCamera() { if (cameraInst != null) { cameraInst.setPreviewCallback(null); cameraInst.release(); cameraInst = null; } adapterSize = null; previewSize = null; } /** * @param mCurrentCameraId2 */ private void setUpCamera(int mCurrentCameraId2) { cameraInst = getCameraInstance(mCurrentCameraId2); if (cameraInst != null) { try { cameraInst.setPreviewDisplay(surfaceView.getHolder()); initCamera(); cameraInst.startPreview(); } catch (IOException e) { e.printStackTrace(); } } else { toast("切换失败,请重试!", Toast.LENGTH_LONG); } } private Camera getCameraInstance(final int id) { Camera c = null; try { c = mCameraHelper.openCamera(id); } catch (Exception e) { e.printStackTrace(); } return c; } }
20343707cce80e2ba100cbfc1e69326d39a19b20
8611a3e8840683553d3799d0322a46ad24595cda
/src/main/java/com/showtime/jkgl/model/entity/Sport.java
a35953c4afba3051165bf79e3ae603637e0e9600
[]
no_license
showTimeQin/jkgl
3df405514e1db779476e674ba7458c3fe55967ae
dd51bffafec87864c3cd196b1ff428099f4e8cd1
refs/heads/master
2021-04-12T10:21:38.962659
2018-04-23T14:14:41
2018-04-23T14:14:41
126,172,993
1
0
null
null
null
null
UTF-8
Java
false
false
3,663
java
package com.showtime.jkgl.model.entity; import javax.persistence.*; public class Sport { /** * 编码 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 项目名 */ @Column(name = "sport_name") private String sportName; /** * 运动类别 */ @Column(name = "sports_category") private Integer sportsCategory; /** * 运动风险 */ @Column(name = "sport_risk") private Integer sportRisk; /** * 运动时间 */ @Column(name = "sport_time") private Integer sportTime; /** * 运动频率 */ @Column(name = "sport_frequency") private String sportFrequency; /** * 拉伸部位 */ @Column(name = "tensile_site") private String tensileSite; /** * 动作方法 */ @Column(name = "action_method") private String actionMethod; /** * 获取编码 * * @return id - 编码 */ public Integer getId() { return id; } /** * 设置编码 * * @param id 编码 */ public void setId(Integer id) { this.id = id; } /** * 获取项目名 * * @return sport_name - 项目名 */ public String getSportName() { return sportName; } /** * 设置项目名 * * @param sportName 项目名 */ public void setSportName(String sportName) { this.sportName = sportName; } /** * 获取运动类别 * * @return sports_category - 运动类别 */ public Integer getSportsCategory() { return sportsCategory; } /** * 设置运动类别 * * @param sportsCategory 运动类别 */ public void setSportsCategory(Integer sportsCategory) { this.sportsCategory = sportsCategory; } /** * 获取运动风险 * * @return sport_risk - 运动风险 */ public Integer getSportRisk() { return sportRisk; } /** * 设置运动风险 * * @param sportRisk 运动风险 */ public void setSportRisk(Integer sportRisk) { this.sportRisk = sportRisk; } /** * 获取运动时间 * * @return sport_time - 运动时间 */ public Integer getSportTime() { return sportTime; } /** * 设置运动时间 * * @param sportTime 运动时间 */ public void setSportTime(Integer sportTime) { this.sportTime = sportTime; } /** * 获取运动频率 * * @return sport_frequency - 运动频率 */ public String getSportFrequency() { return sportFrequency; } /** * 设置运动频率 * * @param sportFrequency 运动频率 */ public void setSportFrequency(String sportFrequency) { this.sportFrequency = sportFrequency; } /** * 获取拉伸部位 * * @return tensile_site - 拉伸部位 */ public String getTensileSite() { return tensileSite; } /** * 设置拉伸部位 * * @param tensileSite 拉伸部位 */ public void setTensileSite(String tensileSite) { this.tensileSite = tensileSite; } /** * 获取动作方法 * * @return action_method - 动作方法 */ public String getActionMethod() { return actionMethod; } /** * 设置动作方法 * * @param actionMethod 动作方法 */ public void setActionMethod(String actionMethod) { this.actionMethod = actionMethod; } }
bc3723a7919a7c5d7cb968f82bf073ba80189d57
d937646fcd3ba303cab55d729cf7f2a8d8a93c83
/app/src/main/java/zhuyekeji/zhengzhou/jxlifecircle/frament/home/TouPaioAllFrament.java
2a8ade3503eda0912d4e34d1c55c9149cf894464
[]
no_license
jingzhixb/jxlifecircle
7e2e61ba3c0207ba547ff2bb228589a402df8121
5247754504d92383fb93f5bda60e03766d84ecce
refs/heads/master
2020-03-19T20:34:15.281494
2018-07-23T12:03:54
2018-07-23T12:03:54
136,907,546
0
0
null
null
null
null
UTF-8
Java
false
false
706
java
package zhuyekeji.zhengzhou.jxlifecircle.frament.home; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import zhuyekeji.zhengzhou.jxlifecircle.R; import zhuyekeji.zhengzhou.jxlifecircle.base.BaseFragment; /** * Created by Administrator on 2018/6/8. */ public class TouPaioAllFrament extends BaseFragment { private View view; @Override protected View initView(LayoutInflater inflater, ViewGroup container) { view=LayoutInflater.from(getActivity()).inflate(R.layout.utils_item,null); return view; } @Override protected void initListener() { } @Override protected void initData() { } }
[ "1390056147qq.com" ]
1390056147qq.com
be1aa04fe2db99e93d37938f4f258215a6a1d1ea
ba3b25d6cf9be46007833ce662d0584dc1246279
/droidsafe_modified/modeling/api-manual/android/content/Context.java
71279ab3f363e6714cba5f6782cb33884519076c
[]
no_license
suncongxd/muDep
46552d4156191b9dec669e246188080b47183a01
b891c09f2c96ff37dcfc00468632bda569fc8b6d
refs/heads/main
2023-03-20T20:04:41.737805
2021-03-01T19:52:08
2021-03-01T19:52:08
326,209,904
8
0
null
null
null
null
UTF-8
Java
false
false
10,016
java
/* * Copyright (C) 2015, Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Please email [email protected] if you need additional * information or have any questions. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /***** THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL BY THE DROIDSAFE PROJECT. *****/ package android.content; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.Set; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.AttributeSet; import droidsafe.annotations.DSC; import droidsafe.annotations.DSModeled; public abstract class Context { public static final String WINDOW_SERVICE = "window"; public static final String SEARCH_SERVICE = "search"; public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater"; public static final String SENSOR_SERVICE = "sensor"; public static final String TELEPHONY_SERVICE = "phone"; /* Concrete Methods */ @DSModeled(DSC.SAFE) public boolean isRestricted() { return false; } @DSModeled(value = DSC.SAFE) public int getThemeResId() { return 0; } @DSModeled(DSC.SAFE) public final String getString(int resId) { String str = new String(); str.addTaint(resId); return str; } @DSModeled(DSC.SAFE) public final CharSequence getText(int resId) { String str = new String(); str.addTaint(resId); return str; } @DSModeled(value = DSC.SAFE) public Context() { //Do Nothing } @DSModeled(DSC.SAFE) public final TypedArray obtainStyledAttributes( AttributeSet set, int[] attrs) { return getTheme().obtainStyledAttributes(set, attrs, 0, 0); } /* Abstract Methods */ public abstract Object getSystemService(String name); public abstract boolean bindService(Intent service, ServiceConnection conn, int flags); public abstract AssetManager getAssets(); public abstract Resources getResources(); public abstract PackageManager getPackageManager(); public abstract ContentResolver getContentResolver(); public abstract Looper getMainLooper(); public abstract Context getApplicationContext(); public abstract void setTheme(int resid); public abstract Resources.Theme getTheme(); public abstract ClassLoader getClassLoader(); public abstract String getPackageName(); public abstract ApplicationInfo getApplicationInfo(); public abstract String getPackageResourcePath(); public abstract File getSharedPrefsFile(String name); public abstract String getPackageCodePath(); public abstract SharedPreferences getSharedPreferences(String name, int mode); public abstract FileInputStream openFileInput(String name) throws FileNotFoundException; public abstract FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException; public abstract boolean deleteFile(String name); public abstract File getFileStreamPath(String name); public abstract String[] fileList(); public abstract File getFilesDir(); public abstract File getExternalFilesDir(String type); public abstract File getObbDir(); public abstract File getCacheDir(); public abstract File getExternalCacheDir(); public abstract File getDir(String name, int mode); public abstract SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory); public abstract SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler); public abstract File getDatabasePath(String name); public abstract String[] databaseList(); public abstract boolean deleteDatabase(String name); public abstract void startActivity(Intent intent); public abstract void startActivities(Intent[] intents); public abstract void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException; public abstract void sendBroadcast(Intent intent); public abstract void sendBroadcast(Intent intent, String receiverPermission); public abstract void sendOrderedBroadcast(Intent intent, String receiverPermission); public abstract void sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras); public abstract void sendStickyBroadcast(Intent intent); public abstract void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras); public abstract void removeStickyBroadcast(Intent intent); public abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter); public abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler); public abstract void unregisterReceiver(BroadcastReceiver receiver); public abstract ComponentName startService(Intent service); public abstract boolean stopService(Intent service); public abstract void unbindService(ServiceConnection conn); public abstract boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments); public abstract int checkPermission(String permission, int pid, int uid); public abstract int checkCallingPermission(String permission); public abstract int checkCallingOrSelfPermission(String permission); public abstract void enforcePermission( String permission, int pid, int uid, String message); public abstract void enforceCallingPermission( String permission, String message); public abstract void enforceCallingOrSelfPermission( String permission, String message); public abstract void grantUriPermission(String toPackage, Uri uri, int modeFlags); public abstract void revokeUriPermission(Uri uri, int modeFlags); public abstract int checkUriPermission(Uri uri, int pid, int uid, int modeFlags); public abstract int checkCallingUriPermission(Uri uri, int modeFlags); public abstract int checkCallingOrSelfUriPermission(Uri uri, int modeFlags); public abstract int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags); public abstract void enforceUriPermission( Uri uri, int pid, int uid, int modeFlags, String message); public abstract void enforceUriPermission( Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message); public abstract void enforceCallingUriPermission( Uri uri, int modeFlags, String message); public abstract void enforceCallingOrSelfUriPermission( Uri uri, int modeFlags, String message); public abstract Context createPackageContext(String packageName, int flags) throws PackageManager.NameNotFoundException; /* Deprecated methods */ @Deprecated public abstract Drawable getWallpaper(); @Deprecated public abstract Drawable peekWallpaper(); @Deprecated public abstract int getWallpaperDesiredMinimumWidth(); @Deprecated public abstract int getWallpaperDesiredMinimumHeight(); @Deprecated public abstract void setWallpaper(Bitmap bitmap) throws IOException; @Deprecated public abstract void setWallpaper(InputStream data) throws IOException; @Deprecated public abstract void clearWallpaper() throws IOException; // Hook to match with value analsysis public Set<IntentFilter> __ds__intentFilters = new HashSet<IntentFilter>(); // We pull out IntentFilters out of xml and register them with the appropriate subclasses of Context here public void __ds__registerIntentFilter(IntentFilter intentFilter) { this.__ds__intentFilters.add(intentFilter); } }
51997ed0d7cbd793372e215afc106fcc8b77a40f
01510da8846a7c1982d4170247796fd9886e6d3c
/SeoulPharm/app/src/main/java/com/daejong/seoulpharm/db/DBHelper.java
45aab894497dc260e308a63487820633c30488a9
[ "MIT", "Apache-2.0", "BSD-3-Clause-No-Nuclear-Warranty" ]
permissive
MobileSeoul/2016seoul-68
22f3ee78b543e12815cb3ce2e1a5874ce8721707
757e01602b2c84e3db6f29f45d1141eb353070f6
refs/heads/master
2021-07-05T04:51:08.797573
2017-09-27T07:20:41
2017-09-27T07:20:41
104,982,974
1
1
null
null
null
null
UTF-8
Java
false
false
17,388
java
package com.daejong.seoulpharm.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.daejong.seoulpharm.model.MedicineInfo; import com.daejong.seoulpharm.model.PharmItem; import java.util.ArrayList; import java.util.List; /** * Created by Hyunwoo on 2016. 10. 1.. */ public class DBHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "pharmDB"; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * TODO : DB COLUMN 추가 적용! (Initialize) */ @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String sql = "CREATE TABLE " + PharmDB.PharmTable.TABLE_NAME + "(" + PharmDB.PharmTable.COLUMN_MAIN_KEY + " TEXT PRIMARY KEY NOT NULL, " + PharmDB.PharmTable.COLUMN_NAME_KOR + " TEXT NOT NULL, " + PharmDB.PharmTable.COLUMN_NAME_ENG + " TEXT NOT NULL, " + PharmDB.PharmTable.COLUMN_NAME_CHI + " TEXT NOT NULL, " + PharmDB.PharmTable.COLUMN_ADDRESS_KOR + " TEXT, " + PharmDB.PharmTable.COLUMN_ADDRESS_ENG + " TEXT, " + PharmDB.PharmTable.COLUMN_H_KOR_CITY + " TEXT, " + PharmDB.PharmTable.COLUMN_H_KOR_GU + " TEXT, " + PharmDB.PharmTable.COLUMN_H_KOR_DONG + " TEXT, " + PharmDB.PharmTable.COLUMN_TEL + " TEXT, " + PharmDB.PharmTable.COLUMN_AVAIL_LAN_KOR + " TEXT, " + PharmDB.PharmTable.COLUMN_AVAIL_LAN_ENG + " TEXT, " + PharmDB.PharmTable.COLUMN_AVAIL_LAN_CHI + " TEXT, " + PharmDB.PharmTable.COLUMN_LATITUDE + " TEXT," + PharmDB.PharmTable.COLUMN_LONGTITUDE + " TEXT );"; sqLiteDatabase.execSQL(sql); sql = "CREATE TABLE " + PharmDB.ScrappedPharmTable.TABLE_NAME + "(" + PharmDB.ScrappedPharmTable.COLUMN_PHARM_KEY + " TEXT PRIMARY KEY NOT NULL );"; sqLiteDatabase.execSQL(sql); sql = "CREATE TABLE " + PharmDB.ScrappedComponentTable.TABLE_NAME + "(" + PharmDB.ScrappedComponentTable.COLUMN_COMPONENT_KEY + " TEXT PRIMARY KEY NOT NULL," + PharmDB.ScrappedComponentTable.COLUMN_COMPANY_NAME + " TEXT, " + PharmDB.ScrappedComponentTable.COLUMN_IMAGE_URL + " TEXT, " + PharmDB.ScrappedComponentTable.COLUMN_MEDICINE_NAME + " TEXT );"; sqLiteDatabase.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { // /? } // INSERT DATA public void addPharmItem(PharmItem item) { // 1. get reference to writable DB SQLiteDatabase db = getWritableDatabase(); // 2. create ContentValues to add key "column"/value ContentValues values = new ContentValues(); values.clear(); values.put(PharmDB.PharmTable.COLUMN_MAIN_KEY, item.getMainKey()); values.put(PharmDB.PharmTable.COLUMN_NAME_KOR, item.getNameKor()); values.put(PharmDB.PharmTable.COLUMN_NAME_ENG, item.getNameEng()); values.put(PharmDB.PharmTable.COLUMN_NAME_CHI, item.getNameChi()); values.put(PharmDB.PharmTable.COLUMN_ADDRESS_KOR, item.getAddressKor()); values.put(PharmDB.PharmTable.COLUMN_ADDRESS_ENG, item.getAddressEng()); values.put(PharmDB.PharmTable.COLUMN_H_KOR_CITY, item.gethKorCity()); values.put(PharmDB.PharmTable.COLUMN_H_KOR_GU, item.gethKorGu()); values.put(PharmDB.PharmTable.COLUMN_H_KOR_DONG, item.gethKorDong()); values.put(PharmDB.PharmTable.COLUMN_TEL, item.getTel()); values.put(PharmDB.PharmTable.COLUMN_AVAIL_LAN_KOR, item.getAvailLanKor()); values.put(PharmDB.PharmTable.COLUMN_AVAIL_LAN_ENG, item.getAvailLanEng()); values.put(PharmDB.PharmTable.COLUMN_AVAIL_LAN_CHI, item.getAvailLanChi()); values.put(PharmDB.PharmTable.COLUMN_LATITUDE, item.getLatitude()); values.put(PharmDB.PharmTable.COLUMN_LONGTITUDE, item.getLongtitude()); // 3. insert db.insertWithOnConflict(PharmDB.PharmTable.TABLE_NAME, // table null, //nullColumnHack values, SQLiteDatabase.CONFLICT_REPLACE); // key/value -> keys = column names/ values = column values // 4. close db.close(); } public int getPharmRowCount() { String countQuery = "SELECT * FROM " + PharmDB.PharmTable.TABLE_NAME; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery, null); int cnt = cursor.getCount(); cursor.close(); return cnt; } // GET DATA LIST public List<PharmItem> getPharmList() { List<PharmItem> list = new ArrayList<PharmItem>(); SQLiteDatabase db = this.getReadableDatabase(); // Select All Query String selectQuery = "SELECT * FROM " + PharmDB.PharmTable.TABLE_NAME; Cursor c = db.rawQuery(selectQuery, null); try { // looping through all rows and adding to list if (c.moveToFirst()) { do { PharmItem item = new PharmItem(); //only one column item.setMainKey(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_MAIN_KEY))); item.setNameKor(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_NAME_KOR))); item.setNameEng(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_NAME_ENG))); item.setNameChi(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_NAME_CHI))); item.setAddressKor(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_ADDRESS_KOR))); item.setAddressEng(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_ADDRESS_ENG))); item.sethKorCity(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_H_KOR_CITY))); item.sethKorGu(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_H_KOR_GU))); item.sethKorDong(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_H_KOR_DONG))); item.setTel(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_TEL))); item.setAvailLanKor(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_AVAIL_LAN_KOR))); item.setAvailLanEng(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_AVAIL_LAN_ENG))); item.setAvailLanChi(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_AVAIL_LAN_CHI))); item.setLatitude(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_LATITUDE))); item.setLongtitude(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_LONGTITUDE))); list.add(item); // Log.d(" GET PHARMS ITEM POS ","LAT : "+c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_LATITUDE)) // + " / LNG : "+c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_LONGTITUDE))); } while (c.moveToNext()); } } finally { try { c.close(); } catch (Exception ignore) { } } return list; } public PharmItem getPharmItemByName(String pharmName) { SQLiteDatabase db = getReadableDatabase(); Cursor c = null; PharmItem item = null; try { c = db.rawQuery("SELECT *" + " FROM " + PharmDB.PharmTable.TABLE_NAME + " WHERE " + PharmDB.PharmTable.COLUMN_NAME_KOR + "=? ", new String[]{pharmName + ""}); if (c.getCount() > 0) { c.moveToFirst(); item = new PharmItem(); item.setMainKey(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_MAIN_KEY))); item.setNameKor(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_NAME_KOR))); item.setNameEng(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_NAME_ENG))); item.setNameChi(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_NAME_CHI))); item.setAddressKor(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_ADDRESS_KOR))); item.setAddressEng(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_ADDRESS_ENG))); item.sethKorCity(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_H_KOR_CITY))); item.sethKorGu(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_H_KOR_GU))); item.sethKorDong(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_H_KOR_DONG))); item.setTel(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_TEL))); item.setAvailLanKor(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_AVAIL_LAN_KOR))); item.setAvailLanEng(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_AVAIL_LAN_ENG))); item.setAvailLanChi(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_AVAIL_LAN_CHI))); item.setLatitude(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_LATITUDE))); item.setLongtitude(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_LONGTITUDE))); } return item; } finally { c.close(); } } public PharmItem getPharmItemByKey(String key) { SQLiteDatabase db = getReadableDatabase(); Cursor c = null; PharmItem item = null; try { c = db.rawQuery("SELECT *" + " FROM " + PharmDB.PharmTable.TABLE_NAME + " WHERE " + PharmDB.PharmTable.COLUMN_MAIN_KEY + "=? ", new String[]{key + ""}); if (c.getCount() > 0) { c.moveToFirst(); item = new PharmItem(); item.setMainKey(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_MAIN_KEY))); item.setNameKor(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_NAME_KOR))); item.setNameEng(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_NAME_ENG))); item.setNameChi(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_NAME_CHI))); item.setAddressKor(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_ADDRESS_KOR))); item.setAddressEng(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_ADDRESS_ENG))); item.sethKorCity(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_H_KOR_CITY))); item.sethKorGu(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_H_KOR_GU))); item.sethKorDong(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_H_KOR_DONG))); item.setTel(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_TEL))); item.setAvailLanKor(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_AVAIL_LAN_KOR))); item.setAvailLanEng(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_AVAIL_LAN_ENG))); item.setAvailLanChi(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_AVAIL_LAN_CHI))); item.setLatitude(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_LATITUDE))); item.setLongtitude(c.getString(c.getColumnIndex(PharmDB.PharmTable.COLUMN_LONGTITUDE))); } return item; } finally { c.close(); } } public void addPharmBookmark(String key) { // 1. get reference to writable DB SQLiteDatabase db = getWritableDatabase(); // 2. create ContentValues to add key "column"/value ContentValues values = new ContentValues(); values.clear(); values.put(PharmDB.PharmTable.COLUMN_MAIN_KEY, key); // 3. insert db.insertWithOnConflict(PharmDB.ScrappedPharmTable.TABLE_NAME, // table null, //nullColumnHack values, SQLiteDatabase.CONFLICT_REPLACE); // key/value -> keys = column names/ values = column values // 4. close db.close(); } public void deletePharmScrapped(String deleteKey) { SQLiteDatabase db = getWritableDatabase(); db.delete(PharmDB.ScrappedPharmTable.TABLE_NAME, PharmDB.ScrappedPharmTable.COLUMN_PHARM_KEY + " = ? ", new String[]{deleteKey + ""}); } public boolean searchPharmScrapped(String searchKey) { SQLiteDatabase db = getWritableDatabase(); Cursor c = db.rawQuery("SELECT " + PharmDB.ScrappedPharmTable.COLUMN_PHARM_KEY + " FROM " + PharmDB.ScrappedPharmTable.TABLE_NAME + " WHERE " + PharmDB.ScrappedPharmTable.COLUMN_PHARM_KEY + " = ? ", new String[]{searchKey + ""}); if (c.getCount() <= 0) { c.close(); return false; } c.close(); return true; } public List<PharmItem> getScrappedPharms() { List<PharmItem> list = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); // Select All Query String selectQuery = "SELECT * FROM " + PharmDB.ScrappedPharmTable.TABLE_NAME; Cursor c = db.rawQuery(selectQuery, null); try { // looping through all rows and adding to list if (c.moveToFirst()) { do { String key = c.getString(c.getColumnIndex(PharmDB.ScrappedPharmTable.COLUMN_PHARM_KEY)); PharmItem item = getPharmItemByKey(key); list.add(item); } while (c.moveToNext()); } } finally { try { c.close(); } catch (Exception ignore) { } } return list; } public void addMedicineBookmark(MedicineInfo medicineInfo) { // 1. get reference to writable DB SQLiteDatabase db = getWritableDatabase(); // 2. create ContentValues to add key "column"/value ContentValues values = new ContentValues(); values.clear(); values.put(PharmDB.ScrappedComponentTable.COLUMN_COMPONENT_KEY, medicineInfo.getBarcode()); values.put(PharmDB.ScrappedComponentTable.COLUMN_COMPANY_NAME, medicineInfo.getCompany()); values.put(PharmDB.ScrappedComponentTable.COLUMN_MEDICINE_NAME, medicineInfo.getName()); values.put(PharmDB.ScrappedComponentTable.COLUMN_IMAGE_URL, medicineInfo.getImageSrc()); // 3. insert db.insertWithOnConflict(PharmDB.ScrappedComponentTable.TABLE_NAME, // table null, //nullColumnHack values, SQLiteDatabase.CONFLICT_REPLACE); // key/value -> keys = column names/ values = column values // 4. close db.close(); } public void deleteMedicineScrapped(String deleteKey) { SQLiteDatabase db = getWritableDatabase(); db.delete(PharmDB.ScrappedComponentTable.TABLE_NAME, PharmDB.ScrappedComponentTable.COLUMN_COMPONENT_KEY + " = ? ", new String[]{deleteKey + ""}); } public boolean searchMedicine(String searchKey) { SQLiteDatabase db = getWritableDatabase(); Cursor c = db.rawQuery("SELECT " + PharmDB.ScrappedComponentTable.COLUMN_COMPONENT_KEY + " FROM " + PharmDB.ScrappedComponentTable.TABLE_NAME + " WHERE " + PharmDB.ScrappedComponentTable.COLUMN_COMPONENT_KEY + " = ? ", new String[]{searchKey + ""}); if (c.getCount() <= 0) { c.close(); return false; } c.close(); return true; } public List<MedicineInfo> getScrappedMedicine() { List<MedicineInfo> list = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); // Select All Query String selectQuery = "SELECT * FROM " + PharmDB.ScrappedComponentTable.TABLE_NAME; Cursor c = db.rawQuery(selectQuery, null); try { // looping through all rows and adding to list if (c.moveToFirst()) { do { String key = c.getString(c.getColumnIndex(PharmDB.ScrappedComponentTable.COLUMN_COMPONENT_KEY)); MedicineInfo item = new MedicineInfo(); item.setName(c.getString(c.getColumnIndex(PharmDB.ScrappedComponentTable.COLUMN_MEDICINE_NAME))); item.setCompany(c.getString(c.getColumnIndex(PharmDB.ScrappedComponentTable.COLUMN_COMPANY_NAME))); item.setImageSrc(c.getString(c.getColumnIndex(PharmDB.ScrappedComponentTable.COLUMN_IMAGE_URL))); item.setBarcode(c.getString(c.getColumnIndex(PharmDB.ScrappedComponentTable.COLUMN_COMPONENT_KEY))); list.add(item); } while (c.moveToNext()); } } finally { try { c.close(); } catch (Exception ignore) { } } return list; } }
5dd4122e41a6cc0666d597eaba54d80f229eafb5
4dbbf63c1937a523890390c5ee34e81589f78e5e
/bus-oauth/src/main/java/org/aoju/bus/oauth/provider/QqProvider.java
d555fc8d62212181eea3be1cafe5e97ececdec42
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
q040407/bus
9b0970b829264899857a5035396ddbb1052e0aac
f10136c6ea472e8886355a76caa331cb607d59ef
refs/heads/master
2022-04-23T10:10:50.686780
2020-04-14T06:43:17
2020-04-14T06:43:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,900
java
/********************************************************************************* * * * The MIT License * * * * Copyright (c) 2015-2020 aoju.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * ********************************************************************************/ package org.aoju.bus.oauth.provider; import com.alibaba.fastjson.JSONObject; import org.aoju.bus.cache.metric.ExtendCache; import org.aoju.bus.core.lang.Normal; import org.aoju.bus.core.lang.Symbol; import org.aoju.bus.core.lang.exception.AuthorizedException; import org.aoju.bus.core.utils.StringUtils; import org.aoju.bus.http.Httpx; import org.aoju.bus.oauth.Builder; import org.aoju.bus.oauth.Context; import org.aoju.bus.oauth.Registry; import org.aoju.bus.oauth.magic.AccToken; import org.aoju.bus.oauth.magic.Callback; import org.aoju.bus.oauth.magic.Message; import org.aoju.bus.oauth.magic.Property; import java.util.Map; /** * qq登录 * * @author Kimi Liu * @version 5.8.6 * @since JDK 1.8+ */ public class QqProvider extends DefaultProvider { public QqProvider(Context context) { super(context, Registry.QQ); } public QqProvider(Context context, ExtendCache extendCache) { super(context, Registry.QQ, extendCache); } @Override protected AccToken getAccessToken(Callback Callback) { return getAuthToken(doGetAuthorizationCode(Callback.getCode())); } @Override public Message refresh(AccToken token) { String response = Httpx.get(refreshTokenUrl(token.getRefreshToken())); return Message.builder().errcode(Builder.ErrorCode.SUCCESS.getCode()).data(getAuthToken(response)).build(); } @Override protected Property getUserInfo(AccToken token) { String openId = this.getOpenId(token); JSONObject object = JSONObject.parseObject(doGetUserInfo(token)); if (object.getIntValue("ret") != 0) { throw new AuthorizedException(object.getString("msg")); } String avatar = object.getString("figureurl_qq_2"); if (StringUtils.isEmpty(avatar)) { avatar = object.getString("figureurl_qq_1"); } String location = String.format("%s-%s", object.getString("province"), object.getString("city")); return Property.builder() .username(object.getString("nickname")) .nickname(object.getString("nickname")) .avatar(avatar) .location(location) .uuid(openId) .gender(Normal.Gender.getGender(object.getString("gender"))) .token(token) .source(source.toString()) .build(); } /** * 获取QQ用户的OpenId,支持自定义是否启用查询unionid的功能,如果启用查询unionid的功能, * 那就需要开发者先通过邮件申请unionid功能,参考链接 {@see http://wiki.connect.qq.com/unionid%E4%BB%8B%E7%BB%8D} * * @param token 通过{@link QqProvider#getAccessToken(Callback)}获取到的{@code authToken} * @return openId */ private String getOpenId(AccToken token) { String response = Httpx.get(Builder.fromUrl("https://graph.qq.com/oauth2.0/me") .queryParam("access_token", token.getAccessToken()) .queryParam("unionid", context.isUnionId() ? 1 : 0) .build()); String removePrefix = StringUtils.replace(response, "callback(", Normal.EMPTY); String removeSuffix = StringUtils.replace(removePrefix, ");", Normal.EMPTY); String openId = StringUtils.trim(removeSuffix); JSONObject object = JSONObject.parseObject(openId); if (object.containsKey("error")) { throw new AuthorizedException(object.get("error") + Symbol.COLON + object.get("error_description")); } token.setOpenId(object.getString("openid")); if (object.containsKey("unionid")) { token.setUnionId(object.getString("unionid")); } return StringUtils.isEmpty(token.getUnionId()) ? token.getOpenId() : token.getUnionId(); } /** * 返回获取userInfo的url * * @param token 用户授权token * @return 返回获取userInfo的url */ @Override protected String userInfoUrl(AccToken token) { return Builder.fromUrl(source.userInfo()) .queryParam("access_token", token.getAccessToken()) .queryParam("oauth_consumer_key", context.getAppKey()) .queryParam("openid", token.getOpenId()) .build(); } private AccToken getAuthToken(String response) { Map<String, String> accessTokenObject = parseStringToMap(response); if (!accessTokenObject.containsKey("access_token") || accessTokenObject.containsKey("code")) { throw new AuthorizedException(accessTokenObject.get("msg")); } return AccToken.builder() .accessToken(accessTokenObject.get("access_token")) .expireIn(Integer.valueOf(accessTokenObject.get("expires_in"))) .refreshToken(accessTokenObject.get("refresh_token")) .build(); } }
630bf496cd6e01993333a70ba5061e2d7f85fe53
665d5a6e7ee7c60083cd002af7891b8e44458e27
/Android/BarnehageSFO/gen/com/example/barnehagesfo/R.java
41939527b0abf5f7108f4d7057a4d622a2037784
[ "Apache-2.0" ]
permissive
petand10/Barnehagen
56e548a44e8c4f90acc5b04e6518677794475de7
e6e9b5bbfbc57048054e4028d440add0f71936ea
refs/heads/master
2016-09-11T05:07:58.921540
2013-08-18T20:35:35
2013-08-18T20:35:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,230
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.example.barnehagesfo; public final class R { public static final class attr { } public static final class dimen { public static final int padding_large=0x7f040002; public static final int padding_medium=0x7f040001; public static final int padding_small=0x7f040000; } public static final class drawable { public static final int ic_action_search=0x7f020000; public static final int ic_launcher=0x7f020001; } public static final class id { public static final int LinearLayout1=0x7f080003; public static final int calendarView1=0x7f080001; public static final int container=0x7f080000; public static final int listviewContactInformation=0x7f080004; public static final int menu_settings=0x7f080009; public static final int textView1=0x7f080002; public static final int txtAdress=0x7f080008; public static final int txtChildName=0x7f080005; public static final int txtGuardianOne=0x7f080006; public static final int txtGuardianTwo=0x7f080007; } public static final class layout { public static final int activity_main=0x7f030000; public static final int contact_details=0x7f030001; public static final int contact_information=0x7f030002; public static final int contact_listview=0x7f030003; } public static final class menu { public static final int activity_main=0x7f070000; } public static final class string { public static final int app_name=0x7f050000; public static final int hello_world=0x7f050004; public static final int menu_settings=0x7f050005; public static final int title_activity_main=0x7f050006; public static final int title_section1=0x7f050003; public static final int title_section2=0x7f050002; public static final int title_section3=0x7f050001; } public static final class style { public static final int AppTheme=0x7f060000; } }
02c8c494ed2d90e028dd82b8c27a15dfbaa71840
61e0a17fc4aa7dac7f870f6b2be94d86bdb97b0f
/liquibase-core/src/main/java/liquibase/serializer/core/xml/XMLChangeLogSerializer.java
c8a66326cb30b114d5eb3f0e45153b16bbe3707c
[ "Apache-2.0" ]
permissive
johnjonathan/liquibase
b62e71bbae8011ba22bf0501b8fd28c9353d3c81
58fca504fcc0fd5157378f627a127a830feb179c
refs/heads/master
2021-01-18T00:04:59.911294
2014-06-28T13:59:50
2014-06-28T13:59:50
21,302,739
1
0
null
null
null
null
UTF-8
Java
false
false
16,362
java
package liquibase.serializer.core.xml; import liquibase.change.*; import liquibase.changelog.ChangeSet; import liquibase.changelog.DatabaseChangeLog; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.parser.NamespaceDetails; import liquibase.parser.NamespaceDetailsFactory; import liquibase.parser.core.xml.LiquibaseEntityResolver; import liquibase.serializer.ChangeLogSerializer; import liquibase.serializer.LiquibaseSerializable; import liquibase.util.ISODateFormat; import liquibase.util.StreamUtil; import liquibase.util.StringUtils; import liquibase.util.XMLUtil; import liquibase.util.xml.DefaultXmlWriter; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.util.*; public class XMLChangeLogSerializer implements ChangeLogSerializer { private Document currentChangeLogFileDOM; public XMLChangeLogSerializer() { try { this.currentChangeLogFileDOM = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (ParserConfigurationException e) { throw new UnexpectedLiquibaseException(e); } } protected XMLChangeLogSerializer(Document currentChangeLogFileDOM) { this.currentChangeLogFileDOM = currentChangeLogFileDOM; } public void setCurrentChangeLogFileDOM(Document currentChangeLogFileDOM) { this.currentChangeLogFileDOM = currentChangeLogFileDOM; } @Override public String[] getValidFileExtensions() { return new String[]{"xml"}; } public String serialize(DatabaseChangeLog databaseChangeLog) { return null; //todo } @Override public String serialize(LiquibaseSerializable object, boolean pretty) { StringBuffer buffer = new StringBuffer(); int indent = -1; if (pretty) { indent = 0; } nodeToStringBuffer(createNode(object), buffer, indent); return buffer.toString(); } @Override public void write(List<ChangeSet> changeSets, OutputStream out) throws IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder documentBuilder; try { documentBuilder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } documentBuilder.setEntityResolver(new LiquibaseEntityResolver(this)); Document doc = documentBuilder.newDocument(); Element changeLogElement = doc.createElementNS(LiquibaseSerializable.STANDARD_CHANGELOG_NAMESPACE, "databaseChangeLog"); changeLogElement.setAttribute("xmlns", LiquibaseSerializable.STANDARD_CHANGELOG_NAMESPACE); changeLogElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); Map<String, String> shortNameByNamespace = new HashMap<String, String>(); Map<String, String> urlByNamespace = new HashMap<String, String>(); for (NamespaceDetails details : NamespaceDetailsFactory.getInstance().getNamespaceDetails()) { for (String namespace : details.getNamespaces()) { if (details.supports(this, namespace)){ String shortName = details.getShortName(namespace); String url = details.getSchemaUrl(namespace); if (shortName != null && url != null) { shortNameByNamespace.put(namespace, shortName); urlByNamespace.put(namespace, url); } } } } for (Map.Entry<String, String> entry : shortNameByNamespace.entrySet()) { if (!entry.getValue().equals("")) { changeLogElement.setAttribute("xmlns:"+entry.getValue(), entry.getKey()); } } String schemaLocationAttribute = ""; for (Map.Entry<String, String> entry : urlByNamespace.entrySet()) { if (!entry.getValue().equals("")) { schemaLocationAttribute += entry.getKey()+" "+entry.getValue()+" "; } } changeLogElement.setAttribute("xsi:schemaLocation", schemaLocationAttribute.trim()); doc.appendChild(changeLogElement); setCurrentChangeLogFileDOM(doc); for (ChangeSet changeSet : changeSets) { doc.getDocumentElement().appendChild(createNode(changeSet)); } new DefaultXmlWriter().write(doc, out); } @Override public void append(ChangeSet changeSet, File changeLogFile) throws IOException { FileInputStream in = new FileInputStream(changeLogFile); String existingChangeLog = StreamUtil.getStreamContents(in); in.close(); FileOutputStream out = new FileOutputStream(changeLogFile); try { if (!existingChangeLog.contains("</databaseChangeLog>")) { write(Arrays.asList(changeSet), out); } else { existingChangeLog = existingChangeLog.replaceFirst("</databaseChangeLog>", serialize(changeSet, true) + "\n</databaseChangeLog>"); StreamUtil.copy(new ByteArrayInputStream(existingChangeLog.getBytes()), out); } out.flush(); } finally { out.close(); } } public Element createNode(LiquibaseSerializable object) { String namespace = object.getSerializedObjectNamespace(); String nodeName = object.getSerializedObjectName(); NamespaceDetails details = NamespaceDetailsFactory.getInstance().getNamespaceDetails(this, namespace); if (details != null && !details.getShortName(namespace).equals("")) { nodeName = details.getShortName(namespace)+":"+nodeName; } Element node = currentChangeLogFileDOM.createElementNS(namespace, nodeName); for (String field : object.getSerializableFields()) { setValueOnNode(node, field, object.getSerializableFieldValue(field), object.getSerializableFieldType(field)); } return node; } private void setValueOnNode(Element node, String objectName, Object value, LiquibaseSerializable.SerializationType serializationType) { if (value == null) { return; } if (value instanceof Collection) { for (Object child : (Collection) value) { setValueOnNode(node, objectName, child, serializationType); } } else if (value instanceof Map) { for (Map.Entry entry : (Set<Map.Entry>) ((Map) value).entrySet()) { Element mapNode = currentChangeLogFileDOM.createElementNS(LiquibaseSerializable.STANDARD_CHANGELOG_NAMESPACE, objectName); setValueOnNode(mapNode, (String) entry.getKey(), entry.getValue(), serializationType); } } else if (value instanceof LiquibaseSerializable) { node.appendChild(createNode((LiquibaseSerializable) value)); } else { if (serializationType.equals(LiquibaseSerializable.SerializationType.NESTED_OBJECT)) { String namespace = LiquibaseSerializable.STANDARD_CHANGELOG_NAMESPACE; node.appendChild(createNode(namespace, objectName, value.toString())); } else if (serializationType.equals(LiquibaseSerializable.SerializationType.DIRECT_VALUE)) { node.setTextContent(value.toString()); } else { node.setAttribute(objectName, value.toString()); } } } // create a XML node with nodeName and simple text content public Element createNode(String nodeNamespace, String nodeName, String nodeContent) { Element element = currentChangeLogFileDOM.createElementNS(nodeNamespace, nodeName); element.setTextContent(nodeContent); return element; } public Element createNode(ColumnConfig columnConfig) { Element element = currentChangeLogFileDOM.createElementNS(columnConfig.getSerializedObjectNamespace(), "column"); if (columnConfig.getName() != null) { element.setAttribute("name", columnConfig.getName()); } if (columnConfig.getType() != null) { element.setAttribute("type", columnConfig.getType()); } if (columnConfig.getDefaultValue() != null) { element.setAttribute("defaultValue", columnConfig.getDefaultValue()); } if (columnConfig.getDefaultValueNumeric() != null) { element.setAttribute("defaultValueNumeric", columnConfig.getDefaultValueNumeric().toString()); } if (columnConfig.getDefaultValueDate() != null) { element.setAttribute("defaultValueDate", new ISODateFormat().format(columnConfig.getDefaultValueDate())); } if (columnConfig.getDefaultValueBoolean() != null) { element.setAttribute("defaultValueBoolean", columnConfig.getDefaultValueBoolean().toString()); } if (columnConfig.getDefaultValueComputed() != null) { element.setAttribute("defaultValueComputed", columnConfig.getDefaultValueComputed().toString()); } if (columnConfig.getDefaultValueSequenceNext() != null) { element.setAttribute("defaultValueSequenceNext", columnConfig.getDefaultValueSequenceNext().toString()); } if (columnConfig.getValue() != null) { element.setAttribute("value", columnConfig.getValue()); } if (columnConfig.getValueNumeric() != null) { element.setAttribute("valueNumeric", columnConfig.getValueNumeric().toString()); } if (columnConfig.getValueBoolean() != null) { element.setAttribute("valueBoolean", columnConfig.getValueBoolean().toString()); } if (columnConfig.getValueDate() != null) { element.setAttribute("valueDate", new ISODateFormat().format(columnConfig.getValueDate())); } if (columnConfig.getValueComputed() != null) { element.setAttribute("valueComputed", columnConfig.getValueComputed().toString()); } if (columnConfig.getValueSequenceNext() != null) { element.setAttribute("valueSequenceNext", columnConfig.getValueSequenceNext().toString()); } if (columnConfig.getValueSequenceCurrent() != null) { element.setAttribute("valueSequenceNext", columnConfig.getValueSequenceCurrent().toString()); } if (StringUtils.trimToNull(columnConfig.getRemarks()) != null) { element.setAttribute("remarks", columnConfig.getRemarks()); } if (columnConfig.isAutoIncrement() != null && columnConfig.isAutoIncrement()) { element.setAttribute("autoIncrement", "true"); } ConstraintsConfig constraints = columnConfig.getConstraints(); if (constraints != null) { Element constraintsElement = currentChangeLogFileDOM.createElementNS(columnConfig.getSerializedObjectNamespace(), "constraints"); if (constraints.getCheckConstraint() != null) { constraintsElement.setAttribute("checkConstraint", constraints.getCheckConstraint()); } if (constraints.getForeignKeyName() != null) { constraintsElement.setAttribute("foreignKeyName", constraints.getForeignKeyName()); } if (constraints.getReferences() != null) { constraintsElement.setAttribute("references", constraints.getReferences()); } if (constraints.getReferencedTableName() != null) { constraintsElement.setAttribute("referencedTableName", constraints.getReferencedTableName()); } if (constraints.getReferencedColumnNames() != null) { constraintsElement.setAttribute("referencedTableName", constraints.getReferencedColumnNames()); } if (constraints.isDeferrable() != null) { constraintsElement.setAttribute("deferrable", constraints.isDeferrable().toString()); } if (constraints.isDeleteCascade() != null) { constraintsElement.setAttribute("deleteCascade", constraints.isDeleteCascade().toString()); } if (constraints.isInitiallyDeferred() != null) { constraintsElement.setAttribute("initiallyDeferred", constraints.isInitiallyDeferred().toString()); } if (constraints.isNullable() != null) { constraintsElement.setAttribute("nullable", constraints.isNullable().toString()); } if (constraints.isPrimaryKey() != null) { constraintsElement.setAttribute("primaryKey", constraints.isPrimaryKey().toString()); } if (constraints.isUnique() != null) { constraintsElement.setAttribute("unique", constraints.isUnique().toString()); } if (constraints.getUniqueConstraintName() != null) { constraintsElement.setAttribute("uniqueConstraintName", constraints.getUniqueConstraintName()); } if (constraints.getPrimaryKeyName() != null) { constraintsElement.setAttribute("primaryKeyName", constraints.getPrimaryKeyName()); } if (constraints.getPrimaryKeyTablespace() != null) { constraintsElement.setAttribute("primaryKeyTablespace", constraints.getPrimaryKeyTablespace()); } element.appendChild(constraintsElement); } return element; } /* * Creates a {@link String} using the XML element representation of this * change * * @param node the {@link Element} associated to this change * @param buffer a {@link StringBuffer} object used to hold the {@link String} * representation of the change */ private void nodeToStringBuffer(Node node, StringBuffer buffer, int indent) { if (indent >= 0) { if (indent > 0) { buffer.append("\n"); } buffer.append(StringUtils.repeat(" ", indent)); } buffer.append("<").append(node.getNodeName()); SortedMap<String, String> attributeMap = new TreeMap<String, String>(); NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); attributeMap.put(attribute.getNodeName(), attribute.getNodeValue()); } boolean firstAttribute = true; for (Map.Entry entry : attributeMap.entrySet()) { String value = (String) entry.getValue(); if (value != null) { if (indent >= 0 && !firstAttribute && attributeMap.size() > 2) { buffer.append("\n").append(StringUtils.repeat(" ", indent)).append(" "); } else { buffer.append(" "); } buffer.append(entry.getKey()).append("=\"").append(value).append("\""); firstAttribute = false; } } String textContent = StringUtils.trimToEmpty(XMLUtil.getTextContent(node)); buffer.append(">").append(textContent); boolean sawChildren = false; NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node childNode = childNodes.item(i); if (childNode instanceof Element) { int newIndent = indent; if (newIndent >= 0) { newIndent += 4; } nodeToStringBuffer(childNode, buffer, newIndent); sawChildren = true; } } if (indent >= 0) { if (sawChildren) { buffer.append("\n").append(StringUtils.repeat(" ", indent)); } } if (!sawChildren && textContent.equals("")) { buffer.replace(buffer.length()-1, buffer.length(), "/>"); } else { buffer.append("</").append(node.getNodeName()).append(">"); } } }
cd87f9444e387e116463fd4b8d4b10ca0288efef
fe4e114e48c64f72e4aa4de353e661b726995c86
/src/main/java/com/pages/CurrentLotteryPage.java
8c97c31f37442ff3869920498f7953f5b56e8fe9
[]
no_license
AlexeyPaskhin/rv
721e7439100b7b6b65d46033d49c8d0a14052e96
92dea175b85bd2bdc0c59c3e7ecf25c49d2c0540
refs/heads/master
2020-04-15T05:40:11.955903
2018-09-25T08:40:56
2018-09-25T08:40:56
164,432,725
0
0
null
null
null
null
UTF-8
Java
false
false
494
java
package com.pages; import com.Elements.Button; import com.Elements.Element; import lombok.Getter; import org.openqa.selenium.By; @Getter public class CurrentLotteryPage extends AbstractPage { private Button GET_A_RAFFLE_TICKET = new Button(By.xpath("//span[text()='Получить лотерейный билет']/..")); private Element LOTTERY_IS_FINISHED_INFO = new Element(By.xpath("//h3[@class='lottery-info__close-title' and text() ='Лотерея завершена']")); }
c9905c0135f6173513152b3dc18bcb8c6798d671
dd61169a3da99ff1f1df94c50fc735ee46b52ef0
/VAReadmissionMoonstoneWorkspace/Moonstone/src/moonstone/api/MoonstoneAnnotationRelation.java
f45368f2f9f1590da00625bf8aef736b8fee1510
[]
no_license
bbauta/VAReadmissionMoonstone
6ef61c94d76964d90a1a84ad4cdc2033b9bb8a3a
7ca0b9cc3f73273a95db7ddca5ace69053c0a685
refs/heads/master
2021-03-10T17:35:15.386095
2019-04-18T22:31:02
2019-04-18T22:31:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,538
java
/* Copyright 2018 Wendy Chapman (wendy.chapman\@utah.edu) & Lee Christensen (leenlp\@q.com) 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 moonstone.api; public class MoonstoneAnnotationRelation { private MoonstoneAnnotation annotation = null; private String relation = null; private MoonstoneAnnotation subject = null; private MoonstoneAnnotation modifier = null; public MoonstoneAnnotationRelation(MoonstoneAnnotation annotation, String relation, MoonstoneAnnotation subject, MoonstoneAnnotation modifier) { this.annotation = annotation; this.relation = relation; this.subject = subject; this.modifier = modifier; } public String toString() { String str = this.relation + "(" + this.subject.getId() + "," + this.modifier.getId() + ")"; return str; } public MoonstoneAnnotation getAnnotation() { return annotation; } public String getRelation() { return relation; } public MoonstoneAnnotation getSubject() { return subject; } public MoonstoneAnnotation getModifier() { return modifier; } }
642171eb2f82385127fb89321e726b41f2711a74
04dffcef5286116520f1f37c8931d873ac9d2725
/src/main/java/me/planetology/dragondefend/kit/kits/DefenderKit.java
9fff9e5703543afa58ff251e053697bc42569d6b
[ "MIT" ]
permissive
planetology/dragon-defend
cc5fa1a8d3bba7bd88f27bfeac71e89772bf2d68
c69703702cd4cee6c1f5097080ffa1488dc69e46
refs/heads/master
2020-03-28T21:24:43.484560
2018-09-17T16:31:53
2018-09-17T16:31:53
149,020,699
0
0
null
null
null
null
UTF-8
Java
false
false
2,193
java
package me.planetology.dragondefend.kit.kits; import me.planetology.dragondefend.DragonDefend; import me.planetology.dragondefend.kit.Kit; import me.planetology.dragondefend.utils.ItemUtil; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import java.util.HashMap; public class DefenderKit implements Kit { private ItemUtil itemUtil; public DefenderKit() { itemUtil = DragonDefend.getInstance().getGameManager().getItemUtil(); } @Override public ItemStack[] getItems() { HashMap<Enchantment, Integer> swordEnchantments = new HashMap<>(); swordEnchantments.put(Enchantment.DAMAGE_ALL, 1); ItemStack sword = itemUtil.setMaterial(Material.IRON_SWORD).setAmount(1).setName(ChatColor.GOLD + "Dragon Breath").setEnchantments(swordEnchantments).setUnbreakable(true).build(); return new ItemStack[]{sword}; } @Override public ItemStack getHelmet() { HashMap<Enchantment, Integer> enchantments = new HashMap<>(); enchantments.put(Enchantment.PROTECTION_ENVIRONMENTAL, 1); return itemUtil.setMaterial(Material.IRON_HELMET).setAmount(1).setEnchantments(enchantments).build(); } @Override public ItemStack getChestPlate() { HashMap<Enchantment, Integer> enchantments = new HashMap<>(); enchantments.put(Enchantment.PROTECTION_ENVIRONMENTAL, 1); return itemUtil.setMaterial(Material.IRON_CHESTPLATE).setAmount(1).setEnchantments(enchantments).build(); } @Override public ItemStack getLeggings() { HashMap<Enchantment, Integer> enchantments = new HashMap<>(); enchantments.put(Enchantment.PROTECTION_ENVIRONMENTAL, 1); return itemUtil.setMaterial(Material.IRON_LEGGINGS).setAmount(1).setEnchantments(enchantments).build(); } @Override public ItemStack getBoots() { HashMap<Enchantment, Integer> enchantments = new HashMap<>(); enchantments.put(Enchantment.PROTECTION_ENVIRONMENTAL, 1); return itemUtil.setMaterial(Material.IRON_BOOTS).setAmount(1).setEnchantments(enchantments).build(); } }
ab44cf36df76797dc9c1e60ed0fd79c1900c8d2b
8927c2c50e46a680b9bafa69a26bbd6471e0c496
/src/main/java/com/ibm/jenkinspractice/jenkinspractice/HomeController.java
06d4a04a0c2a1251632ab9ed83ddcaaa8b7a77f1
[]
no_license
pat5212/testJenkins
46d7fb8c51af0ea5c42fb09ff27474203c9ab6b4
ece5e2ab6dcaa830c6fa9bf52cdb7876336ad64a
refs/heads/master
2020-03-19T20:04:02.108178
2018-06-11T06:58:40
2018-06-11T06:58:40
136,886,454
0
0
null
null
null
null
UTF-8
Java
false
false
320
java
package com.ibm.jenkinspractice.jenkinspractice; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HomeController { @RequestMapping("/home") public String home() { return "Hello IBM"; } }
73cac476818ed97b1a7d94119a6901c9cae3a30a
e4409342dc8043a4a33145e04496766fd9477c57
/src/main/java/com/lesson/model/Menu.java
cbc2b0e2197d9b39a6ce9ce8e4a1bc9c9b776e30
[]
no_license
princeqjzh/iWeb
4d371516b24b607aed7f3e0782057f273e88c78f
87d3901e50f91ba78603c83c5bca5405a34a10e8
refs/heads/master
2023-08-31T04:42:17.030956
2023-08-23T03:57:59
2023-08-23T03:57:59
157,643,718
8
79
null
2022-12-16T03:05:19
2018-11-15T02:59:37
CSS
UTF-8
Java
false
false
617
java
package com.lesson.model; public class Menu { int mid; int cid; String mname; float price; public int getMid() { return mid; } public void setMid(int mid) { this.mid = mid; } public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public String getMname() { return mname; } public void setMname(String mname) { this.mname = mname; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
ad786c263415e04b549dea613eded40b2b607cc0
7586e976f18c8786ce7f9a1fc77d3632a141d796
/SMI-SDK/Java SDK/test/pt/sapo/gis/trace/EntrySeverityEventFilterTest.java
610681360631b9a11665cb2cb84a24f8199358d9
[]
no_license
stvkoch/sapo-services-sdk
3c5612ea66925d89035d4e82b2fc9acbf4d08e4c
6dc065132d0d4af076ca55a1b91a0b703e0056c0
refs/heads/master
2021-01-16T20:07:57.227438
2014-07-09T10:51:00
2014-07-09T10:51:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,134
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pt.sapo.gis.trace; import java.util.Collection; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import pt.sapo.gis.trace.configuration.SeverityType; import static org.junit.Assert.*; /** * * @author GIS Team */ public class EntrySeverityEventFilterTest { EntrySeverityEventFilter instance; @Before public void setUp() { Collection<SeverityType> values = new ArrayList<SeverityType>(); values.add(SeverityType.WARN); values.add(SeverityType.INFO); instance = new EntrySeverityEventFilter(values); } /** * Test of test method, of class EntrySeverityEventFilter. */ @Test public void testTest() { System.out.println("test"); Entry e = new Entry("", SeverityType.WARN); boolean result_1 = instance.test(e); e = new Entry("", SeverityType.DEBUG); boolean result_2 = instance.test(e); assertEquals(result_1, true); assertEquals(result_2, false); } }
f61cc392c9d363ed9b8599b3bb70173e11cbf29e
37d66db1841a62123e6c1cd92b282fbf5864db65
/TheatreSeatingArrangmentApp/src/main/java/com/barclays/service/SeatingService.java
03f97c117e79a77be0b1a3226f2eb94d11beac3e
[]
no_license
neelimapp/Projects
3dbec9767d55637fb206e0828e74bb5bcb74c7cd
d507e9202ee9f104996957979164f9829f3c488b
refs/heads/master
2021-04-09T17:54:17.347138
2020-04-17T03:19:52
2020-04-17T03:19:52
125,667,862
0
0
null
null
null
null
UTF-8
Java
false
false
492
java
package com.barclays.service; import java.util.List; import com.barclays.dao.SeatingRequest; import com.barclays.dao.SeatingResponse; import com.barclays.dao.TheatreLayout; public interface SeatingService { /** * Method to process requests * * @param layout theatre layout * @param seatingRequests sorted set of seating requests * @return List of seating responses */ List<SeatingResponse> processRequests(TheatreLayout layout, List<SeatingRequest> seatingRequests); }
08774c6fc57ce1b8ba17c3614da0b3e3879577fc
dc98a407662e73260ef76ccc8250a422b987de85
/src/main/java/pageObjects/HomePage.java
3f0d5302ca5ef0f57c24dcb89cbd808f16f5370c
[]
no_license
jasna84/AutomationPractice
de5a915608312f9fee0c27093dc47a4b2cd10afa
5dff6dbb13aed8231027839cd8943abe4febc8d3
refs/heads/master
2023-01-08T03:42:35.531661
2020-10-28T14:02:59
2020-10-28T14:02:59
308,034,985
0
0
null
null
null
null
UTF-8
Java
false
false
3,179
java
package main.java.pageObjects; import main.java.config.BasePage; import main.java.config.Driver; import main.java.config.Utils; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import java.util.List; public class HomePage extends BasePage { public String homeURL = "http://automationpractice.com/index.php"; public void navigateToHomePage() { Driver.getInstance().getDriver().navigate().to(homeURL); } By searchField = By.id("search_query_top"); By resultCount = By.className("heading-counter"); By listView = By.id("list"); By addToCartButtons = By.cssSelector("a[title = 'Add to cart'"); By continueShopping = By.cssSelector("span[title = 'Continue shopping'"); By viewShoppingCart = By.cssSelector("a[title = 'View my shopping cart'"); By productNumber = By.className("ajax_cart_quantity"); By totalProducts = By.id("total_product"); By totalShipping = By.id("total_shipping"); By total = By.id("total_price_without_tax"); public void searchForDresses() { enterSearchTerm(searchField, "dresses"); } public int getNumberFromResult() { String text = getElementText(resultCount); int number = Integer.parseInt(Utils.extractNumberFromString(text)); System.out.println(number); return number; } public void clickOnList() { String itemClass = getElementAttribute(listView, "class"); if(itemClass.equals("selected")){ System.out.println("List already selected"); } else { click(listView); System.out.println("List view clicked"); } } public void selectItems() { List<WebElement> buttons = getListElements(addToCartButtons); System.out.println("Number of buttons: " + buttons.size()); click(buttons.get(0)); hardCodedWaiter(2000); click(continueShopping); hardCodedWaiter(2000); click(buttons.get(1)); hardCodedWaiter(2000); click(continueShopping); hardCodedWaiter(2000); click(buttons.get(3)); hardCodedWaiter(2000); click(continueShopping); } public int getProductNumber() { int number = Integer.parseInt(getElementText(productNumber)); System.out.println("Products: " + number); return number; } public void openCartSummary() { clickJS(viewShoppingCart); } public int getTotalProducts() { String text = getElementText(totalProducts); int number = Integer.parseInt(Utils.extractNumberFromString(text)); System.out.println("Total products: " + number); return number; } public int getTotalShipping() { String text = getElementText(totalShipping); int number = Integer.parseInt(Utils.extractNumberFromString(text)); System.out.println("Total shipping: " + number); return number; } public int getTotal() { String text = getElementText(total); int number = Integer.parseInt(Utils.extractNumberFromString(text)); System.out.println("Total: " + number); return number; } }
63fab75d77083498239053f0ad84e2623fd1fa88
1e8b26e3bfed321376dca48d587192e146bb8331
/e1-gui/src/peer/gui/ConfigPanel.java
a1b18440d48e0d112628cd4bfb70c0162d114c8f
[]
no_license
Alchemy-Meister/ddss-tracker
0f84cc3409fce7a791dd6ebcbb943464ec7327cb
1f18a89b38114864bd0418dba57437f03f205849
refs/heads/master
2021-01-21T09:35:05.119232
2016-01-25T22:28:33
2016-01-25T22:28:33
43,552,400
0
0
null
null
null
null
UTF-8
Java
false
false
6,326
java
package peer.gui; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.net.SocketException; import java.util.Observable; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import common.gui.ObserverJPanel; import net.miginfocom.swing.MigLayout; import peer.controllers.ConfigController; import javax.swing.JPanel; import java.awt.FlowLayout; /** * @author Irene * @author Jesus */ public class ConfigPanel extends ObserverJPanel implements FocusListener, DocumentListener, ActionListener { private static final long serialVersionUID = -1098424124151618936L; private static final String INVALID_IP_ADDRESS_MSG = "Invalid IP address"; private static final String UNKNOWN_IP_ADDRESS_MSG = "Unknown IP address"; private static final String INVALID_PORT_MSG = "Invalid port number"; private static final String CONNECT_MSG = "Connect"; private static final String DISCONNECT_MGS = "Disconnect"; private JTextField tfPort; private JTextField tfIP; private JLabel ipAddressError; private JLabel portError; private JButton connectButton; private ConfigController configController; public ConfigPanel(Color color) { super(); configController = new ConfigController(); this.setBackground(color); this.setLayout(new MigLayout("", "[][grow][150px:n]", "[20px:n,grow][][][][20px:n,grow]")); JLabel lblIp = new JLabel("IP"); this.add(lblIp, "cell 0 1,alignx trailing"); tfIP = new JTextField(); this.add(tfIP, "cell 1 1,growx"); tfIP.setColumns(10); tfIP.addFocusListener(this); tfIP.getDocument().putProperty("owner", tfIP); tfIP.getDocument().addDocumentListener(this); JLabel lblPort = new JLabel("Port"); this.add(lblPort, "cell 0 2,alignx trailing"); tfPort = new JTextField(); this.add(tfPort, "cell 1 2,growx"); tfPort.setColumns(10); tfPort.addFocusListener(this); tfPort.getDocument().putProperty("owner", tfPort); tfPort.getDocument().addDocumentListener(this); ipAddressError = new JLabel(); ipAddressError.setVisible(false); ipAddressError.setForeground(Color.RED); ipAddressError.setText(INVALID_IP_ADDRESS_MSG); this.add(ipAddressError, "cell 2 1,alignx left"); portError = new JLabel(INVALID_PORT_MSG); portError.setVisible(false); portError.setForeground(Color.RED); this.add(portError, "cell 2 2,alignx left"); JPanel panel = new JPanel(); add(panel, "cell 1 3,grow"); panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); panel.setBackground(color); connectButton = new JButton("Connect"); connectButton.setEnabled(false); panel.add(connectButton); connectButton.addActionListener(this); } @Override public void update(Observable o, Object arg) { // TODO Auto-generated method stub } @Override public void unsubscribe() { } @Override public void focusGained(FocusEvent e) { Component focusedComponent = e.getComponent(); if(focusedComponent.equals(ConfigPanel.this.tfIP)) { if(!((JTextField) focusedComponent).getText().equals("")) { ((JTextField) focusedComponent).selectAll(); } } else if(focusedComponent.equals(ConfigPanel.this.tfPort)) { if(!((JTextField) focusedComponent).getText().equals("")) { ((JTextField) focusedComponent).selectAll(); } } } @Override public void focusLost(FocusEvent e) { // NOTHING TODO HERE. } @Override public void insertUpdate(DocumentEvent e) { showErrorMessage(e.getDocument()); validateForm(); } @Override public void removeUpdate(DocumentEvent e) { showErrorMessage(e.getDocument()); validateForm(); } @Override public void changedUpdate(DocumentEvent e) { // NOTHING TODO HERE. } private void showErrorMessage(Document doc) { JTextField field = (JTextField) doc.getProperty("owner"); if(field.equals(this.tfIP)) { try { if(!configController.isValidMCIP(doc.getText(0, doc.getLength()))) { ipAddressError.setVisible(true); } else { ipAddressError.setVisible(false); } } catch (BadLocationException e1) { e1.printStackTrace(); } } else if(field.equals(this.tfPort)) { try { if(!configController.isValidPort(doc.getText(0, doc.getLength()))) { portError.setVisible(true); } else { portError.setVisible(false); } } catch (BadLocationException e1) { e1.printStackTrace(); } } } private void validateForm() { boolean validForm = true; Component[] components = this.getComponents(); int i = 0; while (validForm && i < components.length) { if(components[i].getClass().equals(JLabel.class)){ if(components[i].equals(ipAddressError) || components[i].equals(portError)) { if(components[i].isVisible()) { validForm = false; } } } else if(components[i].getClass().equals(JTextField.class)){ if(((JTextField)components[i]).getText().equals("")) { validForm = false; } } i++; } if(validForm) { connectButton.setEnabled(true); } else { connectButton.setEnabled(false); } } @Override public void actionPerformed(ActionEvent e) { JButton clickedButton = (JButton) e.getSource(); if (clickedButton.equals(connectButton)) { if(!this.configController.isConnected()) { try { this.configController.connect( Integer.parseInt(this.tfPort.getText()), this.tfIP.getText()); this.connectButton.setText(DISCONNECT_MGS); this.tfIP.setEnabled(false); this.tfPort.setEnabled(false); } catch (SocketException exception) { exception.printStackTrace(); ipAddressError.setText(UNKNOWN_IP_ADDRESS_MSG); ipAddressError.setVisible(true); connectButton.setEnabled(false); tfIP.requestFocus(); } } else { this.configController.disconnect(); this.connectButton.setText(CONNECT_MSG); this.tfIP.setEnabled(true); this.tfPort.setEnabled(true); } } } }
7eeb507de9088277825e8cc779113d9e70e33983
3d45ff191e67b776f8f8c73c775811600da843bf
/backend/de.unidue.ltl.ctestbuilder.service.LangId/src/main/java/de/unidue/ltl/ctestbuilder/service/LangId/HelloWorld.java
e86e2dc6759ba686f526b73fec346053b47d6109
[]
no_license
zesch/ctest-builder
f1bcf5d71cd6d439025bf81eba12547fd8b65933
f060b64784e2e56495ab91ebaa2ec0fed9fd91b0
refs/heads/master
2022-06-24T14:31:50.632187
2020-03-28T07:41:16
2020-03-28T07:41:16
89,223,570
1
0
null
2022-06-02T20:54:55
2017-04-24T09:43:49
TypeScript
UTF-8
Java
false
false
312
java
package de.unidue.ltl.ctestbuilder.service.LangId; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/hello") public class HelloWorld { @GET @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { return "Hello from Jersey"; } }
05fb7778dced657608aa6c8efbe1e7d9e3e0e427
6f30def756671402119bff2144cfc2550d4b95fb
/cracking-the-coding-interview/src/main/java/chapter07/carddeck/BlackJackCard.java
6b43fe4ee15d7e281996b855a30e59ebb7a3cf58
[]
no_license
Akorsa/books
40542626d818d5587ae04c4cbddeff53ac5f1e1b
cdaa9f3a2ef1cd3c0a0e99e405a53fd57b2c93a7
refs/heads/master
2021-01-11T08:33:35.240352
2016-06-03T15:00:31
2016-06-03T15:00:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
622
java
package chapter07.carddeck; /** * Created by akhalikov on 19/02/16 */ public class BlackJackCard extends Card { public BlackJackCard(int faceValue, Suit suit) { super(faceValue, suit); } @Override public int value() { if (isAce()) return 1; else if (isFaceCard()) return 10; else return faceValue; } public int minValue() { return isAce() ? 1: value(); } public int maxValue() { return isAce() ? 11: value(); } public boolean isAce() { return faceValue == 1; } public boolean isFaceCard() { return faceValue >= 11 && faceValue <= 13; } }
684dc773a09d557d1de3bf4389fbeaca1443b50f
3759284dd4b3992d467cc9ff2f18c0c3c115b711
/src/main/java/org/lemanoman/contas/config/InitialDataConfig.java
0bc5babe64772c1b0bf4765a0bfa8152004f4c1a
[]
no_license
dofun12/contas
bee826add0a189d7498f193959416a60082c6efe
5b1249e524ef9eb93d8f119a77919c2259fe80ff
refs/heads/master
2023-05-26T01:12:37.744135
2020-03-13T01:33:44
2020-03-13T01:33:44
241,358,712
1
0
null
2023-05-23T20:12:19
2020-02-18T12:44:35
CSS
UTF-8
Java
false
false
475
java
package org.lemanoman.contas.config; import org.lemanoman.contas.service.DatabaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; @Configuration public class InitialDataConfig { @Autowired private DatabaseService databaseService; @PostConstruct public void postConstruct() { databaseService.resetDatabase(false); } }
5c608c5d42aa057e2b68ccd1d4a942f97eff9bbc
43d516d103bb08c5df2b3e9eaefdcb754eafca63
/Data Structures/Linked Lists/Insert a node at the head of a linked list/Solution.java
3cf9beb01ad053474e0018127bff3f9134a23f83
[]
no_license
pradeepsharma2004/HackerRank_Solution
1bc1fb943d443eb1c42a3f78d02b7688ef28ca24
7993e2b007e44464cae5772ff6eb9102a900adcd
refs/heads/master
2021-05-10T20:54:20.419064
2018-01-20T19:47:14
2018-01-20T19:47:14
118,208,769
0
0
null
null
null
null
UTF-8
Java
false
false
508
java
/* Insert Node at the beginning of a linked list head pointer input could be NULL as well for empty list Node is defined as class Node { int data; Node next; } */ // This is a "method-only" submission. // You only need to complete this method. Node Insert(Node head,int x) { Node node=new Node(); node.data=x; node.next=null; if(head==null) { return node; } else { node.next=head; head=node; return head; } }
ec3d1a7fa797d48d00c691905262df25e6f3c352
7f52c1414ee44a3efa9fae60308e4ae0128d9906
/core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest4.java
fed3a0a041d361c11c1ef08eaf9cf7c23419b1bb
[ "Apache-2.0" ]
permissive
luoyongsir/druid
1f6ba7c7c5cabab2879a76ef699205f484f2cac7
37552f849a52cf0f2784fb7849007e4656851402
refs/heads/master
2022-11-19T21:01:41.141853
2022-11-19T13:21:51
2022-11-19T13:21:51
474,518,936
0
1
Apache-2.0
2022-03-27T02:51:11
2022-03-27T02:51:10
null
UTF-8
Java
false
false
1,145
java
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.bvt.filter.wall.mysql; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.wall.WallUtils; /** * SQLServerWallTest * * @author RaymondXiu * @version 1.0, 2012-3-18 * @see */ public class MySqlWallTest4 extends TestCase { public void test_stuff() throws Exception { Assert.assertFalse(WallUtils.isValidateMySql(// "SSELECT a.*,b.name FROM vote_info a left join vote_item b on a.item_id=b.id where a.id<10 or 1=1 limit 1,10")); } }
b4fcda6b6e1b1c2b740a8900658e9e96924c78a7
fc7d2d6a843e861059b912da9e354c42209f72d3
/LanguageFactory/src/com/center/service/hrmgt/PositionService.java
c48e7a878fdf1ce7383a5baae2143271c55afda9
[]
no_license
lingyu5219/gitRepo
fc19510743f20793caba02c7e5ff0365784a7d08
5f2e8776dadb8b4be2f87053a8942174c7720263
refs/heads/master
2022-12-15T23:29:34.567063
2022-04-11T16:20:58
2022-04-11T16:20:58
157,998,306
0
0
null
2022-12-04T17:04:01
2018-11-17T15:35:04
JavaScript
UTF-8
Java
false
false
1,219
java
/** * Project Name:trainingCenter * File Name:PositionService.java * Package Name:com.center.service.hrmgt * Date:2018年6月26日下午3:14:06 * Copyright (c) 2016, Tony All Rights Reserved. * */ package com.center.service.hrmgt; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.center.po.hrmgt.Position; import com.center.po.hrmgt.PositionQuery; import com.center.po.query.DatatablesView; /** * ClassName:PositionService <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 2018年6月26日 下午3:14:06 <br/> * * @author 李逢杰 * @version * @see */ public interface PositionService { public List<Position> queryPosition(PositionQuery positionQuery) throws Exception; // 查看全部或个人 public DatatablesView<Position> queryPositionList(PositionQuery positionQuery) throws Exception; // 添加职位信息 public boolean addPosition(HttpServletRequest request, Position position) throws Exception; // 删除职位信息 public boolean deletePosition(int positionId) throws Exception; // 修改职位信息 public boolean updatePosition(Position position)throws Exception; }
514f7fdb2a76b843b93a10ccd4a5b147fee7576b
cf2105c21a4631587893523e4ece4c78d716f178
/skynda_backend/src/java/me/skynda/common/helper/SkyndaUtility.java
d6354f0916ac85380669676e7c1967631b5af58e
[]
no_license
Ecif/Skynda
8a4d965f8f4bbab7a367cd57824d4af8ff56e32c
1f726725ce6fc342aee35362221158010ace1862
refs/heads/master
2022-04-19T13:08:22.656783
2020-04-19T18:12:43
2020-04-19T18:12:43
78,101,266
2
0
null
null
null
null
UTF-8
Java
false
false
1,066
java
package me.skynda.common.helper; import org.apache.commons.codec.binary.Base64; import java.util.Optional; import java.util.function.Supplier; public class SkyndaUtility { /** * Instead of using if param != null && param.nested != null && param.nested.foo != null * you can propagate nulls using resolve(() -> obj.getParam1().getInner().getFoo()); * * @param resolver - агтсешщт * @param <T> - returned type * @return Last method's result in chain or null if some method returns null. */ public static <T> Optional<T> resolve(Supplier<T> resolver) { try { T result = resolver.get(); return Optional.ofNullable(result); } catch (NullPointerException e) { return null; } } public static byte[] toBytearray(String base64File) { // Cut out the part describing the type of the file String second = base64File.split(",")[1]; // Convert base64 to bytes return Base64.decodeBase64(second.getBytes()); } }
6f32297d7e2984fc1726906662733f80b42eb30b
201de1906e9498baa6df7423296c43ce1c04d6b6
/.history/src/main/java/com/example/ManagerProject/Controller/RestProjectFileMpp_20190902112228.java
7326a1149a4754eb8d210ab7259eac4e58645dc3
[]
no_license
Isamae/Project-Estratego
822e9782e94444df8beb2afc736e808ce52fe58f
0429245ff8cc2c5cc4d442cc1d09516ea67ac779
refs/heads/master
2022-12-12T00:34:23.736293
2020-03-27T19:23:22
2020-03-27T19:23:22
200,688,183
0
0
null
2022-11-28T22:21:50
2019-08-05T16:06:52
Java
UTF-8
Java
false
false
60,274
java
package com.example.ManagerProject.Controller; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; //import org.apache.poi.sl.usermodel.TextRun.FieldType; import org.springframework.boot.configurationprocessor.json.JSONArray; import org.springframework.boot.configurationprocessor.json.JSONException; import org.springframework.boot.configurationprocessor.json.JSONObject; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import net.sf.mpxj.*; import net.sf.mpxj.Resource; import net.sf.mpxj.reader.*; import net.sf.mpxj.writer.*; import net.sf.mpxj.mpp.*; import net.sf.mpxj.mspdi.MSPDIWriter; import net.sf.mpxj.mspdi.SaveVersion; //import net.sf.mpxj.writer.*; import net.sf.mpxj.Task; import net.sf.mpxj.common.FieldTypeHelper; import net.sf.mpxj.mspdi.MSPDIWriter; import net.sf.mpxj.reader.UniversalProjectReader; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; /** * RestProject */ @RestController @RequestMapping(value = "/project") public class RestProjectFileMpp { String BASECALENDAR = ""; @GetMapping(value = "/datoJson") public String postJson(@RequestBody String payload) throws Exception{ File file = ResourceUtils.getFile("classpath:"+"Proyecto1.xml"); UniversalProjectReader reader = new UniversalProjectReader(); ProjectFile projectObj = reader.read(file); JSONObject jsonObject = null; try { jsonObject= new JSONObject(payload); } catch (Exception e) { System.out.println("Error al convertir Json: "); e.printStackTrace(); } projectObj = setPropiedades(projectObj, jsonObject); projectObj = addCamposPersonalizados(projectObj,jsonObject); projectObj = addDuracionProyecto(projectObj,jsonObject); projectObj = addRecursos(projectObj,jsonObject); projectObj = addTarea(projectObj,jsonObject); //projectObj = addCalendario(projectObj,jsonObject); //projectObj = addCalendarioTarea(projectObj,jsonObject); projectObj = addCalendario(projectObj,jsonObject); projectObj = addPredecesoras(projectObj,jsonObject); projectObj = addSucesores(projectObj,jsonObject); projectObj = addFechasTareas(projectObj,jsonObject); projectObj = addCalendarioTarea(projectObj,jsonObject); projectObj = addValoresCamposPersonalizados(projectObj,jsonObject); projectObj = addAsignacionesRecursos(projectObj,jsonObject); //projectObj = addDuracionTareas(projectObj,jsonObject); /*ProjectWriter writer = ProjectWriterUtility.getProjectWriter("HOLA.mpx"); writer.write(projectObj,"HOLA.mpx");*/ String nombFile = "archivo"; if (!jsonObject.getString("projectName").equalsIgnoreCase("null")){ nombFile = jsonObject.getString("projectName"); }else if (jsonObject.getString("projectName").equalsIgnoreCase("null") && !jsonObject.getString("projectTittle").equalsIgnoreCase("null")){ nombFile = jsonObject.getString("projectTittle"); } nombFile = nombFile + ".xml"; System.out.println(nombFile); MSPDIWriter writer = new MSPDIWriter(); writer.write(projectObj, nombFile); return "Hola Mundo"; } public ProjectFile setPropiedades (ProjectFile project, JSONObject json) throws JSONException, ParseException { Date startDate = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy").parse(json.getString("PStartDate")); project.getProjectProperties().setStartDate(startDate); Date finishDate = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy").parse(json.getString("PFinishDate")); project.getProjectProperties().setFinishDate(finishDate); if (json.getString("projectName").equalsIgnoreCase("null") && !json.getString("projectTittle").equalsIgnoreCase("null")){ project.getProjectProperties().setName(json.getString("projectTittle")); project.getProjectProperties().setProjectTitle(json.getString("projectTittle")); } project.getProjectProperties().setCompany(json.getString("projectCompany")); project.getProjectProperties().setAuthor(json.getString("projectAuthor")); return project; } public static ProjectFile addCamposPersonalizados(ProjectFile project,JSONObject jsonObject) throws JSONException{ for(int i=0 ;i< ((JSONArray)(jsonObject.get("CamposPersonalizados"))).length();i++){ try { JSONObject object = ((JSONArray)(jsonObject.get("CamposPersonalizados"))).getJSONObject(i); if(object.getString("AliasCampo").compareToIgnoreCase("null")==0 || object.getInt("FieldTypeID")==-1){ } else{ FieldType fieldType = FieldTypeHelper.getInstance14(object.getInt("FieldTypeID")); //CustomFieldContainer fields = project.getCustomFields(); if(fieldType.getName() == null){} else{ //fields.getCustomField(fieldType); project.getCustomFields().getCustomField(fieldType).setAlias(object.getString("AliasCampo")); } } } catch (JSONException e) { e.printStackTrace(); } } return project; } public static ProjectFile addColumnas(ProjectFile project,JSONObject jsonObject) throws Exception{ JSONArray json = jsonObject.getJSONArray("ColumnasTabla1"); if(project.getTables().size() !=0){ List<Column> iter = project.getTables().get(0).getColumns(); for(int i = iter.size()-1; i>0 ; i--){ project.getTables().get(0).getColumns().remove(i); } } else{ Table table = new Table(); table.setName("Tareas"); table.setID(1); project.getTables().add(table); } for(int i = 0; i < json.length(); i ++ ){ Column column = new Column(project); FieldType fieldType = FieldTypeHelper.getInstance14(json.getJSONObject(i).getInt("FieldTypeID")); column.setFieldType(fieldType); column.setTitle(json.getJSONObject(i).getString("ColumTitulo")); project.getTables().get(0).getColumns().add(column); } return project; } public static ProjectFile addDuracionTareas(ProjectFile project,JSONObject jsonObject) throws JSONException{ for(int i=0 ;i< ((JSONArray)(jsonObject.get("tareas"))).length();i++){ try { JSONObject json = ((JSONArray)(jsonObject.get("tareas"))).getJSONObject(i); String duracion = json.getString("duracion"); Duration duracionD = null; if(duracion.contains("h")){ duracionD = Duration.getInstance(Double.parseDouble(duracion.replace("h", "")), TimeUnit.HOURS); } else if(duracion.contains("m")){ duracionD = Duration.getInstance(Double.parseDouble(duracion.replace("m", "")), TimeUnit.MINUTES); } else if(duracion.contains("d")){ duracionD = Duration.getInstance(Double.parseDouble(duracion.replace("d", "")), TimeUnit.DAYS); } else if(duracion.contains("w")){ duracionD = Duration.getInstance(Double.parseDouble(duracion.replace("w", "")), TimeUnit.WEEKS); } else if(duracion.contains("M")){ duracionD = Duration.getInstance(Double.parseDouble(duracion.replace("M", "")), TimeUnit.MONTHS); } else if(duracion.contains("y")){ duracionD = Duration.getInstance(Double.parseDouble(duracion.replace("y", "")), TimeUnit.YEARS); } else{ duracionD = Duration.getInstance(Double.parseDouble(duracion.replace("p", "")), TimeUnit.PERCENT); } String Actualduracion = json.getString("ActualDuration"); Duration duracionA; if(Actualduracion.contains("h")){ duracionA = Duration.getInstance(Double.parseDouble(Actualduracion.replace("h", "")), TimeUnit.HOURS); } else if(Actualduracion.contains("m")){ duracionA = Duration.getInstance(Double.parseDouble(Actualduracion.replace("m", "")), TimeUnit.MINUTES); } else if(Actualduracion.contains("d")){ duracionA = Duration.getInstance(Double.parseDouble(Actualduracion.replace("d", "")), TimeUnit.DAYS); } else if(Actualduracion.contains("w")){ duracionA = Duration.getInstance(Double.parseDouble(Actualduracion.replace("w", "")), TimeUnit.WEEKS); } else if(Actualduracion.contains("M")){ duracionA = Duration.getInstance(Double.parseDouble(Actualduracion.replace("M", "")), TimeUnit.MONTHS); } else if(Actualduracion.contains("y")){ duracionA = Duration.getInstance(Double.parseDouble(Actualduracion.replace("y", "")), TimeUnit.YEARS); } else{ duracionA = Duration.getInstance(Double.parseDouble(Actualduracion.replace("p", "")), TimeUnit.PERCENT); } String ActualTrabajo = json.getString("ActualDuration"); Duration actualT; if(ActualTrabajo.contains("h")){ actualT = Duration.getInstance(Double.parseDouble(ActualTrabajo.replace("h", "")), TimeUnit.HOURS); } else if(ActualTrabajo.contains("m")){ actualT = Duration.getInstance(Double.parseDouble(ActualTrabajo.replace("m", "")), TimeUnit.MINUTES); } else if(ActualTrabajo.contains("d")){ actualT = Duration.getInstance(Double.parseDouble(ActualTrabajo.replace("d", "")), TimeUnit.DAYS); } else if(ActualTrabajo.contains("w")){ actualT = Duration.getInstance(Double.parseDouble(ActualTrabajo.replace("w", "")), TimeUnit.WEEKS); } else if(ActualTrabajo.contains("M")){ actualT = Duration.getInstance(Double.parseDouble(ActualTrabajo.replace("M", "")), TimeUnit.MONTHS); } else if(ActualTrabajo.contains("y")){ actualT = Duration.getInstance(Double.parseDouble(ActualTrabajo.replace("y", "")), TimeUnit.YEARS); } else{ actualT = Duration.getInstance(Double.parseDouble(ActualTrabajo.replace("p", "")), TimeUnit.PERCENT); } //System.out.println("ID :" +json.getInt("id") +"-> " + duracionD); project.getTaskByID(json.getInt("id")).setDuration(duracionD); project.getTaskByID(json.getInt("id")).setActualDuration(duracionA); //project.getTaskByID(json.getInt("id")).setActualWork(actualT); //project.getTaskByID(json.getInt("id")).setDurationText(duracion); } catch (JSONException e) { e.printStackTrace(); } } return project; } public static ProjectFile addFechasTareas(ProjectFile project,JSONObject jsonObject) throws JSONException{ SimpleDateFormat df = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy"); for(int i=0;i< ((JSONArray)(jsonObject.get("tareas"))).length();i++){ try { JSONObject json = ((JSONArray)(jsonObject.get("tareas"))).getJSONObject(i); /*if(json.getJSONArray("hijos").length() == 0){*/ Task task = project.getTaskByID(json.getInt("id")); task.getStart(); task.getFinish(); task.getStartText(); task.getFinishText(); task.getActualStart(); task.getActualFinish(); if(json.getString("AfechaInicio").compareToIgnoreCase("null")!=0 ){ task.setActualStart(df.parse(json.getString("AfechaInicio"))); } if(json.getString("fechaInicio").compareToIgnoreCase("null")!=0){ task.setStart(df.parse(json.getString("fechaInicio"))); } if(json.getString("TfechaInicio").compareToIgnoreCase("null")!=0){ task.setStartText(json.getString("TfechaInicio")); } if(json.getString("AfechaFin").compareToIgnoreCase("null")!=0){ task.setActualFinish(df.parse(json.getString("AfechaFin"))); } if(json.getString("fechaFin").compareToIgnoreCase("null")!=0){ task.setFinish(df.parse(json.getString("fechaFin"))); } if(json.getString("TfechaFin").compareToIgnoreCase("null")!=0){ task.setFinishText(json.getString("TfechaFin")); } /*} else{ project.getTaskByID(json.getInt("id")).getStart(); project.getTaskByID(json.getInt("id")).getFinish(); if(json.getString("AfechaInicio") != "null"){ project.getTaskByID(json.getInt("id")).setActualStart(df.parse(json.getString("fechaInicio"))); } }*/ } catch (JSONException e) { e.printStackTrace(); } catch (ParseException e){ e.printStackTrace(); } } project.updateStructure(); return project; } public static ProjectFile addValoresCamposPersonalizados(ProjectFile project,JSONObject jsonObject) throws JSONException, ParseException { for(int i=0 ;i< ((JSONArray)(jsonObject.get("tareas"))).length();i++){ try { JSONObject json = ((JSONArray)(jsonObject.get("tareas"))).getJSONObject(i); JSONArray columnas = json.getJSONArray("Columnas"); for(int x = 0; x < columnas.length(); x++){ JSONObject datoObject = columnas.getJSONObject(x); if(datoObject.getInt("FieldTypeID") == -1){} else{ Task tarea = project.getTaskByID(json.getInt("id")); String tipodato = datoObject.getString("FieldTypeDataTypeString"); Object seteadoValue = null; if(datoObject.getString("ValorCampo").compareToIgnoreCase("null") ==0){ seteadoValue = null; } else{ if(tipodato.compareToIgnoreCase("STRING")==0 || tipodato.compareToIgnoreCase("ASCII_STRING")==0){ seteadoValue = datoObject.getString("ValorCampo"); } else if(tipodato.compareToIgnoreCase("PERCENTAGE")==0 || tipodato.compareToIgnoreCase("SHORT")==0 || tipodato.compareToIgnoreCase("SHORT")==0 || tipodato.compareToIgnoreCase("NUMERIC")==0 || tipodato.compareToIgnoreCase("CURRENCY")==0 ){ seteadoValue = Double.parseDouble(datoObject.getString("ValorCampo")) ; } else if(tipodato.compareToIgnoreCase("DURATION")==0 || tipodato.compareToIgnoreCase("WORK")==0){ Duration duracionD = null; if(datoObject.getString("ValorCampo").contains("h")){ duracionD = Duration.getInstance(Double.parseDouble(datoObject.getString("ValorCampo").replace("h", "")), TimeUnit.HOURS); } else if(datoObject.getString("ValorCampo").contains("m")){ duracionD = Duration.getInstance(Double.parseDouble(datoObject.getString("ValorCampo").replace("m", "")), TimeUnit.MINUTES); } else if(datoObject.getString("ValorCampo").contains("d")){ duracionD = Duration.getInstance(Double.parseDouble(datoObject.getString("ValorCampo").replace("d", "")), TimeUnit.DAYS); } else if(datoObject.getString("ValorCampo").contains("w")){ duracionD = Duration.getInstance(Double.parseDouble(datoObject.getString("ValorCampo").replace("w", "")), TimeUnit.WEEKS); } else if(datoObject.getString("ValorCampo").contains("M")){ duracionD = Duration.getInstance(Double.parseDouble(datoObject.getString("ValorCampo").replace("M", "")), TimeUnit.MONTHS); } else if(datoObject.getString("ValorCampo").contains("y")){ duracionD = Duration.getInstance(Double.parseDouble(datoObject.getString("ValorCampo").replace("y", "")), TimeUnit.YEARS); } else{ duracionD = Duration.getInstance(Double.parseDouble(datoObject.getString("ValorCampo").replace("p", "")), TimeUnit.PERCENT); } seteadoValue = duracionD; } else if(tipodato.compareToIgnoreCase("CONSTRAINT")==0){ seteadoValue = DataType.CONSTRAINT.valueOf(datoObject.getString("ValorCampo")); } else if(tipodato.compareToIgnoreCase("BOOLEAN")==0){ seteadoValue = Boolean.parseBoolean(datoObject.getString("ValorCampo")); } else if(tipodato.compareToIgnoreCase("TASK_TYPE")==0 || tipodato.compareToIgnoreCase("RELATION_LIST")==0){ } else if(tipodato.compareToIgnoreCase("DATE")==0){ SimpleDateFormat df = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy"); seteadoValue = df.parse(json.getString("ValorCampo")); } else if(tipodato.compareToIgnoreCase("EARNED_VALUE_METHOD")==0){ seteadoValue = DataType.EARNED_VALUE_METHOD.valueOf(json.getString("ValorCampo")); } else if(tipodato.compareToIgnoreCase("INTEGER")==0){ seteadoValue = Integer.parseInt(json.getString("ValorCampo")); } else if(tipodato.compareToIgnoreCase("GUID")==0){ seteadoValue = DataType.GUID.valueOf(json.getString("ValorCampo")); } else if(tipodato.compareToIgnoreCase("ACCRUE")==0){ seteadoValue = DataType.ACCRUE.valueOf(json.getString("ValorCampo")); } else{ seteadoValue = null; } } FieldType fieldType = FieldTypeHelper.getInstance14(datoObject.getInt("FieldTypeID")); tarea.getCurrentValue(fieldType); tarea.set(fieldType,seteadoValue); } } } catch (JSONException e) { e.printStackTrace(); } catch (ClassCastException e) { e.printStackTrace(); } } project.updateStructure(); return project; } public static ProjectFile addTarea(ProjectFile project,JSONObject jsonObject) throws JSONException, ParseException { SimpleDateFormat df = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy"); project.getTasks().get(0).setName(((JSONArray)(jsonObject.get("tareas"))).getJSONObject(0).getString("name")); project.getTasks().get(0).setUniqueID(((JSONArray)(jsonObject.get("tareas"))).getJSONObject(0).getInt("uniqueID")); project.getTasks().get(0).setActive(((JSONArray)(jsonObject.get("tareas"))).getJSONObject(0).getBoolean("estado")); project.getTasks().get(0).setOutlineNumber(((JSONArray)(jsonObject.get("tareas"))).getJSONObject(0).getString("OutlineNumber")); project.getTasks().get(0).setOutlineLevel(((JSONArray)(jsonObject.get("tareas"))).getJSONObject(0).getInt("OutlineLevel")); for(int i=1 ;i< ((JSONArray)(jsonObject.get("tareas"))).length();i++){ try { JSONObject json = ((JSONArray)(jsonObject.get("tareas"))).getJSONObject(i); if( project.getTaskByID(json.getInt("id")) == null){ (project.addTask()).setID(json.getInt("id")); (project.addTask()).disableEvents(); (project.getTaskByID(json.getInt("id"))).setName(json.getString("name")); (project.getTaskByID(json.getInt("id"))).setUniqueID(json.getInt("uniqueID")); (project.getTaskByID(json.getInt("id"))).setActive(json.getBoolean("estado")); (project.getTaskByID(json.getInt("id"))).setOutlineNumber(json.getString("OutlineNumber")); (project.getTaskByID(json.getInt("id"))).setOutlineLevel(json.getInt("OutlineLevel")); TaskType taskType; if(json.getString("Type").equalsIgnoreCase("FIXED_DURATION")){ taskType = TaskType.FIXED_DURATION; } else if(json.getString("Type").equalsIgnoreCase("FIXED_UNITS")){ taskType = TaskType.FIXED_UNITS; } else{ taskType = TaskType.FIXED_WORK; } (project.getTaskByID(json.getInt("id"))).setType(taskType); JSONArray hijos = json.getJSONArray("hijos"); for(int j=0; j <hijos.length() ; j++){ JSONObject hijo = hijos.getJSONObject(j); Task taskhijo = project.addTask(); taskhijo.setID(hijo.getInt("id")); taskhijo.setName(hijo.getString("name")); taskhijo.setUniqueID(hijo.getInt("idUnique")); taskhijo.setOutlineNumber(hijo.getString("OutlineNumber")); taskhijo.setOutlineLevel(hijo.getInt("OutlineLevel")); TaskType taskTypeH; if(hijo.getString("Type").equalsIgnoreCase("FIXED_DURATION")){ taskTypeH = TaskType.FIXED_DURATION; } else if(hijo.getString("Type").equalsIgnoreCase("FIXED_UNITS")){ taskTypeH = TaskType.FIXED_UNITS; } else{ taskTypeH = TaskType.FIXED_WORK; } taskhijo.setType(taskTypeH); if(json.getInt("id") == 0){ } else{ taskhijo.generateOutlineNumber(project.getTaskByID(json.getInt("id"))); } project.getTaskByID(json.getInt("id")).addChildTask(taskhijo); } } else{ JSONArray hijos = json.getJSONArray("hijos"); for(int j=0; j <hijos.length() ; j++){ JSONObject hijo = hijos.getJSONObject(j); Task taskhijo = project.addTask(); taskhijo.setID(hijo.getInt("id")); taskhijo.setName(hijo.getString("name")); taskhijo.setUniqueID(hijo.getInt("idUnique")); taskhijo.setOutlineNumber(hijo.getString("OutlineNumber")); taskhijo.setOutlineLevel(hijo.getInt("OutlineLevel")); TaskType taskTypeH; if(hijo.getString("Type").equalsIgnoreCase("FIXED_DURATION")){ taskTypeH = TaskType.FIXED_DURATION; } else if(hijo.getString("Type").equalsIgnoreCase("FIXED_UNITS")){ taskTypeH = TaskType.FIXED_UNITS; } else{ taskTypeH = TaskType.FIXED_WORK; } taskhijo.setType(taskTypeH); if(json.getInt("id") == 0){ } else{ taskhijo.generateOutlineNumber(project.getTaskByID(json.getInt("id"))); } project.getTaskByID(json.getInt("id")).addChildTask(taskhijo); } } project.getTaskByID(json.getInt("id")).setEstimated(json.getBoolean("estimada")); project.getTaskByID(json.getInt("id")).setActive(json.getBoolean("estado")); project.getTaskByID(json.getInt("id")).setPercentageComplete(json.getDouble("porcentajeCompletado")); project.getTaskByID(json.getInt("id")).setNotes(json.getString("notas")); project.getTaskByID(json.getInt("id")).setHideBar(json.getBoolean("ocultarBarra")); project.getTaskByID(json.getInt("id")).setMilestone(json.getBoolean("hito")); project.getTaskByID(json.getInt("id")).setPriority(Priority.getInstance(json.getInt("priority"))); project.getTaskByID(json.getInt("id")).set(FieldTypeHelper.getInstance(188743812), json.getBoolean("condicionadaEsfuerzo")); project.getTaskByID(json.getInt("id")).set(FieldTypeHelper.getInstance(188743762), json.getBoolean("resumida")); if(json.getString("modoProgramacion").compareToIgnoreCase("AUTO_SCHEDULED")==0){ project.getTaskByID(json.getInt("id")).setTaskMode(TaskMode.AUTO_SCHEDULED); } else{ project.getTaskByID(json.getInt("id")).setTaskMode(TaskMode.MANUALLY_SCHEDULED); } if(json.getString("tipoRestricion").compareToIgnoreCase("AS_SOON_AS_POSSIBLE")==0){ project.getTaskByID(json.getInt("id")).setConstraintType(ConstraintType.AS_SOON_AS_POSSIBLE); } else if(json.getString("tipoRestricion").compareToIgnoreCase("AS_LATE_AS_POSSIBLE")==0){ project.getTaskByID(json.getInt("id")).setConstraintType(ConstraintType.AS_LATE_AS_POSSIBLE); } else if(json.getString("tipoRestricion").compareToIgnoreCase("FINISH_NO_EARLIER_THAN")==0){ project.getTaskByID(json.getInt("id")).setConstraintType(ConstraintType.FINISH_NO_EARLIER_THAN); } else if(json.getString("tipoRestricion").compareToIgnoreCase("FINISH_NO_LATER_THAN")==0){ project.getTaskByID(json.getInt("id")).setConstraintType(ConstraintType.FINISH_NO_LATER_THAN); } else if(json.getString("tipoRestricion").compareToIgnoreCase("MANDATORY_FINISH")==0){ project.getTaskByID(json.getInt("id")).setConstraintType(ConstraintType.MANDATORY_FINISH); } else if(json.getString("tipoRestricion").compareToIgnoreCase("MANDATORY_FINISH")==0){ project.getTaskByID(json.getInt("id")).setConstraintType(ConstraintType.MANDATORY_START); } else if(json.getString("tipoRestricion").compareToIgnoreCase("MUST_FINISH_ON")==0){ project.getTaskByID(json.getInt("id")).setConstraintType(ConstraintType.MUST_FINISH_ON); } else{ } project.getTaskByID(json.getInt("id")).set(FieldTypeHelper.getInstance(188744802), DataType.EARNED_VALUE_METHOD.valueOf(json.getString("metodoValorAcumulado"))); if(json.getString("propetarioAsignacion").compareToIgnoreCase("null")==0){ } else{ project.getTaskByID(json.getInt("id")).set(FieldTypeHelper.getInstance(188744850), json.getString("propetarioAsignacion")); } if(json.getString("fechaRestriccion").compareToIgnoreCase("null")==0){ } else{ project.getTaskByID(json.getInt("id")).set(FieldTypeHelper.getInstance(188743698), df.parse(json.getString("fechaRestriccion"))); } if(json.getString("fechaLimite").compareToIgnoreCase("null")==0){ } else{ project.getTaskByID(json.getInt("id")).set(FieldTypeHelper.getInstance(188744117), df.parse(json.getString("fechaLimite"))); } } catch (JSONException e) { e.printStackTrace(); } catch (ClassCastException e) { e.printStackTrace(); } } project.updateStructure(); return project; } public static ProjectFile addCalendarioTarea(ProjectFile project,JSONObject jsonObject) throws JSONException, ParseException { for(int i=0 ;i< ((JSONArray)(jsonObject.get("tareas"))).length();i++){ try { JSONObject json = ((JSONArray)(jsonObject.get("tareas"))).getJSONObject(i); if(json.getInt("CalendarioUniqueID") ==-1){} else{ project.getTaskByID(json.getInt("id")).setCalendarUniqueID(json.getInt("CalendarioUniqueID")); } } catch (JSONException e) { e.printStackTrace(); } catch (ClassCastException e) { e.printStackTrace(); } } project.updateStructure(); return project; } public static ProjectFile addAsignacionesRecursos(ProjectFile project,JSONObject jsonObject) throws JSONException, ParseException { SimpleDateFormat df = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy"); for(int i=0 ;i< ((JSONArray)(jsonObject.get("asigRecursos"))).length();i++){ try { JSONObject json = ((JSONArray)(jsonObject.get("asigRecursos"))).getJSONObject(i); Task task = project.getTaskByID(json.getInt("idTask")); Resource resource = project.getResourceByID(json.getInt("idResource")); ResourceAssignment assignment = task.addResourceAssignment(resource); assignment.setCost(json.getDouble("Cost")); assignment.getActualStart(); assignment.getActualFinish(); assignment.getStart(); assignment.getFinish(); if(json.getString("ActualStart").compareToIgnoreCase("null")==0){} else{ assignment.setActualStart(df.parse(json.getString("ActualStart"))); } if(json.getString("ActualFinish").compareToIgnoreCase("null")==0){} else{ assignment.setActualFinish(df.parse(json.getString("ActualFinish"))); } if(json.getString("Start").compareToIgnoreCase("null")==0){} else{ assignment.setStart(df.parse(json.getString("Start"))); } if(json.getString("Finish").compareToIgnoreCase("null")==0){} else{ assignment.setFinish(df.parse(json.getString("Finish"))); } assignment.setUnits(json.getDouble("Units")); assignment.setUniqueID(json.getInt("UniqueID")); /*if(json.getString("ActualWork").contains("d")){ assignment.setActualWork(Duration.getInstance(Double.parseDouble(json.getString("ActualWork").replace("d", "")),TimeUnit.DAYS)); if(json.getString("Delay").compareToIgnoreCase("null")!=0){ assignment.setDelay(Duration.getInstance(Double.parseDouble(json.getString("Delay").replace("d", "")),TimeUnit.DAYS)); } } else if(json.getString("ActualWork").contains("h")){ assignment.setActualWork(Duration.getInstance(Double.parseDouble(json.getString("ActualWork").replace("h", "")),TimeUnit.HOURS)); if(json.getString("Delay").compareToIgnoreCase("null")!=0){ assignment.setDelay(Duration.getInstance(Double.parseDouble(json.getString("Delay").replace("h", "")),TimeUnit.HOURS)); } } else if(json.getString("ActualWork").contains("y")){ assignment.setActualWork(Duration.getInstance(Double.parseDouble(json.getString("ActualWork").replace("y", "")),TimeUnit.YEARS)); if(json.getString("Delay").compareToIgnoreCase("null")!=0){ assignment.setDelay(Duration.getInstance(Double.parseDouble(json.getString("Delay").replace("y", "")),TimeUnit.YEARS)); } } else if(json.getString("ActualWork").contains("w")){ assignment.setActualWork(Duration.getInstance(Double.parseDouble(json.getString("ActualWork").replace("w", "")),TimeUnit.WEEKS)); if(json.getString("Delay").compareToIgnoreCase("null")!=0){ assignment.setDelay(Duration.getInstance(Double.parseDouble(json.getString("Delay").replace("w", "")),TimeUnit.WEEKS)); } } else if(json.getString("ActualWork").contains("m")){ assignment.setActualWork(Duration.getInstance(Double.parseDouble(json.getString("ActualWork").replace("m", "")),TimeUnit.MINUTES)); if(json.getString("Delay").compareToIgnoreCase("null")!=0){ assignment.setDelay(Duration.getInstance(Double.parseDouble(json.getString("Delay").replace("m", "")),TimeUnit.MINUTES)); } } else if(json.getString("ActualWork").contains("M")){ assignment.setActualWork(Duration.getInstance(Double.parseDouble(json.getString("ActualWork").replace("M", "")),TimeUnit.MONTHS)); if(json.getString("Delay").compareToIgnoreCase("null")!=0){ assignment.setDelay(Duration.getInstance(Double.parseDouble(json.getString("Delay").replace("M", "")),TimeUnit.MONTHS)); } } else{ assignment.setActualWork(Duration.getInstance(Double.parseDouble(json.getString("ActualWork").replace("p", "")),TimeUnit.PERCENT)); if(json.getString("Delay").compareToIgnoreCase("null")!=0){ assignment.setDelay(Duration.getInstance(Double.parseDouble(json.getString("Delay").replace("p", "")),TimeUnit.PERCENT)); } }*/ } catch (JSONException e) { e.printStackTrace(); } catch (ClassCastException e) { e.printStackTrace(); } } return project; } public static ProjectFile addPredecesoras(ProjectFile project,JSONObject jsonObject) throws JSONException, ParseException{ for(int i=0;i< ((JSONArray)(jsonObject.get("tareas"))).length();i++){ try { JSONObject json = ((JSONArray)(jsonObject.get("tareas"))).getJSONObject(i); JSONArray array = json.getJSONArray("predecesoras"); Task task = project.getTaskByID(json.getInt("id")); for(int x=0; x <array.length(); x++){ JSONObject predecesor = array.getJSONObject(x); String lag = predecesor.getString("lag"); String tipo = predecesor.getString("type"); String idH = predecesor.getString("taskId"); RelationType relationType; if(tipo.contains("FF")){ relationType = RelationType.FINISH_FINISH; } else if(tipo.contains("FS")){ relationType = RelationType.FINISH_START; } else if(tipo.contains("SS")){ relationType = RelationType.START_START; } else{ relationType = RelationType.START_FINISH; } if(lag.contains("d")){ task.addPredecessor( project.getTaskByID(Integer.parseInt(idH)), relationType, Duration.getInstance(Double.parseDouble(lag.replace("d", "")),TimeUnit.DAYS)); } else if(lag.contains("h")){ task.addPredecessor( project.getTaskByID(Integer.parseInt(idH)), relationType, Duration.getInstance(Double.parseDouble(lag.replace("h", "")),TimeUnit.HOURS)); } else if(lag.contains("y")){ task.addPredecessor( project.getTaskByID(Integer.parseInt(idH)), relationType, Duration.getInstance(Double.parseDouble(lag.replace("y", "")),TimeUnit.YEARS)); } else if(lag.contains("w")){ task.addPredecessor( project.getTaskByID(Integer.parseInt(idH)), relationType, Duration.getInstance(Double.parseDouble(lag.replace("w", "")),TimeUnit.WEEKS)); } else if(lag.contains("m")){ task.addPredecessor( project.getTaskByID(Integer.parseInt(idH)), relationType, Duration.getInstance(Double.parseDouble(lag.replace("m", "")),TimeUnit.MINUTES)); } else if(lag.contains("M")){ task.addPredecessor( project.getTaskByID(Integer.parseInt(idH)), relationType, Duration.getInstance(Double.parseDouble(lag.replace("M", "")),TimeUnit.MONTHS)); } else{ task.addPredecessor( project.getTaskByID(Integer.parseInt(idH)), relationType, Duration.getInstance(Double.parseDouble(lag.replace("p", "")),TimeUnit.PERCENT)); } } } catch (JSONException e) { e.printStackTrace(); } } project.updateStructure(); return project; } public static ProjectFile addSucesores(ProjectFile project,JSONObject jsonObject) throws JSONException, ParseException{ for(int i=0;i< ((JSONArray)(jsonObject.get("tareas"))).length();i++){ try { JSONObject json = ((JSONArray)(jsonObject.get("tareas"))).getJSONObject(i); JSONArray array = json.getJSONArray("Sucesores"); Task task = project.getTaskByID(json.getInt("id")); for(int x=0; x <array.length(); x++){ JSONObject sucesores = array.getJSONObject(x); String lag = sucesores.getString("lag"); String tipo = sucesores.getString("type"); String idH = sucesores.getString("taskId"); RelationType relationType; if(tipo.contains("FF")){ relationType = RelationType.FINISH_FINISH; } else if(tipo.contains("FS")){ relationType = RelationType.FINISH_START; } else if(tipo.contains("SS")){ relationType = RelationType.START_START; } else{ relationType = RelationType.START_FINISH; } if(json.getString("id").compareToIgnoreCase(idH) == 0) {} else{ if(lag.contains("d")){ Task targetTask = project.getTaskByID(Integer.parseInt(idH)); Relation arg0 = new Relation(task, targetTask, relationType, Duration.getInstance(Double.parseDouble(lag.replace("d", "")),TimeUnit.DAYS)); task.getSuccessors().add(arg0); } else if(lag.contains("h")){ Task targetTask = project.getTaskByID(Integer.parseInt(idH)); Relation arg0 = new Relation(task, targetTask, relationType, Duration.getInstance(Double.parseDouble(lag.replace("h", "")),TimeUnit.HOURS)); task.getSuccessors().add(arg0); } else if(lag.contains("y")){ Task targetTask = project.getTaskByID(Integer.parseInt(idH)); Relation arg0 = new Relation(task, targetTask, relationType, Duration.getInstance(Double.parseDouble(lag.replace("y", "")),TimeUnit.YEARS)); task.getSuccessors().add(arg0); } else if(lag.contains("w")){ Task targetTask = project.getTaskByID(Integer.parseInt(idH)); Relation arg0 = new Relation(task, targetTask, relationType, Duration.getInstance(Double.parseDouble(lag.replace("w", "")),TimeUnit.WEEKS)); task.getSuccessors().add(arg0); } else if(lag.contains("m")){ Task targetTask = project.getTaskByID(Integer.parseInt(idH)); Relation arg0 = new Relation(task, targetTask, relationType, Duration.getInstance(Double.parseDouble(lag.replace("m", "")),TimeUnit.MINUTES)); task.getSuccessors().add(arg0); } else if(lag.contains("M")){ Task targetTask = project.getTaskByID(Integer.parseInt(idH)); Relation arg0 = new Relation(task, targetTask, relationType, Duration.getInstance(Double.parseDouble(lag.replace("M", "")),TimeUnit.MONTHS)); task.getSuccessors().add(arg0); } else{ Task targetTask = project.getTaskByID(Integer.parseInt(idH)); Relation arg0 = new Relation(task, targetTask, relationType, Duration.getInstance(Double.parseDouble(lag.replace("p", "")),TimeUnit.PERCENT)); task.getSuccessors().add(arg0); } } } } catch (JSONException e) { e.printStackTrace(); } } project.updateStructure(); return project; } public static ProjectFile addDuracionProyecto(ProjectFile project,JSONObject jsonObject) throws JSONException, ParseException{ SimpleDateFormat df = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy"); project.getTaskByID(0).setStart(df.parse(jsonObject.getString("StartDate"))); //project.getProjectProperties().getDefaultStartTime().setHours(6); //project.getProjectProperties().getDefaultEndTime().setHours(19); if(jsonObject.getString("PStartDate").compareToIgnoreCase("null")==0){} else{ project.getProjectProperties().getStartDate(); project.getProjectProperties().getStartDate().setTime(df.parse(jsonObject.getString("StartDate")).getTime()); project.getProjectProperties().getStartDate().setSeconds(df.parse(jsonObject.getString("StartDate")).getSeconds()); project.getProjectProperties().getStartDate().setMinutes(df.parse(jsonObject.getString("StartDate")).getMinutes()); project.getProjectProperties().getStartDate().setHours(df.parse(jsonObject.getString("StartDate")).getHours()); project.getProjectProperties().getStartDate().setMonth(df.parse(jsonObject.getString("StartDate")).getMonth()); project.getProjectProperties().getStartDate().setYear(df.parse(jsonObject.getString("StartDate")).getYear()); } if(jsonObject.getString("PFinishDate").compareToIgnoreCase("null")==0){} else{ project.getProjectProperties().getFinishDate(); project.getProjectProperties().getFinishDate().setTime(df.parse(jsonObject.getString("FinishDate")).getTime()); project.getProjectProperties().getFinishDate().setSeconds(df.parse(jsonObject.getString("FinishDate")).getSeconds()); project.getProjectProperties().getFinishDate().setMinutes(df.parse(jsonObject.getString("FinishDate")).getMinutes()); project.getProjectProperties().getFinishDate().setHours(df.parse(jsonObject.getString("FinishDate")).getHours()); project.getProjectProperties().getFinishDate().setMonth(df.parse(jsonObject.getString("FinishDate")).getMonth()); project.getProjectProperties().getFinishDate().setYear(df.parse(jsonObject.getString("FinishDate")).getYear()); } return project; } public static ProjectFile addRecursos(ProjectFile project,JSONObject jsonObject){ ResourceContainer rContainer = project.getResources(); for (int i=0; i<rContainer.size(); i++){ rContainer.remove(i); } try { JSONArray array = (JSONArray) jsonObject.get("recursos"); System.out.println(array.length()); for(int i=0; i< array.length();i++){ Resource resource = project.addResource(); resource.setName(((JSONObject)array.get(i)).getString("name")); resource.setID(((JSONObject)array.get(i)).getInt("id")); resource.setUniqueID(((JSONObject)array.get(i)).getInt("idUni")); resource.disableEvents(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return project; } public static ProjectFile addDataTablas(ProjectFile project,JSONObject jsonObject) throws Exception{ JSONArray jsonClaves = ((JSONArray)(jsonObject.get("allColum"))).getJSONObject(0).names(); Table table = project.getTables().get(0); try { for (int i = 0; i < ((JSONArray) (jsonObject.get("allColum"))).length(); i++) { JSONObject object = ((JSONArray) (jsonObject.get("allColum"))).getJSONObject(i); for(int j=0; j<jsonClaves.length(); j++){ // System.out.println("Clase: " + object.get((String)jsonClaves.get(j))); Column column = new Column(project); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return project; } public static int containsPalabra(JSONArray findArray, String palabra) { int result = -1; for(int i=0; i< findArray.length(); i++){ try { if (((String) findArray.get(i)).equals(palabra)) { result = i; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } public ProjectFile addCalendario(ProjectFile project,JSONObject jsonObject) throws Exception{ JSONArray calendariosJson = jsonObject.getJSONArray("calendarios"); // set default calendar project = setDefaultCalendario (project, jsonObject); // add calendars project = addCalendarios(project, calendariosJson); for (int i=0; i<project.getCalendars().size(); i++){ System.out.println(project.getCalendars().get(i).getName()); } // link calendars to resources project = linkCalendarioRecurso (project, calendariosJson); // set base calendars project = setCalendariosBase (project, calendariosJson); // set calendarios project = setCalendarios (project, calendariosJson); project.updateStructure(); return project; } public ProjectFile setDefaultCalendario (ProjectFile project, JSONObject json) throws Exception { JSONObject calendarioJson = json.getJSONArray("defaultCalendario").getJSONObject(0); ProjectCalendar defaultCalendario = project.getDefaultCalendar(); defaultCalendario.setName(calendarioJson.getString("nombre")); defaultCalendario.setUniqueID(calendarioJson.getInt("calenderID")); setCalendario(defaultCalendario, calendarioJson, null); project.setDefaultCalendar(defaultCalendario); System.out.println("Default calendar: " + project.getDefaultCalendar().getName() + ", UniqueID " + project.getDefaultCalendar().getUniqueID()); return project; } public ProjectFile addCalendarios(ProjectFile project, JSONArray calendariosJson) throws JSONException { ProjectCalendar defaultCalendario = project.getDefaultCalendar(); for(int i=0; i< calendariosJson.length(); i++){ JSONObject json = calendariosJson.getJSONObject(i); if (!json.getString("nombre").equalsIgnoreCase(defaultCalendario.getName())){ System.out.println("\n\t add new calendar"); ProjectCalendar calendar = project.addCalendar(); calendar.setName(json.getString("nombre")); calendar.setUniqueID(json.getInt("calenderID")); System.out.println("setName " + calendar.getName() + ", setUniqueID " + calendar.getUniqueID()); } } return project; } public ProjectFile linkCalendarioRecurso (ProjectFile project, JSONArray calendariosJson) throws JSONException { String id = ""; JSONObject json = null; ProjectCalendar calendar = null; for (int i=0; i<calendariosJson.length(); i++){ json = calendariosJson.getJSONObject(i); calendar = project.getCalendarByName(json.getString("nombre")); id = json.getString("recursoID"); if (calendar != null){ Resource resource = null; if (!id.equalsIgnoreCase("null") && !id.equalsIgnoreCase("")){ resource = project.getResourceByID(Integer.parseInt(id)); if (resource != null){ calendar.setResource(resource); resource.setResourceCalendar(calendar); System.out.println("set resource: " + calendar.getResource().getName()); System.out.println("set calendar: " + resource.getResourceCalendar().getName()); }else{ System.out.println("resource null"); } } } } return project; } public ProjectFile setCalendariosBase (ProjectFile project, JSONArray calendariosJson) throws JSONException { ProjectCalendar calendarParent = null; JSONObject json = null; ProjectCalendar calendar = null; for (int i=0; i<calendariosJson.length(); i++){ json = calendariosJson.getJSONObject(i); calendar = project.getCalendarByName(json.getString("nombre")); if (calendar != null){ calendarParent = project.getCalendarByName(json.getString("calenderBase")); calendar.setParent(calendarParent); if (calendar.getParent() != null){ System.out.println("calendar " + calendar.getName() + ", parent: " + calendar.getParent().getName()); }else{ System.out.println(calendar.getName() + " es un calendario base"); } } } ProjectCalendar calendar1 = project.getCalendarByName("Estándar"); ProjectCalendar calendar2 = project.getCalendarByName("Standard"); if (calendar1 != null && calendar2 != null){ int idCalendar; if (project.getDefaultCalendar().getName().equalsIgnoreCase(calendar1.getName())){ idCalendar = calendar2.getUniqueID(); System.out.println(calendar2.getName() + ", " + calendar2.getUniqueID()); calendar2 = calendar1; calendar2.setUniqueID(idCalendar); System.out.println(calendar2.getName() + ", " + calendar2.getUniqueID()); }else if (project.getDefaultCalendar().getName().equalsIgnoreCase(calendar2.getName())){ idCalendar = calendar1.getUniqueID(); System.out.println(calendar1.getName() + ", " + calendar1.getUniqueID()); calendar1 = calendar2; calendar1.setUniqueID(idCalendar); System.out.println(calendar1.getName() + ", " + calendar1.getUniqueID()); } } return project; } public ProjectFile setCalendarios (ProjectFile project, JSONArray calendariosJson) throws Exception { JSONObject jsonParent = null; JSONObject json = null; ProjectCalendar calendar = null; for (int i=0; i<calendariosJson.length(); i++){ json = calendariosJson.getJSONObject(i); calendar = project.getCalendarByName(json.getString("nombre")); if (json.getString("nombre").equalsIgnoreCase(json.getString("calenderBase"))){ calendar = setCalendario(calendar, json, jsonParent); }else{ jsonParent = getDefaultCalendario(calendariosJson, calendar.getParent().getName()); calendar = setCalendario(calendar, json, jsonParent); } } return project; } public JSONObject getDefaultCalendario (JSONArray calendarios, String calendarName) throws JSONException { JSONObject json = null; for (int i =0; i<calendarios.length(); i++){ json = calendarios.getJSONObject(i); if (json.getString("nombre").equalsIgnoreCase(calendarName)){ return json; } } return json; } public ProjectCalendar setCalendario(ProjectCalendar calendar,JSONObject json, JSONObject jsonParent) throws Exception{ try { // set working Days calendar = setDayType (json.getJSONArray("diaslab"), calendar, DayType.WORKING); // set non working Days calendar = setDayType (json.getJSONArray("diasnolab"), calendar, DayType.NON_WORKING); // set default Days calendar = setDayType (json.getJSONArray("calenderDefault"), calendar, DayType.DEFAULT); // setHours JSONArray horariosCalendario = json.getJSONArray("calenderHorario"); if (horariosCalendario.length() == 0){ horariosCalendario = jsonParent.getJSONArray("calenderHorario"); calendar = setHorario (horariosCalendario, calendar); }else{ calendar = setHorario (horariosCalendario, calendar); } // set exceptions JSONArray excepcionesCalendario = json.getJSONArray("calenderExcepciones"); calendar = setExcepciones (excepcionesCalendario, calendar); } catch (JSONException e) { e.printStackTrace(); } return calendar; } public ProjectCalendar setDayType (JSONArray dias, ProjectCalendar calendario, DayType dT) throws JSONException { for (int i=0; i<dias.length(); i++){ Day day = Day.valueOf(dias.get(i).toString()); calendario.setWorkingDay(day, dT); } return calendario; } public ProjectCalendar setHorario (JSONArray horarioCalendario, ProjectCalendar calendario) throws JSONException, ParseException { for (int i=0; i<horarioCalendario.length(); i++){ // get horario from horarioCalendario String horarioStr = horarioCalendario.getString(i); String[] horario = horarioStr.split("/"); Day day = Day.valueOf(horario[0]); DateRange dateRange = new DateRange(new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy").parse(horario[1]), new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy").parse(horario[2])); DateRange dateRange2 = new DateRange(new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy").parse(horario[3]), new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy").parse(horario[4])); ProjectCalendarHours hours = calendario.addCalendarHours(day); hours.addRange(dateRange); hours.addRange(dateRange2); } return calendario; } public ProjectCalendar setExcepciones (JSONArray excepcionesCalendario, ProjectCalendar calendario) throws JSONException, ParseException { for (int i=0; i<excepcionesCalendario.length(); i++){ String exStr = excepcionesCalendario.getString(i); String[] excepcion = exStr.split("/"); calendario.addCalendarException(new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy").parse(excepcion[1]), new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy").parse(excepcion[2])); ProjectCalendarException ex = calendario.getException(new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy").parse(excepcion[1])); if (!excepcion[0].equals("null")){ ex.setName(excepcion[0]); } } return calendario; } }
e3630bc7919711184dd5a236caf7dacf677c0637
d6a9f396a16f2c425de876b98f809ab9ccc34dad
/rabbitmq-concurrency-consumer/src/main/java/rabbitmq/concurrency/consumer/rabbitmqconcurrencyconsumer/RabbitmqConcurrencyConsumerApplication.java
3e0ebba4daf22d44dd34e8c34aae4baf62dc18a0
[]
no_license
marcodeba/rabbitmq-study-demo
11c0ca2163403b8e1dbc415bed616d2f930eec0d
cfe3b4e3e03905f081c8d57e0bfdfb68cbffffd7
refs/heads/master
2023-01-08T03:18:11.239207
2020-10-29T00:01:40
2020-10-29T00:01:40
307,910,100
0
0
null
null
null
null
UTF-8
Java
false
false
404
java
package rabbitmq.concurrency.consumer.rabbitmqconcurrencyconsumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RabbitmqConcurrencyConsumerApplication { public static void main(String[] args) { SpringApplication.run(RabbitmqConcurrencyConsumerApplication.class, args); } }
1002f3aeb981b37d29d7a3e4caa8f50fc0d2325f
6a4c6c3d3090e037e93251c1aa736b3c28716fcd
/src/main/java/com/theironyard/Services/UserRepository.java
682e7521d184fd4dac92005e68a381c0344bd5e9
[]
no_license
BrandenSandahl/CalendarSpring
0d2fca9a008f815c33fe9cf16b0c7ed088883cb3
ad708a1f7299d4dcdaf4f2482d619a0daffe6a12
refs/heads/master
2021-01-13T01:00:07.444627
2016-03-15T14:43:43
2016-03-15T14:43:43
53,861,589
0
0
null
null
null
null
UTF-8
Java
false
false
297
java
package com.theironyard.Services; import com.theironyard.Entities.User; import org.springframework.data.repository.CrudRepository; /** * Created by branden on 3/14/16 at 11:16. */ public interface UserRepository extends CrudRepository<User, Integer>{ User findFirstByName(String name); }
2f816b5c2af20aff821ec9325fe8d68e3642f155
c8548cedfa8106f63d38ee8cb4cc33509e22fc64
/src/main/java/cn/smbms/dao/user/UserDao.java
8438522d42c23bd6cad1bcec211ec40f58f639cd
[]
no_license
Cod4Man/SMBMS_SSM
28e209a94474d4b8d845fd352a6e911b8033f737
1e58599e92604dba71cc96d52259e6bc3ad53541
refs/heads/master
2020-05-02T23:54:12.431239
2019-04-10T03:52:58
2019-04-10T03:52:58
178,293,654
0
0
null
null
null
null
UTF-8
Java
false
false
1,587
java
package cn.smbms.dao.user; import java.sql.Connection; import java.util.List; import cn.smbms.pojo.User; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; public interface UserDao { /** * 增加用户信息 * @param connection * @param user * @return * @ */ public int add(User user); /** * 通过userCode获取User * @param connection * @param userCode * @return * @ */ public User getLoginUser(@Param("userCode") String userCode); /** * 通过条件查询-userList * @param connection * @param userName * @param userRole * @return * @ */ public List<User> getUserList( @Param("userName") String userName, @Param("userRole") int userRole, RowBounds rowBounds); /** * 通过条件查询-用户表记录数 * @param connection * @param userName * @param userRole * @return * @ */ public int getUserCount(@Param("userName") String userName, @Param("userRole") int userRole); /** * 通过userId删除user * @param delId * @return * @ */ public int deleteUserById(@Param("delId") Integer delId); /** * 通过userId获取user * @param connection * @param id * @return * @ */ public User getUserById(@Param("id") String id); /** * 修改用户信息 * @param connection * @param user * @return * @ */ public int modify(User user); /** * 修改当前用户密码 * @param connection * @param id * @param pwd * @return * @ */ public int updatePwd(@Param("id") int id, @Param("pwd") String pwd); }
a87c9f02d72fda820ec8313c7804f480d465b14a
b9d48d1f0ed3ebc26a9a83173fd8454b60d6a834
/work/decompile-e341bf68/net/minecraft/server/MinecraftVersion.java
bf5eceac09934fbde469dae1aa8089de9bca36ba
[]
no_license
HitWRight/SlangelizmoServas
70ac99cfd097acd13d654ecf39a308ba8570f06f
017acfe3b1009901226086b9a16260d7aa720344
refs/heads/master
2022-09-27T04:24:29.978046
2020-12-21T20:45:06
2020-12-21T20:45:06
230,753,446
0
0
null
2022-09-16T18:06:17
2019-12-29T13:22:53
Java
UTF-8
Java
false
false
4,641
java
package net.minecraft.server; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.mojang.bridge.game.GameVersion; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.time.ZonedDateTime; import java.util.Date; import java.util.UUID; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class MinecraftVersion implements GameVersion { private static final Logger LOGGER = LogManager.getLogger(); private final String b; private final String c; private final boolean d; private final int e; private final int f; private final int g; private final Date h; private final String i; public MinecraftVersion() { this.b = UUID.randomUUID().toString().replaceAll("-", ""); this.c = "1.15"; this.d = true; this.e = 2225; this.f = 573; this.g = 5; this.h = new Date(); this.i = "1.15"; } protected MinecraftVersion(JsonObject jsonobject) { this.b = ChatDeserializer.h(jsonobject, "id"); this.c = ChatDeserializer.h(jsonobject, "name"); this.i = ChatDeserializer.h(jsonobject, "release_target"); this.d = ChatDeserializer.j(jsonobject, "stable"); this.e = ChatDeserializer.n(jsonobject, "world_version"); this.f = ChatDeserializer.n(jsonobject, "protocol_version"); this.g = ChatDeserializer.n(jsonobject, "pack_version"); this.h = Date.from(ZonedDateTime.parse(ChatDeserializer.h(jsonobject, "build_time")).toInstant()); } public static GameVersion a() { try { InputStream inputstream = MinecraftVersion.class.getResourceAsStream("/version.json"); Throwable throwable = null; MinecraftVersion minecraftversion; try { if (inputstream != null) { InputStreamReader inputstreamreader = new InputStreamReader(inputstream); Throwable throwable1 = null; try { Object object; try { object = new MinecraftVersion(ChatDeserializer.a((Reader) inputstreamreader)); return (GameVersion) object; } catch (Throwable throwable2) { object = throwable2; throwable1 = throwable2; throw throwable2; } } finally { if (inputstreamreader != null) { if (throwable1 != null) { try { inputstreamreader.close(); } catch (Throwable throwable3) { throwable1.addSuppressed(throwable3); } } else { inputstreamreader.close(); } } } } MinecraftVersion.LOGGER.warn("Missing version information!"); minecraftversion = new MinecraftVersion(); } catch (Throwable throwable4) { throwable = throwable4; throw throwable4; } finally { if (inputstream != null) { if (throwable != null) { try { inputstream.close(); } catch (Throwable throwable5) { throwable.addSuppressed(throwable5); } } else { inputstream.close(); } } } return minecraftversion; } catch (JsonParseException | IOException ioexception) { throw new IllegalStateException("Game version information is corrupt", ioexception); } } public String getId() { return this.b; } public String getName() { return this.c; } public String getReleaseTarget() { return this.i; } public int getWorldVersion() { return this.e; } public int getProtocolVersion() { return this.f; } public int getPackVersion() { return this.g; } public Date getBuildTime() { return this.h; } public boolean isStable() { return this.d; } }
b1a16b47a107bbb7b616806e85cb01c52acd023d
69b61da391d99bbd01a655cb6060a5faccbb6044
/src/pojo/WebAutomation.java
baa8380730666c71144a3bf13261e6a69052b233
[]
no_license
Manish5243/Api_Automation
6bcf06d424634bcf841fc2c7540d143b4923bf4f
16ceb4d10b13b5b763d84b873100d9660ac8f568
refs/heads/main
2023-07-10T18:22:32.695334
2021-08-18T17:17:31
2021-08-18T17:17:31
397,679,233
0
0
null
null
null
null
UTF-8
Java
false
false
368
java
package pojo; public class WebAutomation { private String courseTitle; private String price; public String getCourseTitle() { return courseTitle; } public void setCourseTitle(String courseTitle) { this.courseTitle = courseTitle; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } }
e3396328aa56d0346da767f66eac3900b496f3d1
66c3152591aeeefa93a078b4ea38f418a4478e50
/src/main/java/org/edloidas/web/controller/ProjectController.java
99df099d8e4643fa6c749a9c2a102b0607d9a620
[]
no_license
edloidas/texthistory
a8259c98897aed461e1980f49835b2551b5b5760
abcca8493c196053b93b727149e6944ac154e6de
refs/heads/master
2021-01-15T23:40:19.116486
2015-12-07T07:40:44
2015-12-07T07:40:44
5,589,662
1
0
null
null
null
null
UTF-8
Java
false
false
14,249
java
package org.edloidas.web.controller; import org.apache.log4j.Logger; import org.edloidas.entity.common.Project; import org.edloidas.entity.common.Source; import org.edloidas.web.json.JsonData; import org.edloidas.web.service.EntityService; import org.edloidas.web.service.SessionService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.annotation.Resource; import java.io.BufferedReader; import java.io.InputStreamReader; import java.math.BigInteger; import java.security.MessageDigest; import java.util.ArrayList; import java.util.List; /** * Project Controller, that handles requests for project operations and source adding. * * @author Никита */ @Controller @RequestMapping(value = "/project") @SessionAttributes({"userSession"}) public class ProjectController { /** * Logger for common output. Uses root logger output style. * See log4j.properties file for more details. */ private static final Logger LOGGER = Logger.getLogger(ProjectController.class); /** * Project service for CRUD operations. * * @see org.edloidas.web.service.common.ProjectService */ /* USE Interface here. * Otherwise SPRING will throw BeanNotOfRequiredTypeException. * Spring uses the interface type to make dependency injection! */ @Resource(name = "projectService") private EntityService<Project> projectService; /** * Source service for CRUD operations. * * @see org.edloidas.web.service.common.SourceService */ /* USE Interface here. * Otherwise SPRING will throw BeanNotOfRequiredTypeException. * Spring uses the interface type to make dependency injection! */ @Resource(name = "sourceService") private EntityService<Source> sourceService; /** * Session variables holder. * * @see org.edloidas.web.service.SessionService */ @Resource(name = "sessionService") private SessionService userSession; /** * Handles and retrieves the non-AJAX project list page. * * @return {@code String}, that represents view. */ @RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json; charset=utf-8") public String projectList(Model model) { try { if (!userSession.isLogged()) { return "index"; } List<Project> projects; int count; projects = projectService.getAll(new Project(userSession.getUser())); count = projects.size(); model.addAttribute("projects", projects); model.addAttribute("count", count); model.addAttribute("sessionUser", userSession.getUser().getName()); model.addAttribute("sessionProject", userSession.getProject().getName()); return "project-list"; } catch (Exception ex) { LOGGER.info(ex.getMessage()); /* TODO: Replace with error pages */ return "home"; } } /** * Handles and retrieves the non-AJAX project add page. * * @return {@code String}, that represents view. */ @RequestMapping(value = "/new", method = RequestMethod.GET, produces = "application/json; charset=utf-8") public String projectNew(Model model) { try { if (!userSession.isLogged()) { return "index"; } model.addAttribute("sessionUser", userSession.getUser().getName()); model.addAttribute("sessionProject", userSession.getProject().getName()); return "project-add"; } catch (Exception ex) { LOGGER.info(ex.getMessage()); /* TODO: Replace with error pages */ return "home"; } } /** * Handles and retrieves the AJAX request for adding new project. * * @return {@code String}, that represents text response of operation status. */ @RequestMapping(value = "/new/save", method = RequestMethod.POST, produces = "application/json; charset=utf-8") public @ResponseBody String projectAdd(@RequestParam(value = "name", required = true) String name, @RequestParam(value = "desc", required = true) String desc) { try { if (!userSession.isLogged()) { return "{\"code\":2,\"msg\":\"Access denied.\",\"data\":\"User has no rights to do this.\"}"; } JsonData json; Project project = new Project(name, desc, userSession.getUser()); projectService.addEntity(project); json = new JsonData(0, "Project added.", project.getName()); return json.toString(); } catch (Exception ex) { LOGGER.info(ex.getMessage()); return "{\"code\":1,\"msg\":\"Server error.\",\"data\":\"See server log.\"}"; } } /** * Handles and retrieves the AJAX request for deleting project. * * @return {@code String}, that represents text response of operation status. */ @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = "application/json; charset=utf-8") public @ResponseBody String projectDelete(@RequestParam(value = "id", required = true) String id) { try { if (!userSession.isLogged()) { return "{\"code\":2,\"msg\":\"Access denied.\",\"data\":\"User has no rights to do this.\"}"; } JsonData json; Project project = new Project(); project.setId(Integer.parseInt(id)); /* TODO: Check, if user has permission to delete this project. And replace messages with codes. */ List<Source> src1 = sourceService.getAll(new Source(project)); List<Source> src2 = new ArrayList<>(); for (Source s : src1) { src2.add(new Source(s.getId())); } project.setSources(src2); projectService.deleteEntity(project); if (project.getId() == userSession.getProject().getId()) { userSession.closeProject(); json = new JsonData(3, "Project closed and deleted.", "none"); } else { json = new JsonData(0, "Project deleted.", "none"); } return json.toString(); } catch (Exception ex) { LOGGER.info(ex.getMessage()); return "{\"code\":1,\"msg\":\"Server error.\",\"data\":\"See server log.\"}"; } } /** * Handles and retrieves the AJAX request for opening project. * * @return {@code String}, that represents text response of operation status. */ /* Using mapping produces = "application/json; charset=utf-8" is highly recommended. * In other case you will have bad Response with ISO character encoding. */ @RequestMapping(value = "/open", method = RequestMethod.POST, produces = "application/json; charset=utf-8") public @ResponseBody String projectOpen(@RequestParam(value = "id", required = true) String id) { try { if (!userSession.isLogged()) { return "{\"code\":2,\"msg\":\"Access denied.\",\"data\":\"User has no rights to do this.\"}"; } JsonData json; Project project = projectService.getById(new Project(Integer.parseInt(id))); if (userSession.setProject(project)) { json = new JsonData(3, "Project with name [" + project.getName() + "] opened.", project.getName()); userSession.setTextUpdated(false); } else { json = new JsonData(2, "Project can not be opened.", "Something goes wrong."); } return json.toString(); } catch (Exception ex) { LOGGER.info(ex.getMessage()); return "{\"code\":1,\"msg\":\"Server error.\",\"data\":\"See server log.\"}"; } } /** * Handles and retrieves the AJAX request for viewing project. * * @return {@code String}, that represents text response of operation status. */ /* Using mapping produces = "application/json; charset=utf-8" is highly recommended. * In other case you will have bad Response with ISO character encoding. * TODO: Add view by name for mapping '/view/name/{projectName}+' */ @RequestMapping(value = "/view/{projectId}", method = RequestMethod.GET, produces = "application/json; charset=utf-8") public String projectView(@PathVariable("projectId") String projectId, Model model) { try { if (!userSession.isLogged()) { return "index"; } Project project; List<Source> sources; int count; int id = Integer.parseInt(projectId); project = projectService.getById(new Project(id)); if (project.getUser().getId() != userSession.getUser().getId()) { // TODO: Add model message here. return "project-list"; } sources = sourceService.getAll(new Source(new Project(id))); count = sources.size(); model.addAttribute("project", project); model.addAttribute("sources", sources); model.addAttribute("count", count); model.addAttribute("sessionUser", userSession.getUser().getName()); model.addAttribute("sessionProject", userSession.getProject().getName()); return "project-view"; } catch (Exception ex) { LOGGER.info(ex.getMessage()); /* TODO: Replace with error pages */ return "project-list"; } } /** * Handles and retrieves the AJAX request for updating project. * * @return {@code String}, that represents text response of operation status. */ /* Using mapping produces = "application/json; charset=utf-8" is highly recommended. * In other case you will have bad Response with ISO character encoding. */ @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json; charset=utf-8") public @ResponseBody String projectUpdate(@RequestParam(value = "id", required = true) String id, @RequestParam(value = "name", required = true) String name, @RequestParam(value = "desc", required = true) String desc) { try { if (!userSession.isLogged()) { return "{\"code\":2,\"msg\":\"Access denied.\",\"data\":\"User has no rights to do this.\"}"; } JsonData json; Project project = projectService.getById(new Project(Integer.parseInt(id))); project.setName(name); project.setDescription(desc); project.update(); projectService.updateEntity(project); if (userSession.getProject().getId() != Integer.parseInt(id)) { json = new JsonData(0, "Project with name [" + project.getName() + "] updated.", project.getName()); } else { // Update if saved project is currently opened. userSession.setProject(project); json = new JsonData(3, "Project with name [" + project.getName() + "] updated.", project.getName()); } return json.toString(); } catch (Exception ex) { LOGGER.info(ex.getMessage()); return "{\"code\":1,\"msg\":\"Server error.\",\"data\":\"See server log.\"}"; } } /** * Handles and retrieves the AJAX request for file uploading. * * @return {@code String}, that represents text response of operation status. */ /* Using mapping produces = "application/json; charset=utf-8" is highly recommended. * In other case you will have bad Response with ISO character encoding. */ @RequestMapping(value = "/{projectId}/upload", method = RequestMethod.POST, produces = "application/json; charset=utf-8") public @ResponseBody String projectFileUpload(@PathVariable("projectId") String id, @RequestParam(value = "file", required = true) CommonsMultipartFile file) { try { if (!userSession.isLogged()) { return "{\"code\":2,\"msg\":\"Access denied.\",\"data\":\"User has no rights to do this.\"}"; } BufferedReader in = new BufferedReader(new InputStreamReader(file.getInputStream())); StringBuilder sb = new StringBuilder(); String text; while ((text = in.readLine()) != null) { sb.append(text).append("\n"); } text = sb.toString(); // Get MD5 MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes(), 0, text.length()); BigInteger md5Number = new BigInteger(1, md5.digest()); List<Source> sources = sourceService.getAll(new Source(md5Number.toString(16))); if (sources.size() != 0) { return new JsonData(1, "File [" + file.getOriginalFilename() + "] not added. Reason: file with the same signature already exists.", "File with the same signature already exists.").toString(); } Project project = projectService.getById(new Project(Integer.parseInt(id))); Source src = new Source(file.getOriginalFilename(), text, md5Number.toString(16), project); sourceService.addEntity(src); userSession.setTextUpdated(false); return new JsonData(3, "File [" + file.getOriginalFilename() + "] uploaded with total size of " + file.getSize() + " Bytes.", "Total size: " + file.getSize()).toString(); } catch (Exception ex) { LOGGER.info(ex.getMessage()); return "{\"code\":1,\"msg\":\"Server error.\",\"data\":\"See server log.\"}"; } } }
2f30539aa54d35a1bfe2e3f161ec082d8e49a3b9
d2eee6e9a3ad0b3fd2899c3d1cf94778615b10cb
/PROMISE/archives/poi/2.0/org/apache/poi/hssf/record/LabelSSTRecord.java
cc7deced76de1bcdde4eb981223192be5e259e40
[]
no_license
hvdthong/DEFECT_PREDICTION
78b8e98c0be3db86ffaed432722b0b8c61523ab2
76a61c69be0e2082faa3f19efd76a99f56a32858
refs/heads/master
2021-01-20T05:19:00.927723
2018-07-10T03:38:14
2018-07-10T03:38:14
89,766,606
5
1
null
null
null
null
UTF-8
Java
false
false
7,371
java
package org.apache.poi.hssf.record; import org.apache.poi.util.LittleEndian; /** * Title: Label SST Record<P> * Description: Refers to a string in the shared string table and is a column * value. <P> * REFERENCE: PG 325 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)<P> * @author Andrew C. Oliver (acoliver at apache dot org) * @author Jason Height (jheight at chariot dot net dot au) * @version 2.0-pre */ public class LabelSSTRecord extends Record implements CellValueRecordInterface, Comparable { public final static short sid = 0xfd; private int field_1_row; private short field_2_column; private short field_3_xf_index; private int field_4_sst_index; public LabelSSTRecord() { } /** * Constructs an LabelSST record and sets its fields appropriately. * * @param id id must be 0xfd or an exception will be throw upon validation * @param size the size of the data area of the record * @param data data of the record (should not contain sid/len) */ public LabelSSTRecord(short id, short size, byte [] data) { super(id, size, data); } /** * Constructs an LabelSST record and sets its fields appropriately. * * @param id id must be 0xfd or an exception will be throw upon validation * @param size the size of the data area of the record * @param data data of the record (should not contain sid/len) * @param offset of the record's data */ public LabelSSTRecord(short id, short size, byte [] data, int offset) { super(id, size, data, offset); } protected void validateSid(short id) { if (id != sid) { throw new RecordFormatException("NOT A valid LabelSST RECORD"); } } protected void fillFields(byte [] data, short size, int offset) { field_1_row = LittleEndian.getUShort(data, 0 + offset); field_2_column = LittleEndian.getShort(data, 2 + offset); field_3_xf_index = LittleEndian.getShort(data, 4 + offset); field_4_sst_index = LittleEndian.getInt(data, 6 + offset); } public void setRow(int row) { field_1_row = row; } public void setColumn(short col) { field_2_column = col; } /** * set the index to the extended format record * * @see org.apache.poi.hssf.record.ExtendedFormatRecord * @param index - the index to the XF record */ public void setXFIndex(short index) { field_3_xf_index = index; } /** * set the index to the string in the SSTRecord * * @param index - of string in the SST Table * @see org.apache.poi.hssf.record.SSTRecord */ public void setSSTIndex(int index) { field_4_sst_index = index; } public int getRow() { return field_1_row; } public short getColumn() { return field_2_column; } /** * get the index to the extended format record * * @see org.apache.poi.hssf.record.ExtendedFormatRecord * @return the index to the XF record */ public short getXFIndex() { return field_3_xf_index; } /** * get the index to the string in the SSTRecord * * @return index of string in the SST Table * @see org.apache.poi.hssf.record.SSTRecord */ public int getSSTIndex() { return field_4_sst_index; } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("[LABELSST]\n"); buffer.append(" .row = ") .append(Integer.toHexString(getRow())).append("\n"); buffer.append(" .column = ") .append(Integer.toHexString(getColumn())).append("\n"); buffer.append(" .xfindex = ") .append(Integer.toHexString(getXFIndex())).append("\n"); buffer.append(" .sstindex = ") .append(Integer.toHexString(getSSTIndex())).append("\n"); buffer.append("[/LABELSST]\n"); return buffer.toString(); } public int serialize(int offset, byte [] data) { LittleEndian.putShort(data, 0 + offset, sid); LittleEndian.putShort(data, 2 + offset, ( short ) 10); LittleEndian.putShort(data, 4 + offset, ( short )getRow()); LittleEndian.putShort(data, 6 + offset, getColumn()); LittleEndian.putShort(data, 8 + offset, getXFIndex()); LittleEndian.putInt(data, 10 + offset, getSSTIndex()); return getRecordSize(); } public int getRecordSize() { return 14; } public short getSid() { return this.sid; } public boolean isBefore(CellValueRecordInterface i) { if (this.getRow() > i.getRow()) { return false; } if ((this.getRow() == i.getRow()) && (this.getColumn() > i.getColumn())) { return false; } if ((this.getRow() == i.getRow()) && (this.getColumn() == i.getColumn())) { return false; } return true; } public boolean isAfter(CellValueRecordInterface i) { if (this.getRow() < i.getRow()) { return false; } if ((this.getRow() == i.getRow()) && (this.getColumn() < i.getColumn())) { return false; } if ((this.getRow() == i.getRow()) && (this.getColumn() == i.getColumn())) { return false; } return true; } public boolean isEqual(CellValueRecordInterface i) { return ((this.getRow() == i.getRow()) && (this.getColumn() == i.getColumn())); } public boolean isInValueSection() { return true; } public boolean isValue() { return true; } public int compareTo(Object obj) { CellValueRecordInterface loc = ( CellValueRecordInterface ) obj; if ((this.getRow() == loc.getRow()) && (this.getColumn() == loc.getColumn())) { return 0; } if (this.getRow() < loc.getRow()) { return -1; } if (this.getRow() > loc.getRow()) { return 1; } if (this.getColumn() < loc.getColumn()) { return -1; } if (this.getColumn() > loc.getColumn()) { return 1; } return -1; } public boolean equals(Object obj) { if (!(obj instanceof CellValueRecordInterface)) { return false; } CellValueRecordInterface loc = ( CellValueRecordInterface ) obj; if ((this.getRow() == loc.getRow()) && (this.getColumn() == loc.getColumn())) { return true; } return false; } public Object clone() { LabelSSTRecord rec = new LabelSSTRecord(); rec.field_1_row = field_1_row; rec.field_2_column = field_2_column; rec.field_3_xf_index = field_3_xf_index; rec.field_4_sst_index = field_4_sst_index; return rec; } }
5debb8a6460a8070143db74272a2df972cd01e8c
94ac6295a007d5f8550b117a6a39f568c48b34c5
/src/simple/ValidParentheses.java
8486747092a661f091dfbc24cbc99a18b02a720a
[]
no_license
BUPTZHanggg/leetcode
cb1e693a418cf8986611bc58c25d922a6e68eb14
2700f08a771d48fa5376e3aa1aa2149c97df1454
refs/heads/master
2023-08-29T04:46:47.949477
2023-08-02T06:05:13
2023-08-02T06:05:13
218,939,005
0
0
null
null
null
null
UTF-8
Java
false
false
748
java
package simple; import java.util.Stack; public class ValidParentheses { public static boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (char c : s.toCharArray()){ if (c == '(' || c == '{' || c == '['){ stack.push(c); continue; } if (stack.isEmpty()){ return false; }else { Character top = stack.pop(); int dif = c - top; if (!(dif == 1 || dif == 2)) return false; } } return stack.isEmpty(); } public static void main(String[] args) { System.out.println(isValid("{}[{}]((){})(){}")); } }
f5d55780d9df9468b2cbbe82d4ee1a583ea50d97
e9fe29870d01a37540c7b99b06d5490e15e32948
/src/main/java/com/bridgelabz/usermanagement/controller/DashboardController.java
729bda616281a01f3f60620614feb40de53e04da
[]
no_license
VijaykumarBhavanur/UserManagement
91afe63429a3b232d3cae1781d26a8af8b05b9aa
d76bcef199ae250f83e3c22d9fee4ef9aa115674
refs/heads/master
2020-11-30T17:40:13.664700
2019-12-28T07:02:11
2019-12-28T07:02:11
230,450,093
0
0
null
null
null
null
UTF-8
Java
false
false
1,032
java
package com.bridgelabz.usermanagement.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.bridgelabz.usermanagement.response.Response; import com.bridgelabz.usermanagement.service.IDashboardService; @RestController @RequestMapping("/userstatistics") public class DashboardController { @Autowired private IDashboardService dashService; /** * * @param year * @param month * @return response with user registration statistics */ @GetMapping("/{year}/{month}") public ResponseEntity<Response> getYearData(@PathVariable int year, @PathVariable int month) { return new ResponseEntity<>(dashService.getUserStat(year, month), HttpStatus.OK); } }
[ "vijaykumarbhavanur.com" ]
vijaykumarbhavanur.com
5c21058e9e373bb89af8a29559b345d3acd304dc
38eba95967b313f35d0edf621734436e756626b6
/src/org/fieldstream/service/sensor/virtual/RespirationCalculation.java
bec400952a9bde6d8d33d7b69c84f994e56bdc96
[ "BSD-2-Clause" ]
permissive
nesl/FieldStream-AntRadio
1ac0ccd00d6063d0c66ff41cf9abe20c286ab91d
955f15343ca5f808eba37d3c904919c2d4b59ac6
refs/heads/master
2021-01-10T18:58:20.814202
2012-01-03T16:11:40
2012-01-03T16:11:40
2,255,868
0
0
null
null
null
null
UTF-8
Java
false
false
3,577
java
//Copyright (c) 2010, University of Memphis //All rights reserved. // //Redistribution and use in source and binary forms, with or without modification, are permitted provided //that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list of conditions and // the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this list of conditions // and the following disclaimer in the documentation and/or other materials provided with the // distribution. // * Neither the name of the University of Memphis nor the names of its contributors may be used to // endorse or promote products derived from this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED //WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A //PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR //ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED //TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING //NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE //POSSIBILITY OF SUCH DAMAGE. // package org.fieldstream.service.sensor.virtual; //@author Monowar Hossain import java.util.ArrayList; import org.fieldstream.service.logger.Log; public class RespirationCalculation { public int[]calculate(int[] data, long[] timestamp) { RPVCalculationNew rpv=new RPVCalculationNew(); int realPeakValley[]=rpv.calculate(data, timestamp); // String rpvs=""; // for(int i=0;i<realPeakValley.length;i++) // rpvs+=realPeakValley[i]+","; // // Log.d("RespirationVS","RPV= "+rpvs); // RespirationCalculation Respiration=new RespirationCalculation(); // int ie[]=Respiration.calculate(realPeakValley, timestamp); int rd[]=getRespiration(realPeakValley); return rd; } public int[] getRespiration(int[] data) //window size will be 4*(number of real peaks) is typically 4*5 because we are gonna consider 5 real peaks at a time { int length=data.length; int inhalation=0,exhalation=0; ArrayList<Integer> list=new ArrayList<Integer>(); int temp=length; for(int i=0;i<temp;i+=4) { //check the starting whether it starts from valley or not. It should be valley if((i==0) && (data[i+1]>data[i+3])) continue; //it escaping if first member is a peak. in that case we can not find the inspiration. inspiration always starts from a valley //check last element whether it is valley or peak. it should be valley if((i==0)&&(data[length-1]>data[length-3])) //at the beginning the stopping condition is changed temp=length-2; //skipping the last one if it is peak if(i+4<length) { inhalation=data[i+2]-data[i]; exhalation=data[i+4]-data[i+2]; float Respiration=(float)inhalation+(float)exhalation; int raoundedRespiration=(int)(Respiration*10000); list.add(new Integer(raoundedRespiration)); } } //converting the ArrayList to array int Respiration[]=new int[list.size()]; for(int j=0;j<list.size();j++) { Respiration[j]=list.get(j).intValue(); } return Respiration; } }
32536af0c5d130181fb7a5a2fa3cf47b1af50b84
7d34967b06809badc87efc5de8543a6d21e0a5db
/gulimall-ware/src/main/java/com/atguigu/gulimall/ware/controller/WareInfoController.java
813bb8e49ab683fc0d2e86147b162eae5a1bb041
[ "Apache-2.0" ]
permissive
espmihacker/gulimall
7f1f20f62dbed1d1e29ddc15963ab2be93e6cc97
f63e976562dad3d48a28a5ece96ce00be75db272
refs/heads/master
2023-03-12T09:41:04.235302
2022-12-07T03:32:46
2022-12-07T03:32:46
253,051,639
0
0
Apache-2.0
2023-02-22T02:17:31
2020-04-04T16:55:05
JavaScript
UTF-8
Java
false
false
1,928
java
package com.atguigu.gulimall.ware.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.atguigu.gulimall.ware.entity.WareInfoEntity; import com.atguigu.gulimall.ware.service.WareInfoService; import com.atguigu.common.utils.PageUtils; import com.atguigu.common.utils.R; /** * 仓库信息 * * @author mihacker * @email [email protected] * @date 2020-04-05 02:56:55 */ @RestController @RequestMapping("ware/wareinfo") public class WareInfoController { @Autowired private WareInfoService wareInfoService; /** * 列表 */ @RequestMapping("/list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = wareInfoService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") public R info(@PathVariable("id") Long id){ WareInfoEntity wareInfo = wareInfoService.getById(id); return R.ok().put("wareInfo", wareInfo); } /** * 保存 */ @RequestMapping("/save") public R save(@RequestBody WareInfoEntity wareInfo){ wareInfoService.save(wareInfo); return R.ok(); } /** * 修改 */ @RequestMapping("/update") public R update(@RequestBody WareInfoEntity wareInfo){ wareInfoService.updateById(wareInfo); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") public R delete(@RequestBody Long[] ids){ wareInfoService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
0cc593bccaf9e82c6a2913a50b370f1fc4074ac8
4d82090a726577807998a7cac134f12ebb4a66d7
/src/main/java/info/ottawaimagyar/katolikus/exporter/PostDate.java
27fa8be00240e5af4bbf0cf1b1bd9114c23f3204
[]
no_license
tfasanga/ottawa.katolikus.hu-exporter
fbac3b5fd1c652d8afeedec8979ae3083379488e
fd37654306a84ac39fa1b276d0b23f5813327ff3
refs/heads/master
2020-04-23T02:10:39.122354
2015-11-19T03:32:19
2015-11-19T03:32:19
41,768,621
0
0
null
null
null
null
UTF-8
Java
false
false
3,161
java
package info.ottawaimagyar.katolikus.exporter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; class PostDate { private static final Map<String, String> dict; private static final Set<String> missing = new HashSet<>(); private final String year; private final String month; private final String dayNum; private final String day; private final String hour; static { dict = new HashMap<>(); dict.put("janu"+(char)225+"r", "Jan"); dict.put("febru"+(char)225+"r", "Feb"); dict.put("m"+(char)225+"rcius", "Mar"); dict.put((char)225+"prilis", "Apr"); dict.put("m"+(char)225+"jus", "May"); dict.put("j"+(char)250+"nius", "Jun"); dict.put("j"+(char)250+"lius", "Jul"); dict.put("augusztus", "Aug"); dict.put("szeptember", "Sep"); dict.put("okt"+(char)243+"ber", "Oct"); dict.put("november", "Nov"); dict.put("december", "Dec"); dict.put("h"+(char)233+"tf"+(char)337, "Mon"); dict.put("kedd", "Tue"); dict.put("szerda", "Wed"); dict.put("cs"+(char)252+"t"+(char)246+"rt"+(char)246+"k", "Thu"); dict.put("p"+(char)233+"ntek", "Fri"); dict.put("szombat", "Sat"); dict.put("vas"+(char)225+"rnap", "Sun"); dict.put("Jan", "1"); dict.put("Feb", "2"); dict.put("Mar", "3"); dict.put("Apr", "4"); dict.put("May", "5"); dict.put("Jun", "6"); dict.put("Jul", "7"); dict.put("Aug", "8"); dict.put("Sep", "9"); dict.put("Oct", "10"); dict.put("Nov", "11"); dict.put("Dec", "12"); } // "2010. november 6. (szombat) 12:59" private String postDate; public PostDate(String aInPostDate) { postDate = aInPostDate; String[] lSplit = postDate.split(" "); year = lSplit[0].replace(".", ""); String lHonap = lSplit[1]; month = translate(lHonap); dayNum = lSplit[2].replace(".", ""); String lNap = lSplit[3].replace("(", "").replace(")", ""); day = translate(lNap); hour = lSplit[4] + ":00"; } public String toRssPubDate() { // pubDate: Sun, 31 Oct 2010 23:28:57 +0000 String lValue = day + ", " + dayNum + " " + month + " " + year + " " + hour + " " + "+0000"; return lValue; } public String toWpPostDate() { // <wp:post_date>2010-10-31 19:28:57</wp:post_date> String lValue = year + "-" + translate(month) + "-" + dayNum + " " + hour; return lValue; } private static String translate(String aInValue) { String lDayName = dict.get(aInValue); if(lDayName == null) { if(missing.add(aInValue)) { System.out.println("missing: \"" + aInValue + "\""); } lDayName = aInValue; } return lDayName; } }
f73c5eb82c7033cb0b208df309753ecefc9f3792
7bcec451ee79ad4f5ab15f620b93c13a1b218218
/src/cn/edu/nsu/predom/db/function/FunctionDAO.java
9addbf3cfbc03764ca9c95cea90900ef28366328
[]
no_license
NOSucker/first-in
621ddcfc7f278b99e2488674956ade15141b0e2e
421ef0ac61216b9ae028b7723c52824afac930dc
refs/heads/master
2021-07-02T11:30:43.774470
2017-09-25T03:22:50
2017-09-25T03:22:50
104,699,160
0
0
null
null
null
null
UTF-8
Java
false
false
2,786
java
/** * */ package cn.edu.nsu.predom.db.function; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import cn.edu.nsu.predom.db.DBMain; /** * @author ���Ƕ� * */ public class FunctionDAO extends DBMain<Function> { @Override public void add(Function dataObj) throws ClassNotFoundException, SQLException { sql = "insert functions(function_name,function_note) values(?,?)"; pst = this.getPreparedStatement(sql); pst.setString(1, dataObj.getFunction_name()); pst.setString(2, dataObj.getFunction_note()); pst.executeUpdate(); } @Override public Function assemble(ResultSet rst) throws SQLException { Function fc = new Function(); fc.setFunction_id(rst.getInt("function_id")); fc.setFunction_name(rst.getString("function_name")); fc.setFunction_note(rst.getString("function_note")); return fc; } @Override public void delete(int id) throws ClassNotFoundException, SQLException { sql = "delete functions where function_id = ?"; pst = this.getPreparedStatement(sql); pst.setInt(1, id); pst.executeUpdate(); } @Override public ArrayList<Function> getAll() throws ClassNotFoundException, SQLException { ArrayList<Function> functions = new ArrayList<Function>(); Function function = null; sql = "select * from functions"; pst = this.getPreparedStatement(sql); rst = pst.executeQuery(); while (rst.next()) { function = assemble(rst); functions.add(function); } return functions; } public ArrayList<Function> getAllByUserGroupId(int userGroup_id) throws ClassNotFoundException, SQLException { ArrayList<Function> functions = new ArrayList<Function>(); Function function = null; sql = "select functions.* from functions,predom where functions.function_id=predom.function_ID and predom.userGroup_id=?"; pst = this.getPreparedStatement(sql); pst.setInt(1, userGroup_id); rst = pst.executeQuery(); while (rst.next()) { function = assemble(rst); functions.add(function); } return functions; } @Override public Function getById(int id) throws ClassNotFoundException, SQLException { Function function = null; sql = "select * from functions where functions_id = ?"; pst = this.getPreparedStatement(sql); pst.setInt(1, id); rst = pst.executeQuery(); while (rst.next()) { function = assemble(rst); } return function; } @Override public void modify(Function newDataObj) throws ClassNotFoundException, SQLException { sql = "update functions set functions_name = ?,functions_note = ? where functions_id = ?"; pst = this.getPreparedStatement(sql); pst.setString(1, newDataObj.getFunction_name()); pst.setString(2, newDataObj.getFunction_note()); pst.setInt(3, newDataObj.getFunction_id()); pst.executeUpdate(); } }
ff457ea6f00755425081050232ca0735ae746045
1711fa3513ef168348b5f2c98f14de947e35629f
/app/src/main/java/br/usjt/arqdesis/projetopredial/MainActivity.java
8e7276e01c4d088890f3e478f5a52d76158ef92a
[]
no_license
Bruchner/ProjetoPredial
af783dd10fc10216ad025eda6ed93132d1eef2b7
602b4123ac300d6e03540e1deefbd04e0ca656f0
refs/heads/master
2021-06-29T23:43:31.670547
2017-09-20T04:21:24
2017-09-20T04:21:24
104,112,358
0
0
null
null
null
null
UTF-8
Java
false
false
3,645
java
package br.usjt.arqdesis.projetopredial; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputEditText; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AlertDialogLayout; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void login(View v){ EditText login1 = (EditText) findViewById(R.id.login); EditText senha1 = (EditText) findViewById(R.id.senha); Editable login = login1.getText(); Editable senha = senha1.getText(); Button btn = (Button)findViewById(R.id.Cadastrar_Empresa); Button btn2 = (Button)findViewById(R.id.ArquivoAcesso); Button btn3 = (Button) findViewById(R.id.CadastrarUsuario); Button btn4 = (Button) findViewById(R.id.ReconfigTemp); if(login1.equals("func") && senha1.equals("func")){ Intent it = new Intent(MainActivity.this, Funcionalidades.class); startActivity(it); btn.setEnabled(true); btn2.setEnabled(false); btn3.setEnabled(false); btn4.setEnabled(false); }else if(login1.equals("atend") && senha1.equals("atend")){ Intent it = new Intent(MainActivity.this, Funcionalidades.class); startActivity(it); btn.setEnabled(true); btn2.setEnabled(true); btn3.setEnabled(true); btn4.setEnabled(true); }else if(login1.equals("sind")&& senha1.equals("sind")){ Intent it = new Intent(MainActivity.this, Funcionalidades.class); startActivity(it); btn.setEnabled(true); btn2.setEnabled(true); btn3.setEnabled(true); btn4.setEnabled(true); }else { //INSTANCIA DIALOGO DE ALERTA AlertDialog alerta; AlertDialog.Builder builder = new AlertDialog.Builder(this); //Cria titulo & mensagem de erro builder.setTitle("Error"); builder.setMessage("Usuario/Senha inválido"); //Cria botao para caso positivo/negativo, e seu texto interno(Caso negativo, fecha programa) builder.setPositiveButton("Tente Novamente", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(MainActivity.this, "Tente Novamente", Toast.LENGTH_LONG).show(); } }); builder.setNegativeButton("Sair", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(MainActivity.this, "Saiu", Toast.LENGTH_SHORT).show(); finish(); } }); //Cria e mostra dialogo alerta = builder.create(); alerta.show(); } } }
3d480abea62cd03e61b747f2e963f91301894bc6
4c312063a064a9e420bc90dd960bd04cd00478bb
/app/src/main/java/ercanduman/jobschedulerdemo/services/ServiceExample.java
07e18910e88fc8634423253608b65f902462b5ba
[]
no_license
ercanduman/AndroidServicesExamples
000d769e19cf433d736e116e1af46147f3745261
ceb72a9274874126bf012d02c705ba4f1c9bdd09
refs/heads/master
2020-09-01T14:16:34.709444
2019-11-19T07:44:08
2019-11-19T07:44:08
218,977,250
0
0
null
null
null
null
UTF-8
Java
false
false
2,421
java
package ercanduman.jobschedulerdemo.services; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.SystemClock; import android.util.Log; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import ercanduman.jobschedulerdemo.R; import ercanduman.jobschedulerdemo.ui.MainActivity; import static ercanduman.jobschedulerdemo.Constants.CHANNEL_ID; public class ServiceExample extends Service { private static final String TAG = "ServiceExample"; private static final int NOTIFICATION_ID = 1; @Override public void onCreate() { Log.d(TAG, "onCreate: called only once...."); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // all codes written here runs on main thread // so do the heavy work on the background Log.d(TAG, "onStartCommand: called every time service started..."); String passedData = intent.getStringExtra(MainActivity.INPUT_EXTRA); Log.d(TAG, "onStartCommand: passedData: " + passedData); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Plain Service Example") .setContentText(passedData) .setSmallIcon(R.drawable.ic_launcher_background) .setContentIntent(pendingIntent) .build(); startForeground(NOTIFICATION_ID, notification); // when work finished, should stop service // stopSelf(); /* This for loop freezes the app to indicate that all the work done in main thread */ for (int i = 0; i < 5; i++) { Log.d(TAG, "onStartCommand: called for i: " + i); SystemClock.sleep(1000); } return START_NOT_STICKY; } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { Log.d(TAG, "onDestroy: called only once when service is stopped."); super.onDestroy(); } }
c8c11fd1f451d875ba59a716e575d7e664e4f09c
31703986366e1ea30ea2ad4639fd2d854817dc74
/java-basic/src/main/java/bitcamp/java100/ch07/ex4/Test1.java
1c353a0edd785f3ba025986f14d303ad5886fb0c
[]
no_license
ji881111/bitcamp
8c793d14d67b8646a7f9747cc34df795fe7aaca6
59b511dd8e5609a00e5e5f7af8d976216f8c0e29
refs/heads/master
2021-09-08T21:28:39.953027
2018-03-12T10:18:28
2018-03-12T10:18:28
104,423,455
0
0
null
null
null
null
UTF-8
Java
false
false
693
java
package bitcamp.java100.ch07.ex4; public class Test1 /* extends Object */ { public static void main(String[] args) { Test1 obj = new Test1(); if (obj instanceof Test1) System.out.println("obj는 Test1의 인스턴스이다"); if (obj instanceof Object) System.out.println("obj는 Object의 자손이다"); Object o1 = new Object(); if (o1 instanceof Test1) System.out.println("1111"); // Object는 Test1을 상속하지 않았으므로 false Class c = Test1.class; Class sc = c.getSuperclass(); System.out.println(sc.getName()); } }
00b775ade7c536ab4f753ab753b234d0c3502719
d98ed4986ecdd7df4c04e4ad09f38fdb7a7043e8
/Hero_Charms/src/main/java/net/sf/anathema/hero/charms/model/learn/BasicLearningModel.java
8952f56acd50a1011ded18939fbc22f1d6ff6c96
[]
no_license
bjblack/anathema_3e
3d1d42ea3d9a874ac5fbeed506a1a5800e2a99ac
963f37b64d7cf929f086487950d4870fd40ac67f
refs/heads/master
2021-01-19T07:12:42.133946
2018-12-18T23:57:41
2018-12-18T23:57:41
67,353,965
0
0
null
2016-09-04T15:47:48
2016-09-04T15:47:48
null
UTF-8
Java
false
false
386
java
package net.sf.anathema.hero.charms.model.learn; import net.sf.anathema.magic.data.Charm; public interface BasicLearningModel { boolean isCurrentlyLearned (Charm charm); boolean isLearnedOnCreation (Charm charm); boolean isLearnedWithExperience (Charm charm); void toggleLearnedOnCreation (Charm charm); void toggleExperienceLearnedCharm (Charm charm); }
[ "BJ@BJ-PC" ]
BJ@BJ-PC
f433545621fe50a838d7de45c3f08a6b6f21fd4b
d7f0eef76905f8976e9f82078663ea10a281ecd8
/src/Algorithm/BinarySearchNoRecur.java
7b2c91c48e88320290de2c8e097f0d94be0d1b3a
[]
no_license
WeStudyTogether/EveryDayPractice
ce61532568222fe3cfd7a36be1db5eaf48d88963
6afa17206b56c151549b33f8c04d317598526c1a
refs/heads/master
2020-12-06T15:13:25.410652
2020-05-04T13:19:40
2020-05-04T13:19:40
232,493,842
1
0
null
null
null
null
UTF-8
Java
false
false
821
java
package Algorithm; /** * @author Guangyao Gou * @date 2020/38/14 15:38:05 * @ClassName BinarySearchNoRecur.java * @Description 类描述 */ public class BinarySearchNoRecur { public static void main(String[] args) { // TODO Auto-generated method stub int[] arr = {1,3,8,10,11,67,100}; int index = binarySearch(arr, 80); System.out.println(index); } public static int binarySearch(int[] arr, int target) { int left = 0; int right = arr.length - 1; while(left<=right) { int mid = (left +right)/2; if(arr[mid] == target) { return mid; }else if (arr[mid] > target) { right = mid - 1; }else{ left = mid + 1; } } return -1; } }
7f2bd4ba51dc716395c707637d49c4f9f87557f3
827c4d3f1fc5eaec0e0fc6658022fe74960ff200
/src/main/java/ir/maktab/service/ManagerService.java
257ce5c25f7fb5cf1c07a034d55ee12e193df09a
[]
no_license
zahra-asgari1996/home_service_spring
e7a42a34c89c1b2a0184bf626bc60d986db69b57
ac46970faa7aba7486cc581b9fc5b828263290c5
refs/heads/master
2023-06-04T23:09:11.501145
2021-06-25T09:40:51
2021-06-25T09:40:51
367,715,199
0
0
null
null
null
null
UTF-8
Java
false
false
582
java
package ir.maktab.service; import ir.maktab.data.domain.Manager; import ir.maktab.dto.ManagerDto; import ir.maktab.service.exception.InvalidPassword; import ir.maktab.service.exception.NotFoundManagerException; import java.util.List; public interface ManagerService { void saveNewManager(ManagerDto dto); void deleteManager(ManagerDto dto); void updateManager(ManagerDto dto); List<ManagerDto> fetchAllManagers(); ManagerDto findByUserName(String userName); ManagerDto loginManager(ManagerDto dto) throws NotFoundManagerException, InvalidPassword; }
1b342bee3fdd37ff4a7ae72669280aabbb00ad5f
bdfed246ecd7996f3ff831ea42ac3f686f3f1fb4
/src/test.java
8071adb0e33c222033b563b0d7d6a88dd9645b59
[]
no_license
IslamSalah/AvlTree_Implementation
b31f4ad03b46b48b3e1c9fe3cb8e161289f9c0fd
dbf02cdaf24cacf04f4fc51ee7b0fc97e81cf201
refs/heads/master
2020-03-29T17:43:42.814588
2015-03-25T21:54:22
2015-03-25T21:54:22
32,892,569
0
0
null
null
null
null
UTF-8
Java
false
false
700
java
public class test { public static void main(String[] args){ AVL_Tree<Integer,Object> avl = new AVL_Tree<Integer, Object>(); // int[] bookEg = {3,2,1,4,5,6,7,16,15,14,13,12,11,10,8,9}; // for(int i=0; i<bookEg.length; i++) // avl.insert(new Node<Integer,Object>(bookEg[i])); int[] arr = {30,89,80,25,90,53,12,79,64,58,55,17,11,32,98,29,10,45,40,21,66,92,88,97,39,86,16,67,74,94,50,13,47,100,81,83,95,59,33,41,70,48,14,36}; for(int i=0; i<arr.length; i++) avl.insert(new Node<Integer,Object>(arr[i])); for(int i=0; i<arr.length-7; i++) avl.delete(avl.search(arr[i])); avl.showTree(); System.out.println(avl.getTreeHeight()); System.out.println(avl.getSize()); } }
8872bf56eeaf4efb93bd3a8689147cacecea2921
c28324889711ae8457ebe5077c87ce620f53b91f
/src/main/java/com/walker/design/graphic/abstraction/list/ListFactory.java
62888e641fc3b00f0214344bdacbb2d05faee4c3
[]
no_license
walker911/design-pattern
359a96113f13f07250ad66d7a92549e2e5b0968c
f4a3aa53709a401e7b394bc83e4c40708640f1dc
refs/heads/master
2020-08-26T12:48:48.744600
2019-11-12T09:46:52
2019-11-12T09:46:52
217,014,602
0
0
null
null
null
null
UTF-8
Java
false
false
753
java
package com.walker.design.graphic.abstraction.list; import com.walker.design.graphic.abstraction.factory.Factory; import com.walker.design.graphic.abstraction.factory.Link; import com.walker.design.graphic.abstraction.factory.Page; import com.walker.design.graphic.abstraction.factory.Tray; /** * 具体的工厂 * * @author walker * @date 2019/10/30 */ public class ListFactory extends Factory { @Override public Link createLink(String caption, String url) { return new ListLink(caption, url); } @Override public Tray createTray(String caption) { return new ListTray(caption); } @Override public Page createPage(String title, String author) { return new ListPage(title, author); } }
2ee68192050082452946f9249f36d65944cee5a2
39933a810f663de1773e93d2a080c30aad8a8454
/src/main/java/br/jus/cnj/corporativo/bean/CorporativoUsuarioSistemaPerfilPK.java
b41fe45f96214f26e5bdecad559de40f5a9d3d3d
[]
no_license
ViniciusFelix/ProjetoJava
4ce23cf00e53108c67eca0524b308a9ad7d42067
ae23195d6e4decc6d4252e5c525b0b1b1ca60653
refs/heads/master
2021-01-11T23:54:42.362543
2017-01-11T13:47:37
2017-01-11T13:47:37
78,643,045
0
0
null
null
null
null
UTF-8
Java
false
false
1,649
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.jus.cnj.corporativo.bean; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; /** * * @author fabio.pereira */ @Embeddable public class CorporativoUsuarioSistemaPerfilPK implements Serializable { /** * */ private static final long serialVersionUID = 1612746920846611069L; @Column(name = "SEQ_USUARIO") private int idUsuario; @Column(name = "SEQ_SISTEMA") private int idSistema; @Column(name = "SEQ_PERFIL") private int idPerfil; public int getIdUsuario() { return idUsuario; } public void setIdUsuario(int idUsuario) { this.idUsuario = idUsuario; } public int getIdSistema() { return idSistema; } public void setIdSistema(int idSistema) { this.idSistema = idSistema; } public int getIdPerfil() { return idPerfil; } public void setIdPerfil(int idPerfil) { this.idPerfil = idPerfil; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + idPerfil; result = prime * result + idSistema; result = prime * result + idUsuario; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CorporativoUsuarioSistemaPerfilPK other = (CorporativoUsuarioSistemaPerfilPK) obj; if (idPerfil != other.idPerfil) return false; if (idSistema != other.idSistema) return false; if (idUsuario != other.idUsuario) return false; return true; } }
0c83c49f8b965cd59cc4c1a9690ffe1418e435df
f3e573228db8daa9d7e4aea4cef53c65bd47e216
/java_learn/src/demo_007_EXtends/Day_001.java
d84851bc0cc8ef79fc868a42591746c5ecc1c018
[]
no_license
lhyyp/itCast
2f6cd8037c6c64f8fd49c524dc7dd3c9da2f2217
8623d673429290cfd0ec4010dadb9533025d31c2
refs/heads/master
2023-08-19T20:37:42.095099
2021-10-26T06:59:16
2021-10-26T06:59:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
326
java
package demo_007_EXtends; public class Day_001 { public static void main(String[] args) { Zi zi = new Zi(); System.out.println("年龄:"+ zi.age); System.out.println(zi.num); zi.ZiMethods(); Zi.FuMethods(); Zi Z2 = new Zi(99); System.out.println(zi.num); } }
d2979fd6694601e8934b7a3fa5a4faed09f2459b
7ece0a6ecefc2ff7402a756aefea76636d9fdc3f
/bradypod.framework/framework.design/src/main/java/com/bradypod/framework/design/creator/mode/factory/SimpleFactory.java
137f6738ea3284f818f40ab9fd680e1d8002e1e9
[]
no_license
JumperYu/bradypod
f0aa03cfc6dfcbbeac2bedde92a60ab02e29843f
e208e5f416153c9146551236a9f537607d945b26
refs/heads/master
2022-12-21T05:23:57.912657
2019-06-28T10:29:33
2019-06-28T10:29:33
42,263,126
0
2
null
2022-12-16T07:44:35
2015-09-10T18:34:22
Java
UTF-8
Java
false
false
509
java
package com.bradypod.framework.design.creator.mode.factory; /** * Github * User: previous_yu * Date: 2018/10/27-13:19 * Desc: 简单工厂模式, 使用输入指令区别是哪个厂家的实现 */ public class SimpleFactory { public Mouse produceMouse(int type) { if(type == 1) { return new DeilMouse(); } else if(type == 2) { return new HpMouse(); } else { System.out.println("未知类型"); return null; } } }
cfb2e86ae35d8447293992576dd549471b294e4b
55dca62e858f1a44c2186774339823a301b48dc7
/code/my-app/functions/7/getCategory_ZeroOneNumberRule.java
5fcd7db3ebf57dc91466b86eef5109495fbe3303
[]
no_license
jwiszowata/code_reaper
4fff256250299225879d1412eb1f70b136d7a174
17dde61138cec117047a6ebb412ee1972886f143
refs/heads/master
2022-12-15T14:46:30.640628
2022-02-10T14:02:45
2022-02-10T14:02:45
84,747,455
0
0
null
2022-12-07T23:48:18
2017-03-12T18:26:11
Java
UTF-8
Java
false
false
160
java
public Category getCategory(double input) { if (input == 0 || input == 1) { return Category.one; } else { return Category.other; } }
331c706c368f647409980902ef1409b2955ae8cf
a2eeaa709e6a50572b9d80d85c02c2c2829f5be6
/98_validate_binary_search_tree/98_validate_binary_search_tree.java
27ef7d4b0f5207fd32cc9e639908cea31adc1ebc
[]
no_license
wht931011/leetcode
4f6e475417a5355f37cdcb557ce2a027340a5f04
404877b622d92109dca0c3176a84f115e7d21310
refs/heads/master
2021-01-24T02:45:15.212069
2017-01-19T03:19:15
2017-01-19T03:19:15
68,541,405
0
0
null
null
null
null
UTF-8
Java
false
false
942
java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ //first do binary tree inorder travasl and store it in a arraylist //then check whether it is increasing public class Solution { public boolean isValidBST(TreeNode root) { List<Integer> re = new ArrayList<>(); inOrder(root,re); if(re.size() == 1){ return true; } int previous = Integer.MIN_VALUE; for(int n = 0; n<re.size();n++){ if(n+1!=re.size()){ if(re.get(n) >= re.get(n+1)){ return false; } } } return true; } void inOrder(TreeNode root, List re){ if(root != null){ inOrder(root.left,re); re.add(root.val); inOrder(root.right,re); } } }
15b0409ff9b97212c72655584dabae17df065241
693f943e01c284cef93315eee90c0f114697376f
/src/main/java/com/example/wrapper/wrapperchechk/EmplyoeeController.java
c71e3dd6416d272df67ebf5b36b7c1aebe767a4c
[]
no_license
baderusslam/EmployeesSample
6eb5f2dab16337f3362bd01bb40e6d1f79f3ad24
886064df63f6b3876e517216cf39532a5b21976e
refs/heads/master
2023-04-21T03:06:46.680906
2021-04-16T11:44:33
2021-04-16T11:44:33
358,576,614
0
0
null
null
null
null
UTF-8
Java
false
false
605
java
package com.example.wrapper.wrapperchechk; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Arrays; import java.util.List; @RestController public class EmplyoeeController { @GetMapping(path = "/emp") public Employee getemplpyee(){ return new Employee(1,"ahmad"); } @GetMapping(path = "/emps") public Employees getemplpyees(){ Employees employees= new Employees(); employees.setEmployees(Arrays.asList(new Employee(1,"ahmad"))); return employees; } }
083551625bb4919068383a4c599ef90f4dae99fc
acf25d6beade19db09cf821643cd05a668d433fc
/source/src/main/java/ru/tsystems/tchallenge/service/security/token/TokenController.java
872cc4bb6c71bcbfeb6919bdec7890213ad05321
[]
no_license
kirillterekhov/tchallenge-service
c23f88151073f17776f4528a6558f88b7b45c99a
640710fafa7f4818d945415a671195faf2f66e1b
refs/heads/main
2023-06-10T01:06:18.503982
2021-07-06T18:45:18
2021-07-06T18:45:18
381,982,563
0
0
null
2021-07-01T09:40:14
2021-07-01T09:40:14
null
UTF-8
Java
false
false
3,586
java
package ru.tsystems.tchallenge.service.security.token; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.Authorization; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import ru.tsystems.tchallenge.service.reliability.exception.OperationException; import ru.tsystems.tchallenge.service.reliability.exception.OperationExceptionBuilder; import ru.tsystems.tchallenge.service.security.authentication.AuthenticationInvoice; import ru.tsystems.tchallenge.service.security.authentication.AuthenticationManager; import ru.tsystems.tchallenge.service.security.authentication.AuthenticationMethod; import ru.tsystems.tchallenge.service.security.authentication.UserAuthentication; import static ru.tsystems.tchallenge.service.reliability.exception.OperationExceptionType.ERR_INTERNAL; import static ru.tsystems.tchallenge.service.security.authentication.AuthenticationManager.getAuthentication; @RestController @RequestMapping("/security/tokens/") @Api(tags = "Sign in") public class TokenController { private final TokenFacade tokenFacade; private final AuthenticationManager authenticationManager; public TokenController(TokenFacade tokenFacade, AuthenticationManager authenticationManager) { this.tokenFacade = tokenFacade; this.authenticationManager = authenticationManager; } @PostMapping @ApiOperation(value = "Create new token by checking account log/password or using voucher", notes = "Token need to be attached to header to every authorized requests") public SecurityToken createToken(@RequestBody AuthenticationInvoice invoice) { UserAuthentication authentication; if (invoice.getMethod() == AuthenticationMethod.PASSWORD) { authentication = authenticationManager.authenticateByPassword(invoice); } else if (invoice.getMethod() == AuthenticationMethod.VOUCHER) { authentication = authenticationManager.authenticateByVoucher(invoice); } else if (invoice.getMethod() == AuthenticationMethod.GOOGLE) { authentication = authenticationManager.authenticateByGoogleToken(invoice); } else if (invoice.getMethod() == AuthenticationMethod.VK) { authentication = authenticationManager.authenticateByVK(invoice); } else { throw unknownAuthMethod(invoice.getMethod()); } return tokenFacade.createForCurrentAccount(authentication); } @GetMapping("validator") @ApiOperation("Check if token is valid and not expired") public boolean isValid() { return getAuthentication() != null; } @GetMapping("current") @ApiOperation(value = "Retrieve current token", authorizations = @Authorization(value = "bearer")) @PreAuthorize("authentication.authenticated") public SecurityToken getCurrent() { return tokenFacade.retrieveCurrent(getAuthentication()); } @DeleteMapping("current") @PreAuthorize("authentication.authenticated") @ApiOperation(value = "Delete current token", authorizations = @Authorization(value = "bearer")) public void deleteCurrent() { tokenFacade.deleteCurrent(getAuthentication()); } private OperationException unknownAuthMethod(AuthenticationMethod authMethod) { return OperationExceptionBuilder.operationException() .textcode(ERR_INTERNAL) .description("Unknown auth method") .attachment(authMethod) .build(); } }
7abcee733417512d09ccc2a4dc32258349b20efc
797dd6d2c570747618b26adadf04ba7d92260838
/src/main/java/com/mowmaster/pedestals/client/RenderPedestalOutline/RenderPedestalOutline.java
72ed2ce817ef80301721e2037a1591cc85f0d559
[]
no_license
Ridanisaurus/Pedestals
a7d118dc39ca272b3aa5e8a19451b7bbc77f72ff
73e0a9fac3dfd1f63d580e0f171c8176e3ebd882
refs/heads/1.16
2023-02-18T18:59:41.088258
2021-01-21T21:11:30
2021-01-21T21:11:30
329,657,032
0
0
null
2021-01-21T19:27:12
2021-01-14T15:33:15
Java
UTF-8
Java
false
false
15,032
java
package com.mowmaster.pedestals.client.RenderPedestalOutline; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.IVertexBuilder; import com.mowmaster.pedestals.blocks.PedestalBlock; import com.mowmaster.pedestals.item.ItemLinkingTool; import com.mowmaster.pedestals.item.ItemUpgradeTool; import com.mowmaster.pedestals.tiles.PedestalTileEntity; import net.minecraft.block.BlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.item.ItemStack; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.vector.Matrix4f; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.world.World; import net.minecraftforge.client.event.RenderWorldLastEvent; import java.util.List; import static net.minecraft.state.properties.BlockStateProperties.FACING; public class RenderPedestalOutline { public static void render(RenderWorldLastEvent event) { ClientPlayerEntity player = Minecraft.getInstance().player; ItemStack stack = (player.getHeldItemOffhand().getItem() instanceof ItemLinkingTool)?(player.getHeldItemOffhand()):(player.getHeldItemMainhand()); if (stack.isEnchanted() && stack.getItem() instanceof ItemLinkingTool) { ItemLinkingTool LT = (ItemLinkingTool) stack.getItem(); if(stack.hasTag()) { LT.getPosFromNBT(stack); BlockPos pos = LT.getStoredPosition(stack); List<BlockPos> storedRecievers = LT.getStoredPositionList(stack); locateTileEntities(player, event.getMatrixStack(),pos,storedRecievers); } } /*ItemStack stackUpgrade = (player.getHeldItemOffhand().getItem() instanceof ItemUpgradeTool)?(player.getHeldItemOffhand()):(player.getHeldItemMainhand()); if (stackUpgrade.isEnchanted() && stackUpgrade.getItem() instanceof ItemUpgradeTool) { ItemUpgradeTool UT = (ItemUpgradeTool) stackUpgrade.getItem(); if(stackUpgrade.hasTag()) { UT.getPosFromNBT(stack); BlockPos pos = UT.getStoredPosition(stack); if(player.getEntityWorld().getBlockState(pos).getBlock() instanceof PedestalBlock) { int[] getWorkArea = UT.getWorkPosFromNBT(stack); showWorkArea(player, event.getMatrixStack(),pos,getWorkArea); } } }*/ } public static BlockPos getNegRangePosEntity(World world, BlockPos posOfPedestal, int intWidth, int intHeight) { BlockState state = world.getBlockState(posOfPedestal); Direction enumfacing = state.get(FACING); BlockPos blockBelow = posOfPedestal; switch (enumfacing) { case UP: return blockBelow.add(-intWidth,0,-intWidth); case DOWN: return blockBelow.add(-intWidth,-intHeight,-intWidth); case NORTH: return blockBelow.add(-intWidth,-intWidth,-intHeight); case SOUTH: return blockBelow.add(-intWidth,-intWidth,0); case EAST: return blockBelow.add(0,-intWidth,-intWidth); case WEST: return blockBelow.add(-intHeight,-intWidth,-intWidth); default: return blockBelow; } } public static BlockPos getPosRangePosEntity(World world, BlockPos posOfPedestal, int intWidth, int intHeight) { BlockState state = world.getBlockState(posOfPedestal); Direction enumfacing = state.get(FACING); BlockPos blockBelow = posOfPedestal; switch (enumfacing) { case UP: return blockBelow.add(intWidth+1,intHeight,intWidth+1); case DOWN: return blockBelow.add(intWidth+1,0,intWidth+1); case NORTH: return blockBelow.add(intWidth+1,intWidth,0+1); case SOUTH: return blockBelow.add(intWidth+1,intWidth,intHeight+1); case EAST: return blockBelow.add(intHeight+1,intWidth,intWidth+1); case WEST: return blockBelow.add(0+1,intWidth,intWidth+1); default: return blockBelow; } } private static void blueLine(IVertexBuilder builder, Matrix4f positionMatrix, BlockPos pos, float dx1, float dy1, float dz1, float dx2, float dy2, float dz2) { builder.pos(positionMatrix, pos.getX()+dx1, pos.getY()+dy1, pos.getZ()+dz1) .color(0.95f, 0.95f, 0.95f, 1.0f) .endVertex(); builder.pos(positionMatrix, pos.getX()+dx2, pos.getY()+dy2, pos.getZ()+dz2) .color(0.95f, 0.95f, 0.95f, 1.0f) .endVertex(); } private static void areaLine(IVertexBuilder builder, Matrix4f positionMatrix, BlockPos pos, float dx1, float dy1, float dz1, float dx2, float dy2, float dz2) { builder.pos(positionMatrix, pos.getX()+dx1, pos.getY()+dy1, pos.getZ()+dz1) .color(1.0f, 0.0f, 0.0f, 1.0f) .endVertex(); builder.pos(positionMatrix, pos.getX()+dx2, pos.getY()+dy2, pos.getZ()+dz2) .color(1.0f, 0.0f, 0.0f, 1.0f) .endVertex(); } private static void workAreaLine(IVertexBuilder builder, Matrix4f positionMatrix, BlockPos pos, float dx1, float dy1, float dz1, float dx2, float dy2, float dz2) { builder.pos(positionMatrix, pos.getX()+dx1, pos.getY()+dy1, pos.getZ()+dz1) .color(0.0f, 1.0f, 0.0f, 1.0f) .endVertex(); builder.pos(positionMatrix, pos.getX()+dx2, pos.getY()+dy2, pos.getZ()+dz2) .color(0.0f, 1.0f, 0.0f, 1.0f) .endVertex(); } private static void locateTileEntities(ClientPlayerEntity player, MatrixStack matrixStack,BlockPos storedPos, List<BlockPos> storedRecievers) { IRenderTypeBuffer.Impl buffer = Minecraft.getInstance().getRenderTypeBuffers().getBufferSource(); IVertexBuilder builder = buffer.getBuffer(RenderPedestalType.OVERLAY_LINES); World world = player.getEntityWorld(); matrixStack.push(); Vector3d projectedView = Minecraft.getInstance().gameRenderer.getActiveRenderInfo().getProjectedView(); matrixStack.translate(-projectedView.x, -projectedView.y, -projectedView.z); Matrix4f matrix = matrixStack.getLast().getMatrix(); int locationsNum = storedRecievers.size(); for(int i=0;i<locationsNum;i++) { BlockPos pos = storedRecievers.get(i); if (world.getTileEntity(pos) != null) { blueLine(builder, matrix, pos, 0, 0, 0, 1, 0, 0); blueLine(builder, matrix, pos, 0, 1, 0, 1, 1, 0); blueLine(builder, matrix, pos, 0, 0, 1, 1, 0, 1); blueLine(builder, matrix, pos, 0, 1, 1, 1, 1, 1); blueLine(builder, matrix, pos, 0, 0, 0, 0, 0, 1); blueLine(builder, matrix, pos, 1, 0, 0, 1, 0, 1); blueLine(builder, matrix, pos, 0, 1, 0, 0, 1, 1); blueLine(builder, matrix, pos, 1, 1, 0, 1, 1, 1); blueLine(builder, matrix, pos, 0, 0, 0, 0, 1, 0); blueLine(builder, matrix, pos, 1, 0, 0, 1, 1, 0); blueLine(builder, matrix, pos, 0, 0, 1, 0, 1, 1); blueLine(builder, matrix, pos, 1, 0, 1, 1, 1, 1); } } if(world.getTileEntity(storedPos) != null){ if(world.getTileEntity(storedPos) instanceof PedestalTileEntity) { PedestalTileEntity pedestal = ((PedestalTileEntity)world.getTileEntity(storedPos)); int range = pedestal.getLinkingRange(); int zmax = range; int xmax = range; int ymax = range; //Just so we know the differnce from the original int lineLength = zmax + xmax+1; int lineLength2 = zmax + xmax+1; areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), 0, 0, 0,-lineLength, 0, 0); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), 0, -lineLength, 0,-lineLength, -lineLength, 0); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), 0, 0, -lineLength,-lineLength, 0, -lineLength); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), 0, -lineLength, -lineLength,-lineLength, -lineLength, -lineLength); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), 0, 0, 0, 0, 0, -lineLength); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), -lineLength, 0, 0, -lineLength, 0, -lineLength); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), 0, -lineLength, 0, 0, -lineLength, -lineLength); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), -lineLength, -lineLength, 0, -lineLength, -lineLength, -lineLength); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), 0, 0, 0, 0, -lineLength, 0); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), -lineLength, 0, 0, -lineLength, -lineLength, 0); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), 0, 0, -lineLength, 0, -lineLength, -lineLength); areaLine(builder, matrix, storedPos.add(xmax+1,ymax+1,zmax+1), -lineLength, 0, -lineLength, -lineLength, -lineLength, -lineLength); } } /*for (int dx = -10; dx <= 10; dx++) { for (int dy = -10; dy <= 10; dy++) { for (int dz = -10; dz <= 10; dz++) { pos.setPos(px + dx, py + dy, pz + dz); if (world.getTileEntity(pos) != null) { blueLine(builder, matrix, pos, 0, 0, 0, 1, 0, 0); blueLine(builder, matrix, pos, 0, 1, 0, 1, 1, 0); blueLine(builder, matrix, pos, 0, 0, 1, 1, 0, 1); blueLine(builder, matrix, pos, 0, 1, 1, 1, 1, 1); blueLine(builder, matrix, pos, 0, 0, 0, 0, 0, 1); blueLine(builder, matrix, pos, 1, 0, 0, 1, 0, 1); blueLine(builder, matrix, pos, 0, 1, 0, 0, 1, 1); blueLine(builder, matrix, pos, 1, 1, 0, 1, 1, 1); blueLine(builder, matrix, pos, 0, 0, 0, 0, 1, 0); blueLine(builder, matrix, pos, 1, 0, 0, 1, 1, 0); blueLine(builder, matrix, pos, 0, 0, 1, 0, 1, 1); blueLine(builder, matrix, pos, 1, 0, 1, 1, 1, 1); } } } }*/ matrixStack.pop(); RenderSystem.disableDepthTest(); buffer.finish(RenderPedestalType.OVERLAY_LINES); } private static void showWorkArea(ClientPlayerEntity player, MatrixStack matrixStack,BlockPos storedPos, int[] workArea) { IRenderTypeBuffer.Impl buffer = Minecraft.getInstance().getRenderTypeBuffers().getBufferSource(); IVertexBuilder builder = buffer.getBuffer(RenderPedestalType.OVERLAY_LINES); World world = player.getEntityWorld(); matrixStack.push(); Vector3d projectedView = Minecraft.getInstance().gameRenderer.getActiveRenderInfo().getProjectedView(); matrixStack.translate(-projectedView.x, -projectedView.y, -projectedView.z); Matrix4f matrix = matrixStack.getLast().getMatrix(); if(world.getTileEntity(storedPos) != null){ if(world.getTileEntity(storedPos) instanceof PedestalTileEntity) { int z = workArea[2]; int x = workArea[0]; int y = workArea[1]; BlockState state = world.getBlockState(storedPos); Direction enumfacing = state.get(FACING); BlockPos negBlock = getNegRangePosEntity(world,storedPos,z,y); BlockPos posBlock = getPosRangePosEntity(world,storedPos,z,y); /*switch (enumfacing) { case UP: case DOWN: case NORTH: case SOUTH: case EAST: case WEST: default: negBlock.add(0,0,0); posBlock.add(0,0,0); }*/ int xdiff = posBlock.getX() - negBlock.getX(); int ydiff = posBlock.getY() - negBlock.getY(); int zdiff = posBlock.getZ() - negBlock.getZ(); System.out.print(xdiff); System.out.print(" x "); System.out.print(ydiff); System.out.print(" x "); System.out.print(zdiff); int lineLength = zdiff + xdiff+1; int lineLength2 = zdiff + xdiff+1; workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff,zdiff+1), 0, 0, 0,-lineLength, 0, 0); workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff,zdiff+1), 0, lineLength, 0,-lineLength, lineLength, 0); workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff,zdiff+1), 0, 0, -lineLength,-lineLength, 0, -lineLength); workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff,zdiff+1), 0, lineLength, -lineLength,-lineLength, lineLength, -lineLength); //workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff+1,zdiff+1), 0, 0, 0, 0, 0, -lineLength); //workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff+1,zdiff+1), -lineLength, 0, 0, -lineLength, 0, -lineLength); //workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff+1,zdiff+1), 0, -lineLength, 0, 0, -lineLength, -lineLength); //workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff+1,zdiff+1), -lineLength, -lineLength, 0, -lineLength, -lineLength, -lineLength); //workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff+1,zdiff+1), 0, 0, 0, 0, -lineLength, 0); //workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff+1,zdiff+1), -lineLength, 0, 0, -lineLength, -lineLength, 0); //workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff+1,zdiff+1), 0, 0, -lineLength, 0, -lineLength, -lineLength); //workAreaLine(builder, matrix, negBlock.add(xdiff+1,ydiff+1,zdiff+1), -lineLength, 0, -lineLength, -lineLength, -lineLength, -lineLength); } } matrixStack.pop(); RenderSystem.disableDepthTest(); buffer.finish(RenderPedestalType.OVERLAY_LINES); } }
4476f38f60769242db4b4c9bd897ac2311dd72ab
95cb5e35c1cd39377bda0d78fbef73708d4b666a
/vulpe-framework/annotations/src/main/java/org/vulpe/config/annotations/VulpeUpload.java
cf87e47645dd2e5c997648cbfefcf6cc1347113b
[]
no_license
RiusmaX/vulpe
d8532032fdcb1b9cb539a80291eb1ea2ad1f0d1a
cbc96b921dc201dac27f2b99d04de4a8c93b9243
refs/heads/master
2016-08-08T04:49:36.330106
2013-10-30T23:06:32
2013-10-30T23:06:32
42,253,906
0
0
null
null
null
null
UTF-8
Java
false
false
2,361
java
/** * Vulpe Framework - Quick and Smart ;) * Copyright (C) 2011 Active Thread * * Este programa é software livre; você pode redistribuí-lo e/ou * modificá-lo sob os termos da Licença Pública Geral GNU, conforme * publicada pela Free Software Foundation; tanto a versão 2 da * Licença como (a seu critério) qualquer versão mais nova. * * Este programa é distribuído na expectativa de ser útil, mas SEM * QUALQUER GARANTIA; sem mesmo a garantia implícita de * COMERCIALIZAÇÃO ou de ADEQUAÇÃO A QUALQUER PROPÓSITO EM * PARTICULAR. Consulte a Licença Pública Geral GNU para obter mais * detalhes. * * Você deve ter recebido uma cópia da Licença Pública Geral GNU * junto com este programa; se não, escreva para a Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /** * Vulpe Framework - Quick and Smart ;) * Copyright (C) 2011 Active Thread * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.vulpe.config.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface VulpeUpload { /** * Max Width to Image upload. */ int maxWidthImageUpload() default 640; /** * Maximum size in Megabyte. Default 2. */ int maximumSize() default 2; /** * Sets the allowed mimetypes. A comma-delimited list of types. */ String allowedTypes() default "*"; }
4c2e7c3e06b0045f0c892bb6e39fa7857c8b8ab4
31adfb488d650ceeb4f2b893b9a94747ce356805
/src/tests/TestDriver.java
645e51b0b18e5e500efb707b3338e64685427023
[]
no_license
aliiitarek/Buffer-Manager
c0747b988d10699a56cec3f013936a8dbe8429c8
261f1e107b25e15fe760432b6db041eca99d054b
refs/heads/master
2016-09-11T06:46:02.557984
2014-10-01T12:43:44
2014-10-01T12:43:44
24,677,728
2
0
null
null
null
null
UTF-8
Java
false
false
6,363
java
package tests; import java.io.*; import java.util.*; import java.lang.*; import chainexception.*; // Major Changes: // 1. Change the return type of test() functions from 'int' to 'boolean' // to avoid defining static int TRUE/FALSE, which makes it easier for // derived functions to return the right type. // 2. Function runTest is not implemented to avoid dealing with function // pointers. Instead, it's flattened in runAllTests() function. // 3. Change // Status TestDriver::runTests() // Status TestDriver::runAllTests() // to // public boolean runTests(); // protected boolean runAllTests(); /** * TestDriver class is a base class for various test driver * objects. * <br> * Note that the code written so far is very machine dependent. It assumes * the users are on UNIX system. For example, in function runTests, a UNIX * command is called to clean up the working directories. * */ public class TestDriver { public final static boolean OK = true; public final static boolean FAIL = false; protected String dbpath; protected String logpath; /** * TestDriver Constructor * * @param nameRoot The name of the test being run */ protected TestDriver (String nameRoot) { // sprintf( dbpath, MINIBASE_DB, nameRoot, getpid() ); // sprintf( logpath, MINIBASE_LOG, nameRoot, getpid() ); //NOTE: Assign random numbers to the dbpath doesn't work because //we can never open the same database again if everytime we are //given a different number. //To port it to a different platform, get "user.name" should //still work well because this feature is not meant to be UNIX //dependent. //FOR MAC OSX // dbpath = "/Users/AlyTarek/Documents/Paths of BufMng/db"; // logpath = "/Users/AlyTarek/Documents/Paths of BufMng/log"; //FOR LINUX dbpath = "/tmp/"+nameRoot+System.getProperty("user.name")+".minibase-db"; logpath = "/tmp/"+nameRoot +System.getProperty("user.name")+".minibase-log"; } /** * Another Constructor */ protected TestDriver () {} /** * @return whether the test has completely successfully */ protected boolean test1 () { return true; } /** * @return whether the test has completely successfully */ protected boolean test2 () { return true; } /** * @return whether the test has completely successfully */ protected boolean test3 () { return true; } /** * @return whether the test has completely successfully */ protected boolean test4 () { return true; } /** * @return whether the test has completely successfully */ protected boolean test5 () { return true; } /** * @return whether the test has completely successfully */ protected boolean test6 () { return true; } /** * @return <code>String</code> object which contains the name of the test */ protected String testName() { //A little reminder to subclassers return "*** unknown ***"; } /** * This function does the preparation/cleaning work for the * running tests. * * @return a boolean value indicates whether ALL the tests have passed */ public boolean runTests () { System.out.println ("\n" + "Running " + testName() + " tests...." + "\n"); // Kill anything that might be hanging around String newdbpath; String newlogpath; String remove_logcmd; String remove_dbcmd; String remove_cmd = "/bin/rm -rf "; newdbpath = dbpath; newlogpath = logpath; remove_logcmd = remove_cmd + logpath; remove_dbcmd = remove_cmd + dbpath; // Commands here is very machine dependent. We assume // user are on UNIX system here try { Runtime.getRuntime().exec(remove_logcmd); Runtime.getRuntime().exec(remove_dbcmd); } catch (IOException e) { System.err.println (""+e); } remove_logcmd = remove_cmd + newlogpath; remove_dbcmd = remove_cmd + newdbpath; //This step seems redundant for me. But it's in the original //C++ code. So I am keeping it as of now, just in case I //I missed something try { Runtime.getRuntime().exec(remove_logcmd); Runtime.getRuntime().exec(remove_dbcmd); } catch (IOException e) { System.err.println (""+e); } //Run the tests. Return type different from C++ boolean _pass = runAllTests(); //Clean up again try { Runtime.getRuntime().exec(remove_logcmd); Runtime.getRuntime().exec(remove_dbcmd); } catch (IOException e) { System.err.println (""+e); } System.out.println ("\n" + "..." + testName() + " tests "); System.out.print (_pass==OK ? "completely successfully" : "failed"); System.out.println (".\n\n"); return _pass; } protected boolean runAllTests() { boolean _passAll = OK; //The following code checks whether appropriate erros have been logged, //which, if implemented, should be done for each test case. //minibase_errors.clear_errors(); //int result = test(); //if ( !result || minibase_errors.error() ) { // status = FAIL; // if ( minibase_errors.error() ) // cerr << (result? "*** Unexpected error(s) logged, test failed:\n" // : "Errors logged:\n"); // minibase_errors.show_errors(cerr); //} //The following runs all the test functions without checking //the logged error types. //Running test1() to test6() if (!test1()) { _passAll = FAIL; } if (!test2()) { _passAll = FAIL; } if (!test3()) { _passAll = FAIL; } if (!test4()) { _passAll = FAIL; } if (!test5()) { _passAll = FAIL; } if (!test6()) { _passAll = FAIL; } return _passAll; } /** * Used to verify whether the exception thrown from * the bottom layer is the one expected. */ public boolean checkException (ChainException e, String expectedException) { boolean notCaught = true; while (true) { String exception = e.getClass().getName(); if (exception.equals(expectedException)) { return (!notCaught); } if ( e.prev==null ) { return notCaught; } e = (ChainException)e.prev; } } // end of checkException } // end of TestDriver
6db88f7e7b7511fccbbd2f306572b17009a61a9a
b3e32f230ff50636df0a56ffa092f21b82171439
/netty-private-protocol/src/main/java/org/lwl/netty/constant/ProtocolConstant.java
ec4c98a6c5df789e6a42bfdfdeaf59c949c5abaa
[ "Apache-2.0" ]
permissive
phial3/netty-learning-1
8998d887d5186955a582c76b60e0254badb7818b
739323d31ff2a81879bc0e624606f5562a753541
refs/heads/master
2022-01-12T09:21:31.063852
2019-04-28T12:37:38
2019-04-28T12:37:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,439
java
package org.lwl.netty.constant; import org.lwl.netty.config.ProtocolConfig; /** * @author thinking_fioa * @createTime 2018/4/22 * @description 私有协议中配置的信息 */ public final class ProtocolConstant { // can't use private ProtocolConstant() { throw new IllegalAccessError("static class, can not use constructor."); } /** * @link LengthFieldBasedFrameDecoder} 使用的参数. * 最大消息字节数。4K = 4 * 1024 */ private static final int MAX_FRAMELENGTH = ProtocolConfig.getPkgMaxLen(); private static final int LENGTH_FIELD_OFFSET = 0; private static final int LENGTHFIELD_LENGTH = 4; private static final int LENGTH_ADJUSTMENT = -4; private static final int INITIAL_BYTES_TO_STRIP = 0; /** * 序列化/反序列化方式 */ private static final String CODEC_TYPE = MessageCodecTypeEnum.KRYO.getCodecType(); public static int getMaxFramelength() { return MAX_FRAMELENGTH; } public static int getLengthFieldOffset() { return LENGTH_FIELD_OFFSET; } public static int getLengthfieldLength() { return LENGTHFIELD_LENGTH; } public static int getLengthAdjustment() { return LENGTH_ADJUSTMENT; } public static int getInitialBytesToStrip() { return INITIAL_BYTES_TO_STRIP; } public static String getCodecType() { return CODEC_TYPE; } }
cfa8f5878f44c5e82f92dc43b5eb891345f14000
837c6edcb521d7ce7d828de1c3ce2dc89615172b
/后端/src/main/java/com/example/library/controller/BorrowBooksController.java
a7a2a2211005b2aa16aeb2d957f9b655c96926f6
[]
no_license
Frank520lang/library
741821e4d63f1eb2f21cf7c12cd6085b0466bece
6645aaa6ade137843eef94a8656dade4d16083f1
refs/heads/main
2023-02-10T15:33:10.283745
2020-12-23T06:53:21
2020-12-23T06:53:21
323,823,085
0
0
null
null
null
null
UTF-8
Java
false
false
2,894
java
package com.example.library.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSON; import com.example.library.beans.CurrBooks; import com.example.library.beans.User; import com.example.library.exception.CustomizeErrorCode; import com.example.library.exception.CustomizeException; import com.example.library.pojo.HistoryQueryWithPage; import com.example.library.pojo.PaginationWithBooks; import com.example.library.pojo.StateMessage; import com.example.library.service.CurrentService; import com.example.library.service.HistoryService; import com.example.library.service.UserService; @RestController public class BorrowBooksController { @Resource private HistoryService historyService; @Resource private CurrentService currentService; @Resource private UserService userService; @PostMapping("/borrowBooks") public StateMessage borrowBooks(@RequestBody String str, HttpServletRequest request) throws CustomizeException { CurrBooks currBooks = JSON.parseObject(str, CurrBooks.class); userService.preHandle(request, currBooks.getAccountId()); User user = (User) request.getSession().getAttribute("user"); if (user == null) { throw new CustomizeException(CustomizeErrorCode.NO_LOGIN); } long sum = currentService.getCurrentCount(currBooks); StateMessage stateMessage = new StateMessage(); if(sum >= 3) { stateMessage.setState("500"); stateMessage.setMessage("您已经借了三本书了!!"); return stateMessage; }else { currentService.doBorrow(currBooks); // historyService.inserHistory(currBooks); stateMessage.setState("200"); stateMessage.setMessage("借书成功!!"); } return stateMessage; } @PostMapping("/allBook") public PaginationWithBooks getAllBook(@RequestBody String str, HttpServletRequest request){ // User user = (User) request.getSession().getAttribute("user"); // if (user == null) { // throw new CustomizeException(CustomizeErrorCode.NO_LOGIN); //// return ResultDTO.errorOf(CustomizeErrorCode.NO_LOGIN); // } // System.out.println(accountId + " " + page); System.out.println(str); HistoryQueryWithPage historyQueryWithPage = JSON.parseObject(str, HistoryQueryWithPage.class); userService.preHandle(request, historyQueryWithPage.getAccountId()); User user = (User) request.getSession().getAttribute("user"); if (user == null) { throw new CustomizeException(CustomizeErrorCode.NO_LOGIN); } PaginationWithBooks paginationWithBooks = currentService.getAllBookWithState(historyQueryWithPage); return paginationWithBooks; } }
6ded44642c41b0250ca23d33d45df789bbb23216
e85a61d5882a9c291c61e217b5668a8ba38a587e
/app/src/main/java/ar/com/syswork/sysmobile/psincronizar/LogicaSincronizacion.java
5a4f4e1be3dc1839f405c18307eae25ed5e440ba
[]
no_license
sysworkorg/SysMobile
5f5ff7d9d329f4d3d1341080c215ee6a3a750e33
17bbd7b8ebabf9ae7d4c83770adfb672581a8a4b
refs/heads/master
2021-01-11T06:04:37.618039
2016-11-01T12:33:38
2016-11-01T12:33:38
72,534,101
0
1
null
null
null
null
UTF-8
Java
false
false
12,270
java
package ar.com.syswork.sysmobile.psincronizar; import java.util.ArrayList; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Handler.Callback; import android.os.Handler; import android.os.Message; import android.util.Log; import ar.com.syswork.sysmobile.R; import ar.com.syswork.sysmobile.daos.DaoVendedor; import ar.com.syswork.sysmobile.daos.DataManager; import ar.com.syswork.sysmobile.entities.Registro; import ar.com.syswork.sysmobile.shared.AppSysMobile; import ar.com.syswork.sysmobile.util.Utilidades; public class LogicaSincronizacion implements Callback{ private PantallaManagerSincronizacion pantallaManagerSincronizacion; private ThreadPoolExecutor executor; private ThreadSincronizacion ts; private ArrayList<Registro> listaRegistros; private String jSonRegistrosTablas; private ArrayList<String> alJsonArticulos; private String jSonArticulos; private ArrayList<String> alJsonClientes; private String jSonClientes; private int paginasClientes; private int paginasArticulos; private String jSonVendedores; private String jSonRubros; private String jSonDepositos; private boolean huboErrores; private Activity a; private int completadas=0; private String strErrorDeComunicacion; private String strDescargaExitosa; private String strDescargando; private String strConectando; private String strErrorDeConexionAlWebService; private String strIntentandoConectarAlWebService; private AppSysMobile app; private DataManager dm; private DaoVendedor daoVendedor; private int cantVendedores; private final int OBTENER_REGISTROS = 1; private final int OBTENER_JSONS = 2; private int tipoLlamada; public LogicaSincronizacion (Activity a) { this.a = a; executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1) ; this.strErrorDeComunicacion = this.a.getString(R.string.seProdujoUnErrorDeComunicacion); this.strDescargaExitosa = this.a.getString(R.string.descarga_exitosa); this.strConectando = this.a.getString(R.string.conectando); this.strDescargando = this.a.getString(R.string.descargando); this.strErrorDeConexionAlWebService = this.a.getString(R.string.errorDeConexionAlWebService); this.strIntentandoConectarAlWebService = this.a.getString(R.string.strIntentandoConectarAlWebService); app = (AppSysMobile) a.getApplication(); dm = app.getDataManager(); daoVendedor = dm.getDaoVendedor(); setCantVendedores(daoVendedor.getCount()); } public void sincronizar() { pantallaManagerSincronizacion.seteaBotonSincronizarVisible(false); pantallaManagerSincronizacion.seteaPrgEstadoConexionVisible(true); pantallaManagerSincronizacion.seteaTxtEstadoConexionVisible(true); pantallaManagerSincronizacion.seteaTxtEstadoConexion(strIntentandoConectarAlWebService); tipoLlamada = OBTENER_REGISTROS; Handler h = new Handler(this); ThreadSincronizacion tc = new ThreadSincronizacion(h,AppSysMobile.WS_REGISTROS,0); Thread t = new Thread(tc); t.start(); } public void obtenerJsonsYProcesar() { jSonArticulos= ""; alJsonArticulos = new ArrayList<String>(); alJsonArticulos.clear(); alJsonClientes = new ArrayList<String>(); alJsonClientes.clear(); jSonVendedores = ""; jSonRubros = ""; jSonDepositos = ""; jSonClientes = ""; tipoLlamada = OBTENER_JSONS; Log.d("SW","Entra en Obtener Json"); huboErrores = false; Handler h = new Handler(this); pantallaManagerSincronizacion.muestraDialogoSincronizacion(); for (int pos = 0; (pos < listaRegistros.size()); pos++) { if (listaRegistros.get(pos).getTabla().equals("wsSysMobileDepositos")) { //pantallaManagerSincronizacion.seteatxtResultadoRubros(strConectando); ts = new ThreadSincronizacion(h,AppSysMobile.WS_DEPOSITOS,0); executor.execute(ts); Log.d("SW","Lanza Thread Depositos"); } if (listaRegistros.get(pos).getTabla().equals("wsSysMobileRubros")) { pantallaManagerSincronizacion.seteatxtResultadoRubros(strConectando); ts = new ThreadSincronizacion(h,AppSysMobile.WS_RUBROS,0); Log.d("SW","Lanza Thread Rubros"); executor.execute(ts); } if (listaRegistros.get(pos).getTabla().equals("wsSysMobileVendedores")) { pantallaManagerSincronizacion.seteatxtResultadoVendedores(strConectando); ts = new ThreadSincronizacion(h,AppSysMobile.WS_VENDEDORES,0); Log.d("SW","Lanza Thread Vendedores"); executor.execute(ts); } if (listaRegistros.get(pos).getTabla().equals("wsSysMobileArticulos")) { Log.d("SW","Lanza Thread Articulos // paginas:" + listaRegistros.get(pos).getPaginas()); for (int pagina = 1; pagina<= listaRegistros.get(pos).getPaginas(); pagina++) { pantallaManagerSincronizacion.seteaTxtResultadoArticulos(strConectando); ts = new ThreadSincronizacion(h,AppSysMobile.WS_ARTICULOS,pagina); Log.d("SW","Ejecuta Thread bajar pagina: " + pagina + " de Articulos"); executor.execute(ts); } } if (listaRegistros.get(pos).getTabla().equals("wsSysMobileClientes")) { for (int pagina = 1; pagina<= listaRegistros.get(pos).getPaginas(); pagina++) { pantallaManagerSincronizacion.seteatxtResultadoClientes(strConectando); ts = new ThreadSincronizacion(h,AppSysMobile.WS_CLIENTES,pagina); Log.d("SW","Ejecuta Thread bajar pagina: " + pagina + " de Clientes"); executor.execute(ts); } } } } @Override public boolean handleMessage(Message msg) { String resultado ; if (tipoLlamada == OBTENER_REGISTROS) { if (msg.arg1 == AppSysMobile.WS_RECIBE_DATOS) { resultado = (String) msg.obj; jSonRegistrosTablas = resultado; AppSysMobile.setRegistrosPaginacion(100); parseaCantidadRegistros(); paginasClientes = obtienePaginasTabla("wsSysMobileClientes"); paginasArticulos = obtienePaginasTabla("wsSysMobileArticulos"); obtenerJsonsYProcesar(); } else { resultado = (String) msg.obj; pantallaManagerSincronizacion.seteaTxtEstadoConexion(strErrorDeConexionAlWebService + " " + resultado); pantallaManagerSincronizacion.seteaBotonSincronizarVisible(true); pantallaManagerSincronizacion.seteaPrgEstadoConexionVisible(false); } } else { switch (msg.arg1) { // RECIBO DATOS case AppSysMobile.WS_RECIBE_DATOS: resultado = (String) msg.obj; switch (msg.arg2) { case AppSysMobile.WS_DEPOSITOS: jSonDepositos = resultado; //pantallaManagerSincronizacion.seteatxtResultadoRubros(strDescargaExitosa); //pantallaManagerSincronizacion.seteaValorChkRubros(true); break; case AppSysMobile.WS_RUBROS: jSonRubros = resultado; pantallaManagerSincronizacion.seteatxtResultadoRubros(strDescargaExitosa); pantallaManagerSincronizacion.seteaValorChkRubros(true); break; case AppSysMobile.WS_VENDEDORES: jSonVendedores= resultado; pantallaManagerSincronizacion.seteatxtResultadoVendedores(strDescargaExitosa); pantallaManagerSincronizacion.seteaValorChkVendedores(true); break; case AppSysMobile.WS_ARTICULOS: jSonArticulos= resultado; alJsonArticulos.add(jSonArticulos); pantallaManagerSincronizacion.seteaTxtResultadoArticulos(strDescargando + " " + Utilidades.obtienePorcentaje(paginasArticulos,alJsonArticulos.size()) + " %"); if (paginasArticulos == alJsonArticulos.size()) { pantallaManagerSincronizacion.seteaTxtResultadoArticulos(strDescargaExitosa); pantallaManagerSincronizacion.seteaValorChkArticulos(true); } break; case AppSysMobile.WS_CLIENTES: jSonClientes= resultado; alJsonClientes.add(jSonClientes); pantallaManagerSincronizacion.seteatxtResultadoClientes(strDescargando + " " + Utilidades.obtienePorcentaje(paginasClientes,alJsonClientes.size()) + " %"); if (paginasClientes == alJsonClientes.size()) { pantallaManagerSincronizacion.seteatxtResultadoClientes(strDescargaExitosa); pantallaManagerSincronizacion.seteaValorChkClientes(true); } break; } break; case AppSysMobile.WS_RECIBE_ERRORES: // RECIBO ERRORES resultado = (String) msg.obj; huboErrores=true; executor.shutdownNow(); switch (msg.arg2) { case AppSysMobile.WS_RUBROS: Log.d("SW","error rubros"); pantallaManagerSincronizacion.seteatxtResultadoRubros(strErrorDeComunicacion + " (" + resultado + ")"); break; case AppSysMobile.WS_DEPOSITOS: Log.d("SW","error depositos"); //pantallaManagerSincronizacion.seteatxtResultadoRubros(strErrorDeComunicacion + " (" + resultado + ")"); break; case AppSysMobile.WS_VENDEDORES: Log.d("SW","error vendedores"); pantallaManagerSincronizacion.seteatxtResultadoVendedores(strErrorDeComunicacion + " (" + resultado + ")"); break; case AppSysMobile.WS_ARTICULOS: Log.d("SW","error articulos"); pantallaManagerSincronizacion.seteaTxtResultadoArticulos(strErrorDeComunicacion + " (" + resultado + ")"); break; case AppSysMobile.WS_CLIENTES: Log.d("SW","error clientes"); pantallaManagerSincronizacion.seteatxtResultadoClientes(strErrorDeComunicacion + " (" + resultado + ")"); break; } break; } completadas++; Log.d("SW","completadas:" + completadas + " de " + executor.getTaskCount()); if ((executor.getTaskCount()== completadas) || huboErrores) { if (huboErrores) { // NO PARSEO NADA. ASI QUE PERMITO QUE CIERRE LA PANTALLA pantallaManagerSincronizacion.setVisibleBtnCerrarSincronizacion(true); pantallaManagerSincronizacion.seteaImgSincronizarVisible(true); pantallaManagerSincronizacion.seteaProgressBarVisible(false); } else { // PROCESO LOS JSON'S RECIBIDOS ProcesaJson procesaJson = new ProcesaJson(this.a); procesaJson.setPantallaManager(pantallaManagerSincronizacion); procesaJson.setalJsonClientes(alJsonClientes); procesaJson.setalJsonArticulos(alJsonArticulos); procesaJson.setjSonRubros(jSonRubros); procesaJson.setjSonVendedores(jSonVendedores); procesaJson.setjSonDepositos(jSonDepositos); procesaJson.procesarJson(); } } } return false; } public void setPantallaManager(PantallaManagerSincronizacion pantallaManagerSincronizacion) { this.pantallaManagerSincronizacion = pantallaManagerSincronizacion; } public boolean huboErroes() { return this.huboErrores; } public int getCantVendedores() { return cantVendedores; } public void setCantVendedores(int cantVendedores) { this.cantVendedores = cantVendedores; } public void parseaCantidadRegistros() { listaRegistros = new ArrayList<Registro>(); listaRegistros.clear(); JSONArray arrayJson; JSONObject jsObject; try { arrayJson = new JSONArray(jSonRegistrosTablas); for (int x = 0; x < arrayJson.length() ;x++) { jsObject = arrayJson.getJSONObject(x); Registro registro = new Registro(); registro.setTabla(jsObject.getString("tabla")); registro.setCantidadRegistros(jsObject.getLong("cantidadRegistros")); registro.setPaginas((int) (registro.getCantidadRegistros() / AppSysMobile.getRegistrosPaginacion())); if ((registro.getCantidadRegistros() % AppSysMobile.getRegistrosPaginacion()) > 0) registro.setPaginas(registro.getPaginas() + 1); listaRegistros.add(registro); } } catch(JSONException e) { e.printStackTrace(); } } private int obtienePaginasTabla(String tabla) { for (int pos = 0; pos < listaRegistros.size() ; pos++) { if (listaRegistros.get(pos).getTabla().equals(tabla)) { return listaRegistros.get(pos).getPaginas(); } } return 0; } }
ab4efdb9f07c060427b582b685569d27963097a1
0af8b92686a58eb0b64e319b22411432aca7a8f3
/large-multiproject/project32/src/main/java/org/gradle/test/performance32_3/Production32_218.java
cb4a4c9889b773a0bed0cf2a2b08c4e3639c8e08
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
305
java
package org.gradle.test.performance32_3; public class Production32_218 extends org.gradle.test.performance13_3.Production13_218 { private final String property; public Production32_218() { this.property = "foo"; } public String getProperty() { return property; } }
b48db8ce68412235380f738b62b8c069257dd572
d71e879b3517cf4fccde29f7bf82cff69856cfcd
/ExtractedJars/Shopkick_com.shopkick.app/javafiles/com/facebook/share/model/AppInviteContent$Builder.java
0de9c2c0ea781a36895d0222b69563a31525090c
[ "MIT" ]
permissive
Andreas237/AndroidPolicyAutomation
b8e949e072d08cf6c6166c3f15c9c63379b8f6ce
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
refs/heads/master
2020-04-10T02:14:08.789751
2019-05-16T19:29:11
2019-05-16T19:29:11
160,739,088
5
1
null
null
null
null
UTF-8
Java
false
false
15,205
java
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.facebook.share.model; import android.text.TextUtils; // Referenced classes of package com.facebook.share.model: // ShareModelBuilder, AppInviteContent, ShareModel public static class AppInviteContent$Builder implements ShareModelBuilder { public static final class Destination extends Enum { public static Destination valueOf(String s) { return (Destination)Enum.valueOf(com/facebook/share/model/AppInviteContent$Builder$Destination, s); // 0 0:ldc1 #2 <Class AppInviteContent$Builder$Destination> // 1 2:aload_0 // 2 3:invokestatic #50 <Method Enum Enum.valueOf(Class, String)> // 3 6:checkcast #2 <Class AppInviteContent$Builder$Destination> // 4 9:areturn } public static Destination[] values() { return (Destination[])((Destination []) ($VALUES)).clone(); // 0 0:getstatic #37 <Field AppInviteContent$Builder$Destination[] $VALUES> // 1 3:invokevirtual #57 <Method Object _5B_Lcom.facebook.share.model.AppInviteContent$Builder$Destination_3B_.clone()> // 2 6:checkcast #53 <Class AppInviteContent$Builder$Destination[]> // 3 9:areturn } public boolean equalsName(String s) { if(s == null) //* 0 0:aload_1 //* 1 1:ifnonnull 6 return false; // 2 4:iconst_0 // 3 5:ireturn else return name.equals(((Object) (s))); // 4 6:aload_0 // 5 7:getfield #43 <Field String name> // 6 10:aload_1 // 7 11:invokevirtual #65 <Method boolean String.equals(Object)> // 8 14:ireturn } public String toString() { return name; // 0 0:aload_0 // 1 1:getfield #43 <Field String name> // 2 4:areturn } private static final Destination $VALUES[]; public static final Destination FACEBOOK; public static final Destination MESSENGER; private final String name; static { FACEBOOK = new Destination("FACEBOOK", 0, "facebook"); // 0 0:new #2 <Class AppInviteContent$Builder$Destination> // 1 3:dup // 2 4:ldc1 #22 <String "FACEBOOK"> // 3 6:iconst_0 // 4 7:ldc1 #24 <String "facebook"> // 5 9:invokespecial #28 <Method void AppInviteContent$Builder$Destination(String, int, String)> // 6 12:putstatic #30 <Field AppInviteContent$Builder$Destination FACEBOOK> MESSENGER = new Destination("MESSENGER", 1, "messenger"); // 7 15:new #2 <Class AppInviteContent$Builder$Destination> // 8 18:dup // 9 19:ldc1 #31 <String "MESSENGER"> // 10 21:iconst_1 // 11 22:ldc1 #33 <String "messenger"> // 12 24:invokespecial #28 <Method void AppInviteContent$Builder$Destination(String, int, String)> // 13 27:putstatic #35 <Field AppInviteContent$Builder$Destination MESSENGER> $VALUES = (new Destination[] { FACEBOOK, MESSENGER }); // 14 30:iconst_2 // 15 31:anewarray Destination[] // 16 34:dup // 17 35:iconst_0 // 18 36:getstatic #30 <Field AppInviteContent$Builder$Destination FACEBOOK> // 19 39:aastore // 20 40:dup // 21 41:iconst_1 // 22 42:getstatic #35 <Field AppInviteContent$Builder$Destination MESSENGER> // 23 45:aastore // 24 46:putstatic #37 <Field AppInviteContent$Builder$Destination[] $VALUES> //* 25 49:return } private Destination(String s, int i, String s1) { super(s, i); // 0 0:aload_0 // 1 1:aload_1 // 2 2:iload_2 // 3 3:invokespecial #41 <Method void Enum(String, int)> name = s1; // 4 6:aload_0 // 5 7:aload_3 // 6 8:putfield #43 <Field String name> // 7 11:return } } private boolean isAlphanumericWithSpaces(String s) { for(int i = 0; i < s.length(); i++) //* 0 0:iconst_0 //* 1 1:istore_3 //* 2 2:iload_3 //* 3 3:aload_1 //* 4 4:invokevirtual #51 <Method int String.length()> //* 5 7:icmpge 46 { char c = s.charAt(i); // 6 10:aload_1 // 7 11:iload_3 // 8 12:invokevirtual #55 <Method char String.charAt(int)> // 9 15:istore_2 if(!Character.isDigit(c) && !Character.isLetter(c) && !Character.isSpaceChar(c)) //* 10 16:iload_2 //* 11 17:invokestatic #61 <Method boolean Character.isDigit(char)> //* 12 20:ifne 39 //* 13 23:iload_2 //* 14 24:invokestatic #64 <Method boolean Character.isLetter(char)> //* 15 27:ifne 39 //* 16 30:iload_2 //* 17 31:invokestatic #67 <Method boolean Character.isSpaceChar(char)> //* 18 34:ifne 39 return false; // 19 37:iconst_0 // 20 38:ireturn } // 21 39:iload_3 // 22 40:iconst_1 // 23 41:iadd // 24 42:istore_3 //* 25 43:goto 2 return true; // 26 46:iconst_1 // 27 47:ireturn } public AppInviteContent build() { return new AppInviteContent(this, ((AppInviteContent._cls1) (null))); // 0 0:new #9 <Class AppInviteContent> // 1 3:dup // 2 4:aload_0 // 3 5:aconst_null // 4 6:invokespecial #72 <Method void AppInviteContent(AppInviteContent$Builder, AppInviteContent$1)> // 5 9:areturn } public volatile Object build() { return ((Object) (build())); // 0 0:aload_0 // 1 1:invokevirtual #76 <Method AppInviteContent build()> // 2 4:areturn } public AppInviteContent$Builder readFrom(AppInviteContent appinvitecontent) { if(appinvitecontent == null) //* 0 0:aload_1 //* 1 1:ifnonnull 6 return this; // 2 4:aload_0 // 3 5:areturn else return setApplinkUrl(appinvitecontent.getApplinkUrl()).setPreviewImageUrl(appinvitecontent.getPreviewImageUrl()).setPromotionDetails(appinvitecontent.getPromotionText(), appinvitecontent.getPromotionCode()).setDestination(appinvitecontent.getDestination()); // 4 6:aload_0 // 5 7:aload_1 // 6 8:invokevirtual #82 <Method String AppInviteContent.getApplinkUrl()> // 7 11:invokevirtual #86 <Method AppInviteContent$Builder setApplinkUrl(String)> // 8 14:aload_1 // 9 15:invokevirtual #89 <Method String AppInviteContent.getPreviewImageUrl()> // 10 18:invokevirtual #92 <Method AppInviteContent$Builder setPreviewImageUrl(String)> // 11 21:aload_1 // 12 22:invokevirtual #95 <Method String AppInviteContent.getPromotionText()> // 13 25:aload_1 // 14 26:invokevirtual #98 <Method String AppInviteContent.getPromotionCode()> // 15 29:invokevirtual #102 <Method AppInviteContent$Builder setPromotionDetails(String, String)> // 16 32:aload_1 // 17 33:invokevirtual #106 <Method AppInviteContent$Builder$Destination AppInviteContent.getDestination()> // 18 36:invokevirtual #110 <Method AppInviteContent$Builder setDestination(AppInviteContent$Builder$Destination)> // 19 39:areturn } public volatile ShareModelBuilder readFrom(ShareModel sharemodel) { return ((ShareModelBuilder) (readFrom((AppInviteContent)sharemodel))); // 0 0:aload_0 // 1 1:aload_1 // 2 2:checkcast #9 <Class AppInviteContent> // 3 5:invokevirtual #113 <Method AppInviteContent$Builder readFrom(AppInviteContent)> // 4 8:areturn } public AppInviteContent$Builder setApplinkUrl(String s) { applinkUrl = s; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #30 <Field String applinkUrl> return this; // 3 5:aload_0 // 4 6:areturn } public AppInviteContent$Builder setDestination(Destination destination1) { destination = destination1; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #43 <Field AppInviteContent$Builder$Destination destination> return this; // 3 5:aload_0 // 4 6:areturn } public AppInviteContent$Builder setPreviewImageUrl(String s) { previewImageUrl = s; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #33 <Field String previewImageUrl> return this; // 3 5:aload_0 // 4 6:areturn } public AppInviteContent$Builder setPromotionDetails(String s, String s1) { label0: { if(!TextUtils.isEmpty(((CharSequence) (s)))) //* 0 0:aload_1 //* 1 1:invokestatic #119 <Method boolean TextUtils.isEmpty(CharSequence)> //* 2 4:ifne 91 { if(s.length() <= 80) //* 3 7:aload_1 //* 4 8:invokevirtual #51 <Method int String.length()> //* 5 11:bipush 80 //* 6 13:icmpgt 81 { if(isAlphanumericWithSpaces(s)) //* 7 16:aload_0 //* 8 17:aload_1 //* 9 18:invokespecial #121 <Method boolean isAlphanumericWithSpaces(String)> //* 10 21:ifeq 71 { if(!TextUtils.isEmpty(((CharSequence) (s1)))) //* 11 24:aload_2 //* 12 25:invokestatic #119 <Method boolean TextUtils.isEmpty(CharSequence)> //* 13 28:ifne 98 if(s1.length() <= 10) //* 14 31:aload_2 //* 15 32:invokevirtual #51 <Method int String.length()> //* 16 35:bipush 10 //* 17 37:icmpgt 61 { if(!isAlphanumericWithSpaces(s1)) //* 18 40:aload_0 //* 19 41:aload_2 //* 20 42:invokespecial #121 <Method boolean isAlphanumericWithSpaces(String)> //* 21 45:ifeq 51 //* 22 48:goto 98 throw new IllegalArgumentException("Invalid promotion code, promotionCode can only contain alphanumeric characters and spaces."); // 23 51:new #123 <Class IllegalArgumentException> // 24 54:dup // 25 55:ldc1 #125 <String "Invalid promotion code, promotionCode can only contain alphanumeric characters and spaces."> // 26 57:invokespecial #128 <Method void IllegalArgumentException(String)> // 27 60:athrow } else { throw new IllegalArgumentException("Invalid promotion code, promotionCode can be between1 and 10 characters long"); // 28 61:new #123 <Class IllegalArgumentException> // 29 64:dup // 30 65:ldc1 #130 <String "Invalid promotion code, promotionCode can be between1 and 10 characters long"> // 31 67:invokespecial #128 <Method void IllegalArgumentException(String)> // 32 70:athrow } } else { throw new IllegalArgumentException("Invalid promotion text, promotionText can only contain alphanumericcharacters and spaces."); // 33 71:new #123 <Class IllegalArgumentException> // 34 74:dup // 35 75:ldc1 #132 <String "Invalid promotion text, promotionText can only contain alphanumericcharacters and spaces."> // 36 77:invokespecial #128 <Method void IllegalArgumentException(String)> // 37 80:athrow } } else { throw new IllegalArgumentException("Invalid promotion text, promotionText needs to be between1 and 80 characters long"); // 38 81:new #123 <Class IllegalArgumentException> // 39 84:dup // 40 85:ldc1 #134 <String "Invalid promotion text, promotionText needs to be between1 and 80 characters long"> // 41 87:invokespecial #128 <Method void IllegalArgumentException(String)> // 42 90:athrow } } else if(!TextUtils.isEmpty(((CharSequence) (s1)))) break label0; // 43 91:aload_2 // 44 92:invokestatic #119 <Method boolean TextUtils.isEmpty(CharSequence)> // 45 95:ifeq 110 promoCode = s1; // 46 98:aload_0 // 47 99:aload_2 // 48 100:putfield #36 <Field String promoCode> promoText = s; // 49 103:aload_0 // 50 104:aload_1 // 51 105:putfield #39 <Field String promoText> return this; // 52 108:aload_0 // 53 109:areturn } throw new IllegalArgumentException("promotionCode cannot be specified without a valid promotionText"); // 54 110:new #123 <Class IllegalArgumentException> // 55 113:dup // 56 114:ldc1 #136 <String "promotionCode cannot be specified without a valid promotionText"> // 57 116:invokespecial #128 <Method void IllegalArgumentException(String)> // 58 119:athrow } private String applinkUrl; private Destination destination; private String previewImageUrl; private String promoCode; private String promoText; /* static String access$000(AppInviteContent$Builder appinvitecontent$builder) { return appinvitecontent$builder.applinkUrl; // 0 0:aload_0 // 1 1:getfield #30 <Field String applinkUrl> // 2 4:areturn } */ /* static String access$100(AppInviteContent$Builder appinvitecontent$builder) { return appinvitecontent$builder.previewImageUrl; // 0 0:aload_0 // 1 1:getfield #33 <Field String previewImageUrl> // 2 4:areturn } */ /* static String access$200(AppInviteContent$Builder appinvitecontent$builder) { return appinvitecontent$builder.promoCode; // 0 0:aload_0 // 1 1:getfield #36 <Field String promoCode> // 2 4:areturn } */ /* static String access$300(AppInviteContent$Builder appinvitecontent$builder) { return appinvitecontent$builder.promoText; // 0 0:aload_0 // 1 1:getfield #39 <Field String promoText> // 2 4:areturn } */ /* static Destination access$400(AppInviteContent$Builder appinvitecontent$builder) { return appinvitecontent$builder.destination; // 0 0:aload_0 // 1 1:getfield #43 <Field AppInviteContent$Builder$Destination destination> // 2 4:areturn } */ public AppInviteContent$Builder() { // 0 0:aload_0 // 1 1:invokespecial #25 <Method void Object()> // 2 4:return } }
823a6fc6051be71c6df6e62f2956ec70946bd53e
0af8b92686a58eb0b64e319b22411432aca7a8f3
/api-vs-impl-small/domain/src/main/java/org/gradle/testdomain/performancenull_23/Productionnull_2260.java
9abd99e2e158d6ee3adeb93dd23fbff988020968
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
591
java
package org.gradle.testdomain.performancenull_23; public class Productionnull_2260 { private final String property; public Productionnull_2260(String param) { this.property = param; } public String getProperty() { return property; } private String prop0; public String getProp0() { return prop0; } public void setProp0(String value) { prop0 = value; } private String prop1; public String getProp1() { return prop1; } public void setProp1(String value) { prop1 = value; } }
d433ca06c9cf1e512e02fd9f4b6c6f3a6c470b51
977b5326cacbd4248ad06addf8a34eb6be486b97
/src/main/java/com/example/demo/web/HelloController.java
b16a6dc674ea63c1a9836f5d5930dba3784bd8cc
[]
no_license
git4won/Spring-Boot-Learning
828b494d015f212c0157180fed62178745aa5cf1
f52326cca2b6d89fd763411571834d5e1c085773
refs/heads/master
2020-05-19T12:52:40.371352
2019-05-20T03:41:29
2019-05-20T03:41:29
185,023,039
0
0
null
null
null
null
UTF-8
Java
false
false
566
java
package com.example.demo.web; import com.example.demo.exception.MyException; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String index() throws Exception { //return "Hello World"; throw new Exception("发生错误"); } @RequestMapping("/json") public String json() throws MyException { throw new MyException("发生错误返回 json 格式数据"); } }
32414d0bdc0b6d8201150cdc9e135a754a20fb0b
efd47f39c0b6ae996db30892ab3bb38e0c3330e9
/src/main/java/io/pogorzelski/nitro/carriers/domain/enumeration/Grade.java
794ad9f92e91795dc460f726119309e2c4bcc582
[]
no_license
jpogorzelski/nitro-carriers
c8388d4289c8ddd2cc8334d90a5dee26186ab8bd
204c57b84cdfd6b49357cb7c7ef4da3cdede298b
refs/heads/master
2023-08-29T09:30:16.896396
2023-04-17T11:19:47
2023-04-17T11:19:47
166,852,828
0
0
null
2023-05-28T12:45:29
2019-01-21T17:24:52
Java
UTF-8
Java
false
false
162
java
package io.pogorzelski.nitro.carriers.domain.enumeration; /** * The Grade enumeration. */ public enum Grade { DEF_YES, YES, FINE, NO, DEF_NO, BLACK_LIST }
698f1f4cfe513aab1b0c1eb04969723c96da5eea
3ebaee3a565d5e514e5d56b44ebcee249ec1c243
/assetBank 3.77 decomplied fixed/src/java/com/bright/assetbank/user/action/ViewRegisterAction.java
4eb2c3ee126ff78cf244f1e9a505de23d843700c
[]
no_license
webchannel-dev/Java-Digital-Bank
89032eec70a1ef61eccbef6f775b683087bccd63
65d4de8f2c0ce48cb1d53130e295616772829679
refs/heads/master
2021-10-08T19:10:48.971587
2017-11-07T09:51:17
2017-11-07T09:51:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,395
java
/* */ package com.bright.assetbank.user.action; /* */ /* */ import com.bn2web.common.exception.Bn2Exception; /* */ import com.bright.assetbank.customfield.service.CustomFieldManager; /* */ import com.bright.assetbank.language.service.LanguageManager; /* */ import com.bright.assetbank.marketing.service.MarketingGroupManager; /* */ import com.bright.assetbank.orgunit.bean.OrgUnitSearchCriteria; /* */ import com.bright.assetbank.orgunit.constant.OrgUnitConstants; /* */ import com.bright.assetbank.orgunit.service.OrgUnitManager; /* */ import com.bright.assetbank.user.bean.ABUser; /* */ import com.bright.assetbank.user.bean.ABUserProfile; /* */ import com.bright.assetbank.user.form.RegisterForm; /* */ import com.bright.assetbank.user.service.ABUserManager; /* */ import com.bright.framework.customfield.util.CustomFieldUtil; /* */ import com.bright.framework.database.bean.DBTransaction; /* */ import com.bright.framework.language.bean.Language; /* */ import com.bright.framework.language.util.LanguageUtils; /* */ import com.bright.framework.user.bean.User; /* */ import com.bright.framework.user.bean.UserProfile; /* */ import java.util.List; /* */ import java.util.Vector; /* */ import javax.servlet.http.HttpServletRequest; /* */ import javax.servlet.http.HttpServletResponse; /* */ import org.apache.struts.action.ActionForm; /* */ import org.apache.struts.action.ActionForward; /* */ import org.apache.struts.action.ActionMapping; /* */ /* */ public class ViewRegisterAction extends UserAction /* */ implements OrgUnitConstants /* */ { /* 61 */ private OrgUnitManager m_orgUnitManager = null; /* 62 */ private MarketingGroupManager m_marketingGroupManager = null; /* 63 */ private LanguageManager m_languageManager = null; /* 64 */ private CustomFieldManager m_fieldManager = null; /* */ /* */ public ActionForward execute(ActionMapping a_mapping, ActionForm a_form, HttpServletRequest a_request, HttpServletResponse a_response, DBTransaction a_dbTransaction) /* */ throws Bn2Exception /* */ { /* 82 */ ActionForward afForward = null; /* 83 */ RegisterForm form = (RegisterForm)a_form; /* 84 */ ABUserProfile userProfile = (ABUserProfile)UserProfile.getUserProfile(a_request.getSession()); /* */ /* 87 */ RegisterUserAction.stripHtml(form.getUser()); /* */ /* 90 */ long lInvitedBy = getLongParameter(a_request, "invitedBy"); /* 91 */ form.getUser().setInvitedByUserId(lInvitedBy); /* */ /* 94 */ OrgUnitSearchCriteria search = new OrgUnitSearchCriteria(); /* 95 */ Vector vecOrgUnits = this.m_orgUnitManager.getOrgUnitList(a_dbTransaction, search, false); /* 96 */ form.setOrgUnitList(vecOrgUnits); /* */ /* 99 */ Vector vecDivisions = getUserManager().getAllDivisions(a_dbTransaction); /* 100 */ form.setDivisionList(vecDivisions); /* */ /* 103 */ Vector vecGroups = getUserManager().getBrandGroups(a_dbTransaction); /* 104 */ form.setRegisterGroupList(vecGroups); /* */ /* 107 */ List marketingGroups = this.m_marketingGroupManager.getMarketingGroups(a_dbTransaction, form.getUser().getLanguage()); /* 108 */ LanguageUtils.setLanguageOnAll(marketingGroups, userProfile.getCurrentLanguage()); /* 109 */ form.setMarketingGroups(marketingGroups); /* */ /* 112 */ List languages = this.m_languageManager.getLanguages(a_dbTransaction, true, false); /* 113 */ form.setLanguages(languages); /* */ /* 116 */ Language language = userProfile.getCurrentLanguage(); /* */ /* 118 */ form.setSelectedLanguage(language.getId()); /* */ /* 120 */ if ((userProfile.getUser() != null) && (!form.isPopulatedviaReload())) /* */ { /* 122 */ List marketingGroupIds = this.m_marketingGroupManager.getMarketingGroupIdsForUser(a_dbTransaction, userProfile.getUser().getId()); /* 123 */ form.setMarketingGroupIds((String[])(String[])marketingGroupIds.toArray(new String[marketingGroups.size()])); /* */ } /* */ /* 127 */ CustomFieldUtil.prepCustomFields(a_request, form, form.getUser(), this.m_fieldManager, a_dbTransaction, 1L, null); /* 128 */ afForward = a_mapping.findForward("Success"); /* */ /* 130 */ return afForward; /* */ } /* */ /* */ public boolean getAvailableNotLoggedIn() /* */ { /* 145 */ return true; /* */ } /* */ /* */ public void setOrgUnitManager(OrgUnitManager a_orgUnitManager) /* */ { /* 150 */ this.m_orgUnitManager = a_orgUnitManager; /* */ } /* */ /* */ public void setMarketingGroupManager(MarketingGroupManager marketingGroupManager) /* */ { /* 155 */ this.m_marketingGroupManager = marketingGroupManager; /* */ } /* */ /* */ public void setLanguageManager(LanguageManager a_languageManager) /* */ { /* 160 */ this.m_languageManager = a_languageManager; /* */ } /* */ /* */ public void setCustomFieldManager(CustomFieldManager a_fieldManager) /* */ { /* 165 */ this.m_fieldManager = a_fieldManager; /* */ } /* */ } /* Location: C:\Users\mamatha\Desktop\com.zip * Qualified Name: com.bright.assetbank.user.action.ViewRegisterAction * JD-Core Version: 0.6.0 */
646ffb61c1ef00340a3fc5293a715de312516286
f49b68fe094449c06e2a497fa5bd5565e0547be7
/fall_2014/parallel/LockFreeList/src/ru/spbau/afanasev/LockFreeList/Reader.java
f5d5983715a268821c406223c6717073153b05a9
[]
no_license
Icemore/homework
412a1cf3254ed887058569302df432f113a60cf1
6e8a359dd4d153ad98e53e65954eed8dcb12e5de
refs/heads/master
2020-04-30T08:57:45.927198
2015-01-16T10:06:09
2015-01-16T10:06:09
12,825,884
1
0
null
null
null
null
UTF-8
Java
false
false
439
java
package ru.spbau.afanasev.LockFreeList; import java.util.Random; public class Reader extends Worker { protected Reader(Set<Integer> set, int numberOfOperations) { super(set, numberOfOperations); } @Override public void run() { Random rand = new Random(); for(int i = 0; i < numberOfOperations; i++) { int key = rand.nextInt(MAX_KEY); set.contains(key); } } }
d81fc4de30821b8c86c268d815f4b057f012c478
e81f85db7122d9eab155f47483eb020f5d92829a
/Library.java
3d7469ce5bda8145bec7d414fbc95ca4ff5d276c
[]
no_license
CluelessTimmy/JavaAssignment1
ea188be26a4d31a9e411ef155b841d6d59cb5271
b17143232fb19ff10669c48c56c61fa73331ee4b
refs/heads/master
2021-07-05T13:22:33.039821
2017-09-27T11:03:47
2017-09-27T11:03:47
105,007,217
0
0
null
null
null
null
UTF-8
Java
false
false
7,649
java
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Library { public static void main(String[] args) { new Library().use(); } private Catalogue catalogue; private List<Patron> patrons = new ArrayList<Patron>(); public Library() { catalogue = new Catalogue(this); } public void use() { char choice; do { System.out.println("Welcome to the Library! Please make a selection from the menu:"); System.out.println("1. Explore the catalogue."); System.out.println("2. View your patron record."); System.out.println("3. Show you favourite books."); System.out.println("4. Enter Admin Mode."); System.out.println("X. Exit the system."); choice = readChoice(); switch (choice) { case '1': explore(); break; case '2': view(); break; case '3': showFavourite();break; case '4': admin();break; case 'X': break; default : System.out.println("Please enter a number between 1 and 4, or press X to exit."); } } while (choice != 'X'); } private void showFavourite() { System.out.println(" "); System.out.print("Enter a patron ID: "); int i = In.nextInt(); for(Patron patron : patrons) { System.out.println(patron.getName() + "'s favourite books are:"); if(patron.getID() == i ) { calculateFavourite(patron.getBorrowingHistory()); } }System.out.println(" "); } private void calculateFavourite(List<Book> borrowingHistory) { int max = 0; int loc = 0; List<String> titles = new ArrayList<String>(); List<Integer> num = new ArrayList<Integer>(); for(Book book : borrowingHistory) { int count = Collections.frequency(borrowingHistory, book); if(!titles.contains(book.toString())) { num.add(count); titles.add(book.toString()); } } for(int i = 0; i < titles.size(); i++) { if (num.get(i) > max) { max = num.get(i); loc = i; } }System.out.println(titles.get(loc)); titles.remove(titles.get(loc)); num.remove(num.get(loc)); if(num.size() == 1) { System.out.println(titles.get(0)); titles.remove(titles.get(0)); num.remove(num.get(0)); }else { max = 0; for(int i3 = 0; i3 < titles.size(); i3++) { if (num.get(i3) > max) { max = num.get(i3); loc = i3; } }System.out.println(titles.get(loc)); titles.remove(titles.get(loc)); num.remove(num.get(loc)); System.out.println(titles.get(0)); titles.remove(titles.get(0)); num.remove(num.get(0)); } } private char readChoice() { System.out.print("Enter a choice: "); return In.nextChar(); } private void explore() { catalogue.use(); } private void view() { System.out.println(" "); System.out.print("Enter a patron ID: "); int i = In.nextInt(); if(patrons.isEmpty() == true) { System.out.println("That patron does not exist."); System.out.println(" "); }else { for(Patron patron : patrons) { if(patron.getID() == i ) { System.out.println(patron.toString()); System.out.println("Books currently borrowed by " + patron.getName() + ": "); if(patron.getCurrentlyBorrowed().isEmpty() == true) { }else { for (Book book : patron.getCurrentlyBorrowed()) { System.out.println(book.toString()); } } System.out.println(patron.getName() + "'s borrowing history: "); if(patron.getBorrowingHistory().isEmpty() == true) { }else { for (Book book : patron.getBorrowingHistory()) { System.out.println(book.toString()); } }System.out.println(" "); } } } } private void admin() { char choice; do { System.out.println("Welcome to the administration menu:"); System.out.println("1. Add a patron."); System.out.println("2. Remove a patron."); System.out.println("3. Add a book to the catalogue."); System.out.println("4. Remove a book from the catalogue."); System.out.println("R. Return to the previous menu."); choice = readChoice(); switch (choice) { case '1': patronAdd(); break; case '2': patronRemove();break; case '3': bookAdd();break; case '4': bookRemove();break; case 'R': break; default : System.out.println("Please enter a number between 1 and 4 or press R to return to the previous menu."); } } while (choice != 'R'); } private void bookRemove() { System.out.println(" "); System.out.println("Removing a book."); System.out.print("Enter the title of the book: "); String t = In.nextLine(); System.out.print("Enter the author's name: "); Author a = new Author(In.nextLine()); catalogue.bookRemove(t, a); } private void patronRemove() { Patron removePatron = null; System.out.println(" "); System.out.println("Removing a patron."); System.out.print("Enter a patron ID: "); int i = In.nextInt(); for (Patron patron : patrons) { if(patron.getID() == i) { removePatron = patron; } } if (removePatron != null) { patrons.remove(removePatron); System.out.println("Patron removed."); System.out.println(" "); }else { System.out.println("That patron does not exist."); System.out.println(" "); } } private void patronAdd() { System.out.println(" "); System.out.println("Adding a new patron."); System.out.print("Enter a new ID: "); int i = In.nextInt(); System.out.print("Enter the patron's name: "); String n = In.nextLine(); System.out.println("Patron added. "); System.out.println(" "); patrons.add(new Patron(i, n)); } private void bookAdd() { System.out.println(" "); System.out.println("Adding a new book."); System.out.print("Enter the title of the book: "); String t = In.nextLine(); System.out.print("Enter the author's name: "); Author a = new Author(In.nextLine()); System.out.print("Enter the genre: "); Genre g = new Genre(In.nextLine().toLowerCase()); catalogue.bookAdd(t,a,g); } public Book returnBook(int id) { for(Patron patron : patrons) { if(patron.getID() == id ) { System.out.println(patron.getName() + " has the following books: "); System.out.println("Books currently borrowed by " + patron.getName() + ":"); for(Book book : patron.getCurrentlyBorrowed()) { System.out.println(book); } System.out.print("Enter the title of the book you wish to return: "); String title = In.nextLine(); for(Book book : patron.getCurrentlyBorrowed()) { if(title.equals(book.getTitle())) { patron.returnBook(book); System.out.println(book.getTitle() + " has been returned."); System.out.println(" "); return book; } } } } return null; } public Book borrow(int id, List<Book> booksOnShelf) { for(Patron patron : patrons) { if(patron.getID() == id ) { System.out.print("Enter the title of the book you wish to borrow: "); String title = In.nextLine(); for(Book book : booksOnShelf) { if(book.getTitle().equals(title)) { patron.borrow(book); System.out.println("Book loaned."); System.out.println(" "); return book; } } } } System.out.println("That book is not available or doesn't exist. "); System.out.println(" "); return null; } }
a53d8984b525b72f7aa4908baf137ce2c67eb6a0
c061d8a236c1cd7f886ccaadae78ecd27812e160
/engine/src/api/generated/TransPoolTrip.java
98d7d8b4b9c0a7f155e2e44036d5eafce8841124
[ "Apache-2.0" ]
permissive
nadavsu/transpool-web
5a14e11a863b92c7dadcc5ca78c4ffb828843a4e
337671d71f85c5740ab52900af6043bbd24f0d22
refs/heads/master
2023-04-03T20:23:03.773951
2021-04-16T17:08:19
2021-04-16T17:08:19
253,467,624
0
0
null
null
null
null
UTF-8
Java
false
false
3,811
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.1-b171012.0423 // See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.04.17 at 05:00:20 PM IDT // package api.generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element ref="{}Owner"/&gt; * &lt;element ref="{}Capacity"/&gt; * &lt;element ref="{}PPK"/&gt; * &lt;element ref="{}Route"/&gt; * &lt;element ref="{}Scheduling"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "owner", "capacity", "ppk", "route", "scheduling" }) @XmlRootElement(name = "TransPoolTrip") public class TransPoolTrip { @XmlElement(name = "Owner", required = true) protected String owner; @XmlElement(name = "Capacity") protected int capacity; @XmlElement(name = "PPK") protected int ppk; @XmlElement(name = "Route", required = true) protected Route route; @XmlElement(name = "Scheduling", required = true) protected Scheduling scheduling; /** * Gets the value of the owner property. * * @return * possible object is * {@link String } * */ public String getOwner() { return owner; } /** * Sets the value of the owner property. * * @param value * allowed object is * {@link String } * */ public void setOwner(String value) { this.owner = value; } /** * Gets the value of the capacity property. * */ public int getCapacity() { return capacity; } /** * Sets the value of the capacity property. * */ public void setCapacity(int value) { this.capacity = value; } /** * Gets the value of the ppk property. * */ public int getPPK() { return ppk; } /** * Sets the value of the ppk property. * */ public void setPPK(int value) { this.ppk = value; } /** * Gets the value of the route property. * * @return * possible object is * {@link Route } * */ public Route getRoute() { return route; } /** * Sets the value of the route property. * * @param value * allowed object is * {@link Route } * */ public void setRoute(Route value) { this.route = value; } /** * Gets the value of the scheduling property. * * @return * possible object is * {@link Scheduling } * */ public Scheduling getScheduling() { return scheduling; } /** * Sets the value of the scheduling property. * * @param value * allowed object is * {@link Scheduling } * */ public void setScheduling(Scheduling value) { this.scheduling = value; } }
b3091f812d37bc2b3f161da7b1b330ecf888caf9
2a1469663aa74535060fec05b1887a4c70c1801a
/src/test/java/org/mydomain/app/classloader/ClassLoaderUtil.java
40ad2784af3c7bc56bf77dcf370ecb189ec5f5fc
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
baowp/jpetstore-6
797e07fdc87795f440d2b7650cd3887d38234c44
c62c874a985dc9c40adca3afdea749bf0320432e
refs/heads/master
2021-01-18T18:22:52.378905
2013-11-05T13:51:04
2013-11-05T13:51:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,627
java
/** * Project: jpetstore-6 * * File Created at Sep 27, 2013 * $Id$Corporation * * Copyright 2013-2015 Colomob.com Corporation Limited. * All rights reserved. */ package org.mydomain.app.classloader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * @author baowp * */ public class ClassLoaderUtil { public synchronized static void reloadClassesFromPath() { isLoad = false; loadClassesFromPath(); } public synchronized static void loadClassesFromPath() { if (!isLoad) { // String property = System.getProperty("user.dir");// // "sun.boot.class.path" try { URL resource = ClassLoaderUtil.class.getResource("/"); URI uri = resource.toURI(); String property = new File(uri).getPath(); String[] paths = property.split(";"); for (String path : paths) { File file = new File(path); if (file.isFile() && path.endsWith(".jar")) { listClassesInZip(file); } else if (file.isDirectory()) { listClassesInDirectory(path + File.separatorChar, file); } } } catch (URISyntaxException e) { e.printStackTrace(); } } } private synchronized static void listClassesInDirectory(String rootPath, File file) { File[] subFiles = file.listFiles(); for (File subFile : subFiles) { if (subFile.canRead()) { if (subFile.isFile()) { String path = subFile.getPath(); if (path.endsWith(".class")) { try { String className = getClassName(path .substring(rootPath.length())); CLASSES.add(Class.forName(className)); } catch (Throwable e) { e.printStackTrace(); } } else if (path.endsWith(".jar")) { listClassesInZip(subFile); } } else if (subFile.isDirectory()) { listClassesInDirectory(rootPath, subFile); } } } } private synchronized static void listClassesInZip(File jarFile) { ZipInputStream in = null; try { in = new ZipInputStream(new FileInputStream(jarFile)); ZipEntry ze = null; while ((ze = in.getNextEntry()) != null) { if (ze.isDirectory()) { continue; } else { try { String name = ze.getName(); if (!name.endsWith(".class")) continue; String className = getClassName(name); CLASSES.add(Class.forName(className)); } catch (Throwable e) { } } } } catch (Throwable e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } private static String getClassName(String path) { return path.replace('/', '.').replace('\\', '.') .replaceAll(".class$", ""); } public static List<Class<?>> getSubClasses(Class<?> clazz) { List<Class<?>> subClasses = SUB_CLASSES_MAP.get(clazz); if (subClasses == null) { subClasses = new ArrayList<Class<?>>(10); for (Class<?> tmpClass : CLASSES) { if (clazz.isAssignableFrom(tmpClass) && !tmpClass.isAssignableFrom(clazz)) { subClasses.add(tmpClass); } } SUB_CLASSES_MAP.put(clazz, subClasses); } return Collections.unmodifiableList(subClasses); } private static final List<Class<?>> CLASSES = new ArrayList<Class<?>>(200); private static final Map<Class<?>, List<Class<?>>> SUB_CLASSES_MAP = new HashMap<Class<?>, List<Class<?>>>(); private static boolean isLoad; static { loadClassesFromPath(); } }
e3173685adcf24af1bc81d44874e059341cdea01
0dbd987d03145e5864e2031d3523dab013102031
/sroh10378782/QLJava/src/org/uva/sea/ql/ast/nodes/ASTNode.java
7dbce5a19e0847b9b2c052392383c99ba1f5b296
[]
no_license
slvrookie/sea-of-ql
52041a99159327925e586389a9c60c4d708c95f2
1c41ce46ab1e2c5de124f425d2e0e3987d1b6a32
refs/heads/master
2021-01-16T20:47:40.370047
2013-07-15T11:26:56
2013-07-15T11:26:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
62
java
package org.uva.sea.ql.ast.nodes; public interface ASTNode {}
[ "xCQJ2BdUYOPV" ]
xCQJ2BdUYOPV
3ee6449a13dbbe8e2ed249c3a8bd3b4a01e77b21
2517b2628014801f17fbb1899044ac7a75575e90
/src/main/java/com/sefist/scheduler/TestScheduler.java
fb37aa1aa7df29360924f8ba4e6e8e9a0316fa55
[]
no_license
BruceYi119/test
1a9dd96b0e236d9657f11792b9cd41a63c4fe26b
edc067927aaa37051ffce84fc8a42ffe6a1edf87
refs/heads/master
2023-07-11T14:40:52.042227
2021-08-18T23:58:43
2021-08-18T23:58:43
331,846,052
0
0
null
null
null
null
UTF-8
Java
false
false
5,361
java
package com.sefist.scheduler; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.config.ScheduledTaskRegistrar; @Configuration @EnableScheduling public class TestScheduler implements SchedulingConfigurer { private static final Logger log = LoggerFactory.getLogger(TestScheduler.class); private static int procCnt = 0; private Environment env; private String[] rptMsgTypeCds = { "01", "02", "03", "04", "05", "96", "97", "98", "99" }; private String[] ips = { "api.ip1", "api.ip2" }; private String[] fileSize = { "77", "11264", "179200", "12582912", "52428800" }; public TestScheduler(Environment env) { this.env = env; } @Scheduled(cron = "*/3 * * * * *") public void randomAddMt() { int endCnt = Integer.parseInt(env.getProperty("api.proc.endcnt")); if (procCnt < endCnt) { File f = null; Random ran = new Random(); String fileMod = env.getProperty("api.file.mod"); StringBuilder sb = new StringBuilder(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String path = env.getProperty("api.file.dir"); // int ipIdx = ran.nextInt(2); int ipIdx = 0; String ip = env.getProperty(ips[ipIdx]); String url = String.format("http://%s/api/fusendmt", ip); String secretid = env.getProperty("api.hash"); String test = String.valueOf(ran.nextBoolean()); String rptFcltyCd = "DH0001"; String docKndCd = env.getProperty("api.docKndCd"); String rptDocNo = sdf.format(new Date()); String rptStatusCd = "SR"; String rptProcType = "00"; if (fileMod.equals("0")) f = makeFile(rptDocNo, path, fileSize[0]); else if (fileMod.equals("1")) f = makeFile(rptDocNo, path, fileSize[1]); else if (fileMod.equals("2")) f = makeFile(rptDocNo, path, fileSize[2]); else if (fileMod.equals("3")) f = makeFile(rptDocNo, path, fileSize[3]); else if (fileMod.equals("4")) f = makeFile(rptDocNo, path, fileSize[4]); else f = makeFile(rptDocNo, path, fileSize[ran.nextInt(4)]); log.info(f.toString()); String rptMsgTypeCd = rptMsgTypeCds[ran.nextInt(9)]; String preRptDocNo = rptDocNo; String basRptDocNo = rptDocNo; String trnstnOrder = env.getProperty("api.trnstnorder"); String rptFileNm = f.getName(); String centAdminCd = "DH0002"; String rptUserId = "testid"; if (f != null) { sb.setLength(0); sb.append(String.format( "%s?secretid=%s&test=%s&rptFcltyCd=%s&rptDocNo=%s&rptStatusCd=%s&rptProcType=%s&docKndCd=%s&rptMsgTypeCd=%s&preRptDocNo=%s&basRptDocNo=%s&trnstnOrder=%s&rptFileNm=%s&centAdminCd=%s&rptUserId=%s", url, secretid, test, rptFcltyCd, rptDocNo, rptStatusCd, rptProcType, docKndCd, rptMsgTypeCd, preRptDocNo, basRptDocNo, trnstnOrder, rptFileNm, centAdminCd, rptUserId)); log.info(sb.toString()); httpRequest(sb.toString()); log.info(String.format("cnt : %d", procCnt)); procCnt += 1; } } } public void httpRequest(String targetUrl) { HttpURLConnection con = null; try { URL url = new URL(targetUrl); con = (HttpURLConnection) url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String inputLine; while ((inputLine = br.readLine()) != null) sb.append(inputLine); log.info(sb.toString()); } catch (Exception e) { log.info(String.format("httpRequest error %s", e.getMessage())); } finally { if (con != null) con.disconnect(); } } public File makeFile(String rptDocNo, String path, String size) { String txt = String .format("%-" + size + "s", "CTRSTART||06||01||AA0001||2005-00000001||20060103140000||00||접수성공||CTREND") .replace(" ", "A"); String fileName = String.format("%s/CTR_FC0615%s.SND", path, rptDocNo); File file = null; try { FileOutputStream fos = new FileOutputStream(fileName); BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write(txt.getBytes("EUC-KR")); bos.close(); fos.close(); file = new File(fileName); } catch (Exception e) { e.printStackTrace(); } return file; } @SuppressWarnings("unused") private String getRandomAlphabet() { StringBuilder sb = new StringBuilder(); Random ran = new Random(); for (int i = 0; i < 6; i++) sb.append(Character.toString((char) ((int) ran.nextInt(26) + 65))); return sb.toString(); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { ThreadPoolTaskScheduler tpts = new ThreadPoolTaskScheduler(); tpts.setPoolSize(2); tpts.setThreadNamePrefix("testSche-"); tpts.initialize(); taskRegistrar.setTaskScheduler(tpts); } }
f806e7ff2e76a6921e3383293902e644fb126a68
4f31426c08f4fcdfa591df5971868c77386e3814
/core/src/com/terrain/game/TerrainGame.java
be5e17c1f693293d7a8049bb84d5ab3d40af9c8d
[]
no_license
antonshkurenko/inf_terrain
3531a30501c9d3154d20a0b9cab41c0a498d05f2
dcf9d36f44dcc47755ec4eab4cf5930aa6c81041
refs/heads/master
2022-08-24T15:43:34.766758
2015-04-01T11:20:41
2015-04-01T11:20:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,670
java
package com.terrain.game; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.*; import com.badlogic.gdx.utils.Array; import java.util.ArrayList; import java.util.List; import java.util.Random; public class TerrainGame extends Game { Box2DDebugRenderer mRenderer; OrthographicCamera mCamera; World mWorld; Random mRandom; float mNextHill; int mCountOfSlices; final static int PIXEL_STEP = 10; @Override public void create () { mWorld = new World(new Vector2(0, -10), true); mRenderer = new Box2DDebugRenderer(); mCamera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); mCamera.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0f); mCamera.update(); mRandom = new Random(); mNextHill = 140 + mRandom.nextFloat() * 200; mCountOfSlices = 0; mNextHill = drawHill(PIXEL_STEP, 0, mNextHill); } @Override public void render() { super.render(); Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT); mWorld.step(1 / 30, 10, 10); mWorld.clearForces(); Array<Body> bodies = new Array<Body>(); mWorld.getBodies(bodies); for (Body currentBody : bodies) { currentBody.setTransform(currentBody.getPosition().x - 1, currentBody.getPosition().y, 0); if (currentBody.getPosition().x <= 0) { int sliceWidth = Gdx.graphics.getWidth() / PIXEL_STEP; if(mCountOfSlices <= sliceWidth + 1) { mNextHill = drawHill(PIXEL_STEP, Gdx.graphics.getWidth(), mNextHill); } mWorld.destroyBody(currentBody); mCountOfSlices--; } } mRenderer.render(mWorld, mCamera.combined); } private float drawHill(int pixelStep, float xOffset, float yOffset) { float hillStartY = yOffset; final float hillWidth = Gdx.graphics.getWidth(); final float hillSliceWidth = hillWidth / pixelStep; mCountOfSlices += hillSliceWidth; List<Vector2> hillVector; final float randomHeight = mRandom.nextFloat() * 100; if (xOffset != 0) { hillStartY += randomHeight; } for (int j = 0; j < hillSliceWidth; j++) { hillVector=new ArrayList<Vector2>(); hillVector.add(new Vector2((j * pixelStep + xOffset), 0f)); hillVector.add(new Vector2((j * pixelStep + xOffset), (float)(hillStartY - randomHeight * Math.cos(2 * Math.PI / hillSliceWidth * j)))); hillVector.add(new Vector2(((j + 1) * pixelStep + xOffset), (float)(hillStartY - randomHeight * Math.cos(2 * Math.PI / hillSliceWidth * (j + 1))))); hillVector.add(new Vector2(((j + 1) * pixelStep + xOffset), 0f)); BodyDef sliceBody = new BodyDef(); Vector2 centre = findCentroid(hillVector); sliceBody.position.set(centre.x, centre.y); for (int z = 0; z < hillVector.size(); z++) { hillVector.get(z).sub(centre); } PolygonShape slicePoly = new PolygonShape(); slicePoly.set(hillVector.toArray(new Vector2[hillVector.size()])); FixtureDef sliceFixture = new FixtureDef(); sliceFixture.shape = slicePoly; Body worldSlice = mWorld.createBody(sliceBody); worldSlice.createFixture(sliceFixture); } hillStartY -= randomHeight; return (hillStartY); } private Vector2 findCentroid(List<Vector2> vs) { Vector2 c = new Vector2(); float area = 0.0f; float p1X = 0.0f; float p1Y = 0.0f; float inv3 = 1.0f/3.0f; int length = vs.size(); for (int i = 0; i < length; ++i) { Vector2 p2 = vs.get(i); Vector2 p3 = i + 1 < length ? vs.get(i+1) : vs.get(0); float e1X = p2.x - p1X; float e1Y = p2.y - p1Y; float e2X = p3.x - p1X; float e2Y = p3.y - p1Y; float D = (e1X * e2Y - e1Y * e2X); float triangleArea = 0.5f * D; area += triangleArea; c.x += triangleArea * inv3 * (p1X + p2.x + p3.x); c.y += triangleArea * inv3 * (p1Y + p2.y + p3.y); } c.x *= 1.0 / area; c.y *= 1.0 / area; return c; } }
129ff3f3d0578b3e6fd253bfd13124254867ea28
fa1408365e2e3f372aa61e7d1e5ea5afcd652199
/src/testcases/CWE197_Numeric_Truncation_Error/s01/CWE197_Numeric_Truncation_Error__int_large_to_byte_71a.java
6d631b30226f204893f966cf3d6a1839588dc4fc
[]
no_license
bqcuong/Juliet-Test-Case
31e9c89c27bf54a07b7ba547eddd029287b2e191
e770f1c3969be76fdba5d7760e036f9ba060957d
refs/heads/master
2020-07-17T14:51:49.610703
2019-09-03T16:22:58
2019-09-03T16:22:58
206,039,578
1
2
null
null
null
null
UTF-8
Java
false
false
2,042
java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE197_Numeric_Truncation_Error__int_large_to_byte_71a.java Label Definition File: CWE197_Numeric_Truncation_Error__int.label.xml Template File: sources-sink-71a.tmpl.java */ /* * @description * CWE: 197 Numeric Truncation Error * BadSource: large Set data to a number larger than Short.MAX_VALUE * GoodSource: A hardcoded non-zero, non-min, non-max, even number * Sinks: to_byte * BadSink : Convert data to a byte * Flow Variant: 71 Data flow: data passed as an Object reference argument from one method to another in different classes in the same package * * */ package testcases.CWE197_Numeric_Truncation_Error.s01; import testcasesupport.*; public class CWE197_Numeric_Truncation_Error__int_large_to_byte_71a extends AbstractTestCase { public void bad() throws Throwable { int data; /* FLAW: Use a number larger than Short.MAX_VALUE */ data = Short.MAX_VALUE + 5; (new CWE197_Numeric_Truncation_Error__int_large_to_byte_71b()).badSink((Object)data ); } public void good() throws Throwable { goodG2B(); } /* goodG2B() - use goodsource and badsink */ private void goodG2B() throws Throwable { int data; /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; (new CWE197_Numeric_Truncation_Error__int_large_to_byte_71b()).goodG2BSink((Object)data ); } /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
101e842581917e932e129fc1f1073b88d54de93d
7f7f797a8fb586a1697376a31f4a0460f02d39e1
/Aufgabe3/src/ns/Communicator.java
0833c97931c8a60690707e7605c603b62fda2bc5
[]
no_license
HAW-AI/VS-2012-SKAW
95058c730c26107dc2c26811db8f5c3d35da7d1c
e6947a87bfac5e70b6ea1ce3f90fff6d00ebd007
refs/heads/master
2016-08-05T05:05:55.364578
2013-01-16T17:36:59
2013-01-16T17:36:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,948
java
package ns; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; final class Communicator extends Thread { private final Socket socket; private PrintWriter out; private BufferedReader in; private String inputLine; private String[] inputTokens; Communicator(Socket socket) { this.socket=socket; try { out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( socket.getInputStream())); } catch (IOException e) { e.printStackTrace(); } // System.out.println("new socket created"); } @Override public void run() { try { System.out.println("Communicator started"); while (!socket.isClosed() && ((inputLine = in.readLine()) != null)) { inputTokens = inputLine.split(";"); if (inputTokens[0].equals("rebind")) { rebind(inputTokens); } else if (inputTokens[0].equals("resolve")) { resolve(inputTokens); } else { error("unknown command: " + inputTokens[0]); } } in.close(); out.close(); socket.close(); } catch (IOException e) { // e.printStackTrace(); } finally { System.out.println("Communicator stopped"); } } private void rebind(String[] tokens) { if (tokens.length != 5) { error("rebind: wrong number of params"); } else { String name = tokens[1].trim(); String type = tokens[2].trim(); String host = tokens[3].trim(); int port = -1; try { port = Integer.parseInt(tokens[4]); } catch (NumberFormatException e) { } if (name.isEmpty()) { error("rebind: name must not be empty"); } else if (type.isEmpty()) { error("rebind: type must not be empty"); } else if (host.isEmpty()) { error("rebind: host must not be empty"); } else if (port < 0 || port > 65535) { error("rebind: port must be an integer and 0<=port<=65535"); } else { NameserviceDb.rebind(new ObjectInfo(name, type, host, port)); System.out.println("rebind: " + name + "," + type + "," + host + "," + port); out.println("ok"); } } } private void resolve(String[] tokens) { if (tokens.length != 2) { error("resolve: wrong number of params"); } else { String name = tokens[1].trim(); if (name.isEmpty()) { error("resolve: name must not be empty"); } else { ObjectInfo obj = NameserviceDb.resolve(name); if (obj == null) { System.out.println("resolve: name not found: " + name); out.println("nameNotFound"); } else { String type = obj.type(); String host = obj.host(); int port = obj.port(); System.out.println("resolve: " + name + "," + type + "," + host + "," + port); out.println("result," + name + "," + type + "," + host + "," + port); } } } } private void error(String message) { System.out.println("ERROR: " + message); out.println("Exception," + message); } }
427d3663ba74393f0f6420e19879adb9c406440b
6727bc97412eb3d95cf0ef0a604608a2f6c815ff
/backend/PPMToolFullStack/src/main/java/io/agileintelligence/ppmtool/exceptions/ProjectNotFoundException.java
ea7ba3da9d94b04e66665304e95a7934abaf6da6
[]
no_license
ysfagr/react-spring-proje-yonetim
38c2d8c967bf2d166c1c48287ab599dc6861a42b
59d47fd7c6158cadae2a9b328be9b76a0f15fe4a
refs/heads/master
2023-01-14T16:27:26.694043
2021-12-07T19:51:17
2021-12-07T19:51:17
212,144,464
0
0
null
2022-12-14T17:40:35
2019-10-01T16:25:45
JavaScript
UTF-8
Java
false
false
387
java
package io.agileintelligence.ppmtool.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.BAD_REQUEST) public class ProjectNotFoundException extends RuntimeException { public ProjectNotFoundException(String message) { super(message); } }
dcaee59845a5e1c873eddefb68383f5860304569
680335111376ca5d6872a883633ca3232314fc76
/core/src/main/java/usecase/CreateConferenceTrack/ConferenceTrackInput.java
21555e0841bb55f7bfc0c4615411a6026f7fd343
[ "MIT" ]
permissive
sharmapankaj2512/timeless-architecture-example
61e689b1465c4f186837ee68c2f86ace48038356
6010bb55c5bffb5624d992973f9094b42b9e1ba0
refs/heads/master
2020-03-29T21:21:06.686426
2018-09-16T17:16:53
2018-09-17T03:26:55
150,361,970
1
0
null
null
null
null
UTF-8
Java
false
false
356
java
package usecase.CreateConferenceTrack; import java.util.List; public class ConferenceTrackInput { public List<TalkInput> talks; public ConferenceTrackInput() { } public ConferenceTrackInput(List<TalkInput> talks) { this.talks = talks; } public boolean hasTalks() { return talks != null && talks.size() > 0; } }
2f6717137641e7d86a82e50e9e223b5dc411f2c5
f1dd7a9542290c5e6cdcd9b59db7da449bcf9850
/HealthCareUserModule/src/test/java/com/I2I/healthCare/Prototype/UserDataPrototype.java
4bbab0f16c64003c1f997d9ee55a95437abb57ec
[]
no_license
Subash1010/Ideas2It-Training
39a56b2c82801de1dc4cd77306d2f17ca4cb7159
a68506b081bb45fc9f9ed3e94b3f87920c490dc3
refs/heads/master
2023-04-06T08:09:16.876068
2021-04-07T10:41:10
2021-04-07T10:41:10
335,544,071
0
0
null
null
null
null
UTF-8
Java
false
false
295
java
package com.I2I.healthCare.Prototype; import com.I2I.healthCare.Dto.UserDto; public class UserDataPrototype { public static UserDto getUserDto() { UserDto userDto = new UserDto(); userDto.setUserId(1); userDto.setUserName("Test001"); userDto.setRoleId(500); return userDto; } }
5f82cda175b504d6633a7cd130df2b9cdf97307c
820959ada24a496507c45c8e316bb556266f1668
/springcloudoauth/hotel-server/src/main/java/cn/lyf/hotelserver/config/ResourceConfig.java
7d7a64bf8009983cf7d59bd4f2bad7db2964d933
[]
no_license
sweetfly123/bishe
9a767eabba75c95b4b5e90bc2685718ecad48aee
dec705bf7324b525e8c3868756f923b77fbd1933
refs/heads/master
2020-04-09T11:23:56.947423
2019-02-19T08:00:09
2019-02-19T08:00:09
160,308,270
0
1
null
null
null
null
UTF-8
Java
false
false
1,259
java
package cn.lyf.hotelserver.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import javax.servlet.http.HttpServletResponse; /** * @Title: ResourceConfig * @Description: 安全验证 * @author: DIC.lyf * @date: 2018/12/7 11:54 * @Return: * @version: V1.0 */ @Configuration @EnableResourceServer public class ResourceConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.exceptionHandling().authenticationEntryPoint( (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED) ) .and().authorizeRequests().antMatchers("/static/**","/resources/**", "/favicon.ico", "/js_pre/*.js_pre", "/*.html", "/css_pre/*.css_pre", "/images_pre/*.*").permitAll() .and().authorizeRequests().anyRequest().authenticated().and().httpBasic(); } }
9c100d4ad037d8bd6d965914360c462370e96664
52297ca6b35d35182ada1ff4ec27e4264d65cc7b
/Dynamic Programming/Longest Common Subsequence/LCS.java
cc505dc6a0f3cdf14016a60366c3dac844da3b23
[]
no_license
manhtv/CP-Algorithms
3720d0c308a8b0adc3f285914ebd2cf39b5a6aa9
b3860b3069f51435edadde827ab0fa5b7a3da6f5
refs/heads/master
2023-03-22T15:24:06.418656
2020-02-06T22:45:18
2020-02-06T22:45:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,306
java
import java.util.*; public class LCS { /** * @NOTE: Remember, LCS always runs in O(n^2) time (best time complexity) **/ public static void main(String[]args) { Scanner sc = new Scanner(System.in); String a = sc.nextLine(), b = sc.nextLine(); int dp[][] = new int[a.length() + 1][b.length() + 1]; System.out.println(findlen(dp, a, b)); System.out.println(findword(dp, a, b)); sc.close(); } static int findLCS(int dp[][], String a, String b) { int n = a.length(), m = b.length(); for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if(a.charAt(i - 1) == b.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); } } return dp[n][m]; } static String findword(int dp[][], String a, String b) { String res = ""; int i = a.length(), j = b.length(); while(i > 0 && j > 0) { if(a.charAt(i - 1) == b.charAt(i - 1)) { res = a.charAt(i - 1) + res; i--; j--; } else if(dp[i - 1][j] > dp[i][j - 1]) i--; else j--; } return res; } }
d9837cb868bf311c9ea2ac8c2badde398a712b4f
dd08849a71940a7cb921dc383e12606e210def97
/src/codechef/problems/SportsStadium.java
fe3743506bf0c2275f5cc188b2e0352f6e9ed7c4
[]
no_license
brhmshrnv/Solutions
e3581cf1fc5ac7c391b3f62ef087b55c195ad345
0d3a6124030bbe2a2c5b653fc957eba19b631978
refs/heads/master
2022-12-17T22:52:19.455791
2020-09-26T11:15:52
2020-09-26T11:15:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,189
java
package codechef.problems; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class SportsStadium { public static void main(String[] args) { Scanner in = new Scanner(System.in); int stadiums = in.nextInt(); Slot[] slots = new Slot[stadiums]; for (int s = 0; s < stadiums; s++) { slots[s] = new Slot(in.nextInt(), in.nextInt()); } Arrays.sort(slots, new Slot(-1, -1)); //System.out.println(Arrays.asList(slots)); int max = getMaxAlloc(slots); System.out.println(max); } private static int getMaxAlloc(Slot[] slots) { // greedy approach. int count = 1; int end = slots[0].end; for (int i = 1; i < slots.length; i++) { //System.out.println(slots[i].start); if (slots[i].start >= end) { count++; end = slots[i].end+1; } } return count; } static class Slot implements Comparator<Slot> { private final int start, end; public Slot(int start, int length) { this.start = start; this.end = this.start + length; } @Override public String toString() { return this.start+"-"+this.end; } @Override public int compare(Slot s1, Slot s2) { return (s1.end - s2.end); } } }
[ "Gurpreet-makkar" ]
Gurpreet-makkar
e16cb32770c0e316452ad1ba7a1495b3d6f46aa2
0acae11d24e7ada2de6c5bf7acd2223435019801
/pattern 13.java
99e3429fa5ca8c61b6ea7878417d7f4102a55feb
[]
no_license
govindersingh/java-pattern
29f0f30eff13b26a063ff9ed04e30e12a94290ec
ebaa7f89596683d430c1c50439de405d980b9cd1
refs/heads/master
2020-12-02T16:21:55.472886
2017-07-07T22:55:19
2017-07-07T22:55:19
96,539,931
0
0
null
null
null
null
UTF-8
Java
false
false
204
java
class abc { public static void main(String args[]) { int i,j,k; for(i=1;i<=5;i++) { for(j=4;j>=i;j--) { System.out.print(" "); } for(k=1;k<=i;k++) { System.out.print(" *"); } System.out.println(); } } }
4e312487b85d9f3c3c7fab2182d804d3cec75fad
520ecca55a17e5edb5edc8edf28afd82b9b6adcf
/app/src/main/java/home/work/pcconfig/ui/viewer/OrdersAdapter.java
51580a6e6563b15fa78a51930a37ec0a13faab95
[]
no_license
MrVilkaman/Ivan_pc_config
b50bc2ad368ca53dd024e8bcad42f23679e27159
e1d5d959794c61d88e067061260d9c398167c643
refs/heads/master
2021-04-28T08:12:34.750629
2018-02-21T19:23:51
2018-02-21T19:23:51
122,243,627
0
0
null
null
null
null
UTF-8
Java
false
false
4,905
java
package home.work.pcconfig.ui.viewer; import android.content.res.Resources; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.TextView; import com.github.mrvilkaman.di.PerActivity; import com.github.mrvilkaman.presentationlayer.fragments.core.BaseVH; import com.github.mrvilkaman.presentationlayer.fragments.core.ItemListener; import com.github.mrvilkaman.presentationlayer.fragments.core.MySimpleBaseAdapter; import com.github.mrvilkaman.presentationlayer.utils.ui.UIUtils; import java.util.Set; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import home.work.pcconfig.R; import home.work.pcconfig.business.models.OrderItem; @PerActivity public class OrdersAdapter extends MySimpleBaseAdapter<OrderItem, OrdersAdapter.OrdersVH> implements GetSelectionHelper { private final static int NO_SELECTION = -1; private int currentSelection = NO_SELECTION; private SelectionHelper selectionHelper; @Inject public OrdersAdapter() { selectionHelper = new SelectionHelper() { @Override public boolean isSelected(int pos) { return pos == currentSelection; } @Override public void setSelected(int pos) { if (isSelected(pos)) { currentSelection = NO_SELECTION; } else if (currentSelection != NO_SELECTION) { int oldSelection = currentSelection; currentSelection = pos; notifyItemChanged(oldSelection); } else { currentSelection = pos; } notifyItemChanged(pos); } }; } @Override protected OrdersVH getHolder(@NonNull View view) { return new OrdersVH(view, selectionHelper); } @Override protected int getLayoutId() { return R.layout.item_order_list_layout; } @Override @Nullable public OrderItem getSelected() { if (currentSelection != NO_SELECTION) { return getItem(currentSelection); } else { return null; } } @Override public void resetSelection() { int oldSelection = currentSelection; currentSelection = NO_SELECTION; notifyItemChanged(oldSelection); } private interface SelectionHelper { void setSelected(int pos); boolean isSelected(int pos); } public static class OrdersVH extends BaseVH<OrderItem> { private final SelectionHelper selectionHelper; @BindView(R.id.order_number) TextView number; @BindView(R.id.order_main_info) TextView mainInfo; @BindView(R.id.order_gaming_info) TextView gamingInfo; OrdersVH(View view, SelectionHelper selectionHelper) { super(view); this.selectionHelper = selectionHelper; ButterKnife.bind(this, view); } @Override public void setListeners(@NonNull View view, ItemListener<OrderItem> onClick, ItemListener<OrderItem> onLongClick) { view.setOnClickListener(view1 -> { selectionHelper.setSelected(getAdapterPosition()); }); } @Override public void bind(@NonNull OrderItem item, int position, Set<String> payloads) { final Resources resources = itemView.getResources(); final StringBuilder builder = new StringBuilder(); number.setText(resources.getString(R.string.number_format, item.getId())); String storageType = resources.getString(item.isSsd() ? R.string.storage_ssd : R.string.storage_hhd); builder.append(resources.getString(R.string.cpu_intel_core_i_format, item.getCpuInterType())) .append("\n") .append(resources.getString(R.string.motherboard_format, item.getMotherBoard())) .append("\n") .append(resources.getString(R.string.gpu_format, item.getGpu())) .append("\n") .append(resources.getString(R.string.ram_format, item.getRamSize())) .append("\n") .append(resources.getString(R.string.storage_format, storageType, item.getStogareSize())); UIUtils.changeVisibility(gamingInfo, item.isGaming()); mainInfo.setText(builder.toString()); if (selectionHelper.isSelected(position)) { itemView.setBackgroundColor(ContextCompat.getColor(itemView.getContext(), R.color.md_btn_selected)); } else { itemView.setBackground(null); } } } }
7bb670d8e9212e03c7a78063c51dbcf89fd8339b
e946bfd11bb25af8741807c29e9015e0f69bbf3c
/src/com/example/android_projekt/individ/IndividualDB.java
385e5f57912b81798378a658fb5f76ad52bf47ff
[]
no_license
jobe0900/android-brunst
cdf155053cb62953c90de125d32de46e60ce4847
8de9d911775a78a6e236f18149520b79510c6857
refs/heads/master
2021-01-10T09:53:21.809442
2014-06-22T17:06:36
2014-06-22T17:06:36
47,702,946
0
0
null
null
null
null
UTF-8
Java
false
false
10,213
java
package com.example.android_projekt.individ; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.example.android_projekt.BrunstDBHelper; import com.example.android_projekt.Utils; import com.example.android_projekt.productionsite.ProductionSite; import com.example.android_projekt.productionsite.ProductionSiteNr; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.provider.BaseColumns; import android.util.Log; /** * Helper class, "contract", handling the database work for the Individual * @author Jonas Bergman, <[email protected]> */ public class IndividualDB implements BaseColumns { private final static String TAG = "Brunst: IndividualDB"; public static final String TABLE_NAME = "Individual"; public static final String COLUMN_IDNR = "idnr"; public static final String COLUMN_SHORTNR = "shortnr"; public static final String COLUMN_BIRTHDATE = "birthdate"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_SEX = "sex"; public static final String COLUMN_ACTIVE = "active"; public static final String COLUMN_LASTBIRTH = "lastbirth"; public static final String COLUMN_LACTATIONNR = "lactationnr"; public static final String COLUMN_HEATCYCLUS = "heatcyclus"; public static final String COLUMN_HOMESITE = "homesite"; public static final String COLUMN_MOTHERIDNR = "motheridnr"; public static final String COLUMN_FATHERIDNR = "fatheridnr"; public static final String COLUMN_IMAGEURI = "imageuri"; private static final String[] ALL_COLUMNS = { BaseColumns._ID, COLUMN_IDNR, COLUMN_SHORTNR, COLUMN_BIRTHDATE, COLUMN_NAME, COLUMN_SEX, COLUMN_ACTIVE, COLUMN_LASTBIRTH, COLUMN_LACTATIONNR, COLUMN_HEATCYCLUS, COLUMN_HOMESITE, COLUMN_MOTHERIDNR, COLUMN_FATHERIDNR, COLUMN_IMAGEURI }; private static final String SQL_CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_IDNR + " CHAR(16) UNIQUE NOT NULL, " + COLUMN_SHORTNR + " SMALLINT, " + COLUMN_BIRTHDATE + " DATE, " + COLUMN_NAME + " VARCHAR(40), " + COLUMN_SEX + " CHAR(1) NOT NULL, " + COLUMN_ACTIVE + " BOOLEAN NOT NULL, " + COLUMN_LASTBIRTH + " DATE, " + COLUMN_LACTATIONNR + " SMALLINT NOT NULL, " + COLUMN_HEATCYCLUS + " SMALLINT NOT NULL, " + COLUMN_HOMESITE + " CHAR(9) NOT NULL, " + COLUMN_MOTHERIDNR + " CHAR(16), " + COLUMN_FATHERIDNR + " CHAR(16), " + COLUMN_IMAGEURI + " VARCHAR(255), " + "FOREIGN KEY (homesite) REFERENCES ProductionSite(sitenr) ON DELETE CASCADE" + " ) "; private static final String SQL_DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME; private SQLiteDatabase database; private BrunstDBHelper dbHelper; /** Constructor. */ public IndividualDB(Context context) { dbHelper = new BrunstDBHelper(context); } /** Try to open the database to do some work. */ public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } /** Close the database again. */ public void close() { dbHelper.close(); } /** Create this table in the DB. */ public static void onCreate(SQLiteDatabase database) { Log.d(TAG, "creating table Individual"); database.execSQL(SQL_CREATE_TABLE); } /** Upgrade this table to a new version in the DB. */ public static void onUpgrade(SQLiteDatabase database) { // nothing for now. } /** * Save a new Individual, or update an existing. * @param individ The Individual to save/update. * @return true on successful write, or else false */ public boolean saveIndividual(Individual individ) { boolean retval = false; // The values to store ContentValues values = new ContentValues(); values.put(COLUMN_IDNR, individ.getIdNr().toString()); values.put(COLUMN_SHORTNR, individ.getShortNr()); if(individ.hasBirthdate()) values.put(COLUMN_BIRTHDATE, Utils.dateToString(individ.getBirthdate())); if(individ.hasName()) values.put(COLUMN_NAME, individ.getName()); values.put(COLUMN_SEX, individ.getSexAsString()); values.put(COLUMN_ACTIVE, individ.isActive()); if(individ.hasLastBirth()) values.put(COLUMN_LASTBIRTH, Utils.dateToString(individ.getLastBirth())); values.put(COLUMN_LACTATIONNR, individ.getLactationNr()); values.put(COLUMN_HEATCYCLUS, individ.getHeatcyclus()); values.put(COLUMN_HOMESITE, individ.getHomesiteNr().toString()); if(individ.hasMotherIdNr()) values.put(COLUMN_MOTHERIDNR, individ.getMotherIdNr().toString()); if(individ.hasFatherIdNr()) values.put(COLUMN_FATHERIDNR, individ.getFatherIdNr().toString()); if(individ.hasImageUri()) values.put(COLUMN_IMAGEURI, individ.getImageUri()); // unsaved Individual if(individ.get_id() == Individual.UNSAVED_ID) { long insertId = database.insert(TABLE_NAME, null, values); Log.d(TAG, "save new individual, insertID: " + insertId); if(insertId != -1) { retval = true; } } // updating existing Individual else { String selection = BaseColumns._ID + " LIKE ?"; String[] selectionArgs = {String.valueOf(individ.get_id())}; int count = database.update(TABLE_NAME, values, selection, selectionArgs); Log.d(TAG, "update individual, count: " + count); if(count != 0) { retval = true; } } return retval; } /** * Don't actually delete, just mark as not active, meaning the information * for the Individual is available in the future if necessary. * @param idNr * @return */ public int deleteIndividual(IdNr idNr) { ContentValues values = new ContentValues(); values.put(COLUMN_ACTIVE, "FALSE"); String selection = COLUMN_IDNR + " LIKE ?"; String[] selectionArgs = {idNr.toString()}; return database.update(TABLE_NAME, values, selection, selectionArgs); } /** * Get a single individual from the DB. * @param idNr ID for the individual to fetch. * @return Individual or null */ public Individual getIndividual(IdNr idNr) { String selection = COLUMN_IDNR + " LIKE ? AND " + COLUMN_ACTIVE + " LIKE ?"; String[] selectionArgs = {idNr.toString(), "1"}; Cursor cursor = database.query(TABLE_NAME, ALL_COLUMNS, selection, selectionArgs, null, null, null); Individual individ = null; if(cursor.getCount() == 1) { cursor.moveToFirst(); individ = createFromCursor(cursor); } cursor.close(); return individ; } /** * Get a list of all Individs at a ProductionSite * @param site The ProductionSite where the Individs belong * @return list of all Individs at ProductionSite */ public List<Individual> getAllIndividualsAtSite(ProductionSite site) { List<Individual> individs = new ArrayList<Individual>(); String selection = COLUMN_HOMESITE + " LIKE ? AND " + COLUMN_ACTIVE + " LIKE ?"; String[] selectionArgs = {site.getSiteNr().toString(), "1"}; String sortorder = COLUMN_SHORTNR + " ASC"; Cursor cursor = database.query(TABLE_NAME, ALL_COLUMNS, selection, selectionArgs, null, null, sortorder); cursor.moveToFirst(); while(!cursor.isAfterLast()) { Individual individ = createFromCursor(cursor); individs.add(individ); cursor.moveToNext(); } cursor.close(); return individs; } /** * Get a list of all individuals at a ProductionSite, as string * to be used as Spinner titles, like "123 Rosa (SE-012345-0123-5)" * @param siteNrStr * @return */ public List<String> getAllIndividualsAtSiteAsSpinnerTitles(String siteNrStr) { List<String> individs = new ArrayList<String>(); String[] titleCols = {COLUMN_SHORTNR, COLUMN_NAME, COLUMN_IDNR}; String selection = COLUMN_HOMESITE + " LIKE ? AND " + COLUMN_ACTIVE + " LIKE ?"; String[] selectionArgs = {siteNrStr, "1"}; String sortorder = COLUMN_SHORTNR + " ASC"; Cursor cursor = database.query(TABLE_NAME, titleCols, selection, selectionArgs, null, null, sortorder); cursor.moveToFirst(); Log.d(TAG, "nr individs hit count: " + cursor.getCount()); while(!cursor.isAfterLast()) { String individ = cursor.getInt(0) + " "; // short nr if(!cursor.isNull(1)) { // name individ += cursor.getString(1) + " "; } individ += "(" + cursor.getString(2) + ")"; Log.d(TAG, "consutrcted individual title: " + individ); individs.add(individ); cursor.moveToNext(); } cursor.close(); return individs; } /** * Construct an Individual from the row pointed to by the Cursor. * @param cursor Pointer to a row in the Individual DB table. * @return An Individual */ private Individual createFromCursor(Cursor cursor) { String idNrStr = cursor.getString(1); String homeSiteStr = cursor.getString(10); Individual individ = null; try { Log.d(TAG, "cursor count: " + cursor.getCount() + ", columns: " + cursor.getColumnCount()); for(int i = 0; i < cursor.getColumnCount(); ++i) { Log.d(TAG, " " + i + ": " + cursor.getColumnName(i) + ": " + cursor.getString(i)); } individ = new Individual(new IdNr(idNrStr), new ProductionSiteNr(homeSiteStr)); individ.set_id(cursor.getLong(0)); if(!cursor.isNull(2)) individ.setShortNr(cursor.getInt(2)); if(!cursor.isNull(3)) individ.setBirthdate(Utils.stringToDate(cursor.getString(3))); if(!cursor.isNull(4)) individ.setName(cursor.getString(4)); if(!cursor.isNull(5)) individ.setSex(cursor.getString(5)); if(!cursor.isNull(6)) individ.setActive(cursor.getInt(6) == 1); if(!cursor.isNull(7)) individ.setLastBirth(Utils.stringToDate(cursor.getString(7))); if(!cursor.isNull(8)) individ.setLactationNr(cursor.getInt(8)); if(!cursor.isNull(9)) individ.setHeatcyclus(cursor.getInt(9)); if(!cursor.isNull(11)) individ.setMotherIdNr(new IdNr(cursor.getString(11))); if(!cursor.isNull(12)) individ.setFatherIdNr(new IdNr(cursor.getString(12))); if(!cursor.isNull(13)) individ.setImageUri(cursor.getString(13)); } catch (ParseException e) { // TODO Auto-generated catch block Log.d(TAG, "Unabled to create Individual from String"); e.printStackTrace(); } return individ; } }
54cf64bb106bf3295e5960f1fcc9f96cf1b288b9
d18af2a6333b1a868e8388f68733b3fccb0b4450
/java/src/com/google/android/gms/internal/zzaf$7.java
a4475f7594a1f9bf09671590cd65036d0912c8da
[]
no_license
showmaxAlt/showmaxAndroid
60576436172495709121f08bd9f157d36a077aad
d732f46d89acdeafea545a863c10566834ba1dec
refs/heads/master
2021-03-12T20:01:11.543987
2015-08-19T20:31:46
2015-08-19T20:31:46
41,050,587
0
1
null
null
null
null
UTF-8
Java
false
false
678
java
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.google.android.gms.internal; import java.util.Map; // Referenced classes of package com.google.android.gms.internal: // zzcv, zzaf, zzic class zznI implements zzcv { final zzaf zznI; public void zza(zzic zzic1, Map map) { if (!zznI.zza(map)) { return; } else { zznI.zza(zzic1.getWebView(), map); return; } } (zzaf zzaf1) { zznI = zzaf1; super(); } }
4c3cdfdbe1dd5dd9be05bfd9f0ed7bf56d92b875
ea54df435833bfbfc93b20e4efc48c40eb001977
/src/main/java/com/rockagen/gnext/po/KeyValue.java
b23ac4cc1bfd575538b7a1fdf4a9e501ebb683ab
[ "Apache-2.0" ]
permissive
rockagen/security-stateless-samples
ae9fe58564c0f462645bf9e6fcd4439540faa09f
716843c318dfc5d953184ef1d89198b79b63cd50
refs/heads/master
2021-01-02T10:25:37.182983
2015-06-12T09:37:26
2015-06-12T09:37:26
29,226,285
3
0
null
null
null
null
UTF-8
Java
false
false
2,045
java
/* * Copyright 2014-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rockagen.gnext.po; import javax.persistence.*; import java.io.Serializable; /** * Key-Value configuration file * @author RA * @since JPA2.0 */ @Entity @Table( name="KEY_VALUES" ) public class KeyValue implements Serializable{ @Id @Column(name = "ID") @GeneratedValue private Long id; @Column(name = "KEY",unique=true) private String key; @Column(name = "VALUE",length = 1024) private String value; /** * Active ? * <ul> * <li>!0 is active</li> * <li>0 is inactive </li> * </ul> */ @Column(name = "ACTIVE") private Integer active; @Column(name = "DESCR", length = 512) private String descr; @Version private Long version; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Integer getActive() { return active; } /** * Active ? * <ul> * <li>!0 is active</li> * <li>0 is inactive </li> * </ul> */ public void setActive(Integer active) { this.active = active; } public String getDescr() { return descr; } public void setDescr(String descr) { this.descr = descr; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } }
d20ef7d976c419728edb53b4a889bc9f285f6e9f
9a48041212cdbffe64c4c6fa7f7bf8e4397905b9
/src/com/weibo/util/SimpleWebClient.java
d82c94af5b13f0d867d8480381fc4b1edae7ade9
[]
no_license
renhuaigui/SinaWeiboCrawler
883f753f71f43a334136fe0a2cb4a31ac23a71f7
8db49dc6d26807a2290d471783ed7bafb75bc95c
refs/heads/master
2021-01-10T05:05:59.044557
2017-04-18T05:00:59
2017-04-18T05:00:59
54,010,097
0
0
null
null
null
null
UTF-8
Java
false
false
8,238
java
package com.weibo.util; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.zip.GZIPInputStream; import org.apache.log4j.Logger; import com.weibo.Config; public class SimpleWebClient { /** 日志对象. */ private static Logger logger = Logger.getLogger(SimpleWebClient.class); /** * 根据URL,下载网站的页面. * @param pageURL * @param cookie * @return WebPage */ public WebPage getPageContent(String pageURL, String cookie) { WebPage webPage = null; try { //休眠10秒钟 Thread.currentThread().sleep(Config.THREAD_SLEEP); //页面的编码 String contentEncoding = ""; //页面类型 String contentType = ""; //页面的大小 int contentLength = -1; //数据字节流 byte []data = null; //数据读取的位置 int bytesRead = 0; int offset = 0; URL url = new URL(pageURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); //设置请求的参数 conn.setRequestMethod("GET"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"); conn.setRequestProperty("Accept", "text/html,application/xhtml+xml," + "application/xml;q=0.9,image/webp,*/*;q=0.8"); conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8"); //在HTTP压缩传输中启用启用Gzip的方法:发送HTTP请求的时候在HTTP头中增加: Accept-Encoding:gzip,deflate conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch"); conn.setRequestProperty("Accept-Charset", "gb2312,utf-8;q=0.7,*;q=0.7"); // weibo cookie if (cookie != null && !"".equals(cookie)) { conn.setRequestProperty("Cookie", cookie); } //设置链接超时 conn.setConnectTimeout(10 * 60 * 1000); conn.setReadTimeout(10 * 60 * 1000); conn.connect(); /* //显示返回的请求的Header信息. for (int i = 1;; i++) { String header = conn.getHeaderField(i); if (header == null) { break; } logger.debug(conn.getHeaderFieldKey(i) + " : " + header); }*/ //从Header头部查找字符编码 contentType = conn.getContentType(); //System.out.println("conn.getContentType() " + conn.getContentType()); //System.out.println("conn.getContentType() " + conn.getHeaderField("Contetnt-Type")); if (contentType != null && (contentType.toLowerCase().indexOf("charset") != -1)) { contentType = contentType.toLowerCase(); try { contentEncoding = contentType.substring(contentType.indexOf("charset=") + "charset=".length()); } catch (Exception e) { e.printStackTrace(); } } contentLength = conn.getContentLength(); int responseCode = conn.getResponseCode(); logger.info(pageURL + "\t" + responseCode); //System.out.println("contentLength = " +contentLength); //如果有Conent-Length字段,就按指定的大小读取数据;但是如果用“gzip”压缩传送,就不能Conent-Length长度以为准。 if (contentLength != -1) { InputStream in = null; //判断数据是否压缩? if (conn.getContentEncoding() != null && conn.getContentEncoding().indexOf("gzip") > -1) { in = new GZIPInputStream(conn.getInputStream()); //把数据暂时保存在内存中 ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); data = new byte[4096]; int read = 0; while ((read = in.read(data)) != -1) { arrayOutputStream.write(data, 0, read); } data = arrayOutputStream.toByteArray(); arrayOutputStream.close(); } else { in = new BufferedInputStream(conn.getInputStream()); data = new byte[contentLength]; bytesRead = 0; offset = 0; while (offset < contentLength) { bytesRead = in.read(data, offset, data.length - offset); if (bytesRead == -1) { break; } offset += bytesRead; } } in.close(); //取得页面字符集 if (contentEncoding == null || contentEncoding.equals("")) { contentEncoding = getCharset(new String(data, 0, data.length)); if (contentEncoding.equalsIgnoreCase("gb2312")) { contentEncoding = "gbk"; } } //关闭链接 conn.disconnect(); } else { //如果不知道数据大小,循环读取,直到没有数据. InputStream in = null; if (conn.getContentEncoding() != null && conn.getContentEncoding().indexOf("gzip") > -1) { in = new GZIPInputStream(conn.getInputStream()); } else { in = new BufferedInputStream(conn.getInputStream()); } //把数据暂时保存在内存中 ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); data = new byte[4096]; int read = 0; while ((read = in.read(data)) != -1) { arrayOutputStream.write(data, 0, read); } arrayOutputStream.close(); in.close(); //关闭链接 conn.disconnect(); data = arrayOutputStream.toByteArray(); //取得页面字符集 if (contentEncoding.equals("") || contentEncoding == null) { contentEncoding = getCharset(new String(data, 0, 1000)); if (contentEncoding.equalsIgnoreCase("gb2312")) { contentEncoding = "gbk"; } } } webPage = new WebPage(); webPage.setHref(pageURL); webPage.setContentEncoding(contentEncoding); webPage.setContentLength(data.length); webPage.setHtml(new String(data, 0, data.length, contentEncoding)); return webPage; } catch (Exception e) { e.printStackTrace(); return webPage; } } /** * 取得页面的字符集. * @param content 页面开头的一段字符串 * @return 字符集类型 */ public String getCharset(String content) { try { String contentEncoding = ""; content = content.toLowerCase(); if (content != null && content.indexOf("content-type") > -1) { contentEncoding = content.substring(content.indexOf("charset=")); contentEncoding = contentEncoding.substring(contentEncoding.indexOf("charset=") + "charset=".length()); contentEncoding = contentEncoding.substring(0, contentEncoding.indexOf("\"")); } else { contentEncoding = "gbk"; } return contentEncoding; } catch (Exception e) { e.printStackTrace(); return "gbk"; } } }
6f60392f5ea5b9fb22b2de82eb132ee2f54f7925
5a44f08379ffe558c1bc4979770e540d029239cd
/core/src/com/youtoolife/labyrinth/events/InvokeEvent.java
751bce19aa4561337487a41de6537013b560f040
[]
no_license
YouTooLifeTeam/labyrinth
be74831a424756f3f645d03cb096a5de46061604
7c05249064861d3977a67f63b58be53710c836d0
refs/heads/master
2021-01-10T18:26:19.644928
2015-05-07T06:18:21
2015-05-07T06:18:21
28,446,482
2
0
null
null
null
null
UTF-8
Java
false
false
754
java
package com.youtoolife.labyrinth.events; import java.util.Vector; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.youtoolife.labyrinth.chunk.Chunk; import com.youtoolife.labyrinth.units.Unit; public abstract class InvokeEvent { public Element base; public int rotates = 0; public Vector<ActionEvent> events = new Vector<ActionEvent>(); public InvokeEvent(Element e){ this.base = e; NodeList evs = e.getElementsByTagName("ActionEvent"); for(int i = 0;i<evs.getLength();i++){ events.add(ActionResolver.getEvent((Element) (evs.item(i)))); } } public abstract void check(Chunk chunk); public abstract void invoke(Chunk chunk, Unit unit); public abstract void rotate(); public abstract InvokeEvent copy(); }
1a4e22087228364adbd37653e641d5703ddeb8c9
e2392533ca0d6d63ee64033af8aa15753087582c
/src/streetmap/pathfinding/AStarAlgorithm.java
26b35df538b34a501dfe89d6c07908fe42caee19
[]
no_license
Moepelchen/StreetMap
71a491f6bfe28f565ef15658c686b21c3987bcbb
5ed1f8ce889bad2ec3e7e3b297a6b371eb4fe9fe
refs/heads/master
2020-04-27T15:18:43.191275
2014-10-27T14:29:30
2014-10-27T14:29:30
2,830,266
0
0
null
null
null
null
UTF-8
Java
false
false
6,057
java
/* * Copyright (C) Ulrich Tewes GmbH 2010-2014. */ package streetmap.pathfinding; import streetmap.car.Car; import streetmap.map.street.Lane; import java.awt.*; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; /** * Short description in a complete sentence. * <p/> * Purpose of this class / interface * Say how it should be and should'nt be used * <p/> * Known bugs: None * Historical remarks: None * * @author Ulrich Tewes * @version 1.0 * @since Release */ public class AStarAlgorithm extends AbstractPathFinder { private SortedNodeList fOpenList; private List<Lane> fClosedList; private static HashMap<String,LinkedList<Lane>> fPathList = new HashMap<String, LinkedList<Lane>>(); @Override protected boolean createPath(Lane start) { /*if(fPathList.get(fStart.hashCode() + fEnd.hashCode()) != null) { fPath = new LinkedList<Lane>(fPathList.get(fStart.hashCode() + fEnd.hashCode())); return true; }*/ fClosedList = new ArrayList<Lane>(); fOpenList = new SortedNodeList(); Graphics2D g = start.getEnd().getSide().getTile().getMap().getTheGraphics(); double fromStartToEnd = start.getStart().getPosition().distance(fEnd.getEnd().getPosition()); Candidate current = new Candidate(start); current.fDistanceToGoal = fromStartToEnd; fOpenList.add(current); while (fOpenList.size() != 0) { fOpenList.sort(); current = fOpenList.getFirst(); fOpenList.remove(current); //draw(g, current); if(current.candidate.equals(fEnd)) { getPath(current); fPathList.put(fStart.hashCode()+"" + fEnd.hashCode(),fPath); return true; } fClosedList.add(current.candidate); for (Lane lane : current.candidate.getEnd().getOutputLanes()) { Candidate neighbour = new Candidate(lane); if(fClosedList.contains(lane)) continue; double distanceToStart = current.fDistanceToStart + lane.getTrajectory().getLength(); double distanceToEnd = lane.getEnd().getPosition().distance(fEnd.getEnd().getPosition()); double heatMapReading = getHeatMapReading(lane); distanceToStart = distanceToStart + fGlobals.getConfig().getHeatMapModifier()* heatMapReading; if(fOpenList.contains(neighbour) && distanceToStart >= fOpenList.getByLane(neighbour).fDistanceToStart) continue; neighbour.setPrevious(current); neighbour.setDistanceToStart(distanceToStart); neighbour.fDistanceToGoal = distanceToEnd; if (fOpenList.contains(neighbour)) { fOpenList.getByLane(neighbour).fDistanceToStart = distanceToStart; } else { fOpenList.add(neighbour); } } } return false; } private void draw(Graphics2D g, Candidate current) { for (Lane lane : fClosedList) { g.setColor(Color.BLUE); g.drawOval((int) lane.getEnd().getPosition().getX(), (int) lane.getEnd().getPosition().getY(), 5, 5); } for (Candidate openListLane : fOpenList.getList()) { g.setColor(Color.GREEN); g.drawOval((int) openListLane.candidate.getEnd().getPosition().getX(), (int) openListLane.candidate.getEnd().getPosition().getY(), 5, 5); } g.setColor(Color.MAGENTA); g.drawOval((int) current.candidate.getEnd().getPosition().getX(), (int) current.candidate.getEnd().getPosition().getY(), 5, 5); g.setColor(Color.MAGENTA); g.drawOval((int) fEnd.getEnd().getPosition().getX(), (int) fEnd.getEnd().getPosition().getY(), 5, 5); } private double getHeatMapReading(Lane lane) { double heatMapReading= 0; Lane random = lane.getEnd().getRandomLane(); if(random != null) { Point2D arrayPosition = random.getEnd().getSide().getTile().getArrayPosition(); heatMapReading = fGlobals.getMap().getHeatMapReading(arrayPosition); } return heatMapReading * Math.min(1,lane.getCars().size()); } private void getPath(Candidate current) { fPath.addFirst(current.candidate); if(current.previous() != null) { getPath(current.previous()); } } public AStarAlgorithm(Car car) { init(car); } @Override public void update() { if(fEnd != null) { fPath.clear(); createPath(fCar.getLane()); } } private class SortedNodeList { private ArrayList<Candidate> list = new ArrayList<Candidate>(); private HashMap<Integer, Candidate> hash = new HashMap<Integer, Candidate>(); public Candidate getFirst() { return list.get(0); } public void clear() { list.clear(); } public void add(Candidate candidate) { list.add(candidate); hash.put(candidate.hashCode(), candidate); } public void remove(Candidate n) { list.remove(n); hash.remove(n.hashCode()); } public int size() { return list.size(); } public boolean contains(Candidate n) { return hash.get(n.hashCode()) != null; } public Candidate getByLane(Candidate n) { return hash.get(n.hashCode()); } public List<Candidate> getList() { return list; } public void sort() { Collections.sort(list); } } // ----------------------------------------------------- // constants // ----------------------------------------------------- // ----------------------------------------------------- // variables // ----------------------------------------------------- // ----------------------------------------------------- // inner classes // ----------------------------------------------------- // ----------------------------------------------------- // constructors // ----------------------------------------------------- // ----------------------------------------------------- // methods // ----------------------------------------------------- // ----------------------------------------------------- // overwritten methods from superclasses // ----------------------------------------------------- // ----------------------------------------------------- // accessors // ----------------------------------------------------- } //AStarAlgorithm
bb4b9bad89918b21aad6f8c9a3c41bea21c372c6
6d671eb0bfc58d86a789dbe122a900f62aaaab43
/src/com/hhh/trees/Tree.java
f20f871192eda7ce5bc3da50a13a84a90596bf65
[]
no_license
harshssd/BinarySearchTree
68bb82b733714f66f7f68527b9436ab835f4aa74
b7b8d6c1736e1dae162b32f83056ba1668201bc3
refs/heads/master
2021-03-12T22:35:34.416189
2014-09-09T14:05:33
2014-09-09T14:05:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,839
java
package com.hhh.trees; import java.util.ArrayList; public class Tree { private Node root; //populated after running in order method public ArrayList<Integer> elementsInOrder = new ArrayList<Integer>(); //populated after running pre order method public ArrayList<Integer> elementsPreOrder = new ArrayList<Integer>(); //populated after running post order method public ArrayList<Integer> elementsPostOrder = new ArrayList<Integer>(); public Tree(int d) { root = new Node(d); } public Node getRoot() { return root; } public void setRoot(Node root) { this.root = root; } public void insert(int d){ Node current = root; Node parent = null; // track down to bottom while(current != null){ if(d < current.getData()){ parent = current; current = current.getLeft(); }else { parent = current; current = current.getRight(); } } // add node on the appropriate side if(d<parent.getData()) parent.setLeft(new Node(d)); else parent.setRight(new Node(d)); } public Node insertRecursive(int d, Node node) { if(node == null) return new Node(d); else if(d < node.getData()) { node.setLeft(insertRecursive(d, node.getLeft())); return node; }else { node.setRight(insertRecursive(d, node.getRight())); return node; } } public void printInOrder(Node root){ if(root!=null){ printInOrder(root.getLeft()); System.out.print("-->"+root.getData()); this.elementsInOrder.add(root.getData()); printInOrder(root.getRight()); } } public void printPreOrder(Node root){ if(root!=null){ System.out.print("-->"+root.getData()); this.elementsPreOrder.add(root.getData()); printPreOrder(root.getLeft()); printPreOrder(root.getRight()); } } public void printPostOrder(Node root){ if(root!=null){ printPostOrder(root.getLeft()); printPostOrder(root.getRight()); System.out.print("-->"+root.getData()); this.elementsPostOrder.add(root.getData()); } } public int getSize() { return getSizeFromNode(getRoot()); } private int getSizeFromNode(Node node) { if(node == null) return 0; else return 1 + getSizeFromNode(node.getLeft()) + getSizeFromNode(node.getRight()); } public int getMin() { Node current = getRoot(); while(current.getLeft()!=null){ current = current.getLeft(); } return current.getData(); } public int getMax() { Node current = getRoot(); while(current.getRight()!=null){ current = current.getRight(); } return current.getData(); } public boolean lookUp(int searchKey){ return lookUpFromNode(searchKey, getRoot()); } private boolean lookUpFromNode(int searchKey, Node node) { if(node == null) return false; else if (searchKey == node.getData()) return true; else if (searchKey < node.getData()) return lookUpFromNode(searchKey, node.getLeft()); else return lookUpFromNode(searchKey, node.getRight()); } public Node delete(int deleteKey) { return deleteFromNode(deleteKey, getRoot()); } private Node deleteFromNode(int deleteKey, Node node) { if(node == null) return node; else if(deleteKey < node.getData()){ node.setLeft(deleteFromNode(deleteKey, node.getLeft())); return node; } else if(deleteKey > node.getData()){ node.setRight(deleteFromNode(deleteKey, node.getRight())); return node; } else{ // No child if(node.getLeft() == null && node.getRight() == null) return null; // Only One Child else if(node.getLeft() == null) return node.getRight(); else if(node.getRight() == null) return node.getLeft(); // Two Children else { Node minNode = node.getRight(); while(minNode.getLeft() != null) minNode = minNode.getLeft(); node.setData(minNode.getData()); deleteFromNode(minNode.getData(), minNode); return node; } } } }
6d0d5ead0810647a3618f2d1e2223868d09b5d4a
7412831ae9097fdbd4089ea1edc059f164ba9644
/src/bus/SinComparator.java
58d4c6353ccfe1d839c5d005d762e62a27952a8d
[]
no_license
fmaldonadot/IT-Soft_V2.0
3d638f601c19e994f3c669356525f1b905fda8a6
f61a477a4a4ba43ac9d84c750bf519377fecfbef
refs/heads/master
2020-03-08T05:55:26.812903
2018-04-03T19:24:50
2018-04-03T19:24:50
127,959,009
0
0
null
null
null
null
UTF-8
Java
false
false
356
java
package bus; import java.util.Comparator; public class SinComparator implements Comparator<Employee> { public int compare(Employee e1, Employee e2) { if ( e1.getSocial_security().compareTo(e2.getSocial_security()) > 0) return 1; else if ( e1.getSocial_security().compareTo(e2.getSocial_security()) < 0) return -1; return 0; } }
0ff4e857ee53e5db42eaf948c69b6086cf5fd0a7
98c9d4575781bfbd26fa20673ba5a216c4a06429
/src/main/java/com/minshang/erp/common/vo/AccessToken.java
18c69cd57cec699a2a36341650ab618f1670e6fa
[]
no_license
JackLuhan/minshang_back
e06e21899b142a489715fa8110cfad5874992ad8
f54c6a36798005012029d96b355ba9518a33aef3
refs/heads/master
2020-04-13T17:50:56.929733
2019-01-10T16:38:03
2019-01-10T16:38:03
163,357,735
1
5
null
null
null
null
UTF-8
Java
false
false
152
java
package com.minshang.erp.common.vo; import lombok.Data; /** * @author houyi */ @Data public class AccessToken { private String access_token; }
12e19389a50ef742857f9fbef94df493842a443c
2f3150334028e42fd95a4dd5d474dc819a5b09bd
/app/src/main/java/com/terryyamg/bluetoothdatatransfertest/MainActivity.java
eee47cecdbaf4a82e280824d9b39c2c97876a9bb
[]
no_license
terryyamg/BluetoothDataTransferTest
b6dba817bc44cf5990c1ff3061cc35ea21f28481
0b23837107844cf25ae1f49b3583a76cb8cbab16
refs/heads/master
2016-08-09T03:13:13.169248
2015-12-21T09:57:45
2015-12-21T09:57:45
48,364,484
0
0
null
null
null
null
UTF-8
Java
false
false
3,896
java
package com.terryyamg.bluetoothdatatransfertest; import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; public class MainActivity extends AppCompatActivity { private static final int DISCOVER_DURATION = 300; private static final int REQUEST_BLU = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btSend = (Button) findViewById(R.id.btSend); btSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendViaBluetooth(v); } }); } public void sendViaBluetooth(View v) { BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); if (btAdapter == null) { Toast.makeText(this, "裝置沒有藍芽", Toast.LENGTH_LONG).show(); } else { enableBluetooth(); } } //啟動藍芽 public void enableBluetooth() { Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //開啟藍芽時間 discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION); startActivityForResult(discoveryIntent, REQUEST_BLU); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("text/plain");//檔案類型 File file = new File(Environment.getExternalStorageDirectory(), "BluetoothTest.txt"); //建立傳送檔案名稱 String content = "Hello"; //文件內容 try { FileOutputStream fop = new FileOutputStream(file); if (!file.exists()) { // 如果檔案不存在,建立檔案 file.createNewFile(); } byte[] contentInBytes = content.getBytes();// 取的字串內容bytes fop.write(contentInBytes); // 輸出 fop.flush(); fop.close(); } catch (IOException e) { e.printStackTrace(); } intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); PackageManager pm = getPackageManager(); List<ResolveInfo> appsList = pm.queryIntentActivities(intent, 0); if (appsList.size() > 0) { String packageName = null; String className = null; boolean found = false; for (ResolveInfo info : appsList) { packageName = info.activityInfo.packageName; if (packageName.equals("com.android.bluetooth")) { className = info.activityInfo.name; found = true; break; } } if (!found) { Toast.makeText(this, "沒有找到藍芽", Toast.LENGTH_LONG).show(); } else { intent.setClassName(packageName, className); startActivity(intent); } } } else { Toast.makeText(this, "取消", Toast.LENGTH_LONG) .show(); } } }
e823d10b92f99bcd11c64fec4a1bb3444be16497
8dfc9785d2022c5937d1b26eb472c48cb58d0cd2
/Shiro-Limit/src/main/java/com/nh/limit/common/properties/SwaggerProperties.java
8faf902191fce98597af12bfd36ad70030f4a9bf
[]
no_license
iosdouble/ItemLib
da1b924338af2ce84b5bbaf00258d68497f16193
5c4c639dd2bd9ae4c814b3c57f1651cb3760f016
refs/heads/master
2022-09-11T02:01:27.181795
2020-01-03T06:31:21
2020-01-03T06:31:21
214,361,565
0
0
null
2022-09-01T23:13:57
2019-10-11T06:36:07
HTML
UTF-8
Java
false
false
491
java
package com.nh.limit.common.properties; import lombok.Data; /** * @Classname SwaggerProperties * @Description TODO Swagger 配置类封装 * @Date 2019/10/12 9:44 AM * @Created by nihui */ @Data public class SwaggerProperties { private String basePackage; private String title; private String description; private String version; private String author; private String url; private String email; private String license; private String licenseUrl; }
f08653fdfa75c04e23b1be823220f71ff97191a6
bc1e206d958a6a304628ba1b93ad5064fdb44252
/src/test/java/it.algos.vaadflow/ADateServiceTest.java
6c8c07f6884131601dd48fd8ab4b5fba45ee99e6
[]
no_license
algos-soft/vaadflow
a0efa13dffab4408fcf7c1a4d52fd616107e3b05
02a5b99289a1ab5b28a7b7bb00120d9a43375689
refs/heads/master
2023-01-23T08:42:48.028693
2020-10-15T09:08:44
2020-10-15T09:08:44
145,444,963
0
1
null
2023-01-07T16:47:13
2018-08-20T16:44:07
Java
UTF-8
Java
false
false
43,057
java
package it.algos.vaadflow; import it.algos.vaadflow.enumeration.EATime; import it.algos.vaadflow.service.ADateService; import it.algos.vaadflow.service.ATextService; import lombok.extern.slf4j.Slf4j; import name.falgout.jeffrey.testing.junit5.MockitoExtension; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.util.Date; import static it.algos.vaadflow.application.FlowCost.SPAZIO; import static it.algos.vaadflow.application.FlowCost.VUOTA; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Project springvaadin * Created by Algos * User: gac * Date: sab, 10-feb-2018 * Time: 15:04 */ @ExtendWith(MockitoExtension.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @Tag("date") @DisplayName("Test sul service di elaborazione date") @Slf4j public class ADateServiceTest extends ATest { private static int GIORNO = 12; private static int MESE = 7; private static int ANNO = 2004; @InjectMocks public ADateService service; @InjectMocks public ATextService text; // alcuni parametri utilizzati private Date dataPrevista = null; private Date dataOttenuta = null; private LocalDate localData = null; private LocalDate localDataPrevista = null; private LocalDate localDataOttenuta = null; private LocalDateTime localDateTimePrevista = null; private LocalDateTime localDateTimeOttenuta = null; private LocalTime localTimePrevisto = null; private LocalTime localTimeOttenuto = null; @BeforeAll public void setUp() { MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(service); MockitoAnnotations.initMocks(text); service.text = text; }// end of method @BeforeAll public void tearDown() { System.out.println(""); System.out.println(""); System.out.println("Data settimanale lunga: " + service.getWeekLong(LOCAL_DATE_TIME_DUE)); System.out.println("Data settimanale breve: " + service.getDayWeekShort(LOCAL_DATE_TIME_DUE)); System.out.println(""); }// end of method @SuppressWarnings("javadoc") /** * Convert java.util.Date to java.time.LocalDate * Date HA ore, minuti e secondi * LocalDate NON ha ore, minuti e secondi * Si perdono quindi le ore i minuti ed i secondi di Date * * @param data da convertire * * @return data locale (deprecated) */ @Test public void dateToLocalDate() { localDataPrevista = LOCAL_DATE_UNO; localDataOttenuta = service.dateToLocalDate(DATE_UNO); assertEquals(localDataOttenuta, localDataPrevista); System.out.println(""); System.out.println("Convert java.util.Date to java.time.LocalDate: " + DATE_UNO + " -> " + localDataOttenuta); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Convert java.time.LocalDate to java.util.Date * LocalDate NON ha ore, minuti e secondi * Date HA ore, minuti e secondi * La Date ottenuta ha il tempo regolato a mezzanotte * * @param localDate da convertire * * @return data (deprecated) */ @Test public void localDateToDate() { dataPrevista = DATE_UNO; dataOttenuta = service.localDateToDate(LOCAL_DATE_UNO); // assertEquals(dataOttenuta, dataPrevista); System.out.println(""); System.out.println("Convert java.time.LocalDate to java.util.Date: " + LOCAL_DATE_UNO + " -> " + dataOttenuta); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Convert java.util.Date to java.time.LocalDateTime * Date HA ore, minuti e secondi * LocalDateTime HA ore, minuti e secondi * Non si perde nulla * * @param data da convertire * * @return data e ora locale */ @Test public void dateToLocalDateTime() { localDateTimePrevista = LOCAL_DATE_TIME_DUE; localDateTimeOttenuta = service.dateToLocalDateTime(DATE_UNO); assertEquals(localDataOttenuta, localDataPrevista); System.out.println(""); System.out.println("Convert java.util.Date to java.time.LocalDateTime: " + DATE_UNO + " -> " + localDateTimeOttenuta); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Convert java.time.LocalDateTime to java.util.Date * LocalDateTime HA ore, minuti e secondi * Date HA ore, minuti e secondi * Non si perde nulla * * @param localDateTime da convertire * * @return data (deprecated) */ @Test public void localDateTimeToDate() { dataPrevista = DATE_DUE; dataOttenuta = service.localDateTimeToDate(LOCAL_DATE_TIME_DUE); assertEquals(dataOttenuta, dataPrevista); System.out.println(""); System.out.println("Convert java.time.LocalDateTime to java.util.Date: " + LOCAL_DATE_TIME_DUE + " -> " + dataOttenuta); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Convert java.time.LocalDate to java.time.LocalDateTime * LocalDate NON ha ore, minuti e secondi * LocalDateTime HA ore, minuti e secondi * La LocalDateTime ottenuta ha il tempo regolato a mezzanotte * * @param localDate da convertire * * @return data con ore e minuti alla mezzanotte */ @Test public void localDateToLocalDateTime() { localDateTimePrevista = LOCAL_DATE_TIME_DUE; localDateTimeOttenuta = service.localDateToLocalDateTime(LOCAL_DATE_DUE); // assertEquals(localDateTimeOttenuta, localDateTimePrevista); System.out.println(""); System.out.println("Convert java.time.LocalDate to java.time.LocalDateTime: " + LOCAL_DATE_UNO + " -> " + localDateTimeOttenuta); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Convert java.time.LocalDateTime to java.time.LocalDate * LocalDateTime HA ore, minuti e secondi * LocalDate NON ha ore, minuti e secondi * Si perdono quindi le ore i minuti ed i secondi di Date * * @param localDateTime da convertire * * @return data con ore e minuti alla mezzanotte */ @Test public void localDateTimeToLocalDate() { localDataPrevista = LOCAL_DATE_DUE; localDataOttenuta = service.localDateTimeToLocalDate(LOCAL_DATE_TIME_DUE); assertEquals(localDataOttenuta, localDataPrevista); System.out.println(""); System.out.println("Convert java.time.LocalDateTime to java.time.LocalDate: " + LOCAL_DATE_TIME_DUE + " -> " + localDataOttenuta); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Convert java.util.Date to java.time.LocalTime * Estrae la sola parte di Time * Date HA anni, giorni, ore, minuti e secondi * LocalTime NON ha anni e giorni * Si perdono quindi gli anni ed i giorni di Date * * @param data da convertire * * @return time senza ilgiorno */ @Test public void dateToLocalTime() { localTimePrevisto = LOCAL_TIME_UNO; localTimeOttenuto = service.dateToLocalTime(DATE_UNO); assertEquals(localTimeOttenuto, localTimePrevisto); System.out.println(""); System.out.println("Convert java.util.Date to java.time.LocalTime: " + DATE_UNO + " -> " + localTimeOttenuto); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Restituisce una stringa nel formato d-M-yy * <p> * Returns a string representation of the date <br> * Not using leading zeroes in day <br> * Two numbers for year <b> * * @param localDate da rappresentare * * @return la data sotto forma di stringa */ @Test public void getWeekLong() { previsto = "domenica 5"; ottenuto = service.getWeekLong(LOCAL_DATE_TIME_DUE); assertEquals(ottenuto, previsto); System.out.println(""); System.out.println("Restituisce il giorno della settimana in forma estesa: " + LOCAL_DATE_TIME_DUE + " -> " + ottenuto); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Restituisce la data (senza tempo) in forma breve * <p> * Returns a string representation of the date <br> * Not using leading zeroes in day <br> * Two numbers for year <b> * * @param localDateTime da rappresentare * * @return la data sotto forma di stringa */ @Test public void getShort() { previsto = "5-10-14"; ottenuto = service.getShort(LOCAL_DATE_TIME_DUE); assertEquals(ottenuto, previsto); System.out.println(""); System.out.println("Restituisce la data (senza tempo) in forma breve: " + LOCAL_DATE_TIME_DUE + " -> " + ottenuto); System.out.println(""); }// end of single test /** * Restituisce la data completa di tempo * <p> * 5-ott-14 7:04 * <p> * Returns a string representation of the date * Not using leading zeroes in day <br> * Two numbers for year <b> * * @param localDateTime da rappresentare * * @return la data sotto forma di stringa */ @Test public void getDateTime() { LocalDateTime local; previsto = "5-10-14 7:04"; ottenuto = service.getDateTime(LOCAL_DATE_TIME_DUE); assertEquals(ottenuto, previsto); System.out.println(""); System.out.println("Restituisce la data (con tempo) in forma breve: " + LOCAL_DATE_TIME_DUE + " -> " + ottenuto); System.out.println(""); local = LocalDateTime.of(2020, 10, 29, 7, 04); previsto = "29-10-20 7:04"; ottenuto = service.getDateTime(local); assertEquals(ottenuto, previsto); local = LocalDateTime.of(2020, 2, 5, 7, 04); previsto = "5-2-20 7:04"; ottenuto = service.getDateTime(local); assertEquals(ottenuto, previsto); local = LocalDateTime.of(2020, 1, 17, 7, 04); previsto = "17-1-20 7:04"; ottenuto = service.getDateTime(local); assertEquals(ottenuto, previsto); }// end of method @SuppressWarnings("javadoc") /** * Restituisce la data (senza tempo) in forma normale * <p> * Returns a string representation of the date <br> * Not using leading zeroes in day <br> * Two numbers for year <b> * * @param localDateTime da rappresentare * * @return la data sotto forma di stringa */ @Test public void getDate() { previsto = "5-ott-14"; ottenuto = service.getDate(LOCAL_DATE_TIME_DUE); assertEquals(ottenuto, previsto); System.out.println(""); System.out.println("Restituisce la data/time (senza tempo) in forma normale: " + LOCAL_DATE_TIME_DUE + " -> " + ottenuto); System.out.println(""); previsto = "21-ott-14"; ottenuto = service.getDate(LOCAL_DATE_UNO); assertEquals(ottenuto, previsto); System.out.println(""); System.out.println("Restituisce la data (senza tempo) in forma normale: " + LOCAL_DATE_UNO + " -> " + ottenuto); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Restituisce la data completa di tempo * <p> * Returns a string representation of the date <br> * Not using leading zeroes in day <br> * Two numbers for year <b> * * @param localDateTime da rappresentare * * @return la data sotto forma di stringa */ @Test public void getTime() { previsto = "5-ott-14 alle 7:04"; // Date pippo = new Date(1412485480000L); // 5 ottobre 2014, 7 e 12 //long durata=pippo.getTime(); //// Date prova= new Date // Date b=DATE_UNO ; // Date c=DATE_DUE ; // Date a=DATE_TRE ; ottenuto = service.getTime(LOCAL_DATE_TIME_DUE); assertEquals(ottenuto, previsto); System.out.println(""); System.out.println("Restituisce la data completa di tempo: " + LOCAL_DATE_TIME_DUE + " -> " + ottenuto); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Restituisce ora e minuti * * @param localDateTime da rappresentare * * @return l'orario sotto forma di stringa */ @Test public void getOrario() { previsto = "7:04"; ottenuto = service.getOrario(LOCAL_DATE_TIME_DUE); assertEquals(ottenuto, previsto); System.out.println(""); System.out.println("Restituisce l'orario di una dateTime: " + LOCAL_DATE_TIME_DUE + " -> " + ottenuto); System.out.println(""); ottenuto = service.getOrario(LOCAL_TIME_DUE); assertEquals(ottenuto, previsto); System.out.println(""); System.out.println("Restituisce l'orario di un time: " + LOCAL_TIME_DUE + " -> " + ottenuto); System.out.println(""); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il numero della settimana dell'anno di una data fornita. * Usa Calendar * * @param data fornita * * @return il numero della settimana dell'anno */ @Test public void getWeekYear() { previstoIntero = 43; ottenutoIntero = service.getWeekYear(DATE_UNO); assertEquals(ottenutoIntero, previstoIntero); }// end of method @SuppressWarnings("javadoc") /** * Ritorna il numero della settimana del mese di una data fornita. * Usa Calendar * * @param data fornita * * @return il numero della settimana del mese */ @Test public void getWeekMonth() { previstoIntero = 4; ottenutoIntero = service.getWeekMonth(DATE_UNO); assertEquals(ottenutoIntero, previstoIntero); }// end of method @SuppressWarnings("javadoc") /** * Ritorna il numero del giorno dell'anno di una data fornita. * Usa LocalDate internamente, perché Date è deprecato * * @param data fornita * * @return il numero del giorno dell'anno */ @Test public void getDayYear() { previstoIntero = 294; ottenutoIntero = service.getDayYear(DATE_UNO); assertEquals(ottenutoIntero, previstoIntero); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il numero del giorno del mese di una data fornita. * Usa LocalDate internamente, perché Date è deprecato * * @param data fornita * * @return il numero del giorno del mese */ @Test public void getDayOfMonth() { previstoIntero = 21; ottenutoIntero = service.getDayOfMonth(DATE_UNO); assertEquals(ottenutoIntero, previstoIntero); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il numero del giorno della settimana di una data fornita. * Usa Calendar * * @param data fornita * * @return il numero del giorno della settimana (1=dom, 7=sab) */ @Test public void getDayWeek() { previstoIntero = 3; ottenutoIntero = service.getDayWeek(DATE_UNO); assertEquals(ottenutoIntero, previstoIntero); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il giorno (testo) della settimana di una data fornita. * * @param localDate fornita * * @return il giorno della settimana in forma breve */ @Test public void getDayWeekShort() { previsto = "mar"; ottenuto = service.getDayWeekShort(LOCAL_DATE_UNO); assertEquals(ottenuto, previsto); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il giorno (testo) della settimana di una data fornita. * Usa LocalDate internamente, perché Date è deprecato * * @param data fornita * * @return il giorno della settimana in forma breve */ @Test public void getDayWeekShortDate() { previsto = "mar"; ottenuto = service.getDayWeekShort(DATE_UNO); assertEquals(ottenuto, previsto); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il giorno (testo) della settimana di una data fornita. * Usa LocalDate internamente, perché Date è deprecato * * @param data fornita * * @return il giorno della settimana in forma estesa */ @Test public void getDayWeekFull() { previsto = "martedì"; ottenuto = service.getDayWeekFull(LOCAL_DATE_UNO); assertEquals(ottenuto, previsto); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il giorno (testo) della settimana di una data fornita. * Usa LocalDate internamente, perché Date è deprecato * * @param data fornita * * @return il giorno della settimana in forma estesa */ @Test public void getDayWeekFullDate() { previsto = "martedì"; ottenuto = service.getDayWeekFull(DATE_UNO); assertEquals(ottenuto, previsto); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il numero delle ore di una data fornita. * Usa LocalDateTime internamente, perché Date è deprecato * * @param data fornita * * @return il numero delle ore */ @Test public void getOre() { previstoIntero = 7; ottenutoIntero = service.getOre(DATE_UNO); assertEquals(ottenutoIntero, previstoIntero); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il numero dei minuti di una data fornita. * Usa LocalDateTime internamente, perché Date è deprecato * * @param data fornita * * @return il numero dei minuti */ @Test public void getMinuti() { previstoIntero = 42; ottenutoIntero = service.getMinuti(DATE_UNO); assertEquals(ottenutoIntero, previstoIntero); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il numero dei secondi di una data fornita. * Usa LocalDateTime internamente, perché Date è deprecato * * @param data fornita * * @return il numero dei secondi */ @Test public void getSecondi() { previstoIntero = 0; ottenutoIntero = service.getSecondi(DATE_UNO); assertEquals(ottenutoIntero, previstoIntero); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il numero dell'anno di una data fornita. * Usa LocalDate internamente, perché Date è deprecato * * @return il numero dell'anno */ @Test public void getYear() { previstoIntero = 2014; ottenutoIntero = service.getYear(DATE_UNO); assertEquals(ottenutoIntero, previstoIntero); }// end of single test @SuppressWarnings("javadoc") /** * Costruisce la localData per il giorno dell'anno indicato. * * @param giorno di riferimento (numero progressivo dell'anno) * * @return localData */ @Test public void getLocalDateByDay() { localDataPrevista = LocalDate.now(); int numGiorno = LocalDate.now().getDayOfYear(); localDataOttenuta = service.getLocalDateByDay(numGiorno); assertEquals(localDataOttenuta, localDataPrevista); }// end of single test @Test public void formattazione() { System.out.println("LocalDate di riferimento " + LOCAL_DATE_DUE); }// end of single test @Test public void formattazione2() { System.out.println("LocalDateTime di riferimento " + LOCAL_DATE_TIME_DUE); }// end of single test @SuppressWarnings("javadoc") /** * Restituisce la data nella forma del pattern ricevuto * <p> * Returns a string representation of the date <br> * Not using leading zeroes in day <br> * Two numbers for year <b> * * @param localDate da rappresentare * @param patternEnum enumeration di pattern per la formattazione * * @return la data sotto forma di stringa */ @Test public void patternEnumeration() { System.out.println("*************"); System.out.println("Enumeration di possibili formattazioni della data: " + LOCAL_DATE_DUE); System.out.println("*************"); for (EATime eaTime : EATime.values()) { if (eaTime != EATime.iso8601 && eaTime != EATime.completaOrario) { try { // prova ad eseguire il codice ottenuto = service.get(LOCAL_DATE_DUE, eaTime); } catch (Exception unErrore) { // intercetta l'errore log.error(unErrore.toString()); }// fine del blocco try-catch System.out.println("Tipo: " + eaTime.getTag() + " -> " + ottenuto); }// end of if cycle }// end of for cycle System.out.println("*************"); System.out.println(""); }// end of single test @Test public void deltaDiUnaOraTraServerWikiEBrowserGac() { long longUno = LocalDateTime.of(2019, 1, 15, 17, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); long longDue = LocalDateTime.of(2019, 1, 15, 18, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); long delta; delta = longDue - longUno; System.out.println("*************"); System.out.println("Differenza di un'ora in long: " + text.format(delta)); System.out.println("*************"); }// end of single test /** * bv * Restituisce come stringa (intelligente) una durata espressa in long * - Meno di 1 secondo * - Meno di 1 minuto * - Meno di 1 ora * - Meno di 1 giorno * - Meno di 1 anno * * @return durata (arrotondata e semplificata) in forma leggibile */ @Test public void toText() { long durata = 0; int minuto = 60000; System.out.println("*************"); System.out.println("Durata - ingresso in millisecondi"); System.out.println("Meno di 1 secondo: " + service.toText(87)); System.out.println("20 sec.: " + service.toText(20000)); System.out.println("59 secondi: " + service.toText(59000)); System.out.println("58 minuti: " + service.toText(58 * minuto)); System.out.println("118 minuti: " + service.toText(118 * minuto)); System.out.println("122 minuti: " + service.toText(122 * minuto)); System.out.println("Meno di 1 giorno: " + service.toText(7500000)); System.out.println("Meno di 1 anno: " + service.toText(86500000)); System.out.println("*************"); System.out.println("*************"); System.out.println("Durata - ingresso in secondi"); System.out.println("Meno di 1 secondo: " + service.toTextSecondi(0)); System.out.println("20 sec.: " + service.toTextSecondi(20)); System.out.println("59 secondi: " + service.toTextSecondi(59)); System.out.println("58 minuti: " + service.toTextSecondi(58 * 60)); System.out.println("118 minuti: " + service.toTextSecondi(118 * 60)); System.out.println("122 minuti: " + service.toTextSecondi(122 * 60)); System.out.println("Meno di 1 giorno: " + service.toTextSecondi(7500)); System.out.println("Meno di 1 anno: " + service.toTextSecondi(86500)); System.out.println("*************"); System.out.println("*************"); System.out.println("Durata - ingresso in minuti"); System.out.println("Meno di 1 secondo: " + service.toTextMinuti(0)); System.out.println("20 sec.: " + service.toTextMinuti(0)); System.out.println("59 secondi: " + service.toTextMinuti(0)); System.out.println("58 minuti: " + service.toTextMinuti(58)); System.out.println("118 minuti: " + service.toTextMinuti(118)); System.out.println("122 minuti: " + service.toTextMinuti(122)); System.out.println("Meno di 1 giorno: " + service.toTextMinuti(7500 / 60)); System.out.println("Meno di 1 anno: " + service.toTextMinuti(86500 / 60)); System.out.println("*************"); }// end of single test /** * Recupera il primo lunedì precedente al giorno indicato <br> */ @Test public void getFirstLunedì() { localDataPrevista = LocalDate.of(2019, 6, 24); localData = LocalDate.of(2019, 6, 30); localDataOttenuta = service.getFirstLunedì(localData); assertEquals(localDataOttenuta, localDataPrevista); localData = LocalDate.of(2019, 6, 29); localDataOttenuta = service.getFirstLunedì(localData); assertEquals(localDataOttenuta, localDataPrevista); localData = LocalDate.of(2019, 6, 28); localDataOttenuta = service.getFirstLunedì(localData); assertEquals(localDataOttenuta, localDataPrevista); localData = LocalDate.of(2019, 6, 27); localDataOttenuta = service.getFirstLunedì(localData); assertEquals(localDataOttenuta, localDataPrevista); localData = LocalDate.of(2019, 6, 26); localDataOttenuta = service.getFirstLunedì(localData); assertEquals(localDataOttenuta, localDataPrevista); localData = LocalDate.of(2019, 6, 25); localDataOttenuta = service.getFirstLunedì(localData); assertEquals(localDataOttenuta, localDataPrevista); localData = LocalDate.of(2019, 6, 24); localDataOttenuta = service.getFirstLunedì(localData); assertEquals(localDataOttenuta, localDataPrevista); localDataPrevista = LocalDate.of(2019, 6, 17); localData = LocalDate.of(2019, 6, 23); localDataOttenuta = service.getFirstLunedì(localData); assertEquals(localDataOttenuta, localDataPrevista); localDataPrevista = LocalDate.of(2019, 7, 1); localData = LocalDate.of(2019, 7, 1); localDataOttenuta = service.getFirstLunedì(localData); assertEquals(localDataOttenuta, localDataPrevista); localDataPrevista = LocalDate.of(2019, 7, 1); localData = LocalDate.of(2019, 7, 2); localDataOttenuta = service.getFirstLunedì(localData); assertEquals(localDataOttenuta, localDataPrevista); }// end of single test /** * Recupera un giorno tot giorni prima o dopo la data corrente <br> */ @Test public void getGiornoDelta() { sorgenteIntero = -3; localDataPrevista = LocalDate.now().minusDays(3); localDataOttenuta = service.getGiornoDelta(sorgenteIntero); assertEquals(localDataOttenuta, localDataPrevista); sorgenteIntero = 0; localDataPrevista = LocalDate.now(); localDataOttenuta = service.getGiornoDelta(sorgenteIntero); assertEquals(localDataOttenuta, localDataPrevista); sorgenteIntero = 2; localDataPrevista = LocalDate.now().plusDays(2); localDataOttenuta = service.getGiornoDelta(sorgenteIntero); assertEquals(localDataOttenuta, localDataPrevista); sorgente = "-3"; localDataPrevista = LocalDate.now().minusDays(3); localDataOttenuta = service.getGiornoDelta(sorgente); assertEquals(localDataOttenuta, localDataPrevista); sorgente = "0"; localDataPrevista = LocalDate.now(); localDataOttenuta = service.getGiornoDelta(sorgente); assertEquals(localDataOttenuta, localDataPrevista); sorgente = "+2"; localDataPrevista = LocalDate.now().plusDays(2); localDataOttenuta = service.getGiornoDelta(sorgente); assertEquals(localDataOttenuta, localDataPrevista); }// end of single test /** * Durata tra due momenti individuati da ora e minuti <br> */ @Test public void getDurata() { int oraFine; int oraIni; int minFine; int minIni; previstoIntero = 120; oraIni = 15; oraFine = 17; minIni = 0; minFine = 0; ottenutoIntero = service.getDurata(oraFine, oraIni, minFine, minIni); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 150; oraIni = 15; oraFine = 17; minIni = 0; minFine = 30; ottenutoIntero = service.getDurata(oraFine, oraIni, minFine, minIni); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 140; oraIni = 15; oraFine = 17; minIni = 10; minFine = 30; ottenutoIntero = service.getDurata(oraFine, oraIni, minFine, minIni); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 100; oraIni = 15; oraFine = 17; minIni = 30; minFine = 10; ottenutoIntero = service.getDurata(oraFine, oraIni, minFine, minIni); assertEquals(ottenutoIntero, previstoIntero); }// end of single test @SuppressWarnings("javadoc") /** * Costruisce la data per il 1° gennaio dell'anno indicato. * * @param anno di riferimento * * @return primo gennaio dell'anno indicato */ @Test public void primoGennaio() { sorgenteIntero = 2017; localDataPrevista = LocalDate.of(2017, 1, 1); localDataOttenuta = service.primoGennaio(sorgenteIntero); assertEquals(localDataOttenuta, localDataPrevista); sorgenteIntero = 2018; localDataPrevista = LocalDate.of(2018, 1, 1); localDataOttenuta = service.primoGennaio(sorgenteIntero); assertEquals(localDataOttenuta, localDataPrevista); sorgenteIntero = 2019; localDataPrevista = LocalDate.of(2019, 1, 1); localDataOttenuta = service.primoGennaio(sorgenteIntero); assertEquals(localDataOttenuta, localDataPrevista); }// end of single test /** * Costruisce la data per il 1° gennaio dell'anno corrente. * * @return primo gennaio dell'anno corrente */ @Test public void primoGennaioCorrente() { sorgenteIntero = LocalDate.now().getYear(); localDataPrevista = LocalDate.of(sorgenteIntero, 1, 1); localDataOttenuta = service.primoGennaio(); assertEquals(localDataOttenuta, localDataPrevista); }// end of single test @SuppressWarnings("javadoc") /** * Costruisce la data per il 31° dicembre dell'anno indicato. * * @param anno di riferimento * * @return ultimo giorno dell'anno indicato */ @Test public void trentunDicembre() { sorgenteIntero = 2017; localDataPrevista = LocalDate.of(2017, 12, 31); localDataOttenuta = service.trentunDicembre(sorgenteIntero); assertEquals(localDataOttenuta, localDataPrevista); }// end of single test /** * Costruisce la data per il 31° dicembre dell'anno corrente. * * @return ultimo giorno dell'anno corrente */ @Test public void trentunDicembreCorrente() { sorgenteIntero = LocalDate.now().getYear(); localDataPrevista = LocalDate.of(sorgenteIntero, 12, 31); localDataOttenuta = service.trentunDicembre(); assertEquals(localDataOttenuta, localDataPrevista); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il giorno (testo) della settimana ed il giorno (numero) del mese di una data fornita. * <p> * sab 23 * * @param localDate fornita * * @return il giorno della settimana in forma breve */ @Test public void getWeekShort() { previsto = "dom 5"; ottenuto = service.getWeekShort(LOCAL_DATE_DUE); assertEquals(ottenuto, previsto); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna il giorno (testo) della settimana ed il giorno (numero) del mese ed il nome del mese di una data fornita. * <p> * sab 23 apr * * @param localDate fornita * * @return il giorno della settimana in forma breve */ @Test public void getWeekShortMese() { previsto = "dom, 5 ott"; ottenuto = service.getWeekShortMese(LOCAL_DATE_DUE); assertEquals(ottenuto, previsto); }// end of single test @SuppressWarnings("javadoc") /** * Ritorna la data nel formato standar ISO 8601. * <p> * 2017-02-16T21:00:00.000+01:00 * * @param localDate fornita * * @return testo standard ISO */ @Test public void getISO() { previsto = "2014-03-08T07:12:04"; ottenuto = service.getISO(DATE_QUATTRO); assertEquals(ottenuto, previsto); previsto = "2014-10-05T00:00:00"; ottenuto = service.getISO(LOCAL_DATE_DUE); assertEquals(ottenuto, previsto); previsto = "2014-10-21T07:42:00"; ottenuto = service.getISO(LOCAL_DATE_TIME_UNO); assertEquals(ottenuto, previsto); }// end of single test @SuppressWarnings("javadoc") /** * Costruisce una data da una stringa in formato ISO 8601 * * @param isoStringa da leggere * * @return data costruita */ @Test public void parseFromISO() { dataPrevista = DATE_UNO; sorgente = service.getISO(DATE_UNO); dataOttenuta = service.dateFromISO(sorgente); assertEquals(dataOttenuta, dataPrevista); localDataPrevista = LOCAL_DATE_DUE; sorgente = service.getISO(LOCAL_DATE_DUE); localDataOttenuta = service.localDateFromISO(sorgente); assertEquals(localDataOttenuta, localDataPrevista); localDateTimePrevista = LOCAL_DATE_TIME_UNO; sorgente = service.getISO(LOCAL_DATE_TIME_UNO); localDateTimeOttenuta = service.localDateTimeFromISO(sorgente); assertEquals(localDateTimeOttenuta, localDateTimePrevista); }// end of single test @SuppressWarnings("javadoc") /** * Differenza (in giorni) tra due date (LocalDate) <br> * * @param giornoFine data iniziale * @param giornoInizio data finale * * @return giorni di differenza */ @Test public void differenza() { previstoIntero = 16; ottenutoIntero = service.differenza(LOCAL_DATE_UNO, LOCAL_DATE_DUE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = -16; ottenutoIntero = service.differenza(LOCAL_DATE_DUE, LOCAL_DATE_UNO); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 154; ottenutoIntero = service.differenza(LOCAL_DATE_QUATTRO, LOCAL_DATE_DUE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 0; ottenutoIntero = service.differenza(LOCAL_DATE_UNO, null); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 0; ottenutoIntero = service.differenza(null, LOCAL_DATE_DUE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 0; ottenutoIntero = service.differenza((LocalDate) null, (LocalDate) null); assertEquals(ottenutoIntero, previstoIntero); }// end of single test @SuppressWarnings("javadoc") /** * Differenza (in minuti) tra due orari (LocalTime) <br> * * @param orarioInizio orario iniziale * @param orarioFine orario finale * * @return minuti di differenza */ @Test public void durata() { previstoIntero = 38; ottenutoIntero = service.durata(LOCAL_TIME_UNO, LOCAL_TIME_DUE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = -38; ottenutoIntero = service.durata(LOCAL_TIME_DUE, LOCAL_TIME_UNO); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 858; ottenutoIntero = service.durata(LOCAL_TIME_TRE, LOCAL_TIME_UNO); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 896; ottenutoIntero = service.durata(LOCAL_TIME_TRE, LOCAL_TIME_DUE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 0; ottenutoIntero = service.durata(LOCAL_TIME_TRE, null); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 0; ottenutoIntero = service.durata(null, LOCAL_TIME_DUE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 0; ottenutoIntero = service.durata(null, null); assertEquals(ottenutoIntero, previstoIntero); }// end of single test @SuppressWarnings("javadoc") /** * Differenza (in ore) tra due orari (LocalTime) <br> * * @param orarioInizio orario iniziale * @param orarioFine orario finale * * @return minuti di differenza */ @Test public void differenza2() { previstoIntero = 1; ottenutoIntero = service.differenza(LOCAL_TIME_UNO, LOCAL_TIME_DUE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 23; ottenutoIntero = service.differenza(LOCAL_TIME_DUE, LOCAL_TIME_UNO); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 8; ottenutoIntero = service.differenza(LOCAL_TIME_QUATTRO, LOCAL_TIME_TRE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 14; ottenutoIntero = service.differenza(LOCAL_TIME_TRE, LOCAL_TIME_UNO); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 10; ottenutoIntero = service.differenza(LOCAL_TIME_UNO, LOCAL_TIME_TRE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 15; ottenutoIntero = service.differenza(LOCAL_TIME_TRE, LOCAL_TIME_DUE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 9; ottenutoIntero = service.differenza(LOCAL_TIME_DUE, LOCAL_TIME_TRE); assertEquals(ottenutoIntero, previstoIntero); previstoIntero = 0; ottenutoIntero = service.differenza(LOCAL_TIME_VUOTO, LOCAL_TIME_VUOTO); assertEquals(ottenutoIntero, previstoIntero); }// end of single test /** * Controlla la validità del localDate * Deve esistere (not null) * Deve avere valore più recente del 1 gennaio 1970 * * @param localDate in ingresso da controllare * * @return vero se il localDate soddisfa le condizioni previste */ @Test public void isValidDate() { previstoBooleano = true; ottenutoBooleano = service.isValid(LOCAL_DATE_UNO); assertEquals(ottenutoBooleano, previstoBooleano); previstoBooleano = true; ottenutoBooleano = service.isValid(LOCAL_DATE_PRIMO_VALIDO); assertEquals(ottenutoBooleano, previstoBooleano); previstoBooleano = false; ottenutoBooleano = service.isValid((LocalDate) null); assertEquals(ottenutoBooleano, previstoBooleano); previstoBooleano = false; ottenutoBooleano = service.isValid(LOCAL_DATE_VUOTA); assertEquals(ottenutoBooleano, previstoBooleano); previstoBooleano = false; ottenutoBooleano = service.isValid(LOCAL_DATE_OLD); assertEquals(ottenutoBooleano, previstoBooleano); }// end of single test /** * Controlla la validità del localDateTime * Deve esistere (not null) * Deve avere valore più recente del 1 gennaio 1970, ore zero, minuti zero * * @param localDateTime in ingresso da controllare * * @return vero se il localDateTime soddisfa le condizioni previste */ @Test public void isValidDateTime() { previstoBooleano = true; ottenutoBooleano = service.isValid(LOCAL_DATE_TIME_UNO); assertEquals(ottenutoBooleano, previstoBooleano); previstoBooleano = true; ottenutoBooleano = service.isValid(LOCAL_DATE_TIME_PRIMO_VALIDO); assertEquals(ottenutoBooleano, previstoBooleano); previstoBooleano = false; ottenutoBooleano = service.isValid((LocalDateTime) null); assertEquals(ottenutoBooleano, previstoBooleano); previstoBooleano = false; ottenutoBooleano = service.isValid(LOCAL_DATE_TIME_VUOTA); assertEquals(ottenutoBooleano, previstoBooleano); previstoBooleano = false; ottenutoBooleano = service.isValid(LOCAL_DATE_TIME_OLD); assertEquals(ottenutoBooleano, previstoBooleano); }// end of single test /** * Controlla la validità del localTime * Deve esistere (not null) * Deve avere valori delle ore o dei minuti * * @param localTime in ingresso da controllare * * @return vero se il localTime soddisfa le condizioni previste */ @Test public void isValidTime() { previstoBooleano = true; ottenutoBooleano = service.isValid(LOCAL_TIME_DUE); assertEquals(ottenutoBooleano, previstoBooleano); previstoBooleano = false; ottenutoBooleano = service.isValid(LOCAL_TIME_VUOTO); assertEquals(ottenutoBooleano, previstoBooleano); }// end of single test /** * Restituisce la data e l'ora attuali nella forma del pattern completo * <p> * Returns a string representation of the date <br> * Not using leading zeroes in day <br> * Two numbers for year <b> * Esempio: domenica, 5-ottobre-2014 <br> * * @return la data sotto forma di stringa */ @Test public void getDataOraComplete() { ottenuto = service.getDataOraComplete(); System.out.println("*************"); System.out.println("Data e ora attuali nella forma " + EATime.completaOrario.getEsempio()); System.out.println("*************"); System.out.println(ottenuto); System.out.println(""); }// end of single test /** * Sorgente è una data/timestamp del vecchi webambulanze (sql) * da cui estrarre l'ora (in formato LocalTime) che dovrebbe esser '7' * va gestita la differenza di ora legale (2 ore nell'esempio) */ @Test public void oraLegale() { String sorgenteTime = "2019-10-04 09:00:00.0000"; String sorgenteDate = "2019-10-04"; previstoIntero = 0; // DateTime dt = new DateTime( "2010-01-01T12:00:00+01:00") ; Timestamp stamp = Timestamp.valueOf(sorgenteTime); java.sql.Date data = java.sql.Date.valueOf(sorgenteDate); ottenutoIntero = service.getOre(data); assertEquals(ottenutoIntero, previstoIntero); }// end of single test }// end of class
922d0c19c28162b984ecec050d622a64dcc854ce
96f8d42c474f8dd42ecc6811b6e555363f168d3e
/zuiyou/sources/com/facebook/imagepipeline/d/e.java
563d0c717e52332533877325badcdd30894348a9
[]
no_license
aheadlcx/analyzeApk
050b261595cecc85790558a02d79739a789ae3a3
25cecc394dde4ed7d4971baf0e9504dcb7fabaca
refs/heads/master
2020-03-10T10:24:49.773318
2018-04-13T09:44:45
2018-04-13T09:44:45
129,332,351
6
2
null
null
null
null
UTF-8
Java
false
false
195
java
package com.facebook.imagepipeline.d; import java.util.concurrent.Executor; public interface e { Executor a(); Executor b(); Executor c(); Executor d(); Executor e(); }
99f8c4b5255ee8bae6d2e277fc5fccb526bd6ef8
f680ae3cfa887ae4b888d200b55ae1884610b62c
/SiemCore/src/main/java/com/code10/security/service/LogService.java
a1ad90050f0ab9ade0d07f0cc46fc69f9d1dc50d
[ "MIT" ]
permissive
pkrtel/siem-monitor
ffa6c0c77c9e9f77b09bbb266e5341d75633d891
0c06a56f67b39de58db9dc1fc46036f7324aa2ea
refs/heads/master
2023-03-16T17:19:15.179915
2019-01-12T19:55:21
2019-01-12T19:55:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,108
java
package com.code10.security.service; import com.code10.security.model.LogItem; import com.code10.security.model.LogQuery; import com.code10.security.repository.LogRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.Date; @Service public class LogService { private final LogRepository logRepository; @Autowired public LogService(LogRepository logRepository) { this.logRepository = logRepository; } public Page<LogItem> findAll(Pageable pageable) { return logRepository.findAllByOrderByTimestampDesc(pageable); } public Page<LogItem> query(LogQuery logQuery, Pageable pageable) { if (logQuery.getTimestampStart() != null && logQuery.getTimestampEnd() == null) { logQuery.setTimestampEnd(new Date()); } else if (logQuery.getTimestampStart() == null && logQuery.getTimestampEnd() != null) { logQuery.setTimestampStart(new Date(Long.MIN_VALUE)); } return logRepository.query(logQuery, pageable); } public LogItem create(LogItem logItem) { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(logItem.getTimestamp()); stringBuilder.append(" "); stringBuilder.append(logItem.getIpAddress()); stringBuilder.append(" "); stringBuilder.append(logItem.getHostName()); stringBuilder.append(" "); stringBuilder.append(logItem.getSourceName()); stringBuilder.append(" "); stringBuilder.append(logItem.getProcessId()); stringBuilder.append(" "); stringBuilder.append(logItem.getFacility()); stringBuilder.append(" "); stringBuilder.append(logItem.getSeverity()); stringBuilder.append(" "); stringBuilder.append(logItem.getMessage()); stringBuilder.append(" "); logItem.setRaw(stringBuilder.toString()); return logRepository.save(logItem); } }
df2899f8fba11c75e804a1aeb57b915be7e6a8ec
e85fe2d3751865b741bdb4a1a55d46ed35893144
/mapred/timesentimentanalysis/Driver.java
05cc805eb34aff112a9a3e2104fec3eada1a89db
[]
no_license
xiaokaisun90/TwitterSentimentAnalysis
5e1c1f5440ac64d2ea928558f777e2e18803a8d2
e7846e83d31e2d5e283979f855dda4562795f5e6
refs/heads/master
2020-05-19T13:37:41.519958
2015-04-23T17:39:17
2015-04-23T17:39:17
34,470,952
1
0
null
null
null
null
UTF-8
Java
false
false
892
java
package mapred.timesentimentanalysis; import java.io.IOException; import mapred.job.Optimizedjob; import mapred.util.SimpleParser; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; public class Driver { public static void main(String args[]) throws Exception { SimpleParser parser = new SimpleParser(args); String input = parser.get("input"); String output = parser.get("output"); getJobFeatureVector(input, output); } private static void getJobFeatureVector(String input, String output) throws IOException, ClassNotFoundException, InterruptedException { Optimizedjob job = new Optimizedjob(new Configuration(), input, output, "Compute time sentiment"); job.setClasses(SentimentTimeMapper.class, SentimentTimeReducer.class, null); job.setMapOutputClasses(Text.class, Text.class); job.run(); } }
858f6f3afba3ada1a254ff653e8e21ccd7ac0c23
b72c33685c280900f8f99064e05ff48aa63fbdf3
/app/src/main/java/org/hazelcast/evergreencache/DemoApplication.java
9fbca72ea307b7c3dda6da99d42785e047d2b7b4
[]
no_license
itbhp/evergreen-cache
2429cc642f13b9b5a48beea2a309a26391b5f628
6ff92f8a5e7bf46194f68b9f0634e68127eb55c1
refs/heads/master
2023-01-19T04:34:58.101423
2020-05-13T06:40:58
2020-11-23T08:39:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
987
java
package org.hazelcast.evergreencache; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.spring.cache.HazelcastCacheManager; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.core.JdbcTemplate; @SpringBootApplication public class DemoApplication { @Bean public CacheManager cacheManager(HazelcastInstance hazelcastInstance) { return new HazelcastCacheManager(hazelcastInstance); } @Bean public PersonRepository repository(JdbcTemplate template, CacheManager cacheManager) { return new PersonRepository(template, cacheManager.getCache("entities"), cacheManager.getCache("query")); } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
8528242c2aa30a57be92722b25872b8a81f52720
e62c5512d1eadb8fe5b98ccff95655f7f3065048
/src/main/java/com/asx/sbsat/GuiMain.java
60d75faea3cb4e347c0cc165aa72cf30f5e43fe0
[]
no_license
Ri5ux/SBS-Analyzer-Tool-Application
101f7a3bbc5e0adba5918e1e0a8bc1777578d058
c985286364aa95a046ad72ee1c4a66cac4aa2610
refs/heads/master
2021-06-11T02:27:48.220284
2021-05-19T02:36:24
2021-05-19T02:36:24
191,502,743
0
0
null
null
null
null
UTF-8
Java
false
false
426
java
package com.asx.sbsat; import org.asx.glx.gui.GuiPanel; import org.asx.glx.gui.themes.Theme; public class GuiMain extends GuiPanel { public GuiMain() { super(new Theme()); new FormComPortSelection(this, null); new FormBatteryOverview(this, null); this.activeForm = FormComPortSelection.instance(); } @Override public void render() { super.render(); } }
[ "Ri5ux" ]
Ri5ux
c4dbda47ba91cee3629b4a3194e333e801317e34
43487091e74de9ec72c262527ae135abbce1c738
/learning-rabbitmq-consumer/src/main/java/org/learning/rabbitmq/consumer/listener/topic/InfoListener.java
067565901d940d0fde3981be4d61c5602176113e
[]
no_license
xiaxinyu/learning_parent
901b697a3855c703718a017dbfeeafc2ebb38bea
424be1adb4562e53a58219b477c934f809c1ed3c
refs/heads/master
2022-12-23T01:36:51.222536
2020-07-01T07:51:14
2020-07-01T07:51:14
108,367,462
0
0
null
2022-12-16T04:50:11
2017-10-26T05:51:55
Java
UTF-8
Java
false
false
545
java
package org.learning.rabbitmq.consumer.listener.topic; import org.apache.log4j.Logger; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component @RabbitListener(queues = "info-queue") public class InfoListener { private Logger logger = Logger.getLogger(InfoListener.class); @RabbitHandler public void process(String message) { logger.info("info-queue message: " + message + " from TopicExchange."); } }