hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
94a0925223ca4b37918ddc3dfdae4655e03e5f2b
1,447
package com.github.kag0.oauth2; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.github.kag0.oauth2.coding.JsonCodable; import javaslang.collection.Set; import javaslang.control.Either; import org.immutables.value.Value; import java.util.Optional; /** * https://tools.ietf.org/html/rfc6749#section-5.1 * Created by nfischer on 9/2/2016. */ @Value.Immutable @JsonSerialize(as = ImmutableTokenResponse.class) @JsonDeserialize(as = ImmutableTokenResponse.class) public interface TokenResponse extends JsonCodable, Parameters { @JsonProperty(access_token) String accessToken(); @JsonProperty(token_type) TokenType tokenType(); @JsonProperty(expires_in) Optional<Long> exipresIn(); @JsonProperty(refresh_token) Optional<String> refreshToken(); @JsonProperty(scope) Optional<Set<String>> scope(); static TokenResponse fromJson(JsonNode json) throws JsonProcessingException { return MAPPER.treeToValue(json, ImmutableTokenResponse.class); } static Either<ErrorResponse, TokenResponse> parse(JsonNode json) throws JsonProcessingException { if(json.get(access_token) != null) return Either.right(fromJson(json)); return Either.left(ErrorResponse.fromJson(json)); } }
29.530612
98
0.803041
ab69ecb827fc286af68bef3314b4287c1b884a38
4,524
package com.hebaiyi.www.topviewmusic.util; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.hebaiyi.www.topviewmusic.bean.Billboard; import com.hebaiyi.www.topviewmusic.bean.Channel; import com.hebaiyi.www.topviewmusic.bean.FoucsPic; import com.hebaiyi.www.topviewmusic.bean.GeDan; import com.hebaiyi.www.topviewmusic.bean.HotGeDan; import com.hebaiyi.www.topviewmusic.bean.HotWord; import com.hebaiyi.www.topviewmusic.bean.NetMusic; import com.hebaiyi.www.topviewmusic.bean.RecommendRadio; import com.hebaiyi.www.topviewmusic.bean.SearchMerge; import com.hebaiyi.www.topviewmusic.bean.Song; import org.json.JSONException; import org.json.JSONObject; import java.util.Iterator; import java.util.List; public class Utility { public static List<RecommendRadio> analyzeRecommendRadio(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<RecommendRadio>>() { }.getType()); } public static NetMusic analyzeNetMusic(String json) { Gson gson = new Gson(); return gson.fromJson(json, NetMusic.class); } public static List<HotWord> analyzeHotWord(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<HotWord>>() { }.getType()); } public static List<SearchMerge.AlbumInfo> analyzeSearchMergeAlbumInfo(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<SearchMerge.AlbumInfo>>() { }.getType()); } public static List<SearchMerge.ArtistInfo> analyzeSearchMergeArtistInfo(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<SearchMerge.ArtistInfo>>() { }.getType()); } public static List<SearchMerge.SongInfo> analyzeSearchMergeSongInfo(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<SearchMerge.SongInfo>>() { }.getType()); } public static List<Billboard> analyzeBillboard(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<Billboard>>() { }.getType()); } public static List<Channel> analyzeChannel(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<Channel>>() { }.getType()); } public static List<HotGeDan> analyzeHotGeDan(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<HotGeDan>>() { }.getType()); } public static List<GeDan> analyzeGeDan(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<GeDan>>() { }.getType()); } public static List<FoucsPic> analyzeFoucsPic(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<FoucsPic>>() { }.getType()); } public static List<Song> analyzeSong(String json) { Gson gson = new Gson(); return gson.fromJson(json, new TypeToken<List<Song>>() { }.getType()); } /** * 在json多层嵌套情况下,获取指定路径的json字符串, * 如:a.b.c.d.e.f,获取到f层级的json字符串 * * @param json 未加处理的json字符串 * @param route json的指定路径 * @return 处理过后的json字符串 */ public static String obtainDesignationJson(String json, String route) { if (json.isEmpty()) { return null; } // 获取到每一级json字符串的key String[] keys = route.split("\\."); String newJson = json; for (int i = 0; i < keys.length; i++) { newJson = splitJsonByKey(newJson, keys[i]); if (i == keys.length - 1) { return newJson; } } return null; } /** * 根据json字符串的路径裁截子json字符串 * * @param json 原json字符串 * @param key json字符串中的键 * @return 裁截处理后的子json字符串 */ private static String splitJsonByKey(String json, String key) { try { JSONObject obj = new JSONObject(json); for (Iterator<String> it = obj.keys(); it.hasNext(); ) { String s = it.next(); if (s == null) { return null; } if (s.equals(key)) { return obj.getString(key); } } } catch (Exception e) { e.printStackTrace(); return null; } return null; } }
30.77551
90
0.609859
5bf8023cd5087fa62481c213fdaab3ddd75b6c41
9,003
package hotel; import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Scanner; public class Booking { static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); // TODO: make array singleton private static final ArrayList<Booking> BOOKINGS = new ArrayList<Booking>(); private static Integer bookingsNumberIncrease = 1; private Integer bookingsNumber; private LocalDateTime startdate = LocalDateTime.MIN; private LocalDateTime enddate = LocalDateTime.MIN; private Room room; private Customer customer; private Double price; private LocalDateTime bookingDate = LocalDateTime.MIN; private Boolean isBusiness = false; private LocalDateTime checkedIn = LocalDateTime.MIN; private LocalDateTime checkedOut = LocalDateTime.MIN; public Booking(LocalDateTime startdate, LocalDateTime enddate, Room room, Customer customer, boolean isBusiness) throws Exception { if (room == null) { throw new Exception("Room not found"); } if (customer == null) { throw new Exception("Customer not found"); } // check if room is available if (!room.isAvailable(startdate, enddate)) { throw new Exception("Room is not available"); } this.bookingsNumber = bookingsNumberIncrease; bookingsNumberIncrease++; this.startdate = startdate; this.enddate = enddate; this.room = room; this.customer = customer; this.price = this.calculatePrice(startdate, enddate, room, isBusiness); this.bookingDate = LocalDateTime.now(); this.isBusiness = isBusiness; BOOKINGS.add(this); } public static ArrayList<Booking> getBookings() { return BOOKINGS; } public Double calculatePrice(LocalDateTime startdate, LocalDateTime enddate, Room room, boolean isBusiness) { Double price = 0.0; for (LocalDateTime date = startdate; date.isBefore(enddate); date = date.plusDays(1)) { // default price Double dayPrice = room.getPrice(); // add 20 euro if booking is business related if (isBusiness) { dayPrice += 20; } // Add 20 percent discount on saterday and sunday if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY) { dayPrice = dayPrice * 0.8; } price += dayPrice; } return price; } public Integer getBookingNumber() { return this.bookingsNumber; } public Double getPrice() { return this.price; } public LocalDateTime getStartDate() { return this.startdate; } public LocalDateTime getEndDate() { return this.enddate; } public Room getRoom() { return this.room; } public Boolean getCheckedIn() { return !LocalDateTime.MIN.equals(this.checkedIn); } public Boolean getCheckedOut() { return !LocalDateTime.MIN.equals(this.checkedOut); } public LocalDateTime checkIn() { LocalDateTime currentTime = LocalDateTime.now(); this.checkedIn = currentTime; return currentTime; } public LocalDateTime checkOut() { LocalDateTime currentTime = LocalDateTime.now(); this.checkedOut = currentTime; return currentTime; } public static ArrayList<Booking> getBookingsToday() { ArrayList<Booking> bookingsToday = new ArrayList<Booking>(); for (Booking booking : BOOKINGS) { LocalDateTime now = LocalDateTime.now(); if (now.isAfter(booking.getStartDate()) && now.isBefore(booking.getEndDate())) { bookingsToday.add(booking); } } return bookingsToday; } public static void printBookingsToday() { Scanner scanner = new Scanner(System.in); Main.clearConsole(); ArrayList<Booking> bookingsToday = getBookingsToday(); for (Booking booking : bookingsToday) { System.out.println(booking.getBookingNumber() + ". Room: " + booking.getRoom().getRoomNumber() + " checked in: " + (booking.getCheckedIn() ? "yes" : "no")); } System.out.println("Total bookings today: " + bookingsToday.size()); System.out.println("Press enter to continue:"); scanner.nextLine(); Main.printMainMenu(); } public static ArrayList<Booking> getAll() { return BOOKINGS; } public static void createBooking() { Scanner scanner = new Scanner(System.in); Main.clearConsole(); LocalDateTime startdate = LocalDateTime.MIN; while (startdate.isEqual(LocalDateTime.MIN)) { try { System.out.println("Startdate: (dd-mm-yyyy)"); String startdateString = scanner.nextLine() + " 16:00"; LocalDateTime parsedStartdate = LocalDateTime.parse(startdateString, formatter); if (parsedStartdate.plusHours(6).isBefore(LocalDateTime.now())) { throw new Exception("Startdate is in the past"); } startdate = parsedStartdate; } catch (Exception error) { Main.clearConsole(); System.out.println(error.getMessage()); } } Main.clearConsole(); LocalDateTime enddate = LocalDateTime.MIN; while (enddate.isEqual(LocalDateTime.MIN)) { try { System.out.println("Enddate: (dd-mm-yyyy)"); String enddateString = scanner.nextLine() + " 12:00"; LocalDateTime parsedEnddate = LocalDateTime.parse(enddateString, formatter); if (parsedEnddate.isBefore(startdate)) { throw new Exception("Enddate is before startdate"); } enddate = parsedEnddate; } catch (Exception error) { Main.clearConsole(); System.out.println(error.getMessage()); } } Main.clearConsole(); Room.printAvailableRooms(startdate, enddate); Room room = null; while (room == null) { try { System.out.println("Roomnumber:"); String input = scanner.nextLine(); Integer roomNumber = Integer.parseInt(input); Room foundRoom = Room.getRoom(roomNumber); if (foundRoom == null) { throw new Exception("Room not found"); } if (!foundRoom.isAvailable(startdate, enddate)) { throw new Exception("Room not available on selected date"); } room = foundRoom; } catch (Exception error) { Main.clearConsole(); System.out.println(error.getMessage()); } } Main.clearConsole(); Customer customer = null; while (customer == null) { try { System.out.println("Customernumber: (enter for new customer):"); String input = scanner.nextLine(); if (input.length() > 0) { Integer customerNumber = Integer.parseInt(input); Customer foundCustomer = Customer.getCustomer(customerNumber); if (foundCustomer == null) throw new Exception("Customer not found"); } else { Main.clearConsole(); System.out.println("New customer"); System.out.println("Firstname:"); String firstname = scanner.nextLine(); Main.clearConsole(); System.out.println("New customer"); System.out.println("Lastname:"); String lastname = scanner.nextLine(); customer = new Customer(firstname, lastname); } } catch (Exception error) { Main.clearConsole(); System.out.println(error.getMessage()); } } Main.clearConsole(); System.out.println("Is business? y/n"); Boolean isBusiness = scanner.nextLine() == "y"; try { Booking booking = new Booking(startdate, enddate, room, customer, isBusiness); Main.clearConsole(); System.out.println("Price: " + booking.getPrice() + " Room: " + booking.getRoom().getRoomNumber()); } catch (Exception error) { System.out.println(error.getMessage()); } System.out.println("Press enter to continue:"); scanner.nextLine(); Main.printMainMenu(); } }
29.135922
168
0.573253
ecc413d23de812ae49035276592bb842232117e6
14,820
package org.ar.beauty_android.renderer; import android.content.Context; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.os.Handler; import android.os.HandlerThread; import android.text.TextUtils; import android.util.Log; import android.view.Surface; import org.ar.beauty_android.utils.FPSUtil; import com.faceunity.gles.ProgramLandmarks; import com.faceunity.gles.ProgramTexture2d; import com.faceunity.gles.ProgramTextureOES; import com.faceunity.gles.core.GlUtil; import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.ProgressiveMediaSource; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.util.Util; import java.io.File; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * 使用 GLSurfaceView 渲染视频,采用居中裁剪(CenterCrop)的方式显示 * <p> * Created by tujh on 2018/3/2. */ public class VideoRenderer implements GLSurfaceView.Renderer { public final static String TAG = VideoRenderer.class.getSimpleName(); private GLSurfaceView mGlSurfaceView; private OnRendererStatusListener mOnVideoRendererStatusListener; private String mVideoPath; private SurfaceTexture mSurfaceTexture; private Surface mSurface; private int mVideoTextureId; private int mVideoWidth = 720; private int mVideoHeight = 1280; private int mViewWidth; private int mViewHeight; private int mVideoRotation = 0; private float[] mTexMatrix = {0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; private float[] mMvpMatrix; private float[] mLandmarksData; private ProgramLandmarks mProgramLandmarks; private ProgramTexture2d mProgramTexture2d; private ProgramTextureOES mProgramTextureOes; private OnMediaEventListener mOnMediaEventListener; private FPSUtil mFPSUtil; private SimpleExoPlayer mSimpleExoPlayer; private Context mContext; private Handler mPlayerHandler; private boolean mIsSystemCameraRecord; public VideoRenderer(String videoPath, GLSurfaceView glSurfaceView, OnRendererStatusListener onRendererStatusListener) { mVideoPath = videoPath; mGlSurfaceView = glSurfaceView; mContext = glSurfaceView.getContext(); mOnVideoRendererStatusListener = onRendererStatusListener; mFPSUtil = new FPSUtil(); } public void onResume() { startPlayerThread(); mPlayerHandler.post(new Runnable() { @Override public void run() { createExoMediaPlayer(); } }); mGlSurfaceView.onResume(); } public void onPause() { mPlayerHandler.post(new Runnable() { @Override public void run() { releaseExoMediaPlayer(); } }); stopPlayerThread(); final CountDownLatch count = new CountDownLatch(1); mGlSurfaceView.queueEvent(new Runnable() { @Override public void run() { onSurfaceDestroy(); releaseSurface(); count.countDown(); } }); try { count.await(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // ignored } mGlSurfaceView.onPause(); } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { Log.d(TAG, "onSurfaceCreated: "); mProgramTexture2d = new ProgramTexture2d(); mProgramTextureOes = new ProgramTextureOES(); mProgramLandmarks = new ProgramLandmarks(); mVideoTextureId = GlUtil.createTextureObject(GLES11Ext.GL_TEXTURE_EXTERNAL_OES); mOnVideoRendererStatusListener.onSurfaceCreated(); createSurface(); mPlayerHandler.post(new Runnable() { @Override public void run() { mSimpleExoPlayer.setVideoSurface(mSurface); } }); MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); mIsSystemCameraRecord = true; try { mediaMetadataRetriever.setDataSource(mVideoPath); mVideoWidth = Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); mVideoHeight = Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); mVideoRotation = Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)); String location = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION); String genre = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE); // 粗略判断是否系统相机录制 mIsSystemCameraRecord = !(TextUtils.isEmpty(location) || TextUtils.isEmpty(genre)); Log.d(TAG, "onSurfaceChanged: location:" + location + ", genre:" + genre); } catch (Exception e) { Log.e(TAG, "MediaMetadataRetriever extractMetadata: ", e); } finally { mediaMetadataRetriever.release(); } } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { mViewHeight = height; mViewWidth = width; GLES20.glViewport(0, 0, width, height); mOnVideoRendererStatusListener.onSurfaceChanged(width, height, mVideoWidth, mVideoHeight, mVideoRotation, mIsSystemCameraRecord); boolean isLandscape = mVideoRotation % 180 == 0; mMvpMatrix = GlUtil.changeMVPMatrixInside(width, height, isLandscape ? mVideoWidth : mVideoHeight, isLandscape ? mVideoHeight : mVideoWidth); mFPSUtil.resetLimit(); Log.d(TAG, "onSurfaceChanged() width:" + width + ", height:" + height + ", videoWidth:" + mVideoWidth + ", videoHeight:" + mVideoHeight + ", videoRotation:" + mVideoRotation + ", mIsSystemCameraRecord:" + mIsSystemCameraRecord); } @Override public void onDrawFrame(GL10 gl) { if (mProgramTexture2d == null || mProgramTextureOes == null || mSurfaceTexture == null) { return; } GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); try { mSurfaceTexture.updateTexImage(); mSurfaceTexture.getTransformMatrix(mTexMatrix); } catch (Exception e) { Log.e(TAG, "onDrawFrame: ", e); return; } int fuTextureId = mOnVideoRendererStatusListener.onDrawFrame(mVideoTextureId, mVideoWidth, mVideoHeight, mTexMatrix, mSurfaceTexture.getTimestamp()); if (fuTextureId > 0) { mProgramTexture2d.drawFrame(fuTextureId, mTexMatrix, mMvpMatrix); } else { mProgramTextureOes.drawFrame(mVideoTextureId, mTexMatrix, mMvpMatrix); } if (BaseCameraRenderer.ENABLE_DRAW_LANDMARKS && mLandmarksData != null) { mProgramLandmarks.refresh(mLandmarksData, mVideoWidth, mVideoHeight, mVideoRotation, Camera.CameraInfo.CAMERA_FACING_BACK, mMvpMatrix); mProgramLandmarks.drawFrame(0, 0, mViewWidth, mViewHeight); } mFPSUtil.limit(); mGlSurfaceView.requestRender(); } public void setLandmarksData(float[] landmarksData) { mLandmarksData = landmarksData; } private void onSurfaceDestroy() { Log.d(TAG, "onSurfaceDestroy"); if (mVideoTextureId != 0) { int[] textures = new int[]{mVideoTextureId}; GLES20.glDeleteTextures(1, textures, 0); mVideoTextureId = 0; } if (mProgramTexture2d != null) { mProgramTexture2d.release(); mProgramTexture2d = null; } if (mProgramTextureOes != null) { mProgramTextureOes.release(); mProgramTextureOes = null; } if (mProgramLandmarks != null) { mProgramLandmarks.release(); mProgramLandmarks = null; } mOnVideoRendererStatusListener.onSurfaceDestroy(); } private void createExoMediaPlayer() { Log.d(TAG, "createExoMediaPlayer: "); mSimpleExoPlayer = new SimpleExoPlayer.Builder(mContext).build(); MediaEventListener mediaEventListener = new MediaEventListener(); mSimpleExoPlayer.addListener(mediaEventListener); mSimpleExoPlayer.setPlayWhenReady(false); mSimpleExoPlayer.setVolume(0f); String userAgent = Util.getUserAgent(mContext, mContext.getPackageName()); DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(mContext, userAgent); ProgressiveMediaSource.Factory mediaSourceFactory = new ProgressiveMediaSource.Factory(dataSourceFactory); Uri uri = Uri.fromFile(new File(mVideoPath)); MediaSource mediaSource = mediaSourceFactory.createMediaSource(uri); mSimpleExoPlayer.prepare(mediaSource); } private void releaseExoMediaPlayer() { Log.d(TAG, "releaseExoMediaPlayer: "); if (mSimpleExoPlayer != null) { mSimpleExoPlayer.stop(true); mSimpleExoPlayer.release(); mSimpleExoPlayer = null; } } private void createSurface() { Log.d(TAG, "createSurface: "); mSurfaceTexture = new SurfaceTexture(mVideoTextureId); mSurfaceTexture.setDefaultBufferSize(mVideoWidth, mVideoHeight); mSurfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() { @Override public void onFrameAvailable(SurfaceTexture surfaceTexture) { mGlSurfaceView.requestRender(); } }); mSurface = new Surface(mSurfaceTexture); } private void releaseSurface() { Log.d(TAG, "releaseSurface: "); if (mSurfaceTexture != null) { mSurfaceTexture.release(); mSurfaceTexture = null; } if (mSurface != null) { mSurface.release(); mSurface = null; } } public void startMediaPlayer() { Log.d(TAG, "startMediaPlayer: "); mPlayerHandler.post(new Runnable() { @Override public void run() { mSimpleExoPlayer.seekTo(0); mSimpleExoPlayer.setPlayWhenReady(true); } }); } public void setOnMediaEventListener(OnMediaEventListener onMediaEventListener) { mOnMediaEventListener = onMediaEventListener; } public int getVideoWidth() { return mVideoRotation % 180 == 0 ? mVideoWidth : mVideoHeight; } public int getVideoHeight() { return mVideoRotation % 180 == 0 ? mVideoHeight : mVideoWidth; } private void startPlayerThread() { HandlerThread playerThread = new HandlerThread("exo_player"); playerThread.start(); mPlayerHandler = new Handler(playerThread.getLooper()); } private void stopPlayerThread() { mPlayerHandler.getLooper().quitSafely(); mPlayerHandler = null; } private class MediaEventListener implements Player.EventListener { @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { switch (playbackState) { // case Player.STATE_IDLE: // break; // case Player.STATE_BUFFERING: // break; case Player.STATE_READY: if (playWhenReady) { Log.d(TAG, "onPlayerStateChanged: prepared " + Thread.currentThread().getName()); mGlSurfaceView.requestRender(); } break; case Player.STATE_ENDED: Log.d(TAG, "onPlayerStateChanged: completion " + Thread.currentThread().getName()); if (mOnMediaEventListener != null) { mOnMediaEventListener.onCompletion(); } break; default: } } @Override public void onPlayerError(ExoPlaybackException error) { Log.w(TAG, "onPlayerError: ", error); String message; switch (error.type) { case ExoPlaybackException.TYPE_SOURCE: message = "数据源异常"; break; case ExoPlaybackException.TYPE_RENDERER: message = "解码异常"; break; case ExoPlaybackException.TYPE_UNEXPECTED: default: message = "其他异常"; } if (mOnMediaEventListener != null) { mOnMediaEventListener.onLoadError(message); } } } public interface OnRendererStatusListener { /** * Called when surface is created or recreated. */ void onSurfaceCreated(); /** * Called when surface'size changed. * * @param viewWidth * @param viewHeight * @param videoWidth * @param videoHeight * @param videoRotation * @param isSystemCameraRecord */ void onSurfaceChanged(int viewWidth, int viewHeight, int videoWidth, int videoHeight, int videoRotation, boolean isSystemCameraRecord); /** * Called when drawing current frame * * @param videoTextureId * @param videoWidth * @param videoHeight * @param mvpMatrix * @param timeStamp * @return */ int onDrawFrame(int videoTextureId, int videoWidth, int videoHeight, float[] mvpMatrix, long timeStamp); /** * Called when surface is destroyed */ void onSurfaceDestroy(); } public interface OnMediaEventListener { /** * Called when the end of a media source is reached during playback. */ void onCompletion(); /** * Called when error happened * * @param error */ void onLoadError(String error); } }
36.865672
143
0.636235
9dba409e0914fe961bcee89277a1cedca1fcca30
4,003
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.sql.parser.sql.common.util; import lombok.RequiredArgsConstructor; import org.apache.shardingsphere.sql.parser.sql.common.constant.LogicalOperator; import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.expr.BinaryOperationExpression; import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.expr.ExpressionSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.predicate.AndPredicate; import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.predicate.OrPredicateSegment; import java.util.Optional; /** * Expression builder. */ @RequiredArgsConstructor public final class ExpressionBuilder { private final ExpressionSegment expression; /** * Extract and predicates. * * @return Or predicate segment */ public OrPredicateSegment extractAndPredicates() { OrPredicateSegment result = new OrPredicateSegment(); if (expression instanceof BinaryOperationExpression) { String operator = ((BinaryOperationExpression) expression).getOperator(); Optional<LogicalOperator> logicalOperator = LogicalOperator.valueFrom(operator); if (logicalOperator.isPresent() && LogicalOperator.OR == logicalOperator.get()) { ExpressionBuilder leftBuilder = new ExpressionBuilder(((BinaryOperationExpression) expression).getLeft()); ExpressionBuilder rightBuilder = new ExpressionBuilder(((BinaryOperationExpression) expression).getRight()); result.getAndPredicates().addAll(leftBuilder.extractAndPredicates().getAndPredicates()); result.getAndPredicates().addAll(rightBuilder.extractAndPredicates().getAndPredicates()); } else if (logicalOperator.isPresent() && LogicalOperator.AND == logicalOperator.get()) { ExpressionBuilder leftBuilder = new ExpressionBuilder(((BinaryOperationExpression) expression).getLeft()); ExpressionBuilder rightBuilder = new ExpressionBuilder(((BinaryOperationExpression) expression).getRight()); for (AndPredicate eachLeft : leftBuilder.extractAndPredicates().getAndPredicates()) { for (AndPredicate eachRight : rightBuilder.extractAndPredicates().getAndPredicates()) { result.getAndPredicates().add(createAndPredicate(eachLeft, eachRight)); } } } else { AndPredicate andPredicate = new AndPredicate(); andPredicate.getPredicates().add(expression); result.getAndPredicates().add(andPredicate); } } else { AndPredicate andPredicate = new AndPredicate(); andPredicate.getPredicates().add(expression); result.getAndPredicates().add(andPredicate); } return result; } private AndPredicate createAndPredicate(final AndPredicate left, final AndPredicate right) { AndPredicate result = new AndPredicate(); result.getPredicates().addAll(left.getPredicates()); result.getPredicates().addAll(right.getPredicates()); return result; } }
50.0375
124
0.708469
52731c6c26bd92d46ae2b6d24226fe5fae232de7
6,385
/* * Copyright 2010 Proofpoint, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.airlift.dbpool; import com.google.common.io.Files; import com.google.common.io.Resources; import io.airlift.dbpool.H2EmbeddedDataSourceConfig.Cipher; import org.h2.jdbc.JdbcSQLException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import static java.nio.charset.StandardCharsets.UTF_8; @Test(singleThreaded = true) public class H2EmbeddedDataSourceTest { private File file; @BeforeMethod public void setup() throws IOException { file = File.createTempFile("h2db-", ".db"); } @AfterMethod(alwaysRun = true) public void teardown() { file.delete(); } @Test public void testInitFromResource() throws Exception { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { H2EmbeddedDataSourceConfig config = new H2EmbeddedDataSourceConfig() .setFilename(file.getAbsolutePath()) .setInitScript("io/airlift/dbpool/h2.ddl") .setCipher(Cipher.AES) .setFilePassword("filePassword"); H2EmbeddedDataSource dataSource = new H2EmbeddedDataSource(config); connection = dataSource.getConnection(); statement = connection.createStatement(); resultSet = statement.executeQuery("select * from message"); } finally { closeQuietly(resultSet); closeQuietly(statement); closeQuietly(connection); } } @Test public void testInitFromFile() throws Exception { File initScript = File.createTempFile("initscript", ".ddl"); Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { URL url = Resources.getResource("io/airlift/dbpool/h2.ddl"); Resources.asByteSource(url).copyTo(Files.asByteSink(initScript)); H2EmbeddedDataSourceConfig config = new H2EmbeddedDataSourceConfig() .setFilename(file.getAbsolutePath()) .setInitScript(initScript.getAbsolutePath()) .setCipher(Cipher.AES) .setFilePassword("filePassword"); H2EmbeddedDataSource dataSource = new H2EmbeddedDataSource(config); connection = dataSource.getConnection(); statement = connection.createStatement(); resultSet = statement.executeQuery("select * from message"); } finally { initScript.delete(); closeQuietly(resultSet); closeQuietly(statement); closeQuietly(connection); } } @Test(expectedExceptions = JdbcSQLException.class) public void testInitFromInvalidDdlThrows() throws Exception { File initScript = File.createTempFile("initscript", ".ddl"); try { String invalidDdl = "This isn't valid SQL"; Files.write(invalidDdl, initScript, UTF_8); H2EmbeddedDataSourceConfig config = new H2EmbeddedDataSourceConfig() .setFilename(file.getAbsolutePath()) .setInitScript(initScript.getAbsolutePath()) .setCipher(Cipher.AES) .setFilePassword("filePassword"); new H2EmbeddedDataSource(config); } finally { initScript.delete(); } } @Test(expectedExceptions = NullPointerException.class) public void testNullFilenameThrows() throws Exception { H2EmbeddedDataSourceConfig config = new H2EmbeddedDataSourceConfig() // Filename left as null .setInitScript("io/airlift/dbpool/h2.ddl") .setCipher(Cipher.AES) .setFilePassword("filePassword"); new H2EmbeddedDataSource(config); } @Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyFilenameThrows() throws Exception { H2EmbeddedDataSourceConfig config = new H2EmbeddedDataSourceConfig() .setFilename("") .setInitScript("io/airlift/dbpool/h2.ddl") .setCipher(Cipher.AES) .setFilePassword("filePassword"); new H2EmbeddedDataSource(config); } @Test(expectedExceptions = FileNotFoundException.class) public void testCantFindInitScript() throws Exception { H2EmbeddedDataSourceConfig config = new H2EmbeddedDataSourceConfig() .setFilename(file.getAbsolutePath()) .setInitScript("foo") .setCipher(Cipher.AES) .setFilePassword("filePassword"); new H2EmbeddedDataSource(config); } private static void closeQuietly(ResultSet resultSet) { try { if (resultSet != null) { resultSet.close(); } } catch (Throwable ignored) { } } private static void closeQuietly(Statement statement) { try { if (statement != null) { statement.close(); } } catch (Throwable ignored) { } } private static void closeQuietly(Connection connection) { try { if (connection != null) { connection.close(); } } catch (Throwable ignored) { } } }
31.146341
80
0.613156
dd4b7c35b3160691926ef0490ab64a010ebaf0ea
383
//,temp,sample_5618.java,2,14,temp,sample_5616.java,2,14 //,2 public class xxx { public void testDestinationParam() { final DestinationParam p = new DestinationParam(DestinationParam.DEFAULT); Assert.assertEquals(null, p.getValue()); new DestinationParam("/abc"); try { new DestinationParam("abc"); Assert.fail(); } catch(IllegalArgumentException e) { log.info("expected"); } } };
21.277778
74
0.746736
979db9d3e038ba969c614c9bcbee34b9e4857185
161
package de.darealfive; public interface Attractable extends Locatable { void calculateForce(Attractable body, double timePassed); double getMass(); }
17.888889
61
0.763975
8e0bdde1267535fd3797f7cef6276504b916c463
1,870
package crud; import java.util.Scanner; public class Computadora extends Electronico { private Scanner in = new Scanner(System.in); private String modelo; private String ram; private String procesador; public Computadora() { super(); System.out.print("Introduce el modelo: "); modelo = in.nextLine(); System.out.print("Introduce la cantidad de ram: "); ram = in.nextLine(); System.out.print("Introduce los GHz del procesador: "); procesador = in.nextLine(); } @Override public void actualizar() { super.inicializarActualizar(); System.out.println("[4] Modelo"); System.out.println("[5] RAM"); System.out.println("[6] Procesador"); System.out.print("Introduce el atributo que quieres actualizar: "); int atributo = in.nextInt(); in.nextLine(); if (atributo > 0 && atributo <= 3) { super.actualizarAtributo(atributo); } else { switch (atributo) { case 4: System.out.print("Introduce el nuevo modelo: "); modelo = in.nextLine(); break; case 5: System.out.print("Introduce la nueva cantidad de RAM: "); ram = in.nextLine(); break; case 6: System.out.print("Introduce la nueva velocidad del procesador: "); procesador = in.nextLine(); break; default: System.out.println("Opcion inorrecta."); break; } } } public String toString() { return String.format("%s\nModelo: %s\nRAM: %sGB\nProcesador: %sGHz", super.toString(), modelo, ram, procesador); } }
32.241379
95
0.521925
90fc094b949140805fa255f47136e368108a30bf
2,184
/* * Copyright (C) 2007 The Guava 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.google.common.collect; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.google.TestStringMultisetGenerator; import junit.framework.TestCase; import java.util.Arrays; /** * Unit test for {@link HashMultiset}. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public class HashMultisetTest extends TestCase { private static TestStringMultisetGenerator hashMultisetGenerator() { return new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { return HashMultiset.create(asList(elements)); } }; } public void testCreate() { Multiset<String> multiset = HashMultiset.create(); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); } public void testCreateWithSize() { Multiset<String> multiset = HashMultiset.create(50); multiset.add("foo", 2); multiset.add("bar"); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); } public void testCreateFromIterable() { Multiset<String> multiset = HashMultiset.create(Arrays.asList("foo", "bar", "foo")); assertEquals(3, multiset.size()); assertEquals(2, multiset.count("foo")); } /* * The behavior of toString() and iteration is tested by LinkedHashMultiset, * which shares a lot of code with HashMultiset and has deterministic * iteration order. */ }
29.12
78
0.71337
653549b991f552672128a2ffbc0795e59979df41
17,375
package com.alley.ben.movieapp; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import com.alley.ben.movieapp.database.DataContract; import com.alley.ben.movieapp.fetchers.FetchDetailsTask; import com.alley.ben.movieapp.fetchers.FetchMoviesTask; import com.alley.ben.movieapp.fetchers.FetchRatingTask; import com.alley.ben.movieapp.fetchers.FetchVideosTask; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class MovieInfoFragment extends Fragment { private static final String LOG_TAG = MovieInfoFragment.class.getSimpleName(); private View mRootView; private MovieData mMovie; private boolean mIsFavorite; private boolean mIsInDatabase; private String mFavoritesSelection; private String[] mSelectionArgs = new String[1]; private RecommendationsListAdapter mRecAdapter; private TrailerListAdapter mTrailerListAdapter; // TODO backdrop_path with title over it, on upward move, backdrop fades or flows up, title flows up to header and sticks, info comes up into foreground public MovieInfoFragment() { setHasOptionsMenu(false); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_movie_info, container, false); ImageView posterView = (ImageView) mRootView.findViewById(R.id.fragment_movie_info_poster); TextView titleView = (TextView) mRootView.findViewById(R.id.fragment_movie_info_title); ImageView imdbImageView = (ImageView) mRootView.findViewById(R.id.fragment_movie_info_imdb_button); ImageView googleImageView = (ImageView) mRootView.findViewById(R.id.fragment_movie_info_google_button); ImageView roTomatoesImageView = (ImageView) mRootView.findViewById(R.id.fragment_movie_info_rotten_tomatoes_button); final RecyclerView trailersView = (RecyclerView) mRootView.findViewById(R.id.fragment_movie_info_yt_videos); final RecyclerView recsView = (RecyclerView) mRootView.findViewById(R.id.fragment_movie_info_movie_recs); CheckBox starFavorite = (CheckBox) mRootView.findViewById(R.id.star_button); // close button to return straight to main menu instead of going back through every movie info frag ImageView closeBtnView = (ImageView) mRootView.findViewById(R.id.fragment_movie_info_close_button); closeBtnView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getContext(), MainActivity.class)); } }); Intent intent = getActivity().getIntent(); if (intent != null && intent.hasExtra("movieInfoTag")) { mMovie = intent.getParcelableExtra("movieInfoTag"); // get overview, user score avg, release date, imdb id, runtime, genres, tagline FetchDetailsTask detailsTask = new FetchDetailsTask(); detailsTask.setView(mRootView); detailsTask.setContext(getContext()); detailsTask.execute(mMovie.movieId); // get mpaa rating FetchRatingTask ratingTask = new FetchRatingTask(); ratingTask.setView(mRootView); ratingTask.execute(mMovie.movieId); // Set title titleView.setText(mMovie.title); // Set poster image final String POSTER_BASE_URL = "http://image.tmdb.org/t/p/"; final String SIZE = "w780"; final String POSTER_PATH = mMovie.posterPath; Uri builtUri = Uri.parse(POSTER_BASE_URL).buildUpon() .appendPath(SIZE) .appendEncodedPath(POSTER_PATH) .build(); Log.d(LOG_TAG, builtUri.toString()); Picasso.with(super.getContext()).load(builtUri).into(posterView); // set imdb button listener imdbImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String IMDB_BASE_URL = "http://www.imdb.com/title"; TextView tv = (TextView) mRootView.findViewById(R.id.fragment_movie_info_imdb_id); final String IMDB_ID = (String) tv.getText(); // example: // "http://www.imdb.com/title/<imdb_id>" Uri imdbUri = Uri.parse(IMDB_BASE_URL).buildUpon().appendPath(IMDB_ID).build(); Log.d(LOG_TAG, imdbUri.toString()); startActivity(new Intent(Intent.ACTION_VIEW, imdbUri)); } }); // set google button listener googleImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String GOOGLE_BASE_URL = "http://www.google.com/search"; final String QUERY = "q"; final String SEARCH_TERM = mMovie.title.trim(); // example: // "http://www.google.com/#q=<movie_title>" Uri googleUri = Uri.parse(GOOGLE_BASE_URL).buildUpon() .appendQueryParameter(QUERY, SEARCH_TERM) .build(); Log.d(LOG_TAG, googleUri.toString()); startActivity(new Intent(Intent.ACTION_VIEW, googleUri)); } }); // set rotten tomatoes button listener roTomatoesImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String RT_BASE_URL = "http://www.rottentomatoes.com/search/"; final String SEARCH = "search"; final String SEARCH_TERM = mMovie.title.trim(); // example: // "http://www.rottentomatoes.com/search?search=<movie_title>" Uri rtUri = Uri.parse(RT_BASE_URL).buildUpon() .appendQueryParameter(SEARCH, SEARCH_TERM) .build(); Log.d(LOG_TAG, rtUri.toString()); startActivity(new Intent(Intent.ACTION_VIEW, rtUri)); } }); // get trailers LinearLayoutManager trailersLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); mTrailerListAdapter = new TrailerListAdapter(getContext(), new ArrayList<TrailerData>()); trailersView.setLayoutManager(trailersLayoutManager); FetchVideosTask fetchTrailers = new FetchVideosTask(); fetchTrailers.setAdapter(mTrailerListAdapter); fetchTrailers.execute(mMovie.movieId); trailersView.setAdapter(mTrailerListAdapter); mTrailerListAdapter.setOnItemClickListener(new TrailerListAdapter.OnItemClickListener() { @Override public void onItemClick(View itemView, int position) { TrailerData trailerData = mTrailerListAdapter.getItem(position); final String TRAILER_BASE_URL = "http://www.youtube.com/watch?v="; final String TRAILER_PATH = trailerData.trailerPath; // example: // http://www.youtube.com/watch?v=<trailer path> Uri trailerUri = Uri.parse(TRAILER_BASE_URL).buildUpon() .appendEncodedPath(TRAILER_PATH) .build(); startActivity( new Intent(Intent.ACTION_VIEW, trailerUri)); } }); // get similar movie recommendations LinearLayoutManager recsLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); mRecAdapter = new RecommendationsListAdapter(getContext(), new ArrayList<MovieData>()); recsView.setLayoutManager(recsLayoutManager); FetchMoviesTask fetchMovies = new FetchMoviesTask(); fetchMovies.setRecsAdapter(mRecAdapter); fetchMovies.execute(mMovie.movieId); recsView.setAdapter(mRecAdapter); mRecAdapter.setOnItemClickListener(new RecommendationsListAdapter.OnItemClickListener() { @Override public void onItemClick(View itemView, int position) { MovieData movieData = mRecAdapter.getItem(position); Log.d(LOG_TAG, "Rec movie has been clicked!!!! ::: " + movieData.toString() + "\nat position: " + position + "\n"); startActivity( new Intent(getActivity(), MovieInfoActivity.class) .putExtra("movieInfoTag", movieData)); } }); //CHECK FROM FAVORITES String[] projection = {DataContract.FavoritesContract.COLUMN_MOVIE_ID}; mFavoritesSelection = DataContract.FavoritesContract.TABLE_NAME + "." + DataContract.FavoritesContract.COLUMN_MOVIE_ID + " = ? "; mSelectionArgs[0] = mMovie.movieId; // selectionArgs should work for each table as the movie ID // will be the same because we're only dealing with one movie final Cursor cursor = getContext().getContentResolver().query( DataContract.FavoritesContract.buildMovieIdUri(mMovie.movieId), projection, mFavoritesSelection, mSelectionArgs, null); mIsFavorite = (cursor.getCount() > 0); mIsInDatabase = mIsFavorite; // Get star favorite button starFavorite.setChecked(mIsFavorite); starFavorite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mIsFavorite = !mIsFavorite; } }); } return mRootView; } @Override public void onDestroy() { super.onDestroy(); if (mIsInDatabase && !mIsFavorite) { final String trailersSelection = DataContract.TrailersContract.TABLE_NAME + "." + DataContract.TrailersContract.COLUMN_MOVIE_ID + " = ? "; final String recommendationsSelection = DataContract.RecommendationsContract.TABLE_NAME + "." + DataContract.TrailersContract.COLUMN_MOVIE_ID + " = ? "; // content uri references whole table, // favoritesSelection references row depending on column content, // selectionArgs provides specific row getContext().getContentResolver().delete( DataContract.FavoritesContract.CONTENT_URI, mFavoritesSelection, mSelectionArgs); getContext().getContentResolver().delete( DataContract.TrailersContract.CONTENT_URI, trailersSelection, mSelectionArgs); getContext().getContentResolver().delete( DataContract.RecommendationsContract.CONTENT_URI, recommendationsSelection, mSelectionArgs); Log.d(LOG_TAG, mMovie.title + " movie deleted from database"); } else if (!mIsInDatabase && mIsFavorite) { ContentValues movieInfo = mMovie.getMovieDataCV(); TextView overviewTextView = (TextView) mRootView.findViewById(R.id.fragment_movie_info_overview); String overview = (String) "" + overviewTextView.getText(); // Log.d(LOG_TAG, "Overview: " + overview); // "" is due to text of overview being "SpannableString" // not sure why overview is the only text that is that way // ad hoc solution implemented for now; come back later to fix it better movieInfo.put(DataContract.FavoritesContract.COLUMN_OVERVIEW, overview); TextView scoreTextView = (TextView) mRootView.findViewById(R.id.fragment_movie_info_avg_score); String score = (String) scoreTextView.getText(); movieInfo.put(DataContract.FavoritesContract.COLUMN_SCORE, score); TextView dateTextView = (TextView) mRootView.findViewById(R.id.fragment_movie_info_date); String date = (String) dateTextView.getText(); movieInfo.put(DataContract.FavoritesContract.COLUMN_DATE, date); TextView ratingTextView = (TextView) mRootView.findViewById(R.id.fragment_movie_info_rating); String rating = (String) ratingTextView.getText(); movieInfo.put(DataContract.FavoritesContract.COLUMN_RATING, rating); TextView runtimeTextView = (TextView) mRootView.findViewById(R.id.fragment_movie_info_runtime); String runtime = (String) runtimeTextView.getText(); movieInfo.put(DataContract.FavoritesContract.COLUMN_RUNTIME, runtime); TextView taglineTextView = (TextView) mRootView.findViewById(R.id.fragment_movie_info_tagline); String tagline = (String) taglineTextView.getText(); movieInfo.put(DataContract.FavoritesContract.COLUMN_TAGLINE, tagline); TextView genresTextView = (TextView) mRootView.findViewById(R.id.fragment_movie_info_genres); String genres = (String) genresTextView.getText(); movieInfo.put(DataContract.FavoritesContract.COLUMN_GENRES, genres); TextView imdbTextView = (TextView) mRootView.findViewById(R.id.fragment_movie_info_imdb_id); String imdbID = (String) imdbTextView.getText(); movieInfo.put(DataContract.FavoritesContract.COLUMN_IMDB_ID, imdbID); // insert movieData via ContentValues to database getContext().getContentResolver().insert( DataContract.FavoritesContract.CONTENT_URI, movieInfo); // insert trailers to database int trailerCount = mTrailerListAdapter.getItemCount(); ContentValues[] trailersArr = new ContentValues[trailerCount]; // add getCV method to trailerData object for (int i = 0; i < trailerCount; i++) { ContentValues trailersCV = new ContentValues(); TrailerData td = mTrailerListAdapter.getItem(i); trailersCV.put( DataContract.TrailersContract.COLUMN_MOVIE_ID, mMovie.movieId ); trailersCV.put( DataContract.TrailersContract.COLUMN_TRAILER_URL, td.trailerPath ); trailersCV.put( DataContract.TrailersContract.COLUMN_TRAILER_TITLE, td.title ); trailersArr[i] = trailersCV; } getContext().getContentResolver().bulkInsert( DataContract.TrailersContract.CONTENT_URI, trailersArr); // insert recommendations to database int recCount = mRecAdapter.getItemCount(); ContentValues[] recsArr = new ContentValues[recCount]; for (int i = 0; i < recCount; i++) { ContentValues recommendationsCV = new ContentValues(); MovieData md = mRecAdapter.getItem(i); Log.d(LOG_TAG, "\nrec added to database: " + md.title); recommendationsCV.put( DataContract.RecommendationsContract.COLUMN_MOVIE_ID, mMovie.movieId ); recommendationsCV.put( DataContract.RecommendationsContract.COLUMN_SIMILAR_MOVIE_ID, md.movieId ); recommendationsCV.put( DataContract.RecommendationsContract.COLUMN_SIMILAR_MOVIE_TITLE, md.title ); recommendationsCV.put( DataContract.RecommendationsContract.COLUMN_SIMILAR_MOVIE_POSTER_URL, md.posterPath ); recsArr[i] = recommendationsCV; } getContext().getContentResolver().bulkInsert( DataContract.RecommendationsContract.CONTENT_URI, recsArr); } } }
45.965608
156
0.605986
e88872f53122724cf3a7039510ba8025aed81825
482
package main; import java.util.Date; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Date start = new Date(); Map<Book, Double> books = new HashMap<>(); for (int i = 0; i < 10000000; i++) { books.put(new Book(i,"Jane Eyre","Charlotte Bronte",14.99),14.99); } Date end = new Date(); System.out.println("Elapsed time was " + (end.getTime() - start.getTime()) +" ms."); } }
21.909091
87
0.599585
e294a5b84154b54ce787e2c72016bd866c21f74d
1,841
package com.devopslam.reacmiccustomer.controller; import com.devopslam.reacmiccustomer.model.Customer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CustomerControllerTest { private final Logger logger = LoggerFactory.getLogger(CustomerControllerTest.class); private WebClient webClient; @LocalServerPort private int port; @Before public void setup() { this.webClient = WebClient.create("http://localhost:" + port); } @Test public void getCustomerAccounts() { Customer customer = this.webClient.get().uri("/customer/accounts/5aa3852aaf69be087c9343cc") .accept(MediaType.APPLICATION_JSON) .exchange().flatMap(response -> response.bodyToMono(Customer.class)).block(); logger.info("Customer: " + customer.toString()); } @Test public void addCustomer() { Customer customer = new Customer("Adam", "Kowalski", "5aa3852aaf69be087c9343cc"); customer = webClient.post().uri("/customer").accept(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject(customer)) .exchange() .flatMap(response -> response.bodyToMono(Customer.class)).block(); logger.info("Customer: " + customer.toString()); } }
36.82
99
0.727322
4f3f0a5cfd609dae42425b2a52a031d24a88a63b
209
package features; import org.noear.solon.Solon; import org.noear.solon.SolonApp; public class GraphqlTest { public static void main(String[] args) { Solon.start(GraphqlTest.class, args); } }
19
45
0.708134
fced0373abbb04527763c02485ae55d04f3aee5c
1,901
/* * LessCSS Compiler * http://lesscss-compiler.projects.gabrys.biz/ * * Copyright (c) 2015 Adam Gabrys * * This file is licensed under the BSD 3-Clause (the "License"). * You may not use this file except in compliance with the License. * You may obtain: * - a copy of the License at project page * - a template of the License at https://opensource.org/licenses/BSD-3-Clause */ package biz.gabrys.lesscss.compiler2; /** * Thrown to indicate that a compiler cannot read file content. * @since 2.0.0 */ public class ReadFileException extends CompilerException { private static final long serialVersionUID = 3711806897577477826L; private final String filePath; /** * Constructs a new instance with the specified detail message and file path. * @param message the detail message. * @param filePath the file path. * @since 2.0.0 */ public ReadFileException(final String message, final String filePath) { super(message); this.filePath = filePath; } /** * Constructs a new instance with the specified detail message, cause and file path. * @param message the detail message. * @param cause the cause. * @param filePath the file path. * @since 2.0.0 */ public ReadFileException(final String message, final Throwable cause, final String filePath) { super(message, cause); this.filePath = filePath; } /** * Constructs a new instance with the cause and file path. * @param cause the cause. * @param filePath the file path. * @since 2.0.0 */ public ReadFileException(final Throwable cause, final String filePath) { super(cause); this.filePath = filePath; } /** * Returns a file path. * @return the file path. * @since 2.0.0 */ public String getFilePath() { return filePath; } }
27.955882
98
0.651762
69c1696e48d69631e8a9ea671c29eeee50e9212c
1,429
package com.shata.migration.client; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.PropertyConfigurator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.shata.migration.utils.Config; import com.shata.migration.utils.NamedThreadFactory; public class StartMigration { private final static Logger log = LoggerFactory.getLogger(StartMigration.class); static { PropertyConfigurator.configure("config/log4j.properties"); } public static void main(String[] args) throws Exception { PropertyConfigurator.configureAndWatch("config/log4j.properties", 5000L); log.info("\r\n\t Migration-tool client instance start, [version 1.0-SNAPSHOT] " + "\r\n\t\t host=" + Config.getSetting("host") + " port=" + Config.getSetting("port") + " ability=" + Config.getSetting("ability") + " thread_num=" + Config.getSetting("thread_num") + "\r\n\t\t\t Copyright (C) 2015 JJF"); //提前加载驱动 Class.forName("com.mysql.jdbc.Driver"); // int nThreads = Integer.parseInt(Config.getSetting("thread_num")); ExecutorService threadPool = Executors.newFixedThreadPool(nThreads, new NamedThreadFactory("migration")); for(int i=0; i<nThreads; i++) { threadPool.execute(new MigrationTask()); try { //暂停1s是为了 能力值处理 Thread.sleep(1000); } catch (Exception e) { log.error("main thread sleep 1000ms error!",e); } } } }
33.232558
107
0.723583
b56c2e02b5cc31db7bc179f27d6d64eaa3bb7fa0
3,994
/* * (c) 2015 CenturyLink. All Rights Reserved. * * 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.centurylink.cloud.sdk.server.services.dsl.domain; import com.centurylink.cloud.sdk.base.services.dsl.domain.datacenters.refs.DataCenter; import com.centurylink.cloud.sdk.policy.services.dsl.domain.AlertPolicyConfig; import com.centurylink.cloud.sdk.policy.services.dsl.domain.AntiAffinityPolicyConfig; import com.centurylink.cloud.sdk.server.services.dsl.domain.group.GroupHierarchyConfig; import java.util.ArrayList; import java.util.List; import static com.centurylink.cloud.sdk.core.preconditions.Preconditions.checkNotNull; import static java.util.Arrays.asList; /** * Hierarchy configuration with groups and servers for provided data centers. * Should contain data center {@code dataCenter} * and {@link GroupHierarchyConfig} * {@code subitems}. * * @author Aliaksandr Krasitski */ public class InfrastructureConfig { private List<GroupHierarchyConfig> subitems = new ArrayList<>(); private List<DataCenter> dataCenters = new ArrayList<>(); private List<AntiAffinityPolicyConfig> antiAffinityPolicies = new ArrayList<>(); private List<AlertPolicyConfig> alertPolicies = new ArrayList<>(); public static InfrastructureConfig dataCenter(DataCenter... dataCenters) { return new InfrastructureConfig() .dataCenters(dataCenters); } /** * Returns list of hierarchy * @return list of sub items */ public List<GroupHierarchyConfig> getSubitems() { return subitems; } /** * * @param subitems array of {@link GroupHierarchyConfig} * @return current class instance */ public InfrastructureConfig subitems(GroupHierarchyConfig... subitems) { checkNotNull(subitems, "List of server configs must be not a null"); this.subitems.addAll(asList(subitems)); return this; } /** * Returns data centers * @return list of data centers */ public List<DataCenter> getDataCenters() { return dataCenters; } /** * * @param datacenters array of data centers * @return current class instance */ public InfrastructureConfig dataCenters(DataCenter... datacenters) { checkNotNull(datacenters, "List of dataCenters must be not a null"); this.dataCenters.addAll(asList(datacenters)); return this; } /** * Returns anti-affinity policies configs * @return list of anti-affinity policies configs */ public List<AntiAffinityPolicyConfig> getAntiAffinityPolicies() { return antiAffinityPolicies; } /** * * @param antiAffinityPolicies array of anti-affinity policies configs * @return current class instance */ public InfrastructureConfig antiAffinityPolicies(AntiAffinityPolicyConfig... antiAffinityPolicies) { this.antiAffinityPolicies.addAll(asList(antiAffinityPolicies)); return this; } /** * Returns alert policies configs * @return list of alert policies */ public List<AlertPolicyConfig> getAlertPolicies() { return alertPolicies; } /** * * @param alertPolicies array of alert policies configs * @return current class instance */ public InfrastructureConfig alertPolicies(AlertPolicyConfig... alertPolicies) { this.alertPolicies.addAll(asList(alertPolicies)); return this; } }
32.471545
104
0.702804
2e2a9d22797034760aedff0a47fa542b6d48725a
4,051
package my.interest.tamil.rest.resources.api; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import tamil.lang.TamilCharacterLookUpContext; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * <p> * </p> * * @author velsubra */ @Path("api/ezhuththu") public class EzhuththuResource extends BaseResource { @GET @Path("unicode/normalization/map") @Consumes("application/json") @Produces("application/json; charset=UTF-8") public String getMap() throws Exception { return from(TamilCharacterLookUpContext.getMap()).toString(); } @GET @Path("unicode/normalization/map/html") @Produces("text/html; charset=UTF-8") @Consumes(MediaType.TEXT_HTML) public String getMapHtml() throws Exception { StringBuffer table = new StringBuffer(); table.append("<html><head><title>Tamil unicode characters</title><body><table border='1'><tr><th>S.NO</th><th colspan='6'>Sequence =></th></tr>"); table.append(toHtmlTableBody("", TamilCharacterLookUpContext.getMap())); table.append("</table></body></html>"); return table.toString(); } private static JSONArray from(Map<Integer, TamilCharacterLookUpContext> map) throws JSONException { JSONArray array = new JSONArray(); List<Integer> next = new ArrayList<Integer>(map.keySet()); Collections.sort(next); for (Integer item : next) { array.put(from(item, map.get(item))); } return array; } private static JSONObject from(int val, TamilCharacterLookUpContext context) throws JSONException { JSONObject object = new JSONObject(); JSONObject firstcolumn = new JSONObject(); firstcolumn.put("value", String.valueOf(val)); if (!context.currentChar.toString().equals("" + (char) val)) { firstcolumn.put("form", "" + (char) val); } firstcolumn.put("tamil", context.currentChar.toString()); object.put("first", firstcolumn); Map<Integer, TamilCharacterLookUpContext> continuations = context.getContinuations(); if (continuations != null) { object.put("second", from(continuations)); } return object; } private static String toHtmlTableBody(String ssno, Map<Integer, TamilCharacterLookUpContext> map) throws JSONException { StringBuffer table = new StringBuffer(); table.append("<tbody>"); List<Integer> next = new ArrayList<Integer>(map.keySet()); Collections.sort(next); int count = 0; for (Integer item : next) { count ++; table.append("<tr>"); table.append("<td>#" + ssno + count + "</td>"); table.append(toHtml(ssno + String.valueOf(count) +".", item, map.get(item))); table.append("</tr>"); } table.append("</tbody>"); return table.toString(); } private static String toHtml(String sno, int val, TamilCharacterLookUpContext context) throws JSONException { StringBuffer table = new StringBuffer(); table.append("<td>"); table.append("@value:<b>0x0</b>" + Integer.toHexString(val)); table.append("<br/>letter:" + context.currentChar.toString()); if (!context.currentChar.toString().equals("" + (char) val)) { table.append("<br/><br/>form:" + (char) val); } else { } Map<Integer, TamilCharacterLookUpContext> continuations = context.getContinuations(); if (continuations != null && !continuations.isEmpty()) { table.append("</td><td><table border='1'>"); table.append(toHtmlTableBody(sno, continuations)); table.append("</table>"); } table.append("</td>"); return table.toString(); } }
32.408
154
0.627746
24bbc42a70f9b9b4973c9ee97b03643c29229555
1,780
/* * Copyright (C) 2009-2015 Johan Nilsson <http://markupartist.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 com.markupartist.sthlmtraveling.data.api; import android.support.annotation.NonNull; import android.text.TextUtils; import com.markupartist.sthlmtraveling.data.models.TravelMode; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * */ public class TravelModeQuery { private List<TravelMode> modes; public TravelModeQuery(@NonNull List<TravelMode> mode) { this.modes = mode; } public void addMode(TravelMode travelMode) { this.modes.add(travelMode); } public List<TravelMode> getModes() { return modes; } public static TravelModeQuery fromStringList(String travelModes) { if (travelModes == null) { return new TravelModeQuery(Collections.<TravelMode>emptyList()); } String[] rawModes = travelModes.split(","); List<TravelMode> modes = new ArrayList<>(); for (String mode : rawModes) { modes.add(new TravelMode(mode)); } return new TravelModeQuery(modes); } @Override public String toString() { return TextUtils.join(",", modes); } }
27.8125
76
0.68427
dfbce7e5d8abe6e1c7d9b0ba0efea5bdc0d99354
13,576
/** * */ package co.edu.uniquindio.logica; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Clase principal de logica de la aplicacion * * @author Juan David Sanchez A. * @author Juan Camilo Correa Pacheco * @author Carlos Alberto Cardona Beltran * @author Univerisdad Del Quindio * @author Armenia - Quindio */ public class JNetMap { /*** * Atributo auxiliar para obtener el nombre de una NIC */ private static NetworkInterface nombreNIC; /** * Lista de interfaces de red despues del proceso */ private static List<String> interfacesLista; /** * Lista de host disponibles de la red despues del proceso */ private static List<String> hostDisponible; /** * Lista de puertos disponibles despues del proceso */ private static List<Integer> portDisponibles; /** * Mascara de la red asociada a la NIC */ private static String mascaraRed; /** * Direccion inet auxiliar */ private static InetAddress inetAddress; /** * Lista de interfaces de red */ private static NetworkInterface networkIntefrface; /** * Lista auxiliar para guardar algunas IP */ private static ArrayList<String> auxIp; /** * Conjunto de hilos que se encargara de ejecutar tareas futuras */ final static ExecutorService es = Executors.newFixedThreadPool(100); final static List<Future<Boolean>> futures = new ArrayList<>(); /** * Constructor de la clase Nmap */ public JNetMap() { interfacesLista = new ArrayList<>(); hostDisponible = new ArrayList<>(); portDisponibles = new ArrayList<>(); auxIp = new ArrayList<>(); } /** * Metodo que permite listar las tarjetas disponibles * * @throws SocketException */ public void listarTarjetas() throws SocketException { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); NetworkInterface networkIntefrface = null; while (interfaces.hasMoreElements()) { // mientras exista otra tarjeta networkIntefrface = (NetworkInterface) interfaces.nextElement(); if (networkIntefrface.isUp()) // verifica que la tarje este activa interfacesLista.add(networkIntefrface.toString()); } } /** * Metodo que obtiene la informacion del host * * @param intRed * numero de interface de red seleccionada por el usuario * @throws SocketException */ @SuppressWarnings("static-access") public void obtenerInformacion(int intRed) throws SocketException { Enumeration<NetworkInterface> interfaces = nombreNIC.getNetworkInterfaces(); int contador = -1; while (interfaces.hasMoreElements() && contador != intRed) { networkIntefrface = (NetworkInterface) interfaces.nextElement(); if (networkIntefrface.isUp()) // verifica que la tarje este activa contador++; } Enumeration<InetAddress> direccionesIp = networkIntefrface.getInetAddresses(); inetAddress = (InetAddress) direccionesIp.nextElement(); for (InterfaceAddress iface : networkIntefrface.getInterfaceAddresses()) { if (iface == null) { continue; } if (iface.getAddress() instanceof Inet4Address) { mascaraRed = iface.getNetworkPrefixLength() + ""; } } while ((inetAddress instanceof Inet6Address)) { inetAddress = (InetAddress) direccionesIp.nextElement(); } } /** * Metodo que reopila la informacion del host * * @return msj con la informacion del host * @throws SocketException */ public String imprimirInformacion() throws SocketException { String inf = ""; inf += "Interfaces:" + networkIntefrface.toString() + "\n"; inf += "Mi direccion IP es:" + inetAddress.getHostAddress() + "\n"; inf += "Mi Mascara de red es:" + mascaraRed + "\n"; return inf; } /** * Metodo que calcula los host disponibles de una red a partir de la * direccion de la red * * @param i, * es el octeto a partir de el cual empieza a cambiar la * direccion que es la correspondiente para los hosts de la red * @param nuemroE, * ultimo octeto de la direccion de la red * @param direccion * de la red en arreglo de 4 posiciones */ private void calcularHostDisponibles(int i, int numeroE, int red[], int disponible) { if (numeroE == 255) { return; } else { for (int j = i; j < red.length; j++) { for (int k = numeroE; k <= disponible; k++) { red[i] = k; if (i != 3) { calcularHostDisponibles(i + 1, 0, red, 255); } else { red[i] = k; } String ip = red[0] + "." + red[1] + "." + red[2] + "." + red[3]; // Se envia la tarea de hacer ping, pero se deja como una // tarea futura, cuyo resultado se leera despues if (!auxIp.contains(ip)) { futures.add(realizarPing2(ip, es)); auxIp.add(ip); } } } } } /** * Metodo que calcula la direccion de la red y llama el metodo verificar * host disponibles */ public void hostDisponibles() { hostDisponible.clear(); int aux = Integer.parseInt(mascaraRed); int[] mascaraIP = new int[4]; String[] ipCadena = inetAddress.getHostAddress().split("\\."); int cont = 0; while (aux != 0) { if (aux >= 8) { mascaraIP[cont] = 255; aux -= 8; } else { int res = 0; for (int i = 7; i >= 8 - aux; i--) { res += (int) Math.pow(2, i); } mascaraIP[cont] = res; aux -= aux; } cont++; } // se clacula l adirecion de la red realizando una operacion and entre // la direcion ip y la mascara de la subred jd int[] dirRed = new int[4]; for (int i = 0; i < mascaraIP.length; i++) { dirRed[i] = mascaraIP[i] & Integer.parseInt(ipCadena[i]); } int indice = 3; while (mascaraIP[indice] != 255) { indice--; } int posicionMascara = Integer.parseInt(mascaraRed) / 8; int distancia = (int) Math.pow(2, 8 - Integer.parseInt(mascaraRed) % 8); calcularHostDisponibles(posicionMascara, dirRed[posicionMascara], dirRed, distancia + dirRed[posicionMascara] - 1); // El numero actual hace se asocia con el resultado falso o // verdadedo obtenido de la tarea enviada con anterioridad // de los futures int contador = 0; // Se lee en el ciclo para identificar cuales fueron las direcciones ip // que respondieron ante el ping realizado con anterioridad for (final Future<Boolean> f : futures) { try { if (f.get()) { hostDisponible.add(auxIp.get(contador)); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } contador++; } } /** * Metodo que realiza ping a un host * * @throws IOException, * UnknownHostException */ public boolean realizarPing(String ip) throws IOException, UnknownHostException { InetAddress direccion; direccion = InetAddress.getByName(ip); boolean alcanzable = direccion.isReachable(1500); if (alcanzable) return true; return false; } /** * Metodo que verfica los puertos disponibles de un host * * @param ip, * la direccion ip del host en el que se va a escanear todos los * puertos * @return listaPuertos, listado de puertos abiertos */ public ArrayList<Integer> port(String ip) { final ExecutorService es = Executors.newFixedThreadPool(1000); final int timeout = 400; final List<Future<Boolean>> tareas = new ArrayList<>(); for (int port = 1; port <= 65535; port++) { tareas.add(portIsOpen(es, ip, port, timeout)); } es.shutdown(); // Variable auxiliar para saber cual es el puerto que se esta leyendo en // la lista de tareas // int auxPuerto = 1; // ArrayList con la lista de puertos activos para este host ArrayList<Integer> listadoPuertos = new ArrayList<>(); for (final Future<Boolean> puertoActual : tareas) { try { if (puertoActual.get()) { listadoPuertos.add(auxPuerto); } } catch (Exception e) { } auxPuerto++; } return listadoPuertos; } /** * Metodo encargado de veificar si un puerto est� abierto * * @param es, * el ejecutor de tareas * @param ip, * la ip del host al que se escanearan los puertos * @param port, * el numero del puerto * @param timeout, * tiempo limite de respuesta * @return un hilo con el resultado */ private Future<Boolean> portIsOpen(final ExecutorService es, final String ip, final int port, final int timeout) { return es.submit(new Callable<Boolean>() { public Boolean call() { try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(ip, port), timeout); portDisponibles.add(port); socket.close(); return true; } catch (Exception ex) { return false; } } }); } /** * Metodo que verfica los puertos disponibles de un host * * @param ip, * la ip del host a que se har� ping */ public ArrayList<Integer> portServicios(String ip) { final ExecutorService es = Executors.newFixedThreadPool(1000); final int timeout = 400; final List<Future<Boolean>> tareas = new ArrayList<>(); for (int port = 1; port <= 65535; port++) { tareas.add(portIsOpenServicios(es, ip, port, timeout)); } es.shutdown(); // Variable auxiliar para saber cual es el puerto que se esta leyendo en // la lista de tareas // int auxPuerto = 1; // ArrayList con la lista de puertos activos para este host ArrayList<Integer> listadoPuertos = new ArrayList<>(); for (final Future<Boolean> puertoActual : tareas) { try { if (puertoActual.get()) { listadoPuertos.add(auxPuerto); } } catch (Exception e) { } auxPuerto++; } return listadoPuertos; } /** * Metodo encargado de veificar si un puerto est� abierto, y analizar su * servicio * * @param es, * el ejecutor de tareas * @param ip, * la ip del host al que se escanearan los puertos * @param port, * el numero del puerto * @param timeout, * tiempo limite de respuesta * @return un hilo con el resultado */ private Future<Boolean> portIsOpenServicios(final ExecutorService es, final String ip, final int port, final int timeout) { return es.submit(new Callable<Boolean>() { public Boolean call() { try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(ip, port), timeout); boolean autoflush = true; PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // send an HTTP request to the web server out.println("GET / HTTP/1.1"); out.println("Host: www.google.com:80"); out.println("Connection: Close"); out.println(); // read the response boolean loop = true; StringBuilder sb = new StringBuilder(8096); while (loop) { if (in.ready()) { int i = 0; while (i != -1) { i = in.read(); sb.append((char) i); } loop = false; } } System.out.println(sb.toString() + port); System.out.println("sales"); socket.close(); return true; } catch (Exception ex) { return false; } } }); } /** * Este metodo se encarga de realizar ping a la direccion ip recibida por * parametro pero lo pospone como un * * @param ip, * la ip del host al que se har� ping * @param es, * el ejecutor de tareas * @return un hilo con el resultado */ private Future<Boolean> realizarPing2(final String ip, final ExecutorService es) { return es.submit(new Callable<Boolean>() { public Boolean call() throws UnknownHostException, IOException { InetAddress direccion; direccion = InetAddress.getByName(ip); boolean alcanzable = direccion.isReachable(1500); if (alcanzable) return true; return false; } }); } /** * Metodo para obtener unlistado de las interfaces de red * * @return lista string con la descripcion de la interfaces de red */ public List<String> getInterfacesLista() { return interfacesLista; } /** * Metodo para obtener el listado de los host disponibles en mi red * * @return lista de string con las direcciones ip de los host disponibles */ public List<String> getHostDisponible() { return hostDisponible; } /** * Metodo para obtener el listado de los puertos disponibles de un host * * @return lista de enteros con los puertos disponibless */ public List<Integer> getPortDisponibles() { return portDisponibles; } }
28.34238
116
0.640174
e1e961f5b895e86a60fa68fbbaad4bb74859964d
1,287
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.openjpa.datacache; import org.apache.openjpa.kernel.PCData; /** * Specialized {@link PCData} implementation for data caching. * * @author Patrick Linskey */ public interface DataCachePCData extends PCData { /** * Whether this data is timed out. */ public boolean isTimedOut(); /** * Gets the original timeout of this instance. * * @return -1 for no timeout ever. */ public long getTimeOut(); }
29.930233
63
0.708625
87fd3b368953167ffb8375c86a667b362b3736f7
805
/* * Copyright (c) 2020-2021 - for information on the respective copyright owner * see the NOTICE file and/or the repository at * https://github.com/hyperledger-labs/acapy-java-client * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.aries.api.issue_credential_v1; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hyperledger.aries.api.credentials.CredentialPreview; /** * V1CredentialConnFreeOfferRequest */ @Data @AllArgsConstructor @NoArgsConstructor @Builder public class V1CredentialFreeOfferRequest { private Boolean autoIssue; private Boolean autoRemove; private String comment; private String credDefId; private CredentialPreview credentialPreview; private Boolean trace; }
25.967742
78
0.787578
76934aafb7b5a5a7808abbb8f102a64a51da0078
369
package poui; import processing.core.PGraphics; public interface Touchable { public void renderToTouchSurface(PGraphics context, int actionIndex, int color); public void applyTransformation(PGraphics _c); public void onHover(int actionIndex, boolean in); public void onClick(int actionIndex, boolean in); public void onDrag(int actionIndex, boolean in); }
28.384615
82
0.788618
228338ff91b6ef80142f39e82ba6e70b9e3fa930
269
package com.dtstack.flink.sql.util; import org.junit.Assert; import org.junit.Test; public class MD5UtilTest { @Test public void testGetMD5String(){ Assert.assertNotEquals(MD5Utils.getMD5String("aaaaa"), "d41d8cd98f00b204e9800998ecf8427e"); } }
19.214286
99
0.732342
80cda40f9fe2af2400f6f1ba2ca6b5c33ac60c2a
4,207
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.costmanagement.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; import java.util.List; /** The DimensionProperties model. */ @Fluent public final class DimensionProperties { @JsonIgnore private final ClientLogger logger = new ClientLogger(DimensionProperties.class); /* * Dimension description. */ @JsonProperty(value = "description", access = JsonProperty.Access.WRITE_ONLY) private String description; /* * Filter enabled. */ @JsonProperty(value = "filterEnabled", access = JsonProperty.Access.WRITE_ONLY) private Boolean filterEnabled; /* * Grouping enabled. */ @JsonProperty(value = "groupingEnabled", access = JsonProperty.Access.WRITE_ONLY) private Boolean groupingEnabled; /* * The data property. */ @JsonProperty(value = "data") private List<String> data; /* * Total number of data for the dimension. */ @JsonProperty(value = "total", access = JsonProperty.Access.WRITE_ONLY) private Integer total; /* * Dimension category. */ @JsonProperty(value = "category", access = JsonProperty.Access.WRITE_ONLY) private String category; /* * Usage start. */ @JsonProperty(value = "usageStart", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime usageStart; /* * Usage end. */ @JsonProperty(value = "usageEnd", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime usageEnd; /* * The link (url) to the next page of results. */ @JsonProperty(value = "nextLink", access = JsonProperty.Access.WRITE_ONLY) private String nextLink; /** * Get the description property: Dimension description. * * @return the description value. */ public String description() { return this.description; } /** * Get the filterEnabled property: Filter enabled. * * @return the filterEnabled value. */ public Boolean filterEnabled() { return this.filterEnabled; } /** * Get the groupingEnabled property: Grouping enabled. * * @return the groupingEnabled value. */ public Boolean groupingEnabled() { return this.groupingEnabled; } /** * Get the data property: The data property. * * @return the data value. */ public List<String> data() { return this.data; } /** * Set the data property: The data property. * * @param data the data value to set. * @return the DimensionProperties object itself. */ public DimensionProperties withData(List<String> data) { this.data = data; return this; } /** * Get the total property: Total number of data for the dimension. * * @return the total value. */ public Integer total() { return this.total; } /** * Get the category property: Dimension category. * * @return the category value. */ public String category() { return this.category; } /** * Get the usageStart property: Usage start. * * @return the usageStart value. */ public OffsetDateTime usageStart() { return this.usageStart; } /** * Get the usageEnd property: Usage end. * * @return the usageEnd value. */ public OffsetDateTime usageEnd() { return this.usageEnd; } /** * Get the nextLink property: The link (url) to the next page of results. * * @return the nextLink value. */ public String nextLink() { return this.nextLink; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
24.317919
96
0.630853
a3828475546a174279fa76210903542dfb9b32ad
3,310
/* * Copyright 2010-2019 Miyamoto Daisuke. * * 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 jp.xet.baseunits.time.formatter; import java.io.Serializable; import java.util.Locale; import java.util.TimeZone; import jp.xet.baseunits.time.TimePoint; import jp.xet.baseunits.time.TimeUnit; import com.google.common.base.Preconditions; import com.ibm.icu.impl.duration.BasicPeriodFormatterService; import com.ibm.icu.impl.duration.DurationFormatter; import com.ibm.icu.impl.duration.DurationFormatterFactory; /** * ICU4Jを利用した {@link RelativeTimePointFormatter} 実装クラス。 * * @author daisuke * @since 2.0 */ @SuppressWarnings("serial") public class Icu4jRelativeTimePointFormatter extends AbstractRelativeTimePointFormatter implements Serializable { private static final BasicPeriodFormatterService SERVICE = BasicPeriodFormatterService.getInstance(); private final FallbackConfig config; private final TimeZone timeZone; /** * インスタンスを生成する。 */ public Icu4jRelativeTimePointFormatter() { this(null, null); } /** * インスタンスを生成する。 * * <p>フォールバック設定及びタイムゾーンは必須ではないが、フォールバック設定を有効にした場合はタイムゾーンも必要である。</p> * * @param config フォールバック設定 * @param timeZone タイムゾーン * @throws IllegalArgumentException 引数{@code config}を指定したにも関わらず{@code timeZone}を与えなかった場合 */ public Icu4jRelativeTimePointFormatter(FallbackConfig config, TimeZone timeZone) { Preconditions.checkArgument((config == null && timeZone == null) || (config != null && timeZone != null)); this.config = config; this.timeZone = timeZone; } @Override public String format(TimePoint target, TimePoint standard, Locale locale) { Preconditions.checkNotNull(target); Preconditions.checkNotNull(standard); Preconditions.checkNotNull(locale); long t = target.toEpochMillisec(); long s = standard.toEpochMillisec(); long delta = t - s; if (config != null && timeZone != null && config.getLowerFallbackLimit() != null && Math.abs(delta) < config.getLowerFallbackLimit().to(TimeUnit.millisecond)) { return config.getLowerFallbackFormatter().format(target, locale, timeZone); } if (config != null && timeZone != null && config.getUpperFallbackLimit() != null && Math.abs(delta) >= config.getUpperFallbackLimit().to(TimeUnit.millisecond)) { return config.getUpperFallbackFormatter().format(target, locale, timeZone); } DurationFormatterFactory dff = SERVICE.newDurationFormatterFactory(); if (SERVICE.getAvailableLocaleNames().contains(locale.getLanguage())) { dff.setLocale(locale.getLanguage()); } else { dff.setLocale("en"); } DurationFormatter df = dff.getFormatter(); String result = df.formatDurationFrom(delta, s); return result; } }
33.434343
114
0.724169
f3625bb521d9e9bf66c16fc7797b57b67ba13932
14,189
/******************************************************************************* * Copyright (c) 2021 Gregory Mazo * * 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. *******************************************************************************/ /** * Author: Greg Mazo * Date Modified: May 1, 2021 * Version: 2021.1 */ package graphicalObjects; import java.awt.Color; import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.HashMap; import animations.KeyFrameCompatible; import applicationAdapters.CanvasMouseEvent; import animations.Animation; import animations.KeyFrameAnimation; import fLexibleUIKit.MenuItemExecuter; import graphicActionToolbar.CurrentFigureSet; import graphicalObjects_LayerTypes.GraphicLayer; import graphicalObjects_LayerTypes.GraphicLayerPane; import graphicalObjects_Shapes.GraphicUtil; import handles.DecorativeSmartHandleList; import handles.HasHandles; import keyFrameAnimators.BasicGraphicObjectKeyFrameAnimator; import locatedObject.AttachmentPosition; import locatedObject.Hideable; import locatedObject.LocationChangeListener; import locatedObject.LocationChangeListenerList; import locatedObject.ObjectContainer; import locatedObject.RectangleEdgePositions; import logging.IssueLog; import menuUtil.PopupMenuSupplier; import undo.AbstractUndoableEdit2; import undo.UndoManagerPlus; import undo.UndoScalingAndRotation; import menuUtil.HasUniquePopupMenu; /**The abstract superclass for many graphical objects*/ public abstract class BasicGraphicalObject implements GraphicalObject, HasHandles, HasUniquePopupMenu,KnowsSetContainer,KnowsParentLayer, Hideable, KeyFrameCompatible { /** * */ private static final long serialVersionUID = 1L; protected int locationType=RectangleEdgePositions.UPPER_LEFT;//indicates which location will actually be returned and set by the getlocation and set location methods protected double angle=0; LocationChangeListenerList listeners=new LocationChangeListenerList(); protected boolean handlesHidden=false; protected GraphicLayer parent;// the parent layer protected Animation animation=null;//if an animation has been set up transient boolean hidden=false;//set to true if hidden protected String name="";//the name of the object protected transient boolean selected=false, superSelected=false;// the selection state of the object protected double x=0;//location of an object protected double y=0;//location of an object Object key=null; public final HashMap<String, Object> map=new HashMap<String, Object>(); transient GraphicUtil Gu=new GraphicUtil(); transient boolean isDead=false; /**A smart handle list that is just for drawing. is not used by most subclasses*/ protected transient DecorativeSmartHandleList handleBoxes=new DecorativeSmartHandleList(); /**The worksheet that contains this object is stored here. TODO: determine if this is set properly*/ private transient FigureDisplayWorksheet parentWorksheet; /***/ private AttachmentPosition attachementPosition=null; protected int userLocked=NOT_LOCKED; protected GraphicUtil getGrahpicUtil() { if (Gu==null) Gu=new GraphicUtil(); return Gu; } @Override public String getName() { return name; } @Override public void setName(String st) { name=st; } @Override public String toString() { return this.getName(); } /**The list of items that are informed when the object size changes*/ public LocationChangeListenerList getListenerList() { return listeners; } /**The list of items that are informed when the object size changes * never returns null*/ public LocationChangeListenerList getListeners() { if (listeners==null) { listeners=new LocationChangeListenerList(); } return listeners; } /**Calls the objectMoved method for each listener */ public void notifyListenersOfMoveMent() { try { LocationChangeListenerList list = getListeners(); list.notifyListenersOfMoveMent(this); } catch (Exception e) { IssueLog.logT(e); } } /**Calls the object size changed method for each listener */ protected void notifyListenersOfSizeChange() { ArrayList<LocationChangeListener> list = getListeners(); for(LocationChangeListener lis: list) try { if (lis==null) continue; lis.objectSizeChanged(this); } catch(Throwable t) {} } /**Calls the user size changed method for each listener */ public void notifyListenersOfUserSizeChange() { getListeners().notifyListenersOfUserSizeChange(this); } /**Calls the object eliminated method for each listener */ public void notifyListenersOfDeath() { LocationChangeListenerList list = getListeners(); list.notifyListenersOfDeath(this); } /**Adds a location change listener*/ @Override public void addLocationChangeListener(LocationChangeListener l) { if (getListeners().contains(l)) return; getListeners().add(l); } /**removes a location change listener*/ @Override public void removeLocationChangeListener(LocationChangeListener l) { getListeners().remove(l); } /**removes all location change listener*/ @Override public void removeAllLocationChangeListeners() { getListeners().clear(); } /**sets object as selected*/ @Override public void select() { selected=true; } /**sets object as not selected*/ @Override public void deselect() { selected=false; superSelected=false; } /**returns true if the object is selected*/ @Override public boolean isSelected() { return selected; } /**returns a tag*/ @Override public Object getTag(String Key) { return map.get(Key); } /**returns all the tags*/ @Override public HashMap<String, Object> getTagHashMap() { return map; } /**moves the object*/ @Override public void moveLocation(double xmov, double ymov) { x=x+xmov; y=y+ymov; notifyListenersOfMoveMent(); } /**returns the location*/ public Point2D getLocation() { return new Point2D.Double(x,y); } /**sets the location. does not trigger the listeners*/ public void setLocation(double x,double y) { this.x=x; this.y=y; } /**sets the location. does not trigger the listeners*/ public void setLocation( Point2D p) { setLocation(p.getX(), p.getY()); } /**calls the object eliminated method*/ public void kill() { notifyListenersOfDeath(); isDead=true; } /**this method is called after a mouse event * shows and options dialog if the item is double clicked. * will be deprecated in the future*/ @Override public void handleMouseEvent(CanvasMouseEvent me, int handlenum, int button, int clickcount, int type, int... other) { if (clickcount<2||handlenum>NO_HANDLE_) return; if (clickcount==2) showOptionsDialog(); } /**Implementation depends on the subclass*/ @Override public Object dropObject(Object ob, int x, int y) { Point p = new Point((int)getBounds().getCenterX(), (int)getBounds().getCenterY()); if (ob instanceof Color) { Color c = (Color) ob; dropColor(c,new Point(x,y)); } return dropOther(ob, p); } /**Implementation depends on the subclass*/ public Object dropOther(Object ob, Point p) { // TODO Auto-generated method stub return null; } public void dropColor(Color c, Point p) { } /**returns the attachment position*/ public AttachmentPosition getAttachmentPosition() { return attachementPosition; } /**sets the attachment position*/ public void setAttachmentPosition(AttachmentPosition snappingBehaviour) { this.attachementPosition = snappingBehaviour; } public boolean isDead() { return isDead; } /**returns the menu supplier for this object*/ public PopupMenuSupplier getMenuSupplier() { return new MenuItemExecuter(this); } /**given a center of rotation and a point, returns the angle*/ public static double distanceFromCenterOfRotationtoAngle(Point2D pcent, Point2D p2) { //Point2D pcent=getCenterOfRotation(); double xc2=p2.getX()-pcent.getX(); double yc2=p2.getY()-pcent.getY(); double angle=-Math.atan((yc2)/(xc2)); if (!Double.isNaN(angle)) { if (xc2<0) angle+=Math.PI; while (angle<0) angle+=Math.PI*2; return angle; } return 0; } /**returns the handle number at the raw location of the lickpoint*/ @Override public int handleNumber(double x, double y) { { if (handleBoxes==null||handleBoxes.size()==1) return NO_HANDLE_; return handleBoxes.handleNumberForClickPoint(x, y); } } /**eliminates the */ public void clearHandleBoxes() { handleBoxes=new DecorativeSmartHandleList(); } /**sets the worksheet that contains this object*/ @Override public void setGraphicSetContainer(FigureDisplayWorksheet gc) { this.parentWorksheet=gc; } /**if the worksheet is known, this updates the display*/ @Override public void updateDisplay() { if( this.parentWorksheet==null) return; parentWorksheet.updateDisplay(); } /**returns the parent layer*/ @Override public GraphicLayer getParentLayer() { return parent; } /**set the parent layer*/ @Override public void setParentLayer(GraphicLayer parent) { this.parent=parent; } @Override public boolean isHidden() { return hidden; } @Override public void setHidden(boolean b) { hidden=b; } /**makes this item a primary selected item*/ public boolean makePrimarySelectedItem(boolean isFirst) { this.superSelected=isFirst; if(isFirst) this.select(); return superSelected; } /**Sets the location*/ public void setLocationUpperLeft(Point2D p2) { setLocationUpperLeft(p2.getX(),p2.getY()); } /**scales the point location * @param p1 the point to be scaled and returned * @param the center with respect to scaling * @param sx the x axis scale factor * @param sy the y axis scale factor * */ protected static Point2D scalePointAbout(Point2D p1, Point2D about, double sx, double sy) { double dx=p1.getX()-about.getX(); double dy=p1.getY()-about.getY(); dx*=sx; dy*=sy; p1.setLocation(dx+about.getX(), dy+about.getY()); return p1; } /**returns true if this item is inside of the rectangle*/ @Override public boolean isInside(Rectangle2D rect) { return rect.contains(getBounds()); } /**returns true if this item intersects the rectangle*/ @Override public boolean doesIntersect(Rectangle2D rect) { return getOutline().intersects(rect); } /**returns the location type. What point on the bounding box is the location (@see RectangleEdgePosisions)*/ public int getLocationType() { return locationType; } /**sets the location type. What point on the bounding box is the location (@see RectangleEdgePosisions)*/ public void setLocationType(int locationType) { this.locationType = locationType; } /**Returns the user locked property * @see LocatedObject2D * * */ public int isUserLocked() { return userLocked; } /**Called whenever a handle is released. In this case, does nothing */ public void handleRelease(int handlenum, Point p1, Point p2) {} /**Called whenever a handle is pressed. In this case, does nothing */ public void handlePress(int handlenum, Point p2) {} /**Called whenever a handle is moved. In this case, does nothing*/ public void handleMove(int handlenum, Point p1, Point p2) {} /**returns the animation for the object*/ public Animation getAnimation() {return animation;} /**sets the animation for the object*/ public void setAnimation(Animation animation) { this.animation = animation; } /**if there is not animation, creates one and returns it*/ public KeyFrameAnimation getOrCreateAnimation() { if (animation instanceof KeyFrameAnimation) return (KeyFrameAnimation) animation; animation=new BasicGraphicObjectKeyFrameAnimator(this); return (KeyFrameAnimation) animation; } /**returns the rotation transform for the shape*/ public AffineTransform getRotationTransform() { double xr = getCenterOfRotation().getX(); double yr = getCenterOfRotation().getY(); return AffineTransform.getRotateInstance(-angle, xr, yr); } /**returns the pivot point about which this object rotates */ public Point2D getCenterOfRotation() { Rectangle b = this.getBounds(); return new Point2D.Double(b.getCenterX(), b.getCenterY()); } /**returns the current angle*/ public double getAngle() { return angle; } /**set the current angle*/ public void setAngle(double angle) { if (angle==this.getAngle()) return; Point2D p = this.getLocation(); this.angle=angle; this.setLocation(p.getX(), p.getY()); } /**adds the argument to the current angle*/ public void rotate(double angle) { Point2D p = this.getLocation(); this.angle+=angle; this.setLocation(p.getX(), p.getY()); } /**provides an edit that can be used to undo a mouse drag */ public AbstractUndoableEdit2 provideDragEdit() { return new UndoScalingAndRotation(this); } /**returns an undo manager that is available * TODO: find a way to replace this*/ public UndoManagerPlus getUndoManager() { return new CurrentFigureSet().getCurrentlyActiveDisplay().getUndoManager(); } /**finds the layer pane at the top of the tree*/ public ObjectContainer getTopLevelContainer() { if(this.getParentLayer()==null) return null; GraphicLayer layer = getParentLayer().getTopLevelParentLayer(); if(layer instanceof GraphicLayerPane) return (ObjectContainer) layer; return null; } /**set to true to hide the handles*/ public void hideHandles(boolean b) { handlesHidden=b; } /**returns nothing but subclass may return */ public Object getScaleWarning() { return null; } }
26.924099
170
0.727606
cfc493d04fcf3b70089a8d9625f53a5415333f27
10,264
package com.hepengju.hekele.base.core; import com.hepengju.hekele.base.constant.HeConst; import lombok.*; import org.apache.commons.io.IOUtils; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; /** * 中文提示信息均提取到文件 * * @author hepengju 2018-02-05 */ public class M { private static ResourceLoader resourceLoader = new DefaultResourceLoader(); private static final String MESSAGE_NAME = "classpath:he.message"; // 由于SpringBoot项目, 配置文件在jar包里面, 不能动态修改文件了, 此处加入get/set用于前端界面动态修改(重启后失效) @Getter @Setter private static Map<String, HeMessage> keyHeMessageMap; static { try (InputStream inputStream = resourceLoader.getResource(MESSAGE_NAME).getInputStream();){ List<Integer> codeList = new ArrayList<>(); List<String> keyList = new ArrayList<>(); List<HeMessage> hmList = new ArrayList<>(); // SpringBoot的jar包里面不能使用此种方式读取 //File file = ResourceUtils.getFile(MESSAGE_NAME); //List<String> lineList = Files.readAllLines(file.toPath()); List<String> lineList = IOUtils.readLines(inputStream, StandardCharsets.UTF_8); for (String line : lineList) { if (line.startsWith("#") || "".equals(line.trim())) continue; //#号注释处理 try { String[] arr = line.split(":"); Integer code = Integer.parseInt(arr[0].trim()); String key = arr[1].trim(); String value = arr[2].trim(); if (codeList.contains(code)) throw new RuntimeException("file [" + MESSAGE_NAME + "] code repeat: " + line); if (keyList .contains(key )) throw new RuntimeException("file [" + MESSAGE_NAME + "] key repeat: " + line); codeList.add(code); keyList.add(key); hmList.add(new HeMessage(code, key, value)); } catch (Exception e) { throw new RuntimeException("file [" + MESSAGE_NAME + "] line format error: " + line); } } keyHeMessageMap = hmList.stream().collect(Collectors.toMap(HeMessage::getKey, Function.identity(), (e1, e2) -> e1, LinkedHashMap::new)); } catch (IOException e) { throw new RuntimeException("load file [" + MESSAGE_NAME + "] exception: ", e); } } /** * 获取: 参数传入多少都不能报错 */ public static String get(String key, Object... args) { String value = Optional.ofNullable(keyHeMessageMap.get(key)) .map(HeMessage::getValue) .orElse(key); if (value == null) return ""; //配置文本 if (args != null) { int length = args.length; //参数个数 while (length > 0) { //参数个数大于零时,逐个减少参数直到成功 try { return String.format(value, args); } catch (Exception e) { length--; if (length == 0) return value; args = Arrays.copyOf(args, length); } } } return value; } public static JsonR getErrR(String key, Object... args) { String value = get(key, args); Integer code = Optional.ofNullable(keyHeMessageMap.get(key)).map(HeMessage::getCode).orElse(HeConst.ErrorCode.UNKNOWN_ERROR); return JsonR.err(value).setErrCode(code); } /** * 打印输出给客户方(CSV) */ public static void printCSVFormat() { keyHeMessageMap.forEach((key, hm) -> { System.out.printf("%d,%s,%s\n", hm.getCode(), hm.getKey(), hm.getValue()); }); } @Data @AllArgsConstructor @NoArgsConstructor static class HeMessage { private Integer code; private String key; private String value; } } // 旧版本 ///** // * 中文提示信息均提取到文件 // * // * <br> // * <br> 需求 // * <br> 1. 可以方便的修改提示信息 // * <br> 2. 需要实现通过配置可以热加载(不用重启系统) // * <br> 3. 启动校验key值的重复,不停机,记录错误日志 // * <br> 4. 集成String.format功能,并保证不传参数时不报错 // * <br> // * <br> 文件格式采用message,而没有采用properties的考虑 // * <br> 1. properties文件中的中文编译后为\\uXXXX, 修改某个提示, 需要先开发环境修改好文件, 再替换到生产环境, 比较麻烦 // * <br> 2. properties文件中key值重复时,默认会自动覆盖之前的,不便于校验 // * <br> // * <br> // * <br> 日期: 20180507 // * <br> 变更: 讨论考虑追加错误代码,同时修正此类 // * <br> // * // * @author hepengju 2018-02-05 // */ //public class M { // // private static Logger logger = LoggerFactory.getLogger(M.class); // // //属性配置文件的名称 // private static final String PROPERTIES_NAME = "classpath:topcheer.message"; // private static File file; // private static Long lastModifyTime; // // //静态代码块取得配置信息 --> 20190616 加入负号的正则, 错误代码前面加入负号表示前端提示用信息提示而不是错误提示 // //private static final String REG_ERRCODE = "\\{\\{(\\d+)\\}\\}"; // private static final String REG_ERRCODE = "\\{\\{(-?\\d+)}}"; // Idea提示对于-和}前面加的\\是冗余的转义,实测去掉也可以 // // private static Map<String,Integer> errcodeMap; // private static Map<String,String> errmsgMap; // static { // loadProperties(); // reloadProperties(); // } // // //重新加载属性 // private static boolean reload; // private static int reloadSeconds; // // //定时器 // private static Timer timer; // // /** // * 取得配置信息 // */ // private static synchronized void loadProperties() { // //注意: 这种方式对于路径含有空格的会转换为%20,导致下面Files.readAllLines方法报错无法找到这个文件 // //file = new File(Thread.currentThread().getContextClassLoader().getResource(PROPERTIES_NAME).getFile()); // try { // file = ResourceUtils.getFile(PROPERTIES_NAME); // List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); // Map<String,Integer> tempErrcodeMap = new HashMap<>(); // Map<String,String> tempErrmsgMap = new HashMap<>(); // // lines.forEach(line -> { // if(line.startsWith("#")) return; //#号注释处理 // int position = line.indexOf('='); // if (position < 1) return; //没有等号的行忽略 // // //20190516 加入trim // String key = line.substring(0, position).trim(); // String value = line.substring(position + 1).trim(); // // //20180507 value值中追加错误代码 {{errcode}}errmsg // int errcode = -1; // Pattern pattern = Pattern.compile(REG_ERRCODE); // Matcher matcher = pattern.matcher(value); // if(matcher.find()) { // String errcodeStr = matcher.group(1).trim(); //20190516 加入trim // errcode = NumberUtils.toInt(errcodeStr,-1); // } // // String errmsg = value.replaceFirst(REG_ERRCODE, "").trim(); //20190516 加入trim // //判断是否已经存在,存在的打印错误日志 // if (tempErrcodeMap.containsKey(key)) { // logger.error("{}: preValue [{}] of key [{}] already exists, this value [{}] will be ingored ", // PROPERTIES_NAME, tempErrcodeMap.get(key), key, value); // } else { // tempErrcodeMap.put(key, errcode); // tempErrmsgMap.put(key, errmsg); // } // // }); // // //取得所有属性值后,修改map指向新的map // errcodeMap = tempErrcodeMap; // errmsgMap = tempErrmsgMap; // logger.info("{}load properties: {}", Objects.isNull(lastModifyTime) ? "" : "re",PROPERTIES_NAME); // lastModifyTime = file.lastModified(); // } catch (IOException e) { // logger.error("load properties: {} failure ",PROPERTIES_NAME); // } // } // // // // /** // * 定时任务重载配置: 配置为重载,且文件的最后修改时间与保存的不一致,则重载属性 // */ // private static void reloadProperties() { // reload = PropUtil.getBoolean("topcheer.message.reload", true); // if(reload) { // reloadSeconds = PropUtil.getInteger("topcheer.message.reloadSeconds", 300); // timer = new Timer(); // timer.schedule(new TimerTask() { // public void run() { // if (file.lastModified() != lastModifyTime) loadProperties(); // } // }, reloadSeconds * 1000L, reloadSeconds * 1000L); // } // } // // /** // * 取消Timer // */ // public static void cancelTimer() { // if(timer != null) timer.cancel(); // } // // /** // * 获取: 参数传入多少都不能报错 // */ // public static String get(String key,Object... args) { // String confMsg = errmsgMap.get(key); //配置文本 // if(args != null) { // int length = args.length; //参数个数 // while(length > 0) { //参数个数大于零时,逐个减少参数直到成功 // try { // return String.format(confMsg, args); // }catch(Exception e) { // length--; // if(length == 0) return confMsg; // args = Arrays.copyOf(args, length); // } // } // } // return confMsg; // } // // /** // * 获取(不带变参): 因为带变参的key,每次写代码提示都需要删除后面的args,非常烦人 // */ // public static String key(String key) { // return get(key); // } // // /** // * 取得错误代码 // */ // public static int getCode(String key) { // return errcodeMap.get(key) == null ? -1 : errcodeMap.get(key); // } // // public static R getErrR(String key,Object... args) { // return R.err(get(key, args)).setErrCode(getCode(key)); // } // // public static R keyErrR(String key) { // return getErrR(key); // } // // public static R getOkR(String key,Object... args) { // return R.ok().setErrMsg(get(key, args)); // } // // public static R keyOkR(String key) { // return getOkR(key); // } // // public static Map<String, Integer> getErrcodeMap() { // return errcodeMap; // } // // public static Map<String, String> getErrmsgMap() { // return errmsgMap; // } //}
34.558923
148
0.545012
598258ed01a994e06fc986c4869bae7c6592efec
3,159
package org.yinan.rpc.service; import io.grpc.Server; import io.grpc.ServerBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yinan.config.context.ConfigContext; import org.yinan.grpc.MapBackFeedEntry; import org.yinan.grpc.MasterReceiveServiceGrpc.MasterReceiveServiceImplBase; import org.yinan.grpc.ReduceBackFeedEntry; import org.yinan.rpc.service.callback.ICallBack; import org.yinan.rpc.service.impl.MasterReceiveServiceImpl; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * @author yinan * @date 2021/5/12 */ public class MasterReceiver extends MasterReceiveServiceImplBase { private static volatile boolean hashInit = false; private final static Logger LOGGER = LoggerFactory.getLogger(MasterReceiver.class); private final Map<String, ICallBack<?>> callBackMap = new HashMap<>(); public final static String MAP_NOTIFY = "map_notify"; public final static String REDUCE_NOTIFY = "reduce_notify"; private Server server; private final Executor executor = Executors.newFixedThreadPool(3, new ThreadFactory() { private int count = 0; @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setName("master receiver thread " + count ++); return thread; } }); public MasterReceiver() { if (!hashInit) { try { hashInit = true; this.server = ServerBuilder.forPort(ConfigContext.getInstance() .getRpcInfos() .get("master").getPort()) .addService(new MasterReceiveServiceImpl(this)) .build(); } catch (Exception e) { LOGGER.error("create grpc error: {}", e.toString()); } } } public MasterReceiver register(String name, ICallBack<?> callBack) { callBackMap.put(name, callBack); return this; } public void finished() { if (this.server != null) { try { this.server.start(); this.server.awaitTermination(); } catch (Exception e) { LOGGER.error("init server error: {}", e.toString()); } } } @SuppressWarnings("unchecked") public void mapNotify(MapBackFeedEntry request) { LOGGER.info("receive map worker info: {}", request.toString()); executor.execute(() -> ((ICallBack<MapBackFeedEntry>) callBackMap.get(MAP_NOTIFY)).call(request)); } @SuppressWarnings("unchecked") public void reduceNotify(ReduceBackFeedEntry request) { LOGGER.info("receive reduce worker info: {}", request.toString()); executor.execute(() -> ((ICallBack<ReduceBackFeedEntry>) callBackMap.get(REDUCE_NOTIFY)).call(request)); } public synchronized void stop() { if (this.server != null) { this.server.shutdown(); } } }
31.909091
112
0.638177
ef92c5e67f046341c0aa4720d34fcf911bcd3c56
3,748
package de.goatfryed.pm.battleships.model; import java.beans.PropertyChangeSupport; import java.beans.PropertyChangeListener; public class Shot { public static final String PROPERTY_column = "column"; private int column; public int getColumn() { return column; } public Shot setColumn(int value) { if (value != this.column) { int oldValue = this.column; this.column = value; firePropertyChange("column", oldValue, value); } return this; } public static final String PROPERTY_row = "row"; private String row; public String getRow() { return row; } public Shot setRow(String value) { if (value == null ? this.row != null : ! value.equals(this.row)) { String oldValue = this.row; this.row = value; firePropertyChange("row", oldValue, value); } return this; } public static final String PROPERTY_player = "player"; private Player player = null; public Player getPlayer() { return this.player; } public Shot setPlayer(Player value) { if (this.player != value) { Player oldValue = this.player; if (this.player != null) { this.player = null; oldValue.withoutShots(this); } this.player = value; if (value != null) { value.withShots(this); } firePropertyChange("player", oldValue, value); } return this; } public static final String PROPERTY_hit = "hit"; private Section hit = null; public Section getHit() { return this.hit; } public Shot setHit(Section value) { if (this.hit != value) { Section oldValue = this.hit; if (this.hit != null) { this.hit = null; oldValue.setShotBy(null); } this.hit = value; if (value != null) { value.setShotBy(this); } firePropertyChange("hit", oldValue, value); } return this; } protected PropertyChangeSupport listeners = null; public boolean firePropertyChange(String propertyName, Object oldValue, Object newValue) { if (listeners != null) { listeners.firePropertyChange(propertyName, oldValue, newValue); return true; } return false; } public boolean addPropertyChangeListener(PropertyChangeListener listener) { if (listeners == null) { listeners = new PropertyChangeSupport(this); } listeners.addPropertyChangeListener(listener); return true; } public boolean addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { if (listeners == null) { listeners = new PropertyChangeSupport(this); } listeners.addPropertyChangeListener(propertyName, listener); return true; } public boolean removePropertyChangeListener(PropertyChangeListener listener) { if (listeners != null) { listeners.removePropertyChangeListener(listener); } return true; } public boolean removePropertyChangeListener(String propertyName,PropertyChangeListener listener) { if (listeners != null) { listeners.removePropertyChangeListener(propertyName, listener); } return true; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(" ").append(this.getRow()); return result.substring(1); } public void removeYou() { this.setPlayer(null); this.setHit(null); } }
20.480874
99
0.595251
8c8b1ad36f2a0784299db15cf16d34632dd11774
2,221
package com.drools; import lombok.extern.slf4j.Slf4j; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieContainerSessionsPool; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.StatelessKieSession; /** * @author cWww * @Title * @Description * @date: 2019/2/25 15:34 */ @Slf4j() public class BaseTest { /** * The default pool size * 16 */ private static final Integer POOL_SIZE = 1 << 4; private KieContainerSessionsPool kieContainerSessionsPool; private KieContainer kieContainer; private KieServices kieServices; { final KieServices kieServices = KieServices.get(); final KieContainer kieContainer = kieServices.getKieClasspathContainer(); this.kieContainer = kieContainer; this.kieServices = kieServices; kieContainerSessionsPool = kieContainer.newKieSessionsPool(POOL_SIZE); String format = "yyyy-MM-dd HH:mm:ss"; System.setProperty("drools.dateformat", format); } protected KieContainer getKieContainer(){ return kieContainer; } protected KieServices getKieServices(){ return this.kieServices; } protected KieSession getKieSession(String agendaGroup){ KieSession kieSession = getKieSession(); kieSession.getAgenda().getAgendaGroup(agendaGroup).setFocus(); return kieSession; } protected KieSession getKieSession(String agendaGroup,String sessionName){ KieSession kieSession = getKieSessions(sessionName); kieSession.getAgenda().getAgendaGroup(agendaGroup).setFocus(); return kieSession; } protected KieSession getKieSession(){ return kieContainerSessionsPool.newKieSession("all-rules"); } protected KieSession getKieSessions(String sessionName){ return kieContainerSessionsPool.newKieSession(sessionName); } /** * notice:由于通过kieContainerSessionsPool创建以后的session默认为stateful * 然后将stateful的结果包装为stateless * @return */ protected StatelessKieSession getStatelessKieSession(String sessionName){ return kieContainerSessionsPool.newStatelessKieSession(sessionName); } }
28.844156
81
0.715894
c90250bee3b8cb1aa7da3f1256eac2b439cd206a
2,670
/* Copyright 2006, Carnegie Mellon, All Rights Reserved */ package edu.cmu.minorthird.classify.ranking; import java.util.Iterator; import java.util.List; import java.util.Map; import edu.cmu.minorthird.classify.Classifier; import edu.cmu.minorthird.classify.Dataset; import edu.cmu.minorthird.classify.Example; import edu.cmu.minorthird.classify.algorithms.linear.Hyperplane; import edu.cmu.minorthird.util.ProgressCounter; /** * A ranking method based on a voted perceptron. */ public class RankingPerceptron extends BatchRankingLearner { private int numEpochs; private static final double MARGIN = 0.1; public RankingPerceptron() { this(100); } public RankingPerceptron(int numEpochs) { this.numEpochs=numEpochs; } @Override public Classifier batchTrain(Dataset data) { Hyperplane h = new Hyperplane(); Hyperplane s = new Hyperplane(); int numUpdates = 0; Map<String,List<Example>> rankingMap = listsWithOneExampleEach( splitIntoRankings(data) ); //Map rankingMap = splitIntoRankings(data); ProgressCounter pc = new ProgressCounter("perceptron training", "epoch", numEpochs); for (int e=0; e<numEpochs; e++) { //System.out.println("epoch "+e+"/"+numEpochs); for (Iterator<String> i=rankingMap.keySet().iterator(); i.hasNext(); ) { String subpop = i.next(); List<Example> ranking = rankingMap.get(subpop); numUpdates += batchTrainSubPop( h, s, ranking ); } pc.progress(); } pc.finished(); // turn sum hyperplane into an average s.multiply( 1.0/(numUpdates) ); //new ViewerFrame("hyperplane", s.toGUI()); return s; } // return the number of times h has been updated private int batchTrainSubPop( Hyperplane h, Hyperplane s, List<Example> ranking ) { sortByScore(h,ranking); int updates = 0; // int highestNegativeIndex = ranking.size(); Example highestNegativeExample = null; for (int i=0; i<ranking.size(); i++) { Example exi = ranking.get(i); if (exi.getLabel().isNegative()) { // highestNegativeIndex = i; highestNegativeExample = ranking.get(i); break; } } // look for positive example, update for (int i=0; i<ranking.size(); i++) { Example exi = ranking.get(i); if (exi.getLabel().isPositive()) { if (highestNegativeExample!=null && (h.score(exi) < h.score(highestNegativeExample)+MARGIN)) { //if (i>highestNegativeIndex) { // the positive example is ranked below the // highestNegativeExample, which is incorrect Example pos = ranking.get(i); h.increment( highestNegativeExample, -1.0); h.increment( pos, +1.0 ); } s.increment( h ); updates++; } } return updates; } }
29.021739
98
0.689888
d2f46277da1b3fa68d3142d5a79ebe7ada4210ce
2,010
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 dashboard.domain; import java.io.Serializable; import com.google.common.base.MoreObjects; @SuppressWarnings("serial") public class InstitutionIdentityProvider implements Serializable { private String id; private String name; private String nameNl; private String institutionId; public InstitutionIdentityProvider() { } public InstitutionIdentityProvider(String id, String name, String nameNl, String institutionId) { this.id = id; this.name = name; this.nameNl = nameNl; this.institutionId = institutionId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getInstitutionId() { return institutionId; } public void setInstitutionId(String institutionId) { this.institutionId = institutionId; } public String getNameNl() { return nameNl; } public void setNameNl(String nameNl) { this.nameNl = nameNl; } @Override public String toString() { return MoreObjects.toStringHelper(this).add("id", id).add("name", name).toString(); } }
24.814815
99
0.718408
3d6af2bfdf099f249fe399c1599e08d30c632c53
11,339
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 javax.naming.ldap; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import javax.naming.InvalidNameException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import org.apache.harmony.jndi.internal.nls.Messages; import org.apache.harmony.jndi.internal.parser.LdapRdnParser; import org.apache.harmony.jndi.internal.parser.LdapTypeAndValueList; /** * TODO: JavaDoc */ public class Rdn implements Serializable, Comparable<Object> { private static final long serialVersionUID = -5994465067210009656L; public static String escapeValue(Object val) { if (val == null) { throw new NullPointerException("val " + Messages.getString("ldap.00")); } return LdapRdnParser.escapeValue(val); } public static Object unescapeValue(String val) { if (val == null) { throw new NullPointerException("val " + Messages.getString("ldap.00")); } return LdapRdnParser.unescapeValue(val); } private transient List<Attribute> list; private transient LdapRdnParser parser; public Rdn(Attributes attrSet) throws InvalidNameException { if (attrSet == null) { throw new NullPointerException("attrSet " + Messages.getString("ldap.00")); } if (attrSet.size() == 0) { throw new InvalidNameException("atrrSet " + Messages.getString("ldap.03")); } // check all the elements to follow RI's behavior NamingEnumeration<? extends Attribute> ne = attrSet.getAll(); while (ne.hasMoreElements()) { Attribute at = ne.nextElement(); try { at.get(); } catch (NamingException e) { } } list = convertToAttributeArrayList(attrSet); } public Rdn(Rdn rdn) { if (rdn == null) { throw new NullPointerException("rdn " + Messages.getString("ldap.00")); } list = convertToAttributeArrayList(rdn.toAttributes()); } public Rdn(String rdnString) throws InvalidNameException { if (rdnString == null) { throw new NullPointerException("rdnString " + Messages.getString("ldap.00")); } if (rdnString.length() != 0) { parser = new LdapRdnParser(rdnString); list = parser.getList(); } else { list = new ArrayList<Attribute>(); } } public Rdn(String type, Object value) throws InvalidNameException { if (type == null) { throw new NullPointerException("type " + Messages.getString("ldap.00")); } if (value == null) { throw new NullPointerException("value " + Messages.getString("ldap.00")); } if (type.length() == 0) { throw new InvalidNameException("type " + Messages.getString("ldap.04")); } if (value instanceof String && ((String) value).length() == 0) { throw new InvalidNameException("value " + Messages.getString("ldap.04")); } list = convertToAttributeArrayList(new BasicAttributes(type, value, true)); } public int compareTo(Object obj) { if (!(obj instanceof Rdn)) { throw new ClassCastException(Messages.getString("ldap.06")); //$NON-NLS-1$ } Rdn rdn = (Rdn) obj; String s1 = ""; //$NON-NLS-1$ String s2 = ""; //$NON-NLS-1$ for (Enumeration<?> iter = toAttributes().getAll(); iter .hasMoreElements();) { s1 = s1 + escapeValue(iter.nextElement().toString()); /* * this one does not seem necessary. Spec does not require it, if * there are apps that depend on commas, uncomment it */ // if (iter.hasMoreElements()) { // s1 = s1 + ","; // } } for (Enumeration<?> iter = rdn.toAttributes().getAll(); iter .hasMoreElements();) { s2 = s2 + escapeValue(iter.nextElement().toString()); /* * this one does not seem necessary. Spec does not require it, if * there are apps that depend on commas, uncomment it */ // if (iter.hasMoreElements()) { // s2 = s2 + ","; // } } return s1.toLowerCase().compareTo(s2.toLowerCase()); } private List<Attribute> convertToAttributeArrayList(Attributes attrList) { LdapTypeAndValueList myList = new LdapTypeAndValueList(); NamingEnumeration<? extends Attribute> ne = attrList.getAll(); try { while (ne.hasMoreElements()) { Attribute attr = ne.nextElement(); myList.put(attr.getID(), attr.get()); } } catch (NamingException e) { } return myList.toAttributeList(); } public boolean equals(Object obj) { if (!(obj instanceof Rdn) || this.size() != ((Rdn) obj).size()) { return false; } if (this == obj) { return true; } NamingEnumeration<? extends Attribute> iter1 = toAttributes().getAll(); NamingEnumeration<? extends Attribute> iter2 = ((Rdn) obj) .toAttributes().getAll(); while (iter1.hasMoreElements()) { Attribute a1 = iter1.nextElement(); Attribute a2 = iter2.nextElement(); if (!(a1.getID().toLowerCase().equals(a2.getID().toLowerCase())) || a1.size() != a2.size()) { return false; } Enumeration<?> en1 = null; Enumeration<?> en2 = null; try { en1 = a1.getAll(); en2 = a2.getAll(); } catch (NamingException e) { // what is the correct way for this? return false; } while (en1.hasMoreElements()) { Object o1 = en1.nextElement(); String s1 = (o1 instanceof String) ? (String) o1 : escapeValue(o1); Object o2 = en2.nextElement(); String s2 = (o2 instanceof String) ? (String) o2 : escapeValue(o2); if (!(s1.toLowerCase().equals(s2.toLowerCase()))) { return false; } } } return true; } public String getType() { return list.get(0).getID(); } public Object getValue() { Object a = null; try { a = list.get(0).get(); } catch (NamingException e) { } catch (NullPointerException e) { } return a; } public int hashCode() { int sum = 0; for (Iterator<Attribute> attr = list.iterator(); attr.hasNext();) { Attribute a = attr.next(); NamingEnumeration<?> en = null; sum += a.getID().toLowerCase().hashCode(); try { en = a.getAll(); } catch (NamingException e) { continue; } while (en.hasMoreElements()) { Object obj = en.nextElement(); if (obj instanceof byte[]) { obj = new String((byte[]) obj); } try { String s = (String) obj; sum += escapeValue(s.toLowerCase()).hashCode(); } catch (ClassCastException e) { sum += obj.hashCode(); } } } return sum; } public int size() { int result = 0; for (Iterator<Attribute> iter = list.iterator(); iter.hasNext();) { result += iter.next().size(); } return result; } public Attributes toAttributes() { BasicAttributes bas = new BasicAttributes(true); for (Iterator<Attribute> iter = list.iterator(); iter.hasNext();) { Attribute attr = iter.next(); BasicAttribute ba = new BasicAttribute(attr.getID(), false); try { NamingEnumeration nameEnum = attr.getAll(); while (nameEnum.hasMore()) { ba.add(nameEnum.next()); } } catch (NamingException ne) { } bas.put(ba); } return bas; } public String toString() { StringBuilder sb = new StringBuilder(); for (Iterator<Attribute> iter = list.iterator(); iter.hasNext();) { Attribute element = iter.next(); NamingEnumeration<?> ne = null; try { ne = element.getAll(); } catch (NamingException e) { } while (ne.hasMoreElements()) { sb.append(element.getID()); sb.append('='); sb.append(escapeValue(ne.nextElement())); if (ne.hasMoreElements()) { sb.append('+'); } } if (iter.hasNext()) { sb.append('+'); } } return sb.toString(); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException, InvalidNameException { ois.defaultReadObject(); String rdnString = (String) ois.readObject(); if (rdnString == null) { throw new NullPointerException("rdnString " + Messages.getString("ldap.00")); } if (rdnString.length() != 0) { parser = new LdapRdnParser(rdnString); list = parser.getList(); } else { list = new ArrayList<Attribute>(); } } private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); oos.writeObject(this.toString()); } }
31.497222
86
0.537261
44457702c0a01868f1d5648b13d9f1324835c2ef
883
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1998-1999 IBM Corp. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package omega; /** * omega/Climax.java * Generated by the IBM IDL-to-Java compiler (portable), version "3.0" * from d:/java/java/idl/omega/Lima.idl * 06 May 1999 17:02:50 o'clock GMT+00:00 */ public final class Climax extends org.omg.CORBA.UserException implements org.omg.CORBA.portable.IDLEntity { public int quickstep = (int)0; public Climax () { } // ctor public Climax (int _quickstep) { quickstep = _quickstep; } // ctor } // class Climax
24.527778
105
0.691959
0b9884b5c055814a50a7e76f1d0e82726222260d
3,526
package net.smackem.ylang.runtime; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import java.util.Iterator; import java.util.Locale; import java.util.Objects; public class LineVal extends GeometryVal<PointVal> { private final float x1, y1; private final float x2, y2; public LineVal(float x1, float y1, float x2, float y2) { super(ValueType.LINE); this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public float x1() { return x1; } public float y1() { return y1; } public float x2() { return x2; } public float y2() { return y2; } public float length() { return (float) Math.hypot(this.x2 - this.x1, this.y2 - this.y1); } @Override Geometry createGeometry() { final GeometryFactory gf = new GeometryFactory(); return gf.createLineString(new Coordinate[] { new Coordinate(this.x1, this.y1), new Coordinate(this.x2, this.y2) }); } @Override public GeometryVal<PointVal> translate(PointVal pt) { return new LineVal(this.x1 + pt.x(), this.y1 + pt.y(), this.x2 + pt.x(), this.y2 + pt.y()); } @Override public RectVal bounds() { final float left = Math.min(this.x1, this.x2); final float right = Math.max(this.x1, this.x2); final float top = Math.min(this.y1, this.y2); final float bottom = Math.max(this.y1, this.y2); return new RectVal(left, top, right - left, bottom - top); } @SuppressWarnings("NullableProblems") @Override public Iterator<PointVal> iterator() { return new PointIterator(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LineVal values = (LineVal) o; return Float.compare(values.x1, x1) == 0 && Float.compare(values.y1, y1) == 0 && Float.compare(values.x2, x2) == 0 && Float.compare(values.y2, y2) == 0; } @Override public int hashCode() { return Objects.hash(x1, y1, x2, y2); } @Override public String toString() { return "LineVal{" + "x1=" + x1 + ", y1=" + y1 + ", x2=" + x2 + ", y2=" + y2 + '}'; } @Override public String toLangString() { return String.format(Locale.ROOT, "line(%f;%f, %f;%f)", this.x1, this.y1, this.x2, this.y2); } private class PointIterator implements Iterator<PointVal> { final float stepX, stepY; final int steps; float x, y; int index; PointIterator() { final float dx = x2 - x1; final float dy = y2 - y1; this.steps = (int) Math.max(Math.abs(dx), Math.abs(dy)); this.stepX = dx / (float)steps; this.stepY = dy / (float)steps; this.x = x1; this.y = y1; } @Override public boolean hasNext() { return this.index < this.steps; } @Override public PointVal next() { final PointVal pt = new PointVal(this.x, this.y); this.index++; this.x += this.stepX; this.y += this.stepY; return pt; } } }
26.313433
100
0.534884
67c926a4af367ca75ca6e89f4aaa0e1bdcf07981
354
package com.pattern.designpattern.command; import com.pattern.designpattern.command.entity.IProduct; public class LightOnCommand implements Command { private IProduct light; public LightOnCommand(IProduct light) { this.light = light; } @Override public void execute() { light.on(); } @Override public void undo() { light.off(); } }
14.75
57
0.728814
13d29e99e032d721bdb6759f4ada64fa79d84e0f
239
package my.rnd.totp.ctrl; import org.springframework.data.repository.CrudRepository; import my.rnd.totp.dao.AuthSecret; public interface AppRepository extends CrudRepository<AuthSecret, String> { AuthSecret findByAppID(String id); }
21.727273
75
0.811715
dbb886931857da360cb59c174f741901ca3153f7
257
package com.ajoy.test; import java.util.List; import javafx.scene.control.ChoiceDialog; public class ChoiceDialogBox<T> extends ChoiceDialog<T> { private List<T> choices; public ChoiceDialogBox(List<T> choiceList) { choices = choiceList; } }
15.117647
55
0.743191
eeb1cd99602eaf970db7a9d53800d9b6c4910dfd
1,067
package com.electric_decade.calculator.api; import java.time.LocalDate; public class SeriesDay { private LocalDate date; private float[] intervals; private float sum; private float average; private float min; private float max; public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } public float[] getIntervals() { return intervals; } public void setIntervals(float[] intervals) { this.intervals = intervals; } public float getSum() { return sum; } public void setSum(float sum) { this.sum = sum; } public float getAverage() { return average; } public void setAverage(float average) { this.average = average; } public float getMin() { return min; } public void setMin(float min) { this.min = min; } public float getMax() { return max; } public void setMax(float max) { this.max = max; } }
17.209677
49
0.581068
fcd60897c2c473f84f23964894548a7942946b49
705
package com.nawy.liquidmongo.storage; import com.mongodb.client.MongoClient; public class DefaultMongoStorage implements StorageAdapter { private final MongoClient mongoClient; private final String databaseName; public DefaultMongoStorage(MongoClient mongoClient, String databaseName) { this.mongoClient = mongoClient; this.databaseName = databaseName; } @Override public <ENTITY_T> StorageCollection<ENTITY_T> getCollection(String collectionName, Class<ENTITY_T> clazz) { return new DefaultMongoCollection<>( this.mongoClient, this.databaseName, collectionName, clazz ); } }
28.2
111
0.68227
7d950198b21dd31aab93fd46469e087e2d292159
2,131
package com.naver.nid.cover.parser.coverage.jacoco; import com.naver.nid.cover.parser.coverage.CoverageReportParser; import com.naver.nid.cover.parser.coverage.model.FileCoverageReport; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import java.net.URL; import java.util.List; import static com.naver.nid.cover.parser.coverage.model.CoverageStatus.COVERED; import static org.junit.jupiter.api.Assertions.*; @Slf4j class JacocoHtmlReportParserTest { @Test public void htmlFileParsing() { htmlFileParsingTest(new JacocoHtmlReportParser(file -> file.getName().endsWith(".java.html"))); } void htmlFileParsingTest(CoverageReportParser parser) { URL diffUrl = getClass().getClassLoader().getResource("reports/html/com.naver.nid.cover.github/GithubCommentManager.java.html"); log.debug("diffUrl {}", diffUrl.toString()); List<FileCoverageReport> parse = parser.parse(diffUrl); log.debug("{}", parse); FileCoverageReport fileCoverageReport = parse.get(0); assertEquals("com/naver/nid/cover/github/GithubCommentManager.java", fileCoverageReport.getFileName()); assertEquals("java", fileCoverageReport.getType()); assertEquals(COVERED, fileCoverageReport.getLineCoverageReportList().stream().filter(l -> l.getLineNum() == 21).findFirst().orElseThrow(AssertionError::new).getStatus()); } @Test public void directoryParsing() { htmlDirectoryParsing(new JacocoHtmlReportParser(file -> file.getName().endsWith(".java.html"))); } void htmlDirectoryParsing(CoverageReportParser parser) { URL reportUrl = getClass().getClassLoader().getResource("reports"); log.debug("diffUrl {}", reportUrl); List<FileCoverageReport> reports = parser.parse(reportUrl); log.debug("{}", reports); FileCoverageReport fileCoverageReport = reports.get(0); assertEquals("com/naver/nid/cover/github/GithubCommentManager.java", fileCoverageReport.getFileName()); assertEquals("java", fileCoverageReport.getType()); assertEquals(COVERED, fileCoverageReport.getLineCoverageReportList().stream().filter(l -> l.getLineNum() == 21).findFirst().orElseThrow(AssertionError::new).getStatus()); } }
39.462963
172
0.773815
bbd09c8c8a67f38850674e1c21efc9a79a3f35fa
196
package us.codecraft.xsoup; import org.jsoup.nodes.Element; /** * 匹配单个元素接口 * * @author code4crafter@gmail.com */ public interface XElement { String get(); Element getElement(); }
11.529412
33
0.673469
4f94011805f6c2a0ef774dd4a6a3741b1edff041
3,555
/** * Copyright 2019 DataCompressionPrimitives. * * Licensed under the Apache License, Version 2.0 (the "License"); */ package org.dcp.test.util; import org.dcp.util.EntropyUtil; import org.junit.Test; import java.math.BigInteger; import static org.junit.Assert.assertEquals; public class EntropyUtilTest { @Test public void testFindSizeOfBitsToHold() { assertEquals(EntropyUtil.findSizeOfBitsToHold(0), 0); assertEquals(EntropyUtil.findSizeOfBitsToHold(1), 1); assertEquals(EntropyUtil.findSizeOfBitsToHold(-1), 2); assertEquals(EntropyUtil.findSizeOfBitsToHold(2), 2); assertEquals(EntropyUtil.findSizeOfBitsToHold(Short.MAX_VALUE), 15); assertEquals(EntropyUtil.findSizeOfBitsToHold(Short.MIN_VALUE), 17); assertEquals(EntropyUtil.findSizeOfBitsToHold(Long.MAX_VALUE), 63); assertEquals(EntropyUtil.findSizeOfBitsToHold(Long.MIN_VALUE), 65); assertEquals(EntropyUtil.findSizeOfBitsToHoldBig(new BigInteger("0")), 0); assertEquals(EntropyUtil.findSizeOfBitsToHoldBig(new BigInteger("1")), 1); assertEquals(EntropyUtil.findSizeOfBitsToHoldBig(new BigInteger("-1")), 2); assertEquals(EntropyUtil.findSizeOfBitsToHoldBig(new BigInteger("2")), 2); assertEquals(EntropyUtil.findSizeOfBitsToHoldBig(new BigInteger("255")), 8); assertEquals(EntropyUtil.findSizeOfBitsToHoldBig(new BigInteger("-128")), 9); assertEquals(EntropyUtil.findSizeOfBitsToHoldBig(new BigInteger("9223372036854775807")), 63); assertEquals(EntropyUtil.findSizeOfBitsToHoldBig(new BigInteger("-115792089237316195423570985008687907853269984665640564039457584007913129639935")), 257); assertEquals(EntropyUtil.findSizeOfBitsToHoldBig(new BigInteger("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137215")), 1024); } @Test public void findMaximumValueRepresentible() { assertEquals(EntropyUtil.findMaximumValueRepresentible(0), 0); assertEquals(EntropyUtil.findMaximumValueRepresentible(1), 1); assertEquals(EntropyUtil.findMaximumValueRepresentible(2), 3); assertEquals(EntropyUtil.findMaximumValueRepresentible(8), 255); assertEquals(EntropyUtil.findMaximumValueRepresentible(32), 4294967295L); assertEquals(EntropyUtil.findMaximumValueRepresentible(63), 9223372036854775807L); assertEquals(EntropyUtil.findMaximumValueRepresentibleBig(63), new BigInteger("9223372036854775807")); assertEquals(EntropyUtil.findMaximumValueRepresentibleBig(64), new BigInteger("18446744073709551615")); assertEquals(EntropyUtil.findMaximumValueRepresentibleBig(128), new BigInteger("340282366920938463463374607431768211455")); assertEquals(EntropyUtil.findMaximumValueRepresentibleBig(256), new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639935")); assertEquals(EntropyUtil.findMaximumValueRepresentibleBig(1024), new BigInteger("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137215")); } }
63.482143
402
0.808158
2e8d4446cb29b0d47c871bb9d90fdd5fc35cfce7
9,636
/* * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * * THIS FILE WAS MODIFIED BY SUN MICROSYSTEMS, INC. */ package com.sun.xml.internal.org.jvnet.fastinfoset.sax; import org.xml.sax.SAXException; /** * SAX2 extention handler to receive notification of character data as * primtive types. * * <p>This is an optional extension handler for SAX2. XML readers are not * required to recognize this handler, and it is not part of core-only * SAX2 distributions.</p> * * <p>This interface may be used with with a Fast Infoset * SAX parser to receive notification of data encoded using the * following built-in encoding algorithms specified in ITU-T Rec. X.891 | ISO/IEC 24824-1 * (Fast Infoset), clause 10: "boolean", "base64", "short", "int", "long", * "float", "double" and "uuid" encoding algorithms.<p> * * <p>To set the PrimitiveTypeContentHandler for an XML reader, use the * {@link org.xml.sax.XMLReader#setProperty setProperty} method * with the property name * <code>URI TO BE DEFINED</code> * and an object implementing this interface (or null) as the value. * If the reader does not report primitive data types, it will throw a * {@link org.xml.sax.SAXNotRecognizedException SAXNotRecognizedException}</p> * * <p>To set the PrimitiveTypeContentHandler for an Fast Infoset reader, use * {@link com.sun.xml.internal.org.jvnet.fastinfoset.sax.FastInfosetReader#setPrimitiveTypeContentHandler * setPrimitiveTypeContentHandler} method.<p> * <p>The Parser will call methods of this interface to report each * chunk of character data that has been converted to an array of primitive * types, for example an array of integer or an array of float. Parsers may * return all contiguous primtive types in a single chunk, or they may split * it into several chunks</p> * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * @see com.sun.xml.internal.org.jvnet.fastinfoset.sax.EncodingAlgorithmContentHandler * @see com.sun.xml.internal.org.jvnet.fastinfoset.sax.FastInfosetReader * @see org.xml.sax.XMLReader */ public interface PrimitiveTypeContentHandler { /** * Receive notification of character data as an array of boolean. * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Such notifications will occur for a Fast Infoset SAX parser * when processing data encoded using the "boolean" encoding * algorithm, see subclause 10.7<p>. * * @param b the array of boolean * @param start the start position in the array * @param length the number of boolean to read from the array * @throws org.xml.sax.SAXException any SAX exception, possibly * wrapping another exception */ public void booleans(boolean [] b, int start, int length) throws SAXException; /** * Receive notification of character data as an array of byte. * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Such notifications will occur for a Fast Infoset SAX parser * when processing data encoded using the "base64" encoding * algorithm, see subclause 10.3, or the "hexadecimal" encoding * algorithm, see subclause 10.2. * * <p>Such a notification may occur for binary data that would * normally require base 64 encoding and reported as character data * using the {@link org.xml.sax.ContentHandler#characters characters} * method <p>. * * @param b the array of byte * @param start the start position in the array * @param length the number of byte to read from the array * @throws org.xml.sax.SAXException any SAX exception, possibly * wrapping another exception */ public void bytes(byte[] b, int start, int length) throws SAXException; /** * Receive notification of character data as an array of short. * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Such notifications will occur for a Fast Infoset SAX parser * when processing data encoded using the "short" encoding * algorithm, see subclause 10.4<p>. * * @param s the array of short * @param start the start position in the array * @param length the number of short to read from the array * @throws org.xml.sax.SAXException any SAX exception, possibly * wrapping another exception */ public void shorts(short[] s, int start, int length) throws SAXException; /** * Receive notification of character data as an array of int. * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Such notifications will occur for a Fast Infoset SAX parser * when processing data encoded using the "int" encoding * algorithm, see subclause 10.5<p>. * * @param i the array of int * @param start the start position in the array * @param length the number of int to read from the array * @throws org.xml.sax.SAXException any SAX exception, possibly * wrapping another exception */ public void ints(int [] i, int start, int length) throws SAXException; /** * Receive notification of character data as an array of long. * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Such notifications will occur for a Fast Infoset SAX parser * when processing data encoded using the "long" encoding * algorithm, see subclause 10.6<p>. * * @param l the array of long * @param start the start position in the array * @param length the number of long to read from the array * @throws org.xml.sax.SAXException any SAX exception, possibly * wrapping another exception */ public void longs(long [] l, int start, int length) throws SAXException; /** * Receive notification of character data as an array of float. * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Such notifications will occur for a Fast Infoset SAX parser * when processing data encoded using the "float" encoding * algorithm, see subclause 10.8<p>. * * @param f the array of float * @param start the start position in the array * @param length the number of float to read from the array * @throws org.xml.sax.SAXException any SAX exception, possibly * wrapping another exception */ public void floats(float [] f, int start, int length) throws SAXException; /** * Receive notification of character data as an array of double. * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Such notifications will occur for a Fast Infoset SAX parser * when processing data encoded using the "double" encoding * algorithm, see subclause 10.9<p>. * * @param d the array of double * @param start the start position in the array * @param length the number of double to read from the array * @throws org.xml.sax.SAXException any SAX exception, possibly * wrapping another exception */ public void doubles(double [] d, int start, int length) throws SAXException; /** * Receive notification of character data as an two array of UUID. * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Such notifications will occur for a Fast Infoset SAX parser * when processing data encoded using the "uuid" encoding * algorithm, see subclause 10.10<p>. * * @param msblsb the array of long containing pairs of most signficant * bits and least significant bits of the UUIDs * @param start the start position in the array * @param length the number of long to read from the array. This will * be twice the number of UUIDs, which are pairs of two long values * @throws org.xml.sax.SAXException any SAX exception, possibly * wrapping another exception */ public void uuids(long[] msblsb, int start, int length) throws SAXException; }
43.017857
105
0.691781
7956af9d2b07fc8b89d9a0008b9f6d32e76f803c
1,028
package main; import helper.CompileException; import org.jetbrains.annotations.NotNull; import java.io.FileNotFoundException; import java.io.PrintWriter; public class FileWriter { /** * Utility method for writing to the output directory * @param directory The OutputDirs constant for the directory. * @param name The file name to write to. * @param content The content to write as a string (platform default encoding). * @throws CompileException If there is an error writing to the file = */ public static void writeToOutput(@NotNull OutputDirs directory, @NotNull String name, @NotNull String content) throws CompileException { directory.createDir(); try { PrintWriter pw = new PrintWriter(directory.location + name); pw.println(content); pw.flush(); pw.close(); } catch (FileNotFoundException e) { throw new CompileException("Couldn't write to the file", e, name, -1); } } }
31.151515
114
0.661479
1fa03b6d30f16ec19971882eee392b6e258b3fd8
4,348
package havis.llrpservice.common.concurrent; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.ReentrantLock; import org.testng.annotations.Test; public class EventPipesTest { @Test public void await() throws Exception { ExecutorService threadPool = Executors.newFixedThreadPool(2); final EventPipes et = new EventPipes(new ReentrantLock()); // get current events without a waiting time List<Integer> intEvents = et.await(Integer.class, EventPipe.RETURN_IMMEDIATELY); // an empty list is received assertEquals(intEvents.size(), 0); // fire events of different types and get them without a waiting time et.fire(1); et.fire(2L); intEvents = et.await(Integer.class, EventPipe.RETURN_IMMEDIATELY); List<Long> longEvents = et.await(Long.class, EventPipe.RETURN_IMMEDIATELY); // the events are received assertEquals(intEvents.size(), 1); assertEquals(intEvents.get(0).intValue(), 1); assertEquals(longEvents.size(), 1); assertEquals(longEvents.get(0).longValue(), 2); // wait without a time out and fire events of different types final List<Integer> threadIntEvents1 = new ArrayList<>(); final List<Long> threadLongEvents1 = new ArrayList<>(); final CountDownLatch threadIntStarted1 = new CountDownLatch(1); final CountDownLatch threadLongStarted1 = new CountDownLatch(1); Future<?> futureInt1 = threadPool.submit(new Runnable() { @Override public void run() { try { threadIntStarted1.countDown(); threadIntEvents1.addAll(et.await(Integer.class, EventPipe.NO_TIMEOUT)); } catch (Exception e) { fail(); } } }); Future<?> futureLong1 = threadPool.submit(new Runnable() { @Override public void run() { try { threadLongStarted1.countDown(); threadLongEvents1.addAll(et.await(Long.class, EventPipe.NO_TIMEOUT)); } catch (Exception e) { fail(); } } }); assertTrue(threadIntStarted1.await(3, TimeUnit.SECONDS)); assertTrue(threadLongStarted1.await(3, TimeUnit.SECONDS)); Thread.sleep(500); et.fire(2); et.fire(3L); futureInt1.get(3, TimeUnit.SECONDS); futureLong1.get(3, TimeUnit.SECONDS); // the events are received assertEquals(threadIntEvents1.size(), 1); assertEquals(threadIntEvents1.get(0).intValue(), 2); assertEquals(threadLongEvents1.size(), 1); assertEquals(threadLongEvents1.get(0).intValue(), 3L); // wait with a time out and fire an event before the waiting time // elapses final List<Integer> threadIntEvents2 = new ArrayList<>(); final List<Long> threadLongEvents2 = new ArrayList<>(); final CountDownLatch threadIntStarted2 = new CountDownLatch(1); final CountDownLatch threadLongStarted2 = new CountDownLatch(1); Future<?> futureInt2 = threadPool.submit(new Runnable() { @Override public void run() { try { threadIntStarted2.countDown(); threadIntEvents2.addAll(et.await(Integer.class, 5000)); } catch (Exception e) { fail(); } } }); Future<?> futureLong2 = threadPool.submit(new Runnable() { @Override public void run() { try { threadLongStarted2.countDown(); threadLongEvents2.addAll(et.await(Long.class, 5000)); } catch (Exception e) { fail(); } } }); assertTrue(threadIntStarted2.await(3, TimeUnit.SECONDS)); assertTrue(threadLongStarted2.await(3, TimeUnit.SECONDS)); Thread.sleep(500); et.fire(2); et.fire(3L); futureInt2.get(3, TimeUnit.SECONDS); futureLong2.get(3, TimeUnit.SECONDS); // the event is received assertEquals(threadIntEvents1.size(), 1); assertEquals(threadIntEvents1.get(0).intValue(), 2); assertEquals(threadLongEvents1.size(), 1); assertEquals(threadLongEvents1.get(0).longValue(), 3); // wait with a time out but do not send any event try { et.await(Integer.class, 1000); fail(); } catch (TimeoutException e) { // an exception occurs assertTrue(e.getMessage().contains("1000")); } threadPool.shutdown(); } }
31.507246
82
0.718721
ddf5afe7f80d855bff65f1a3d31324ba62b1ecaf
3,291
/** * Copyright (c) 2013-2020 Nikita Koksharov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.spring.cache; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.URL; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; /** * * @author Nikita Koksharov * */ public class CacheConfigSupport { ObjectMapper jsonMapper = new ObjectMapper(); ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory()); public Map<String, CacheConfig> fromJSON(String content) throws IOException { return jsonMapper.readValue(content, new TypeReference<Map<String, CacheConfig>>() {}); } public Map<String, CacheConfig> fromJSON(File file) throws IOException { return jsonMapper.readValue(file, new TypeReference<Map<String, CacheConfig>>() {}); } public Map<String, CacheConfig> fromJSON(URL url) throws IOException { return jsonMapper.readValue(url, new TypeReference<Map<String, CacheConfig>>() {}); } public Map<String, CacheConfig> fromJSON(Reader reader) throws IOException { return jsonMapper.readValue(reader, new TypeReference<Map<String, CacheConfig>>() {}); } public Map<String, CacheConfig> fromJSON(InputStream inputStream) throws IOException { return jsonMapper.readValue(inputStream, new TypeReference<Map<String, CacheConfig>>() {}); } public String toJSON(Map<String, ? extends CacheConfig> configs) throws IOException { return jsonMapper.writeValueAsString(configs); } public Map<String, CacheConfig> fromYAML(String content) throws IOException { return yamlMapper.readValue(content, new TypeReference<Map<String, CacheConfig>>() {}); } public Map<String, CacheConfig> fromYAML(File file) throws IOException { return yamlMapper.readValue(file, new TypeReference<Map<String, CacheConfig>>() {}); } public Map<String, CacheConfig> fromYAML(URL url) throws IOException { return yamlMapper.readValue(url, new TypeReference<Map<String, CacheConfig>>() {}); } public Map<String, CacheConfig> fromYAML(Reader reader) throws IOException { return yamlMapper.readValue(reader, new TypeReference<Map<String, CacheConfig>>() {}); } public Map<String, CacheConfig> fromYAML(InputStream inputStream) throws IOException { return yamlMapper.readValue(inputStream, new TypeReference<Map<String, CacheConfig>>() {}); } public String toYAML(Map<String, ? extends CacheConfig> configs) throws IOException { return yamlMapper.writeValueAsString(configs); } }
36.977528
99
0.727438
981275302e543b7fc3b289bf2ffdbd69e785e2ca
3,086
/* This file is part of Intake24. © Crown copyright, 2012, 2013, 2014. This software is licensed under the Open Government Licence 3.0: http://www.nationalarchives.gov.uk/doc/open-government-licence/ */ package uk.ac.ncl.openlab.intake24.client.survey.rules; import org.pcollections.PSet; import org.workcraft.gwt.shared.client.Option; import uk.ac.ncl.openlab.intake24.client.survey.*; import uk.ac.ncl.openlab.intake24.client.survey.prompts.EnergyValidationPrompt; public class ShowEnergyValidationPrompt implements PromptRule<Survey, SurveyOperation> { final private double energyValueThreshold; public ShowEnergyValidationPrompt(double energyValueThreshold) { this.energyValueThreshold = energyValueThreshold; } private double totalEnergyValue(Survey survey) { double sum = 0.0; for (Meal m : survey.meals) for (FoodEntry f : m.foods) { sum += f.accept(new FoodEntry.Visitor<Double>() { @Override public Double visitRaw(RawFood food) { return 0.0; } @Override public Double visitEncoded(EncodedFood food) { if (food.data.categories.contains(SpecialData.FOOD_CODE_MILK_IN_HOT_DRINK)) return 0.0; else { CompletedPortionSize completedPortionSize = food.completedPortionSize(); return food.data.caloriesPer100g * (completedPortionSize.servingWeight() - completedPortionSize.leftoversWeight()) / 100.0; } } @Override public Double visitTemplate(TemplateFood food) { return 0.0; } @Override public Double visitMissing(MissingFood food) { return 0.0; } @Override public Double visitCompound(CompoundFood food) { return 0.0; } }); } return sum; } @Override public Option<Prompt<Survey, SurveyOperation>> apply(Survey state, SelectionMode selectionType, PSet<String> surveyFlags) { if (!state.isPortionSizeComplete() || state.meals.isEmpty() || state.energyValueConfirmed()) return Option.none(); else if (totalEnergyValue(state) < energyValueThreshold) return Option.<Prompt<Survey, SurveyOperation>>some(new EnergyValidationPrompt()); else return Option.none(); } @Override public String toString() { return "Show energy value confirmation prompt"; } public static WithPriority<PromptRule<Survey, SurveyOperation>> withPriority(int priority, double energyValueThreshold) { return new WithPriority<PromptRule<Survey, SurveyOperation>>(new ShowEnergyValidationPrompt(energyValueThreshold), priority); } }
36.305882
151
0.597213
3a0decfc7d26e9ae9216c75f27711a3384bc7992
480
package uk.ac.ebi.spot.goci; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.support.SpringBootServletInitializer; /** * Created by dwelter on 22/06/15. */ @SpringBootApplication public class PussycatApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(PussycatApplication.class, args); } }
30
73
0.797917
6ab1a2cde2b018fe3ee258c160c3889f3d67d0ab
4,503
package io.github.delirius325.jmeter.config.livechanges.api.resources; import io.github.delirius325.jmeter.config.livechanges.LiveChanges; import io.github.delirius325.jmeter.config.livechanges.ResultHolder; import io.github.delirius325.jmeter.config.livechanges.SamplerMap; import io.github.delirius325.jmeter.config.livechanges.helpers.GenericHelper; import io.github.delirius325.jmeter.config.livechanges.helpers.JSONHelper; import org.apache.jmeter.threads.JMeterContextService; import org.json.JSONArray; import org.json.JSONObject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.text.DecimalFormat; import java.util.Map; /** * Base Endpoint for the TestResource class */ @Path("/test") public class TestResource { /** * GET Endpoint that retrieves the current status of the running test (startTime, runningTime, etc.) * @return A stringified JSONObject as the Response */ @GET @Path("/status") @Produces(MediaType.APPLICATION_JSON) public Response getTestStatus() { JSONObject jsonObject = new JSONObject(); jsonObject.put("startTime", JMeterContextService.getTestStartTime()); jsonObject.put("runningTime", GenericHelper.getTestTimeElapsedSec()); jsonObject.put("totalActiveThreads", JMeterContextService.getNumberOfThreads()); jsonObject.put("totalThreads", JMeterContextService.getTotalThreads()); return Response.ok(jsonObject.toString()).build(); } /** * GET Endpoint that allows the user to stop the test * @return A stringified JSONObject as the Response */ @GET @Path("/end") @Produces(MediaType.APPLICATION_JSON) public Response endTestRun() { JSONObject jsonObject = new JSONObject(); LiveChanges.setStopTest(true); JSONHelper.jsonSetInfo(jsonObject, "success", "Threads will gracefully stop."); return Response.ok(jsonObject.toString()).build(); } @GET @Path("/summary") @Produces(MediaType.APPLICATION_JSON) public Response getTestSummary() { JSONArray jsonArray = new JSONArray(); SamplerMap samplerMap = LiveChanges.getSamplerMap(); for(Map.Entry<String, ResultHolder> entry : samplerMap.getMap().entrySet()) { try { DecimalFormat df = new DecimalFormat("#.##"); JSONObject parentObject = new JSONObject(); JSONObject childObject = new JSONObject(); ResultHolder resultHolder = entry.getValue(); String sampleLabel = resultHolder.getCalculator().getLabel(); // construct JSON objects and add to array childObject.put("averageBytes", df.format(resultHolder.getCalculator().getAvgPageBytes())); childObject.put("averageLatency", df.format(resultHolder.getAvgLatency())); childObject.put("averageResponseTime", df.format(resultHolder.getCalculator().getMeanAsNumber())); childObject.put("errorPercentage", df.format(resultHolder.getCalculator().getErrorPercentage())); childObject.put("hitsPerSecond", df.format(resultHolder.getCalculator().getRate())); childObject.put("minResponseTime", df.format(resultHolder.getCalculator().getMin())); childObject.put("maxResponseTime", df.format(resultHolder.getCalculator().getMax())); childObject.put("90thPercentile", df.format(resultHolder.getNinetiethPercentile())); childObject.put("standardDeviation", df.format(resultHolder.getCalculator().getStandardDeviation())); childObject.put("sentBytesPerSecond", df.format(resultHolder.getCalculator().getSentBytesPerSecond())); childObject.put("receivedBytesPerSecond", df.format(resultHolder.getCalculator().getBytesPerSecond())); childObject.put("totalSamples", df.format(resultHolder.getCalculator().getCount())); childObject.put("totalErrors", df.format(resultHolder.getTotalErrors())); childObject.put("totalBytes", df.format(resultHolder.getCalculator().getTotalBytes())); parentObject.put(sampleLabel, childObject); jsonArray.put(parentObject); } catch (Exception e) { e.printStackTrace(); } } return Response.ok(jsonArray.toString()).build(); } }
48.419355
119
0.686209
60e4056d416930700fbb395f70377857a249b65d
4,768
package com.hernandes.pontointeligente.entities; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Optional; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.persistence.Transient; import com.hernandes.pontointeligente.enums.PerfilEnum; @Entity @Table(name = "funcionario") public class Funcionario implements Serializable { private static final long serialVersionUID = -5754246207015712518L; private Long id; private String nome; private String email; private String senha; private String cpf; private BigDecimal valorHora; private Float qtdHorasTrabalhoDia; private Float qtdHorasAlmoco; private PerfilEnum perfil; private Date dataCriacao; private Date dataAtualizacao; private Empresa empresa; private List<Lancamento> lancamentos; public Funcionario() { } @Id @GeneratedValue(strategy=GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "nome", nullable = false) public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } @Column(name = "email", nullable = false) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Column(name = "cpf", nullable = false) public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } @Column(name = "valor_hora", nullable = true) public BigDecimal getValorHora() { return valorHora; } @Transient public Optional<BigDecimal> getValorHoraOpt() { return Optional.ofNullable(valorHora); } public void setValorHora(BigDecimal valorHora) { this.valorHora = valorHora; } @Column(name = "qtd_horas_trabalho_dia", nullable = true) public Float getQtdHorasTrabalhoDia() { return qtdHorasTrabalhoDia; } @Transient public Optional<Float> getQtdHorasTrabalhoDiaOpt() { return Optional.ofNullable(qtdHorasTrabalhoDia); } public void setQtdHorasTrabalhoDia(Float qtdHorasTrabalhoDia) { this.qtdHorasTrabalhoDia = qtdHorasTrabalhoDia; } @Column(name = "qtd_horas_almoco", nullable = true) public Float getQtdHorasAlmoco() { return qtdHorasAlmoco; } @Transient public Optional<Float> getQtdHorasAlmocoOpt() { return Optional.ofNullable(qtdHorasAlmoco); } public void setQtdHorasAlmoco(Float qtdHorasAlmoco) { this.qtdHorasAlmoco = qtdHorasAlmoco; } @Enumerated(EnumType.STRING) @Column(name = "perfil", nullable = false) public PerfilEnum getPerfil() { return perfil; } public void setPerfil(PerfilEnum perfil) { this.perfil = perfil; } @Column(name = "data_criacao", nullable = false) public Date getDataCriacao() { return dataCriacao; } public void setDataCriacao(Date dataCriacao) { this.dataCriacao = dataCriacao; } @Column(name = "data_atualizacao", nullable = false) public Date getDataAtualizacao() { return dataAtualizacao; } public void setDataAtualizacao(Date dataAtualizacao) { this.dataAtualizacao = dataAtualizacao; } @Column(name = "senha", nullable = false) public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } @ManyToOne(fetch = FetchType.EAGER) public Empresa getEmpresa() { return empresa; } public void setEmpresa(Empresa empresa) { this.empresa = empresa; } @OneToMany(mappedBy = "funcionario", fetch = FetchType.LAZY, cascade = CascadeType.ALL) public List<Lancamento> getLancamentos() { return lancamentos; } public void setLancamentos(List<Lancamento> lancamentos) { this.lancamentos = lancamentos; } @PreUpdate public void preUpdate() { dataAtualizacao = new Date(); } @PrePersist public void prePersist() { final Date atual = new Date(); dataCriacao = atual; dataAtualizacao = atual; } @Override public String toString() { return "Funcionario [id=" + id + ", nome=" + nome + ", email=" + email + ", senha=" + senha + ", cpf=" + cpf + ", valorHora=" + valorHora + ", qtdHorasTrabalhoDia=" + qtdHorasTrabalhoDia + ", qtdHorasAlmoco=" + qtdHorasAlmoco + ", perfil=" + perfil + ", dataCriacao=" + dataCriacao + ", dataAtualizacao=" + dataAtualizacao + ", empresa=" + empresa + "]"; } }
23.033816
110
0.730076
7fed4d96cb3c0cba88f01aa211a621581fe3bb49
162
@RDFNamespaces("pkg = http://example.com/package-ns#") package org.cyberborean.rdfbeans.test.reflect; import org.cyberborean.rdfbeans.annotations.RDFNamespaces;
32.4
58
0.808642
385801cfca4b9fe1de6d0d9eed3c4d085f4d0a9e
1,616
package net.savantly.sprout.module.content.model.webPage; import java.util.List; import net.savantly.spring.fixture.AbstractBaseFixture; import net.savantly.spring.fixture.Fixture; import net.savantly.sprout.module.content.model.webPageLayout.WebPageLayout; import net.savantly.sprout.module.content.model.webPageLayout.WebPageLayoutFixture; import net.savantly.sprout.module.content.model.webPageLayout.WebPageLayoutRepository; public class WebPageFixture extends AbstractBaseFixture<WebPage, WebPageRepository> { public static final String DEFAULT_WEB_PAGE_NAME = "Default WebPage"; private WebPageRepository repository; private WebPageLayoutFixture webPageLayoutFixture; private WebPageLayoutRepository webPageLayoutRepository; public WebPageFixture(WebPageRepository repository, WebPageLayoutRepository webPageLayoutRepository, WebPageLayoutFixture webPageLayoutFixture) { super(repository); this.repository = repository; this.webPageLayoutRepository = webPageLayoutRepository; this.webPageLayoutFixture = webPageLayoutFixture; } @Override public void addEntities(List<WebPage> entityList) { WebPage page = repository.findOneByName(DEFAULT_WEB_PAGE_NAME); if (page == null) { WebPageLayout layout = webPageLayoutRepository.findOneByName(webPageLayoutFixture.defaultWebPageLayoutName); page = new WebPage(); page.setName(DEFAULT_WEB_PAGE_NAME); page.setWebPageLayout(layout); entityList.add(page); } } @Override public void addDependencies(List<Fixture<?>> dependencies) { dependencies.add(webPageLayoutFixture); } }
36.727273
147
0.803218
ed06204da14c34cab0b0a3fa1684c75e2c33f92c
3,176
public class Heap { private class PriorityQueue { int size; int capacity; int[] elements; public PriorityQueue(int capacity) { this.capacity = capacity; this.size = 0; // elements[0] is a sentinel elements = new int[capacity + 1]; // this is a min heap elements[0] = Integer.MIN_VALUE; } } private PriorityQueue pq; public Heap(int capacity) { this.pq = new PriorityQueue(capacity); } public Heap() { this.pq = new PriorityQueue(128); } public int getLeftChild(int parent) { return pq.elements[parent * 2]; } public int getRightChild(int parent) { return pq.elements[parent * 2 + 1]; } public int getParent(int child) { return pq.elements[child / 2]; } public void insert(int value) { if (pq.size >= pq.capacity) { System.out.println("Reaches the capacity of the heap: should less than " + pq.capacity); return; } pq.size++; int i; for (i = pq.size; pq.elements[i / 2] > value; i = i / 2) { pq.elements[i] = pq.elements[i / 2]; } pq.elements[i] = value; return; } public int deleteMin() { if (pq.size == 0) { System.out.println("Nothing to delete!"); return -1; } int res = pq.elements[1]; // move the last element to the first pq.elements[1] = pq.elements[pq.size]; pq.elements[pq.size] = 0; pq.size--; // re-heapfy heapfy(); return res; } private void heapfy() { int i = 1; int target = pq.elements[1]; while (i <= pq.size / 2) { int left = i * 2; int right = i * 2 + 1; int tmp = left; // we need to exhausitively list all conditions, otherwise, // the routine will fall into infinite loop if (pq.elements[i] < pq.elements[left]) { if (right > pq.size || pq.elements[i] < pq.elements[right]) return; } // && (right <= pq.size && pq.elements[i] < pq.elements[right])) //return; // break; // when comparing among three or more elements, we need to fix // the index of one of them if (pq.elements[i] > pq.elements[left]) { pq.elements[i] = pq.elements[left]; // wrong: // i = left; tmp = left; } if (right <= pq.size && pq.elements[i] > pq.elements[right]) { pq.elements[i] = pq.elements[right]; // wrong: // i = right; tmp = right; } i = tmp; pq.elements[i] = target; } return; } public void print() { for (int i = 1; i <= pq.size; i++) { if (pq.elements[i] == 0) break; System.out.print(pq.elements[i] + " "); } System.out.println(); } public static void main(String[] args) { Heap heap = new Heap(); //int[] a = {2, 1, 3, 4, 10, 9, 8, 7, 5, 6}; int[] a = {11, 12, 20, 14, 16, 13, 2, 1, 3, 4, 10, 9, 8, 7, 5, 6}; for (int i = 0; i < a.length; i++) heap.insert(a[i]); heap.print(); for (int i = 0; i < a.length; i++) { System.out.print(heap.deleteMin() + " "); } //heap.deleteMin(); System.out.println(); //heap.print(); } }
22.685714
78
0.531486
57bf52bfb7774c66a858ee541656fc2796fc89ba
212
package com.sunyi.cloud; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DependenciesApplication { public static void main(String[] args) { } }
19.272727
68
0.787736
473d95b3884ab462292a0cc09dc152a53f89368f
34,623
/* Copyright 2018-2021 WeAreFrank! 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 nl.nn.testtool; import java.beans.Transient; import java.io.Serializable; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import org.apache.commons.lang.NotImplementedException; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.SneakyThrows; import nl.nn.testtool.MessageEncoder.ToStringResult; import nl.nn.testtool.run.ReportRunner; import nl.nn.testtool.storage.Storage; import nl.nn.testtool.transform.MessageTransformer; import nl.nn.testtool.transform.ReportXmlTransformer; import nl.nn.testtool.util.CsvUtil; import nl.nn.testtool.util.EscapeUtil; import nl.nn.testtool.util.XmlUtil; /** * @author Jaco de Groot */ public class Report implements Serializable { // The serialVersionUID only needs to be changed when throwing an exception // on reading an older version needs to be forced. As long as Java is able // to read the older version there's probably no reason to force an // exception. In the case Java isn't able to read the older version it will // throw an exception, hence no reason either to force throwing an // exception. The serialVersionUID also only effects reading objects through // ObjectInputStream, it doesn't effect reading objects through XMLDecoder. private transient static final long serialVersionUID = 5; private transient static Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); protected transient static final long TIME_NOT_SET_VALUE = Long.MIN_VALUE; // Please note that the set method should return void for XmlEncoder to // store the property (hence the setVariableCsvWithoutException method) private long startTime; private long endTime = TIME_NOT_SET_VALUE; private String correlationId; private String name; private String description; private String path; private String stubStrategy; // See Checkpoint also for properties that will be stored by XmlEncoder and // serialization / ObjectOutputStream private List<Checkpoint> checkpoints = new ArrayList<Checkpoint>(); private String transformation; private String variableCsv; // Please note that the get and set methods need @Transient annotation for // XmlEncoder to not store the property. This is in contrast to // serialization / ObjectOutputStream that is using variables (and doesn't // look at get and set methods) and needs a variable to be declared // transient to not store the field. private transient String mainThread; private transient List<String> threads = new ArrayList<String>(); private transient Map<String, Integer> threadCheckpointIndex = new HashMap<String, Integer>(); private transient Map<String, Integer> threadFirstLevel = new HashMap<String, Integer>(); private transient Map<String, Integer> threadLevel = new HashMap<String, Integer>(); private transient Map<String, String> threadParent = new HashMap<String, String>(); private transient int threadsActiveCount = 0; private transient TestTool testTool; private transient boolean closed; private transient Storage storage; private transient Integer storageId; private transient long storageSize; private transient ReportXmlTransformer reportXmlTransformer; private transient ReportXmlTransformer globalReportXmlTransformer; private transient String xml; private transient Report originalReport; private transient boolean differenceChecked = false; private transient boolean differenceFound = false; private transient Map<String, String> truncatedMessageMap = new RefCompareMap<String, String>(); private transient boolean reportFilterMatching = true; private transient boolean logReportFilterMatching = true; private transient boolean logMaxCheckpoints = true; private transient boolean logMaxMemoryUsage = true; private transient Map<Object, Set<Checkpoint>> streamingMessageListeners = new HashMap<Object, Set<Checkpoint>>(); private transient Map<Object, StreamingMessageResult> streamingMessageResults = new HashMap<Object, StreamingMessageResult>(); public Report() { mainThread = Thread.currentThread().getName(); threads.add(mainThread); threadCheckpointIndex.put(mainThread, new Integer(0)); threadFirstLevel.put(mainThread, new Integer(0)); threadLevel.put(mainThread, new Integer(0)); threadsActiveCount++; } @Transient @JsonIgnore public void setTestTool(TestTool testTool) { this.testTool = testTool; } @Transient @JsonIgnore public TestTool getTestTool() { return testTool; } @Transient @JsonIgnore public void setClosed(boolean closed) { this.closed = closed; } @Transient @JsonIgnore public boolean isClosed() { return closed; } @Transient @JsonIgnore public void setStorage(Storage storage) { this.storage = storage; } @Transient @JsonIgnore public Storage getStorage() { return storage; } public void setStorageId(Integer storageId) { this.storageId = storageId; } public Integer getStorageId() { return storageId; } @Transient @JsonIgnore public void setStorageSize(long storageSize) { this.storageSize = storageSize; } @Transient @JsonIgnore public Long getStorageSize() { return storageSize; } public void setStartTime(long startTime) { this.startTime = startTime; } public long getStartTime() { return startTime; } public void setEndTime(long endTime) { this.endTime = endTime; } public long getEndTime() { return endTime; } public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } public String getCorrelationId() { return correlationId; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setPath(String path) { this.path = path; } public String getPath() { return path; } public String getFullPath() { return (StringUtils.isNotEmpty(getPath()) ? getPath() : "/") + getName(); } public void setStubStrategy(String stubStrategy) { this.stubStrategy = stubStrategy; } public String getStubStrategy() { return stubStrategy; } public void setTransformation(String transformation) { this.transformation = transformation; } public String getTransformation() { return transformation; } @Transient @JsonIgnore public void setReportXmlTransformer(ReportXmlTransformer reportXmlTransformer) { this.reportXmlTransformer = reportXmlTransformer; } @Transient @JsonIgnore public ReportXmlTransformer getReportXmlTransformer() { return reportXmlTransformer; } @Transient @JsonIgnore public void setGlobalReportXmlTransformer(ReportXmlTransformer globalReportXmlTransformer) { this.globalReportXmlTransformer = globalReportXmlTransformer; } @Transient @JsonIgnore public ReportXmlTransformer getGlobalReportXmlTransformer() { return globalReportXmlTransformer; } @Transient @JsonIgnore public void setOriginalReport(Report originalReport) { this.originalReport = originalReport; } @Transient public Report getOriginalReport() { return originalReport; } @Transient public void setReportFilterMatching(boolean reportFilterMatching) { this.reportFilterMatching = reportFilterMatching; } @Transient public boolean isReportFilterMatching() { return reportFilterMatching; } protected <T> T checkpoint(String childThreadId, String sourceClassName, String name, T message, StubableCode stubableCode, StubableCodeThrowsException stubableCodeThrowsException, Set<String> matchingStubStrategies, int checkpointType, int levelChangeNextCheckpoint) { String parentThreadName = Thread.currentThread().getName(); if (checkpointType == Checkpoint.TYPE_THREADCREATEPOINT) { if (!threads.contains(parentThreadName)) { log.warn("Unknown parent thread '" + parentThreadName + "' for child thread '" + childThreadId + "' , ignored checkpoint " + getCheckpointLogDescription(name, checkpointType, null)); } else { name = "Waiting for thread '" + childThreadId + "' to start..."; threadCreatepoint(parentThreadName, childThreadId); } } else { if (checkpointType == Checkpoint.TYPE_THREADSTARTPOINT && !threads.contains(childThreadId)) { parentThreadName = threads.get(threads.size() - 1); threadCreatepoint(parentThreadName, childThreadId); log.warn("New child thread '" + childThreadId + "' for parent thread '" + parentThreadName + "' detected, use threadCreatepoint() before threadStartpoint() for checkpoint " + getCheckpointLogDescription(name, checkpointType, null)); } else if (checkpointType == Checkpoint.TYPE_STARTPOINT && !threads.contains(parentThreadName)) { checkpointType = Checkpoint.TYPE_THREADSTARTPOINT; childThreadId = parentThreadName; parentThreadName = threads.get(threads.size() - 1); threadCreatepoint(parentThreadName, childThreadId); log.warn("New child thread '" + childThreadId + "' for parent thread '" + parentThreadName + "' detected, use threadCreatepoint() and threadStartpoint() instead of startpoint() for checkpoint " + getCheckpointLogDescription(name, checkpointType, null)); } } message = addCheckpoint(childThreadId, sourceClassName, name, message, stubableCode, stubableCodeThrowsException, matchingStubStrategies, checkpointType, levelChangeNextCheckpoint); return message; } private void threadCreatepoint(String parentThreadName, String childThreadId) { threads.add(threads.indexOf(parentThreadName), childThreadId); threadCheckpointIndex.put(childThreadId, threadCheckpointIndex.get(parentThreadName)); threadFirstLevel.put(childThreadId, threadLevel.get(parentThreadName)); threadLevel.put(childThreadId, threadLevel.get(parentThreadName)); threadParent.put(childThreadId, parentThreadName); threadsActiveCount++; } /** * For threadCreatepoints a checkpoint is added to the report and removed when a threadStartpoint is added to * visualize the status of waiting for a thread to start. A threadCreatepoint should be visualized as an error as a * thread was expected to start but didn't start. * * @param index * @param threadName */ private void removeThreadCreatepoint(int index, String threadName) { if (index < checkpoints.size() && checkpoints.get(index).getType() == Checkpoint.TYPE_THREADCREATEPOINT) { checkpoints.remove(index); for (int i = threads.indexOf(threadName) + 1; i < threads.size(); i++) { String key = threads.get(i); Integer value = threadCheckpointIndex.get(key); threadCheckpointIndex.put(key, new Integer(value.intValue() - 1)); } } } private <T> T addCheckpoint(String childThreadId, String sourceClassName, String name, T message, StubableCode stubableCode, StubableCodeThrowsException stubableCodeThrowsException, Set<String> matchingStubStrategies, int checkpointType, int levelChangeNextCheckpoint) { String threadName = Thread.currentThread().getName(); Integer index = threadCheckpointIndex.get(threadName); Integer level = threadLevel.get(threadName); if (name == null) { log.warn("Ignored checkpoint with null name " + getCheckpointLogDescription(name, checkpointType, level)); } else { if (checkpointType == Checkpoint.TYPE_THREADSTARTPOINT) { // At this point index will already be != null when name of the child thread was used as childThreadId // when calling threadCreatepoint() if (index == null) { index = threadCheckpointIndex.remove(childThreadId); if (index != null) { // Rename child thread id in the relevant maps to the actual thread name of the child thread (which // at this point is the current thread (calling it's first checkpoint (threadStartpoint())) for as // far as they are not already the same (in which case index will be initialized with a non null // value at the beginning of this method threads.add(threads.indexOf(childThreadId), threadName); threads.remove(childThreadId); threadCheckpointIndex.put(threadName, index); level = threadFirstLevel.remove(childThreadId); threadFirstLevel.put(threadName, level); level = threadLevel.remove(childThreadId); threadLevel.put(threadName, level); String parent = (String)threadParent.remove(childThreadId); threadParent.put(threadName, parent); } else { log.warn("Unknown childThreadId '" + childThreadId + "', use the same childThreadId when calling threadCreatepoint() and threadStartpoint()"); } } if (index != null) { removeThreadCreatepoint(index, threadName); } } if (index == null) { log.warn("Unknown thread, ignored checkpoint " + getCheckpointLogDescription(name, checkpointType, level)); } else { if (!isReportFilterMatching()) { message = TestTool.execute(stubableCode, stubableCodeThrowsException, message); if (logReportFilterMatching) { log.debug("Report name doesn't match report filter regex, ignored checkpoint " + getCheckpointLogDescription(name, checkpointType, level) + " " + getOtherCheckpointsLogDescription()); logReportFilterMatching = false; } } else if (checkpoints.size() >= testTool.getMaxCheckpoints()) { message = TestTool.execute(stubableCode, stubableCodeThrowsException, message); if (logMaxCheckpoints) { log.warn("Maximum number of checkpoints exceeded, ignored checkpoint " + getCheckpointLogDescription(name, checkpointType, level) + " " + getOtherCheckpointsLogDescription()); logMaxCheckpoints = false; } } else if (getEstimatedMemoryUsage() >= testTool.getMaxMemoryUsage()) { message = TestTool.execute(stubableCode, stubableCodeThrowsException, message); if (logMaxMemoryUsage) { log.warn("Maximum memory usage reached for this report, ignored checkpoint " + getCheckpointLogDescription(name, checkpointType, level) + " " + getOtherCheckpointsLogDescription()); logMaxMemoryUsage = false; } } else { message = addCheckpoint(threadName, sourceClassName, name, message, stubableCode, stubableCodeThrowsException, matchingStubStrategies, checkpointType, index, level ); } Integer newLevel = new Integer(level.intValue() + levelChangeNextCheckpoint); threadLevel.put(threadName, newLevel); if (newLevel.equals(threadFirstLevel.get(threadName))) { // threadCreatepoint has already been removed on first checkpoint for thread, hence use false close(threadName, false); } } } return message; } @SneakyThrows private <T> T addCheckpoint(String threadName, String sourceClassName, String name, T message, StubableCode stubableCode, StubableCodeThrowsException stubableCodeThrowsException, Set<String> matchingStubStrategies, int checkpointType, Integer index, Integer level) { Checkpoint checkpoint = new Checkpoint(this, threadName, sourceClassName, name, checkpointType, level.intValue()); boolean stub = false; if (originalReport != null) { Path path = checkpoint.getPath(true); Checkpoint originalCheckpoint = (Checkpoint)originalReport.getCheckpoint(path); if (originalCheckpoint == null) { if (matchingStubStrategies != null) { if (matchingStubStrategies.contains(originalReport.getStubStrategy())) { stub = true; } } else if (testTool.getDebugger() != null) { stub = testTool.stub(checkpoint, originalReport.getStubStrategy()); } } else { checkpoint.setStub(originalCheckpoint.getStub()); if (originalCheckpoint.getStub() == Checkpoint.STUB_FOLLOW_REPORT_STRATEGY) { if (matchingStubStrategies != null) { if (matchingStubStrategies.contains(originalReport.getStubStrategy())) { stub = true; } } else if (testTool.getDebugger() != null) { stub = testTool.stub(originalCheckpoint, originalReport.getStubStrategy()); } } else if (originalCheckpoint.getStub() == Checkpoint.STUB_NO) { stub = false; } else if (originalCheckpoint.getStub() == Checkpoint.STUB_YES) { stub = true; } } if (stub) { checkpoint.setStubbed(true); if (originalCheckpoint == null) { checkpoint.setStubNotFound(path.toString()); } message = getMessageEncoder().toObject(originalCheckpoint, message); message = checkpoint.setMessage(message); } } if (!stub) { try { message = TestTool.execute(stubableCode, stubableCodeThrowsException, message); } catch(Throwable t) { testTool.abortpoint(correlationId, sourceClassName, name, t.getMessage()); throw t; } message = checkpoint.setMessage(message); } for (int i = threads.indexOf(threadName); i < threads.size(); i++) { String key = threads.get(i); Integer value = threadCheckpointIndex.get(key); threadCheckpointIndex.put(key, new Integer(value.intValue() + 1)); } // Add checkpoint to the list after stubable code has been executed. Otherwise when a report in progress is // opened is might give the impression that the stubable code is already executed checkpoints.add(index.intValue(), checkpoint); if (log.isDebugEnabled()) { log.debug("Added checkpoint " + getCheckpointLogDescription(name, checkpointType, level)); } return message; } protected String truncateMessage(Checkpoint checkpoint, String message) { if (testTool.getMaxMessageLength() > -1 && message != null && message.toString().length() > testTool.getMaxMessageLength()) { // For a message that is referenced by multiple checkpoints, have one truncated message that is // referenced by those checkpoints, to prevent creating multiple String objects representing the // same string and occupying unnecessary memory. checkpoint.setPreTruncatedMessageLength(message.length()); if(truncatedMessageMap.containsKey(message)) { return truncatedMessageMap.get(message); } else { String truncatedMessage = message.substring(0, testTool.getMaxMessageLength()); truncatedMessageMap.put(message, truncatedMessage); return truncatedMessage; } } return message; } public Checkpoint getOriginalEndpointOrAbortpointForCurrentLevel() { Checkpoint result = null; if (originalReport != null) { Checkpoint lastCheckpoint = (Checkpoint)checkpoints.get(checkpoints.size() - 1); Checkpoint checkpoint = originalReport.getCheckpoint(lastCheckpoint.getPath()); if (checkpoint != null) { int i = originalReport.checkpoints.indexOf(checkpoint) + 1; while (checkpoint.getType() != Checkpoint.TYPE_ENDPOINT && checkpoint.getType() != Checkpoint.TYPE_ABORTPOINT && i < originalReport.checkpoints.size()) { checkpoint = (Checkpoint)originalReport.checkpoints.get(i); i++; } if (checkpoint.getType() == Checkpoint.TYPE_ENDPOINT || checkpoint.getType() == Checkpoint.TYPE_ABORTPOINT) { result = checkpoint; } } } return result; } protected void close() { while (threads.size() > 0) { close(threads.get(0), false); } } protected void close(String threadName, boolean removeThreadCreatepoint) { if (threads.remove(threadName)) { Integer index = threadCheckpointIndex.remove(threadName); threadFirstLevel.remove(threadName); threadLevel.remove(threadName); threadParent.remove(threadName); threadsActiveCount--; if (removeThreadCreatepoint) { removeThreadCreatepoint(index, threadName); } } else { log.warn("Thread '" + threadName + "' to close for report with correlationId '" + correlationId + "' not found"); } } protected boolean threadsFinished() { return threadsActiveCount < 1; } protected boolean mainThreadFinished() { return !threads.contains(mainThread); } protected boolean streamingMessageListenersFinished() { return streamingMessageListeners.size() < 1; } protected void addStreamingMessageListener(Object streamingMessage, Checkpoint checkpoint) { synchronized(streamingMessageListeners) { Set<Checkpoint> checkpoints = streamingMessageListeners.get(streamingMessage); if (checkpoints == null) { checkpoints = new HashSet<Checkpoint>(); } checkpoints.add(checkpoint); streamingMessageListeners.put(streamingMessage, checkpoints); } } protected void removeStreamingMessageListener(Object streamingMessage, Checkpoint checkpoint) { synchronized(streamingMessageListeners) { Set<Checkpoint> checkpoints = streamingMessageListeners.remove(streamingMessage); if (checkpoints != null) { checkpoints.remove(checkpoint); if (checkpoints.size() > 0) { streamingMessageListeners.put(streamingMessage, checkpoints); } } } } protected void removeStreamingMessageListeners() { synchronized(streamingMessageListeners) { streamingMessageListeners.clear(); } } protected boolean isKnownStreamingMessage(Object streamingMessage) { synchronized(streamingMessageListeners) { return streamingMessageListeners.get(streamingMessage) != null; } } protected void closeStreamingMessage(String messageClassName, Object streamingMessage, String streamingType, String charset, Object message, int preTruncatedMessageLength, Throwable exception) { StreamingMessageResult streamingMessageResult = new StreamingMessageResult(); streamingMessageResult.setMessageClassName(messageClassName); streamingMessageResult.setStreamingType(streamingType); streamingMessageResult.setCharset(charset); streamingMessageResult.setMessage(message); streamingMessageResult.setPreTruncatedMessageLength(preTruncatedMessageLength); streamingMessageResult.setException(exception); synchronized(streamingMessageListeners) { // Check whether TestTool.close() already closed the message capturer if (streamingMessageListeners.containsKey(streamingMessage)) { streamingMessageResults.put(streamingMessage, streamingMessageResult); } closeStreamingMessageListeners(); } getTestTool().closeReportIfFinished(this); } /** * Close all streaming message listeners for which the streaming message has been closed */ private void closeStreamingMessageListeners() { synchronized(streamingMessageListeners) { Set<Object> finishedStreamingMessage = new HashSet<Object>(); for (Object streamingMessage : streamingMessageListeners.keySet()) { StreamingMessageResult streamingMessageResult = streamingMessageResults.remove(streamingMessage); if (streamingMessageResult != null) { finishedStreamingMessage.add(streamingMessage); for (Checkpoint checkpoint : streamingMessageListeners.get(streamingMessage)) { checkpoint.setWaitingForStream(false); checkpoint.setStreaming(streamingMessageResult.getStreamingType()); if (streamingMessageResult.getException() != null) { checkpoint.setMessage(streamingMessageResult.getException()); } else { Object message = streamingMessageResult.getMessage(); String charset = streamingMessageResult.getCharset(); ToStringResult toStringResult = getMessageEncoder().toString(message, charset); checkpoint.setMessage(toStringResult.getString()); checkpoint.setEncoding(toStringResult.getEncoding()); checkpoint.setMessageClassName(streamingMessageResult.getMessageClassName()); checkpoint.setPreTruncatedMessageLength(streamingMessageResult.getPreTruncatedMessageLength()); } } } } for (Object streamingMessage: finishedStreamingMessage) { streamingMessageListeners.remove(streamingMessage); } } } public Checkpoint getCheckpoint(Path path) { Checkpoint result = null; Iterator<Checkpoint> iterator = checkpoints.iterator(); while (result == null && iterator.hasNext()) { Checkpoint checkpoint = (Checkpoint)iterator.next(); if (path.equals(checkpoint.getPath())) { result = checkpoint; } } return result; } public void setCheckpoints(List<Checkpoint> checkpoints) { this.checkpoints = checkpoints; } public List<Checkpoint> getCheckpoints() { return checkpoints; } public Checkpoint getInputCheckpoint() { return checkpoints.get(0); } public int getNumberOfCheckpoints() { return checkpoints.size(); } public long getEstimatedMemoryUsage() { long estimatedMemoryUsage = 0L; for (Checkpoint checkpoint : checkpoints) { estimatedMemoryUsage += checkpoint.getEstimatedMemoryUsage(); } return estimatedMemoryUsage; } @Transient @JsonIgnore public void setDifferenceChecked(boolean differenceChecked) { this.differenceChecked = differenceChecked; } @Transient @JsonIgnore public boolean isDifferenceChecked() { return differenceChecked; } @Transient @JsonIgnore public void setDifferenceFound(boolean differenceFound) { this.differenceFound = differenceFound; } @Transient @JsonIgnore public boolean isDifferenceFound() { return differenceFound; } @Transient @JsonIgnore public MessageTransformer getMessageTransformer() { return testTool.getMessageTransformer(); } @Transient @JsonIgnore public MessageEncoder getMessageEncoder() { return testTool.getMessageEncoder(); } @Transient @JsonIgnore public MessageCapturer getMessageCapturer() { return testTool.getMessageCapturer(); } public Object clone() throws CloneNotSupportedException { Report report = new Report(); report.setTestTool(testTool); report.setStartTime(startTime); report.setEndTime(endTime); report.setCorrelationId(correlationId); report.setName(name); report.setDescription(description); report.setPath(path); report.setStubStrategy(stubStrategy); report.setTransformation(transformation); report.setVariableCsv(variableCsv); List<Checkpoint> checkpoints = new ArrayList<Checkpoint>(); for (Checkpoint checkpoint : this.checkpoints) { checkpoint = (Checkpoint)checkpoint.clone(); checkpoint.setReport(report); checkpoints.add(checkpoint); } report.setCheckpoints(checkpoints); return report; } public String toString() { return name; } public String toXml() { return toXml(null); } public String toXml(ReportRunner reportRunner) { if (xml == null) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("<Report"); stringBuffer.append(" Name=\"" + EscapeUtil.escapeXml(name) + "\""); stringBuffer.append(" Description=\"" + EscapeUtil.escapeXml(description) + "\""); stringBuffer.append(" Path=\"" + EscapeUtil.escapeXml(path) + "\""); stringBuffer.append(" CorrelationId=\"" + EscapeUtil.escapeXml(correlationId) + "\""); stringBuffer.append(" StartTime=\"" + startTime + "\""); stringBuffer.append(" EndTime=\"" + endTime + "\""); stringBuffer.append(" NumberOfCheckpoints=\"" + getNumberOfCheckpoints() + "\""); stringBuffer.append(" EstimatedMemoryUsage=\"" + getEstimatedMemoryUsage() + "\""); stringBuffer.append(">"); for (Checkpoint checkpoint : checkpoints) { String message; if(reportRunner != null && checkpoint.containsVariables()) { message = checkpoint.getMessageWithResolvedVariables(reportRunner); } else { message = checkpoint.getMessage(); } stringBuffer.append("<Checkpoint"); stringBuffer.append(" Name=\"" + EscapeUtil.escapeXml(checkpoint.getName()) + "\""); stringBuffer.append(" Type=\"" + EscapeUtil.escapeXml(checkpoint.getTypeAsString()) + "\""); stringBuffer.append(" Level=\"" + checkpoint.getLevel() + "\""); if (checkpoint.getSourceClassName() != null) { stringBuffer.append(" SourceClassName=\"" + EscapeUtil.escapeXml(checkpoint.getSourceClassName()) + "\""); } if (checkpoint.getMessageClassName() != null) { stringBuffer.append(" MessageClassName=\"" + EscapeUtil.escapeXml(checkpoint.getMessageClassName()) + "\""); } if (checkpoint.getPreTruncatedMessageLength() != -1) { stringBuffer.append(" PreTruncatedMessageLength=\"" + checkpoint.getPreTruncatedMessageLength() + "\""); } if (checkpoint.getEncoding() != null) { stringBuffer.append(" Encoding=\"" + EscapeUtil.escapeXml(checkpoint.getEncoding()) + "\""); } if (checkpoint.getStreaming() != null) { stringBuffer.append(" Streaming=\"" + EscapeUtil.escapeXml(checkpoint.getStreaming()) + "\""); } if (checkpoint.isWaitingForStream()) { stringBuffer.append(" WaitingForStream=\"" + checkpoint.isWaitingForStream() + "\""); } if (checkpoint.getStub() != Checkpoint.STUB_FOLLOW_REPORT_STRATEGY) { stringBuffer.append(" Stub=\"" + checkpoint.getStub() + "\""); } if (checkpoint.isStubbed()) { stringBuffer.append(" Stubbed=\"" + checkpoint.isStubbed() + "\""); } if (checkpoint.getStubNotFound() != null) { stringBuffer.append(" StubNotFound=\"" + checkpoint.getStubNotFound() + "\""); } if (message == null) { stringBuffer.append(" Null=\"true\"/>"); } else { if (XmlUtil.isXml(message)) { String textDecl = null; if (message.startsWith("<?")) { int i = message.indexOf("?>") + 2; textDecl = message.substring(0, i); stringBuffer.append(" TextDecl=\""); stringBuffer.append(EscapeUtil.escapeXml(textDecl)); stringBuffer.append("\">"); message = message.substring(i); } else { stringBuffer.append(">"); } stringBuffer.append(message); } else { stringBuffer.append(">"); stringBuffer.append(EscapeUtil.escapeXml(message)); } stringBuffer.append("</Checkpoint>"); } } stringBuffer.append("</Report>"); xml = stringBuffer.toString(); if (reportXmlTransformer != null || (transformation != null && transformation.trim().length() > 0)) { if (reportXmlTransformer == null) { reportXmlTransformer = new ReportXmlTransformer(); reportXmlTransformer.setXslt(transformation); } xml = reportXmlTransformer.transform(xml); } else if (globalReportXmlTransformer != null) { xml = globalReportXmlTransformer.transform(xml); } } return xml; } public void flushCachedXml() { reportXmlTransformer = null; xml = null; } private String getCheckpointLogDescription(String name, int type, Integer level) { return "(name: " + name + ", type: " + Checkpoint.getTypeAsString(type) + ", level: " + level + ", correlationId: " + correlationId + ")"; } private String getOtherCheckpointsLogDescription() { return "(next checkpoints for this report will be ignored without any logging)"; } public String getVariableCsv() { return variableCsv; } // XMLEncoder requires a void setter function. public void setVariableCsv(String variableCsv) { if (StringUtils.isEmpty(variableCsv)) { this.variableCsv = null; return; } String errorMessage = CsvUtil.validateCsv(variableCsv, ";", 2); if (errorMessage != null) { throw new IllegalArgumentException(errorMessage); } this.variableCsv = variableCsv; } public String setVariableCsvWithoutException(String variableCsv) { try { setVariableCsv(variableCsv); return null; } catch (IllegalArgumentException e) { return e.getMessage(); } } public Map<String, String> getVariablesAsMap() { if(StringUtils.isEmpty(variableCsv)) { return null; } Map<String, String> variableMap = new LinkedHashMap<String, String>(); Scanner scanner = new Scanner(variableCsv); List<String> lines = new ArrayList<String>(); while(scanner.hasNextLine()) { String nextLine = scanner.nextLine(); if(StringUtils.isNotEmpty(nextLine) && !nextLine.startsWith("#")) { lines.add(nextLine); } } scanner.close(); List<String> params = Arrays.asList(lines.get(0).split(";")); for(String key : params) { String value = lines.get(1).split(";")[params.indexOf(key)]; variableMap.put(key, value); } return variableMap; } } /** * A custom implementation of the map interface that compares keys based on their object reference, i.e. comparing with 'o1 == o2' rather than 'o1.equals(o2)'. * This greatly enhances the performance of maps with large objects as keys. * <p> * Note: Since this implementation was written with a specific use case in mind, most methods are not implemented and will throw an exception when called. */ class RefCompareMap<K, V> implements Map<K, V> { private List<K> keys = new ArrayList<K>(); private List<V> values = new ArrayList<V>(); @Override public V get(Object key) { int i = 0; for(Object o : keys) { if(o == key) { return values.get(i); } i++; } return null; } @Override public V put(K key, V value) { keys.add(key); values.add(value); return value; } @Override public boolean containsKey(Object key) { for(Object o : keys) { if(o == key) { return true; } } return false; } @Override public void clear() { throw new NotImplementedException(); } @Override public boolean containsValue(Object value) { throw new NotImplementedException(); } @Override public Set<Map.Entry<K,V>> entrySet() { throw new NotImplementedException(); } @Override public boolean isEmpty() { throw new NotImplementedException(); } @Override public Set<K> keySet() { throw new NotImplementedException(); } @Override public void putAll(Map<? extends K,? extends V> m) { throw new NotImplementedException(); } @Override public V remove(Object key) { throw new NotImplementedException(); } @Override public int size() { throw new NotImplementedException(); } @Override public Collection<V> values() { throw new NotImplementedException(); } } @Data class StreamingMessageResult { String messageClassName; String streamingType; String charset; Object message; int preTruncatedMessageLength; Throwable exception; }
34.178677
159
0.733414
eeee8504b6d860d0f815caadc2e40c550ccaed6f
486
package org.theospi.portfolio.tagging.api; import java.util.List; import java.util.Set; import org.sakaiproject.taggable.api.TaggableItem; public interface DecoratedTaggableItem { public String getTypeName(); public void setTypeName(String typeName); public Set<TaggableItem> getTaggableItems(); public List<TaggableItem> getSortedTaggableItems(); public void setTaggableItems(Set<TaggableItem> taggableItems); public void addTaggableItem(TaggableItem taggableItem); }
22.090909
63
0.808642
0312e184d76c2cf306b9f20d78d162b6b9e7d9d8
1,876
package com.joker17.redundant.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 存放属性所对应的值 */ public class ChangedVo { private Map<String, Object> beforeValMap = new HashMap<String, Object>(); private Map<String, Object> currentValMap = new HashMap<String, Object>(); private List<String> changedPropertys = new ArrayList<String>(); private Object current; private Object before; private String primaryId; private Object primaryIdVal; public Object getCurrent() { return current; } public void setCurrent(Object current) { this.current = current; } public Object getBefore() { return before; } public void setBefore(Object before) { this.before = before; } public String getPrimaryId() { return primaryId; } public void setPrimaryId(String primaryId) { this.primaryId = primaryId; } public Object getPrimaryIdVal() { return primaryIdVal; } public void setPrimaryIdVal(Object primaryIdVal) { this.primaryIdVal = primaryIdVal; } public void addChangedProperty(String property) { changedPropertys.add(property); } public void setVal(String property, Object currentVal, Object beforeVal) { currentValMap.put(property, currentVal); beforeValMap.put(property, beforeVal); } public Object getBeforeVal(String property) { return beforeValMap.get(property); } public Object getCurrentVal(String property) { if (!currentValMap.containsKey(property)) throw new IllegalArgumentException("has no key " + property + " val"); return currentValMap.get(property); } //获取属性值改变的属性列表 public List<String> getChangedPropertys() { return changedPropertys; } }
23.45
120
0.668977
1f21c3c9c31a7a4c0add62c370e0028d006770f2
3,956
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Name: Pritish Wadhwa * * RollNumber: 2019440 * * Section: A * * Stream: CSE * * Topic: Assignment 2 * * SubTopic: Main Class For Assignment 2 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package AP_Assignment2; import java.util.Map; import java.util.Scanner; public class Assignment2_Main { static Scanner input = new Scanner(System.in); public static void main(String[] args) { Zotato handler = new Zotato(); addRestaurants(handler); addCustomers(handler); int choice = 0; do { showHomeScreen(); choice = input.nextInt(); if (choice == 1) { addressQuery1(handler); } else if (choice == 2) { addressQuery2(handler); } else if (choice == 3) { addressQuery3(handler); } else if (choice == 4) { addressQuery4(handler); } } while (choice != 5); input.close(); } public static void addRestaurants(Zotato handler) { Restaurant rest1 = new AuthenticRestaurants("Shah (Authentic)", "Rohini, Delhi"); handler.addRestaurant(rest1.getId(), rest1); Restaurant rest2 = new NormalRestaurants("Ravi's", "IIITD, Delhi"); handler.addRestaurant(rest2.getId(), rest2); Restaurant rest3 = new AuthenticRestaurants("The Chinese (Authentic)", "Chinatown, Delhi"); handler.addRestaurant(rest3.getId(), rest3); Restaurant rest4 = new FastFoodRestaurants("Wang's (Fast Food)", "New York Sanctum, Delhi"); handler.addRestaurant(rest4.getId(), rest4); Restaurant rest5 = new NormalRestaurants("Paradise", "Heaven, Delhi"); handler.addRestaurant(rest5.getId(), rest5); } public static void addCustomers(Zotato handler) { Customer cust1 = new EliteCustomers("Ram (Elite)", "Ayodhya, Delhi"); handler.addCustomer(cust1.getId(), cust1); Customer cust2 = new EliteCustomers("Sam (Elite)", "London, Delhi"); handler.addCustomer(cust2.getId(), cust2); Customer cust3 = new SpecialCustomers("Tim (Special)", "Cape Town, Delhi"); handler.addCustomer(cust3.getId(), cust3); Customer cust4 = new NormalCustomers("Kim", "North Korea, Delhi"); handler.addCustomer(cust4.getId(), cust4); Customer cust5 = new NormalCustomers("Jim", "Scranton, Delhi"); handler.addCustomer(cust5.getId(), cust5); } public static void showHomeScreen() { System.out.println("Welcome to Zotato:"); System.out.println("\t1) Enter as Restaurant Owner"); System.out.println("\t2) Enter as Customer"); System.out.println("\t3) Check User Details"); System.out.println("\t4) Company Account Details"); System.out.println("\t5) Exit"); } public static void showQuery3FirstScreen() { System.out.println("\t1) Customer List"); System.out.println("\t2) Restaurant List"); } public static void addressQuery1(Zotato handler) { handler.showRestaurants(); int choice = input.nextInt(); handler.controlRestaurant(choice); } public static void addressQuery2(Zotato handler) { handler.showCustomers(); int choice = input.nextInt(); handler.controlCustomer(choice); } public static void addressQuery3(Zotato handler) { showQuery3FirstScreen(); int choice1 = input.nextInt(); if (choice1 == 1) { handler.showCustomers(); int choice2 = input.nextInt(); Map<Integer, Customer> customers = handler.getCustList(); Customer cust = customers.get(choice2); cust.printDetails(); } else if (choice1 == 2) { handler.showRestaurants(); int choice2 = input.nextInt(); Map<Integer, Restaurant> rests = handler.getRestList(); Restaurant rest = rests.get(choice2); rest.printDetails(); } } public static void addressQuery4(Zotato handler) { System.out.println("Total Company Balance - INR " + handler.getCompanyBalance() + "/-"); System.out.println("Total Delivery Charges Collected - INR " + handler.getDeliveryCharges() + "/-"); } }
34.103448
102
0.655207
ef71a37864f884dd44971fc28b829bd6ad7b718d
8,532
package com.xjeffrose.xio.http; import static io.netty.handler.codec.http.HttpMethod.*; import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpVersion.*; import com.google.common.util.concurrent.Uninterruptibles; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.LastHttpContent; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @Slf4j public class Http1ClientCodecUnitTest extends Assert { EmbeddedChannel channel = new EmbeddedChannel(); List<HttpObject> requests = new ArrayList<>(); List<Response> responses = new ArrayList<>(); CountDownLatch outputReceived; @Before public void setUp() { channel .pipeline() .addLast( "nextRequest", new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { log.debug("request: " + msg); requests.add((HttpObject) msg); outputReceived.countDown(); } }); channel.pipeline().addLast("handler", new Http1ClientCodec()); channel .pipeline() .addLast( "nextResponse", new SimpleChannelInboundHandler<Response>() { @Override protected void channelRead0(ChannelHandlerContext ctx, Response msg) { log.debug("response: " + msg); responses.add(msg); outputReceived.countDown(); } }); } @Test public void testFullRequest() throws Exception { outputReceived = new CountDownLatch(1); FullRequest requestIn = RequestBuilders.newGet("/").build(); channel.writeOutbound(requestIn); channel.runPendingTasks(); // blocks Uninterruptibles.awaitUninterruptibly(outputReceived); FullHttpRequest requestOut = (FullHttpRequest) requests.remove(0); assertTrue(requestOut != null); assertEquals(HTTP_1_1, requestOut.protocolVersion()); assertEquals(HttpMethod.GET, requestOut.method()); assertEquals("/", requestOut.uri()); assertFalse(requestOut.content() == null); assertEquals(0, requestOut.content().readableBytes()); } @Test public void testFullRequestWithBody() throws Exception { outputReceived = new CountDownLatch(1); ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body"); FullRequest requestIn = RequestBuilders.newPost("/").body(body).build(); channel.writeOutbound(requestIn); channel.runPendingTasks(); // blocks Uninterruptibles.awaitUninterruptibly(outputReceived); FullHttpRequest requestOut = (FullHttpRequest) requests.remove(0); assertTrue(requestOut != null); assertEquals(HTTP_1_1, requestOut.protocolVersion()); assertEquals(HttpMethod.POST, requestOut.method()); assertEquals("/", requestOut.uri()); assertFalse(requestOut.content() == null); assertEquals(body, requestOut.content()); } @Test public void testStreamingRequest() throws Exception { outputReceived = new CountDownLatch(3); SegmentedRequest requestIn = DefaultSegmentedRequest.builder() .method(POST) .path("/") .headers(new DefaultHeaders()) .build(); ByteBuf body1 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body1"); SegmentedData content = DefaultSegmentedData.builder().content(body1).endOfMessage(false).build(); ByteBuf body2 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body2"); SegmentedData lastContent = DefaultSegmentedData.builder() .content(body2) .endOfMessage(true) .trailingHeaders(new DefaultHeaders()) .build(); channel.writeOutbound(requestIn); channel.writeOutbound(content); channel.writeOutbound(lastContent); channel.runPendingTasks(); // blocks Uninterruptibles.awaitUninterruptibly(outputReceived); HttpRequest requestOut = (HttpRequest) requests.remove(0); assertTrue(requestOut != null); assertEquals(HTTP_1_1, requestOut.protocolVersion()); assertEquals(HttpMethod.POST, requestOut.method()); assertEquals("/", requestOut.uri()); HttpContent bodyOut1 = (HttpContent) requests.remove(0); assertTrue(bodyOut1 != null); assertFalse(bodyOut1.content() == null); assertEquals(body1, bodyOut1.content()); HttpContent bodyOut2 = (HttpContent) requests.remove(0); assertTrue(bodyOut2 != null); assertFalse(bodyOut2.content() == null); assertEquals(body2, bodyOut2.content()); } @Test public void testFullResponse() throws Exception { outputReceived = new CountDownLatch(1); ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "response"); FullHttpResponse responseIn = new DefaultFullHttpResponse(HTTP_1_1, OK, body); channel.writeInbound(responseIn); channel.runPendingTasks(); // blocks Uninterruptibles.awaitUninterruptibly(outputReceived); Response responseOut = responses.remove(0); assertTrue(responseOut != null); assertTrue(responseOut instanceof FullResponse); assertEquals("HTTP/1.1", responseOut.version()); assertEquals(OK, responseOut.status()); assertTrue(responseOut.hasBody()); assertFalse(responseOut.body() == null); assertEquals(body, responseOut.body()); } @Test public void testStreamingResponse() throws Exception { outputReceived = new CountDownLatch(3); HttpResponse responseIn = new DefaultHttpResponse(HTTP_1_1, OK); ByteBuf body1 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body1"); HttpContent content = new DefaultHttpContent(body1); ByteBuf body2 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body2"); LastHttpContent lastContent = new DefaultLastHttpContent(body2); channel.writeInbound(responseIn); channel.writeInbound(content); channel.writeInbound(lastContent); channel.runPendingTasks(); // blocks Uninterruptibles.awaitUninterruptibly(outputReceived); SegmentedResponse responseOut = (SegmentedResponse) responses.remove(0); assertTrue(responseOut != null); assertEquals("HTTP/1.1", responseOut.version()); assertEquals(HttpResponseStatus.OK, responseOut.status()); assertFalse(responseOut.hasBody()); assertFalse(responseOut.body() == null); assertEquals(0, responseOut.body().readableBytes()); SegmentedResponseData bodyOut1 = (SegmentedResponseData) responses.remove(0); assertTrue(bodyOut1 != null); assertEquals("HTTP/1.1", responseOut.version()); assertEquals(HttpResponseStatus.OK, responseOut.status()); assertFalse(bodyOut1.hasBody()); assertFalse(bodyOut1.body() == null); assertFalse(bodyOut1.content() == null); assertEquals(body1, bodyOut1.content()); assertFalse(bodyOut1.endOfMessage()); SegmentedResponseData bodyOut2 = (SegmentedResponseData) responses.remove(0); assertTrue(bodyOut2 != null); assertEquals("HTTP/1.1", responseOut.version()); assertEquals(HttpResponseStatus.OK, responseOut.status()); assertFalse(bodyOut2.hasBody()); assertFalse(bodyOut2.body() == null); assertFalse(bodyOut2.content() == null); assertEquals(body2, bodyOut2.content()); assertTrue(bodyOut2.endOfMessage()); } }
35.55
96
0.719526
3ae4b527fc7251e987d09b2f922c3d39f6155edd
2,048
package es.urjc.LDMpiratas.juego; /** * Created by liliana.santacruz on 14/11/2016. */ import es.urjc.LDMpiratas.liliana.core.FileIO; import java.io.*; public class Configuraciones { public static boolean sonidoHabilitado = true; public static int[] maxPuntuaciones = new int[]{100, 80, 50, 30, 10}; public static void cargar(FileIO files) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader( files.leerArchivo(".piratas"))); sonidoHabilitado = Boolean.parseBoolean(in.readLine()); for (int i = 0; i < 5; i++) { maxPuntuaciones[i] = Integer.parseInt(in.readLine()); } } catch (IOException e) { // :( Está bien aquí debería ir algo } catch (NumberFormatException e) { // :/ Nadie es perfecto } finally { try { if (in != null) in.close(); } catch (IOException e) { } } } public static void save(FileIO files) { BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter( files.escribirArchivo(".piratas"))); out.write(Boolean.toString(sonidoHabilitado)); out.write("\n"); for (int i = 0; i < 5; i++) { out.write(Integer.toString(maxPuntuaciones[i])); out.write("\n"); } } catch (IOException e) { } finally { try { if (out != null) out.close(); } catch (IOException e) { } } } public static void addScore(int score) { for (int i = 0; i < 5; i++) { if (maxPuntuaciones[i] < score) { for (int j = 4; j > i; j--) maxPuntuaciones[j] = maxPuntuaciones[j - 1]; maxPuntuaciones[i] = score; break; } } } }
28.84507
73
0.485352
d769925d3168cc7331054692e7eafaeb36eb3641
216
@ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault package com.jozufozu.flywheel.backend.state; import javax.annotation.ParametersAreNonnullByDefault; import net.minecraft.MethodsReturnNonnullByDefault;
30.857143
61
0.893519
7c6ebcfab7a957ff29529d2ee34da180fa5c05ef
8,104
/*Domain class of table m_prj_notifications*/ package com.airback.module.project.domain; import com.airback.core.arguments.ValuedBean; import com.airback.db.metadata.Column; import com.airback.db.metadata.Table; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.ibatis.type.Alias; import org.hibernate.validator.constraints.Length; @SuppressWarnings("ucd") @Table("m_prj_notifications") @Alias("ProjectNotificationSetting") public class ProjectNotificationSetting extends ValuedBean { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column m_prj_notifications.id * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ @Column("id") private Integer id; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column m_prj_notifications.username * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ @NotEmpty @Length(max=45, message="Field value is too long") @Column("username") private String username; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column m_prj_notifications.projectId * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ @NotNull @Column("projectId") private Integer projectid; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column m_prj_notifications.sAccountId * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ @NotNull @Column("sAccountId") private Integer saccountid; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column m_prj_notifications.level * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ @NotEmpty @Length(max=45, message="Field value is too long") @Column("level") private String level; private static final long serialVersionUID = 1; public final boolean equals(Object obj) { if (obj == null) { return false;} if (obj == this) { return true;} if (!obj.getClass().isAssignableFrom(getClass())) { return false;} ProjectNotificationSetting item = (ProjectNotificationSetting)obj; return new EqualsBuilder().append(id, item.id).build(); } public final int hashCode() { return new HashCodeBuilder(1745, 97).append(id).build(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_prj_notifications.id * * @return the value of m_prj_notifications.id * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_notifications * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public ProjectNotificationSetting withId(Integer id) { this.setId(id); return this; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_prj_notifications.id * * @param id the value for m_prj_notifications.id * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_prj_notifications.username * * @return the value of m_prj_notifications.username * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public String getUsername() { return username; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_notifications * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public ProjectNotificationSetting withUsername(String username) { this.setUsername(username); return this; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_prj_notifications.username * * @param username the value for m_prj_notifications.username * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public void setUsername(String username) { this.username = username; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_prj_notifications.projectId * * @return the value of m_prj_notifications.projectId * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public Integer getProjectid() { return projectid; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_notifications * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public ProjectNotificationSetting withProjectid(Integer projectid) { this.setProjectid(projectid); return this; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_prj_notifications.projectId * * @param projectid the value for m_prj_notifications.projectId * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public void setProjectid(Integer projectid) { this.projectid = projectid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_prj_notifications.sAccountId * * @return the value of m_prj_notifications.sAccountId * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public Integer getSaccountid() { return saccountid; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_notifications * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public ProjectNotificationSetting withSaccountid(Integer saccountid) { this.setSaccountid(saccountid); return this; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_prj_notifications.sAccountId * * @param saccountid the value for m_prj_notifications.sAccountId * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public void setSaccountid(Integer saccountid) { this.saccountid = saccountid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_prj_notifications.level * * @return the value of m_prj_notifications.level * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public String getLevel() { return level; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_notifications * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public ProjectNotificationSetting withLevel(String level) { this.setLevel(level); return this; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_prj_notifications.level * * @param level the value for m_prj_notifications.level * * @mbg.generated Fri Apr 12 22:39:46 CDT 2019 */ public void setLevel(String level) { this.level = level; } public enum Field { id, username, projectid, saccountid, level; public boolean equalTo(Object value) { return name().equals(value); } } }
29.576642
90
0.655849
dd5896e4f20c63062a6e89da9e65b047b743840e
3,343
/* * Copyright 2019-2021 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vividus.reportportal.jbehave; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.function.Consumer; import com.epam.reportportal.jbehave.ReportPortalStoryReporter; import com.epam.reportportal.listeners.LogLevel; import com.epam.reportportal.service.ReportPortal; import com.epam.reportportal.service.tree.TestItemTree.TestItemLeaf; import com.epam.ta.reportportal.ws.model.log.SaveLogRQ; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import org.apache.commons.lang3.exception.ExceptionUtils; import org.jbehave.core.model.Scenario; import org.jbehave.core.model.Step; import org.jbehave.core.reporters.DelegatingStoryReporter; import org.jbehave.core.steps.Timing; import org.vividus.softassert.event.AssertionFailedEvent; public class AdaptedDelegatingReportPortalStoryReporter extends DelegatingStoryReporter { private final ReportPortalStoryReporter reporter; private final List<TestItemLeaf> failedSteps = new ArrayList<>(); public AdaptedDelegatingReportPortalStoryReporter(EventBus eventBus, ReportPortalStoryReporter reporter) { super(reporter); this.reporter = reporter; eventBus.register(this); } @Override public void beforeStep(Step step) { runIfNotSystem(step.getStepAsString(), reporter::beforeStep); } @Override public void successful(String step) { reporter.getLastStep() .map(failedSteps::remove) .filter(Boolean.TRUE::equals) .ifPresentOrElse(e -> reporter.failed(step, null), () -> runIfNotSystem(step, reporter::successful)); } private void runIfNotSystem(String step, Consumer<String> toRun) { if (!step.contains("afterStories")) { toRun.accept(step); } } @Override public void afterScenario(Timing timing) { reporter.afterScenario(); } @Override public void scenarioExcluded(Scenario scenario, String filter) { reporter.scenarioNotAllowed(scenario, filter); } @Subscribe public void onAssertionFailure(AssertionFailedEvent event) { reporter.getLastStep().ifPresent(s -> { failedSteps.add(s); ReportPortal.emitLog(s.getItemId(), itemUuid -> { SaveLogRQ rq = new SaveLogRQ(); rq.setItemUuid(itemUuid); rq.setLevel(LogLevel.ERROR.name()); rq.setLogTime(new Date()); rq.setMessage(ExceptionUtils.getStackTrace(event.getSoftAssertionError().getError())); return rq; }); }); } }
32.456311
108
0.693987
72aa6dbc166c29adf45abadbd99638de0ec569cd
1,976
package com.example.root.amtab.database; import android.provider.BaseColumns; /** * Created by root on 29/10/16. */ public final class EntryContract { private EntryContract() {} /* Inner class that defines the table contents */ public static class BusStopEntry implements BaseColumns { public static final String TABLE_NAME = "FERMATE"; public static final String COLUMN_NAME_ID = "ID"; public static final String COLUMN_NAME_DETAILS = "DETTAGLI"; public static final String COLUMN_NAME_LONGITUDE = "LONGITUDINE"; public static final String COLUMN_NAME_LATITUDE = "LATITUDINE"; public static final String COLUMN_NAME_FAVORITE = "PREFERITO"; } public static class LineEntry implements BaseColumns { public static final String TABLE_NAME = "LINEE"; public static final String COLUMN_NAME_ID = "ID"; public static final String COLUMN_NAME_DETAILS = "DETTAGLI"; } public static class BusStopOfLineEntry implements BaseColumns { public static final String TABLE_NAME = "FERMATE_DI_LINEA"; public static final String COLUMN_NAME_LINE_ID = "ID_LINEA"; public static final String COLUMN_NAME_BUSSTOP_ID = "ID_FERMATA"; public static final String COLUMN_NAME_PROGRESSIVE = "PROGRESSIVO"; public static final String COLUMN_NAME_DIRECTION = "DIREZIONE"; } public static class DailyServiceEntry implements BaseColumns{ public static final String TABLE_NAME_PRE = "SERVIZIO_GIORNALIERO_"; public static final String COLUMN_NAME_LINE_ID = "ID_LINEA"; public static final String COLUMN_NAME_BUSSTOP_ID = "ID_FERMATA"; public static final String COLUMN_NAME_ROAD_ID = "ID_CORSA"; public static final String COLUMN_NAME_TIME = "ORARIO"; public static final String COLUMN_NAME_PROGRESSIVE = "PROGRESSIVO"; public static final String COLUMN_NAME_DIRECTION = "DIREZIONE"; } }
40.326531
76
0.723178
3dcfa542d231237b7e66c1cc82703a7a436f3c33
1,303
package com.example.demo.doa; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jndi.JndiTemplate; import org.springframework.stereotype.Repository; import com.example.demo.bean.UserInfo; @Repository public class UserDao { private JdbcTemplate jdbcTemplate; @Autowired public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public UserInfo getUserInfo(String userName) { String sql = "SELECT u.username name, u.password pass, a.authority role FROM " + "comp_users u INNER JOIN comp_authorities a on u.username=a.username WHERE " + "u.enabled =1 and u.username = ?"; UserInfo user = jdbcTemplate.queryForObject(sql, new Object[] { userName }, new RowMapper<UserInfo>() { @Override public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException { UserInfo info = new UserInfo(); info.setPassword(rs.getString("pass")); info.setUsername("name"); info.setRole(rs.getString("role")); return info; } }); return user; } }
28.326087
106
0.726017
e0bc0d99fc85833b94ac70460594f6cc183c7d7f
933
package com.revolsys.gis.parallel; import com.revolsys.parallel.channel.Channel; import com.revolsys.parallel.process.BaseInOutProcess; import com.revolsys.record.Record; import com.revolsys.util.count.LabelCountMap; import com.revolsys.util.count.LabelCounters; public class StatisticsProcess extends BaseInOutProcess<Record, Record> { private LabelCounters labelCountMap; @Override protected void postRun(final Channel<Record> in, final Channel<Record> out) { if (this.labelCountMap != null) { this.labelCountMap.disconnect(); } } @Override protected void preRun(final Channel<Record> in, final Channel<Record> out) { this.labelCountMap = new LabelCountMap(getBeanName()); this.labelCountMap.connect(); } @Override protected void process(final Channel<Record> in, final Channel<Record> out, final Record object) { this.labelCountMap.addCount(object); out.write(object); } }
28.272727
100
0.755627
1f0a0f0b195c128bee35bc23f0216b55e5bfd69f
51
package a.a.a; public final class g extends q { }
10.2
32
0.686275
508375028cd585e562e31481d0acb46bfd3ab488
4,856
package com.jlhood.ddbcopier; import static com.jlhood.ddbcopier.EventualConsistency.waitUntil; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.services.cloudformation.AmazonCloudFormationClientBuilder; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.GetItemResult; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import com.amazonaws.services.dynamodbv2.model.ScanRequest; import com.amazonaws.services.dynamodbv2.model.ScanResult; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.junit.Before; import org.junit.Test; import lombok.extern.slf4j.Slf4j; @Slf4j public class DynamoDBCopierIT { private AmazonDynamoDB ddb; private TestStackHelper testStackHelper; @Before public void setup() throws Exception { ddb = AmazonDynamoDBClientBuilder.standard().build(); testStackHelper = new TestStackHelper(AmazonCloudFormationClientBuilder.standard().build()); } @Test public void endToEnd() throws Exception { List<Map<String, AttributeValue>> writtenRecords = generateTestRecords(13); writtenRecords.stream() .map(this::toPutItemRequest) .forEach(ddb::putItem); ScanResult scanResult = waitForCopyComplete(13); List<Map<String, AttributeValue>> copiedRecords = scanResult.getItems(); assertThat(ImmutableSet.copyOf(copiedRecords), is(ImmutableSet.copyOf(writtenRecords))); Map<String, AttributeValue> item = writtenRecords.get(0); item.put("attribute", new AttributeValue("modified")); ddb.putItem(toPutItemRequest(item)); GetItemResult getItemResult = waitForItemModified(item); assertThat(getItemResult.getItem(), is(item)); ddb.deleteItem(testStackHelper.getSourceTableName(), toKey(item)); waitForItemDeleted(item); } private List<Map<String, AttributeValue>> generateTestRecords(int count) { List<Map<String, AttributeValue>> records = new ArrayList<>(count); for (int i = 0; i < count; i++) { Map<String, AttributeValue> record = new HashMap<>(); record.put("id", new AttributeValue("id-" + i)); record.put("attribute", new AttributeValue("attribute-" + i)); records.add(record); } return records; } private PutItemRequest toPutItemRequest(Map<String, AttributeValue> record) { return new PutItemRequest() .withTableName(testStackHelper.getSourceTableName()) .withItem(record); } private ScanResult waitForCopyComplete(int expectedNumItems) { return waitUntil(scanTable(testStackHelper.getCopyTableName()), scanResult -> { log.info("Waiting for copy completion: {} records expected, {} records found", expectedNumItems, scanResult.getCount()); return scanResult.getCount() == expectedNumItems; }, 180000, "Timed out waiting for table copy to complete"); } private Supplier<ScanResult> scanTable(String tableName) { return () -> ddb.scan(new ScanRequest(tableName) .withLimit(20)); } private GetItemResult waitForItemModified(Map<String, AttributeValue> item) { return waitUntil(getItem(testStackHelper.getCopyTableName(), toKey(item)), result -> { log.info("waiting for modified item to be copied: expected={}, actual={}", item, result.getItem()); return item.equals(result.getItem()); }, 180000, "Timed out waiting for item modification to complete"); } private Map<String, AttributeValue> toKey(Map<String, AttributeValue> item) { return ImmutableMap.of("id", item.get("id")); } private Supplier<GetItemResult> getItem(String tableName, Map<String, AttributeValue> key) { return () -> ddb.getItem(tableName, key); } private GetItemResult waitForItemDeleted(Map<String, AttributeValue> item) { return waitUntil(getItem(testStackHelper.getCopyTableName(), toKey(item)), result -> { log.info("waiting for item to be deleted"); return result.getItem() == null; }, 180000, "Timed out waiting for item deletion to complete"); } }
38.848
140
0.672158
4a27cc9539560d7a3c8f5be3112d6e595ca07a20
2,183
package ch.hslu.oop.person; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class PersonTest { private Person person; @BeforeEach void setUp() { person = new Person(1,"vorname","nachname"); } @Test void getId() { assertEquals(1,person.getId()); } @Test void getVorname() { assertEquals("vorname",person.getVorname()); } @Test void setVorname() { person.setVorname("neuername"); assertEquals("neuername", person.getVorname()); } @Test void getNachname() { assertEquals("nachname",person.getNachname()); } @Test void setNachname() { person.setNachname("neuer nachname"); assertEquals("neuer nachname",person.getNachname()); } @Test void testToString() { assertEquals("Person{" + "id=" + 1 + ", vorname='" + "vorname" + '\'' + ", nachname='" + "nachname" + '\'' + '}', person.toString()); } @Test void testEquals() { assertTrue(person.equals(new Person(1,"vorname","nachname"))); assertFalse(person.equals(new Person(1,"vorname","nachnam"))); assertFalse(person.equals(new Person(2,"vorname","nachname"))); } @Test void testHashCode() { assertEquals(person.hashCode(), new Person(1,"vorname","nachname").hashCode()); assertNotEquals(person.hashCode(), new Person(2,"vorname","nachname").hashCode()); assertNotEquals(person.hashCode(), new Person(1,"voname","nachname").hashCode()); } @Test void testEqualsContract() { EqualsVerifier.simple().forClass(Person.class).verify(); } @Test void compareTo() { assertEquals(0, new Person(1,"vorname","nachname").compareTo(new Person(1, "vorname","nachname"))); assertTrue(0 > new Person(4, "Anne", "Ackermann").compareTo(new Person(2, "Jonas", "Becker"))); assertTrue(0 < new Person(6, "Manuel", "Peter").compareTo(new Person(3,"Aaron", "Müller"))); } }
27.2875
107
0.594595
e1e00b33c23ae1e3a39d71521e947f82b554d980
2,985
package com.general.controller.api; import java.util.List; import com.general.dto.*; import com.general.param.student.ConfirmCodeParam; import com.general.param.student.ProjectListParam; import com.general.param.student.ProjectMemberParam; import com.general.service.ProjectService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.RequestMethod; @Controller @RequestMapping("/api/projects") public class ProjectController { @Autowired private ProjectService projectService; //getProjectList @RequestMapping(value="",method=RequestMethod.GET) public List<ProjectDTO> getProjectList(ProjectListParam projectListParam){ return projectService.getProjectList(projectListParam); } //getTokenForCreatingTopic @RequestMapping(value="",method=RequestMethod.POST) public TokenDTO postProject(@RequestBody String json){ return projectService.getTokenForCreatingTopic(json); } //getConfirmCode @RequestMapping(value="/{project_token}/confirm_code",method=RequestMethod.GET) public ConfirmCodeDTO getConfirmCode(ConfirmCodeParam confirmCodeParam, @PathVariable("project_token") String projectToken){ return projectService.getConfirmCode(confirmCodeParam, projectToken); } //switchProject @RequestMapping(value="/{project_token}",method=RequestMethod.PUT) public ErrorDTO putProject(@RequestBody String json,@PathVariable("project_token") String projectToken){ return projectService.switchProject(json, projectToken); } //getMemberList @RequestMapping(value="/{project_token}/students") public List<ProjectStudentDTO> getProjectStudent(@RequestBody String json, @PathVariable("project_token") String projectToken){ return projectService.getMemberList(json, projectToken); } //editTopic @RequestMapping(value="/{project_token}/transactions/{transaction_token}") public ErrorDTO putProject(@RequestBody String json, @PathVariable("project_token") String projectToken, @PathVariable("transaction_token") String transactionToken){ return projectService.editTopic(json, projectToken, transactionToken); } //getProjectMember @RequestMapping(value="/{project_token}/members", method = RequestMethod.GET) public ProjectMemberDTO getProjectMember(@RequestBody ProjectMemberParam projectMemberParam, @PathVariable("project_token") String projectToken){ return projectService.getProjectMember(projectMemberParam, projectToken); } /* @RequestMapping(value="/{project_token}/members",method=RequestMethod.GET) public ErrorDTO getProjectMember(@RequestBody String json,@PathVariable("project_token") String projectToken){ return null; }*/ }
42.642857
128
0.79062
fbc7d32c117dd1ca7b81f5574006f8ec29a29bb4
6,585
package com.sequenceiq.cloudbreak.service.cluster; import static com.sequenceiq.cloudbreak.service.stack.connector.VolumeUtils.buildVolumePathString; import static com.sequenceiq.cloudbreak.service.stack.connector.VolumeUtils.getLogVolume; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.JsonNode; import com.sequenceiq.cloudbreak.domain.Cluster; import com.sequenceiq.cloudbreak.domain.HostGroup; import com.sequenceiq.cloudbreak.repository.HostGroupRepository; import com.sequenceiq.cloudbreak.util.FileReaderUtils; import com.sequenceiq.cloudbreak.util.JsonUtil; @Service public class HadoopConfigurationService { @Inject private HostGroupRepository hostGroupRepository; private Map<String, ServiceConfig> serviceConfigs = new HashMap<>(); private Map<String, Map<String, String>> bpConfigs = new HashMap<>(); @PostConstruct public void init() throws IOException { String serviceConfigJson = FileReaderUtils.readFileFromClasspath("hdp/service-config.json"); JsonNode services = JsonUtil.readTree(serviceConfigJson).get("services"); for (JsonNode service : services) { String serviceName = service.get("name").asText(); JsonNode configurations = service.get("configurations"); Map<String, List<ConfigProperty>> globalConfig = new HashMap<>(); Map<String, List<ConfigProperty>> hostConfig = new HashMap<>(); for (JsonNode config : configurations) { String type = config.get("type").asText(); List<ConfigProperty> global = toList(config.get("global")); if (!global.isEmpty()) { globalConfig.put(type, global); } List<ConfigProperty> host = toList(config.get("host")); if (!host.isEmpty()) { hostConfig.put(type, host); } } serviceConfigs.put(serviceName, new ServiceConfig(serviceName, globalConfig, hostConfig)); } String bpConfigJson = FileReaderUtils.readFileFromClasspath("hdp/bp-config.json"); JsonNode bps = JsonUtil.readTree(bpConfigJson).get("sites"); for (JsonNode bp : bps) { String siteName = bp.get("name").asText(); JsonNode configurations = bp.get("configurations"); Map<String, String> keyVals = new HashMap<>(); for (JsonNode config : configurations) { String key = config.get("key").asText(); String value = config.get("value").asText(); keyVals.put(key, value); } bpConfigs.put(siteName, keyVals); } } public Map<String, Map<String, String>> getGlobalConfiguration(Cluster cluster) throws IOException { Map<String, Map<String, String>> config = new HashMap<>(); JsonNode blueprintNode = JsonUtil.readTree(cluster.getBlueprint().getBlueprintText()); JsonNode hostGroups = blueprintNode.path("host_groups"); for (JsonNode hostGroup : hostGroups) { JsonNode components = hostGroup.path("components"); for (JsonNode component : components) { String name = component.path("name").asText(); config.putAll(getProperties(name, true, null)); } } for (Map.Entry<String, Map<String, String>> entry : bpConfigs.entrySet()) { if (config.containsKey(entry.getKey())) { for (Map.Entry<String, String> inEntry : entry.getValue().entrySet()) { config.get(entry.getKey()).put(inEntry.getKey(), inEntry.getValue()); } } else { config.put(entry.getKey(), entry.getValue()); } } return config; } public Map<String, Map<String, Map<String, String>>> getHostGroupConfiguration(Cluster cluster) { Set<HostGroup> hostGroups = hostGroupRepository.findHostGroupsInCluster(cluster.getId()); Map<String, Map<String, Map<String, String>>> hadoopConfig = new HashMap<>(); for (HostGroup hostGroup : hostGroups) { int volumeCount = hostGroup.getInstanceGroup().getTemplate().getVolumeCount(); Map<String, Map<String, String>> componentConfig = new HashMap<>(); for (String serviceName : serviceConfigs.keySet()) { componentConfig.putAll(getProperties(serviceName, false, volumeCount)); } hadoopConfig.put(hostGroup.getName(), componentConfig); } return hadoopConfig; } private List<ConfigProperty> toList(JsonNode nodes) { List<ConfigProperty> list = new ArrayList<>(); for (JsonNode node : nodes) { list.add(new ConfigProperty(node.get("name").asText(), node.get("directory").asText(), node.get("prefix").asText())); } return list; } private Map<String, Map<String, String>> getProperties(String name, boolean global, Integer volumeCount) { Map<String, Map<String, String>> result = new HashMap<>(); String serviceName = getServiceName(name); if (serviceName != null) { ServiceConfig serviceConfig = serviceConfigs.get(serviceName); Map<String, List<ConfigProperty>> config = global ? serviceConfig.getGlobalConfig() : serviceConfig.getHostGroupConfig(); for (String siteConfig : config.keySet()) { Map<String, String> properties = new HashMap<>(); for (ConfigProperty property : config.get(siteConfig)) { String directory = serviceName.toLowerCase() + (property.getDirectory().isEmpty() ? "" : "/" + property.getDirectory()); String value = global ? property.getPrefix() + getLogVolume(directory) : buildVolumePathString(volumeCount, directory); properties.put(property.getName(), value); } result.put(siteConfig, properties); } } return result; } private String getServiceName(String componentName) { for (String serviceName : serviceConfigs.keySet()) { if (componentName.toLowerCase().startsWith(serviceName.toLowerCase())) { return serviceName; } } return null; } }
45.413793
140
0.633561
3ff2c2b666f3f5d370785be451873d839ee64a72
207
package edge.javax.xml.bind; import au.net.netstorm.boost.bullet.scalpel.core.Edge; public interface JAXBContext extends Edge { Marshaller createMarshaller(); Unmarshaller createUnmarshaller(); }
20.7
54
0.777778
d7bf7d2c5b28b41334a53086499de9f0c89cc17e
678
// Copyright Eagle Legacy Modernization, 2010-date // Original author: Steven A. O'Hara, Feb 11, 2011 package com.eagle.programmar.Gupta.Declarations; import com.eagle.programmar.Gupta.Gupta_Declaration; import com.eagle.programmar.Gupta.Terminals.Gupta_CommentToEndOfLine; import com.eagle.programmar.Gupta.Terminals.Gupta_Keyword; public class Gupta_Application extends Gupta_Declaration { public Gupta_Keyword Application = new Gupta_Keyword("Application"); public Gupta_Keyword description = new Gupta_Keyword("description"); public Gupta_CommentToEndOfLine comment; public @INDENT Gupta_Libraries libraries; public Gupta_Global_Declarations globalDeclarations; }
35.684211
69
0.833333
4b64836f34a23b8f3f02dfd3176a75b528e1b2f1
6,162
package com.njlabs.guide.android.dev; import java.io.IOException; import java.io.InputStream; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.SubMenu; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import android.annotation.TargetApi; import android.content.Intent; import android.content.res.AssetManager; public class Threads extends SherlockActivity { String title=null; String codesnippet=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.threads); Bundle extras = getIntent().getExtras(); title = extras.getString("title"); codesnippet = extras.getString("codesnippet"); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(title); TextView textView = (TextView) findViewById(R.id.textViewThreads); if(title.equals("Regular Thread")) { textView.setText("Sometimes there arises a situation when you need to run long processes. But when we run these process on the main thread, there is a delay in the UI causing a lag for the user. So, it's always better to go for a seperate thread to run the long process in the background without affecting the Main UI Thread.\n\nThis is an example for a simple background thread."); } else if(title.equals("A Thread with a handler")) { textView.setText("In some cases, there is a need for the background thread to make changes in the UI thread. But since a Background thread cannot handle UI Operation, we make use of a seperate handler that acts as bridge between the background thread and the UI thread.\n\nThis is an example for a simple background thread with a handler. Both posting an object and a runnable is shown."); } else if(title.equals("An AsyncTask")) { textView.setText("An AsyncThread is a special type of thread that can handle both a background process and the user interface.\n\nHere is a small example of an AsyncTask."); } WebView webView1 = (WebView) findViewById(R.id.webViewJava); webView1.setWebViewClient(new WebViewClient(){ @TargetApi(11) @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { Log.d("shouldInterceptRequest", url); InputStream stream = inputStreamForAndroidResource(url); if (stream != null) { return new WebResourceResponse("text/javascript", "utf-8", stream); } return super.shouldInterceptRequest(view, url); } private InputStream inputStreamForAndroidResource(String url) { final String ANDROID_ASSET = "file:///android_asset/"; if (url.contains(ANDROID_ASSET)) { url = url.replaceFirst(ANDROID_ASSET, ""); try { AssetManager assets = getAssets(); Uri uri = Uri.parse(url); return assets.open(uri.getPath(), AssetManager.ACCESS_STREAMING); } catch (IOException e) { e.printStackTrace(); } } return null; } }); webView1.getSettings().setJavaScriptEnabled(true); webView1.setWebChromeClient(new WebChromeClient()); webView1.loadUrl("file:///android_asset/code_snippets/"+codesnippet+"_java.html"); } public void DemoThread(View view) { Intent intent1 = new Intent(this, BitmapCanvas.class); startActivity(intent1); overridePendingTransition(R.anim.fadein,R.anim.fadeout); } private Menu mainMenu; private SubMenu subMenu1; @Override public boolean onCreateOptionsMenu(Menu menu) { mainMenu = menu; subMenu1 = menu.addSubMenu("Options"); MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.main, subMenu1); MenuItem subMenu1Item = subMenu1.getItem(); subMenu1Item.setIcon(R.drawable.abs__ic_menu_moreoverflow_normal_holo_dark); subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case android.R.id.home: // app icon in action bar clicked; go home finish(); overridePendingTransition(R.anim.fadein,R.anim.fadeout); return true; case R.id.AboutAppOption: Intent intent1 = new Intent(this, AboutApp.class); startActivity(intent1); overridePendingTransition(R.anim.fadein,R.anim.fadeout); return true; case R.id.BugReportOption: Intent intent2 = new Intent(this, BugReport.class); startActivity(intent2); overridePendingTransition(R.anim.fadein,R.anim.fadeout); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.fadein, R.anim.fadeout); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { mainMenu.performIdentifierAction(subMenu1.getItem().getItemId(), 0); return true; } return super.onKeyUp(keyCode, event); } }
39.5
398
0.662285
42bc185b996a4c84c670f2d1a64005088b16bff2
661
package sarf.verb.quadriliteral.unaugmented; import java.util.*; /** * <p>Title: قائمة الجذور الرباعية المجردة </p> * * <p>Description: </p> * * <p>Copyright: Copyright (c) 2006</p> * * <p>Company: </p> * * @author not attributable * @version 1.0 */ public class UnaugmentedQuadriliteralRootTree { private final List<UnaugmentedQuadrilateralRoot> roots = new ArrayList<>(); public UnaugmentedQuadriliteralRootTree() { } public void addRoot(UnaugmentedQuadrilateralRoot root) { roots.add(root); } public List<UnaugmentedQuadrilateralRoot> getRoots() { return roots; } }
21.322581
80
0.639939
b54489ab8befddd4a9f2a6243df590f75a39f21f
2,088
package io.github.lama06.llamagames.llama_says; import io.github.lama06.llamagames.GameCommand; import io.github.lama06.llamagames.LlamaCommand; import io.github.lama06.llamagames.LlamaGamesPlugin; import net.kyori.adventure.text.Component; public class LlamaSaysCommand extends GameCommand { public LlamaSaysCommand(LlamaGamesPlugin plugin) { super(plugin, "llamasays"); addSubCommand("floorCenter", LlamaCommand.createBlockPositionConfigSubCommand( plugin, LlamaSaysGame.class, config -> Component.text("The floor center is currently at %s".formatted(config.getFloorCenter())), LlamaSaysConfig::setFloorCenter, position -> Component.text("Floor center successfully changed to %s".formatted(position)) )); addSubCommand("numberOfRounds", createIntegerConfigSubCommand( plugin, LlamaSaysGame.class, config -> Component.text("The game will end after %d rounds".formatted(config.getNumberOfRounds())), LlamaSaysConfig::setNumberOfRounds, rounds -> Component.text("Number of rounds successfully changed to %d".formatted(rounds)) )); addSubCommand("floor", createBlockAreaConfigSubCommand( plugin, LlamaSaysGame.class, config -> Component.text("The floor is currently at %s".formatted(config.getFloor())), LlamaSaysConfig::setFloor, floor -> Component.text("The position of the floor was successfully changed to %s".formatted(floor)) )); addSubCommand("floorBlock", createMaterialConfigSubCommand( plugin, LlamaSaysGame.class, config -> Component.text("The floor is currently made of ").append(Component.translatable(config.getFloorMaterial())), LlamaSaysConfig::setFloorMaterial, material -> Component.text("The floor is now made of ").append(Component.translatable(material)) )); } }
46.4
134
0.650862
e024cdb2bb3e49eac60bdcdb4bc7855dbae6a761
3,129
package com.github.nilstrieb.commands.fun; import com.github.nilstrieb.cofig.Config; import com.github.nilstrieb.core.command.Command; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; import java.util.*; public class FightCommand extends Command { public FightCommand() { super("fight", "Fight against someone else!", "fight Tonpa", ""); } @Override public void called(String args) { if (args.isEmpty()) { reply("You need to specify who you want to fight against!"); return; } EmbedBuilder builder = Config.getDefaultEmbed(); String author = event.getAuthor().getAsTag(); builder.addField(author + " x " + args, "A fight breaks out between " + author + " and " + args, false); event.getTextChannel().sendMessage(builder.build()).queue(m -> new Fight(m, author, args)); } static class Fight { private static String[] abilities = {"Little Flower", "Jajanken", "Lightning", "punch", "Chapter 7 Bankruptcy", "Ripper Cyclotron", "Rising Sun", "100-Type Guanyin Bodhisattva"}; private Message fightMessage; private Fighter fighter1; private Fighter fighter2; private Fighter currentFighter; Random random = new Random(); public Fight(Message fightMessage, String fighter1, String fighter2) { this.fightMessage = fightMessage; this.fighter1 = new Fighter(fighter1); this.fighter2 = new Fighter(fighter2); Timer t = new Timer(); if (random.nextBoolean()) { currentFighter = this.fighter1; } else { currentFighter = this.fighter2; } t.schedule(new TimerTask() { @Override public void run() { doRound(); } }, 1000); } private void doRound() { if (random.nextBoolean()) { if (random.nextInt(10) < 7) { fighter2.damage(random.nextInt(20) + 10); } } } private void reply(MessageEmbed embed) { fightMessage.editMessage(embed).queue(); } private MessageEmbed getNextEmbed(String attack) { return Config.getDefaultEmbed() .setTitle(attack) .addField(fighter1.name, fighter1.hp + " hp", true) .addField(fighter2.name, fighter2.hp + " hp", true).build(); } static class Fighter { private final String name; private int hp; public Fighter(String name) { this.name = name; this.hp = 100; } public void damage(int dmg) { hp -= dmg; } public String getName() { return name; } public int getHp() { return hp; } } } }
28.972222
153
0.537552
fb2c1afa3062487d9e8625d081cdcbf7ebe4f632
19,078
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ package org.apache.ofbiz.htmlreport.util; import java.util.Collection; import java.util.Iterator; /** * Provides String utility functions.<p> * */ public final class ReportStringUtil { /** Constant for <code>"false"</code>. */ public static final String FALSE = Boolean.toString(false); /** a convenient shorthand to the line separator constant. */ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** Contains all chars that end a sentence in the {@link #trimToSize(String, int, int, String)} method. */ public static final char[] SENTENCE_ENDING_CHARS = {'.', '!', '?'}; /** a convenient shorthand for tabulations. */ public static final String TABULATOR = " "; /** Constant for <code>"true"</code>. */ public static final String TRUE = Boolean.toString(true); /** Day constant. */ private static final long DAYS = 1000 * 60 * 60 * 24; /** Hour constant. */ private static final long HOURS = 1000 * 60 * 60; /** Minute constant. */ private static final long MINUTES = 1000 * 60; /** Second constant. */ private static final long SECONDS = 1000; /** * Default constructor (empty), private because this class has only * static methods.<p> */ private ReportStringUtil() { // empty } /** * Changes the filename suffix. * * @param filename the filename to be changed * @param suffix the new suffix of the file * * @return the filename with the replaced suffix */ public static String changeFileNameSuffixTo(String filename, String suffix) { int dotPos = filename.lastIndexOf('.'); if (dotPos != -1) { return filename.substring(0, dotPos + 1) + suffix; } else { // the string has no suffix return filename; } } /** * Returns a string representation for the given collection using the given separator.<p> * * @param collection the collection to print * @param separator the item separator * * @return the string representation for the given collection */ public static String collectionAsString(Collection<String> collection, String separator) { StringBuffer string = new StringBuffer(128); Iterator<String> it = collection.iterator(); while (it.hasNext()) { string.append(it.next()); if (it.hasNext()) { string.append(separator); } } return string.toString(); } /** * Replaces occurrences of special control characters in the given input with * a HTML representation.<p> * * This method currently replaces line breaks to <code>&lt;br/&gt;</code> and special HTML chars * like <code>&lt; &gt; &amp; &quot;</code> with their HTML entity representation.<p> * * @param source the String to escape * * @return the escaped String */ public static String escapeHtml(String source) { if (source == null) { return null; } source = ReportEncoder.escapeXml(source); source = substitute(source, "\r", ""); source = substitute(source, "\n", "<br/>\n"); return source; } /** * Escapes a String so it may be used in JavaScript String definitions.<p> * * This method replaces line breaks, quotation marks and \ characters.<p> * * @param source the String to escape * * @return the escaped String */ public static String escapeJavaScript(String source) { source = substitute(source, "\\", "\\\\"); source = substitute(source, "\"", "\\\""); source = substitute(source, "\'", "\\\'"); source = substitute(source, "\r\n", "\\n"); source = substitute(source, "\n", "\\n"); return source; } /** * Escapes a String so it may be used as a Perl5 regular expression.<p> * * This method replaces the following characters in a String:<br> * <code>{}[]()\$^.*+/</code><p> * * @param source the string to escape * * @return the escaped string */ public static String escapePattern(String source) { if (source == null) { return null; } StringBuffer result = new StringBuffer(source.length() * 2); for (int i = 0; i < source.length(); ++i) { char ch = source.charAt(i); switch (ch) { case '\\': result.append("\\\\"); break; case '/': result.append("\\/"); break; case '$': result.append("\\$"); break; case '^': result.append("\\^"); break; case '.': result.append("\\."); break; case '*': result.append("\\*"); break; case '+': result.append("\\+"); break; case '|': result.append("\\|"); break; case '?': result.append("\\?"); break; case '{': result.append("\\{"); break; case '}': result.append("\\}"); break; case '[': result.append("\\["); break; case ']': result.append("\\]"); break; case '(': result.append("\\("); break; case ')': result.append("\\)"); break; default: result.append(ch); } } return new String(result); } /** * Formats a runtime in the format hh:mm:ss, to be used e.g. in reports.<p> * * If the runtime is greater then 24 hours, the format dd:hh:mm:ss is used.<p> * * @param runtime the time to format * * @return the formatted runtime */ public static String formatRuntime(long runtime) { long seconds = (runtime / SECONDS) % 60; long minutes = (runtime / MINUTES) % 60; long hours = (runtime / HOURS) % 24; long days = runtime / DAYS; StringBuffer strBuf = new StringBuffer(); if (days > 0) { if (days < 10) { strBuf.append('0'); } strBuf.append(days); strBuf.append(':'); } if (hours < 10) { strBuf.append('0'); } strBuf.append(hours); strBuf.append(':'); if (minutes < 10) { strBuf.append('0'); } strBuf.append(minutes); strBuf.append(':'); if (seconds < 10) { strBuf.append('0'); } strBuf.append(seconds); return strBuf.toString(); } /** * Returns <code>true</code> if the provided String is either <code>null</code> * or the empty String <code>""</code>.<p> * * @param value the value to check * * @return true, if the provided value is null or the empty String, false otherwise */ public static boolean isEmpty(String value) { return (value == null) || (value.length() == 0); } /** * Returns <code>true</code> if the provided String is either <code>null</code> * or contains only white spaces.<p> * * @param value the value to check * * @return true, if the provided value is null or contains only white spaces, false otherwise */ public static boolean isEmptyOrWhitespaceOnly(String value) { return isEmpty(value) || (value.trim().length() == 0); } /** * Returns <code>true</code> if the provided Objects are either both <code>null</code> * or equal according to {@link Object#equals(Object)}.<p> * * @param value1 the first object to compare * @param value2 the second object to compare * * @return <code>true</code> if the provided Objects are either both <code>null</code> * or equal according to {@link Object#equals(Object)} */ public static boolean isEqual(Object value1, Object value2) { if (value1 == null) { return (value2 == null); } return value1.equals(value2); } /** * Returns <code>true</code> if the provided String is neither <code>null</code> * nor the empty String <code>""</code>.<p> * * @param value the value to check * * @return true, if the provided value is not null and not the empty String, false otherwise */ public static boolean isNotEmpty(String value) { return (value != null) && (value.length() != 0); } /** * Returns <code>true</code> if the provided String is neither <code>null</code> * nor contains only white spaces.<p> * * @param value the value to check * * @return <code>true</code>, if the provided value is <code>null</code> * or contains only white spaces, <code>false</code> otherwise */ public static boolean isNotEmptyOrWhitespaceOnly(String value) { return (value != null) && (value.trim().length() > 0); } /** * Returns the last index of any of the given chars in the given source.<p> * * If no char is found, -1 is returned.<p> * * @param source the source to check * @param chars the chars to find * * @return the last index of any of the given chars in the given source, or -1 */ public static int lastIndexOf(String source, char[] chars) { // now try to find an "sentence ending" char in the text in the "findPointArea" int result = -1; for (int i = 0; i < chars.length; i++) { int pos = source.lastIndexOf(chars[i]); if (pos > result) { // found new last char result = pos; } } return result; } /** * Returns the last index a whitespace char the given source.<p> * * If no whitespace char is found, -1 is returned.<p> * * @param source the source to check * * @return the last index a whitespace char the given source, or -1 */ public static int lastWhitespaceIn(String source) { if (isEmpty(source)) { return -1; } int pos = -1; for (int i = source.length() - 1; i >= 0; i--) { if (Character.isWhitespace(source.charAt(i))) { pos = i; break; } } return pos; } /** * Substitutes <code>searchString</code> in the given source String with <code>replaceString</code>.<p> * * This is a high-performance implementation which should be used as a replacement for * <code>{@link String#replaceAll(java.lang.String, java.lang.String)}</code> in case no * regular expression evaluation is required.<p> * * @param source the content which is scanned * @param searchString the String which is searched in content * @param replaceString the String which replaces <code>searchString</code> * * @return the substituted String */ public static String substitute(String source, String searchString, String replaceString) { if (source == null) { return null; } if (isEmpty(searchString)) { return source; } if (replaceString == null) { replaceString = ""; } int len = source.length(); int sl = searchString.length(); int rl = replaceString.length(); int length; if (sl == rl) { length = len; } else { int c = 0; int s = 0; int e; while ((e = source.indexOf(searchString, s)) != -1) { c++; s = e + sl; } if (c == 0) { return source; } length = len - (c * (sl - rl)); } int s = 0; int e = source.indexOf(searchString, s); if (e == -1) { return source; } StringBuffer sb = new StringBuffer(length); while (e != -1) { sb.append(source.substring(s, e)); sb.append(replaceString); s = e + sl; e = source.indexOf(searchString, s); } e = len; sb.append(source.substring(s, e)); return sb.toString(); } /** * Returns the java String literal for the given String. <p> * * This is the form of the String that had to be written into source code * using the unicode escape sequence for special characters. <p> * * Example: "�" would be transformed to "\\u00C4".<p> * * @param s a string that may contain non-ascii characters * * @return the java unicode escaped string Literal of the given input string */ public static String toUnicodeLiteral(String s) { StringBuffer result = new StringBuffer(); char[] carr = s.toCharArray(); String unicode; for (int i = 0; i < carr.length; i++) { result.append("\\u"); // append leading zeros unicode = Integer.toHexString(carr[i]).toUpperCase(); for (int j = 4 - unicode.length(); j > 0; j--) { result.append("0"); } result.append(unicode); } return result.toString(); } /** * Returns a substring of the source, which is at most length characters long.<p> * * This is the same as calling {@link #trimToSize(String, int, String)} with the * parameters <code>(source, length, " ...")</code>.<p> * * @param source the string to trim * @param length the maximum length of the string to be returned * * @return a substring of the source, which is at most length characters long */ public static String trimToSize(String source, int length) { return trimToSize(source, length, length, " ..."); } /** * Returns a substring of the source, which is at most length characters long.<p> * * If a char is cut, the given <code>suffix</code> is appended to the result.<p> * * This is almost the same as calling {@link #trimToSize(String, int, int, String)} with the * parameters <code>(source, length, length*, suffix)</code>. If <code>length</code> * if larger then 100, then <code>length* = length / 2</code>, * otherwise <code>length* = length</code>.<p> * * @param source the string to trim * @param length the maximum length of the string to be returned * @param suffix the suffix to append in case the String was trimmed * * @return a substring of the source, which is at most length characters long */ public static String trimToSize(String source, int length, String suffix) { int area = (length > 100) ? length / 2 : length; return trimToSize(source, length, area, suffix); } /** * Returns a substring of the source, which is at most length characters long, cut * in the last <code>area</code> chars in the source at a sentence ending char or whitespace.<p> * * If a char is cut, the given <code>suffix</code> is appended to the result.<p> * * @param source the string to trim * @param length the maximum length of the string to be returned * @param area the area at the end of the string in which to find a sentence ender or whitespace * @param suffix the suffix to append in case the String was trimmed * * @return a substring of the source, which is at most length characters long */ public static String trimToSize(String source, int length, int area, String suffix) { if ((source == null) || (source.length() <= length)) { // no operation is required return source; } if (isEmpty(suffix)) { // we need an empty suffix suffix = ""; } // must remove the length from the after sequence chars since these are always added in the end int modLength = length - suffix.length(); if (modLength <= 0) { // we are to short, return beginning of the suffix return suffix.substring(0, length); } int modArea = area + suffix.length(); if ((modArea > modLength) || (modArea < 0)) { // area must not be longer then max length modArea = modLength; } // first reduce the String to the maximum allowed length String findPointSource = source.substring(modLength - modArea, modLength); String result; // try to find an "sentence ending" char in the text int pos = lastIndexOf(findPointSource, SENTENCE_ENDING_CHARS); if (pos >= 0) { // found a sentence ender in the lookup area, keep the sentence ender result = source.substring(0, modLength - modArea + pos + 1) + suffix; } else { // no sentence ender was found, try to find a whitespace pos = lastWhitespaceIn(findPointSource); if (pos >= 0) { // found a whitespace, don't keep the whitespace result = source.substring(0, modLength - modArea + pos) + suffix; } else { // not even a whitespace was found, just cut away what's to long result = source.substring(0, modLength) + suffix; } } return result; } }
33.470175
110
0.543715
623ca90f097f202169e4d4e80b08a3b89cb325cb
9,088
package lapr.project.data; import lapr.project.model.User; import oracle.jdbc.OracleTypes; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class UsersAPI extends DatabaseAPI { public UsersAPI() { super(); } public UsersAPI(String databaseUrl, String databaseUsername, String databasePassword) { super(databaseUrl, databaseUsername, databasePassword); } /** * Queries the database directly and returns a list with all the users. */ public List<User> getAllUsers(Integer idUser, String username, String email, String hashedSaltedPassword, String creditCardNumber, Double height, Double weight, Integer creditPoints, Double avgSpeed, Boolean isAdmin) { List<User> userList = new ArrayList<>(); StringBuilder query = new StringBuilder("SELECT * FROM \"User\" WHERE 1=1 "); if (idUser != null) query.append(" AND id_user = ").append(idUser); if (username != null) query.append(" AND username = '").append(username).append("'"); if (email != null) query.append(" AND email = '").append(email).append("'"); if (hashedSaltedPassword != null) query.append(" AND password = '").append(hashedSaltedPassword).append("'"); if (creditCardNumber != null) query.append(" AND credit_card_number = '").append(creditCardNumber).append("'"); if (height != null) query.append(" AND height = ").append(height); if (weight != null) query.append(" AND weight = ").append(weight); if (creditPoints != null) query.append(" AND credit_points = ").append(creditPoints); if (avgSpeed != null) query.append(" AND avg_speed = ").append(avgSpeed); if (isAdmin != null) query.append(" AND is_admin = ").append(isAdmin ? "1" : "0"); try { // 1. Start the connection startAll(); // 2. Query the database resultSet = statement.executeQuery(query.toString()); // 3. Get the data while (resultSet.next()) { userList.add(extractUserFromResultSet(resultSet)); } // 4. Close the connection closeAll(); } catch (Exception e) { e.printStackTrace(); } finally { closeAll(); } return userList; } /** * Queries the database directly and returns a list with all the users. */ public List<User> getAllUsers() { return getAllUsers(null, null, null, null, null, null, null, null, null, null); } /** * Queries the database directly and returns a specific user by id. */ public User getUserById(Integer id) { User user = null; List<User> userList = getAllUsers(id, null, null, null, null, null, null, null, null, null); if (!userList.isEmpty()) { user = userList.get(0); } return user; } /** * Queries the database directly and returns a specific user by email. */ public User getUserByEmail(String email) { User user = null; List<User> userList = getAllUsers(null, null, email, null, null, null, null, null, null, null); if (!userList.isEmpty()) { user = userList.get(0); } return user; } public User getUserByUsername(String username) { User user = null; List<User> userList = getAllUsers(null, username, null, null, null, null, null, null, null, null); if (!userList.isEmpty()) { user = userList.get(0); } return user; } /** * Removed a specific user from the database, given it's id, return it's id. */ public Integer removeUserById(Integer id) { Integer idUserRemoved = null; try { // 1. Start the connection startAll(); // 2. Query the database callableStatement = connection.prepareCall("{ ? = call removeUserById(?) }"); callableStatement.registerOutParameter(1, OracleTypes.INTEGER); callableStatement.setInt(2, id); callableStatement.execute(); idUserRemoved = callableStatement.getInt(1); // 3. Close the connection closeAll(); } catch (Exception e) { e.printStackTrace(); } finally { closeAll(); } return idUserRemoved; } /** * Removed a specific user from the database, given it's email, return it's id. */ public Integer removeUserByEmail(String email) { Integer idUserRemoved = null; try { // 1. Start the connection startAll(); // 2. Query the database callableStatement = connection.prepareCall("{ ? = call removeUserByEmail(?) }"); callableStatement.registerOutParameter(1, OracleTypes.INTEGER); callableStatement.setString(2, email); callableStatement.execute(); idUserRemoved = callableStatement.getInt(1); // 3. Close the connection closeAll(); } catch (Exception e) { e.printStackTrace(); } finally { closeAll(); } return idUserRemoved; } /** * Update a specific user from the database, given it's park, return it's id. */ public Integer updateUser(User user) { return updateUser(user.getIdUser(), user.getUsername(), user.getEmail(), user.getHashedSaltedPassword(), user.getCreditCardNumber(), user.getHeight(), user.getWeight(), user.getCreditPoints(), user.getAvgSpeed(), user.isIsAdmin()); } /** * Make the update call to the database */ private Integer updateUser(Integer idUser, String username, String email, String password, String creditCard, Double height, Double weight, Integer creditPoints, Double avgSpeed, boolean isAdmin) { Integer idUserUpdated = null; try { // 1. Start the connection startAll(); // 2. Query the database callableStatement = connection.prepareCall("{ ? = call updateUserById(?,?,?,?,?,?,?,?,?,?) }"); callableStatement.registerOutParameter(1, OracleTypes.INTEGER); callableStatement.setInt(2, idUser); callableStatement.setString(3, username); callableStatement.setString(4, email); callableStatement.setString(5, password); callableStatement.setString(6, creditCard); callableStatement.setDouble(7, height); callableStatement.setDouble(8, weight); if (creditPoints == null) { callableStatement.setInt(9, creditPoints); } else { callableStatement.setInt(9, creditPoints); } callableStatement.setDouble(10, avgSpeed); callableStatement.setInt(11, isAdmin ? 1 : 0); callableStatement.execute(); idUserUpdated = callableStatement.getInt(1); // 3. Close the connection closeAll(); } catch (SQLException e) { e.printStackTrace(); } finally { closeAll(); } return idUserUpdated; } public Integer addUser(User u1) { return addUser(u1.getEmail(), u1.getUsername(), u1.getHashedSaltedPassword(), u1.getCreditCardNumber(), u1.getHeight(), u1.getWeight(), u1.getCreditPoints(), u1.getAvgSpeed(), u1.isIsAdmin()); } private Integer addUser(String email, String username, String password, String creditCardNumber, Double height, Double weight, Integer creditPoints, Double avgSpeed, boolean isAdmin) { Integer idUserAdded = null; try { // 1. Start the connection startAll(); // 2. Query the database callableStatement = connection.prepareCall("{ ? = call addUser(?,?,?,?,?,?,?,?,?) }"); callableStatement.registerOutParameter(1, OracleTypes.NUMBER); callableStatement.setString(2, username); callableStatement.setString(3, email); callableStatement.setString(4, password); callableStatement.setString(5, creditCardNumber); callableStatement.setDouble(6, height); callableStatement.setDouble(7, weight); if (creditPoints == null) { callableStatement.setObject(8, null); } else { callableStatement.setInt(8, creditPoints); } callableStatement.setDouble(9, avgSpeed); callableStatement.setInt(10, isAdmin ? 1 : 0); callableStatement.execute(); idUserAdded = callableStatement.getInt(1); // 3. Close all connections closeAll(); } catch (SQLException e) { e.printStackTrace(); } finally { closeAll(); } return idUserAdded; } }
36.497992
239
0.585057
d7e94738a9fd4a5fe19114b4a564fa853b7b9e02
252
package sunrise.raas.sdk.core.requests.rest; import java.util.Map; public final class GetRequest extends AbstractRestRequest { public GetRequest(String route, Map<String, String> headers) { super(HttpVerb.Delete, route, headers); } }
25.2
66
0.738095
278f4d29d8000f1de7761acb99197dc9bcf65947
8,786
package codejam.y2014.qualifications.krige.d; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Problem * * Naomi and Ken sometimes play games together. Before they play, each of them * gets N identical-looking blocks of wood with masses between 0.0kg and 1.0kg * (exclusive). All of the blocks have different weights. There are lots of * games they could play with those blocks, but they usually play something they * call War. Here is how War works: * * Each player weighs each of his or her own blocks, so each player knows the * weights of all of his or her own blocks, but not the weights of the other * player's blocks. They repeat the following process N times: Naomi chooses one * of her own blocks, with mass ChosenNaomi. Naomi tells Ken the mass of the * block she chose. Ken chooses one of his own blocks, with mass ChosenKen. They * each put their block on one side of a balance scale, and the person whose * block is heavier gets one point. Both blocks are destroyed in a fire. * * Naomi has realized three things about War. First, she has realized that she * loses a lot. Second, she has realized that there is a unique strategy that * Ken can follow to maximize his points without assuming anything about Naomi's * strategy, and that Ken always uses it. Third, she has realized that she hates * to lose. Naomi has decided that instead of playing War, she will play a game * she calls Deceitful War. The great thing about Deceitful War is that Ken will * think they're playing War! * * Here is how Deceitful War works, with differences between Deceitful War and * War in bold: * * 1. Each player weighs each of his or her own blocks. Naomi also weighs Ken's * blocks while he isn't looking, so Naomi knows the weights of all blocks and * Ken only knows the weights of his own blocks. * * 2. They repeat the following process N times: Naomi chooses one of her own * blocks, with mass ChosenNaomi. Naomi tells Ken a number, ToldNaomi, between * 0.0kg and 1.0kg exclusive. Ken, who thinks they're playing War, thinks the * number Naomi just told him is ChosenNaomi. Ken chooses one of his own blocks, * with mass ChosenKen. They each put their block on one side of a balance * scale, and the person whose block is heavier gets one point. Both blocks are * destroyed in a fire. * * Naomi doesn't want Ken to know that she isn't playing War; so when she is * choosing which block to play, and what mass to tell Ken, she must make sure * that the balance scale won't reveal that ChosenNaomi ≠ ToldNaomi. In other * words, she must make decisions so that: * * ChosenNaomi > ChosenKen if, and only if, ToldNaomi > ChosenKen, and ToldNaomi * is not equal to the mass of any of Ken's blocks, because he knows that isn't * possible. * * It might seem like Naomi won't win any extra points by being deceitful, * because Ken might discover that she wasn't playing War; but Naomi knows Ken * thinks both players are playing War, and she knows what he knows, and she * knows Ken will always follow his unique optimal strategy for War, so she can * always predict what he will play. * * You'll be given the masses of the blocks Naomi and Ken started with. Naomi * will play Deceitful War optimally to gain the maximum number of points. Ken * will play War optimally to gain the maximum number of points assuming that * both players are playing War. What will Naomi's score be? What would it have * been if she had played War optimally instead? * * Examples * * If each player has a single block left, where Naomi has 0.5kg and Ken has * 0.6kg, then Ken is guaranteed to score the point. Naomi can't say her number * is ≥ 0.6kg, or Ken will know she isn't playing War when the balance scale * shows his block was heavier. * * If each player has two blocks left, where Naomi has [0.7kg, 0.2kg] and Ken * has [0.8kg, 0.3kg], then Naomi could choose her 0.2kg block, and deceive Ken * by telling him that she chose a block that was 0.6kg. Ken assumes Naomi is * telling the truth (as in how the War game works) and will play his 0.8kg * block to score a point. Ken was just deceived, but he will never realize it * because the balance scale shows that his 0.8kg block is, like he expected, * heavier than the block Naomi played. Now Naomi can play her 0.7kg block, tell * Ken it is 0.7kg, and score a point. If Naomi had played War instead of * Deceitful War, then Ken would have scored two points and Naomi would have * scored zero. * * Input * * The first line of the input gives the number of test cases, T. T test cases * follow. Each test case starts with a line containing a single integer N, the * number of blocks each player has. Next follows a line containing N * space-separated real numbers: the masses of Naomi's blocks, in kg. Finally * there will be a line containing N space-separated real numbers: the masses of * Ken's blocks, in kg. * * Each of the masses given to Ken and Naomi will be represented as a 0, * followed by a decimal point, followed by 1-5 digits. Even though all the * numbers in the input have 1-5 digits after the decimal point, Ken and Naomi * don't know that; so Naomi can still tell Ken that she played a block with * mass 0.5000001kg, and Ken has no reason not to believe her. * * Output * * For each test case, output one line containing "Case #x: y z", where x is the * test case number (starting from 1), y is the number of points Naomi will * score if she plays Deceitful War optimally, and z is the number of points * Naomi will score if she plays War optimally. * * Limits * * 1 ≤ T ≤ 50. * * All the masses given to Ken and Naomi are distinct, and between 0.0 and 1.0 * exclusive. * * Small dataset * * 1 ≤ N ≤ 10. * * Large dataset * * 1 ≤ N ≤ 1000. * * @author Marco Lackovic <marco.lackovic@gmail.com> * @version 1.0, 12/apr/2014 */ public class DeceitfulWar { private static final String YEAR = "2014"; private static final String ROUND = "qualifications"; private static final String FILE_NAME = "D-sample"; private final int blocks; private final double[][] masses; private static final int NAOMI = 0; private static final int KEN = 1; public DeceitfulWar(Scanner input) { blocks = input.nextInt(); masses = new double[2][blocks]; for (int i = 0; i < 2; i++) { for (int j = 0; j < blocks; j++) { masses[i][j] = input.nextDouble(); } } } private String solve() { return null; } @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException, InterruptedException { try (Scanner input = new Scanner(new BufferedInputStream( new FileInputStream(PATH + INPUT_FILE_NAME))); PrintWriter output = new PrintWriter(new FileWriter(PATH + OUTPUT_FILE_NAME))) { ExecutorService executorService = Executors .newFixedThreadPool(NUM_CPUS); int numTestCases = input.nextInt(); Future<String>[] result = new Future[numTestCases + 1]; for (int tc = 1; tc < result.length; tc++) { final DeceitfulWar problem = new DeceitfulWar(input); final int testCase = tc; result[testCase] = executorService .submit(new Callable<String>() { @Override public String call() throws Exception { try { return problem.solve(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "Failed to solve test case #" + testCase); } } }); } executorService.shutdown(); for (int tc = 1; tc < result.length; tc++) { String outputLine; try { outputLine = "Case #" + tc + ":\n" + result[tc].get(); } catch (InterruptedException | ExecutionException e) { output.close(); e.printStackTrace(); throw new RuntimeException( "Failed to get the result of test case #" + tc); } System.out.println(outputLine); output.println(outputLine); } } catch (IOException e) { e.printStackTrace(); } } private static final String INPUT_FILE_NAME = FILE_NAME + ".in"; private static final String OUTPUT_FILE_NAME = FILE_NAME + ".out"; private static final String ROOT_DIR = "dat"; private static final String PATH = ROOT_DIR + File.separator + YEAR + File.separator + ROUND + File.separator; private static final int NUM_CPUS = Runtime.getRuntime() .availableProcessors(); }
39.755656
80
0.712156
699c4e3476ae5dd532d6c070e8f26949f9bdcf09
6,083
package com.aquima.plugin.xslt.ui; import com.aquima.interactions.foundation.io.IResource; import com.aquima.interactions.foundation.io.IResourceManager; import com.aquima.interactions.foundation.io.ResourceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; @Component public class DynamicXsltLoader implements IDynamicXsltLoader { private static final Logger LOG = LoggerFactory.getLogger(DynamicXsltLoader.class); private final List<String> registeredStyleSheets = new ArrayList<>(); @Override public void registerXslt(String fileName) { LOG.debug("Registering xslt: " + fileName); this.registeredStyleSheets.add(fileName); } /** * {@inheritDoc} * * This method creates a xslt source that imports/includes in that order: * * <ol> * <li>the main xslt as configured in the xslt configuration</li> * <li>the registered xslts {@link #registerXslt(String)}</li> * <li>the xslts found in the dynamic xslt folder {@link XsltConfiguration#getDynamicStyleFolder()} order by * filename</li> * <ol> * For every xslt there is also a template (name is head-FILENAME-WITHOUT_EXTENSION) created that can be used to add * html to the head. * * Example output: * * <pre> * {@code * <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' > * <xsl:import href='aquima:main.xsl'/> * * <!-- per plugin a empty head and the include of the xsl --> * <xsl:template match='page' mode='head-treecontainer' /> * <xsl:include href='aquima:com/mycompany/myplugin/treecontainer.xsl'/> * * <xsl:template match='page' mode='head-specialbutton' /> * <xsl:include href='aquima:xslui/dynamic/specialbutton.xsl'/> * * <!-- call all the head templates --> * <xsl:template match='page' mode='plugins'> * <xsl:apply-templates select='.' mode='head-treecontainer' /> * <xsl:apply-templates select='.' mode='head-specialbutton.xsl' /> * </xsl:template> * * </xsl:stylesheet> * } * </pre> * * Example to include custom css in your custom <i>button.xsl</i>: * * <pre> * {@code * <xsl:template match="page" mode="head-button"> * <link rel="stylesheet" type="text/css" href="mycustom.css" /> * </xsl:template> * } * </pre> */ public Source createRootXslt(IResourceManager resourceManager, XsltConfiguration xsltConfiguration, String theme) { List<String> dynamicStyleSheets = this.getDynamicStyleSheets(xsltConfiguration, resourceManager, theme); if (dynamicStyleSheets.size() == 0 && this.registeredStyleSheets.size() == 0) { LOG.debug("No dynamic xslts found"); IResource resource = resourceManager.getResource(xsltConfiguration.getStyleSheet(theme)); return XsltURIResolver.asResource(resource); } dynamicStyleSheets.addAll(0, this.registeredStyleSheets); StringBuilder xsl = new StringBuilder(); xsl.append("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' >"); xsl.append("<xsl:import href='aquima:").append(xsltConfiguration.getStyleSheet(theme)).append("'/>"); // Include the stylesheets for (String styleSheet : dynamicStyleSheets) { // Add empty match as fallback if the xsl has no head template xsl.append("<xsl:template match='page' mode='head-" + getName(styleSheet) + "' />"); xsl.append("<xsl:include href='aquima:").append(styleSheet).append("'/>"); } // call the head templates xsl.append("<xsl:template match='page' mode='plugins'>"); for (String styleSheet : dynamicStyleSheets) { xsl.append("<xsl:apply-templates select='.' mode='head-" + getName(styleSheet) + "' />"); } xsl.append("</xsl:template>"); xsl.append("</xsl:stylesheet>"); LOG.debug("Created dynamic stylesheet: " + xsl.toString()); return new StreamSource(new ByteArrayInputStream(xsl.toString().getBytes())); } private static String getName(String styleSheet) { int index = styleSheet.lastIndexOf("/"); if (index == -1) { index = styleSheet.lastIndexOf("\\"); } index++; return styleSheet.substring(index, styleSheet.lastIndexOf(".")); } private List<String> getDynamicStyleSheets(XsltConfiguration xsltConfiguration, IResourceManager resourceManager, String theme) { List<String> dynamicStyleSheets = new ArrayList<>(); for (File file : this.getStylesheetsInDynamicDir(xsltConfiguration, resourceManager, theme)) { String fileName = xsltConfiguration.getDynamicStyleFolder(theme) + file.getName(); LOG.debug("Found dynamic xslt: " + fileName); dynamicStyleSheets.add(fileName); } return dynamicStyleSheets; } private File[] getStylesheetsInDynamicDir(XsltConfiguration xsltConfiguration, IResourceManager resourceManager, String theme) { IResource resource; try { resource = resourceManager.getResource(xsltConfiguration.getDynamicStyleFolder(theme)); } catch (ResourceException e) { LOG.debug("Dynamic xslt folder '{}' does not exist", xsltConfiguration.getDynamicStyleFolder(theme)); return new File[0]; } File dynamicFolder = new File(resource.getInfo().getURI()); LOG.debug("Checking {} for xsl files", dynamicFolder.getAbsolutePath()); File[] files = dynamicFolder.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".xsl"); } }); Arrays.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { return o1.getName().compareTo(o2.getName()); } }); return files; } }
36.866667
118
0.683709
674fcbe975524e71ed93a593a92621c7a7445e32
1,950
/* Copyright (c) 2010, Carl Burch. License information is located in the * logisim_src.Main source code and at www.cburch.com/logisim/. */ package logisim_src.std.wiring; import java.util.Arrays; import java.util.List; import logisim_src.comp.EndData; import logisim_src.data.Attribute; import logisim_src.data.BitWidth; import logisim_src.instance.StdAttr; class PinAttributes extends ProbeAttributes { public static PinAttributes instance = new PinAttributes(); private static final List<Attribute<?>> ATTRIBUTES = Arrays.asList(new Attribute<?>[] { StdAttr.FACING, Pin.ATTR_TYPE, StdAttr.WIDTH, Pin.ATTR_TRISTATE, Pin.ATTR_PULL, StdAttr.LABEL, Pin.ATTR_LABEL_LOC, StdAttr.LABEL_FONT }); BitWidth width = BitWidth.ONE; boolean threeState = true; int type = EndData.INPUT_ONLY; Object pull = Pin.PULL_NONE; public PinAttributes() { } @Override public List<Attribute<?>> getAttributes() { return ATTRIBUTES; } @Override @SuppressWarnings("unchecked") public <V> V getValue(Attribute<V> attr) { if (attr == StdAttr.WIDTH) return (V) width; if (attr == Pin.ATTR_TRISTATE) return (V) Boolean.valueOf(threeState); if (attr == Pin.ATTR_TYPE) return (V) Boolean.valueOf(type == EndData.OUTPUT_ONLY); if (attr == Pin.ATTR_PULL) return (V) pull; return super.getValue(attr); } boolean isOutput() { return type != EndData.INPUT_ONLY; } boolean isInput() { return type != EndData.OUTPUT_ONLY; } @Override public <V> void setValue(Attribute<V> attr, V value) { if (attr == StdAttr.WIDTH) { width = (BitWidth) value; } else if (attr == Pin.ATTR_TRISTATE) { threeState = ((Boolean) value).booleanValue(); } else if (attr == Pin.ATTR_TYPE) { type = ((Boolean) value).booleanValue() ? EndData.OUTPUT_ONLY : EndData.INPUT_ONLY; } else if (attr == Pin.ATTR_PULL) { pull = value; } else { super.setValue(attr, value); return; } fireAttributeValueChanged(attr, value); } }
27.083333
86
0.711282
63f7d07cc615330191acf89dcdcf1f26fd21405a
231
package Debugging; public class Car { public int run(int speed, int accelerate) { return speed + accelerate; } public static void main(String[] args) { System.out.println(new Car().run(5,4)); } }
17.769231
47
0.61039
0d936694273d7ca5b9ab9c474d2d5d13317e271e
1,722
/* * Copyright 2008 blue media labs 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 org.bluemedialabs.util; /** * <p></p> * * @author J. Marco Bremer * @version 1.0 */ public class MyPrint { static public final boolean DISABLED = false; static private final int[] POWER_10 = { 1, 10, 100, 1000, 10000, 100000, 1000000 }; static public void p(String s) { if (!DISABLED) System.out.print(s); } static public void pl(String s) { if (!DISABLED) System.out.println(s); } static public void pl() { if (!DISABLED) System.out.println(); } static public void pe(String s) { if (!DISABLED) System.err.print(s); } static public void ple(String s) { if (!DISABLED) System.err.println(s); } static public void ple() { if (!DISABLED) System.err.println(); } // static public void pn(double d, int prec) { // int prec *= 10; // // return Math.round(d * prec) // / (double) 10000 static public String toPercent(double d, int prec) { assert prec >= 0; double f = (prec <= 6? POWER_10[prec]: Math.pow(10.0, (double) prec)); return String.valueOf(Math.round(d * f * 100) / f); } static public String toPercent(double d) { return toPercent(d, 0); } }
25.701493
75
0.673055
253b099462f71be1f750aa34939d75fbd9992cda
904
package com.googlecode.gwt.test; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.PushButton; import com.googlecode.gwt.test.utils.events.Browser; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class PushButtonTest extends GwtTestTest { private boolean clicked; @Test public void click() { // Given clicked = false; final PushButton b = new PushButton("Up", "Down"); b.addClickHandler(event -> clicked = true); // Preconditions assertThat(b.getText()).isEqualTo("Up"); // When Browser.click(b); // Then assertThat(clicked).as("PushButton onClick was not triggered").isTrue(); assertThat(b.getText()).isEqualTo("Up"); } }
25.111111
81
0.641593
9d9fd8b32cf67b28d637297fe8ec8543efa725b5
619
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lab.de.onasis; /** * * @author Monica */ public class LabDeOnasis { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // } }
19.34375
79
0.547658
f5c14c568d41b36cbb566b675654ab6147dfb607
5,576
package models; import c195.Application; import java.time.*; import java.sql.*; import java.util.*; import java.util.stream.*; import javafx.beans.property.*; public abstract class DBEntity { private ReadOnlyObjectWrapper<ZonedDateTime> createDate = new ReadOnlyObjectWrapper(); private ReadOnlyStringWrapper createdBy = new ReadOnlyStringWrapper(); private ReadOnlyObjectWrapper<ZonedDateTime> lastUpdate = new ReadOnlyObjectWrapper(); private ReadOnlyStringWrapper lastUpdateBy = new ReadOnlyStringWrapper();; private boolean isNew = true; public boolean getIsNew() { return isNew; } public DBEntity() { } public ZonedDateTime getCreateDate() { return createDate.get(); } protected void setCreateDate(ZonedDateTime value) { this.createDate.set(value); } public ReadOnlyObjectProperty<ZonedDateTime> createDateProperty() { return createDate.getReadOnlyProperty(); } public String getCreatedBy() { return createdBy.get(); } protected void setCreatedBy(String value) { createdBy.set(value); } public ReadOnlyStringProperty createdByProperty() { return createdBy.getReadOnlyProperty(); } public ZonedDateTime getLastUpdate() { return lastUpdate.get(); } protected void setLastUpdate(ZonedDateTime value) { this.lastUpdate.set(value); } public ReadOnlyObjectProperty<ZonedDateTime> lastUpdateProperty() { return lastUpdate.getReadOnlyProperty(); } public String getLastUpdateBy() { return lastUpdateBy.get(); } protected void setLastUpdateBy(String value) { lastUpdateBy.set(value); } public ReadOnlyStringProperty lastUpdateByProperty() { return lastUpdateBy.getReadOnlyProperty(); } // I guess I'll avoid using reflection. abstract int getId(); abstract void setId(int value); abstract String[] getColumnNames(); abstract String getTableName(); protected String getIdColumnName() { return getTableName() + "Id"; } protected void fromResultSet(ResultSet rs) throws SQLException { setId(rs.getInt(getIdColumnName())); setCreateDate(Application.toZonedDateTime(rs.getTimestamp("createDate"))); setCreatedBy(rs.getString("createdBy")); setLastUpdate(Application.toZonedDateTime(rs.getTimestamp("lastUpdate"))); setLastUpdateBy(rs.getString("lastUpdateBy")); isNew = false; } protected void commitToDb(PreparedStatement statement) throws Exception { statement.executeUpdate(); if (isNew) { try (ResultSet rs = statement.getGeneratedKeys()) { if (rs.next()) { setId(rs.getInt(1)); isNew = false; } else { throw new Exception("The result set returned no generated id."); } } } setLastUpdate(ZonedDateTime.now()); } protected PreparedStatement getPreparedStatement(Connection connection) throws SQLException { if (this.isNew) return getPreparedInsertStatement(connection); return getPreparedUpdateStatement(connection); } private PreparedStatement getPreparedInsertStatement(Connection connection) throws SQLException { String[] columns = this.getColumnNames(); StringBuilder sql = new StringBuilder(); int count = columns.length + 3; sql.append("INSERT INTO " + getTableName() + " (" + String.join(", ", columns) + ", createDate, createdBy, lastUpdateBy) VALUES("); for (int i = 1; i <= count; i++) { sql.append("?"); if (i < count) sql.append(","); } sql.append(")"); PreparedStatement statement = connection.prepareStatement(sql.toString(), new String[] { getIdColumnName(), "lastUpdate" }); Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now(ZoneOffset.UTC)); String userName = Application.getInstance().getActiveUser().getUserName(); statement.setTimestamp(count - 2, timestamp); statement.setString(count - 1, userName); statement.setString(count, userName); return statement; } private PreparedStatement getPreparedUpdateStatement(Connection connection) throws SQLException { String[] columns = this.getColumnNames(); StringBuilder sql = new StringBuilder(); int count = columns.length; sql.append("UPDATE " + getTableName() + " SET "); for (int i = 1; i <= count; i++) { sql.append(columns[i - 1] + " = ?,"); } sql.append(" lastUpdateBy = ?"); sql.append(" WHERE " + this.getIdColumnName() + " = ?"); PreparedStatement statement = connection.prepareStatement(sql.toString(), new String[] { getIdColumnName(), "lastUpdate" }); String userName = Application.getInstance().getActiveUser().getUserName(); statement.setString(count + 1, userName); statement.setInt(count + 2, this.getId()); return statement; } public void deleteFromDb() throws Exception { if (isNew) return; try (Connection connection = Application.getInstance().getDBConnection()) { String sql = "DELETE FROM " + getTableName() + " WHERE " + getIdColumnName() + " = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, getId()); statement.execute(); } catch (Exception ex) { throw ex; } } }
42.564885
132
0.647238
0ac1a66399beee6d424d60f91fa1feca9c63905f
1,342
package com.ozruit; public class Match { private String homeTeam; private String awayTeam; private int homeScore; private int awayScore; public Match() { } public Match(final String homeTeam, final String awayTeam, final int homeScore, final int awayScore) { this.homeTeam = homeTeam; this.awayTeam = awayTeam; this.homeScore = homeScore; this.awayScore = awayScore; } public String getHomeTeam() { return homeTeam; } public void setHomeTeam(String homeTeam) { this.homeTeam = homeTeam; } public String getAwayTeam() { return awayTeam; } public void setAwayTeam(String awayTeam) { this.awayTeam = awayTeam; } public int getHomeScore() { return homeScore; } public void setHomeScore(int homeScore) { this.homeScore = homeScore; } public int getAwayScore() { return awayScore; } public void setAwayScore(int awayScore) { this.awayScore = awayScore; } @Override public String toString() { return "Match{" + "homeTeam='" + homeTeam + '\'' + ", awayTeam='" + awayTeam + '\'' + ", homeScore=" + homeScore + ", awayScore=" + awayScore + '}'; } }
22.366667
106
0.570045
8ff64bfd731c67399f6ef85f0b906098cc318929
1,282
package cn.yueshutong.springprojecttree.db.service.impl; import cn.yueshutong.springprojecttree.db.dao.MethodNodeDao; import cn.yueshutong.springprojecttree.db.entity.MethodNode; import cn.yueshutong.springprojecttree.db.service.MethodNodeService; import cn.yueshutong.springprojecttree.db.service.util.ServiceUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Create by yster@foxmail.com 2019/2/1 0001 15:36 */ @Service public class MethodNodeServiceImpl implements MethodNodeService { @Autowired private MethodNodeDao methodNodeDao; @Override public boolean saveNotRedo(MethodNode methodNode) { //根据方法签名查找是否已存在该方法 List<MethodNode> methodList = methodNodeDao.findAllByMethodId(methodNode.getMethodId()); //不存在直接保存,若存在调用链不相同也保存 if (methodList == null || methodList.size()==0|| !ServiceUtil.analyzeList(methodNode, methodList)) { return methodNodeDao.save(methodNode); } return false; } @Override public List<MethodNode> findAll() { return methodNodeDao.findAll(); } @Override public MethodNode findAllById(Long id) { return methodNodeDao.findAllById(id); } }
30.52381
108
0.73869
a29d9e0486ec0cfee5dd00b29c4cf85aee60108f
2,482
package com.swdave.popular_movies_app_final.adapters; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import com.bumptech.glide.Glide; import com.swdave.popular_movies_app_final.R; import com.swdave.popular_movies_app_final.activities.DetailActivity; import com.swdave.popular_movies_app_final.model.MovieResults; import java.util.List; public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> { private static final String SMALL_POSTER_URL = "https://image.tmdb.org/t/p/w200"; private List<MovieResults> results; private Context context; public MovieAdapter(Context context, List<MovieResults> results) { this.context = context; this.results = results; } @NonNull @Override public MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false); return new MovieViewHolder(view); } @Override public void onBindViewHolder(@NonNull MovieViewHolder holder, final int position) { // Loading img from Internet with Glide Glide.with(context) .load(SMALL_POSTER_URL + results.get(position).getPosterPath()) .into(holder.thumbImg); holder.parentLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, DetailActivity.class); intent.putExtra("Movie", results.get(position)); context.startActivity(intent); } }); } @Override public int getItemCount() { return results.size(); } public void setFavs(List<MovieResults> results) { this.results = results; } public static class MovieViewHolder extends RecyclerView.ViewHolder { ImageView thumbImg; RelativeLayout parentLayout; MovieViewHolder(View itemView) { super(itemView); thumbImg = itemView.findViewById(R.id.posterImg); parentLayout = itemView.findViewById(R.id.movie_parent_layout); } } }
27.88764
104
0.69581
ce5dc7ca83a464b5449488a5c671473272946e54
3,657
package pro.taskana.testapi.tests; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import pro.taskana.TaskanaEngineConfiguration; import pro.taskana.spi.priority.api.PriorityServiceProvider; import pro.taskana.testapi.CleanTaskanaContext; import pro.taskana.testapi.TaskanaEngineConfigurationModifier; import pro.taskana.testapi.TaskanaInject; import pro.taskana.testapi.TaskanaIntegrationTest; import pro.taskana.testapi.WithServiceProvider; @TaskanaIntegrationTest class TaskanaInitializationExtensionTest { @TaskanaInject TaskanaEngineConfiguration taskanaEngineConfiguration; @Test void should_UseDefaultTaskanaEngine_When_TestIsCreated() { assertThat(taskanaEngineConfiguration.getDomains()) .containsExactlyInAnyOrder("DOMAIN_A", "DOMAIN_B"); } @Nested @TestInstance(Lifecycle.PER_CLASS) class ReuseTaskana { @TaskanaInject TaskanaEngineConfiguration taskanaEngineConfiguration; @Test void should_useTopLevelTaskanaInstance_For_NestedTestClasses() { assertThat(taskanaEngineConfiguration) .isSameAs(TaskanaInitializationExtensionTest.this.taskanaEngineConfiguration); } } @Nested @TestInstance(Lifecycle.PER_CLASS) class ModifiedTaskanaEngineConfig implements TaskanaEngineConfigurationModifier { @TaskanaInject TaskanaEngineConfiguration taskanaEngineConfiguration; @Override public void modify(TaskanaEngineConfiguration taskanaEngineConfiguration) { taskanaEngineConfiguration.setDomains(List.of("A", "B")); } @Test void should_OverrideConfiguration_When_ClassImplementsTaskanaEngineConfigurationModifier() { assertThat(taskanaEngineConfiguration.getDomains()).containsExactlyInAnyOrder("A", "B"); } @Test void should_createNewTaskanaInstance_For_NestedTestClassImplementingModifierInterface() { assertThat(taskanaEngineConfiguration) .isNotSameAs(TaskanaInitializationExtensionTest.this.taskanaEngineConfiguration); } } @CleanTaskanaContext @Nested @TestInstance(Lifecycle.PER_CLASS) class NestedTestClassAnnotatedWithCleanTaskanaContext { @TaskanaInject TaskanaEngineConfiguration taskanaEngineConfiguration; @Test void should_createNewTaskanaInstance_For_NestedTestClassAnnotatedWithCleanTaskanaContext() { assertThat(taskanaEngineConfiguration) .isNotSameAs(TaskanaInitializationExtensionTest.this.taskanaEngineConfiguration); } @Test void should_UseDefaultTaskanaEngine_When_NestedClassDoesNotImplementModifier() { assertThat(taskanaEngineConfiguration.getDomains()) .containsExactlyInAnyOrder("DOMAIN_A", "DOMAIN_B"); } } @WithServiceProvider( serviceProviderInterface = PriorityServiceProvider.class, serviceProviders = TestPriorityServiceProvider.class) @Nested @TestInstance(Lifecycle.PER_CLASS) class NestedTestClassWithServiceProvider { @TaskanaInject TaskanaEngineConfiguration taskanaEngineConfiguration; @Test void should_createNewTaskanaInstance_For_NestedTestClassAnnotatedWithCleanTaskanaContext() { assertThat(taskanaEngineConfiguration) .isNotSameAs(TaskanaInitializationExtensionTest.this.taskanaEngineConfiguration); } @Test void should_UseDefaultTaskanaEngine_When_NestedClassDoesNotImplementModifier() { assertThat(taskanaEngineConfiguration.getDomains()) .containsExactlyInAnyOrder("DOMAIN_A", "DOMAIN_B"); } } }
33.861111
96
0.803391
5d673f70c5e5a487b7e5248dcf32f96ac936c6a2
203
package org.springframework.aop.mytest; public class Aspect2 { public void before(){ System.out.println("Aspect2--before执行"); } public void after(){ System.out.println("Aspect2--after执行"); } }
16.916667
42
0.70936
9fe9c9a532c1118a550afb42f24bfde7def99cbe
1,380
/* * Copyright 2018 Confluent Inc. * * Licensed under the Confluent Community License (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.confluent.io/confluent-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.damian.ksql.udf; import io.confluent.ksql.function.udf.Udf; import io.confluent.ksql.function.udf.UdfDescription; /** * This class deliberately has same FCQN as the other Multiply class in the udf-example.jar * We do this to demonstrate classloader isolation and how you can have two UDFs with different * classes with same FQCNs in different jars - each jar should be given its own classloader with * a child first delegation policy */ @UdfDescription(name = "multiply2", description = "multiplies 2 numbers shadowed version!") public class Multiply { @Udf(description = "multiply two ints") public long multiply(final int v1, final int v2) { // Deliberately return wrong value so we can distinguish it from the other multiply udf return 1 + v1 * v2; } }
37.297297
96
0.752174
9c4a4e12a31f562deeefd74f15e7e9e968e57d67
3,419
package com.schening.phoenix.security.config; import com.mysql.fabric.xmlrpc.Client; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; import javax.sql.DataSource; /** * @author schening * @date 2020/7/28 */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { private static final String DEMO_RESOURCE_ID = "*"; @Autowired private DataSource dataSource; @Override public void configure(AuthorizationServerSecurityConfigurer security) { // 允许表单认证 security.allowFormAuthenticationForClients(); // 授权认证服务需要把 /oauth/check_toke 暴露出来,并且附带上权限访问。 security.checkTokenAccess("isAuthenticated()"); } /** * 第三方用户客户端详情 * Grant Type代表当前授权的类型: * <p> * authorization_code:传统的授权码模式<br> * implicit:隐式授权模式<br> * password:资源所有者(即用户)密码模式<br> * client_credentials:客户端凭据(客户端ID以及Key)模式<br> * refresh_token:获取access token时附带的用于刷新新的token模式 * </p> * * @param clients * @throws Exception */ @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.withClientDetails(clientDetailsService()); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { // redis保存token // endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory)) // JDBC 保存 token endpoints.tokenStore(tokenStore()); endpoints.setClientDetailsService(clientDetailsService()); } /** * 客户端详情相关配置,加密相关 * @return */ @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * 声明TokenStore实现 * * @return */ @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource); } /** * 声明 ClientDetails实现 * * @return */ @Bean public ClientDetailsService clientDetailsService() { JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource); jdbcClientDetailsService.setPasswordEncoder(passwordEncoder()); return jdbcClientDetailsService; } }
33.851485
116
0.747879
53cd8debf2a652709c575732316af70b5c50d3bb
810
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Same */ public class Laskuri { private int arvo; public Laskuri(int alkuarvo) { this.arvo = alkuarvo; } public Laskuri() { this(0); } public int arvo() { return arvo; } public void lisaa(int lisays) { if (lisays > 0) { arvo += lisays; } } public void vahenna(int vahennys) { if (vahennys > 0) { arvo -= vahennys; } } public void lisaa() { lisaa(1); } public void vahenna() { vahenna(1); } }
16.530612
80
0.493827
333a8bd2342095d35a84bcb5f71bfc5473615da4
3,876
package io.coderr.client.dto; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /*** * Represents an exception being transferred for analysis */ public class ExceptionDTO { ExceptionDTO() { Properties = new HashMap<>(); } public ExceptionDTO(Throwable exception) { copy(exception, this); } public ExceptionDTO(ExceptionDTO exception) { copy(exception, this); } /** * Java library name */ public String AssemblyName; /** * Exception base classes. Most specific first: ArgumentOutOfRangeException, ArgumentException, Exception. **/ public String[] BaseClasses; /** * Full type name (namespace + class name) */ public String FullName; /** * Inner exception (if any; otherwise null). */ public ExceptionDTO InnerException; /** * Exception message */ public String Message; /** * Type name (of the exception) */ public String Name; /** * Package name */ public String Namespace; /** * All exception properties (public and private) */ public Map<String, String> Properties; /** *Stack trace, line numbers included if your app also distributes the PDB files. */ public String StackTrace; private static void copy(Throwable source, ExceptionDTO destination) { createExceptionObject(source, source.getClass(), destination); } private static void copy(ExceptionDTO source, ExceptionDTO destination) { if (source == null) return; destination.BaseClasses = source.BaseClasses; destination.AssemblyName = source.AssemblyName; destination.FullName = source.FullName; destination.Message = source.Message; destination.Name = source.Name; destination.Namespace = source.Namespace; destination.StackTrace = source.StackTrace; if (source.InnerException != null) destination.InnerException = new ExceptionDTO(source.InnerException); } private static void createExceptionObject(Throwable exception, Class<? extends Throwable> aClass, ExceptionDTO destination) { if (exception == null) return; destination.BaseClasses = collectClasses(aClass); destination.AssemblyName = exception.getClass().getPackage().getName(); destination.FullName = exception.getClass().getCanonicalName(); destination.Message = exception.getMessage(); destination.Name = exception.getClass().getSimpleName(); destination.Namespace = exception.getClass().getPackage().getName(); destination.StackTrace = buildStackTraceString(exception.getStackTrace()); Throwable cause = exception.getCause(); if (cause != null) destination.InnerException = new ExceptionDTO(cause); } private static <T extends Throwable> String[] collectClasses(Class<T> aClass) { List<String> names = new ArrayList<>(); Class<T> cls = aClass; //noinspection unchecked do { names.add(cls.getName()); } while ((cls = (Class<T>) cls.getSuperclass()) != null); return names.toArray(new String[0]); } private static String buildStackTraceString(StackTraceElement[] stackTrace) { StringBuilder builder = new StringBuilder(); for (StackTraceElement stackTraceElement : stackTrace) { builder.append(buildStackTraceString(stackTraceElement)); } return builder.toString(); } private static String buildStackTraceString(StackTraceElement stackTrace) { return String.format("at %s->%s(%s:%d)\n", stackTrace.getClassName(), stackTrace.getMethodName(), stackTrace.getFileName(), stackTrace.getLineNumber()); } }
30.761905
160
0.653767
1c0ac93cba4f2bf2934ff1ae540ae9f4d373749c
2,778
package com.example.mvcp.controllers; import com.example.mvcp.entities.Cart; import com.example.mvcp.entities.CartProps; import com.example.mvcp.entities.Users; import com.example.mvcp.repositories.CartPropsRepository; import com.example.mvcp.repositories.CartRepositoy; import com.example.mvcp.repositories.CategoryRepository; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller public class CartController { int cartid = 0; final CategoryRepository catRepo; final CartRepositoy cartRepo; final CartPropsRepository cartPropsRepo; public CartController(CategoryRepository catRepo, CartRepositoy cartRepo, CartPropsRepository cartPropsRepo) { this.catRepo = catRepo; this.cartRepo = cartRepo; this.cartPropsRepo = cartPropsRepo; } @GetMapping("/cart") public String cart(Model model, HttpServletRequest request) { model.addAttribute("catlist", catRepo.findAll()); Users usr = (Users) request.getSession().getAttribute("user"); request.setAttribute("user_info", usr); if (usr != null){ List<CartProps> cartPropsList = cartPropsRepo.fillCart(usr.getUid()); int total = 0; for (CartProps item : cartPropsList) { total = total + (Integer.parseInt(item.getPrice()) * item.getQuantity()); } model.addAttribute("cartlist", cartPropsList); model.addAttribute("total", total); } else { return "redirect:/"; } return "cart"; } @GetMapping("/cartDelete/{scartid}") public String cartDelete(@PathVariable String scartid) { try { int cartid = Integer.parseInt(scartid); cartRepo.deleteById(cartid); } catch (EmptyResultDataAccessException e) { return "redirect:/cart"; } return "redirect:/cart"; } @PostMapping("/cartAdd") public String cartAdd(Cart cart, HttpServletRequest request) { Users usr = (Users) request.getSession().getAttribute("user"); request.setAttribute("user_info", usr); if (usr != null){ cart.setUid(usr.getUid()); if (cartid != 0) { cart.setCartid(cartid); } cartRepo.saveAndFlush(cart); cartid = 0; } else { return "redirect:/"; } return "redirect:/cart"; } }
34.725
114
0.659467