blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
8b8ece81e64fff2dd2b7fee8adb03617faa4f5bc
5cc7094e26c04bbfe77d83066ca03346a92e842f
/app/src/main/java/com/yktx/check/listview/TwoWayView.java
04d07adc537478f4509c1238de213bae59ca29d2
[]
no_license
wudi1986/ClockCalendar
ae71ac45b2475c9efef9f37497d1b68913df2c14
76ea6015238dea17f4d4b6b25d9ad0f0130c13f6
refs/heads/master
2021-01-19T02:27:50.913587
2016-06-20T08:53:53
2016-06-20T08:53:53
49,640,962
0
0
null
null
null
null
UTF-8
Java
false
false
225,911
java
/* * Copyright (C) 2013 Lucas Rocha * * This code is based on bits and pieces of Android's AbsListView, * Listview, and StaggeredGridView. * * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yktx.check.listview; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.support.v4.util.SparseArrayCompat; import android.support.v4.view.AccessibilityDelegateCompat; import android.support.v4.view.KeyEventCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.VelocityTrackerCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.support.v4.widget.EdgeEffectCompat; import android.util.AttributeSet; import android.util.Log; import android.util.LongSparseArray; import android.util.SparseBooleanArray; import android.view.ContextMenu.ContextMenuInfo; import android.view.FocusFinder; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.ViewTreeObserver; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.Checkable; import android.widget.ListAdapter; import android.widget.Scroller; import com.yktx.check.R; /* * Implementation Notes: * * Some terminology: * * index - index of the items that are currently visible * position - index of the items in the cursor * * Given the bi-directional nature of this view, the source code * usually names variables with 'start' to mean 'top' or 'left'; and * 'end' to mean 'bottom' or 'right', depending on the current * orientation of the widget. */ /** * A view that shows items in a vertical or horizontal scrolling list. * The items come from the {@link ListAdapter} associated with this view. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public class TwoWayView extends AdapterView<ListAdapter> implements ViewTreeObserver.OnTouchModeChangeListener { private static final String LOGTAG = "TwoWayView"; private static final int NO_POSITION = -1; private static final int INVALID_POINTER = -1; public static final int[] STATE_NOTHING = new int[] { 0 }; private static final int TOUCH_MODE_REST = -1; private static final int TOUCH_MODE_DOWN = 0; private static final int TOUCH_MODE_TAP = 1; private static final int TOUCH_MODE_DONE_WAITING = 2; private static final int TOUCH_MODE_DRAGGING = 3; private static final int TOUCH_MODE_FLINGING = 4; private static final int TOUCH_MODE_OVERSCROLL = 5; private static final int TOUCH_MODE_UNKNOWN = -1; private static final int TOUCH_MODE_ON = 0; private static final int TOUCH_MODE_OFF = 1; private static final int LAYOUT_NORMAL = 0; private static final int LAYOUT_FORCE_TOP = 1; private static final int LAYOUT_SET_SELECTION = 2; private static final int LAYOUT_FORCE_BOTTOM = 3; private static final int LAYOUT_SPECIFIC = 4; private static final int LAYOUT_SYNC = 5; private static final int LAYOUT_MOVE_SELECTION = 6; private static final int SYNC_SELECTED_POSITION = 0; private static final int SYNC_FIRST_POSITION = 1; private static final int SYNC_MAX_DURATION_MILLIS = 100; private static final int CHECK_POSITION_SEARCH_DISTANCE = 20; private static final float MAX_SCROLL_FACTOR = 0.33f; private static final int MIN_SCROLL_PREVIEW_PIXELS = 10; public static enum ChoiceMode { NONE, SINGLE, MULTIPLE } public static enum Orientation { HORIZONTAL, VERTICAL; }; private ListAdapter mAdapter; private boolean mIsVertical; private int mItemMargin; private boolean mInLayout; private boolean mBlockLayoutRequests; private boolean mIsAttached; private final RecycleBin mRecycler; private AdapterDataSetObserver mDataSetObserver; private boolean mItemsCanFocus; final boolean[] mIsScrap = new boolean[1]; private boolean mDataChanged; private int mItemCount; private int mOldItemCount; private boolean mHasStableIds; private boolean mAreAllItemsSelectable; private int mFirstPosition; private int mSpecificStart; private SavedState mPendingSync; private final int mTouchSlop; private final int mMaximumVelocity; private final int mFlingVelocity; private float mLastTouchPos; private float mTouchRemainderPos; private int mActivePointerId; private final Rect mTempRect; private final ArrowScrollFocusResult mArrowScrollFocusResult; private Rect mTouchFrame; private int mMotionPosition; private CheckForTap mPendingCheckForTap; private CheckForLongPress mPendingCheckForLongPress; private CheckForKeyLongPress mPendingCheckForKeyLongPress; private PerformClick mPerformClick; private Runnable mTouchModeReset; private int mResurrectToPosition; private boolean mIsChildViewEnabled; private boolean mDrawSelectorOnTop; private Drawable mSelector; private int mSelectorPosition; private final Rect mSelectorRect; private int mOverScroll; private final int mOverscrollDistance; private boolean mDesiredFocusableState; private boolean mDesiredFocusableInTouchModeState; private SelectionNotifier mSelectionNotifier; private boolean mNeedSync; private int mSyncMode; private int mSyncPosition; private long mSyncRowId; private long mSyncHeight; private int mSelectedStart; private int mNextSelectedPosition; private long mNextSelectedRowId; private int mSelectedPosition; private long mSelectedRowId; private int mOldSelectedPosition; private long mOldSelectedRowId; private ChoiceMode mChoiceMode; private int mCheckedItemCount; private SparseBooleanArray mCheckStates; LongSparseArray<Integer> mCheckedIdStates; private ContextMenuInfo mContextMenuInfo; private int mLayoutMode; private int mTouchMode; private int mLastTouchMode; private VelocityTracker mVelocityTracker; private final Scroller mScroller; private EdgeEffectCompat mStartEdge; private EdgeEffectCompat mEndEdge; private OnScrollListener mOnScrollListener; private int mLastScrollState; private View mEmptyView; private ListItemAccessibilityDelegate mAccessibilityDelegate; private int mLastAccessibilityScrollEventFromIndex; private int mLastAccessibilityScrollEventToIndex; public interface OnScrollListener { /** * The view is not scrolling. Note navigating the list using the trackball counts as * being in the idle state since these transitions are not animated. */ public static int SCROLL_STATE_IDLE = 0; /** * The user is scrolling using touch, and their finger is still on the screen */ public static int SCROLL_STATE_TOUCH_SCROLL = 1; /** * The user had previously been scrolling using touch and had performed a fling. The * animation is now coasting to a stop */ public static int SCROLL_STATE_FLING = 2; /** * Callback method to be invoked while the list view or grid view is being scrolled. If the * view is being scrolled, this method will be called before the next frame of the scroll is * rendered. In particular, it will be called before any calls to * {@link Adapter#getView(int, View, ViewGroup)}. * * @param view The view whose scroll state is being reported * * @param scrollState The current scroll state. One of {@link #SCROLL_STATE_IDLE}, * {@link #SCROLL_STATE_TOUCH_SCROLL} or {@link #SCROLL_STATE_IDLE}. */ public void onScrollStateChanged(TwoWayView view, int scrollState); /** * Callback method to be invoked when the list or grid has been scrolled. This will be * called after the scroll has completed * @param view The view whose scroll state is being reported * @param firstVisibleItem the index of the first visible cell (ignore if * visibleItemCount == 0) * @param visibleItemCount the number of visible cells * @param totalItemCount the number of items in the list adaptor */ public void onScroll(TwoWayView view, int firstVisibleItem, int visibleItemCount, int totalItemCount); } /** * A RecyclerListener is used to receive a notification whenever a View is placed * inside the RecycleBin's scrap heap. This listener is used to free resources * associated to Views placed in the RecycleBin. * * @see RecycleBin * @see TwoWayView#setRecyclerListener(RecyclerListener) */ public static interface RecyclerListener { /** * Indicates that the specified View was moved into the recycler's scrap heap. * The view is not displayed on screen any more and any expensive resource * associated with the view should be discarded. * * @param view */ void onMovedToScrapHeap(View view); } public TwoWayView(Context context) { this(context, null); } public TwoWayView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TwoWayView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mNeedSync = false; mVelocityTracker = null; mLayoutMode = LAYOUT_NORMAL; mTouchMode = TOUCH_MODE_REST; mLastTouchMode = TOUCH_MODE_UNKNOWN; mIsAttached = false; mContextMenuInfo = null; mOnScrollListener = null; mLastScrollState = OnScrollListener.SCROLL_STATE_IDLE; final ViewConfiguration vc = ViewConfiguration.get(context); mTouchSlop = vc.getScaledTouchSlop(); mMaximumVelocity = vc.getScaledMaximumFlingVelocity(); mFlingVelocity = vc.getScaledMinimumFlingVelocity(); mOverscrollDistance = getScaledOverscrollDistance(vc); mOverScroll = 0; mScroller = new Scroller(context); mIsVertical = true; mItemsCanFocus = false; mTempRect = new Rect(); mArrowScrollFocusResult = new ArrowScrollFocusResult(); mSelectorPosition = INVALID_POSITION; mSelectorRect = new Rect(); mSelectedStart = 0; mResurrectToPosition = INVALID_POSITION; mSelectedStart = 0; mNextSelectedPosition = INVALID_POSITION; mNextSelectedRowId = INVALID_ROW_ID; mSelectedPosition = INVALID_POSITION; mSelectedRowId = INVALID_ROW_ID; mOldSelectedPosition = INVALID_POSITION; mOldSelectedRowId = INVALID_ROW_ID; mChoiceMode = ChoiceMode.NONE; mCheckedItemCount = 0; mCheckedIdStates = null; mCheckStates = null; mRecycler = new RecycleBin(); mDataSetObserver = null; mAreAllItemsSelectable = true; mStartEdge = null; mEndEdge = null; setClickable(true); setFocusableInTouchMode(true); setWillNotDraw(false); setAlwaysDrawnWithCacheEnabled(false); setWillNotDraw(false); setClipToPadding(false); ViewCompat.setOverScrollMode(this, ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TwoWayView, defStyle, 0); // initializeScrollbars(a); mDrawSelectorOnTop = a.getBoolean( R.styleable.TwoWayView_android_drawSelectorOnTop, false); Drawable d = a.getDrawable(R.styleable.TwoWayView_android_listSelector); if (d != null) { setSelector(d); } int orientation = a.getInt(R.styleable.TwoWayView_android_orientation, -1); if (orientation >= 0) { setOrientation(Orientation.values()[orientation]); } int choiceMode = a.getInt(R.styleable.TwoWayView_android_choiceMode, -1); if (choiceMode >= 0) { setChoiceMode(ChoiceMode.values()[choiceMode]); } a.recycle(); updateScrollbarsDirection(); } public void setOrientation(Orientation orientation) { final boolean isVertical = (orientation.compareTo(Orientation.VERTICAL) == 0); if (mIsVertical == isVertical) { return; } mIsVertical = isVertical; updateScrollbarsDirection(); resetState(); mRecycler.clear(); requestLayout(); } public Orientation getOrientation() { return (mIsVertical ? Orientation.VERTICAL : Orientation.HORIZONTAL); } public void setItemMargin(int itemMargin) { if (mItemMargin == itemMargin) { return; } mItemMargin = itemMargin; requestLayout(); } public int getItemMargin() { return mItemMargin; } /** * Indicates that the views created by the ListAdapter can contain focusable * items. * * @param itemsCanFocus true if items can get focus, false otherwise */ public void setItemsCanFocus(boolean itemsCanFocus) { mItemsCanFocus = itemsCanFocus; if (!itemsCanFocus) { setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); } } /** * @return Whether the views created by the ListAdapter can contain focusable * items. */ public boolean getItemsCanFocus() { return mItemsCanFocus; } /** * Set the listener that will receive notifications every time the list scrolls. * * @param l the scroll listener */ public void setOnScrollListener(OnScrollListener l) { mOnScrollListener = l; invokeOnItemScrollListener(); } /** * Sets the recycler listener to be notified whenever a View is set aside in * the recycler for later reuse. This listener can be used to free resources * associated to the View. * * @param listener The recycler listener to be notified of views set aside * in the recycler. * * @see RecycleBin * @see RecyclerListener */ public void setRecyclerListener(RecyclerListener l) { mRecycler.mRecyclerListener = l; } /** * Controls whether the selection highlight drawable should be drawn on top of the item or * behind it. * * @param onTop If true, the selector will be drawn on the item it is highlighting. The default * is false. * * @attr ref android.R.styleable#AbsListView_drawSelectorOnTop */ public void setDrawSelectorOnTop(boolean drawSelectorOnTop) { mDrawSelectorOnTop = drawSelectorOnTop; } /** * Set a Drawable that should be used to highlight the currently selected item. * * @param resID A Drawable resource to use as the selection highlight. * * @attr ref android.R.styleable#AbsListView_listSelector */ public void setSelector(int resID) { setSelector(getResources().getDrawable(resID)); } /** * Set a Drawable that should be used to highlight the currently selected item. * * @param selector A Drawable to use as the selection highlight. * * @attr ref android.R.styleable#AbsListView_listSelector */ public void setSelector(Drawable selector) { if (mSelector != null) { mSelector.setCallback(null); unscheduleDrawable(mSelector); } mSelector = selector; Rect padding = new Rect(); selector.getPadding(padding); selector.setCallback(this); updateSelectorState(); } /** * Returns the selector {@link Drawable} that is used to draw the * selection in the list. * * @return the drawable used to display the selector */ public Drawable getSelector() { return mSelector; } /** * {@inheritDoc} */ @Override public int getSelectedItemPosition() { return mNextSelectedPosition; } /** * {@inheritDoc} */ @Override public long getSelectedItemId() { return mNextSelectedRowId; } /** * Returns the number of items currently selected. This will only be valid * if the choice mode is not {@link #CHOICE_MODE_NONE} (default). * * <p>To determine the specific items that are currently selected, use one of * the <code>getChecked*</code> methods. * * @return The number of items currently selected * * @see #getCheckedItemPosition() * @see #getCheckedItemPositions() * @see #getCheckedItemIds() */ public int getCheckedItemCount() { return mCheckedItemCount; } /** * Returns the checked state of the specified position. The result is only * valid if the choice mode has been set to {@link #CHOICE_MODE_SINGLE} * or {@link #CHOICE_MODE_MULTIPLE}. * * @param position The item whose checked state to return * @return The item's checked state or <code>false</code> if choice mode * is invalid * * @see #setChoiceMode(int) */ public boolean isItemChecked(int position) { if (mChoiceMode.compareTo(ChoiceMode.NONE) == 0 && mCheckStates != null) { return mCheckStates.get(position); } return false; } /** * Returns the currently checked item. The result is only valid if the choice * mode has been set to {@link #CHOICE_MODE_SINGLE}. * * @return The position of the currently checked item or * {@link #INVALID_POSITION} if nothing is selected * * @see #setChoiceMode(int) */ public int getCheckedItemPosition() { if (mChoiceMode.compareTo(ChoiceMode.SINGLE) == 0 && mCheckStates != null && mCheckStates.size() == 1) { return mCheckStates.keyAt(0); } return INVALID_POSITION; } /** * Returns the set of checked items in the list. The result is only valid if * the choice mode has not been set to {@link #CHOICE_MODE_NONE}. * * @return A SparseBooleanArray which will return true for each call to * get(int position) where position is a position in the list, * or <code>null</code> if the choice mode is set to * {@link #CHOICE_MODE_NONE}. */ public SparseBooleanArray getCheckedItemPositions() { if (mChoiceMode.compareTo(ChoiceMode.NONE) != 0) { return mCheckStates; } return null; } /** * Returns the set of checked items ids. The result is only valid if the * choice mode has not been set to {@link #CHOICE_MODE_NONE} and the adapter * has stable IDs. ({@link ListAdapter#hasStableIds()} == {@code true}) * * @return A new array which contains the id of each checked item in the * list. */ @SuppressLint("NewApi") public long[] getCheckedItemIds() { if (mChoiceMode.compareTo(ChoiceMode.NONE) == 0 || mCheckedIdStates == null || mAdapter == null) { return new long[0]; } final LongSparseArray<Integer> idStates = mCheckedIdStates; final int count = idStates.size(); final long[] ids = new long[count]; for (int i = 0; i < count; i++) { ids[i] = idStates.keyAt(i); } return ids; } /** * Sets the checked state of the specified position. The is only valid if * the choice mode has been set to {@link #CHOICE_MODE_SINGLE} or * {@link #CHOICE_MODE_MULTIPLE}. * * @param position The item whose checked state is to be checked * @param value The new checked state for the item */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public void setItemChecked(int position, boolean value) { if (mChoiceMode.compareTo(ChoiceMode.NONE) == 0) { return; } if (mChoiceMode.compareTo(ChoiceMode.MULTIPLE) == 0) { boolean oldValue = mCheckStates.get(position); mCheckStates.put(position, value); if (mCheckedIdStates != null && mAdapter.hasStableIds()) { if (value) { mCheckedIdStates.put(mAdapter.getItemId(position), position); } else { mCheckedIdStates.delete(mAdapter.getItemId(position)); } } if (oldValue != value) { if (value) { mCheckedItemCount++; } else { mCheckedItemCount--; } } } else { boolean updateIds = mCheckedIdStates != null && mAdapter.hasStableIds(); // Clear all values if we're checking something, or unchecking the currently // selected item if (value || isItemChecked(position)) { mCheckStates.clear(); if (updateIds) { mCheckedIdStates.clear(); } } // This may end up selecting the value we just cleared but this way // we ensure length of mCheckStates is 1, a fact getCheckedItemPosition relies on if (value) { mCheckStates.put(position, true); if (updateIds) { mCheckedIdStates.put(mAdapter.getItemId(position), position); } mCheckedItemCount = 1; } else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) { mCheckedItemCount = 0; } } // Do not generate a data change while we are in the layout phase if (!mInLayout && !mBlockLayoutRequests) { mDataChanged = true; rememberSyncState(); requestLayout(); } } /** * Clear any choices previously set */ public void clearChoices() { if (mCheckStates != null) { mCheckStates.clear(); } if (mCheckedIdStates != null) { mCheckedIdStates.clear(); } mCheckedItemCount = 0; } /** * @see #setChoiceMode(int) * * @return The current choice mode */ public ChoiceMode getChoiceMode() { return mChoiceMode; } /** * Defines the choice behavior for the List. By default, Lists do not have any choice behavior * ({@link #CHOICE_MODE_NONE}). By setting the choiceMode to {@link #CHOICE_MODE_SINGLE}, the * List allows up to one item to be in a chosen state. By setting the choiceMode to * {@link #CHOICE_MODE_MULTIPLE}, the list allows any number of items to be chosen. * * @param choiceMode One of {@link #CHOICE_MODE_NONE}, {@link #CHOICE_MODE_SINGLE}, or * {@link #CHOICE_MODE_MULTIPLE} */ @SuppressLint("NewApi") public void setChoiceMode(ChoiceMode choiceMode) { mChoiceMode = choiceMode; if (mChoiceMode.compareTo(ChoiceMode.NONE) != 0) { if (mCheckStates == null) { mCheckStates = new SparseBooleanArray(); } if (mCheckedIdStates == null && mAdapter != null && mAdapter.hasStableIds()) { mCheckedIdStates = new LongSparseArray<Integer>(); } } } @Override public ListAdapter getAdapter() { return mAdapter; } @Override public void setAdapter(ListAdapter adapter) { if (mAdapter != null && mDataSetObserver != null) { mAdapter.unregisterDataSetObserver(mDataSetObserver); } resetState(); mRecycler.clear(); mAdapter = adapter; mDataChanged = true; mOldSelectedPosition = INVALID_POSITION; mOldSelectedRowId = INVALID_ROW_ID; if (mCheckStates != null) { mCheckStates.clear(); } if (mCheckedIdStates != null) { mCheckedIdStates.clear(); } if (mAdapter != null) { mOldItemCount = mItemCount; mItemCount = adapter.getCount(); mDataSetObserver = new AdapterDataSetObserver(); mAdapter.registerDataSetObserver(mDataSetObserver); mRecycler.setViewTypeCount(adapter.getViewTypeCount()); mHasStableIds = adapter.hasStableIds(); mAreAllItemsSelectable = adapter.areAllItemsEnabled(); if (mChoiceMode.compareTo(ChoiceMode.NONE) != 0 && mHasStableIds && mCheckedIdStates == null) { mCheckedIdStates = new LongSparseArray<Integer>(); } final int position = lookForSelectablePosition(0); setSelectedPositionInt(position); setNextSelectedPositionInt(position); if (mItemCount == 0) { checkSelectionChanged(); } } else { mItemCount = 0; mHasStableIds = false; mAreAllItemsSelectable = true; checkSelectionChanged(); } checkFocus(); requestLayout(); } @Override public int getFirstVisiblePosition() { return mFirstPosition; } @Override public int getLastVisiblePosition() { return mFirstPosition + getChildCount() - 1; } @Override public int getCount() { return mItemCount; } @Override public int getPositionForView(View view) { View child = view; try { View v; while (!(v = (View) child.getParent()).equals(this)) { child = v; } } catch (ClassCastException e) { // We made it up to the window without find this list view return INVALID_POSITION; } // Search the children for the list item final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { if (getChildAt(i).equals(child)) { return mFirstPosition + i; } } // Child not found! return INVALID_POSITION; } @Override public void getFocusedRect(Rect r) { View view = getSelectedView(); if (view != null && view.getParent() == this) { // The focused rectangle of the selected view offset into the // coordinate space of this view. view.getFocusedRect(r); offsetDescendantRectToMyCoords(view, r); } else { super.getFocusedRect(r); } } @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); if (gainFocus && mSelectedPosition < 0 && !isInTouchMode()) { if (!mIsAttached && mAdapter != null) { // Data may have changed while we were detached and it's valid // to change focus while detached. Refresh so we don't die. mDataChanged = true; mOldItemCount = mItemCount; mItemCount = mAdapter.getCount(); } resurrectSelection(); } final ListAdapter adapter = mAdapter; int closetChildIndex = INVALID_POSITION; int closestChildStart = 0; if (adapter != null && gainFocus && previouslyFocusedRect != null) { previouslyFocusedRect.offset(getScrollX(), getScrollY()); // Don't cache the result of getChildCount or mFirstPosition here, // it could change in layoutChildren. if (adapter.getCount() < getChildCount() + mFirstPosition) { mLayoutMode = LAYOUT_NORMAL; layoutChildren(); } // Figure out which item should be selected based on previously // focused rect. Rect otherRect = mTempRect; int minDistance = Integer.MAX_VALUE; final int childCount = getChildCount(); final int firstPosition = mFirstPosition; for (int i = 0; i < childCount; i++) { // Only consider selectable views if (!adapter.isEnabled(firstPosition + i)) { continue; } View other = getChildAt(i); other.getDrawingRect(otherRect); offsetDescendantRectToMyCoords(other, otherRect); int distance = getDistance(previouslyFocusedRect, otherRect, direction); if (distance < minDistance) { minDistance = distance; closetChildIndex = i; closestChildStart = (mIsVertical ? other.getTop() : other.getLeft()); } } } if (closetChildIndex >= 0) { setSelectionFromOffset(closetChildIndex + mFirstPosition, closestChildStart); } else { requestLayout(); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); final ViewTreeObserver treeObserver = getViewTreeObserver(); treeObserver.addOnTouchModeChangeListener(this); if (mAdapter != null && mDataSetObserver == null) { mDataSetObserver = new AdapterDataSetObserver(); mAdapter.registerDataSetObserver(mDataSetObserver); // Data may have changed while we were detached. Refresh. mDataChanged = true; mOldItemCount = mItemCount; mItemCount = mAdapter.getCount(); } mIsAttached = true; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); // Detach any view left in the scrap heap mRecycler.clear(); final ViewTreeObserver treeObserver = getViewTreeObserver(); treeObserver.removeOnTouchModeChangeListener(this); if (mAdapter != null) { mAdapter.unregisterDataSetObserver(mDataSetObserver); mDataSetObserver = null; } if (mPerformClick != null) { removeCallbacks(mPerformClick); } if (mTouchModeReset != null) { removeCallbacks(mTouchModeReset); mTouchModeReset.run(); } mIsAttached = false; } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); final int touchMode = isInTouchMode() ? TOUCH_MODE_ON : TOUCH_MODE_OFF; if (!hasWindowFocus) { if (touchMode == TOUCH_MODE_OFF) { // Remember the last selected element mResurrectToPosition = mSelectedPosition; } } else { // If we changed touch mode since the last time we had focus if (touchMode != mLastTouchMode && mLastTouchMode != TOUCH_MODE_UNKNOWN) { // If we come back in trackball mode, we bring the selection back if (touchMode == TOUCH_MODE_OFF) { // This will trigger a layout resurrectSelection(); // If we come back in touch mode, then we want to hide the selector } else { hideSelector(); mLayoutMode = LAYOUT_NORMAL; layoutChildren(); } } } mLastTouchMode = touchMode; } @Override protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { boolean needsInvalidate = false; if (mIsVertical && mOverScroll != scrollY) { onScrollChanged(getScrollX(), scrollY, getScrollX(), mOverScroll); mOverScroll = scrollY; needsInvalidate = true; } else if (!mIsVertical && mOverScroll != scrollX) { onScrollChanged(scrollX, getScrollY(), mOverScroll, getScrollY()); mOverScroll = scrollX; needsInvalidate = true; } if (needsInvalidate) { invalidate(); awakenScrollbarsInternal(); } } @TargetApi(9) private boolean overScrollByInternal(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) { if (Build.VERSION.SDK_INT < 9) { return false; } return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent); } @Override @TargetApi(9) public void setOverScrollMode(int mode) { if (Build.VERSION.SDK_INT < 9) { return; } if (mode != ViewCompat.OVER_SCROLL_NEVER) { if (mStartEdge == null) { Context context = getContext(); mStartEdge = new EdgeEffectCompat(context); mEndEdge = new EdgeEffectCompat(context); } } else { mStartEdge = null; mEndEdge = null; } super.setOverScrollMode(mode); } public int pointToPosition(int x, int y) { Rect frame = mTouchFrame; if (frame == null) { mTouchFrame = new Rect(); frame = mTouchFrame; } final int count = getChildCount(); for (int i = count - 1; i >= 0; i--) { final View child = getChildAt(i); if (child.getVisibility() == View.VISIBLE) { child.getHitRect(frame); if (frame.contains(x, y)) { return mFirstPosition + i; } } } return INVALID_POSITION; } @Override protected int computeVerticalScrollExtent() { final int count = getChildCount(); if (count == 0) { return 0; } int extent = count * 100; View child = getChildAt(0); final int childTop = child.getTop(); int childHeight = child.getHeight(); if (childHeight > 0) { extent += (childTop * 100) / childHeight; } child = getChildAt(count - 1); final int childBottom = child.getBottom(); childHeight = child.getHeight(); if (childHeight > 0) { extent -= ((childBottom - getHeight()) * 100) / childHeight; } return extent; } @Override protected int computeHorizontalScrollExtent() { final int count = getChildCount(); if (count == 0) { return 0; } int extent = count * 100; View child = getChildAt(0); final int childLeft = child.getLeft(); int childWidth = child.getWidth(); if (childWidth > 0) { extent += (childLeft * 100) / childWidth; } child = getChildAt(count - 1); final int childRight = child.getRight(); childWidth = child.getWidth(); if (childWidth > 0) { extent -= ((childRight - getWidth()) * 100) / childWidth; } return extent; } @Override protected int computeVerticalScrollOffset() { final int firstPosition = mFirstPosition; final int childCount = getChildCount(); if (firstPosition < 0 || childCount == 0) { return 0; } final View child = getChildAt(0); final int childTop = child.getTop(); int childHeight = child.getHeight(); if (childHeight > 0) { return Math.max(firstPosition * 100 - (childTop * 100) / childHeight, 0); } return 0; } @Override protected int computeHorizontalScrollOffset() { final int firstPosition = mFirstPosition; final int childCount = getChildCount(); if (firstPosition < 0 || childCount == 0) { return 0; } final View child = getChildAt(0); final int childLeft = child.getLeft(); int childWidth = child.getWidth(); if (childWidth > 0) { return Math.max(firstPosition * 100 - (childLeft * 100) / childWidth, 0); } return 0; } @Override protected int computeVerticalScrollRange() { int result = Math.max(mItemCount * 100, 0); if (mIsVertical && mOverScroll != 0) { // Compensate for overscroll result += Math.abs((int) ((float) mOverScroll / getHeight() * mItemCount * 100)); } return result; } @Override protected int computeHorizontalScrollRange() { int result = Math.max(mItemCount * 100, 0); if (!mIsVertical && mOverScroll != 0) { // Compensate for overscroll result += Math.abs((int) ((float) mOverScroll / getWidth() * mItemCount * 100)); } return result; } @Override public boolean showContextMenuForChild(View originalView) { final int longPressPosition = getPositionForView(originalView); if (longPressPosition >= 0) { final long longPressId = mAdapter.getItemId(longPressPosition); boolean handled = false; OnItemLongClickListener listener = getOnItemLongClickListener(); if (listener != null) { handled = listener.onItemLongClick(TwoWayView.this, originalView, longPressPosition, longPressId); } if (!handled) { mContextMenuInfo = createContextMenuInfo( getChildAt(longPressPosition - mFirstPosition), longPressPosition, longPressId); handled = super.showContextMenuForChild(originalView); } return handled; } return false; } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (disallowIntercept) { recycleVelocityTracker(); } super.requestDisallowInterceptTouchEvent(disallowIntercept); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (!mIsAttached) { return false; } final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; switch (action) { case MotionEvent.ACTION_DOWN: initOrResetVelocityTracker(); mVelocityTracker.addMovement(ev); mScroller.abortAnimation(); final float x = ev.getX(); final float y = ev.getY(); mLastTouchPos = (mIsVertical ? y : x); final int motionPosition = findMotionRowOrColumn((int) mLastTouchPos); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mTouchRemainderPos = 0; if (mTouchMode == TOUCH_MODE_FLINGING) { return true; } else if (motionPosition >= 0) { mMotionPosition = motionPosition; mTouchMode = TOUCH_MODE_DOWN; } break; case MotionEvent.ACTION_MOVE: { if (mTouchMode != TOUCH_MODE_DOWN) { break; } initVelocityTrackerIfNotExists(); mVelocityTracker.addMovement(ev); final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId); if (index < 0) { Log.e(LOGTAG, "onInterceptTouchEvent could not find pointer with id " + mActivePointerId + " - did TwoWayView receive an inconsistent " + "event stream?"); return false; } final float pos; if (mIsVertical) { pos = MotionEventCompat.getY(ev, index); } else { pos = MotionEventCompat.getX(ev, index); } final float diff = pos - mLastTouchPos + mTouchRemainderPos; final int delta = (int) diff; mTouchRemainderPos = diff - delta; if (maybeStartScrolling(delta)) { return true; } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: mActivePointerId = INVALID_POINTER; mTouchMode = TOUCH_MODE_REST; recycleVelocityTracker(); reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); break; } return false; } @Override public boolean onTouchEvent(MotionEvent ev) { if (!isEnabled()) { // A disabled view that is clickable still consumes the touch // events, it just doesn't respond to them. return isClickable() || isLongClickable(); } if (!mIsAttached) { return false; } boolean needsInvalidate = false; initVelocityTrackerIfNotExists(); mVelocityTracker.addMovement(ev); final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; switch (action) { case MotionEvent.ACTION_DOWN: { if (mDataChanged) { break; } mVelocityTracker.clear(); mScroller.abortAnimation(); final float x = ev.getX(); final float y = ev.getY(); mLastTouchPos = (mIsVertical ? y : x); int motionPosition = pointToPosition((int) x, (int) y); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mTouchRemainderPos = 0; if (mDataChanged) { break; } if (mTouchMode == TOUCH_MODE_FLINGING) { mTouchMode = TOUCH_MODE_DRAGGING; reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); motionPosition = findMotionRowOrColumn((int) mLastTouchPos); return true; } else if (mMotionPosition >= 0 && mAdapter.isEnabled(mMotionPosition)) { mTouchMode = TOUCH_MODE_DOWN; triggerCheckForTap(); } mMotionPosition = motionPosition; break; } case MotionEvent.ACTION_MOVE: { final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId); if (index < 0) { Log.e(LOGTAG, "onInterceptTouchEvent could not find pointer with id " + mActivePointerId + " - did TwoWayView receive an inconsistent " + "event stream?"); return false; } final float pos; if (mIsVertical) { pos = MotionEventCompat.getY(ev, index); } else { pos = MotionEventCompat.getX(ev, index); } if (mDataChanged) { // Re-sync everything if data has been changed // since the scroll operation can query the adapter. layoutChildren(); } final float diff = pos - mLastTouchPos + mTouchRemainderPos; final int delta = (int) diff; mTouchRemainderPos = diff - delta; switch (mTouchMode) { case TOUCH_MODE_DOWN: case TOUCH_MODE_TAP: case TOUCH_MODE_DONE_WAITING: // Check if we have moved far enough that it looks more like a // scroll than a tap maybeStartScrolling(delta); break; case TOUCH_MODE_DRAGGING: case TOUCH_MODE_OVERSCROLL: mLastTouchPos = pos; maybeScroll(delta); break; } break; } case MotionEvent.ACTION_CANCEL: cancelCheckForTap(); mTouchMode = TOUCH_MODE_REST; reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); setPressed(false); View motionView = this.getChildAt(mMotionPosition - mFirstPosition); if (motionView != null) { motionView.setPressed(false); } if (mStartEdge != null && mEndEdge != null) { needsInvalidate = mStartEdge.onRelease() | mEndEdge.onRelease(); } recycleVelocityTracker(); break; case MotionEvent.ACTION_UP: { switch (mTouchMode) { case TOUCH_MODE_DOWN: case TOUCH_MODE_TAP: case TOUCH_MODE_DONE_WAITING: { final int motionPosition = mMotionPosition; final View child = getChildAt(motionPosition - mFirstPosition); final float x = ev.getX(); final float y = ev.getY(); boolean inList = false; if (mIsVertical) { inList = x > getPaddingLeft() && x < getWidth() - getPaddingRight(); } else { inList = y > getPaddingTop() && y < getHeight() - getPaddingBottom(); } if (child != null && !child.hasFocusable() && inList) { if (mTouchMode != TOUCH_MODE_DOWN) { child.setPressed(false); } if (mPerformClick == null) { mPerformClick = new PerformClick(); } final PerformClick performClick = mPerformClick; performClick.mClickMotionPosition = motionPosition; performClick.rememberWindowAttachCount(); mResurrectToPosition = motionPosition; if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) { if (mTouchMode == TOUCH_MODE_DOWN) { cancelCheckForTap(); } else { cancelCheckForLongPress(); } mLayoutMode = LAYOUT_NORMAL; if (!mDataChanged && mAdapter.isEnabled(motionPosition)) { mTouchMode = TOUCH_MODE_TAP; setPressed(true); positionSelector(mMotionPosition, child); child.setPressed(true); if (mSelector != null) { Drawable d = mSelector.getCurrent(); if (d != null && d instanceof TransitionDrawable) { ((TransitionDrawable) d).resetTransition(); } } if (mTouchModeReset != null) { removeCallbacks(mTouchModeReset); } mTouchModeReset = new Runnable() { @Override public void run() { mTouchMode = TOUCH_MODE_REST; setPressed(false); child.setPressed(false); if (!mDataChanged) { performClick.run(); } mTouchModeReset = null; } }; postDelayed(mTouchModeReset, ViewConfiguration.getPressedStateDuration()); } else { mTouchMode = TOUCH_MODE_REST; updateSelectorState(); } } else if (!mDataChanged && mAdapter.isEnabled(motionPosition)) { performClick.run(); } } mTouchMode = TOUCH_MODE_REST; updateSelectorState(); break; } case TOUCH_MODE_DRAGGING: if (contentFits()) { mTouchMode = TOUCH_MODE_REST; reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); break; } mVelocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); final float velocity; if (mIsVertical) { velocity = VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId); } else { velocity = VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId); } if (Math.abs(velocity) >= mFlingVelocity) { mTouchMode = TOUCH_MODE_FLINGING; reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING); mScroller.fling(0, 0, (int) (mIsVertical ? 0 : velocity), (int) (mIsVertical ? velocity : 0), (mIsVertical ? 0 : Integer.MIN_VALUE), (mIsVertical ? 0 : Integer.MAX_VALUE), (mIsVertical ? Integer.MIN_VALUE : 0), (mIsVertical ? Integer.MAX_VALUE : 0)); mLastTouchPos = 0; needsInvalidate = true; } else { mTouchMode = TOUCH_MODE_REST; reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); } break; case TOUCH_MODE_OVERSCROLL: mTouchMode = TOUCH_MODE_REST; reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); break; } cancelCheckForTap(); cancelCheckForLongPress(); setPressed(false); if (mStartEdge != null && mEndEdge != null) { needsInvalidate |= mStartEdge.onRelease() | mEndEdge.onRelease(); } recycleVelocityTracker(); break; } } if (needsInvalidate) { ViewCompat.postInvalidateOnAnimation(this); } return true; } @Override public void onTouchModeChanged(boolean isInTouchMode) { if (isInTouchMode) { // Get rid of the selection when we enter touch mode hideSelector(); // Layout, but only if we already have done so previously. // (Otherwise may clobber a LAYOUT_SYNC layout that was requested to restore // state.) if (getWidth() > 0 && getHeight() > 0 && getChildCount() > 0) { layoutChildren(); } updateSelectorState(); } else { final int touchMode = mTouchMode; if (touchMode == TOUCH_MODE_OVERSCROLL) { if (mOverScroll != 0) { mOverScroll = 0; finishEdgeGlows(); invalidate(); } } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return handleKeyEvent(keyCode, 1, event); } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return handleKeyEvent(keyCode, repeatCount, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { return handleKeyEvent(keyCode, 1, event); } @Override public void sendAccessibilityEvent(int eventType) { // Since this class calls onScrollChanged even if the mFirstPosition and the // child count have not changed we will avoid sending duplicate accessibility // events. if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) { final int firstVisiblePosition = getFirstVisiblePosition(); final int lastVisiblePosition = getLastVisiblePosition(); if (mLastAccessibilityScrollEventFromIndex == firstVisiblePosition && mLastAccessibilityScrollEventToIndex == lastVisiblePosition) { return; } else { mLastAccessibilityScrollEventFromIndex = firstVisiblePosition; mLastAccessibilityScrollEventToIndex = lastVisiblePosition; } } super.sendAccessibilityEvent(eventType); } @Override @TargetApi(14) public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(TwoWayView.class.getName()); } @Override @TargetApi(14) public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName(TwoWayView.class.getName()); AccessibilityNodeInfoCompat infoCompat = new AccessibilityNodeInfoCompat(info); if (isEnabled()) { if (getFirstVisiblePosition() > 0) { infoCompat.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); } if (getLastVisiblePosition() < getCount() - 1) { infoCompat.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); } } } @Override @TargetApi(16) public boolean performAccessibilityAction(int action, Bundle arguments) { if (super.performAccessibilityAction(action, arguments)) { return true; } switch (action) { case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: if (isEnabled() && getLastVisiblePosition() < getCount() - 1) { final int viewportSize; if (mIsVertical) { viewportSize = getHeight() - getPaddingTop() - getPaddingBottom(); } else { viewportSize = getWidth() - getPaddingLeft() - getPaddingRight(); } // TODO: Use some form of smooth scroll instead scrollListItemsBy(viewportSize); return true; } return false; case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: if (isEnabled() && mFirstPosition > 0) { final int viewportSize; if (mIsVertical) { viewportSize = getHeight() - getPaddingTop() - getPaddingBottom(); } else { viewportSize = getWidth() - getPaddingLeft() - getPaddingRight(); } // TODO: Use some form of smooth scroll instead scrollListItemsBy(-viewportSize); return true; } return false; } return false; } /** * Return true if child is an ancestor of parent, (or equal to the parent). */ private boolean isViewAncestorOf(View child, View parent) { if (child == parent) { return true; } final ViewParent theParent = child.getParent(); return (theParent instanceof ViewGroup) && isViewAncestorOf((View) theParent, parent); } private void forceValidFocusDirection(int direction) { if (mIsVertical && direction != View.FOCUS_UP && direction != View.FOCUS_DOWN) { throw new IllegalArgumentException("Focus direction must be one of" + " {View.FOCUS_UP, View.FOCUS_DOWN} for vertical orientation"); } else if (!mIsVertical && direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT) { throw new IllegalArgumentException("Focus direction must be one of" + " {View.FOCUS_LEFT, View.FOCUS_RIGHT} for vertical orientation"); } } private void forceValidInnerFocusDirection(int direction) { if (mIsVertical && direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT) { throw new IllegalArgumentException("Direction must be one of" + " {View.FOCUS_LEFT, View.FOCUS_RIGHT} for vertical orientation"); } else if (!mIsVertical && direction != View.FOCUS_UP && direction != View.FOCUS_DOWN) { throw new IllegalArgumentException("direction must be one of" + " {View.FOCUS_UP, View.FOCUS_DOWN} for horizontal orientation"); } } /** * Scrolls up or down by the number of items currently present on screen. * * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the * current view orientation. * * @return whether selection was moved */ boolean pageScroll(int direction) { forceValidFocusDirection(direction); boolean forward = false; int nextPage = -1; if (direction == View.FOCUS_UP || direction == View.FOCUS_LEFT) { nextPage = Math.max(0, mSelectedPosition - getChildCount() - 1); } else if (direction == View.FOCUS_DOWN || direction == View.FOCUS_RIGHT) { nextPage = Math.min(mItemCount - 1, mSelectedPosition + getChildCount() - 1); forward = true; } if (nextPage < 0) { return false; } final int position = lookForSelectablePosition(nextPage, forward); if (position >= 0) { mLayoutMode = LAYOUT_SPECIFIC; mSpecificStart = (mIsVertical ? getPaddingTop() : getPaddingLeft()); if (forward && position > mItemCount - getChildCount()) { mLayoutMode = LAYOUT_FORCE_BOTTOM; } if (!forward && position < getChildCount()) { mLayoutMode = LAYOUT_FORCE_TOP; } setSelectionInt(position); invokeOnItemScrollListener(); if (!awakenScrollbarsInternal()) { invalidate(); } return true; } return false; } /** * Go to the last or first item if possible (not worrying about panning across or navigating * within the internal focus of the currently selected item.) * * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the * current view orientation. * * @return whether selection was moved */ boolean fullScroll(int direction) { forceValidFocusDirection(direction); boolean moved = false; if (direction == View.FOCUS_UP || direction == View.FOCUS_LEFT) { if (mSelectedPosition != 0) { int position = lookForSelectablePosition(0, true); if (position >= 0) { mLayoutMode = LAYOUT_FORCE_TOP; setSelectionInt(position); invokeOnItemScrollListener(); } moved = true; } } else if (direction == View.FOCUS_DOWN || direction == View.FOCUS_RIGHT) { if (mSelectedPosition < mItemCount - 1) { int position = lookForSelectablePosition(mItemCount - 1, true); if (position >= 0) { mLayoutMode = LAYOUT_FORCE_BOTTOM; setSelectionInt(position); invokeOnItemScrollListener(); } moved = true; } } if (moved && !awakenScrollbarsInternal()) { awakenScrollbarsInternal(); invalidate(); } return moved; } /** * To avoid horizontal/vertical focus searches changing the selected item, * we manually focus search within the selected item (as applicable), and * prevent focus from jumping to something within another item. * * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the * current view orientation. * * @return Whether this consumes the key event. */ private boolean handleFocusWithinItem(int direction) { forceValidInnerFocusDirection(direction); final int numChildren = getChildCount(); if (mItemsCanFocus && numChildren > 0 && mSelectedPosition != INVALID_POSITION) { final View selectedView = getSelectedView(); if (selectedView != null && selectedView.hasFocus() && selectedView instanceof ViewGroup) { final View currentFocus = selectedView.findFocus(); final View nextFocus = FocusFinder.getInstance().findNextFocus( (ViewGroup) selectedView, currentFocus, direction); if (nextFocus != null) { // Do the math to get interesting rect in next focus' coordinates currentFocus.getFocusedRect(mTempRect); offsetDescendantRectToMyCoords(currentFocus, mTempRect); offsetRectIntoDescendantCoords(nextFocus, mTempRect); if (nextFocus.requestFocus(direction, mTempRect)) { return true; } } // We are blocking the key from being handled (by returning true) // if the global result is going to be some other view within this // list. This is to achieve the overall goal of having horizontal/vertical // d-pad navigation remain in the current item depending on the current // orientation in this view. final View globalNextFocus = FocusFinder.getInstance().findNextFocus( (ViewGroup) getRootView(), currentFocus, direction); if (globalNextFocus != null) { return isViewAncestorOf(globalNextFocus, this); } } } return false; } /** * Scrolls to the next or previous item if possible. * * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the * current view orientation. * * @return whether selection was moved */ private boolean arrowScroll(int direction) { forceValidFocusDirection(direction); try { mInLayout = true; final boolean handled = arrowScrollImpl(direction); if (handled) { playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction)); } return handled; } finally { mInLayout = false; } } /** * When selection changes, it is possible that the previously selected or the * next selected item will change its size. If so, we need to offset some folks, * and re-layout the items as appropriate. * * @param selectedView The currently selected view (before changing selection). * should be <code>null</code> if there was no previous selection. * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the * current view orientation. * @param newSelectedPosition The position of the next selection. * @param newFocusAssigned whether new focus was assigned. This matters because * when something has focus, we don't want to show selection (ugh). */ private void handleNewSelectionChange(View selectedView, int direction, int newSelectedPosition, boolean newFocusAssigned) { forceValidFocusDirection(direction); if (newSelectedPosition == INVALID_POSITION) { throw new IllegalArgumentException("newSelectedPosition needs to be valid"); } // Whether or not we are moving down/right or up/left, we want to preserve the // top/left of whatever view is at the start: // - moving down/right: the view that had selection // - moving up/left: the view that is getting selection final int selectedIndex = mSelectedPosition - mFirstPosition; final int nextSelectedIndex = newSelectedPosition - mFirstPosition; int startViewIndex, endViewIndex; boolean topSelected = false; View startView; View endView; if (direction == View.FOCUS_UP || direction == View.FOCUS_LEFT) { startViewIndex = nextSelectedIndex; endViewIndex = selectedIndex; startView = getChildAt(startViewIndex); endView = selectedView; topSelected = true; } else { startViewIndex = selectedIndex; endViewIndex = nextSelectedIndex; startView = selectedView; endView = getChildAt(endViewIndex); } final int numChildren = getChildCount(); // start with top view: is it changing size? if (startView != null) { startView.setSelected(!newFocusAssigned && topSelected); measureAndAdjustDown(startView, startViewIndex, numChildren); } // is the bottom view changing size? if (endView != null) { endView.setSelected(!newFocusAssigned && !topSelected); measureAndAdjustDown(endView, endViewIndex, numChildren); } } /** * Re-measure a child, and if its height changes, lay it out preserving its * top, and adjust the children below it appropriately. * * @param child The child * @param childIndex The view group index of the child. * @param numChildren The number of children in the view group. */ private void measureAndAdjustDown(View child, int childIndex, int numChildren) { int oldHeight = child.getHeight(); measureChild(child); if (child.getMeasuredHeight() == oldHeight) { return; } // lay out the view, preserving its top relayoutMeasuredChild(child); // adjust views below appropriately final int heightDelta = child.getMeasuredHeight() - oldHeight; for (int i = childIndex + 1; i < numChildren; i++) { getChildAt(i).offsetTopAndBottom(heightDelta); } } /** * Do an arrow scroll based on focus searching. If a new view is * given focus, return the selection delta and amount to scroll via * an {@link ArrowScrollFocusResult}, otherwise, return null. * * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the * current view orientation. * * @return The result if focus has changed, or <code>null</code>. */ private ArrowScrollFocusResult arrowScrollFocused(final int direction) { forceValidFocusDirection(direction); final View selectedView = getSelectedView(); final View newFocus; final int searchPoint; if (selectedView != null && selectedView.hasFocus()) { View oldFocus = selectedView.findFocus(); newFocus = FocusFinder.getInstance().findNextFocus(this, oldFocus, direction); } else { if (direction == View.FOCUS_DOWN || direction == View.FOCUS_RIGHT) { final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft()); final int selectedStart; if (selectedView != null) { selectedStart = (mIsVertical ? selectedView.getTop() : selectedView.getLeft()); } else { selectedStart = start; } searchPoint = Math.max(selectedStart, start); } else { final int end = (mIsVertical ? getHeight() - getPaddingBottom() : getWidth() - getPaddingRight()); final int selectedEnd; if (selectedView != null) { selectedEnd = (mIsVertical ? selectedView.getBottom() : selectedView.getRight()); } else { selectedEnd = end; } searchPoint = Math.min(selectedEnd, end); } final int x = (mIsVertical ? 0 : searchPoint); final int y = (mIsVertical ? searchPoint : 0); mTempRect.set(x, y, x, y); newFocus = FocusFinder.getInstance().findNextFocusFromRect(this, mTempRect, direction); } if (newFocus != null) { final int positionOfNewFocus = positionOfNewFocus(newFocus); // If the focus change is in a different new position, make sure // we aren't jumping over another selectable position. if (mSelectedPosition != INVALID_POSITION && positionOfNewFocus != mSelectedPosition) { final int selectablePosition = lookForSelectablePositionOnScreen(direction); final boolean movingForward = (direction == View.FOCUS_DOWN || direction == View.FOCUS_RIGHT); final boolean movingBackward = (direction == View.FOCUS_UP || direction == View.FOCUS_LEFT); if (selectablePosition != INVALID_POSITION && ((movingForward && selectablePosition < positionOfNewFocus) || (movingBackward && selectablePosition > positionOfNewFocus))) { return null; } } int focusScroll = amountToScrollToNewFocus(direction, newFocus, positionOfNewFocus); final int maxScrollAmount = getMaxScrollAmount(); if (focusScroll < maxScrollAmount) { // Not moving too far, safe to give next view focus newFocus.requestFocus(direction); mArrowScrollFocusResult.populate(positionOfNewFocus, focusScroll); return mArrowScrollFocusResult; } else if (distanceToView(newFocus) < maxScrollAmount){ // Case to consider: // Too far to get entire next focusable on screen, but by going // max scroll amount, we are getting it at least partially in view, // so give it focus and scroll the max amount. newFocus.requestFocus(direction); mArrowScrollFocusResult.populate(positionOfNewFocus, maxScrollAmount); return mArrowScrollFocusResult; } } return null; } /** * @return The maximum amount a list view will scroll in response to * an arrow event. */ public int getMaxScrollAmount() { return (int) (MAX_SCROLL_FACTOR * getHeight()); } /** * @return The amount to preview next items when arrow scrolling. */ private int getArrowScrollPreviewLength() { // FIXME: TwoWayView has no fading edge support just yet but using it // makes it convenient for defining the next item's previous length. int fadingEdgeLength = (mIsVertical ? getVerticalFadingEdgeLength() : getHorizontalFadingEdgeLength()); return mItemMargin + Math.max(MIN_SCROLL_PREVIEW_PIXELS, fadingEdgeLength); } /** * @param newFocus The view that would have focus. * @return the position that contains newFocus */ private int positionOfNewFocus(View newFocus) { final int numChildren = getChildCount(); for (int i = 0; i < numChildren; i++) { final View child = getChildAt(i); if (isViewAncestorOf(newFocus, child)) { return mFirstPosition + i; } } throw new IllegalArgumentException("newFocus is not a child of any of the" + " children of the list!"); } /** * Handle an arrow scroll going up or down. Take into account whether items are selectable, * whether there are focusable items, etc. * * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the * current view orientation. * * @return Whether any scrolling, selection or focus change occurred. */ private boolean arrowScrollImpl(int direction) { forceValidFocusDirection(direction); if (getChildCount() <= 0) { return false; } View selectedView = getSelectedView(); int selectedPos = mSelectedPosition; int nextSelectedPosition = lookForSelectablePositionOnScreen(direction); int amountToScroll = amountToScroll(direction, nextSelectedPosition); // If we are moving focus, we may OVERRIDE the default behaviour final ArrowScrollFocusResult focusResult = (mItemsCanFocus ? arrowScrollFocused(direction) : null); if (focusResult != null) { nextSelectedPosition = focusResult.getSelectedPosition(); amountToScroll = focusResult.getAmountToScroll(); } boolean needToRedraw = (focusResult != null); if (nextSelectedPosition != INVALID_POSITION) { handleNewSelectionChange(selectedView, direction, nextSelectedPosition, focusResult != null); setSelectedPositionInt(nextSelectedPosition); setNextSelectedPositionInt(nextSelectedPosition); selectedView = getSelectedView(); selectedPos = nextSelectedPosition; if (mItemsCanFocus && focusResult == null) { // There was no new view found to take focus, make sure we // don't leave focus with the old selection. final View focused = getFocusedChild(); if (focused != null) { focused.clearFocus(); } } needToRedraw = true; checkSelectionChanged(); } if (amountToScroll > 0) { scrollListItemsBy(direction == View.FOCUS_UP || direction == View.FOCUS_LEFT ? amountToScroll : -amountToScroll); needToRedraw = true; } // If we didn't find a new focusable, make sure any existing focused // item that was panned off screen gives up focus. if (mItemsCanFocus && focusResult == null && selectedView != null && selectedView.hasFocus()) { final View focused = selectedView.findFocus(); if (!isViewAncestorOf(focused, this) || distanceToView(focused) > 0) { focused.clearFocus(); } } // If the current selection is panned off, we need to remove the selection if (nextSelectedPosition == INVALID_POSITION && selectedView != null && !isViewAncestorOf(selectedView, this)) { selectedView = null; hideSelector(); // But we don't want to set the ressurect position (that would make subsequent // unhandled key events bring back the item we just scrolled off) mResurrectToPosition = INVALID_POSITION; } if (needToRedraw) { if (selectedView != null) { positionSelector(selectedPos, selectedView); mSelectedStart = selectedView.getTop(); } if (!awakenScrollbarsInternal()) { invalidate(); } invokeOnItemScrollListener(); return true; } return false; } /** * Determine how much we need to scroll in order to get the next selected view * visible. The amount is capped at {@link #getMaxScrollAmount()}. * * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the * current view orientation. * @param nextSelectedPosition The position of the next selection, or * {@link #INVALID_POSITION} if there is no next selectable position * * @return The amount to scroll. Note: this is always positive! Direction * needs to be taken into account when actually scrolling. */ private int amountToScroll(int direction, int nextSelectedPosition) { forceValidFocusDirection(direction); final int numChildren = getChildCount(); if (direction == View.FOCUS_DOWN || direction == View.FOCUS_RIGHT) { final int end = (mIsVertical ? getHeight() - getPaddingBottom() : getWidth() - getPaddingRight()); int indexToMakeVisible = numChildren - 1; if (nextSelectedPosition != INVALID_POSITION) { indexToMakeVisible = nextSelectedPosition - mFirstPosition; } final int positionToMakeVisible = mFirstPosition + indexToMakeVisible; final View viewToMakeVisible = getChildAt(indexToMakeVisible); int goalEnd = end; if (positionToMakeVisible < mItemCount - 1) { goalEnd -= getArrowScrollPreviewLength(); } final int viewToMakeVisibleStart = (mIsVertical ? viewToMakeVisible.getTop() : viewToMakeVisible.getLeft()); final int viewToMakeVisibleEnd = (mIsVertical ? viewToMakeVisible.getBottom() : viewToMakeVisible.getRight()); if (viewToMakeVisibleEnd <= goalEnd) { // Target item is fully visible return 0; } if (nextSelectedPosition != INVALID_POSITION && (goalEnd - viewToMakeVisibleStart) >= getMaxScrollAmount()) { // Item already has enough of it visible, changing selection is good enough return 0; } int amountToScroll = (viewToMakeVisibleEnd - goalEnd); if (mFirstPosition + numChildren == mItemCount) { final View lastChild = getChildAt(numChildren - 1); final int lastChildEnd = (mIsVertical ? lastChild.getBottom() : lastChild.getRight()); // Last is last in list -> Make sure we don't scroll past it final int max = lastChildEnd - end; amountToScroll = Math.min(amountToScroll, max); } return Math.min(amountToScroll, getMaxScrollAmount()); } else { final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft()); int indexToMakeVisible = 0; if (nextSelectedPosition != INVALID_POSITION) { indexToMakeVisible = nextSelectedPosition - mFirstPosition; } final int positionToMakeVisible = mFirstPosition + indexToMakeVisible; final View viewToMakeVisible = getChildAt(indexToMakeVisible); int goalStart = start; if (positionToMakeVisible > 0) { goalStart += getArrowScrollPreviewLength(); } final int viewToMakeVisibleStart = (mIsVertical ? viewToMakeVisible.getTop() : viewToMakeVisible.getLeft()); final int viewToMakeVisibleEnd = (mIsVertical ? viewToMakeVisible.getBottom() : viewToMakeVisible.getRight()); if (viewToMakeVisibleStart >= goalStart) { // Item is fully visible return 0; } if (nextSelectedPosition != INVALID_POSITION && (viewToMakeVisibleEnd - goalStart) >= getMaxScrollAmount()) { // Item already has enough of it visible, changing selection is good enough return 0; } int amountToScroll = (goalStart - viewToMakeVisibleStart); if (mFirstPosition == 0) { final View firstChild = getChildAt(0); final int firstChildStart = (mIsVertical ? firstChild.getTop() : firstChild.getLeft()); // First is first in list -> make sure we don't scroll past it final int max = start - firstChildStart; amountToScroll = Math.min(amountToScroll, max); } return Math.min(amountToScroll, getMaxScrollAmount()); } } /** * Determine how much we need to scroll in order to get newFocus in view. * * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the * current view orientation. * @param newFocus The view that would take focus. * @param positionOfNewFocus The position of the list item containing newFocus * * @return The amount to scroll. Note: this is always positive! Direction * needs to be taken into account when actually scrolling. */ private int amountToScrollToNewFocus(int direction, View newFocus, int positionOfNewFocus) { forceValidFocusDirection(direction); int amountToScroll = 0; newFocus.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(newFocus, mTempRect); if (direction == View.FOCUS_UP || direction == View.FOCUS_LEFT) { final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft()); final int newFocusStart = (mIsVertical ? mTempRect.top : mTempRect.left); if (newFocusStart < start) { amountToScroll = start - newFocusStart; if (positionOfNewFocus > 0) { amountToScroll += getArrowScrollPreviewLength(); } } } else { final int end = (mIsVertical ? getHeight() - getPaddingBottom() : getWidth() - getPaddingRight()); final int newFocusEnd = (mIsVertical ? mTempRect.bottom : mTempRect.right); if (newFocusEnd > end) { amountToScroll = newFocusEnd - end; if (positionOfNewFocus < mItemCount - 1) { amountToScroll += getArrowScrollPreviewLength(); } } } return amountToScroll; } /** * Determine the distance to the nearest edge of a view in a particular * direction. * * @param descendant A descendant of this list. * @return The distance, or 0 if the nearest edge is already on screen. */ private int distanceToView(View descendant) { descendant.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(descendant, mTempRect); final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft()); final int end = (mIsVertical ? getHeight() - getPaddingBottom() : getWidth() - getPaddingRight()); final int viewStart = (mIsVertical ? mTempRect.top : mTempRect.left); final int viewEnd = (mIsVertical ? mTempRect.bottom : mTempRect.right); int distance = 0; if (viewEnd < start) { distance = start - viewEnd; } else if (viewStart > end) { distance = viewStart - end; } return distance; } private boolean handleKeyScroll(KeyEvent event, int count, int direction) { boolean handled = false; if (KeyEventCompat.hasNoModifiers(event)) { handled = resurrectSelectionIfNeeded(); if (!handled) { while (count-- > 0) { if (arrowScroll(direction)) { handled = true; } else { break; } } } } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_ALT_ON)) { handled = resurrectSelectionIfNeeded() || fullScroll(direction); } return handled; } private boolean handleKeyEvent(int keyCode, int count, KeyEvent event) { if (mAdapter == null || !mIsAttached) { return false; } if (mDataChanged) { layoutChildren(); } boolean handled = false; final int action = event.getAction(); if (action != KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_UP: if (mIsVertical) { handled = handleKeyScroll(event, count, View.FOCUS_UP); } else if (KeyEventCompat.hasNoModifiers(event)) { handled = handleFocusWithinItem(View.FOCUS_UP); } break; case KeyEvent.KEYCODE_DPAD_DOWN: { if (mIsVertical) { handled = handleKeyScroll(event, count, View.FOCUS_DOWN); } else if (KeyEventCompat.hasNoModifiers(event)) { handled = handleFocusWithinItem(View.FOCUS_DOWN); } break; } case KeyEvent.KEYCODE_DPAD_LEFT: if (!mIsVertical) { handled = handleKeyScroll(event, count, View.FOCUS_LEFT); } else if (KeyEventCompat.hasNoModifiers(event)) { handled = handleFocusWithinItem(View.FOCUS_LEFT); } break; case KeyEvent.KEYCODE_DPAD_RIGHT: if (!mIsVertical) { handled = handleKeyScroll(event, count, View.FOCUS_RIGHT); } else if (KeyEventCompat.hasNoModifiers(event)) { handled = handleFocusWithinItem(View.FOCUS_RIGHT); } break; case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: if (KeyEventCompat.hasNoModifiers(event)) { handled = resurrectSelectionIfNeeded(); if (!handled && event.getRepeatCount() == 0 && getChildCount() > 0) { keyPressed(); handled = true; } } break; case KeyEvent.KEYCODE_SPACE: if (KeyEventCompat.hasNoModifiers(event)) { handled = resurrectSelectionIfNeeded() || pageScroll(mIsVertical ? View.FOCUS_DOWN : View.FOCUS_RIGHT); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { handled = resurrectSelectionIfNeeded() || fullScroll(mIsVertical ? View.FOCUS_UP : View.FOCUS_LEFT); } handled = true; break; case KeyEvent.KEYCODE_PAGE_UP: if (KeyEventCompat.hasNoModifiers(event)) { handled = resurrectSelectionIfNeeded() || pageScroll(mIsVertical ? View.FOCUS_UP : View.FOCUS_LEFT); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_ALT_ON)) { handled = resurrectSelectionIfNeeded() || fullScroll(mIsVertical ? View.FOCUS_UP : View.FOCUS_LEFT); } break; case KeyEvent.KEYCODE_PAGE_DOWN: if (KeyEventCompat.hasNoModifiers(event)) { handled = resurrectSelectionIfNeeded() || pageScroll(mIsVertical ? View.FOCUS_DOWN : View.FOCUS_RIGHT); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_ALT_ON)) { handled = resurrectSelectionIfNeeded() || fullScroll(mIsVertical ? View.FOCUS_DOWN : View.FOCUS_RIGHT); } break; case KeyEvent.KEYCODE_MOVE_HOME: if (KeyEventCompat.hasNoModifiers(event)) { handled = resurrectSelectionIfNeeded() || fullScroll(mIsVertical ? View.FOCUS_UP : View.FOCUS_LEFT); } break; case KeyEvent.KEYCODE_MOVE_END: if (KeyEventCompat.hasNoModifiers(event)) { handled = resurrectSelectionIfNeeded() || fullScroll(mIsVertical ? View.FOCUS_DOWN : View.FOCUS_RIGHT); } break; } } if (handled) { return true; } switch (action) { case KeyEvent.ACTION_DOWN: return super.onKeyDown(keyCode, event); case KeyEvent.ACTION_UP: if (!isEnabled()) { return true; } if (isClickable() && isPressed() && mSelectedPosition >= 0 && mAdapter != null && mSelectedPosition < mAdapter.getCount()) { final View child = getChildAt(mSelectedPosition - mFirstPosition); if (child != null) { performItemClick(child, mSelectedPosition, mSelectedRowId); child.setPressed(false); } setPressed(false); return true; } return false; case KeyEvent.ACTION_MULTIPLE: return super.onKeyMultiple(keyCode, count, event); default: return false; } } private void initOrResetVelocityTracker() { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } else { mVelocityTracker.clear(); } } private void initVelocityTrackerIfNotExists() { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } } private void recycleVelocityTracker() { if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } /** * Notify our scroll listener (if there is one) of a change in scroll state */ private void invokeOnItemScrollListener() { if (mOnScrollListener != null) { mOnScrollListener.onScroll(this, mFirstPosition, getChildCount(), mItemCount); } // Dummy values, View's implementation does not use these. onScrollChanged(0, 0, 0, 0); } private void reportScrollStateChange(int newState) { if (newState == mLastScrollState) { return; } if (mOnScrollListener != null) { mLastScrollState = newState; mOnScrollListener.onScrollStateChanged(this, newState); } } private boolean maybeStartScrolling(int delta) { final boolean isOverScroll = (mOverScroll != 0); if (Math.abs(delta) <= mTouchSlop && !isOverScroll) { return false; } if (isOverScroll) { mTouchMode = TOUCH_MODE_OVERSCROLL; } else { mTouchMode = TOUCH_MODE_DRAGGING; } // Time to start stealing events! Once we've stolen them, don't // let anyone steal from us. final ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } cancelCheckForLongPress(); setPressed(false); View motionView = getChildAt(mMotionPosition - mFirstPosition); if (motionView != null) { motionView.setPressed(false); } reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); return true; } private void maybeScroll(int delta) { if (mTouchMode == TOUCH_MODE_DRAGGING) { handleDragChange(delta); } else if (mTouchMode == TOUCH_MODE_OVERSCROLL) { handleOverScrollChange(delta); } } private void handleDragChange(int delta) { // Time to start stealing events! Once we've stolen them, don't // let anyone steal from us. final ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } final int motionIndex; if (mMotionPosition >= 0) { motionIndex = mMotionPosition - mFirstPosition; } else { // If we don't have a motion position that we can reliably track, // pick something in the middle to make a best guess at things below. motionIndex = getChildCount() / 2; } int motionViewPrevStart = 0; View motionView = this.getChildAt(motionIndex); if (motionView != null) { motionViewPrevStart = (mIsVertical ? motionView.getTop() : motionView.getLeft()); } boolean atEdge = scrollListItemsBy(delta); motionView = this.getChildAt(motionIndex); if (motionView != null) { final int motionViewRealStart = (mIsVertical ? motionView.getTop() : motionView.getLeft()); if (atEdge) { final int overscroll = -delta - (motionViewRealStart - motionViewPrevStart); updateOverScrollState(delta, overscroll); } } } private void updateOverScrollState(int delta, int overscroll) { overScrollByInternal((mIsVertical ? 0 : overscroll), (mIsVertical ? overscroll : 0), (mIsVertical ? 0 : mOverScroll), (mIsVertical ? mOverScroll : 0), 0, 0, (mIsVertical ? 0 : mOverscrollDistance), (mIsVertical ? mOverscrollDistance : 0), true); if (Math.abs(mOverscrollDistance) == Math.abs(mOverScroll)) { // Break fling velocity if we impacted an edge if (mVelocityTracker != null) { mVelocityTracker.clear(); } } final int overscrollMode = ViewCompat.getOverScrollMode(this); if (overscrollMode == ViewCompat.OVER_SCROLL_ALWAYS || (overscrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS && !contentFits())) { mTouchMode = TOUCH_MODE_OVERSCROLL; float pull = (float) overscroll / (mIsVertical ? getHeight() : getWidth()); if (delta > 0) { mStartEdge.onPull(pull); if (!mEndEdge.isFinished()) { mEndEdge.onRelease(); } } else if (delta < 0) { mEndEdge.onPull(pull); if (!mStartEdge.isFinished()) { mStartEdge.onRelease(); } } if (delta != 0) { ViewCompat.postInvalidateOnAnimation(this); } } } private void handleOverScrollChange(int delta) { final int oldOverScroll = mOverScroll; final int newOverScroll = oldOverScroll - delta; int overScrollDistance = -delta; if ((newOverScroll < 0 && oldOverScroll >= 0) || (newOverScroll > 0 && oldOverScroll <= 0)) { overScrollDistance = -oldOverScroll; delta += overScrollDistance; } else { delta = 0; } if (overScrollDistance != 0) { updateOverScrollState(delta, overScrollDistance); } if (delta != 0) { if (mOverScroll != 0) { mOverScroll = 0; ViewCompat.postInvalidateOnAnimation(this); } scrollListItemsBy(delta); mTouchMode = TOUCH_MODE_DRAGGING; // We did not scroll the full amount. Treat this essentially like the // start of a new touch scroll mMotionPosition = findClosestMotionRowOrColumn((int) mLastTouchPos); mTouchRemainderPos = 0; } } /** * What is the distance between the source and destination rectangles given the direction of * focus navigation between them? The direction basically helps figure out more quickly what is * self evident by the relationship between the rects... * * @param source the source rectangle * @param dest the destination rectangle * @param direction the direction * @return the distance between the rectangles */ private static int getDistance(Rect source, Rect dest, int direction) { int sX, sY; // source x, y int dX, dY; // dest x, y switch (direction) { case View.FOCUS_RIGHT: sX = source.right; sY = source.top + source.height() / 2; dX = dest.left; dY = dest.top + dest.height() / 2; break; case View.FOCUS_DOWN: sX = source.left + source.width() / 2; sY = source.bottom; dX = dest.left + dest.width() / 2; dY = dest.top; break; case View.FOCUS_LEFT: sX = source.left; sY = source.top + source.height() / 2; dX = dest.right; dY = dest.top + dest.height() / 2; break; case View.FOCUS_UP: sX = source.left + source.width() / 2; sY = source.top; dX = dest.left + dest.width() / 2; dY = dest.bottom; break; case View.FOCUS_FORWARD: case View.FOCUS_BACKWARD: sX = source.right + source.width() / 2; sY = source.top + source.height() / 2; dX = dest.left + dest.width() / 2; dY = dest.top + dest.height() / 2; break; default: throw new IllegalArgumentException("direction must be one of " + "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, " + "FOCUS_FORWARD, FOCUS_BACKWARD}."); } int deltaX = dX - sX; int deltaY = dY - sY; return deltaY * deltaY + deltaX * deltaX; } private int findMotionRowOrColumn(int motionPos) { int childCount = getChildCount(); if (childCount == 0) { return INVALID_POSITION; } for (int i = 0; i < childCount; i++) { View v = getChildAt(i); if ((mIsVertical && motionPos <= v.getBottom()) || (!mIsVertical && motionPos <= v.getRight())) { return mFirstPosition + i; } } return INVALID_POSITION; } private int findClosestMotionRowOrColumn(int motionPos) { final int childCount = getChildCount(); if (childCount == 0) { return INVALID_POSITION; } final int motionRow = findMotionRowOrColumn(motionPos); if (motionRow != INVALID_POSITION) { return motionRow; } else { return mFirstPosition + childCount - 1; } } @TargetApi(9) private int getScaledOverscrollDistance(ViewConfiguration vc) { if (Build.VERSION.SDK_INT < 9) { return 0; } return vc.getScaledOverscrollDistance(); } private boolean contentFits() { final int childCount = getChildCount(); if (childCount == 0) { return true; } if (childCount != mItemCount) { return false; } View first = getChildAt(0); View last = getChildAt(childCount - 1); if (mIsVertical) { return first.getTop() >= getPaddingTop() && last.getBottom() <= getHeight() - getPaddingBottom(); } else { return first.getLeft() >= getPaddingLeft() && last.getRight() <= getWidth() - getPaddingRight(); } } private void updateScrollbarsDirection() { setHorizontalScrollBarEnabled(false); setVerticalScrollBarEnabled(false); } private void triggerCheckForTap() { if (mPendingCheckForTap == null) { mPendingCheckForTap = new CheckForTap(); } postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); } private void cancelCheckForTap() { if (mPendingCheckForTap == null) { return; } removeCallbacks(mPendingCheckForTap); } private void triggerCheckForLongPress() { if (mPendingCheckForLongPress == null) { mPendingCheckForLongPress = new CheckForLongPress(); } mPendingCheckForLongPress.rememberWindowAttachCount(); postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout()); } private void cancelCheckForLongPress() { if (mPendingCheckForLongPress == null) { return; } removeCallbacks(mPendingCheckForLongPress); } private boolean scrollListItemsBy(int incrementalDelta) { final int childCount = getChildCount(); if (childCount == 0) { return true; } final View first = getChildAt(0); final int firstStart = (mIsVertical ? first.getTop() : first.getLeft()); final View last = getChildAt(childCount - 1); final int lastEnd = (mIsVertical ? last.getBottom() : last.getRight()); final int paddingTop = getPaddingTop(); final int paddingBottom = getPaddingBottom(); final int paddingLeft = getPaddingLeft(); final int paddingRight = getPaddingRight(); final int paddingStart = (mIsVertical ? paddingTop : paddingLeft); final int spaceBefore = paddingStart - firstStart; final int end = (mIsVertical ? getHeight() - paddingBottom : getWidth() - paddingRight); final int spaceAfter = lastEnd - end; final int size; if (mIsVertical) { size = getHeight() - paddingBottom - paddingTop; } else { size = getWidth() - paddingRight - paddingLeft; } if (incrementalDelta < 0) { incrementalDelta = Math.max(-(size - 1), incrementalDelta); } else { incrementalDelta = Math.min(size - 1, incrementalDelta); } final int firstPosition = mFirstPosition; final boolean cannotScrollDown = (firstPosition == 0 && firstStart >= paddingStart && incrementalDelta >= 0); final boolean cannotScrollUp = (firstPosition + childCount == mItemCount && lastEnd <= end && incrementalDelta <= 0); if (cannotScrollDown || cannotScrollUp) { return incrementalDelta != 0; } final boolean inTouchMode = isInTouchMode(); if (inTouchMode) { hideSelector(); } int start = 0; int count = 0; final boolean down = (incrementalDelta < 0); if (down) { int childrenStart = -incrementalDelta + paddingStart; for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final int childEnd = (mIsVertical ? child.getBottom() : child.getRight()); if (childEnd >= childrenStart) { break; } count++; mRecycler.addScrapView(child, firstPosition + i); } } else { int childrenEnd = end - incrementalDelta; for (int i = childCount - 1; i >= 0; i--) { final View child = getChildAt(i); final int childStart = (mIsVertical ? child.getTop() : child.getLeft()); if (childStart <= childrenEnd) { break; } start = i; count++; mRecycler.addScrapView(child, firstPosition + i); } } mBlockLayoutRequests = true; if (count > 0) { detachViewsFromParent(start, count); } // invalidate before moving the children to avoid unnecessary invalidate // calls to bubble up from the children all the way to the top if (!awakenScrollbarsInternal()) { invalidate(); } offsetChildren(incrementalDelta); if (down) { mFirstPosition += count; } final int absIncrementalDelta = Math.abs(incrementalDelta); if (spaceBefore < absIncrementalDelta || spaceAfter < absIncrementalDelta) { fillGap(down); } if (!inTouchMode && mSelectedPosition != INVALID_POSITION) { final int childIndex = mSelectedPosition - mFirstPosition; if (childIndex >= 0 && childIndex < getChildCount()) { positionSelector(mSelectedPosition, getChildAt(childIndex)); } } else if (mSelectorPosition != INVALID_POSITION) { final int childIndex = mSelectorPosition - mFirstPosition; if (childIndex >= 0 && childIndex < getChildCount()) { positionSelector(INVALID_POSITION, getChildAt(childIndex)); } } else { mSelectorRect.setEmpty(); } mBlockLayoutRequests = false; invokeOnItemScrollListener(); return false; } @TargetApi(14) private final float getCurrVelocity() { if (Build.VERSION.SDK_INT >= 14) { return mScroller.getCurrVelocity(); } return 0; } @TargetApi(5) private boolean awakenScrollbarsInternal() { if (Build.VERSION.SDK_INT >= 5) { return super.awakenScrollBars(); } else { return false; } } @Override public void computeScroll() { if (!mScroller.computeScrollOffset()) { return; } final int pos; if (mIsVertical) { pos = mScroller.getCurrY(); } else { pos = mScroller.getCurrX(); } final int diff = (int) (pos - mLastTouchPos); mLastTouchPos = pos; final boolean stopped = scrollListItemsBy(diff); if (!stopped && !mScroller.isFinished()) { ViewCompat.postInvalidateOnAnimation(this); } else { if (stopped) { final int overScrollMode = ViewCompat.getOverScrollMode(this); if (overScrollMode != ViewCompat.OVER_SCROLL_NEVER) { final EdgeEffectCompat edge = (diff > 0 ? mStartEdge : mEndEdge); boolean needsInvalidate = edge.onAbsorb(Math.abs((int) getCurrVelocity())); if (needsInvalidate) { ViewCompat.postInvalidateOnAnimation(this); } } mScroller.abortAnimation(); } mTouchMode = TOUCH_MODE_REST; reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); } } private void finishEdgeGlows() { if (mStartEdge != null) { mStartEdge.finish(); } if (mEndEdge != null) { mEndEdge.finish(); } } private boolean drawStartEdge(Canvas canvas) { if (mStartEdge.isFinished()) { return false; } if (mIsVertical) { return mStartEdge.draw(canvas); } final int restoreCount = canvas.save(); final int height = getHeight() - getPaddingTop() - getPaddingBottom(); canvas.translate(0, height); canvas.rotate(270); final boolean needsInvalidate = mStartEdge.draw(canvas); canvas.restoreToCount(restoreCount); return needsInvalidate; } private boolean drawEndEdge(Canvas canvas) { if (mEndEdge.isFinished()) { return false; } final int restoreCount = canvas.save(); final int width = getWidth() - getPaddingLeft() - getPaddingRight(); final int height = getHeight() - getPaddingTop() - getPaddingBottom(); if (mIsVertical) { canvas.translate(-width, height); canvas.rotate(180, width, 0); } else { canvas.translate(width, 0); canvas.rotate(90); } final boolean needsInvalidate = mEndEdge.draw(canvas); canvas.restoreToCount(restoreCount); return needsInvalidate; } private void drawSelector(Canvas canvas) { if (!mSelectorRect.isEmpty()) { final Drawable selector = mSelector; selector.setBounds(mSelectorRect); selector.draw(canvas); } } private void useDefaultSelector() { setSelector(getResources().getDrawable( android.R.drawable.list_selector_background)); } private boolean shouldShowSelector() { return (hasFocus() && !isInTouchMode()) || touchModeDrawsInPressedState(); } private void positionSelector(int position, View selected) { if (position != INVALID_POSITION) { mSelectorPosition = position; } mSelectorRect.set(selected.getLeft(), selected.getTop(), selected.getRight(), selected.getBottom()); final boolean isChildViewEnabled = mIsChildViewEnabled; if (selected.isEnabled() != isChildViewEnabled) { mIsChildViewEnabled = !isChildViewEnabled; if (getSelectedItemPosition() != INVALID_POSITION) { refreshDrawableState(); } } } private void hideSelector() { if (mSelectedPosition != INVALID_POSITION) { if (mLayoutMode != LAYOUT_SPECIFIC) { mResurrectToPosition = mSelectedPosition; } if (mNextSelectedPosition >= 0 && mNextSelectedPosition != mSelectedPosition) { mResurrectToPosition = mNextSelectedPosition; } setSelectedPositionInt(INVALID_POSITION); setNextSelectedPositionInt(INVALID_POSITION); mSelectedStart = 0; } } private void setSelectedPositionInt(int position) { mSelectedPosition = position; mSelectedRowId = getItemIdAtPosition(position); } private void setSelectionInt(int position) { setNextSelectedPositionInt(position); boolean awakeScrollbars = false; final int selectedPosition = mSelectedPosition; if (selectedPosition >= 0) { if (position == selectedPosition - 1) { awakeScrollbars = true; } else if (position == selectedPosition + 1) { awakeScrollbars = true; } } layoutChildren(); if (awakeScrollbars) { awakenScrollbarsInternal(); } } private void setNextSelectedPositionInt(int position) { mNextSelectedPosition = position; mNextSelectedRowId = getItemIdAtPosition(position); // If we are trying to sync to the selection, update that too if (mNeedSync && mSyncMode == SYNC_SELECTED_POSITION && position >= 0) { mSyncPosition = position; mSyncRowId = mNextSelectedRowId; } } private boolean touchModeDrawsInPressedState() { switch (mTouchMode) { case TOUCH_MODE_TAP: case TOUCH_MODE_DONE_WAITING: return true; default: return false; } } /** * Sets the selector state to "pressed" and posts a CheckForKeyLongPress to see if * this is a long press. */ private void keyPressed() { if (!isEnabled() || !isClickable()) { return; } final Drawable selector = mSelector; final Rect selectorRect = mSelectorRect; if (selector != null && (isFocused() || touchModeDrawsInPressedState()) && !selectorRect.isEmpty()) { final View child = getChildAt(mSelectedPosition - mFirstPosition); if (child != null) { if (child.hasFocusable()) { return; } child.setPressed(true); } setPressed(true); final boolean longClickable = isLongClickable(); final Drawable d = selector.getCurrent(); if (d != null && d instanceof TransitionDrawable) { if (longClickable) { ((TransitionDrawable) d).startTransition( ViewConfiguration.getLongPressTimeout()); } else { ((TransitionDrawable) d).resetTransition(); } } if (longClickable && !mDataChanged) { if (mPendingCheckForKeyLongPress == null) { mPendingCheckForKeyLongPress = new CheckForKeyLongPress(); } mPendingCheckForKeyLongPress.rememberWindowAttachCount(); postDelayed(mPendingCheckForKeyLongPress, ViewConfiguration.getLongPressTimeout()); } } } private void updateSelectorState() { if (mSelector != null) { if (shouldShowSelector()) { mSelector.setState(getDrawableState()); } else { mSelector.setState(STATE_NOTHING); } } } private void checkSelectionChanged() { if ((mSelectedPosition != mOldSelectedPosition) || (mSelectedRowId != mOldSelectedRowId)) { selectionChanged(); mOldSelectedPosition = mSelectedPosition; mOldSelectedRowId = mSelectedRowId; } } private void selectionChanged() { OnItemSelectedListener listener = getOnItemSelectedListener(); if (listener == null) { return; } if (mInLayout || mBlockLayoutRequests) { // If we are in a layout traversal, defer notification // by posting. This ensures that the view tree is // in a consistent state and is able to accommodate // new layout or invalidate requests. if (mSelectionNotifier == null) { mSelectionNotifier = new SelectionNotifier(); } post(mSelectionNotifier); } else { fireOnSelected(); performAccessibilityActionsOnSelected(); } } private void fireOnSelected() { OnItemSelectedListener listener = getOnItemSelectedListener(); if (listener == null) { return; } final int selection = getSelectedItemPosition(); if (selection >= 0) { View v = getSelectedView(); listener.onItemSelected(this, v, selection, mAdapter.getItemId(selection)); } else { listener.onNothingSelected(this); } } private void performAccessibilityActionsOnSelected() { final int position = getSelectedItemPosition(); if (position >= 0) { // We fire selection events here not in View sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } } private int lookForSelectablePosition(int position) { return lookForSelectablePosition(position, true); } private int lookForSelectablePosition(int position, boolean lookDown) { final ListAdapter adapter = mAdapter; if (adapter == null || isInTouchMode()) { return INVALID_POSITION; } final int itemCount = mItemCount; if (!mAreAllItemsSelectable) { if (lookDown) { position = Math.max(0, position); while (position < itemCount && !adapter.isEnabled(position)) { position++; } } else { position = Math.min(position, itemCount - 1); while (position >= 0 && !adapter.isEnabled(position)) { position--; } } if (position < 0 || position >= itemCount) { return INVALID_POSITION; } return position; } else { if (position < 0 || position >= itemCount) { return INVALID_POSITION; } return position; } } /** * @param direction either {@link View#FOCUS_UP} or {@link View#FOCUS_DOWN} or * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT} depending on the * current view orientation. * * @return The position of the next selectable position of the views that * are currently visible, taking into account the fact that there might * be no selection. Returns {@link #INVALID_POSITION} if there is no * selectable view on screen in the given direction. */ private int lookForSelectablePositionOnScreen(int direction) { forceValidFocusDirection(direction); final int firstPosition = mFirstPosition; final ListAdapter adapter = getAdapter(); if (direction == View.FOCUS_DOWN || direction == View.FOCUS_RIGHT) { int startPos = (mSelectedPosition != INVALID_POSITION ? mSelectedPosition + 1 : firstPosition); if (startPos >= adapter.getCount()) { return INVALID_POSITION; } if (startPos < firstPosition) { startPos = firstPosition; } final int lastVisiblePos = getLastVisiblePosition(); for (int pos = startPos; pos <= lastVisiblePos; pos++) { if (adapter.isEnabled(pos) && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) { return pos; } } } else { final int last = firstPosition + getChildCount() - 1; int startPos = (mSelectedPosition != INVALID_POSITION) ? mSelectedPosition - 1 : firstPosition + getChildCount() - 1; if (startPos < 0 || startPos >= adapter.getCount()) { return INVALID_POSITION; } if (startPos > last) { startPos = last; } for (int pos = startPos; pos >= firstPosition; pos--) { if (adapter.isEnabled(pos) && getChildAt(pos - firstPosition).getVisibility() == View.VISIBLE) { return pos; } } } return INVALID_POSITION; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); updateSelectorState(); } @Override protected int[] onCreateDrawableState(int extraSpace) { // If the child view is enabled then do the default behavior. if (mIsChildViewEnabled) { // Common case return super.onCreateDrawableState(extraSpace); } // The selector uses this View's drawable state. The selected child view // is disabled, so we need to remove the enabled state from the drawable // states. final int enabledState = ENABLED_STATE_SET[0]; // If we don't have any extra space, it will return one of the static state arrays, // and clearing the enabled state on those arrays is a bad thing! If we specify // we need extra space, it will create+copy into a new array that safely mutable. int[] state = super.onCreateDrawableState(extraSpace + 1); int enabledPos = -1; for (int i = state.length - 1; i >= 0; i--) { if (state[i] == enabledState) { enabledPos = i; break; } } // Remove the enabled state if (enabledPos >= 0) { System.arraycopy(state, enabledPos + 1, state, enabledPos, state.length - enabledPos - 1); } return state; } @Override protected boolean canAnimate() { return (super.canAnimate() && mItemCount > 0); } @Override protected void dispatchDraw(Canvas canvas) { final boolean drawSelectorOnTop = mDrawSelectorOnTop; if (!drawSelectorOnTop) { drawSelector(canvas); } super.dispatchDraw(canvas); if (drawSelectorOnTop) { drawSelector(canvas); } } @Override public void draw(Canvas canvas) { super.draw(canvas); boolean needsInvalidate = false; if (mStartEdge != null) { needsInvalidate |= drawStartEdge(canvas); } if (mEndEdge != null) { needsInvalidate |= drawEndEdge(canvas); } if (needsInvalidate) { ViewCompat.postInvalidateOnAnimation(this); } } @Override public void requestLayout() { if (!mInLayout && !mBlockLayoutRequests) { super.requestLayout(); } } @Override public View getSelectedView() { if (mItemCount > 0 && mSelectedPosition >= 0) { return getChildAt(mSelectedPosition - mFirstPosition); } else { return null; } } @Override public void setSelection(int position) { setSelectionFromOffset(position, 0); } public void setSelectionFromOffset(int position, int offset) { if (mAdapter == null) { return; } if (!isInTouchMode()) { position = lookForSelectablePosition(position); if (position >= 0) { setNextSelectedPositionInt(position); } } else { mResurrectToPosition = position; } if (position >= 0) { mLayoutMode = LAYOUT_SPECIFIC; if (mIsVertical) { mSpecificStart = getPaddingTop() + offset; } else { mSpecificStart = getPaddingLeft() + offset; } if (mNeedSync) { mSyncPosition = position; mSyncRowId = mAdapter.getItemId(position); } requestLayout(); } } public void scrollBy(int offset) { scrollListItemsBy(offset); } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Dispatch in the normal way boolean handled = super.dispatchKeyEvent(event); if (!handled) { // If we didn't handle it... final View focused = getFocusedChild(); if (focused != null && event.getAction() == KeyEvent.ACTION_DOWN) { // ... and our focused child didn't handle it // ... give it to ourselves so we can scroll if necessary handled = onKeyDown(event.getKeyCode(), event); } } return handled; } @Override protected void dispatchSetPressed(boolean pressed) { // Don't dispatch setPressed to our children. We call setPressed on ourselves to // get the selector in the right state, but we don't want to press each child. } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mSelector == null) { useDefaultSelector(); } int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int childWidth = 0; int childHeight = 0; mItemCount = (mAdapter == null ? 0 : mAdapter.getCount()); if (mItemCount > 0 && (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED)) { final View child = obtainView(0, mIsScrap); final int secondaryMeasureSpec = (mIsVertical ? widthMeasureSpec : heightMeasureSpec); measureScrapChild(child, 0, secondaryMeasureSpec); childWidth = child.getMeasuredWidth(); childHeight = child.getMeasuredHeight(); if (recycleOnMeasure()) { mRecycler.addScrapView(child, -1); } } if (widthMode == MeasureSpec.UNSPECIFIED) { widthSize = getPaddingLeft() + getPaddingRight() + childWidth; if (mIsVertical) { widthSize += getVerticalScrollbarWidth(); } } if (heightMode == MeasureSpec.UNSPECIFIED) { heightSize = getPaddingTop() + getPaddingBottom() + childHeight; if (!mIsVertical) { heightSize += getHorizontalScrollbarHeight(); } } if (mIsVertical && heightMode == MeasureSpec.AT_MOST) { heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1); } if (!mIsVertical && widthMode == MeasureSpec.AT_MOST) { widthSize = measureWidthOfChildren(heightMeasureSpec, 0, NO_POSITION, widthSize, -1); } setMeasuredDimension(widthSize, heightSize); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mInLayout = true; if (changed) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { getChildAt(i).forceLayout(); } mRecycler.markChildrenDirty(); } layoutChildren(); mInLayout = false; final int width = r - l - getPaddingLeft() - getPaddingRight(); final int height = b - t - getPaddingTop() - getPaddingBottom(); if (mStartEdge != null && mEndEdge != null) { if (mIsVertical) { mStartEdge.setSize(width, height); mEndEdge.setSize(width, height); } else { mStartEdge.setSize(height, width); mEndEdge.setSize(height, width); } } } private void layoutChildren() { if (getWidth() == 0 || getHeight() == 0) { return; } final boolean blockLayoutRequests = mBlockLayoutRequests; if (!blockLayoutRequests) { mBlockLayoutRequests = true; } else { return; } try { invalidate(); if (mAdapter == null) { resetState(); return; } final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft()); final int end = (mIsVertical ? getHeight() - getPaddingBottom() : getWidth() - getPaddingRight()); int childCount = getChildCount(); int index = 0; int delta = 0; View focusLayoutRestoreView = null; View selected = null; View oldSelected = null; View newSelected = null; View oldFirstChild = null; switch (mLayoutMode) { case LAYOUT_SET_SELECTION: index = mNextSelectedPosition - mFirstPosition; if (index >= 0 && index < childCount) { newSelected = getChildAt(index); } break; case LAYOUT_FORCE_TOP: case LAYOUT_FORCE_BOTTOM: case LAYOUT_SPECIFIC: case LAYOUT_SYNC: break; case LAYOUT_MOVE_SELECTION: default: // Remember the previously selected view index = mSelectedPosition - mFirstPosition; if (index >= 0 && index < childCount) { oldSelected = getChildAt(index); } // Remember the previous first child oldFirstChild = getChildAt(0); if (mNextSelectedPosition >= 0) { delta = mNextSelectedPosition - mSelectedPosition; } // Caution: newSelected might be null newSelected = getChildAt(index + delta); } final boolean dataChanged = mDataChanged; if (dataChanged) { handleDataChanged(); } // Handle the empty set by removing all views that are visible // and calling it a day if (mItemCount == 0) { resetState(); return; } else if (mItemCount != mAdapter.getCount()) { throw new IllegalStateException("The content of the adapter has changed but " + "TwoWayView did not receive a notification. Make sure the content of " + "your adapter is not modified from a background thread, but only " + "from the UI thread. [in TwoWayView(" + getId() + ", " + getClass() + ") with Adapter(" + mAdapter.getClass() + ")]"); } setSelectedPositionInt(mNextSelectedPosition); // Reset the focus restoration View focusLayoutRestoreDirectChild = null; // Pull all children into the RecycleBin. // These views will be reused if possible final int firstPosition = mFirstPosition; final RecycleBin recycleBin = mRecycler; if (dataChanged) { for (int i = 0; i < childCount; i++) { recycleBin.addScrapView(getChildAt(i), firstPosition + i); } } else { recycleBin.fillActiveViews(childCount, firstPosition); } // Take focus back to us temporarily to avoid the eventual // call to clear focus when removing the focused child below // from messing things up when ViewAncestor assigns focus back // to someone else. final View focusedChild = getFocusedChild(); if (focusedChild != null) { // We can remember the focused view to restore after relayout if the // data hasn't changed, or if the focused position is a header or footer. if (!dataChanged) { focusLayoutRestoreDirectChild = focusedChild; // Remember the specific view that had focus focusLayoutRestoreView = findFocus(); if (focusLayoutRestoreView != null) { // Tell it we are going to mess with it focusLayoutRestoreView.onStartTemporaryDetach(); } } requestFocus(); } // FIXME: We need a way to save current accessibility focus here // so that it can be restored after we re-attach the children on each // layout round. detachAllViewsFromParent(); switch (mLayoutMode) { case LAYOUT_SET_SELECTION: if (newSelected != null) { final int newSelectedStart = (mIsVertical ? newSelected.getTop() : newSelected.getLeft()); selected = fillFromSelection(newSelectedStart, start, end); } else { selected = fillFromMiddle(start, end); } break; case LAYOUT_SYNC: selected = fillSpecific(mSyncPosition, mSpecificStart); break; case LAYOUT_FORCE_BOTTOM: selected = fillBefore(mItemCount - 1, end); adjustViewsStartOrEnd(); break; case LAYOUT_FORCE_TOP: mFirstPosition = 0; selected = fillFromOffset(start); adjustViewsStartOrEnd(); break; case LAYOUT_SPECIFIC: selected = fillSpecific(reconcileSelectedPosition(), mSpecificStart); break; case LAYOUT_MOVE_SELECTION: selected = moveSelection(oldSelected, newSelected, delta, start, end); break; default: if (childCount == 0) { final int position = lookForSelectablePosition(0); setSelectedPositionInt(position); selected = fillFromOffset(start); } else { if (mSelectedPosition >= 0 && mSelectedPosition < mItemCount) { int offset = start; if (oldSelected != null) { offset = (mIsVertical ? oldSelected.getTop() : oldSelected.getLeft()); } selected = fillSpecific(mSelectedPosition, offset); } else if (mFirstPosition < mItemCount) { int offset = start; if (oldFirstChild != null) { offset = (mIsVertical ? oldFirstChild.getTop() : oldFirstChild.getLeft()); } selected = fillSpecific(mFirstPosition, offset); } else { selected = fillSpecific(0, start); } } break; } recycleBin.scrapActiveViews(); if (selected != null) { if (mItemsCanFocus && hasFocus() && !selected.hasFocus()) { final boolean focusWasTaken = (selected == focusLayoutRestoreDirectChild && focusLayoutRestoreView != null && focusLayoutRestoreView.requestFocus()) || selected.requestFocus(); if (!focusWasTaken) { // Selected item didn't take focus, fine, but still want // to make sure something else outside of the selected view // has focus final View focused = getFocusedChild(); if (focused != null) { focused.clearFocus(); } positionSelector(INVALID_POSITION, selected); } else { selected.setSelected(false); mSelectorRect.setEmpty(); } } else { positionSelector(INVALID_POSITION, selected); } mSelectedStart = (mIsVertical ? selected.getTop() : selected.getLeft()); } else { if (mTouchMode > TOUCH_MODE_DOWN && mTouchMode < TOUCH_MODE_DRAGGING) { View child = getChildAt(mMotionPosition - mFirstPosition); if (child != null) { positionSelector(mMotionPosition, child); } } else { mSelectedStart = 0; mSelectorRect.setEmpty(); } // Even if there is not selected position, we may need to restore // focus (i.e. something focusable in touch mode) if (hasFocus() && focusLayoutRestoreView != null) { focusLayoutRestoreView.requestFocus(); } } // Tell focus view we are done mucking with it, if it is still in // our view hierarchy. if (focusLayoutRestoreView != null && focusLayoutRestoreView.getWindowToken() != null) { focusLayoutRestoreView.onFinishTemporaryDetach(); } mLayoutMode = LAYOUT_NORMAL; mDataChanged = false; mNeedSync = false; setNextSelectedPositionInt(mSelectedPosition); if (mItemCount > 0) { checkSelectionChanged(); } invokeOnItemScrollListener(); } finally { if (!blockLayoutRequests) { mBlockLayoutRequests = false; mDataChanged = false; } } } protected boolean recycleOnMeasure() { return true; } private void offsetChildren(int offset) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (mIsVertical) { child.offsetTopAndBottom(offset); } else { child.offsetLeftAndRight(offset); } } } private View moveSelection(View oldSelected, View newSelected, int delta, int start, int end) { final int selectedPosition = mSelectedPosition; final int oldSelectedStart = (mIsVertical ? oldSelected.getTop() : oldSelected.getLeft()); final int oldSelectedEnd = (mIsVertical ? oldSelected.getBottom() : oldSelected.getRight()); View selected = null; if (delta > 0) { /* * Case 1: Scrolling down. */ /* * Before After * | | | | * +-------+ +-------+ * | A | | A | * | 1 | => +-------+ * +-------+ | B | * | B | | 2 | * +-------+ +-------+ * | | | | * * Try to keep the top of the previously selected item where it was. * oldSelected = A * selected = B */ // Put oldSelected (A) where it belongs oldSelected = makeAndAddView(selectedPosition - 1, oldSelectedStart, true, false); final int itemMargin = mItemMargin; // Now put the new selection (B) below that selected = makeAndAddView(selectedPosition, oldSelectedEnd + itemMargin, true, true); final int selectedStart = (mIsVertical ? selected.getTop() : selected.getLeft()); final int selectedEnd = (mIsVertical ? selected.getBottom() : selected.getRight()); // Some of the newly selected item extends below the bottom of the list if (selectedEnd > end) { // Find space available above the selection into which we can scroll upwards final int spaceBefore = selectedStart - start; // Find space required to bring the bottom of the selected item fully into view final int spaceAfter = selectedEnd - end; // Don't scroll more than half the size of the list final int halfSpace = (end - start) / 2; int offset = Math.min(spaceBefore, spaceAfter); offset = Math.min(offset, halfSpace); if (mIsVertical) { oldSelected.offsetTopAndBottom(-offset); selected.offsetTopAndBottom(-offset); } else { oldSelected.offsetLeftAndRight(-offset); selected.offsetLeftAndRight(-offset); } } // Fill in views before and after fillBefore(mSelectedPosition - 2, selectedStart - itemMargin); adjustViewsStartOrEnd(); fillAfter(mSelectedPosition + 1, selectedEnd + itemMargin); } else if (delta < 0) { /* * Case 2: Scrolling up. */ /* * Before After * | | | | * +-------+ +-------+ * | A | | A | * +-------+ => | 1 | * | B | +-------+ * | 2 | | B | * +-------+ +-------+ * | | | | * * Try to keep the top of the item about to become selected where it was. * newSelected = A * olSelected = B */ if (newSelected != null) { // Try to position the top of newSel (A) where it was before it was selected final int newSelectedStart = (mIsVertical ? newSelected.getTop() : newSelected.getLeft()); selected = makeAndAddView(selectedPosition, newSelectedStart, true, true); } else { // If (A) was not on screen and so did not have a view, position // it above the oldSelected (B) selected = makeAndAddView(selectedPosition, oldSelectedStart, false, true); } final int selectedStart = (mIsVertical ? selected.getTop() : selected.getLeft()); final int selectedEnd = (mIsVertical ? selected.getBottom() : selected.getRight()); // Some of the newly selected item extends above the top of the list if (selectedStart < start) { // Find space required to bring the top of the selected item fully into view final int spaceBefore = start - selectedStart; // Find space available below the selection into which we can scroll downwards final int spaceAfter = end - selectedEnd; // Don't scroll more than half the height of the list final int halfSpace = (end - start) / 2; int offset = Math.min(spaceBefore, spaceAfter); offset = Math.min(offset, halfSpace); if (mIsVertical) { selected.offsetTopAndBottom(offset); } else { selected.offsetLeftAndRight(offset); } } // Fill in views above and below fillBeforeAndAfter(selected, selectedPosition); } else { /* * Case 3: Staying still */ selected = makeAndAddView(selectedPosition, oldSelectedStart, true, true); final int selectedStart = (mIsVertical ? selected.getTop() : selected.getLeft()); final int selectedEnd = (mIsVertical ? selected.getBottom() : selected.getRight()); // We're staying still... if (oldSelectedStart < start) { // ... but the top of the old selection was off screen. // (This can happen if the data changes size out from under us) int newEnd = selectedEnd; if (newEnd < start + 20) { // Not enough visible -- bring it onscreen if (mIsVertical) { selected.offsetTopAndBottom(start - selectedStart); } else { selected.offsetLeftAndRight(start - selectedStart); } } } // Fill in views above and below fillBeforeAndAfter(selected, selectedPosition); } return selected; } void confirmCheckedPositionsById() { // Clear out the positional check states, we'll rebuild it below from IDs. mCheckStates.clear(); for (int checkedIndex = 0; checkedIndex < mCheckedIdStates.size(); checkedIndex++) { final long id = mCheckedIdStates.keyAt(checkedIndex); final int lastPos = mCheckedIdStates.valueAt(checkedIndex); final long lastPosId = mAdapter.getItemId(lastPos); if (id != lastPosId) { // Look around to see if the ID is nearby. If not, uncheck it. final int start = Math.max(0, lastPos - CHECK_POSITION_SEARCH_DISTANCE); final int end = Math.min(lastPos + CHECK_POSITION_SEARCH_DISTANCE, mItemCount); boolean found = false; for (int searchPos = start; searchPos < end; searchPos++) { final long searchId = mAdapter.getItemId(searchPos); if (id == searchId) { found = true; mCheckStates.put(searchPos, true); mCheckedIdStates.setValueAt(checkedIndex, searchPos); break; } } if (!found) { mCheckedIdStates.delete(id); checkedIndex--; mCheckedItemCount--; } } else { mCheckStates.put(lastPos, true); } } } private void handleDataChanged() { if (mChoiceMode.compareTo(ChoiceMode.NONE) != 0 && mAdapter != null && mAdapter.hasStableIds()) { confirmCheckedPositionsById(); } mRecycler.clearTransientStateViews(); final int itemCount = mItemCount; if (itemCount > 0) { int newPos; int selectablePos; // Find the row we are supposed to sync to if (mNeedSync) { // Update this first, since setNextSelectedPositionInt inspects it mNeedSync = false; mPendingSync = null; switch (mSyncMode) { case SYNC_SELECTED_POSITION: if (isInTouchMode()) { // We saved our state when not in touch mode. (We know this because // mSyncMode is SYNC_SELECTED_POSITION.) Now we are trying to // restore in touch mode. Just leave mSyncPosition as it is (possibly // adjusting if the available range changed) and return. mLayoutMode = LAYOUT_SYNC; mSyncPosition = Math.min(Math.max(0, mSyncPosition), itemCount - 1); return; } else { // See if we can find a position in the new data with the same // id as the old selection. This will change mSyncPosition. newPos = findSyncPosition(); if (newPos >= 0) { // Found it. Now verify that new selection is still selectable selectablePos = lookForSelectablePosition(newPos, true); if (selectablePos == newPos) { // Same row id is selected mSyncPosition = newPos; if (mSyncHeight == getHeight()) { // If we are at the same height as when we saved state, try // to restore the scroll position too. mLayoutMode = LAYOUT_SYNC; } else { // We are not the same height as when the selection was saved, so // don't try to restore the exact position mLayoutMode = LAYOUT_SET_SELECTION; } // Restore selection setNextSelectedPositionInt(newPos); return; } } } break; case SYNC_FIRST_POSITION: // Leave mSyncPosition as it is -- just pin to available range mLayoutMode = LAYOUT_SYNC; mSyncPosition = Math.min(Math.max(0, mSyncPosition), itemCount - 1); return; } } if (!isInTouchMode()) { // We couldn't find matching data -- try to use the same position newPos = getSelectedItemPosition(); // Pin position to the available range if (newPos >= itemCount) { newPos = itemCount - 1; } if (newPos < 0) { newPos = 0; } // Make sure we select something selectable -- first look down selectablePos = lookForSelectablePosition(newPos, true); if (selectablePos >= 0) { setNextSelectedPositionInt(selectablePos); return; } else { // Looking down didn't work -- try looking up selectablePos = lookForSelectablePosition(newPos, false); if (selectablePos >= 0) { setNextSelectedPositionInt(selectablePos); return; } } } else { // We already know where we want to resurrect the selection if (mResurrectToPosition >= 0) { return; } } } // Nothing is selected. Give up and reset everything. mLayoutMode = LAYOUT_FORCE_TOP; mSelectedPosition = INVALID_POSITION; mSelectedRowId = INVALID_ROW_ID; mNextSelectedPosition = INVALID_POSITION; mNextSelectedRowId = INVALID_ROW_ID; mNeedSync = false; mPendingSync = null; mSelectorPosition = INVALID_POSITION; checkSelectionChanged(); } private int reconcileSelectedPosition() { int position = mSelectedPosition; if (position < 0) { position = mResurrectToPosition; } position = Math.max(0, position); position = Math.min(position, mItemCount - 1); return position; } boolean resurrectSelection() { final int childCount = getChildCount(); if (childCount <= 0) { return false; } int selectedStart = 0; int selectedPosition; final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft()); final int end = (mIsVertical ? getHeight() - getPaddingBottom() : getWidth() - getPaddingRight()); final int firstPosition = mFirstPosition; final int toPosition = mResurrectToPosition; boolean down = true; if (toPosition >= firstPosition && toPosition < firstPosition + childCount) { selectedPosition = toPosition; final View selected = getChildAt(selectedPosition - mFirstPosition); selectedStart = (mIsVertical ? selected.getTop() : selected.getLeft()); } else if (toPosition < firstPosition) { // Default to selecting whatever is first selectedPosition = firstPosition; for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final int childStart = (mIsVertical ? child.getTop() : child.getLeft()); if (i == 0) { // Remember the position of the first item selectedStart = childStart; } if (childStart >= start) { // Found a view whose top is fully visible selectedPosition = firstPosition + i; selectedStart = childStart; break; } } } else { selectedPosition = firstPosition + childCount - 1; down = false; for (int i = childCount - 1; i >= 0; i--) { final View child = getChildAt(i); final int childStart = (mIsVertical ? child.getTop() : child.getLeft()); final int childEnd = (mIsVertical ? child.getBottom() : child.getRight()); if (i == childCount - 1) { selectedStart = childStart; } if (childEnd <= end) { selectedPosition = firstPosition + i; selectedStart = childStart; break; } } } mResurrectToPosition = INVALID_POSITION; mTouchMode = TOUCH_MODE_REST; reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE); mSpecificStart = selectedStart; selectedPosition = lookForSelectablePosition(selectedPosition, down); if (selectedPosition >= firstPosition && selectedPosition <= getLastVisiblePosition()) { mLayoutMode = LAYOUT_SPECIFIC; updateSelectorState(); setSelectionInt(selectedPosition); invokeOnItemScrollListener(); } else { selectedPosition = INVALID_POSITION; } return selectedPosition >= 0; } /** * If there is a selection returns false. * Otherwise resurrects the selection and returns true if resurrected. */ boolean resurrectSelectionIfNeeded() { if (mSelectedPosition < 0 && resurrectSelection()) { updateSelectorState(); return true; } return false; } private int getChildWidthMeasureSpec(LayoutParams lp) { if (!mIsVertical && lp.width == LayoutParams.WRAP_CONTENT) { return MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } else if (mIsVertical) { final int maxWidth = getWidth() - getPaddingLeft() - getPaddingRight(); return MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.EXACTLY); } else { return MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY); } } private int getChildHeightMeasureSpec(LayoutParams lp) { if (mIsVertical && lp.height == LayoutParams.WRAP_CONTENT) { return MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } else if (!mIsVertical) { final int maxHeight = getHeight() - getPaddingTop() - getPaddingBottom(); return MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.EXACTLY); } else { return MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY); } } private void measureChild(View child) { measureChild(child, (LayoutParams) child.getLayoutParams()); } private void measureChild(View child, LayoutParams lp) { final int widthSpec = getChildWidthMeasureSpec(lp); final int heightSpec = getChildHeightMeasureSpec(lp); child.measure(widthSpec, heightSpec); } private void relayoutMeasuredChild(View child) { final int w = child.getMeasuredWidth(); final int h = child.getMeasuredHeight(); final int childLeft = getPaddingLeft(); final int childRight = childLeft + w; final int childTop = child.getTop(); final int childBottom = childTop + h; child.layout(childLeft, childTop, childRight, childBottom); } private void measureScrapChild(View scrapChild, int position, int secondaryMeasureSpec) { LayoutParams lp = (LayoutParams) scrapChild.getLayoutParams(); if (lp == null) { lp = generateDefaultLayoutParams(); scrapChild.setLayoutParams(lp); } lp.viewType = mAdapter.getItemViewType(position); lp.forceAdd = true; final int widthMeasureSpec; final int heightMeasureSpec; if (mIsVertical) { widthMeasureSpec = secondaryMeasureSpec; heightMeasureSpec = getChildHeightMeasureSpec(lp); } else { widthMeasureSpec = getChildWidthMeasureSpec(lp); heightMeasureSpec = secondaryMeasureSpec; } scrapChild.measure(widthMeasureSpec, heightMeasureSpec); } /** * Measures the height of the given range of children (inclusive) and * returns the height with this TwoWayView's padding and item margin heights * included. If maxHeight is provided, the measuring will stop when the * current height reaches maxHeight. * * @param widthMeasureSpec The width measure spec to be given to a child's * {@link View#measure(int, int)}. * @param startPosition The position of the first child to be shown. * @param endPosition The (inclusive) position of the last child to be * shown. Specify {@link #NO_POSITION} if the last child should be * the last available child from the adapter. * @param maxHeight The maximum height that will be returned (if all the * children don't fit in this value, this value will be * returned). * @param disallowPartialChildPosition In general, whether the returned * height should only contain entire children. This is more * powerful--it is the first inclusive position at which partial * children will not be allowed. Example: it looks nice to have * at least 3 completely visible children, and in portrait this * will most likely fit; but in landscape there could be times * when even 2 children can not be completely shown, so a value * of 2 (remember, inclusive) would be good (assuming * startPosition is 0). * @return The height of this TwoWayView with the given children. */ private int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition, final int maxHeight, int disallowPartialChildPosition) { final int paddingTop = getPaddingTop(); final int paddingBottom = getPaddingBottom(); final ListAdapter adapter = mAdapter; if (adapter == null) { return paddingTop + paddingBottom; } // Include the padding of the list int returnedHeight = paddingTop + paddingBottom; final int itemMargin = mItemMargin; // The previous height value that was less than maxHeight and contained // no partial children int prevHeightWithoutPartialChild = 0; int i; View child; // mItemCount - 1 since endPosition parameter is inclusive endPosition = (endPosition == NO_POSITION) ? adapter.getCount() - 1 : endPosition; final RecycleBin recycleBin = mRecycler; final boolean shouldRecycle = recycleOnMeasure(); final boolean[] isScrap = mIsScrap; for (i = startPosition; i <= endPosition; ++i) { child = obtainView(i, isScrap); measureScrapChild(child, i, widthMeasureSpec); if (i > 0) { // Count the item margin for all but one child returnedHeight += itemMargin; } // Recycle the view before we possibly return from the method if (shouldRecycle) { recycleBin.addScrapView(child, -1); } returnedHeight += child.getMeasuredHeight(); if (returnedHeight >= maxHeight) { // We went over, figure out which height to return. If returnedHeight > maxHeight, // then the i'th position did not fit completely. return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1) && (i > disallowPartialChildPosition) // We've past the min pos && (prevHeightWithoutPartialChild > 0) // We have a prev height && (returnedHeight != maxHeight) // i'th child did not fit completely ? prevHeightWithoutPartialChild : maxHeight; } if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) { prevHeightWithoutPartialChild = returnedHeight; } } // At this point, we went through the range of children, and they each // completely fit, so return the returnedHeight return returnedHeight; } /** * Measures the width of the given range of children (inclusive) and * returns the width with this TwoWayView's padding and item margin widths * included. If maxWidth is provided, the measuring will stop when the * current width reaches maxWidth. * * @param heightMeasureSpec The height measure spec to be given to a child's * {@link View#measure(int, int)}. * @param startPosition The position of the first child to be shown. * @param endPosition The (inclusive) position of the last child to be * shown. Specify {@link #NO_POSITION} if the last child should be * the last available child from the adapter. * @param maxWidth The maximum width that will be returned (if all the * children don't fit in this value, this value will be * returned). * @param disallowPartialChildPosition In general, whether the returned * width should only contain entire children. This is more * powerful--it is the first inclusive position at which partial * children will not be allowed. Example: it looks nice to have * at least 3 completely visible children, and in portrait this * will most likely fit; but in landscape there could be times * when even 2 children can not be completely shown, so a value * of 2 (remember, inclusive) would be good (assuming * startPosition is 0). * @return The width of this TwoWayView with the given children. */ private int measureWidthOfChildren(int heightMeasureSpec, int startPosition, int endPosition, final int maxWidth, int disallowPartialChildPosition) { final int paddingLeft = getPaddingLeft(); final int paddingRight = getPaddingRight(); final ListAdapter adapter = mAdapter; if (adapter == null) { return paddingLeft + paddingRight; } // Include the padding of the list int returnedWidth = paddingLeft + paddingRight; final int itemMargin = mItemMargin; // The previous height value that was less than maxHeight and contained // no partial children int prevWidthWithoutPartialChild = 0; int i; View child; // mItemCount - 1 since endPosition parameter is inclusive endPosition = (endPosition == NO_POSITION) ? adapter.getCount() - 1 : endPosition; final RecycleBin recycleBin = mRecycler; final boolean shouldRecycle = recycleOnMeasure(); final boolean[] isScrap = mIsScrap; for (i = startPosition; i <= endPosition; ++i) { child = obtainView(i, isScrap); measureScrapChild(child, i, heightMeasureSpec); if (i > 0) { // Count the item margin for all but one child returnedWidth += itemMargin; } // Recycle the view before we possibly return from the method if (shouldRecycle) { recycleBin.addScrapView(child, -1); } returnedWidth += child.getMeasuredHeight(); if (returnedWidth >= maxWidth) { // We went over, figure out which width to return. If returnedWidth > maxWidth, // then the i'th position did not fit completely. return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1) && (i > disallowPartialChildPosition) // We've past the min pos && (prevWidthWithoutPartialChild > 0) // We have a prev width && (returnedWidth != maxWidth) // i'th child did not fit completely ? prevWidthWithoutPartialChild : maxWidth; } if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) { prevWidthWithoutPartialChild = returnedWidth; } } // At this point, we went through the range of children, and they each // completely fit, so return the returnedWidth return returnedWidth; } private View makeAndAddView(int position, int offset, boolean flow, boolean selected) { final int top; final int left; if (mIsVertical) { top = offset; left = getPaddingLeft(); } else { top = getPaddingTop(); left = offset; } if (!mDataChanged) { // Try to use an existing view for this position final View activeChild = mRecycler.getActiveView(position); if (activeChild != null) { // Found it -- we're using an existing child // This just needs to be positioned setupChild(activeChild, position, top, left, flow, selected, true); return activeChild; } } // Make a new view for this position, or convert an unused view if possible final View child = obtainView(position, mIsScrap); // This needs to be positioned and measured setupChild(child, position, top, left, flow, selected, mIsScrap[0]); return child; } @TargetApi(11) private void setupChild(View child, int position, int top, int left, boolean flow, boolean selected, boolean recycled) { final boolean isSelected = selected && shouldShowSelector(); final boolean updateChildSelected = isSelected != child.isSelected(); final int touchMode = mTouchMode; final boolean isPressed = touchMode > TOUCH_MODE_DOWN && touchMode < TOUCH_MODE_DRAGGING && mMotionPosition == position; final boolean updateChildPressed = isPressed != child.isPressed(); final boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested(); // Respect layout params that are already in the view. Otherwise make some up... LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp == null) { lp = generateDefaultLayoutParams(); } lp.viewType = mAdapter.getItemViewType(position); if (recycled && !lp.forceAdd) { attachViewToParent(child, (flow ? -1 : 0), lp); } else { lp.forceAdd = false; addViewInLayout(child, (flow ? -1 : 0), lp, true); } if (updateChildSelected) { child.setSelected(isSelected); } if (updateChildPressed) { child.setPressed(isPressed); } if (mChoiceMode.compareTo(ChoiceMode.NONE) != 0 && mCheckStates != null) { if (child instanceof Checkable) { ((Checkable) child).setChecked(mCheckStates.get(position)); } else if (getContext().getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) { child.setActivated(mCheckStates.get(position)); } } if (needToMeasure) { measureChild(child, lp); } else { cleanupLayoutState(child); } final int w = child.getMeasuredWidth(); final int h = child.getMeasuredHeight(); final int childTop = (mIsVertical && !flow ? top - h : top); final int childLeft = (!mIsVertical && !flow ? left - w : left); if (needToMeasure) { final int childRight = childLeft + w; final int childBottom = childTop + h; child.layout(childLeft, childTop, childRight, childBottom); } else { child.offsetLeftAndRight(childLeft - child.getLeft()); child.offsetTopAndBottom(childTop - child.getTop()); } } void fillGap(boolean down) { final int childCount = getChildCount(); if (down) { final int paddingStart = (mIsVertical ? getPaddingTop() : getPaddingLeft()); final int lastEnd; if (mIsVertical) { lastEnd = getChildAt(childCount - 1).getBottom(); } else { lastEnd = getChildAt(childCount - 1).getRight(); } final int offset = (childCount > 0 ? lastEnd + mItemMargin : paddingStart); fillAfter(mFirstPosition + childCount, offset); correctTooHigh(getChildCount()); } else { final int end; final int firstStart; if (mIsVertical) { end = getHeight() - getPaddingBottom(); firstStart = getChildAt(0).getTop(); } else { end = getWidth() - getPaddingRight(); firstStart = getChildAt(0).getLeft(); } final int offset = (childCount > 0 ? firstStart - mItemMargin : end); fillBefore(mFirstPosition - 1, offset); correctTooLow(getChildCount()); } } private View fillBefore(int pos, int nextOffset) { View selectedView = null; final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft()); while (nextOffset > start && pos >= 0) { boolean isSelected = (pos == mSelectedPosition); View child = makeAndAddView(pos, nextOffset, false, isSelected); if (mIsVertical) { nextOffset = child.getTop() - mItemMargin; } else { nextOffset = child.getLeft() - mItemMargin; } if (isSelected) { selectedView = child; } pos--; } mFirstPosition = pos + 1; return selectedView; } private View fillAfter(int pos, int nextOffset) { View selectedView = null; final int end = (mIsVertical ? getHeight() - getPaddingBottom() : getWidth() - getPaddingRight()); while (nextOffset < end && pos < mItemCount) { boolean selected = (pos == mSelectedPosition); View child = makeAndAddView(pos, nextOffset, true, selected); if (mIsVertical) { nextOffset = child.getBottom() + mItemMargin; } else { nextOffset = child.getRight() + mItemMargin; } if (selected) { selectedView = child; } pos++; } return selectedView; } private View fillSpecific(int position, int offset) { final boolean tempIsSelected = (position == mSelectedPosition); View temp = makeAndAddView(position, offset, true, tempIsSelected); // Possibly changed again in fillBefore if we add rows above this one. mFirstPosition = position; final int itemMargin = mItemMargin; final int offsetBefore; if (mIsVertical) { offsetBefore = temp.getTop() - itemMargin; } else { offsetBefore = temp.getLeft() - itemMargin; } final View before = fillBefore(position - 1, offsetBefore); // This will correct for the top of the first view not touching the top of the list adjustViewsStartOrEnd(); final int offsetAfter; if (mIsVertical) { offsetAfter = temp.getBottom() + itemMargin; } else { offsetAfter = temp.getRight() + itemMargin; } final View after = fillAfter(position + 1, offsetAfter); final int childCount = getChildCount(); if (childCount > 0) { correctTooHigh(childCount); } if (tempIsSelected) { return temp; } else if (before != null) { return before; } else { return after; } } private View fillFromOffset(int nextOffset) { mFirstPosition = Math.min(mFirstPosition, mSelectedPosition); mFirstPosition = Math.min(mFirstPosition, mItemCount - 1); if (mFirstPosition < 0) { mFirstPosition = 0; } return fillAfter(mFirstPosition, nextOffset); } private View fillFromMiddle(int start, int end) { final int size = end - start; int position = reconcileSelectedPosition(); View selected = makeAndAddView(position, start, true, true); mFirstPosition = position; if (mIsVertical) { int selectedHeight = selected.getMeasuredHeight(); if (selectedHeight <= size) { selected.offsetTopAndBottom((size - selectedHeight) / 2); } } else { int selectedWidth = selected.getMeasuredWidth(); if (selectedWidth <= size) { selected.offsetLeftAndRight((size - selectedWidth) / 2); } } fillBeforeAndAfter(selected, position); correctTooHigh(getChildCount()); return selected; } private void fillBeforeAndAfter(View selected, int position) { final int itemMargin = mItemMargin; final int offsetBefore; if (mIsVertical) { offsetBefore = selected.getTop() - itemMargin; } else { offsetBefore = selected.getLeft() - itemMargin; } fillBefore(position - 1, offsetBefore); adjustViewsStartOrEnd(); final int offsetAfter; if (mIsVertical) { offsetAfter = selected.getBottom() + itemMargin; } else { offsetAfter = selected.getRight() + itemMargin; } fillAfter(position + 1, offsetAfter); } private View fillFromSelection(int selectedTop, int start, int end) { final int selectedPosition = mSelectedPosition; View selected; selected = makeAndAddView(selectedPosition, selectedTop, true, true); final int selectedStart = (mIsVertical ? selected.getTop() : selected.getLeft()); final int selectedEnd = (mIsVertical ? selected.getBottom() : selected.getRight()); // Some of the newly selected item extends below the bottom of the list if (selectedEnd > end) { // Find space available above the selection into which we can scroll // upwards final int spaceAbove = selectedStart - start; // Find space required to bring the bottom of the selected item // fully into view final int spaceBelow = selectedEnd - end; final int offset = Math.min(spaceAbove, spaceBelow); // Now offset the selected item to get it into view selected.offsetTopAndBottom(-offset); } else if (selectedStart < start) { // Find space required to bring the top of the selected item fully // into view final int spaceAbove = start - selectedStart; // Find space available below the selection into which we can scroll // downwards final int spaceBelow = end - selectedEnd; final int offset = Math.min(spaceAbove, spaceBelow); // Offset the selected item to get it into view selected.offsetTopAndBottom(offset); } // Fill in views above and below fillBeforeAndAfter(selected, selectedPosition); correctTooHigh(getChildCount()); return selected; } private void correctTooHigh(int childCount) { // First see if the last item is visible. If it is not, it is OK for the // top of the list to be pushed up. final int lastPosition = mFirstPosition + childCount - 1; if (lastPosition != mItemCount - 1 || childCount == 0) { return; } // Get the last child ... final View lastChild = getChildAt(childCount - 1); // ... and its end edge final int lastEnd; if (mIsVertical) { lastEnd = lastChild.getBottom(); } else { lastEnd = lastChild.getRight(); } // This is bottom of our drawable area final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft()); final int end = (mIsVertical ? getHeight() - getPaddingBottom() : getWidth() - getPaddingRight()); // This is how far the end edge of the last view is from the end of the // drawable area int endOffset = end - lastEnd; View firstChild = getChildAt(0); int firstStart = (mIsVertical ? firstChild.getTop() : firstChild.getLeft()); // Make sure we are 1) Too high, and 2) Either there are more rows above the // first row or the first row is scrolled off the top of the drawable area if (endOffset > 0 && (mFirstPosition > 0 || firstStart < start)) { if (mFirstPosition == 0) { // Don't pull the top too far down endOffset = Math.min(endOffset, start - firstStart); } // Move everything down offsetChildren(endOffset); if (mFirstPosition > 0) { firstStart = (mIsVertical ? firstChild.getTop() : firstChild.getLeft()); // Fill the gap that was opened above mFirstPosition with more rows, if // possible fillBefore(mFirstPosition - 1, firstStart - mItemMargin); // Close up the remaining gap adjustViewsStartOrEnd(); } } } private void correctTooLow(int childCount) { // First see if the first item is visible. If it is not, it is OK for the // bottom of the list to be pushed down. if (mFirstPosition != 0 || childCount == 0) { return; } final View first = getChildAt(0); final int firstStart = (mIsVertical ? first.getTop() : first.getLeft()); final int start = (mIsVertical ? getPaddingTop() : getPaddingLeft()); final int end; if (mIsVertical) { end = getHeight() - getPaddingBottom(); } else { end = getWidth() - getPaddingRight(); } // This is how far the start edge of the first view is from the start of the // drawable area int startOffset = firstStart - start; View last = getChildAt(childCount - 1); int lastEnd = (mIsVertical ? last.getBottom() : last.getRight()); int lastPosition = mFirstPosition + childCount - 1; // Make sure we are 1) Too low, and 2) Either there are more columns/rows below the // last column/row or the last column/row is scrolled off the end of the // drawable area if (startOffset > 0) { if (lastPosition < mItemCount - 1 || lastEnd > end) { if (lastPosition == mItemCount - 1) { // Don't pull the bottom too far up startOffset = Math.min(startOffset, lastEnd - end); } // Move everything up offsetChildren(-startOffset); if (lastPosition < mItemCount - 1) { lastEnd = (mIsVertical ? last.getBottom() : last.getRight()); // Fill the gap that was opened below the last position with more rows, if // possible fillAfter(lastPosition + 1, lastEnd + mItemMargin); // Close up the remaining gap adjustViewsStartOrEnd(); } } else if (lastPosition == mItemCount - 1) { adjustViewsStartOrEnd(); } } } private void adjustViewsStartOrEnd() { if (getChildCount() == 0) { return; } final View firstChild = getChildAt(0); int delta; if (mIsVertical) { delta = firstChild.getTop() - getPaddingTop() - mItemMargin; } else { delta = firstChild.getLeft() - getPaddingLeft() - mItemMargin; } if (delta < 0) { // We only are looking to see if we are too low, not too high delta = 0; } if (delta != 0) { offsetChildren(-delta); } } @TargetApi(14) private SparseBooleanArray cloneCheckStates() { if (mCheckStates == null) { return null; } SparseBooleanArray checkedStates; if (Build.VERSION.SDK_INT >= 14) { checkedStates = mCheckStates.clone(); } else { checkedStates = new SparseBooleanArray(); for (int i = 0; i < mCheckStates.size(); i++) { checkedStates.put(mCheckStates.keyAt(i), mCheckStates.valueAt(i)); } } return checkedStates; } private int findSyncPosition() { int itemCount = mItemCount; if (itemCount == 0) { return INVALID_POSITION; } final long idToMatch = mSyncRowId; // If there isn't a selection don't hunt for it if (idToMatch == INVALID_ROW_ID) { return INVALID_POSITION; } // Pin seed to reasonable values int seed = mSyncPosition; seed = Math.max(0, seed); seed = Math.min(itemCount - 1, seed); long endTime = SystemClock.uptimeMillis() + SYNC_MAX_DURATION_MILLIS; long rowId; // first position scanned so far int first = seed; // last position scanned so far int last = seed; // True if we should move down on the next iteration boolean next = false; // True when we have looked at the first item in the data boolean hitFirst; // True when we have looked at the last item in the data boolean hitLast; // Get the item ID locally (instead of getItemIdAtPosition), so // we need the adapter final ListAdapter adapter = mAdapter; if (adapter == null) { return INVALID_POSITION; } while (SystemClock.uptimeMillis() <= endTime) { rowId = adapter.getItemId(seed); if (rowId == idToMatch) { // Found it! return seed; } hitLast = (last == itemCount - 1); hitFirst = (first == 0); if (hitLast && hitFirst) { // Looked at everything break; } if (hitFirst || (next && !hitLast)) { // Either we hit the top, or we are trying to move down last++; seed = last; // Try going up next time next = false; } else if (hitLast || (!next && !hitFirst)) { // Either we hit the bottom, or we are trying to move up first--; seed = first; // Try going down next time next = true; } } return INVALID_POSITION; } @TargetApi(16) private View obtainView(int position, boolean[] isScrap) { isScrap[0] = false; View scrapView = mRecycler.getTransientStateView(position); if (scrapView != null) { return scrapView; } scrapView = mRecycler.getScrapView(position); final View child; if (scrapView != null) { child = mAdapter.getView(position, scrapView, this); if (child != scrapView) { mRecycler.addScrapView(scrapView, position); } else { isScrap[0] = true; } } else { child = mAdapter.getView(position, null, this); } if (ViewCompat.getImportantForAccessibility(child) == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); } if (mHasStableIds) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp == null) { lp = generateDefaultLayoutParams(); } else if (!checkLayoutParams(lp)) { lp = generateLayoutParams(lp); } lp.id = mAdapter.getItemId(position); child.setLayoutParams(lp); } if (mAccessibilityDelegate == null) { mAccessibilityDelegate = new ListItemAccessibilityDelegate(); } ViewCompat.setAccessibilityDelegate(child, mAccessibilityDelegate); return child; } void resetState() { removeAllViewsInLayout(); mSelectedStart = 0; mFirstPosition = 0; mDataChanged = false; mNeedSync = false; mPendingSync = null; mOldSelectedPosition = INVALID_POSITION; mOldSelectedRowId = INVALID_ROW_ID; mOverScroll = 0; setSelectedPositionInt(INVALID_POSITION); setNextSelectedPositionInt(INVALID_POSITION); mSelectorPosition = INVALID_POSITION; mSelectorRect.setEmpty(); invalidate(); } private void rememberSyncState() { if (getChildCount() == 0) { return; } mNeedSync = true; if (mSelectedPosition >= 0) { View child = getChildAt(mSelectedPosition - mFirstPosition); mSyncRowId = mNextSelectedRowId; mSyncPosition = mNextSelectedPosition; if (child != null) { mSpecificStart = (mIsVertical ? child.getTop() : child.getLeft()); } mSyncMode = SYNC_SELECTED_POSITION; } else { // Sync the based on the offset of the first view View child = getChildAt(0); ListAdapter adapter = getAdapter(); if (mFirstPosition >= 0 && mFirstPosition < adapter.getCount()) { mSyncRowId = adapter.getItemId(mFirstPosition); } else { mSyncRowId = NO_ID; } mSyncPosition = mFirstPosition; if (child != null) { mSpecificStart = child.getTop(); } mSyncMode = SYNC_FIRST_POSITION; } } private ContextMenuInfo createContextMenuInfo(View view, int position, long id) { return new AdapterContextMenuInfo(view, position, id); } @TargetApi(11) private void updateOnScreenCheckedViews() { final int firstPos = mFirstPosition; final int count = getChildCount(); final boolean useActivated = getContext().getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB; for (int i = 0; i < count; i++) { final View child = getChildAt(i); final int position = firstPos + i; if (child instanceof Checkable) { ((Checkable) child).setChecked(mCheckStates.get(position)); } else if (useActivated) { child.setActivated(mCheckStates.get(position)); } } } @Override public boolean performItemClick(View view, int position, long id) { boolean checkedStateChanged = false; if (mChoiceMode.compareTo(ChoiceMode.MULTIPLE) == 0) { boolean checked = !mCheckStates.get(position, false); mCheckStates.put(position, checked); if (mCheckedIdStates != null && mAdapter.hasStableIds()) { if (checked) { mCheckedIdStates.put(mAdapter.getItemId(position), position); } else { mCheckedIdStates.delete(mAdapter.getItemId(position)); } } if (checked) { mCheckedItemCount++; } else { mCheckedItemCount--; } checkedStateChanged = true; } else if (mChoiceMode.compareTo(ChoiceMode.SINGLE) == 0) { boolean checked = !mCheckStates.get(position, false); if (checked) { mCheckStates.clear(); mCheckStates.put(position, true); if (mCheckedIdStates != null && mAdapter.hasStableIds()) { mCheckedIdStates.clear(); mCheckedIdStates.put(mAdapter.getItemId(position), position); } mCheckedItemCount = 1; } else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) { mCheckedItemCount = 0; } checkedStateChanged = true; } if (checkedStateChanged) { updateOnScreenCheckedViews(); } return super.performItemClick(view, position, id); } private boolean performLongPress(final View child, final int longPressPosition, final long longPressId) { // CHOICE_MODE_MULTIPLE_MODAL takes over long press. boolean handled = false; OnItemLongClickListener listener = getOnItemLongClickListener(); if (listener != null) { handled = listener.onItemLongClick(TwoWayView.this, child, longPressPosition, longPressId); } if (!handled) { mContextMenuInfo = createContextMenuInfo(child, longPressPosition, longPressId); handled = super.showContextMenuForChild(TwoWayView.this); } if (handled) { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); } return handled; } @Override protected LayoutParams generateDefaultLayoutParams() { if (mIsVertical) { return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } else { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); } } @Override protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { return new LayoutParams(lp); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams lp) { return lp instanceof LayoutParams; } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } @Override protected ContextMenuInfo getContextMenuInfo() { return mContextMenuInfo; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); if (mPendingSync != null) { ss.selectedId = mPendingSync.selectedId; ss.firstId = mPendingSync.firstId; ss.viewStart = mPendingSync.viewStart; ss.position = mPendingSync.position; ss.height = mPendingSync.height; return ss; } boolean haveChildren = (getChildCount() > 0 && mItemCount > 0); long selectedId = getSelectedItemId(); ss.selectedId = selectedId; ss.height = getHeight(); if (selectedId >= 0) { ss.viewStart = mSelectedStart; ss.position = getSelectedItemPosition(); ss.firstId = INVALID_POSITION; } else if (haveChildren && mFirstPosition > 0) { // Remember the position of the first child. // We only do this if we are not currently at the top of // the list, for two reasons: // // (1) The list may be in the process of becoming empty, in // which case mItemCount may not be 0, but if we try to // ask for any information about position 0 we will crash. // // (2) Being "at the top" seems like a special case, anyway, // and the user wouldn't expect to end up somewhere else when // they revisit the list even if its content has changed. View child = getChildAt(0); ss.viewStart = (mIsVertical ? child.getTop() : child.getLeft()); int firstPos = mFirstPosition; if (firstPos >= mItemCount) { firstPos = mItemCount - 1; } ss.position = firstPos; ss.firstId = mAdapter.getItemId(firstPos); } else { ss.viewStart = 0; ss.firstId = INVALID_POSITION; ss.position = 0; } if (mCheckStates != null) { ss.checkState = cloneCheckStates(); } if (mCheckedIdStates != null) { final LongSparseArray<Integer> idState = new LongSparseArray<Integer>(); final int count = mCheckedIdStates.size(); for (int i = 0; i < count; i++) { idState.put(mCheckedIdStates.keyAt(i), mCheckedIdStates.valueAt(i)); } ss.checkIdState = idState; } ss.checkedItemCount = mCheckedItemCount; return ss; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); mDataChanged = true; mSyncHeight = ss.height; if (ss.selectedId >= 0) { mNeedSync = true; mPendingSync = ss; mSyncRowId = ss.selectedId; mSyncPosition = ss.position; mSpecificStart = ss.viewStart; mSyncMode = SYNC_SELECTED_POSITION; } else if (ss.firstId >= 0) { setSelectedPositionInt(INVALID_POSITION); // Do this before setting mNeedSync since setNextSelectedPosition looks at mNeedSync setNextSelectedPositionInt(INVALID_POSITION); mSelectorPosition = INVALID_POSITION; mNeedSync = true; mPendingSync = ss; mSyncRowId = ss.firstId; mSyncPosition = ss.position; mSpecificStart = ss.viewStart; mSyncMode = SYNC_FIRST_POSITION; } if (ss.checkState != null) { mCheckStates = ss.checkState; } if (ss.checkIdState != null) { mCheckedIdStates = ss.checkIdState; } mCheckedItemCount = ss.checkedItemCount; requestLayout(); } public static class LayoutParams extends ViewGroup.LayoutParams { /** * Type of this view as reported by the adapter */ int viewType; /** * The stable ID of the item this view displays */ long id = -1; /** * The position the view was removed from when pulled out of the * scrap heap. * @hide */ int scrappedFromPosition; /** * When a TwoWayView is measured with an AT_MOST measure spec, it needs * to obtain children views to measure itself. When doing so, the children * are not attached to the window, but put in the recycler which assumes * they've been attached before. Setting this flag will force the reused * view to be attached to the window rather than just attached to the * parent. */ boolean forceAdd; public LayoutParams(int width, int height) { super(width, height); if (this.width == MATCH_PARENT) { Log.w(LOGTAG, "Constructing LayoutParams with width FILL_PARENT " + "does not make much sense as the view might change orientation. " + "Falling back to WRAP_CONTENT"); this.width = WRAP_CONTENT; } if (this.height == MATCH_PARENT) { Log.w(LOGTAG, "Constructing LayoutParams with height FILL_PARENT " + "does not make much sense as the view might change orientation. " + "Falling back to WRAP_CONTENT"); this.height = WRAP_CONTENT; } } public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); if (this.width == MATCH_PARENT) { Log.w(LOGTAG, "Inflation setting LayoutParams width to MATCH_PARENT - " + "does not make much sense as the view might change orientation. " + "Falling back to WRAP_CONTENT"); this.width = MATCH_PARENT; } if (this.height == MATCH_PARENT) { Log.w(LOGTAG, "Inflation setting LayoutParams height to MATCH_PARENT - " + "does not make much sense as the view might change orientation. " + "Falling back to WRAP_CONTENT"); this.height = WRAP_CONTENT; } } public LayoutParams(ViewGroup.LayoutParams other) { super(other); if (this.width == MATCH_PARENT) { Log.w(LOGTAG, "Constructing LayoutParams with width MATCH_PARENT - " + "does not make much sense as the view might change orientation. " + "Falling back to WRAP_CONTENT"); this.width = WRAP_CONTENT; } if (this.height == MATCH_PARENT) { Log.w(LOGTAG, "Constructing LayoutParams with height MATCH_PARENT - " + "does not make much sense as the view might change orientation. " + "Falling back to WRAP_CONTENT"); this.height = WRAP_CONTENT; } } } class RecycleBin { private RecyclerListener mRecyclerListener; private int mFirstActivePosition; private View[] mActiveViews = new View[0]; private ArrayList<View>[] mScrapViews; private int mViewTypeCount; private ArrayList<View> mCurrentScrap; private SparseArrayCompat<View> mTransientStateViews; public void setViewTypeCount(int viewTypeCount) { if (viewTypeCount < 1) { throw new IllegalArgumentException("Can't have a viewTypeCount < 1"); } @SuppressWarnings("unchecked") ArrayList<View>[] scrapViews = new ArrayList[viewTypeCount]; for (int i = 0; i < viewTypeCount; i++) { scrapViews[i] = new ArrayList<View>(); } mViewTypeCount = viewTypeCount; mCurrentScrap = scrapViews[0]; mScrapViews = scrapViews; } public void markChildrenDirty() { if (mViewTypeCount == 1) { final ArrayList<View> scrap = mCurrentScrap; final int scrapCount = scrap.size(); for (int i = 0; i < scrapCount; i++) { scrap.get(i).forceLayout(); } } else { final int typeCount = mViewTypeCount; for (int i = 0; i < typeCount; i++) { final ArrayList<View> scrap = mScrapViews[i]; final int scrapCount = scrap.size(); for (int j = 0; j < scrapCount; j++) { scrap.get(j).forceLayout(); } } } if (mTransientStateViews != null) { final int count = mTransientStateViews.size(); for (int i = 0; i < count; i++) { mTransientStateViews.valueAt(i).forceLayout(); } } } public boolean shouldRecycleViewType(int viewType) { return viewType >= 0; } void clear() { if (mViewTypeCount == 1) { final ArrayList<View> scrap = mCurrentScrap; final int scrapCount = scrap.size(); for (int i = 0; i < scrapCount; i++) { removeDetachedView(scrap.remove(scrapCount - 1 - i), false); } } else { final int typeCount = mViewTypeCount; for (int i = 0; i < typeCount; i++) { final ArrayList<View> scrap = mScrapViews[i]; final int scrapCount = scrap.size(); for (int j = 0; j < scrapCount; j++) { removeDetachedView(scrap.remove(scrapCount - 1 - j), false); } } } if (mTransientStateViews != null) { mTransientStateViews.clear(); } } void fillActiveViews(int childCount, int firstActivePosition) { if (mActiveViews.length < childCount) { mActiveViews = new View[childCount]; } mFirstActivePosition = firstActivePosition; final View[] activeViews = mActiveViews; for (int i = 0; i < childCount; i++) { View child = getChildAt(i); // Note: We do place AdapterView.ITEM_VIEW_TYPE_IGNORE in active views. // However, we will NOT place them into scrap views. activeViews[i] = child; } } View getActiveView(int position) { final int index = position - mFirstActivePosition; final View[] activeViews = mActiveViews; if (index >= 0 && index < activeViews.length) { final View match = activeViews[index]; activeViews[index] = null; return match; } return null; } View getTransientStateView(int position) { if (mTransientStateViews == null) { return null; } final int index = mTransientStateViews.indexOfKey(position); if (index < 0) { return null; } final View result = mTransientStateViews.valueAt(index); mTransientStateViews.removeAt(index); return result; } void clearTransientStateViews() { if (mTransientStateViews != null) { mTransientStateViews.clear(); } } View getScrapView(int position) { if (mViewTypeCount == 1) { return retrieveFromScrap(mCurrentScrap, position); } else { int whichScrap = mAdapter.getItemViewType(position); if (whichScrap >= 0 && whichScrap < mScrapViews.length) { return retrieveFromScrap(mScrapViews[whichScrap], position); } } return null; } @TargetApi(14) void addScrapView(View scrap, int position) { LayoutParams lp = (LayoutParams) scrap.getLayoutParams(); if (lp == null) { return; } lp.scrappedFromPosition = position; final int viewType = lp.viewType; final boolean scrapHasTransientState = ViewCompat.hasTransientState(scrap); // Don't put views that should be ignored into the scrap heap if (!shouldRecycleViewType(viewType) || scrapHasTransientState) { if (scrapHasTransientState) { if (mTransientStateViews == null) { mTransientStateViews = new SparseArrayCompat<View>(); } mTransientStateViews.put(position, scrap); } return; } if (mViewTypeCount == 1) { mCurrentScrap.add(scrap); } else { mScrapViews[viewType].add(scrap); } // FIXME: Unfortunately, ViewCompat.setAccessibilityDelegate() doesn't accept // null delegates. if (Build.VERSION.SDK_INT >= 14) { scrap.setAccessibilityDelegate(null); } if (mRecyclerListener != null) { mRecyclerListener.onMovedToScrapHeap(scrap); } } @TargetApi(14) void scrapActiveViews() { final View[] activeViews = mActiveViews; final boolean multipleScraps = (mViewTypeCount > 1); ArrayList<View> scrapViews = mCurrentScrap; final int count = activeViews.length; for (int i = count - 1; i >= 0; i--) { final View victim = activeViews[i]; if (victim != null) { final LayoutParams lp = (LayoutParams) victim.getLayoutParams(); int whichScrap = lp.viewType; activeViews[i] = null; final boolean scrapHasTransientState = ViewCompat.hasTransientState(victim); if (!shouldRecycleViewType(whichScrap) || scrapHasTransientState) { if (scrapHasTransientState) { removeDetachedView(victim, false); if (mTransientStateViews == null) { mTransientStateViews = new SparseArrayCompat<View>(); } mTransientStateViews.put(mFirstActivePosition + i, victim); } continue; } if (multipleScraps) { scrapViews = mScrapViews[whichScrap]; } lp.scrappedFromPosition = mFirstActivePosition + i; scrapViews.add(victim); // FIXME: Unfortunately, ViewCompat.setAccessibilityDelegate() doesn't accept // null delegates. if (Build.VERSION.SDK_INT >= 14) { victim.setAccessibilityDelegate(null); } if (mRecyclerListener != null) { mRecyclerListener.onMovedToScrapHeap(victim); } } } pruneScrapViews(); } private void pruneScrapViews() { final int maxViews = mActiveViews.length; final int viewTypeCount = mViewTypeCount; final ArrayList<View>[] scrapViews = mScrapViews; for (int i = 0; i < viewTypeCount; ++i) { final ArrayList<View> scrapPile = scrapViews[i]; int size = scrapPile.size(); final int extras = size - maxViews; size--; for (int j = 0; j < extras; j++) { removeDetachedView(scrapPile.remove(size--), false); } } if (mTransientStateViews != null) { for (int i = 0; i < mTransientStateViews.size(); i++) { final View v = mTransientStateViews.valueAt(i); if (!ViewCompat.hasTransientState(v)) { mTransientStateViews.removeAt(i); i--; } } } } void reclaimScrapViews(List<View> views) { if (mViewTypeCount == 1) { views.addAll(mCurrentScrap); } else { final int viewTypeCount = mViewTypeCount; final ArrayList<View>[] scrapViews = mScrapViews; for (int i = 0; i < viewTypeCount; ++i) { final ArrayList<View> scrapPile = scrapViews[i]; views.addAll(scrapPile); } } } View retrieveFromScrap(ArrayList<View> scrapViews, int position) { int size = scrapViews.size(); if (size <= 0) { return null; } for (int i = 0; i < size; i++) { final View scrapView = scrapViews.get(i); final LayoutParams lp = (LayoutParams) scrapView.getLayoutParams(); if (lp.scrappedFromPosition == position) { scrapViews.remove(i); return scrapView; } } return scrapViews.remove(size - 1); } } @Override public void setEmptyView(View emptyView) { super.setEmptyView(emptyView); mEmptyView = emptyView; updateEmptyStatus(); } @Override public void setFocusable(boolean focusable) { final ListAdapter adapter = getAdapter(); final boolean empty = (adapter == null || adapter.getCount() == 0); mDesiredFocusableState = focusable; if (!focusable) { mDesiredFocusableInTouchModeState = false; } super.setFocusable(focusable && !empty); } @Override public void setFocusableInTouchMode(boolean focusable) { final ListAdapter adapter = getAdapter(); final boolean empty = (adapter == null || adapter.getCount() == 0); mDesiredFocusableInTouchModeState = focusable; if (focusable) { mDesiredFocusableState = true; } super.setFocusableInTouchMode(focusable && !empty); } private void checkFocus() { final ListAdapter adapter = getAdapter(); final boolean focusable = (adapter != null && adapter.getCount() > 0); // The order in which we set focusable in touch mode/focusable may matter // for the client, see View.setFocusableInTouchMode() comments for more // details super.setFocusableInTouchMode(focusable && mDesiredFocusableInTouchModeState); super.setFocusable(focusable && mDesiredFocusableState); if (mEmptyView != null) { updateEmptyStatus(); } } private void updateEmptyStatus() { final boolean isEmpty = (mAdapter == null || mAdapter.isEmpty()); if (isEmpty) { if (mEmptyView != null) { mEmptyView.setVisibility(View.VISIBLE); setVisibility(View.GONE); } else { // If the caller just removed our empty view, make sure the list // view is visible setVisibility(View.VISIBLE); } // We are now GONE, so pending layouts will not be dispatched. // Force one here to make sure that the state of the list matches // the state of the adapter. if (mDataChanged) { layout(getLeft(), getTop(), getRight(), getBottom()); } } else { if (mEmptyView != null) { mEmptyView.setVisibility(View.GONE); } setVisibility(View.VISIBLE); } } private class AdapterDataSetObserver extends DataSetObserver { private Parcelable mInstanceState = null; @Override public void onChanged() { mDataChanged = true; mOldItemCount = mItemCount; mItemCount = getAdapter().getCount(); // Detect the case where a cursor that was previously invalidated has // been re-populated with new data. if (TwoWayView.this.mHasStableIds && mInstanceState != null && mOldItemCount == 0 && mItemCount > 0) { TwoWayView.this.onRestoreInstanceState(mInstanceState); mInstanceState = null; } else { rememberSyncState(); } checkFocus(); requestLayout(); } @Override public void onInvalidated() { mDataChanged = true; if (TwoWayView.this.mHasStableIds) { // Remember the current state for the case where our hosting activity is being // stopped and later restarted mInstanceState = TwoWayView.this.onSaveInstanceState(); } // Data is invalid so we should reset our state mOldItemCount = mItemCount; mItemCount = 0; mSelectedPosition = INVALID_POSITION; mSelectedRowId = INVALID_ROW_ID; mNextSelectedPosition = INVALID_POSITION; mNextSelectedRowId = INVALID_ROW_ID; mNeedSync = false; checkFocus(); requestLayout(); } } static class SavedState extends BaseSavedState { long selectedId; long firstId; int viewStart; int position; int height; int checkedItemCount; SparseBooleanArray checkState; LongSparseArray<Integer> checkIdState; /** * Constructor called from {@link TwoWayView#onSaveInstanceState()} */ SavedState(Parcelable superState) { super(superState); } /** * Constructor called from {@link #CREATOR} */ private SavedState(Parcel in) { super(in); selectedId = in.readLong(); firstId = in.readLong(); viewStart = in.readInt(); position = in.readInt(); height = in.readInt(); checkedItemCount = in.readInt(); checkState = in.readSparseBooleanArray(); final int N = in.readInt(); if (N > 0) { checkIdState = new LongSparseArray<Integer>(); for (int i = 0; i < N; i++) { final long key = in.readLong(); final int value = in.readInt(); checkIdState.put(key, value); } } } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeLong(selectedId); out.writeLong(firstId); out.writeInt(viewStart); out.writeInt(position); out.writeInt(height); out.writeInt(checkedItemCount); out.writeSparseBooleanArray(checkState); final int N = checkIdState != null ? checkIdState.size() : 0; out.writeInt(N); for (int i = 0; i < N; i++) { out.writeLong(checkIdState.keyAt(i)); out.writeInt(checkIdState.valueAt(i)); } } @Override public String toString() { return "TwoWayView.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " selectedId=" + selectedId + " firstId=" + firstId + " viewStart=" + viewStart + " height=" + height + " position=" + position + " checkState=" + checkState + "}"; } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } private class SelectionNotifier implements Runnable { @Override public void run() { if (mDataChanged) { // Data has changed between when this SelectionNotifier // was posted and now. We need to wait until the AdapterView // has been synched to the new data. if (mAdapter != null) { post(this); } } else { fireOnSelected(); performAccessibilityActionsOnSelected(); } } } private class WindowRunnnable { private int mOriginalAttachCount; public void rememberWindowAttachCount() { mOriginalAttachCount = getWindowAttachCount(); } public boolean sameWindow() { return hasWindowFocus() && getWindowAttachCount() == mOriginalAttachCount; } } private class PerformClick extends WindowRunnnable implements Runnable { int mClickMotionPosition; @Override public void run() { if (mDataChanged) { return; } final ListAdapter adapter = mAdapter; final int motionPosition = mClickMotionPosition; if (adapter != null && mItemCount > 0 && motionPosition != INVALID_POSITION && motionPosition < adapter.getCount() && sameWindow()) { final View child = getChildAt(motionPosition - mFirstPosition); if (child != null) { performItemClick(child, motionPosition, adapter.getItemId(motionPosition)); } } } } private final class CheckForTap implements Runnable { @Override public void run() { if (mTouchMode != TOUCH_MODE_DOWN) { return; } mTouchMode = TOUCH_MODE_TAP; final View child = getChildAt(mMotionPosition - mFirstPosition); if (child != null && !child.hasFocusable()) { mLayoutMode = LAYOUT_NORMAL; if (!mDataChanged) { setPressed(true); child.setPressed(true); layoutChildren(); positionSelector(mMotionPosition, child); refreshDrawableState(); positionSelector(mMotionPosition, child); refreshDrawableState(); final boolean longClickable = isLongClickable(); if (mSelector != null) { Drawable d = mSelector.getCurrent(); if (d != null && d instanceof TransitionDrawable) { if (longClickable) { final int longPressTimeout = ViewConfiguration.getLongPressTimeout(); ((TransitionDrawable) d).startTransition(longPressTimeout); } else { ((TransitionDrawable) d).resetTransition(); } } } if (longClickable) { triggerCheckForLongPress(); } else { mTouchMode = TOUCH_MODE_DONE_WAITING; } } else { mTouchMode = TOUCH_MODE_DONE_WAITING; } } } } private class CheckForLongPress extends WindowRunnnable implements Runnable { @Override public void run() { final int motionPosition = mMotionPosition; final View child = getChildAt(motionPosition - mFirstPosition); if (child != null) { final long longPressId = mAdapter.getItemId(mMotionPosition); boolean handled = false; if (sameWindow() && !mDataChanged) { handled = performLongPress(child, motionPosition, longPressId); } if (handled) { mTouchMode = TOUCH_MODE_REST; setPressed(false); child.setPressed(false); } else { mTouchMode = TOUCH_MODE_DONE_WAITING; } } } } private class CheckForKeyLongPress extends WindowRunnnable implements Runnable { public void run() { if (!isPressed() || mSelectedPosition < 0) { return; } final int index = mSelectedPosition - mFirstPosition; final View v = getChildAt(index); if (!mDataChanged) { boolean handled = false; if (sameWindow()) { handled = performLongPress(v, mSelectedPosition, mSelectedRowId); } if (handled) { setPressed(false); v.setPressed(false); } } else { setPressed(false); if (v != null) { v.setPressed(false); } } } } private static class ArrowScrollFocusResult { private int mSelectedPosition; private int mAmountToScroll; /** * How {@link TwoWayView#arrowScrollFocused} returns its values. */ void populate(int selectedPosition, int amountToScroll) { mSelectedPosition = selectedPosition; mAmountToScroll = amountToScroll; } public int getSelectedPosition() { return mSelectedPosition; } public int getAmountToScroll() { return mAmountToScroll; } } private class ListItemAccessibilityDelegate extends AccessibilityDelegateCompat { @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(host, info); final int position = getPositionForView(host); final ListAdapter adapter = getAdapter(); // Cannot perform actions on invalid items if (position == INVALID_POSITION || adapter == null) { return; } // Cannot perform actions on disabled items if (!isEnabled() || !adapter.isEnabled(position)) { return; } if (position == getSelectedItemPosition()) { info.setSelected(true); info.addAction(AccessibilityNodeInfoCompat.ACTION_CLEAR_SELECTION); } else { info.addAction(AccessibilityNodeInfoCompat.ACTION_SELECT); } if (isClickable()) { info.addAction(AccessibilityNodeInfoCompat.ACTION_CLICK); info.setClickable(true); } if (isLongClickable()) { info.addAction(AccessibilityNodeInfoCompat.ACTION_LONG_CLICK); info.setLongClickable(true); } } @Override public boolean performAccessibilityAction(View host, int action, Bundle arguments) { if (super.performAccessibilityAction(host, action, arguments)) { return true; } final int position = getPositionForView(host); final ListAdapter adapter = getAdapter(); // Cannot perform actions on invalid items if (position == INVALID_POSITION || adapter == null) { return false; } // Cannot perform actions on disabled items if (!isEnabled() || !adapter.isEnabled(position)) { return false; } final long id = getItemIdAtPosition(position); switch (action) { case AccessibilityNodeInfoCompat.ACTION_CLEAR_SELECTION: if (getSelectedItemPosition() == position) { setSelection(INVALID_POSITION); return true; } return false; case AccessibilityNodeInfoCompat.ACTION_SELECT: if (getSelectedItemPosition() != position) { setSelection(position); return true; } return false; case AccessibilityNodeInfoCompat.ACTION_CLICK: if (isClickable()) { return performItemClick(host, position, id); } return false; case AccessibilityNodeInfoCompat.ACTION_LONG_CLICK: if (isLongClickable()) { return performLongPress(host, position, id); } return false; } return false; } } }
[ "390553699@qq.com" ]
390553699@qq.com
94e471a17d7dc9bce3f1fb81a3852737e43a54ce
7a6bf4385a17b1010646e06e8024375514386a86
/avatar-finance/avatar-finance-dao/src/main/java/com/kirana/avatar/finance/repositories/BankAccountRepository.java
6f3398419598d960f27101228a0e875bbc315043
[]
no_license
dhamotharang/avatar
bd7a11d68b3e1e0ed96a604f1efdf803a366b3ff
9799130f74e48bfedc67cace73848dc86ee09d45
refs/heads/master
2023-05-07T10:41:02.466182
2019-07-10T06:44:03
2019-07-10T06:44:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
355
java
package com.kirana.avatar.finance.repositories; import org.springframework.stereotype.Repository; import com.kirana.avatar.common.jpa.repository.BaseRepository; import com.kirana.avatar.finance.model.BankAccount; /** * @author __Telmila__ * */ @Repository public interface BankAccountRepository extends BaseRepository<BankAccount> { }
[ "arunnprakash@gmail.com" ]
arunnprakash@gmail.com
03a28381036083fb6a1ca507081a975754c3e8d0
59e77e378726a0fd1c5c915a07f2454153370263
/app/src/main/java/com/l000phone/autohomen/GuideActivity.java
76e8cfc4b5dd5f747a1650358225c8304d13715e
[]
no_license
xutongle/AutoHomen
55c0a794b6e59a9261f141c111bfa0742cb25693
a540e7b246fa60c8a14d07bf9892455912fbddaa
refs/heads/master
2021-01-18T19:00:55.446610
2016-11-30T10:33:07
2016-11-30T10:33:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,789
java
package com.l000phone.autohomen; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.l000phone.fragment.GuideFragment; import java.util.LinkedList; import java.util.List; /** * 引导界面 * Created by DJ on 2016/10/27. */ public class GuideActivity extends AppCompatActivity { private ViewPager guideVp; private List<GuideFragment> ds; private LinearLayout guideLl; private int before; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //偏好参数实例的获取 SharedPreferences sharedPreferences = getSharedPreferences("info", MODE_PRIVATE); //第一次默认是false,true代表使用过,false代表第一次使用 boolean isUse = sharedPreferences.getBoolean("isUse", false); if(isUse){ //跳转到主界面 startActivity(new Intent(this,Welcome.class)); //然后销毁界面 finish(); }else{ //若没有使用加载引导界面 setContentView(R.layout.activity_guide); Log.i("dj","走了么"); //获得界面控件的实例 guideVp = (ViewPager) findViewById(R.id.guide_vp_id); guideLl = (LinearLayout) findViewById(R.id.guide_ll_id); //关于小圆点的操作 aboutYuanDian(); //关于ViewPager的操作 aboutViewPager(); } } /** * 关于ViewPager的操作 */ private void aboutViewPager() { //数据源 ds = new LinkedList<>(); //填充数据源 fillDs(); //适配器 MyAdapter adapter = new MyAdapter(getSupportFragmentManager()); //绑定适配器 guideVp.setAdapter(adapter); //添加监听器 guideVp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){ @Override public void onPageSelected(int position) { guideLl.getChildAt(position).setEnabled(false); guideLl.getChildAt(before).setEnabled(true); before=position; super.onPageSelected(position); } }); } /** * ViewPager自定义适配器 */ private final class MyAdapter extends FragmentStatePagerAdapter { public MyAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return ds.get(position); } @Override public int getCount() { return ds.size(); } } /** * 填充数据源 */ private void fillDs() { //获得图片对应的名字数组 String[] pics = getResources().getStringArray(R.array.picName); //将图片转换成ImageView的实例,传递到GuideFragment for(String pic:pics){ int picId = getResources().getIdentifier(pic, "drawable", getPackageName()); addGuideFragment(picId); } addGuideFragment(0); } private void addGuideFragment(int picId) { GuideFragment guideF = new GuideFragment(); Bundle args = new Bundle(); args.putInt("picId",picId); guideF.setArguments(args); ds.add(guideF); } /** * 关于小圆点的操作 */ private void aboutYuanDian() { MyListener listener = new MyListener(); //小圆点初始化 for(int i=0;i<guideLl.getChildCount();i++){ ImageView mIv = (ImageView) guideLl.getChildAt(i); //设置小圆点的属性,可点击 mIv.setEnabled(true); //给小圆点添加别名 mIv.setTag(i); //给每个小圆点添加监听器 mIv.setOnClickListener(listener); } //默认第一个是选中 guideLl.getChildAt(0).setEnabled(false); } /** * 监听器实现类(小圆点) */ private final class MyListener implements View.OnClickListener{ @Override public void onClick(View view) { //小圆点的别名和在数据源的编号是一致的 guideVp.setCurrentItem((Integer) view.getTag()); } } }
[ "173627694@qq.com" ]
173627694@qq.com
2a637a26d12f8121e0db7fe81d5f0660d2233bb5
e5c4242727344587cf76f0f2aa97759390ab6290
/src/main/java/com/example/prutest/mappers/EmployeesMapper.java
1b9746b4811edd5e7de71acdf405a84323cad641
[]
no_license
ivandemydko/prutest
ec9f0410bc3335609e993c35392bfdf092a61671
17d494dc502d524e2034f71e2be0da4a97ee3e1d
refs/heads/master
2023-01-12T06:07:13.396186
2020-11-16T18:17:43
2020-11-16T18:17:43
312,032,972
0
0
null
2020-11-16T18:17:44
2020-11-11T16:52:45
Java
UTF-8
Java
false
false
679
java
package com.example.prutest.mappers; import com.example.prutest.entities.Employee; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.List; @Mapper @Component public interface EmployeesMapper { List<HashMap<String, Object>> getTopFiveNamesOfEmployeesAndProfit(); List<Employee> getTopEmployees(@Param("limit") int limit); void addEmployee(Employee employee); List<Employee> getAllEmployees(); List<Employee> findEmployeesByOfficeCodeAndJobTitle(@Param("officeCode") int officeCode, @Param("jobTitle") String jobTitle); }
[ "ivandemydko@gmail.com" ]
ivandemydko@gmail.com
89d81af11e126a554d6444824d5a638c3120d308
5eae683a6df0c4b97ab1ebcd4724a4bf062c1889
/bin/ext-commerce/subscriptionbundlecockpits/src/de/hybris/platform/subscriptionbundlecockpits/jalo/SubscriptionbundlecockpitsManager.java
f887923c167fa7da051d76daa21ea5022acd39f4
[]
no_license
sujanrimal/GiftCardProject
1c5e8fe494e5c59cca58bbc76a755b1b0c0333bb
e0398eec9f4ec436d20764898a0255f32aac3d0c
refs/heads/master
2020-12-11T18:05:17.413472
2020-01-17T18:23:44
2020-01-17T18:23:44
233,911,127
0
0
null
2020-06-18T15:26:11
2020-01-14T18:44:18
null
UTF-8
Java
false
false
1,211
java
/* * * [y] hybris Platform * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.subscriptionbundlecockpits.jalo; import de.hybris.platform.jalo.JaloSession; import de.hybris.platform.jalo.extension.ExtensionManager; import de.hybris.platform.subscriptionbundlecockpits.constants.SubscriptionbundlecockpitsConstants; import org.apache.log4j.Logger; @SuppressWarnings("PMD") public class SubscriptionbundlecockpitsManager extends GeneratedSubscriptionbundlecockpitsManager { @SuppressWarnings("unused") private static final Logger log = Logger.getLogger( SubscriptionbundlecockpitsManager.class.getName() ); public static final SubscriptionbundlecockpitsManager getInstance() { ExtensionManager em = JaloSession.getCurrentSession().getExtensionManager(); return (SubscriptionbundlecockpitsManager) em.getExtension(SubscriptionbundlecockpitsConstants.EXTENSIONNAME); } }
[ "travis.d.crawford@accenture.com" ]
travis.d.crawford@accenture.com
0c98d10c2e1797bc3cfa2a41d9b6da3af4cebada
f662526b79170f8eeee8a78840dd454b1ea8048c
/ant$a.java
04c50e525b21059d63d9bea56c4962df7413a580
[]
no_license
jason920612/Minecraft
5d3cd1eb90726efda60a61e8ff9e057059f9a484
5bd5fb4dac36e23a2c16576118da15c4890a2dff
refs/heads/master
2023-01-12T17:04:25.208957
2020-11-26T08:51:21
2020-11-26T08:51:21
316,170,984
0
0
null
null
null
null
UTF-8
Java
false
false
2,515
java
/* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ class a /* */ extends aio<afa> /* */ { /* */ public a(ant ☃) { /* 177 */ super(☃, afa.class, 0, true, true, ant.dA()); /* */ } /* */ /* */ /* */ public boolean a() { /* 182 */ return (ant.a((ant)this.e) && super.a()); /* */ } /* */ } /* Location: F:\dw\server.jar!\ant$a.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
[ "jasonya2206@gmail.com" ]
jasonya2206@gmail.com
597fcde420e0f187cb08fec3b04089633b208607
246e1cbd80c3ae6162da0dd89ec9e93137052c4f
/src/DBCRUD/PostgreSQL/tblKlinikTanimlari.java
d693347601a2d1dfa757c3b7d66b0c1f90938ac9
[]
no_license
rifatcan/hastaneotomasyonu
077cf9b6eb9572e6a236b36e60b11cf2c7ef708f
b37ce761fa524d4ceb67846d3d53a35a3c696b7a
refs/heads/master
2021-05-01T05:40:41.025235
2018-02-11T13:40:19
2018-02-11T13:40:19
121,127,084
0
0
null
null
null
null
UTF-8
Java
false
false
2,085
java
/* * 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 DBCRUD.PostgreSQL; import DBBaglantilari.allConnections; import DBFramework.ICRUD; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author rbarka */ public class tblKlinikTanimlari implements ICRUD{ allConnections baglanti = new allConnections(); @Override public void Kaydet(Object o) { try { PreparedStatement ifade = baglanti.baglan().prepareCall("insert into tblklinik_tanimlari(id,klinik_adi,kapasite) values('3','Cildiye',30)"); ifade.executeUpdate(); } catch (ClassNotFoundException ex) { Logger.getLogger(tblkangrubu.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(tblkangrubu.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void Duzenle(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void Sil(long id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List<Object> Listele() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Object Bul(long id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public static void main(String[] args) { tblKlinikTanimlari klinik = new tblKlinikTanimlari(); klinik.Kaydet(""); } }
[ "rbarka@N109402.innova.com.tr" ]
rbarka@N109402.innova.com.tr
367e03e9fa1ea7324b7d1b9a067628f6ed3de97e
260ffca605956d7cb9490a8c33e2fe856e5c97bf
/src/com/google/android/gms/drive/zzd.java
ffac40a86a36828428da216cd8d3b2bdbe1ef27b
[]
no_license
yazid2016/com.incorporateapps.fakegps.fre
cf7f1802fcc6608ff9a1b82b73a17675d8068beb
44856c804cea36982fcc61d039a46761a8103787
refs/heads/master
2021-06-02T23:32:09.654199
2016-07-21T03:28:48
2016-07-21T03:28:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
206
java
package com.google.android.gms.drive; public abstract interface zzd {} /* Location: * Qualified Name: com.google.android.gms.drive.zzd * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "reverseengineeringer@hackeradmin.com" ]
reverseengineeringer@hackeradmin.com
61f47719058728d82aeb5b84c56302d323c1721d
a78ed6c3ec41789684c713015fc8d89d74fcf5f7
/vigor-web/src/main/java/cn/vigor/modules/compute/bean/OutputTemplate.java
301a1227f0341ec44cc4f11fa6a1389ac7557fa6
[]
no_license
wangzkiss/spring-boot-examples
b04da95a4204284de332e9af87cbffeda8b6a0e7
13441c9e904d8796f2fdebb88cdd3938498ebca6
refs/heads/master
2021-01-21T06:47:29.314223
2017-10-30T12:00:49
2017-10-30T12:00:49
101,947,141
0
0
null
2017-08-31T01:51:40
2017-08-31T01:51:40
null
UTF-8
Java
false
false
1,451
java
package cn.vigor.modules.compute.bean; /** * 数据存储模板 * @author yangtao * */ public class OutputTemplate extends ModelObject{ private int type; private String ip; private int id; private int port; private String db; private String typeText; private String username = ""; private String password = ""; public void setType(int type) { firePropertyChange("type", this.type, this.type = type); } public int getType() { return type; } public String getIp() { return ip; } public void setIp(String ip) { firePropertyChange("ip", this.ip, this.ip = ip); } public int getPort() { return port; } public void setPort(int port) { firePropertyChange("port", this.port, this.port = port); } public String getDb() { return db; } public void setDb(String db) { firePropertyChange("db", this.db, this.db = db); } public String getTypeText() { return typeText; } public void setTypeText(String typeText) { firePropertyChange("typeText", this.typeText, this.typeText = typeText); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { if(username != null) this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { if(password != null) this.password = password; } }
[ "wangzhaowen@tospur.com" ]
wangzhaowen@tospur.com
698526abd6b974b807699498a795cab3bac65ac6
96a247bca3064d5689e87c387aee1a86ccb8d691
/src/main/java/ar/com/kecat/repositories/TarjetaRepository.java
4bfd7b141751c23336806ccda8b623ac6ec30ddd
[]
no_license
villat/IntegracionApi
b78797f9ba045d2ceac4908351388d9518be9b7c
8ba16d424343d3608e021fe5099df45964a8eb10
refs/heads/master
2020-04-03T15:48:06.731886
2018-11-02T22:09:30
2018-11-02T22:09:30
155,378,051
0
0
null
null
null
null
UTF-8
Java
false
false
636
java
package ar.com.kecat.repositories; import ar.com.kecat.models.Tarjeta; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; @RepositoryRestResource public interface TarjetaRepository extends CrudRepository<Tarjeta, Long> { @Override @RestResource(exported = false) <S extends Tarjeta> S save(S s); @Override default void delete(Tarjeta tarjeta){ tarjeta.setActivo(false); save(tarjeta); } Tarjeta findByNroTarjeta(String nroTarjeta); }
[ "tomas@metechi.com" ]
tomas@metechi.com
8a8c3efb0eae245586a907767dc53478b0cbf58c
ce76ba58fd1537eade23ddb3c49c15c123f86447
/CodeSessionbackUp/codeSession/src/com/demo/Que10Hobby.java
4f6cb18a040ce412c4ee2e9a83f067f6e1b48c0e
[]
no_license
nutan291214/collectionAsssignment
b0398935069986097a2cf11e6b7ed4af787f4632
6f0e860380bc2e5b18a864624b1c3beed265e0ed
refs/heads/master
2022-12-03T23:18:47.303307
2020-08-24T14:19:43
2020-08-24T14:19:43
289,935,789
0
0
null
null
null
null
UTF-8
Java
false
false
2,203
java
package com.demo; /*"Consider an array of Student Student (int sid, String sname, List<String> hobby) From this list create a Map<String,List<Student>> where key is hobby name and list of student objects having same hobby. Also find out most common hobby among students" */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner; class Student{ private int sid; private String sname; private List<String> hobby; public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public List<String> getHobby() { return hobby; } public void setHobby(List<String> hobby) { this.hobby = hobby; } @Override public String toString() { return "Student [sid=" + sid + ", sname=" + sname + ", hobby=" + hobby + "]"; } } public class Que10Hobby { public static void main(String[] args) { ArrayList<Student> sal=new ArrayList<>(); Scanner sc=new Scanner(System.in); char ch,ch1; do { Student s=new Student(); System.out.println("enter student id, student name"); s.setSid(sc.nextInt()); s.setSname(sc.next()); ArrayList<String> hobbyAl=new ArrayList<>(); do { System.out.println("Enter hobby"); hobbyAl.add(sc.next()); System.out.println("Do ypu want to add one more hobby y/n"); ch1=sc.next().charAt(0); }while(ch1=='y'||ch1=='Y'); s.setHobby(hobbyAl); System.out.println("Do ypu want to add one more student y/n"); ch=sc.next().charAt(0); sal.add(s); }while(ch=='y'||ch=='Y'); //System.out.println(sal); HashMap<String, List<String>> hm=new HashMap<>(); for(Student stud:sal) { String sname=stud.getSname(); List<String> hobby=stud.getHobby(); for(String hb:hobby) { if(hm.containsKey(hb)) { List<String> snm=hm.get(hb); snm.add(sname); } else { ArrayList<String> al=new ArrayList<>(); al.add(sname); hm.put(hb, al); } } } System.out.println(hm); } }
[ "noreply@github.com" ]
nutan291214.noreply@github.com
390d6c186cd88e5025c847a53afa9bb05e0b7846
23f75389c70cbc1936f079a1deeeb111c8e35eb0
/src/test/java/com/lian/create/factory/method/FactoryMethodTest.java
7c0ea8be919c3a341ce7b6a52c0a880ddc03a364
[]
no_license
lian08/design_pattern_demo
3866341a3066e1f860b1594fd20e656f9db78daf
c39079a79302dee64b4f0ab8bc63674681c21256
refs/heads/master
2021-01-19T18:44:32.288820
2017-09-13T06:30:17
2017-09-13T06:30:17
101,160,744
0
1
null
null
null
null
UTF-8
Java
false
false
463
java
package com.lian.create.factory.method; import com.lian.create.factory.simple.IHuman; /** */ public class FactoryMethodTest { public static void main(String[] args) { IHumanFactory humanFactory = new YellowHumanFactory(); // IHumanFactory humanFactory = new BlackHumanFactory(); // IHumanFactory humanFactory = new WhiteHumanFactory(); IHuman human = humanFactory.creactHuman(); human.laugh(); } }
[ "201294@nd.com" ]
201294@nd.com
1cf44e8961cb011d97b1d998e577c5ad95ea1e53
0b2c67f8523862aecfc4dc97a52d63e408ea2099
/src/com/javarush/test/level08/lesson11/bonus02/Solution.java
919f08dba1ef1793861fc67564e9f42f03b5b7d7
[]
no_license
CRCx86/JavaRushHomeWork
c952e7ddf8e3d0add0c787521fd57d8334dab137
ac83eed2bd49a5a1827fe053625c001ef8d58355
refs/heads/master
2021-01-21T15:26:05.907144
2017-02-08T06:14:37
2017-02-08T06:14:37
68,360,725
0
0
null
null
null
null
UTF-8
Java
false
false
1,583
java
package com.javarush.test.level08.lesson11.bonus02; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /* Нужно добавить в программу новую функциональность Задача: Программа определяет, какая семья (фамилию) живёт в доме с указанным номером. Новая задача: Программа должна работать не с номерами домов, а с городами: Пример ввода: Москва Ивановы Киев Петровы Лондон Абрамовичи Лондон Пример вывода: Абрамовичи */ public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //list of addresses Map<String, String> addresses = new HashMap<>(); while (true) { String family = reader.readLine(); if (family.isEmpty()) break; String city = reader.readLine(); if (city.isEmpty()) break; addresses.put(family, city); } //read home number String citysName = reader.readLine(); if (!citysName.isEmpty()) { String familySecondName = addresses.get(citysName); System.out.println(familySecondName); } } }
[ "crc32zinov@gmail.com" ]
crc32zinov@gmail.com
e77b45f75d679de82d6298b966670a049c25b742
812be6b9d1ba4036652df166fbf8662323f0bdc9
/java/Dddml.Wms.JavaCommon/src/generated/java/org/dddml/wms/domain/inventoryitementrymvo/DeleteInventoryItemEntryMvoDto.java
1ba348db7b290e332395ff84e30ccd329627ed9f
[]
no_license
lanmolsz/wms
8503e54a065670b48a15955b15cea4926f05b5d6
4b71afd80127a43890102167a3af979268e24fa2
refs/heads/master
2020-03-12T15:10:26.133106
2018-09-27T08:28:05
2018-09-27T08:28:05
130,684,482
0
0
null
2018-04-23T11:11:24
2018-04-23T11:11:24
null
UTF-8
Java
false
false
622
java
package org.dddml.wms.domain.inventoryitementrymvo; public class DeleteInventoryItemEntryMvoDto extends AbstractInventoryItemEntryMvoCommandDto { @Override public String getCommandType() { return COMMAND_TYPE_DELETE; } public InventoryItemEntryMvoCommand.DeleteInventoryItemEntryMvo toDeleteInventoryItemEntryMvo() { AbstractInventoryItemEntryMvoCommand.SimpleDeleteInventoryItemEntryMvo command = new AbstractInventoryItemEntryMvoCommand.SimpleDeleteInventoryItemEntryMvo(); ((AbstractInventoryItemEntryMvoCommandDto)this).copyTo(command); return command; } }
[ "yangjiefeng@gmail.com" ]
yangjiefeng@gmail.com
3af4394bbc26e7d00ea26cce19f265e93ef7e2d9
6707f9f2b2cfa6c8c436f64e2b4897f41aeab4bd
/Dacza/Trunk/Codigo/DACZA/app/src/main/java/com/duxstar/dacza/presentadores/interfaces/IServidorComunicaciones.java
e96ce0b27c61e8bc9aed292f0e8a6add094b31ab
[]
no_license
cadusousa/Productos
b36a2ace550b7c61ecae1b28d0f95b7ffc8f91a6
c70bdeff530d699aa9f1c08577c99a0ebaeb0de4
refs/heads/master
2023-03-07T17:44:45.009859
2021-02-26T20:07:23
2021-02-26T20:07:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
454
java
package com.duxstar.dacza.presentadores.interfaces; /** * Created by Adriana on 23/06/2016. */ import com.duxstar.dacza.presentadores.IVista; public interface IServidorComunicaciones extends IVista { void setMaxPasos(int valorMaximo); void setMaxDetallePasos(int valorMaximo); void setProgresoPasos(int valor); void setProgresoDetallePasos(int valor); void setTextoPasos(String texto); void setTextoProgreso(String texto); }
[ "escoraxel@gmail.com" ]
escoraxel@gmail.com
76ea6ba46a33907ee836cad4bbcd5a6bf5e96b80
fcec499132ca67bc2047a1bbcf7ffe21a46bf109
/TMessagesProj/src/main/java/com/google/android/exoplayer2/source/dash/offline/DashDownloadHelper.java
1b0f007d68677fe69ad427630b5c5b0f485dad67
[]
no_license
amirreza-rostamian/aan-client
29881c09ae81b2dc2902dc72b025c4847472b428
c2cc8dd1e1657d41b8f0a55d293ec4fbc936c5df
refs/heads/master
2020-08-31T02:52:56.440025
2019-10-30T15:36:15
2019-10-30T15:36:15
218,558,479
0
0
null
null
null
null
UTF-8
Java
false
false
4,419
java
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.source.dash.offline; import android.net.Uri; import android.support.annotation.Nullable; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.offline.DownloadHelper; import com.google.android.exoplayer2.offline.StreamKey; import com.google.android.exoplayer2.offline.TrackKey; import com.google.android.exoplayer2.source.TrackGroup; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.source.dash.manifest.AdaptationSet; import com.google.android.exoplayer2.source.dash.manifest.DashManifest; import com.google.android.exoplayer2.source.dash.manifest.DashManifestParser; import com.google.android.exoplayer2.source.dash.manifest.Representation; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.ParsingLoadable; import com.google.android.exoplayer2.util.Assertions; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * A {@link DownloadHelper} for DASH streams. */ public final class DashDownloadHelper extends DownloadHelper { private final Uri uri; private final DataSource.Factory manifestDataSourceFactory; private @MonotonicNonNull DashManifest manifest; public DashDownloadHelper(Uri uri, DataSource.Factory manifestDataSourceFactory) { this.uri = uri; this.manifestDataSourceFactory = manifestDataSourceFactory; } private static List<StreamKey> toStreamKeys(List<TrackKey> trackKeys) { List<StreamKey> streamKeys = new ArrayList<>(trackKeys.size()); for (int i = 0; i < trackKeys.size(); i++) { TrackKey trackKey = trackKeys.get(i); streamKeys.add(new StreamKey(trackKey.periodIndex, trackKey.groupIndex, trackKey.trackIndex)); } return streamKeys; } @Override protected void prepareInternal() throws IOException { DataSource dataSource = manifestDataSourceFactory.createDataSource(); manifest = ParsingLoadable.load(dataSource, new DashManifestParser(), uri, C.DATA_TYPE_MANIFEST); } /** * Returns the DASH manifest. Must not be called until after preparation completes. */ public DashManifest getManifest() { Assertions.checkNotNull(manifest); return manifest; } @Override public int getPeriodCount() { Assertions.checkNotNull(manifest); return manifest.getPeriodCount(); } @Override public TrackGroupArray getTrackGroups(int periodIndex) { Assertions.checkNotNull(manifest); List<AdaptationSet> adaptationSets = manifest.getPeriod(periodIndex).adaptationSets; TrackGroup[] trackGroups = new TrackGroup[adaptationSets.size()]; for (int i = 0; i < trackGroups.length; i++) { List<Representation> representations = adaptationSets.get(i).representations; Format[] formats = new Format[representations.size()]; int representationsCount = representations.size(); for (int j = 0; j < representationsCount; j++) { formats[j] = representations.get(j).format; } trackGroups[i] = new TrackGroup(formats); } return new TrackGroupArray(trackGroups); } @Override public DashDownloadAction getDownloadAction(@Nullable byte[] data, List<TrackKey> trackKeys) { return DashDownloadAction.createDownloadAction(uri, data, toStreamKeys(trackKeys)); } @Override public DashDownloadAction getRemoveAction(@Nullable byte[] data) { return DashDownloadAction.createRemoveAction(uri, data); } }
[ "rostamianamirreza@yahoo.com" ]
rostamianamirreza@yahoo.com
77b0d42538e73d5867e6307b5231998f6f194ff9
97f270610d6a6d298dc99f0c3b7c679bc979b773
/ch01/src/main/java/com/springbook/ioc/polymorphism/LgTV.java
9f38bc707f89e32dbc5d2065daa73f611077293d
[]
no_license
unisung/springQuick01
878f7b4ec3439a53695f69cb2c618309d78646ef
2e246df35fb315768bf8601afd755a282348d6eb
refs/heads/master
2022-12-02T19:48:36.416711
2020-08-21T07:33:39
2020-08-21T07:33:39
287,486,105
0
0
null
null
null
null
UTF-8
Java
false
false
1,179
java
package com.springbook.ioc.polymorphism; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component("Tv") public class LgTV implements Tv{ //@Autowired//자동 주입(componentScan에 의해 등록된 component중에 speaker객체 주입) //@Qualifier("sony") @Resource(name = "sony")//java제공 private Speaker speaker; private int price; /* * //생성자 public LgTV(Speaker speaker) { System.out.println("===>LgTv 객체 생성"); * this.speaker = speaker; } * * //생성자 public LgTV(Speaker speaker, int price) { this.speaker = speaker; * this.price = price; } */ @Override public void powerOn() { System.out.println("LgTV---전원켠다"); } @Override public void powerOff() { System.out.println("LgTV---전원끈다"); } @Override public void volumeUp() { speaker.volumeUp(); } @Override public void volumeDown() { speaker.volumeDown(); } @Override public int getPrice() { return price; } }
[ "vctor@naver.com" ]
vctor@naver.com
67925a162219c352a107d7e2f7d036a38504dd42
287b7aaa84c4a311deabf1e5ec3ac9a361bd16a4
/src/Ejercicio13.java
8f0770b6849f61ac41132bb27c4a8915fe85bc6e
[]
no_license
Tesitolol24/Ejercicios_Java
2f67b1688222eba4efc3c34f255243a1c0d81302
5c15ec55270cd18d7bef730990db805fc0dfd85f
refs/heads/main
2023-03-05T21:37:28.596401
2021-02-20T16:41:20
2021-02-20T16:41:20
340,702,084
0
0
null
null
null
null
UTF-8
Java
false
false
678
java
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Ejercicio13 { public static void main(String[] args) throws Exception { //Ejercicio 13 Date fecha = new Date(); DateFormat hourFormat = new SimpleDateFormat("HH:mm:ss"); System.out.println("Hora: "+hourFormat.format(fecha)); DateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy"); System.out.println("Fecha: "+ dateFormat.format(fecha)); DateFormat hourdateFormat = new SimpleDateFormat("HH:mm:ss dd:MM:yyyy"); System.out.println("Hora y fecha: "+ hourdateFormat.format(fecha)); } }
[ "tesitolol24@gmail.com" ]
tesitolol24@gmail.com
fddf8e422ca2466386a1f405c70b1958ea74efa5
28576e9c7389dab8e6c757a9b50df4ca12833a69
/app/src/main/java/ku/reh/gdu/graduationrehearsal/Model/PracticeModel.java
e149609278ff6bb643fbf0a0fb4e76bd03ea5a44
[]
no_license
subbass5/GraduationRehearsal
2825d4c022d2e440157c49595ff55eea3d14b95a
409edef8aef8fc5d4a83672b2e69f2024372dfc0
refs/heads/master
2020-03-27T06:37:47.504523
2018-09-24T08:07:26
2018-09-24T08:07:26
146,121,451
0
0
null
null
null
null
UTF-8
Java
false
false
2,030
java
package ku.reh.gdu.graduationrehearsal.Model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class PracticeModel { @SerializedName("id") @Expose private String id; @SerializedName("name") @Expose private String name; @SerializedName("idcard") @Expose private String idcard; @SerializedName("score1") @Expose private String score1; @SerializedName("score2") @Expose private String score2; @SerializedName("score3") @Expose private String score3; @SerializedName("score4") @Expose private String score4; @SerializedName("score5") @Expose private String score5; @SerializedName("score6") @Expose private String score6; 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 getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } public String getScore1() { return score1; } public void setScore1(String score1) { this.score1 = score1; } public String getScore2() { return score2; } public void setScore2(String score2) { this.score2 = score2; } public String getScore3() { return score3; } public void setScore3(String score3) { this.score3 = score3; } public String getScore4() { return score4; } public void setScore4(String score4) { this.score4 = score4; } public String getScore5() { return score5; } public void setScore5(String score5) { this.score5 = score5; } public String getScore6() { return score6; } public void setScore6(String score6) { this.score6 = score6; } }
[ "dumtk1@gmail.com" ]
dumtk1@gmail.com
ecf9065c66be35c12fe16e5f6bc0899db070d241
0263a5c1bc395ca5d65b02a349c98bd8f8bcac98
/src/dymanicProgramming/LCS.java
1e731d95c54886be6827b28cad6e3fbdce870da5
[]
no_license
dheeraj9198/Algorithms-and-Data-Structures-in-Java
01caaff40c080e0693b4e9b15f55eac8ceed1c0b
18d075adfc072f031c38ea283a2604c59098fb6f
refs/heads/master
2020-12-25T16:49:04.451677
2020-02-07T20:04:17
2020-02-07T20:04:17
26,867,050
28
27
null
null
null
null
UTF-8
Java
false
false
1,537
java
package dymanicProgramming; import java.util.Stack; /** * Created by dheeraj on 7/9/2016. */ public class LCS { private static Integer sol[][]; private static int findLis(String one, String two, int start, int end) { if(start < 0 || start > one.length()-1 || end > two.length()-1 || end < 0){ return 0; } if (sol[start][end] != null) { return sol[start][end]; } int a = findLis(one, two, start - 1, end - 1); int b = findLis(one, two, start - 1, end); int c = findLis(one, two, start, end - 1); int ans = one.charAt(start) == two.charAt(end) ? a + 1 : Math.max(b, c); sol[start][end] = ans; return ans; } public static void main(String[] strings) { String one = "abcd"; String two = "abcxd"; sol = new Integer[one.length()][two.length()]; int ans = findLis(one, two, one.length() - 1, two.length() - 1); System.out.println(ans); Stack<Character> characters = new Stack<Character>(); int x = one.length()-1; int y = two.length()-1; while(x >= 0 && y >=0){ if(x-1 >= 0 && sol[x][y] == sol[x-1][y]){ x--; }else if(y-1 > 0 && sol[x][y] == sol[x][y-1]){ y--; }else{ characters.push(one.charAt(x)); x--;y--; } } while(!characters.empty()){ System.out.print(characters.pop()+" "); } } }
[ "dhirajsiitk9@gmail.com" ]
dhirajsiitk9@gmail.com
acbb9218d32b31cb58fced4d02edb6edcea5188e
d9caf7328f8656e674b79de3fc91dab8ad572ba3
/src/main/java/DeconvolutionProgram.java
e137d9a8f5b234a9db1f3a00a02209d022892ebc
[]
no_license
ASGusev/nir2017
533f97c3ff3d91b96044b3954c4d32a8c07dda23
d745310f120deb07e4dcbb56a56b110d897c2112
refs/heads/master
2021-01-19T14:24:10.732148
2017-06-21T11:14:54
2017-06-21T11:14:54
88,157,651
0
0
null
null
null
null
UTF-8
Java
false
false
11,608
java
import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; /** * A enumeration of supported deconvolution programs. */ public enum DeconvolutionProgram { MSDeconv { private final String SCAN_BEGINNING = "BEGIN IONS"; private final String SCAN_END = "END IONS"; private final String ID_PREF = "ID="; private final String PRECURSOR_MASS_PREF = "PRECURSOR_MASS="; private final String PRECURSOR_CHARGE_PREF = "PRECURSOR_CHARGE="; @Override public Iterator<ExperimentalScan> getOutputIterator(final Path filePath) throws IOException { return new Iterator<ExperimentalScan>() { private ExperimentalScan nextScan; private BufferedReader resultsReader; { resultsReader = Files.newBufferedReader(filePath); nextScan = readScan(); } @Override public boolean hasNext() { return nextScan != null; } @Override public ExperimentalScan next() { if (nextScan == null) { return null; } ExperimentalScan curScan = nextScan; nextScan = readScan(); return curScan; } private ExperimentalScan readScan() { String line = null; ExperimentalScan scan = null; int id = 0; int prsmId = 0; int charge = 0; double precursorMass = 0; double[] peaks; List<Double> peaksList = new ArrayList<>(); try { while (scan == null && (line = resultsReader.readLine()) != null) { if (line.startsWith(ID_PREF)) { id = Integer.valueOf(line.substring(ID_PREF.length())); continue; } if (line.startsWith(PRECURSOR_MASS_PREF)) { precursorMass = Double.valueOf( line.substring(PRECURSOR_MASS_PREF.length())); continue; } if (line.startsWith(PRECURSOR_CHARGE_PREF)) { charge = Integer.valueOf( line.substring(PRECURSOR_CHARGE_PREF.length())); continue; } if (!line.isEmpty() && Character.isDigit(line.charAt(0))) { String peak = line.substring(0, line.indexOf('\t')); peaksList.add(Double.valueOf(peak)); continue; } if (line.equals(SCAN_END)) { peaks = new double[peaksList.size()]; for (int i = 0; i < peaks.length; i++) { peaks[i] = peaksList.get(i); } scan = new ExperimentalScan(id, prsmId, charge, precursorMass, peaks); } } } catch (IOException e) { try { resultsReader.close(); } catch (IOException e1) { e.addSuppressed(e1); } throw new ScanReadError(e); } if (line == null) { try { resultsReader.close(); } catch (IOException e) { throw new ScanReadError(e); } } return scan; } }; } }, ThermoXtract { private final String SCAN_BEGINNING = "BEGIN IONS"; private final String SCAN_END = "END IONS"; private final String TITLE_PREF = "TITLE="; private final String PEPMASS_PREF = "PEPMASS="; @Override public Iterator<ExperimentalScan> getOutputIterator( final Path filePath) throws IOException { return new Iterator<ExperimentalScan>() { private ExperimentalScan nextScan; private BufferedReader resultsReader; { resultsReader = Files.newBufferedReader(filePath); nextScan = readScan(); } @Override public boolean hasNext() { return nextScan != null; } @Override public ExperimentalScan next() { if (nextScan == null) { return null; } ExperimentalScan curScan = nextScan; nextScan = readScan(); return curScan; } private ExperimentalScan readScan() { String line = null; ExperimentalScan scan = null; int id = 0; int prsmId = 0; int charge = 0; double precursorMass = 0; double[] peaks; List<Double> peaksList = new ArrayList<>(); try { while (scan == null && (line = resultsReader.readLine()) != null) { if (line.startsWith(TITLE_PREF)) { String[] tokens = line.split(" "); String idToken = tokens[tokens.length - 1]; id = Integer.valueOf(idToken.substring(5, idToken.length() - 1)); } if (line.startsWith(PEPMASS_PREF)) { line = line.substring(PEPMASS_PREF.length()); if (line.contains(" ")) { line = line.substring(0, line.indexOf(" ")); } precursorMass = Double.valueOf(line); continue; } if (!line.isEmpty() && Character.isDigit(line.charAt(0))) { String peak = line.substring(0, line.indexOf(' ')); peaksList.add(Double.valueOf(peak)); continue; } if (line.equals(SCAN_END)) { peaks = new double[peaksList.size()]; for (int i = 0; i < peaks.length; i++) { peaks[i] = peaksList.get(i); } scan = new ExperimentalScan(id, prsmId, charge, precursorMass, peaks); } } } catch (IOException e) { try { resultsReader.close(); } catch (IOException e1) { e.addSuppressed(e1); } throw new ScanReadError(e); } if (line == null) { try { resultsReader.close(); } catch (IOException e) { throw new ScanReadError(e); } } return scan; } }; } }, Hardklor { @Override public Iterator<ExperimentalScan> getOutputIterator(Path filePath) throws IOException { return new Iterator<ExperimentalScan>() { private String nextLine; private BufferedReader scansReader; { scansReader = Files.newBufferedReader(filePath); nextLine = scansReader.readLine(); } @Override public boolean hasNext() { return nextLine != null; } @Override public ExperimentalScan next() { String[] tokens = nextLine.split("\t"); int scanNumber = Integer.valueOf(tokens[1]); double mass = Double.valueOf(tokens[4]); int charge = Integer.valueOf(tokens[5]); List<Double> peaksList = new ArrayList<>(); try { nextLine = scansReader.readLine(); while (nextLine != null && nextLine.charAt(0) == 'P') { tokens = nextLine.split("\t"); peaksList.add(Double.valueOf(tokens[1])); nextLine = scansReader.readLine(); } } catch (IOException e) { throw new ScanReadError(e); } double[] peaks = new double[peaksList.size()]; for (int i = 0; i < peaks.length; i++) { peaks[i] = peaksList.get(i); } return new ExperimentalScan(scanNumber, 0, charge, mass, peaks); } }; } }; /** * Makes an iterator over the output of the program. * @param filePath the output file to read. * @return an Iterator<ExperimentalScan> containing all the scans * described in the file. * @throws IOException if an error during reading the file occurs. */ public abstract Iterator<ExperimentalScan> getOutputIterator(Path filePath) throws IOException; /** * Reads a file with output of the program and collects all the scans * in a map from the number of the scan to tis ExperimentalScan * representation. */ public Map<Integer, ExperimentalScan> getOutputMap(Path path) throws IOException { Map<Integer, ExperimentalScan> outputMap = new HashMap<>(); Iterator<ExperimentalScan> outputIterator = getOutputIterator(path); outputIterator.forEachRemaining(scan -> outputMap.put(scan.getId(), scan) ); return outputMap; } /** * A error thrown in case of an error reading a scan. */ public static class ScanReadError extends Error { private ScanReadError() { super(); } private ScanReadError(Throwable cause) { super(cause); } } }
[ "andy.gusev@list.ru" ]
andy.gusev@list.ru
aae5576d524e1f017e1801f85255e2e09981ff36
8c8738568beb72df69b5da435acbde09c3399ddb
/comlansosdkplaysdk/build/generated/source/buildConfig/androidTest/debug/com/example/com/lansosdkplay/sdk/test/BuildConfig.java
4b0bf11a69128f4dc9c4e323274e3ce0bfe39157
[]
no_license
stm32f103vc/lansosdkPlayDemo-AndroidStudio
a434d53667410208aad8297fdb7467453277fc83
4f7ef2bf3677caf26ca7dd7db6e39aa451b6200b
refs/heads/master
2021-01-17T11:53:54.897030
2016-08-17T09:04:21
2016-08-17T09:04:21
65,892,712
0
0
null
null
null
null
UTF-8
Java
false
false
479
java
/** * Automatically generated file. DO NOT MODIFY */ package com.example.com.lansosdkplay.sdk.test; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "com.example.com.lansosdkplay.sdk.test"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = -1; public static final String VERSION_NAME = ""; }
[ "1025543531@qq.com" ]
1025543531@qq.com
2780179cc4c256b94e5f51d5463bd576b60d2b82
9a3b7b91ce358d4861eb06b680bea48994d768f3
/src/main/java/com/weichou/service/impl/ProductServiceImpl.java
931fe16cf73e3b5887bb451ebdb210175d43c00a
[]
no_license
gph2015/weichou
ffcbfa8400348448813bebc426bede3d20db1cca
0e479096eedf508bc422113c19afbea6708d1df0
refs/heads/master
2021-01-10T10:52:08.395981
2016-04-09T02:35:35
2016-04-09T02:35:35
55,754,981
0
0
null
null
null
null
UTF-8
Java
false
false
558
java
package com.weichou.service.impl; import com.weichou.dao.ProductDao; import com.weichou.entity.Product; import com.weichou.service.ProductService; import com.weichou.util.utils.ServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ProductServiceImpl implements ProductService { @Autowired ProductDao dao; @Override public Product getById(Integer productId) throws ServiceException { return dao.queryProductDetail(productId); } }
[ "511878572@qq.com" ]
511878572@qq.com
5931b6080423420add65e21ad40f75a3b60c21c6
d9eca71c763fe6383cc8d8b388a7ef4425940a95
/src/main/java/com/invoicing/manage/request/UserRequestEntity.java
450892a0dc1fbac506126a53dc6c3ca631fcd7ce
[]
no_license
Zxy675272387/SMM
18d5b2ba6ef03db2d29a2c140d13c49a6d2f1b71
e787010e8cc51ef48d76466df538360dca052b01
refs/heads/master
2020-03-12T16:03:55.837560
2018-06-04T13:50:33
2018-06-04T13:50:33
130,706,481
0
0
null
null
null
null
UTF-8
Java
false
false
1,182
java
package com.invoicing.manage.request; import com.invoicing.manage.comment.entity.BaseRequestEntity; /** * 类名: UserRequestEntity * 类描述: TODO. 用户请求实体 */ @SuppressWarnings("serial") public class UserRequestEntity extends BaseRequestEntity{ /** * 用户姓名 */ private String userName; /** * 登录名 */ private String loginName; /** * 登录密码 */ private String password; /** * 机构名称 */ private String orgName; /** * 电话号码 */ private String phone; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getOrgName() { return orgName; } public void setOrgName(String orgName) { this.orgName = orgName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
[ "38657737+Zxy675272387@users.noreply.github.com" ]
38657737+Zxy675272387@users.noreply.github.com
597e202439ed9d0adf160baf5d16413d89b312ef
547f154dd20ffb1c32a90d2834d904860d34127d
/SKProject/src/cn/sise/dao/EmpDaoImpl.java
b1bb82dc585814a13f5003ba08a46067f57ce0fc
[]
no_license
YSYUP/Java
59a3b43f9a7a21c5669725d99725c1788ff5fd88
5e3cf95b8786c4e311d12f10d16b4dfce92030a0
refs/heads/master
2023-01-25T00:11:24.656158
2020-11-18T01:21:23
2020-11-18T01:21:23
297,196,530
0
1
null
null
null
null
UTF-8
Java
false
false
11,337
java
package cn.sise.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import cn.sise.pojo.Attend; import cn.sise.pojo.Employee; import cn.sise.pojo.Goods; import cn.sise.pojo.Vip; import cn.sise.util.JDBCUtil; public class EmpDaoImpl implements EmpDao { // 管理员登录 public Employee findByNum(String num) { String sql = "select * from employee where number = ?"; ResultSet rs = JDBCUtil.executeQuery(sql, num); Employee emp = null; try { if (rs.next()) { emp = new Employee(rs.getString("number"), rs.getString("username"), rs.getString("password"), rs.getString("sex"), rs.getString("phone"), rs.getInt("role"), rs.getInt("remark")); } } catch (SQLException e) { e.printStackTrace(); } return emp; } public Employee login(String num, String pwd) { Employee emp = findByNum(num); if (emp != null) { if (pwd.equals(emp.getPassword())) { return emp; } return null; } return null; } // 查询收银员 @Override public ArrayList<Employee> cashierList() { ArrayList<Employee> list = new ArrayList<Employee>(); String sql = "select * from employee where role = 2"; ResultSet rs = JDBCUtil.executeQuery(sql); Employee emp = null; try { while (rs.next()) { emp = new Employee(rs.getString("number"), rs.getString("username"), rs.getString("password"), rs.getString("sex"), rs.getString("phone"), rs.getInt("role"), rs.getInt("remark")); list.add(emp); } } catch (SQLException e) { e.printStackTrace(); } return list; } // 添加收银员 @Override public int addCashier(Employee emp) { String sql = "insert into employee(number, username, password, sex, phone, role, remark) values (?,?,?,?,?,?,?)"; int res = JDBCUtil.executeUpdate(sql, emp.getNumber(), emp.getUsername(), emp.getPassword(), emp.getSex(), emp.getPhone(), 2, 1); return res; } // 员工修改模块 @Override public int editName(String num, String name) { String sql = "update employee set username = ? where number = ?"; int res = JDBCUtil.executeUpdate(sql, name, num); return res; } @Override public int editSex(String num, String sex) { String sql = "update employee set sex = ? where number = ?"; int res = JDBCUtil.executeUpdate(sql, sex, num); return res; } @Override public int editPhone(String num, String phone) { String sql = "update employee set phone = ? where number = ?"; int res = JDBCUtil.executeUpdate(sql, phone, num); return res; } @Override public int takeOffice(String num, int tmp) { String sql = "update employee set remark = ? where number = ?"; int res = JDBCUtil.executeUpdate(sql, tmp, num); return res; } @Override public int editPwd(String num, String pwd) { String sql = "update employee set password = ? where number = ?"; int res = JDBCUtil.executeUpdate(sql, pwd, num); return res; } // 采购员模块 @Override public ArrayList<Employee> buyerList() { ArrayList<Employee> list = new ArrayList<Employee>(); String sql = "select * from employee where role = 3"; ResultSet rs = JDBCUtil.executeQuery(sql); Employee emp = null; try { while (rs.next()) { emp = new Employee(rs.getString("number"), rs.getString("username"), rs.getString("password"), rs.getString("sex"), rs.getString("phone"), rs.getInt("role"), rs.getInt("remark")); list.add(emp); } } catch (SQLException e) { e.printStackTrace(); } return list; } @Override public int addBuyer(Employee emp) { String sql = "insert into employee(number, username, password, sex, phone, role, remark) values (?,?,?,?,?,?,?)"; int res = JDBCUtil.executeUpdate(sql, emp.getNumber(), emp.getUsername(), emp.getPassword(), emp.getSex(), emp.getPhone(), 3, 1); return res; } // Vip 模块 @Override public ArrayList<Vip> vipList() { ArrayList<Vip> list = new ArrayList<Vip>(); String sql = "select * from vip"; ResultSet rs = JDBCUtil.executeQuery(sql); Vip vip = null; try { while (rs.next()) { vip = new Vip(rs.getString("v_number"), rs.getString("v_name"), rs.getInt("v_score"), rs.getString("v_phone"), rs.getString("v_date")); list.add(vip); } } catch (SQLException e) { e.printStackTrace(); } return list; } @Override public int addVip(Vip vip) { String sql = "insert into vip(v_number, v_name, v_score, v_phone, v_date) values (?,?,?,?,?)"; String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); int res = JDBCUtil.executeUpdate(sql, vip.getNumber(), vip.getName(), 0, vip.getPhone(), date); return res; } @Override public int deleteVip(String pho) { String sql = "delete from vip where v_phone=?"; int res = JDBCUtil.executeUpdate(sql, pho); return res; } @Override public Vip findByPhone(String pho) { String sql = "select * from vip where v_phone = ?"; ResultSet rs = JDBCUtil.executeQuery(sql, pho); Vip vip = null; try { if (rs.next()) { vip = new Vip(rs.getString("v_number"), rs.getString("v_name"), rs.getInt("v_score"), rs.getString("v_phone"), rs.getString("v_date")); } } catch (SQLException e) { e.printStackTrace(); } return vip; } @Override public int v_editName(String pho, String name) { String sql = "update vip set v_name = ? where v_phone = ?"; int res = JDBCUtil.executeUpdate(sql, name, pho); return res; } @Override public int v_editPhone(String pho, String t_pho) { String sql = "update vip set v_phone = ? where v_phone = ?"; int res = JDBCUtil.executeUpdate(sql, t_pho, pho); return res; } // 查询所有人员信息 @Override public ArrayList<Employee> empList() { ArrayList<Employee> list = new ArrayList<Employee>(); String sql = "select * from employee"; ResultSet rs = JDBCUtil.executeQuery(sql); Employee emp = null; try { while (rs.next()) { emp = new Employee(rs.getString("number"), rs.getString("username"), rs.getString("password"), rs.getString("sex"), rs.getString("phone"), rs.getInt("role"), rs.getInt("remark")); list.add(emp); } } catch (SQLException e) { e.printStackTrace(); } return list; } @Override public int checkPoints(String pho) { String sql = "select v_score from vip where v_phone = ?"; ResultSet rs = JDBCUtil.executeQuery(sql, pho); int tmp = 0; try { if (rs.next()) { tmp = rs.getInt("v_score"); } } catch (SQLException e) { e.printStackTrace(); } return tmp; } @Override public ArrayList<Goods> goodsList(int tmp) { ArrayList<Goods> list = new ArrayList<Goods>(); String sql1 = "select * from goods where inventory < 100"; String sql2 = "select * from goods"; Goods g = null; ResultSet rs = null; if (tmp == 0) { rs = JDBCUtil.executeQuery(sql2); } if (tmp == 1) { rs = JDBCUtil.executeQuery(sql1); } try { while (rs.next()) { g = new Goods(rs.getInt("c_number"), rs.getString("c_name"), rs.getDouble("c_price"), rs.getDouble("vip_price"), rs.getInt("inventory")); list.add(g); } } catch (SQLException e) { e.printStackTrace(); } return list; } @Override public int purchase(String c_name, int inventory) { String sql = "update goods set inventory = (? + inventory) where c_name=?"; int res = JDBCUtil.executeUpdate(sql, inventory, c_name); return res; } @Override public int newProduct(Goods g) { String sql = "insert into goods(c_name, c_price, vip_price, inventory) values (?,?,?,?)"; int res = JDBCUtil.executeUpdate(sql, g.getC_name(), g.getC_price(), g.getVip_price(), g.getInventory()); return res; } // 添加账单结算信息 @Override public int checkBill(String e_id, String str, String pho, int g_id, int amount) { String tmp = null; int res = 0; String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); // 有会员卡 if (str.equals("Y")) { String sql1 = "select v_number from vip where v_phone = ?"; String sql2 = "insert into sell_info(s_c_number, s_quantity, s_time, s_e_number, s_vip_number) values(?,?,?,?,?)"; ResultSet rs = JDBCUtil.executeQuery(sql1, pho); try { if (rs.next()) { tmp = rs.getString("v_number"); } res = JDBCUtil.executeUpdate(sql2, g_id, amount, date, e_id, tmp); } catch (SQLException e) { e.printStackTrace(); } } if (str.equals("N")) { String sql3 = "insert into sell_info(s_c_number, s_quantity, s_time, s_e_number) values(?,?,?,?)"; res = JDBCUtil.executeUpdate(sql3, g_id, amount, date, e_id); } return res; } @Override public ArrayList<Attend> todayAttend() { ArrayList<Attend> list = new ArrayList<Attend>(); String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String sql = "select * from check_info where work_date = ?"; ResultSet rs = JDBCUtil.executeQuery(sql, date); Attend a = null; try { while (rs.next()) { a = new Attend(rs.getString("work_date"), rs.getString("employee_no"), rs.getString("clock_in_time"), rs.getString("clock_off_time"), rs.getString("diff_in_status"), rs.getString("diff_off_time")); list.add(a); } } catch (SQLException e) { e.printStackTrace(); } return list; } @Override public ArrayList<Attend> dateAttend(String date) { ArrayList<Attend> list = new ArrayList<Attend>(); String sql = "select * from check_info where work_date = ?"; ResultSet rs = JDBCUtil.executeQuery(sql, date); Attend a = null; try { while (rs.next()) { a = new Attend(rs.getString("work_date"), rs.getString("employee_no"), rs.getString("clock_in_time"), rs.getString("clock_off_time"), rs.getString("diff_in_status"), rs.getString("diff_off_time")); list.add(a); } } catch (SQLException e) { e.printStackTrace(); } return list; } @Override public String attendCount(String date2) { // 出勤异常的员工工号 String sql1 = "select employee_no from check_info where not diff_in_status='正常' and not diff_off_time = '正常' and work_date = ?"; // 旷工人数 String sql2 = "select count(*) from check_info where diff_in_status='旷工' and work_date = ?"; // 迟到人数 String sql3 = "select count(*) from check_info where diff_in_status='迟到' and work_date = ?"; // 早退人数 String sql4 = "select count(*) from check_info where diff_off_time='早退' and work_date = ?"; String tmp = ""; ResultSet rs1 = JDBCUtil.executeQuery(sql1, date2); ResultSet rs2 = JDBCUtil.executeQuery(sql2, date2); ResultSet rs3 = JDBCUtil.executeQuery(sql3, date2); ResultSet rs4 = JDBCUtil.executeQuery(sql4, date2); try { if (rs2.next()) { tmp += rs2.getInt("count(*)") + "/"; } if (rs3.next()) { tmp += rs3.getInt("count(*)") + "/"; } if (rs4.next()) { tmp += rs4.getInt("count(*)") + "/"; } while (rs1.next()) { tmp += rs1.getString("employee_no") + ","; } } catch (SQLException e) { e.printStackTrace(); } return tmp; } }
[ "noreply@github.com" ]
YSYUP.noreply@github.com
b735d882bdf9d3fecae8fb5c93490dcd8c01e1ac
84bfca7d33355eef24fe3ef476b5252ffbc29e05
/ballo-net/src/main/java/com/logiforge/ballo/net/HttpAdaptor.java
427687e735303ef1e93a89eaf994599855038ea8
[]
no_license
iorlanov-lf/ballo-as
416c9aef0df63e3f21e6e47acba20b7c5bdbcf9b
322ccfb9bed96d30ac389a07f0e609727b635750
refs/heads/master
2021-09-19T11:46:46.811484
2018-07-27T16:50:30
2018-07-27T16:50:30
100,595,977
0
0
null
null
null
null
UTF-8
Java
false
false
159
java
package com.logiforge.ballo.net; import java.io.IOException; public interface HttpAdaptor { Response execute(PostRequest request) throws IOException; }
[ "igor.orlanov@logiforge.com" ]
igor.orlanov@logiforge.com
0d2102ca0334b5dafc096e5c3519d2de6f78a320
c6ea6193a3cdf2d9237cd4ed1de0db3ce525fa07
/app/src/test/java/com/administrator/myapp/ExampleUnitTest.java
a58b2bb2c4ee1f047ee850e9010c304490f0cde9
[]
no_license
Zizi-And-Wazi/Maotai
9060131f7a1d2869f18a7c60b9cd7826d0837eb5
897c0ddeeb72e4d897a4db5ba9bacaec515eb7b5
refs/heads/master
2022-02-13T20:37:37.617543
2019-08-21T20:32:23
2019-08-21T20:32:23
111,219,933
2
0
null
null
null
null
UTF-8
Java
false
false
401
java
package com.administrator.myapp; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "yaoyanandejia@sina.com" ]
yaoyanandejia@sina.com
94243141faa3afc5eeff570a06750b5b1de3b020
0aa3006d31c768279846f62a785c5a93d3041994
/WineSampleCellar.java
117705687e66720ff9c78f7bc0cc5b275afa3a59
[]
no_license
Emi1699/wineBrowser
dceda126bee2d30a70c6897ae1a055d014d7f52b
2d8f13dce5e93c47940d2b537ac09b40c66af55a
refs/heads/master
2020-07-11T13:37:43.417042
2019-08-26T20:28:07
2019-08-26T20:28:07
204,555,671
0
0
null
null
null
null
UTF-8
Java
false
false
12,495
java
package assignment2019; import java.util.ArrayList; import java.util.List; import assignment2019.codeprovided.AbstractWineSampleCellar; import assignment2019.codeprovided.Query; import assignment2019.codeprovided.QueryCondition; import assignment2019.codeprovided.WineProperty; import assignment2019.codeprovided.WineSample; import assignment2019.codeprovided.WineType; /** * WineSampleCellar.java * * Class that provides ways of creating Query objects from file + methods for * the 10 question. * * @version 1.0 08/05/2019 * * @author Buliga Fanel Emanuel (febuliga1@sheffield.ac.uk) */ public class WineSampleCellar extends AbstractWineSampleCellar { public WineSampleCellar(String redWineFilename, String whiteWineFilename, String queryFilename) { super(redWineFilename, whiteWineFilename, queryFilename); // TODO Auto-generated constructor stub } @Override // this methods basically constructs each individual query from the list of // words we have built from the text file. // we're assuming that each word is separated by a space. // the only thing that is being checked is whether // the operator and value are separated by a space or not public List<Query> readQueries(List<String> queryList) { // the list of complete Queries (----> return value) ArrayList<Query> queries = new ArrayList<>(); // the 3 objects needed to create a Query ArrayList<QueryCondition> conditions = new ArrayList<>(); ArrayList<WineSample> wineList = new ArrayList<>(); WineType wineType = null; // the 3 variables used to build a QueryCondition WineProperty property = null; String operator = null; double value = 0; for (int i = 0; i < queryList.size(); i++) { if (queryList.get(i).equalsIgnoreCase("select")) { // this is where we set the WineType, and the WineList which our query is going // to use if (queryList.get(i + 1).equalsIgnoreCase("red") || queryList.get(i + 1).equalsIgnoreCase("white")) { if (queryList.get(i + 3).equalsIgnoreCase("red") || queryList.get(i + 3).equalsIgnoreCase("white")) { wineType = WineType.ALL; wineList = (ArrayList<WineSample>) getWineSampleList(wineType); i += 5; } else { if (queryList.get(i + 1).equalsIgnoreCase("red")) { wineType = WineType.RED; wineList = (ArrayList<WineSample>) getWineSampleList(wineType); i += 3; } else { wineType = WineType.WHITE; wineList = (ArrayList<WineSample>) getWineSampleList(wineType); i += 3; } } } // this variable is true while there still are properties in the current query boolean stillInTheSameQuery = true; // loops until it finds the word 'select' again while (stillInTheSameQuery) { // depending on whether the operator and value are separated by a space // this variable helps us know where to look for the next // word in the current query boolean addOneMore = true; // constructing a QueryCondition for current Query's list of conditions property = WineProperty.fromFileIdentifier(queryList.get(i)); operator = queryList.get(i + 1); // Here we check if the operator and the value are separated by a space; // if they are not separated, we have to be careful when extracting them. if (operator.length() > 2) { if (Character.isDigit(operator.charAt(1))) { value = Double.parseDouble(operator.substring(1)); operator = Character.toString(operator.charAt(0)); } else { value = Double.parseDouble((operator.substring(2))); operator = operator.substring(0, 2); } addOneMore = false; } else { if (operator.length() == 2) { if (Character.isDigit(operator.charAt(1))) { value = Double.parseDouble(operator.substring(1)); operator = Character.toString(operator.charAt(0)); addOneMore = false; } else { value = Double.parseDouble(queryList.get(i + 2)); } } else { value = Double.parseDouble(queryList.get(i + 2)); } } // build a new QueryCondition with the previously built objects QueryCondition condition = new QueryCondition(property, operator, value); conditions.add(condition); // check if there are more property-operator-value triplets, // or if we've hit the end of the String list if (addOneMore) { if ((i + 3) >= queryList.size() || queryList.get(i + 3).equalsIgnoreCase("select")) { stillInTheSameQuery = false; } else { i += 4; } } else { if ((i + 2) >= queryList.size() || queryList.get(i + 2).equals("select")) { stillInTheSameQuery = false; } else { i += 3; } } } // create a new Query with the values we just calculated and add it to the list Query q = new Query(wineList, conditions, wineType); queries.add(q); // At first it might seem that the program would run just fine without this line. // One might even be tempted to ask 'Hey, what is this line of code doing here?' // The reason is straightforward and I'll try to explain it as simple as possible: // the program doesn't work without this line and nobody knows why ._. conditions = new ArrayList<>(); } } return queries; } @Override // create a new wine list that contains both red and white samples public void updateCellar() { ArrayList<WineSample> allWineSamples = new ArrayList<>(); allWineSamples.addAll(getWineSampleList(WineType.RED)); allWineSamples.addAll(getWineSampleList(WineType.WHITE)); wineSampleRacks.put(WineType.ALL, allWineSamples); } @Override public void displayQueryResults(Query query) { ArrayList<WineSample> solvedList = (ArrayList<WineSample>) query.solveQuery(); System.out.println(" select " + query.getWineType() + " where " + query.getQueryConditionList()); // not necessary, but it looks WAY better with a bit with good grammar switch (query.getWineType()) { case ALL: { if (solvedList.size() > 1) { System.out.println(" -/ in total, " + "*" + solvedList.size() + "*" + " red and white wine samples match your query"); System.out.println(" -/ the list of those samples is: "); } else { if (solvedList.size() == 1) { System.out.println(" -/ in total, " + "*" + solvedList.size() + "*" + " red/white wine sample matches your query"); System.out.println(" -/ that sample is: "); } else { System.out.println(" -/ there are no wine samples that match your query"); } } } break; case RED: { if (solvedList.size() > 1) { System.out.println(" -/ in total, " + "*" + solvedList.size() + "*" + " red wine samples match your query"); System.out.println(" -/ the list of those samples is: "); } else { if (solvedList.size() == 1) { System.out.println(" -/ in total, " + "*" + solvedList.size() + "*" + " red wine sample matches your query"); System.out.println(" -/ that sample is: "); } else { System.out.println(" -/ there are no wine samples that match your query"); } } } break; case WHITE: { if (solvedList.size() > 1) { System.out.println(" -/ in total, " + "*" + solvedList.size() + "*" + " white wine samples match your query"); System.out.println(" -/ the list of those samples is: "); } else { if (solvedList.size() == 1) { System.out.println(" -/ in total, " + "*" + solvedList.size() + "*" + " white wine sample matches your query"); System.out.println(" -/ that sample is: "); } else { System.out.println(" -/ there are no wine samples that match your query"); } } } break; } for (WineSample s : solvedList) { System.out.println(" -> [" + query.getWineType().toString().toLowerCase() + " wine, sample #" + s.getId() + ", f_acid: " + s.getFixedAcidity() + ", v_acid: " + s.getVolatileAcidity() + ", c_acid: " + s.getCitricAcid() + ", r_sugar: " + s.getResidualSugar() + ", chlorid: " + s.getChlorides() + ", f_sulf: " + s.getFreeSulfurDioxide() + ", t_sulf: " + s.getTotalSulfurDioxide() + ", dens: " + s.getDensity() + ", pH: " + s.getpH() + ", sulph: " + s.getSulphates() + ", alc: " + s.getAlcohol() + ", qual: " + s.getQuality() + "]"); } } @Override // Go through the entire wine list of the specified type // and try to find the samples with the best quality. public List<WineSample> bestQualityWine(WineType wineType) { // using an ArrayList as there may be more wine samples that have the same // *best* quality ArrayList<WineSample> bestQualityWineSamples = new ArrayList<>(); ArrayList<WineSample> samples = (ArrayList<WineSample>) getWineSampleList(wineType); double bestQuality = 0; // If a wine sample has a greater quality than previous wine samples, // then we erase all the previous samples from the list containing all the // best samples until that moment // and add the current sample to the list (which is of better quality than those // we just erased). // If the quality of the sample is the same as that of the previous samples, we // simply add it to the list. for (WineSample sample : samples) { if (sample.getQuality() > bestQuality) { bestQuality = sample.getQuality(); bestQualityWineSamples.clear(); bestQualityWineSamples.add(sample); } else { if (sample.getQuality() == bestQuality) { bestQualityWineSamples.add(sample); } } } return bestQualityWineSamples; } @Override public List<WineSample> worstQualityWine(WineType wineType) { ArrayList<WineSample> worstQualityWineSamples = new ArrayList<>(); ArrayList<WineSample> samples = (ArrayList<WineSample>) getWineSampleList(wineType); double worstQuality = 10; // this method is basically the same as the one above it // the only difference is that now we're looking for the lowest quality samples for (WineSample sample : samples) { if (sample.getQuality() < worstQuality) { worstQuality = sample.getQuality(); worstQualityWineSamples.clear(); worstQualityWineSamples.add(sample); } else { if (sample.getQuality() == worstQuality) { worstQualityWineSamples.add(sample); } } } return worstQualityWineSamples; } @Override public List<WineSample> highestPH(WineType wineType) { ArrayList<WineSample> highestPHWineSamples = new ArrayList<>(); ArrayList<WineSample> samples = (ArrayList<WineSample>) getWineSampleList(wineType); double highestPH = -100; for (WineSample sample : samples) { if (sample.getpH() > highestPH) { highestPH = sample.getpH(); highestPHWineSamples.clear(); highestPHWineSamples.add(sample); } else { if (sample.getpH() == highestPH) { highestPHWineSamples.add(sample); } } } return highestPHWineSamples; } @Override public List<WineSample> lowestPH(WineType wineType) { ArrayList<WineSample> lowestPHWineSamples = new ArrayList<>(); ArrayList<WineSample> samples = (ArrayList<WineSample>) getWineSampleList(wineType); double lowestPH = 100; for (WineSample sample : samples) { if (sample.getpH() < lowestPH) { lowestPH = sample.getpH(); lowestPHWineSamples.clear(); lowestPHWineSamples.add(sample); } else { if (sample.getpH() == lowestPH) { lowestPHWineSamples.add(sample); } } } return lowestPHWineSamples; } @Override public double highestAlcoholContent(WineType wineType) { double highestAlcoholGrade = -1; ArrayList<WineSample> samples = (ArrayList<WineSample>) getWineSampleList(wineType); for (WineSample sample : samples) { if (sample.getAlcohol() > highestAlcoholGrade) { highestAlcoholGrade = sample.getAlcohol(); } } return highestAlcoholGrade; } @Override public double lowestCitricAcid(WineType wineType) { double lowestCitricAcidValue = 100; ArrayList<WineSample> samples = (ArrayList<WineSample>) getWineSampleList(wineType); for (WineSample sample : samples) { if (sample.getCitricAcid() < lowestCitricAcidValue) { lowestCitricAcidValue = sample.getCitricAcid(); } } return lowestCitricAcidValue; } @Override public double averageAlcoholContent(WineType wineType) { double averageAlcoholContent = 0; ArrayList<WineSample> samples = (ArrayList<WineSample>) getWineSampleList(wineType); for (WineSample sample : samples) { averageAlcoholContent += sample.getAlcohol(); } averageAlcoholContent = averageAlcoholContent / samples.size(); return averageAlcoholContent; } }
[ "emisv_16@yahoo.ro" ]
emisv_16@yahoo.ro
0ab5a978f12fc89ea1fb838590990054e990da47
1302a788aa73d8da772c6431b083ddd76eef937f
/WORKING_DIRECTORY/frameworks/support/samples/SupportLeanbackDemos/src/com/example/android/leanback/VerticalGridFragment.java
fe664dd7a6799c6b03aa8117cdf0afea490a7913
[]
no_license
rockduan/androidN-android-7.1.1_r28
b3c1bcb734225aa7813ab70639af60c06d658bf6
10bab435cd61ffa2e93a20c082624954c757999d
refs/heads/master
2021-01-23T03:54:32.510867
2017-03-30T07:17:08
2017-03-30T07:17:08
86,135,431
2
1
null
null
null
null
UTF-8
Java
false
false
4,227
java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.example.android.leanback; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v17.leanback.widget.ArrayObjectAdapter; import android.support.v17.leanback.widget.Presenter; import android.support.v17.leanback.widget.RowPresenter; import android.support.v17.leanback.widget.VerticalGridPresenter; import android.support.v17.leanback.widget.Row; import android.support.v17.leanback.widget.OnItemViewClickedListener; import android.support.v17.leanback.widget.OnItemViewSelectedListener; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class VerticalGridFragment extends android.support.v17.leanback.app.VerticalGridFragment { private static final String TAG = "leanback.VerticalGridFragment"; private static final int NUM_COLUMNS = 3; private static final int NUM_ITEMS = 50; private static final int HEIGHT = 200; private static final boolean TEST_ENTRANCE_TRANSITION = true; private static class Adapter extends ArrayObjectAdapter { public Adapter(StringPresenter presenter) { super(presenter); } public void callNotifyChanged() { super.notifyChanged(); } } private Adapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate"); super.onCreate(savedInstanceState); setBadgeDrawable(getActivity().getResources().getDrawable(R.drawable.ic_title)); setTitle("Leanback Vertical Grid Demo"); setupFragment(); if (TEST_ENTRANCE_TRANSITION) { // don't run entrance transition if fragment is restored. if (savedInstanceState == null) { prepareEntranceTransition(); } } // simulates in a real world use case data being loaded two seconds later new Handler().postDelayed(new Runnable() { public void run() { loadData(); startEntranceTransition(); } }, 2000); } private void loadData() { for (int i = 0; i < NUM_ITEMS; i++) { mAdapter.add(Integer.toString(i)); } } private void setupFragment() { VerticalGridPresenter gridPresenter = new VerticalGridPresenter(); gridPresenter.setNumberOfColumns(NUM_COLUMNS); setGridPresenter(gridPresenter); mAdapter = new Adapter(new StringPresenter()); setAdapter(mAdapter); setOnItemViewSelectedListener(new OnItemViewSelectedListener() { @Override public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { Log.i(TAG, "onItemSelected: " + item + " row " + row); } }); setOnItemViewClickedListener(new OnItemViewClickedListener() { @Override public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { Log.i(TAG, "onItemClicked: " + item + " row " + row); mAdapter.callNotifyChanged(); } }); setOnSearchClickedListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), SearchActivity.class); startActivity(intent); } }); } }
[ "duanliangsilence@gmail.com" ]
duanliangsilence@gmail.com
6a40fa6f36c7a8038366b1ebe2b96b38f5c5692f
62b368e2e432a666b8c4c88431856366b09f2208
/src/main/java/org/contacomigo/service/events/config/package-info.java
4330b83790ee789a2666f9d4199e70c16a19193c
[]
no_license
hackathon-ici-conta-comigo/service-events
4e46c30163cce6d21243811d5f89d607a20d7a22
b8fcfe97046553c1de0afb45c983fd6c5f154b98
refs/heads/master
2021-06-08T02:07:19.030356
2017-05-22T22:58:30
2017-05-22T22:58:30
88,569,378
0
0
null
null
null
null
UTF-8
Java
false
false
96
java
/** * Spring Framework configuration files. */ package org.contacomigo.service.events.config;
[ "willsch89@gmail.com" ]
willsch89@gmail.com
18c2405ec09ceb8545fc160ee4cd87e2dfc6802b
cb5d53e0577d55601a62a4edaa45dfff43211190
/taskmanager/TaskController.java
7f28a1902775a818ce23d1b5b6c174fbc8a85ac1
[]
no_license
Mone20/TaskManager
3d375e094a5914c25b2d34a12aab8aaca9f7cf70
f46c00af0425faa7e759c2670e4814708a6cac92
refs/heads/master
2020-09-08T05:02:39.750748
2020-02-15T15:19:25
2020-02-15T15:19:25
221,023,229
0
1
null
2019-12-05T13:53:43
2019-11-11T16:30:56
Java
UTF-8
Java
false
false
1,858
java
/* * 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 taskmanager; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.text.ParseException; import java.util.ArrayList; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * @author Rodion */ public class TaskController { private Log tl; private View ui; public TaskController() throws ClassNotFoundException, IOException, SAXException, ParserConfigurationException, ParseException { this.tl = new TaskLog(); this.ui = new View(); } public Log getLog() { return tl; } public void mainView() { ui.mainView(); } public boolean createTask(TaskNode newTask) throws IOException, ParseException { if (!newTask.getTaskName().isEmpty() && !newTask.getTaskDescription().isEmpty() && !newTask.getPhoneNumber().isEmpty()) { tl.createTask(newTask); tl.saveAll(); return true; } else return false; } public boolean deleteTask(int index) throws IOException { if (tl.size() > index && index >= 0) { this.tl.deleteTask(tl.get(index)); tl.saveAll(); return true; } else return false; } public void viewAll() { if (!this.tl.isEmpty()) ui.viewAllTasks(tl); } public void notification() throws IOException, ClassNotFoundException, ParseException { new TimeNotification(tl).onTimeNotification(); } public void clear() { ui.clear(); } }
[ "noreply@github.com" ]
Mone20.noreply@github.com
2172720bb358aff61a7cb4ce2f28eda72c55b38a
a742277ed7a0e86a814e3e78fd952ac1d9a80c65
/src/main/java/com/smtown/smhds/board/BoardController.java
f05a1652236b8e8e367775a1d43674458675b071
[]
no_license
chocodigo/HDS
27ff3f3ff2463805bd606f639fc0f3424c44f19b
6a9c30e57c3b9b0e8039e733c9462fcb9d5ea7f4
refs/heads/master
2021-07-01T19:29:27.198852
2021-06-28T01:20:38
2021-06-28T01:20:38
211,219,016
0
0
null
2021-06-28T01:24:15
2019-09-27T02:22:11
Java
UTF-8
Java
false
false
24,563
java
package com.smtown.smhds.board; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.MailSender; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.DelegatingPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.smtown.smhds.account.Account; import com.smtown.smhds.account.AccountService; import com.smtown.smhds.admin.AdminService; import com.smtown.smhds.admin.CategoryVO; import com.smtown.smhds.comment.CommentService; import com.smtown.smhds.util.FileUtil; import com.smtown.smhds.util.FileVO; import com.smtown.smhds.util.MailUtil; import com.smtown.smhds.util.PageMaker; import com.smtown.smhds.util.PrintPage; /** * <pre> * BoardController.java - 요청사항 게시판 컨트롤러 * </pre> * * @author 최해림 * @since 2019.05.21 * @version 1.0 * * <pre> * == Modification Information == * Date Modifier Comment * ==================================================== * 2019.05.21 최해림 Initial Created. * 2019.09.20 방재훈 * ==================================================== * </pre> * * Copyright SM Entertainment.(C) All right reserved. */ @Controller public class BoardController{ private static final Logger log = LoggerFactory.getLogger(BoardController.class); // 요청사항 게시판 서비스(Service) 클래스 private final BoardService boardService; // 카테고리 관리 서비스(Service 클래스 private final AdminService adminService; //답글 서비스(Service) 클래스 private final CommentService commentService; //계정 서비스(Service) 클래스 private final AccountService accountService; private final MailSender sender; //메일 발송 기능을 위한 sender 객체 @Autowired public BoardController(BoardService boardService, CommentService commentService, AccountService accountService, AdminService adminService, MailSender sender){ this.boardService = boardService; this.commentService = commentService; this.accountService = accountService; this.adminService = adminService; this.sender = sender; } /* * 최초 프로젝트 접근 시 목록페이지로 넘김 * @param * @return "/main" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping(value="/") public String root() { return "redirect:/main"; } /* * 로그인 페이지 * @param * @return "/main/login" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping("/login") public String login() { return "main/login"; } /* * 비밀번호 초기화 페이지 * @param * @return "/main/login" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping("/forgot") public String forgot() { return "main/forgot"; } /* * 생일 인증 * @param request : 입력된 ID, 생일 * @return returnMap : 조회성공 여부(성공 1, 실패 0) * @exception Exception - 조회시 발생한 예외 */ @RequestMapping(value = "/forgotProc", method = RequestMethod.POST) @ResponseBody public Map<String,String> forgotProc(HttpServletRequest request) throws Exception{ Map<String,String> returnMap = new HashMap<>(); //ID, 생일 추가할 맵 생성 String user_name = request.getParameter("user_name"); //입력된 ID 받아오기 String phon_enum = request.getParameter("phon_enum"); //입력된 생일 받아오기 Account account = new Account(); //account 객체 생성 account.setUser_name(user_name); //user_name 설정 account.setPhon_enum(phon_enum); //phon_enum 설정 int isItPermit = boardService.boardCompareBirthService(account); //user_name, phon_enum 비교 서비스 returnMap.put("isItPermit",String.valueOf(isItPermit)); //조회성공 1, 조회실패 0을 isItPermit값에 저장후 리턴 return returnMap; } /* * 비밀번호 재설정 * @param request : 입력된 ID, 비밀번호 * @return 로그인 페이지로 이동 * @exception Exception - 조회시 발생한 예외 */ @RequestMapping(value = "/resetPWProc", method = RequestMethod.POST) @ResponseBody public int resetPWProc(HttpServletRequest request) throws Exception{ //bycrpt encoder 설정 Map encoders = new HashMap<>(); encoders.put("bcrypt",new BCryptPasswordEncoder()); PasswordEncoder passwordEncoder = new DelegatingPasswordEncoder("bcrypt",encoders); String user_name = request.getParameter("user_name"); //입력된 ID 받아오기 String pass_word = request.getParameter("pass_word"); //입력된 비밀번호 받아오기 String enc_pass_word = passwordEncoder.encode(pass_word); //패스워드 암호화 Account account = new Account(); //account 객체 생성 account.setUser_name(user_name); //user_name 설정 account.setPass_word(enc_pass_word); //pass_word 설정 return boardService.boardResetPasswordService(account); //비밀번호 변경 서비스 } /* * 비밀번호 null 확인 * @param request : 입력된 ID * @return : 패스워드 존재시 1, 없을 시 0 * @exception Exception - 조회시 발생한 예외 */ @RequestMapping("/isPwNull") @ResponseBody public int isPwNull(HttpServletRequest request) throws Exception{ String user_name = request.getParameter("user_name"); //user_name 받아오기 return boardService.isPasswordNullService(user_name); //패스워드 존재하는지 확인하는 Query 실행 } /* * 게시판 목록 * @param model - 게시글 정보,페이징 정보, 현재 페이지 , * printPage - 조회하려는 페이징 정보 printPage에 파라미터 없을 시에 생성자에서 기본 값으로 셋팅(page = 1 , perPageNum=5) * @return "/board/BoardList" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping(value="/list") public String boardList(HttpServletRequest request, @ModelAttribute("printPage") PrintPage printPage, Model model) throws Exception{ String cate_gory = request.getParameter("cate_gory"); //카테고리받아오기 printPage.setCate_gory(cate_gory); //카테고리 설정 int listCnt = boardService.boardcount(printPage); //전체 게시글 수 List<BoardVO> list = boardService.boardListService(printPage); //전체 게시글 list List<CategoryVO> category_list = adminService.getCategoryListService(); //카테고리 list model.addAttribute("list", list); //전체 게시글 List model.addAttribute("category_list", category_list);//카테고리 이름 넘기기 PageMaker pageMaker = new PageMaker(); //페이징 처리 객체 생성 pageMaker.setprintPage(printPage); //현재 페이지 정보 pageMaker.setTotalCount(listCnt); //전체 게시글 수 model.addAttribute("pageMaker",pageMaker); model.addAttribute("curpage",printPage.getPage()); model.addAttribute("cate_gory",cate_gory); return "board/BoardList"; } /* * 게시판 상세 * @param idxx_numb - 글 번호 * model - 글 정보 * @return "/board/BoardDetail" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping(value="/detail",method=RequestMethod.POST) public String boardDetail(@ModelAttribute("idxx_numb") String idxx_numb, Model model) throws Exception{ BoardVO detail = boardService.boardDetailService(idxx_numb); //게시글 정보 FileVO files = boardService.fileDetailService(idxx_numb); //게시글의 첨부파일 정보 int hasReply = boardService.boardHasReplyService(idxx_numb); //게시글에 답글이 등록돼있는지 갯수 확인 model.addAttribute("detail", detail); //글정보를 넘기기 model.addAttribute("files", files); //파일 정보 넘기기 model.addAttribute("hasReply",hasReply); //답글갯수 넘기기 //답글 갯수가 1이면 답글 ID 넘기기 if(hasReply == 1) { String comm_idxx = commentService.commentSelectCommIdxxService(idxx_numb); model.addAttribute("comm_idxx",comm_idxx); } return "board/BoardDetail"; } /* * 파일 다운로드 * @param idxx_numb - 글 번호 * request - 요청 * response - 응답 * @return * @exception Exception - 조회시 발생한 예외 */ @RequestMapping(value="/fileDown/{idxx_numb}") public void fileDown(@PathVariable String idxx_numb, HttpServletRequest request, HttpServletResponse response) throws Exception{ request.setCharacterEncoding("UTF-8"); FileVO fileVO = boardService.fileDetailService(idxx_numb); try { //파일 업로드 된 경로 String fileUrl = fileVO.getFile_urll(); //fileUrl : 업로드된 파일 경로 fileUrl += "/"; String fileName = fileVO.getFile_name(); //fileName : 파일 원본 이름 //실제 내보낼 파일명 String oriFileName = fileVO.getFile_orig(); //oriFileName : 원래 파일명 InputStream in = null; OutputStream os = null; File file = null; boolean skip = false; //skip : 파일 읽지못하면 false String browser = ""; //파일을 읽어 스트림에 담기 try { file = new File(fileUrl, fileName); in = new FileInputStream(file); }catch(FileNotFoundException fe) { skip = true; } browser = request.getHeader("User-Agent"); //파일 다운로드 헤더 지정 response.reset(); response.setContentType("application/octet-stream"); response.setHeader("Content-DesprintPageption", "JSP Generated Data"); //파일을 읽었을 경우 if(!skip) { //IE if(browser.contains("MSIE")) { response.setHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(oriFileName, "UTF-8").replaceAll("\\+", "\\ ")+"\""); } //IE 11 이상 else if(browser.contains("Trident")) { response.setHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(oriFileName, "UTF-8").replaceAll("\\+", "\\ ")+"\""); } else { response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(oriFileName.getBytes("UTF-8"), "ISO8859_1") + "\""); response.setHeader("Content-Type", "application/octet-stream; charset=utf-8"); } response.setHeader("Content-Length", "" + file.length()); os = response.getOutputStream(); byte b[] = new byte[(int)file.length()]; int leng = 0; while((leng = in.read(b)) > 0) { os.write(b, 0 ,leng); } }else { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<script>alert('파일을 찾을 수 없습니다.');history.back();</script>"); out.flush(); } in.close(); os.close(); } catch (Exception e) { System.out.println("Error : " + e.getMessage()); } } /* * 게시글 작성 * @param * @return "/board/BoardInsert" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping("/insert") public String boardInsertForm(Model model) throws Exception { model.addAttribute("category_list",adminService.getCategoryListService());//카테고리 이름 넘기기 Account account = (Account)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String user_name = account.getUsername(); //로그인한 사용자의 user_name받아오기 Account user_account = accountService.accountDetailService(user_name); //user_name을 통해 계정정보 받아오기 String real_name = user_account.getReal_name(); //사용자의 실제 이름 받아오기 model.addAttribute("real_name",real_name); return "board/BoardInsert"; } /* * 게시글 DB에 등록 * @param request - 요청 * files - 파일 * @return "/list" * @exception Exception - 조회시 발생한 예외 */ @Transactional @RequestMapping("/insertProc") public String boardInsertProc(HttpServletRequest request, @RequestPart MultipartFile files) throws Exception{ try { BoardVO board = new BoardVO(); FileVO file; String idxx_numb = boardService.boardSelectIdxxService(); //게시글 주키 생성 Account account = (Account)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //acoount 정보 받아오기 String user_name = account.getUsername(); //로그인한 사용자의 user_name받아오기 Account user_account = accountService.accountDetailService(user_name); //user_name을 통해 계정정보 받아오기 String titl_name = request.getParameter("titl_name"); String cont_ents = request.getParameter("cont_ents"); String crea_user = user_account.getReal_name(); String stat_flag = "01"; String cate_gory = request.getParameter("cate_gory"); board.setTitl_name(titl_name); //게시글 제목 board.setCont_ents(cont_ents); //게시글 내용 board.setUser_name(user_name); //작성자 이름 board.setCrea_user(crea_user); //작성자 이름 board.setStat_flag(stat_flag); //첫 글 작성시 신규상태로 초기화( 01 - 신규/ 02 - 담당자 접수/ 03 - 진행/ 04 - 완료) board.setIdxx_numb(idxx_numb); //idxx_numb 생성 board.setCate_gory(cate_gory); //카테고리 설정 //파일첨부시 if(!files.isEmpty()) { FileUtil fileUtil = new FileUtil(); file = fileUtil.uploadFile(idxx_numb, files); //업로드 if(file!=null) boardService.fileInsertService(file); //파일 등록 쿼리 실행 } boardService.boardInsertService(board); //게시글 등록 쿼리 실행 } catch(Exception e) { log.error("boardInsertProc에서 에러발생..."); throw new RuntimeException(e); } return "redirect:/main?tab_menu=list"; } /* * 게시글 수정 * @param idxx_numb - 글 번호 * model - 게시글 정보 * @return "/board/BoardUpdate" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping("/update") public String boardUpdateForm(HttpServletRequest request, Model model) throws Exception{ String idxx_numb = request.getParameter("idxx_numb"); List category_list = adminService.getCategoryListService(); //카테고리 이름 넘기기 BoardVO boardVO = boardService.boardDetailService(idxx_numb); //idxx_numb를 가진 글 상세정보 넘기기 model.addAttribute("category_list",category_list); model.addAttribute("detail", boardVO); if(boardService.fileDetailService(idxx_numb) != null) { //idxx_numb를 가진 파일 존재 시 model.addAttribute("files",boardVO); //idxx_numb를 가진 파일 상세정보 넘기기 } return "board/BoardUpdate"; } /* * 게시글 DB 수정 * @param request - 수정할 글 정보 받아오기 * response - 지원하지 않는 첨부파일 등록 시 오류 알람 * files - 첨부파일 * @return "/detail/idxx_numb" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping("/updateProc") public String boardUpdateProc(HttpServletRequest request, HttpServletResponse response , @RequestPart MultipartFile files) throws Exception{ BoardVO board = new BoardVO(); FileUtil fileUtil = new FileUtil(); String titl_name = request.getParameter("titl_name"); //글 제목 받아오기 String cont_ents = request.getParameter("cont_ents"); //글 내용 받아오기 String idxx_numb = request.getParameter("idxx_numb"); //글 ID 받아오기 String cate_gory = request.getParameter("cate_gory"); //글 카테고리 받아오기 board.setTitl_name(titl_name); //글 제목 설정 board.setCont_ents(cont_ents); //글 내용 설정 board.setIdxx_numb(idxx_numb); //글 ID 설정 board.setCate_gory(cate_gory); //글 카테고리 설정 FileVO befoFileVO = boardService.fileDetailService(idxx_numb); //idxx_numb가 가지고 있는 파일 정보 가져오기 FileVO fileVO; //새로 등록할 파일 정보 if(befoFileVO!=null && !files.isEmpty()) {//게시글에 파일이 등록되어 있고 등록한 파일이 있을 경우 boardService.fileDeleteService(idxx_numb); //DB에 등록돼 있는 파일 정보 삭제 File file = new File(befoFileVO.getFile_urll()+befoFileVO.getFile_name()); //파일이 등록돼있는 URL에서 파일 가져오기 file.delete(); //파일 삭제 fileVO= fileUtil.uploadFile(idxx_numb, files); //새로운 파일 업로드 boardService.fileInsertService(fileVO); //새로운 파일 정보 DB에 입력 } else if(befoFileVO==null && !files.isEmpty()) { //파일이 등록돼 있지 않을 경우 fileVO = fileUtil.uploadFile(idxx_numb, files); //업로드 boardService.fileInsertService(fileVO); //파일 정보 DB에 입력 } boardService.boardUpdateService(board); //글 update Query 실행 return "redirect:/main?tab_menu=list"; } /* * 게시글 DB 파일 삭제 * @param request - idxx_numb 요청 * @return boardService.fileDeleteService(idxx_numb) * @exception Exception - 조회시 발생한 예외 */ @RequestMapping("/fileDelete") @ResponseBody public int boardFileDelete(HttpServletRequest request) throws Exception{ String idxx_numb = request.getParameter("idxx_numb"); //글 ID 받아오기 FileVO befoFileVO= boardService.fileDetailService(idxx_numb); //등록돼있는 파일 정보 가져오기 File file = new File(befoFileVO.getFile_urll()+befoFileVO.getFile_name()); //파일이 등록돼있는 URL에서 파일 가져오기 file.delete(); //파일 삭제 return boardService.fileDeleteService(idxx_numb); //게시글 삭제 Query 실행 } /* * 게시글 진행상황 DB 수정 * @param request - idxx_numb, stat_flag * @return "/detail/idxx_numb" * @exception Exception - 조회시 발생한 예외 */ @Transactional @RequestMapping("/updateStatProc") public String boardUpdateStatProc(HttpServletRequest request) throws Exception{ try { BoardVO board = new BoardVO(); Account boardAccount = new Account(); //글 작성자 계정 String stat_flag = request.getParameter("stat_flag"); String idxx_numb = request.getParameter("idxx_numb"); String titl_name = request.getParameter("titl_name"); String user_name = request.getParameter("user_name"); board.setStat_flag(stat_flag); //변화 상태 받아오기 board.setIdxx_numb(idxx_numb); //idxx_numb 받아오기 board.setTitl_name(titl_name); //게시글 제목 받아오기 board.setUser_name(user_name); //글 작성자 받아오기 boardService.boardUpdateStatService(board); //게시글 상태 변화 Query 실행 boardAccount = accountService.accountDetailService(user_name); //글작성자 계정정보 받아오기 //글 상태 수정 시 글 작성자에게 메일 보내기 MailUtil mailUtil=new MailUtil(sender); //메일 내용 설정 String from="cocoa1149@smtown.com"; String to =boardAccount.getUser_mail(); String subject = "smHDS : 등록된 글의 진행상황이 변경되었습니다."; String mailMsg = "등록하신 요청사항 '"+board.getTitl_name()+"' 의 진행상황이 '"+ boardService.selectCodeNameService(stat_flag)+ "'으로 변경되었습니다."; mailUtil.sendMail(from,to,subject,mailMsg); //메일 내용 보내기 } catch(Exception e) { log.error("boardUpdateStatProc에서 에러발생..."); throw new RuntimeException(e); } return "redirect:/main?tab_menu=list"; } /* * 게시글 삭제 * @param * @return "/list/" * @exception Exception - 조회시 발생한 예외 */ @Transactional @RequestMapping("/delete") public String boardDelete(HttpServletRequest request) throws Exception{ try { String idxx_numb = request.getParameter("idxx_numb"); //삭제할 게시글 ID 가져오기 FileVO befoFileVO= boardService.fileDetailService(idxx_numb); //게시글에 등록돼있는 파일 정보 가져오기 boardService.boardDeleteService(idxx_numb); //게시글 삭제 Query 실행 //파일이 등록돼있으면 if(befoFileVO != null) { File file = new File(befoFileVO.getFile_urll()+befoFileVO.getFile_name()); //파일이 등록돼있는 URL에서 파일 가져오기 file.delete(); //파일 삭제 boardService.fileDeleteService(idxx_numb); //DB에서 파일정보 삭제 } } catch(Exception e) { log.error("boardDelete에서 에러발생..."); throw new RuntimeException(e); } return "redirect:/main?tab_menu=list"; } /* * 자동완성 * @param printPage - 출력할 페이지 정보 * model - 자동완성 리스트 * @return "/common/AutoComplete" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping(value="/board/autoComplete") public String suggestion(HttpServletRequest request, Model model) throws Exception{ String search = request.getParameter("search"); //search 값 가져오기 Map<String,String> searchMap = new HashMap<>(); searchMap.put("search",search); List<String> autoComplete = boardService.boardSuggestionService(searchMap); //자동완성 Query 실행 model.addAttribute("list", autoComplete); //list에 결과값 넘기기 return "common/AutoComplete"; } /* * 메인화면 * @param model - 공지사항 5개 출력 , FAQ 5개 출력 * @return "/main/boardMain" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping(value="/main") public String boardMain(@ModelAttribute("tab_menu") String tabMenu, Model model) throws Exception{ Account account = (Account)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //로그인한 계정 정보 String user_name = account.getUsername(); //로그인한 계정의 user_name Account accountDetail = accountService.accountDetailService(user_name); //사용자 상세정보 가져오기 model.addAttribute("tab_menu",tabMenu); model.addAttribute("accountDetail",accountDetail); StatInfo statInfo = boardService.boardStatInfoService(); //전체 진행상황 정보 model.addAttribute("statInfo",statInfo); return "main/boardMain"; } /* * 메인화면 상태에 따른 분류 * @param model - 공지사항 5개 출력 , FAQ 5개 출력 * @return "/main/boardMain" * @exception Exception - 조회시 발생한 예외 */ @RequestMapping(value="/findByStat") public String boardFindStat(HttpServletRequest request, @ModelAttribute("printPage") PrintPage printPage, Model model) throws Exception{ String stat_flag = request.getParameter("stat_flag"); //상태코드 받아오 String cate_gory = request.getParameter("cate_gory"); //카테고리받아오기 printPage.setCate_gory(cate_gory); printPage.setStat_flag(stat_flag); StatInfo statInfo = boardService.boardStatInfoService(); //전체 진행상황 정보 int listCnt = 0; //전체 게시글 수 switch (stat_flag){ case "01": listCnt = statInfo.getStat_neww(); break; case "02": listCnt = statInfo.getStat_chek(); break; case "03": listCnt = statInfo.getStat_load(); break; case "04": listCnt = statInfo.getStat_comp(); break; } model.addAttribute("list",boardService.boardFindStatService(printPage)); //전체 게시글 List model.addAttribute("category_list",adminService.getCategoryListService());//카테고리 이름 넘기기 PageMaker pageMaker = new PageMaker(); //페이징 처리 객체 생성 pageMaker.setprintPage(printPage); //현재 페이지 정보 pageMaker.setTotalCount(listCnt); //전체 게시글 수 model.addAttribute("pageMaker",pageMaker); model.addAttribute("curpage",printPage.getPage()); model.addAttribute("cate_gory",cate_gory); return "board/BoardList"; } }
[ "chocodigo1149@gmail.com" ]
chocodigo1149@gmail.com
76cb63759eb98d2f23acaa946629df0cb7b34b31
366ddfd53c0b104635e82a59d931b8b1159649b1
/Semester 3/Data Structure And Algorithm/CityRoutMapping/src/cityroutmapping/Graph.java
70b7ecc1270f43c1606ce76c259dd66941763c80
[]
no_license
hgmehta/AcademicProjects
c4250987211c7f330755fa74a7907dc44ebc12f2
47b774fd27248a5c564066dc721fd1461ca0af56
refs/heads/master
2021-01-23T03:53:42.750557
2017-08-03T18:43:42
2017-08-03T18:43:42
86,132,566
0
1
null
null
null
null
UTF-8
Java
false
false
9,851
java
/* * 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 cityroutmapping; /** * * @author gaurang */ import java.util.Iterator; import java.util.Set; import java.util.HashSet; import java.util.InputMismatchException; public class Graph { //----------Initialization----------------------------------------------------------------------------------------------- private int max_vertex; private Vertex vertexList[]; private int adjMat[][]; private int nVertex; private Queue theQueue; private Stack theStack,printStack; //----------End of initialization--------------------------------------------------------------------------------------- //---------------Start of constructor----------------------------------------------------------------------------------- public Graph(int vertex){ max_vertex = vertex; vertexList = new Vertex[max_vertex]; adjMat = new int[max_vertex][max_vertex]; nVertex = 0; for(int i=0;i<max_vertex;i++){ for(int j=0;j<max_vertex;j++){ adjMat[i][j]=0; } } //theQueue = new Queue(max_vertex); theQueue = new Queue(); theStack = new Stack(); printStack = new Stack(); // theStack = new Stack(); }//end of constructor.. //----------------------------End of constructor------------------------------------------------------------------------ //-------------------Start of addVertex(int lab)------------------------------------------------------------------------ public void addVertex(int lab){ nVertex = lab; vertexList[nVertex] = new Vertex(lab); } //----------------End of addVertex(int lab)---------------------------------------------------------------------------- //-------------Start of addEdge(int start,int end,int weight)---------------------------------------------------------- public void addEdge(int start,int end,int weight){ adjMat[start][end] = weight; adjMat[end][start] = weight; } //--------------End of addEdge(int start,int end,int weight)----------------------------------------------------------- //------------Start of displayVertex(int v)----------------------------------------------------------------------------- public void displayVertex(int v){ System.out.print(vertexList[v].getLabel()); } //-------------------End of displayVertex(int v)----------------------------------------------------------------------- //----------------Start of printGraph()-------------------------------------------------------------------------------- public void printGraph(){ for(int j=0;j<max_vertex;j++){ System.out.print(j + "\t"); }//end of for.. System.out.print("\n"); for(int i=0;i<max_vertex;i++){ for(int j=0;j<max_vertex;j++){ System.out.print(adjMat[i][j]+"\t"); }//end of inner for.. System.out.print("\n"); }//end of outter for.. }//end of printGraph.. //-----------------End of printGraph()--------------------------------------------------------------------------------- public int[][] getAjdMatrix(){ return adjMat; } //------------start of breadthFirstSearch(int start,int end , BusStands bus)------------------------------------------- public String breadthFirstSearch(int start,int end , BusStands bus){ //theStack = new Stack(); vertexList[start].setWasVisited(true);// = true; int i=0; theQueue.insert(start); printStack.push(start); String s = ""; int v2; while(!theQueue.isEmpty()){ int v1 = theQueue.remove(); v2 = getAdjUnvisitedVertex(v1); while(v2 != -1){ if(v2 != end){ vertexList[v2].setWasVisited(true);// = true; printStack.push(v2); theQueue.insert(v2); v2 = getAdjUnvisitedVertex(v1); }else if(v2 == end){ printStack.push(v2); break; }//end of (v2 != end)..else if(v2 == end).. }//end of while(v2 != -1).. if(v2 == end){ break; }//end of if(v2 == end).. }//end of (!theQueue.isEmpty()).. for(int j=0;j<nVertex;j++){ vertexList[j].setWasVisited(false);// = false; }//end of for.. theQueue.makeQueueEmpty(); int first = printStack.peek(); s = s + bus.splitName(first); printStack.pop(); double dist=0; while(!printStack.isEmpty()){ boolean isAdj = isAdjcent(first,printStack.peek()); if(isAdj){ dist = dist + adjMat[first][printStack.peek()]; s = bus.splitName(printStack.peek())+ "\n" + s; first = printStack.peek(); printStack.pop(); }else{ if(!printStack.isEmpty()){ printStack.pop(); }//end of if(!theStack.isEmpty()).. }//end of if(isAdj).. else.. }//end of while(!theStack.isEmpty()).. printStack.makeStackEmpty(); s = s + "\n\n Distance from\n " + bus.splitName(start) + "\n" + " to\n " + bus.splitName(end) + "\n" + " is : " + dist + " m" + "(" + dist/1000 + " Km)"; return s; }//end of breadthFirstSearch.. //---------------------End of breadthFirstSearch(int start,int end , BusStands bus)----------------------------------- //-------------------Start of depthFirstSearch(int start,int end , BusStands bus)------------------------------------- public String depthFirstSearch(int start,int end , BusStands bus){ //Stack theStack = new Stack(); vertexList[start].setWasVisited(true);// = true; //int i=0; printStack.push(start); theStack.push(start); String s = ""; int v2; while(!theStack.isEmpty()){ int v = getAdjUnvisitedVertex(theStack.peek()); while(v != -1){ if(v == end){ printStack.push(v); break; }else{ vertexList[v].setWasVisited(true);// = true; theStack.push(v); printStack.push(v); //theStack.pop(); v = getAdjUnvisitedVertex(theStack.peek()); } }//end of while(v != -1) if(v == end){ printStack.push(v); break; }//end of if(v == end) theStack.pop(); }//end of (!theQueue.isEmpty()).. for(int j=0;j<nVertex;j++){ vertexList[j].setWasVisited(false);// = false; }//end of for.. theStack.makeStackEmpty(); int first = printStack.peek(); s = s + bus.splitName(first); printStack.pop(); double dist = 0; while(!printStack.isEmpty()){ boolean isAdj = isAdjcent(first,printStack.peek()); if(isAdj){ dist = dist + adjMat[first][printStack.peek()]; s = s + "\n" + bus.splitName(printStack.peek());// + "\n" + s; first = printStack.peek(); printStack.pop(); }else{ if(!printStack.isEmpty()){ printStack.pop(); }//end of if(!theStack.isEmpty()).. }//end of if(isAdj).. else.. }//end of while(!theStack.isEmpty()).. printStack.makeStackEmpty(); s = s + "\n\n Distance from\n " + bus.splitName(start) + "\n" + " to\n " + bus.splitName(end) + "\n" + " is : " + dist + " m" + "(" + dist/1000 + " Km)"; return s; //System.out.print("\nDistance from " + end + " to " + start + " is: " + dist + " m" + "(" +dist/1000 + " Km)");// }//end of depthFirstSearch.. //-------------------End of depthFirstSearch(int start,int end , BusStands bus)--------------------------------------- //--------------Start of int getAdjUnvisitedVertex(int v)------------------------------------------------------------- public int getAdjUnvisitedVertex(int v){ for(int j=0;j<nVertex;j++){ if(adjMat[v][j] !=0 && vertexList[j].getWasVisited() == false){ return j; }//end of if.. }//end of for.. return -1; }//end of getAdjUnvisitedVertex.. //--------------End of int getAdjUnvisitedVertex(int v)---------------------------------------------------------------- //--------------Start of boolean isAdjcent(int first,int second)------------------------------------------------------- public boolean isAdjcent(int first,int second){ for(int j=0;j<nVertex;j++){ if(adjMat[first][second] !=0){ return true; }//end of if(adjMat[first][second] !=0).. }//end of for.. return false; }//end of isAdjcent.. //--------------------End of boolean isAdjcent(int first,int second)---------------------------------------------------- }//end of class Graph.
[ "noreply@github.com" ]
hgmehta.noreply@github.com
acbcee2dbf45ebf2fe519f612247a17b3bfdebff
aaac8ac40cb4e87e4630f61484658e6b8f40e4a5
/src/ie/gmit/sw/DerivedTypeator.java
68cf2f37d91f809109c52c0d0a4eb933b896896d
[]
no_license
BrendanToolan/testRepo
351e0fa969873f360b5d69a7621f9b9d751346e2
2f995e1e91e9069179fe49c685940bc574a669f3
refs/heads/master
2020-09-19T18:13:43.410711
2019-11-28T23:43:21
2019-11-28T23:43:21
224,261,122
0
0
null
null
null
null
UTF-8
Java
false
false
256
java
package ie.gmit.sw; public interface DerivedTypeator extends Typeator { @Override default int execute() { // TODO Auto-generated method stub return -1; } @Override default int invoke() { // TODO Auto-generated method stub return 0; } }
[ "btoolan73@gmail.com" ]
btoolan73@gmail.com
c3ff1e6573bfae976977629d8b46769eee0c4839
4c3d2c35e525dc25513d127d0c9bf58d3a6b6101
/vladlep/SuperAwesomeFighters/src/fighter/Rule.java
9cf4eae74bb51f1e4d18fde2200c7600bf94c73f
[]
no_license
tvdstorm/sea-of-saf
13e01b744b3f883c8020d33d78edb2e827447ba2
6e6bb3ae8c7014b0b8c2cc5fea5391126ed9b2f1
refs/heads/master
2021-01-10T19:16:15.261630
2014-05-06T11:30:14
2014-05-06T11:30:14
33,249,341
0
0
null
null
null
null
UTF-8
Java
false
false
1,510
java
package fighter; import java.util.List; import java.util.Random; import fighter.action.*; import fighter.checker.Visitor; import fighter.condition.ConditionType; import fighter.condition.ICondition; public class Rule implements ASTNode { private ICondition condition; private Actions<MoveActionType> moveActions; private Actions<FightActionType> fightActions; public Rule(ICondition condition, Actions<MoveActionType> moveActions, Actions<FightActionType> fightActions) { this.condition = condition; this.moveActions = moveActions; this.fightActions = fightActions; } @Override public void accept(Visitor visitor) { visitor.visit(this); } public boolean checkCondition(List<ConditionType> acceptedConditions) { return condition.testCondition(acceptedConditions); } private int generatRandomIndex(int maxSize) { Random randomGenerator = new Random(); return randomGenerator.nextInt(maxSize); } public ICondition getCondition() { return condition; } public Actions<FightActionType> getFightActions() { return fightActions; } public Actions<MoveActionType> getMoveActions() { return moveActions; } public FightActionType getNextFightAction() { int index; index = generatRandomIndex(fightActions.size()); return fightActions.get(index); } public MoveActionType getNextMoveAction() { int index; index = generatRandomIndex(moveActions.size()); return moveActions.get(index); } }
[ "vlad.lep@gmail.com@e25deb68-5119-325c-d63b-03bbf1c8524c" ]
vlad.lep@gmail.com@e25deb68-5119-325c-d63b-03bbf1c8524c
bbf979fff84b54c2207d6b05f242980271fb647d
68296d704f28ab7f99d06a432b6a9900b246f290
/Task_5/src/main/java/mozzherin/QueueStackException.java
b81286f72bb64fa09a949553ceec4a0fbb54884b
[]
no_license
SuperArt3000/JavaSchool2021
b47a6c59278dd960ddbb78e4fcc66f0b3326ca53
a1c1246043512d1bcb915f570773613b49b098fa
refs/heads/main
2023-05-14T15:12:53.657897
2021-06-08T04:50:54
2021-06-08T04:50:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
695
java
package mozzherin; import java.util.Objects; public class QueueStackException extends Exception{ private ErrorCode exceptionCode; public QueueStackException(ErrorCode exceptionCode) { this.exceptionCode = exceptionCode; } public ErrorCode getErrorCode() { return this.exceptionCode; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QueueStackException that = (QueueStackException) o; return exceptionCode == that.exceptionCode; } @Override public int hashCode() { return Objects.hash(exceptionCode); } }
[ "alex_m1991@mail.ru" ]
alex_m1991@mail.ru
e65dc3671a94d05eaa9bb67652bdb3d17ff07861
83813487a644037edc7ae2c1b48c13adad28aa1d
/src/com/scyb/aisbroadcast/webservice/dao/IWebserviceDao.java
4b577e6b1c91679cc7b7d65f9b60a8aa60e3a894
[]
no_license
cheunyu/ysjais
2e0832edb16d5d679a29fee5d1bdd481bdc9f607
754cfe55844d2a074b1d7cf4d64ddd4df46d35ca
refs/heads/master
2021-01-19T06:50:54.927060
2017-12-19T03:24:05
2017-12-19T03:24:05
95,674,748
0
0
null
null
null
null
UTF-8
Java
false
false
379
java
package com.scyb.aisbroadcast.webservice.dao; import com.scyb.aisbroadcast.common.dao.IBaseDao; import com.scyb.aisbroadcast.webservice.po.WebserviceLogPo; /** * Created by foo on 2017/6/30. */ public interface IWebserviceDao extends IBaseDao{ /** * 存储Webservice记录到日记表 * */ public boolean saveWebserviceLog(WebserviceLogPo WebservicePo); }
[ "cheunyufoo@gmail.com" ]
cheunyufoo@gmail.com
dd4f785c5360f02dce4fae39bc4b49488d417796
fe60e7881ddf86dec4f693e179f412c0f95d33c4
/src/main/java/com/progetto/projectmanagement/service/notification/NotificationService.java
73268d6e399ab30849b561fe874e987c3d93fda9
[]
no_license
Reza-Radan/pjm
249358234080301c1c39e6723d93db9c09c5d2a8
5ad613a0a489cb71771c4ecb87f426771e725aec
refs/heads/master
2020-09-17T02:02:23.432648
2019-11-26T09:46:14
2019-11-26T09:46:14
223,955,239
0
0
null
null
null
null
UTF-8
Java
false
false
130
java
package com.progetto.projectmanagement.service.notification; public class NotificationService implements INotificationService { }
[ "m.radan@dabacenter.ir" ]
m.radan@dabacenter.ir
8c6d58aceabb59b0af2d0d2980a2f8f760c74767
be8306e7d48abde5025d59f6438b02b4236acebe
/dbtools_1.0/dbtools_app/src/com/dbm/client/ui/menu/Lgn01Dialog.java
c97d8d8f347f0a9f5c07dc3ef7a0e557809453a6
[]
no_license
jiangjs2008/dbtools
6c9f8d7834982dbf5ed73c635565dc111ab08a06
ae2960feea2faa1fd6a3985bea6d8d50d443a16d
refs/heads/master
2021-01-23T22:39:33.045727
2015-02-12T10:10:09
2015-02-12T10:10:09
30,734,162
0
0
null
null
null
null
UTF-8
Java
false
false
7,146
java
package com.dbm.client.ui.menu; import java.awt.BorderLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.List; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.JTree; import com.dbm.client.action.AbstractActionListener; import com.dbm.client.db.DbClient4HttpWrapperImpl; import com.dbm.client.db.DbClient4TcpWrapperImpl; import com.dbm.client.ui.AppUIAdapter; import com.dbm.client.ui.Session; import com.dbm.client.ui.help.Msg01Dialog; import com.dbm.client.ui.tbllist.ObjectsTreeModel; import com.dbm.common.db.DbClient; import com.dbm.common.db.DbClientFactory; import com.dbm.common.property.ConnBean; import com.dbm.common.property.FavrBean; import com.dbm.common.property.PropUtil; import com.dbm.common.util.SecuUtil; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ /** * [name]<br> * 数据库登陆画面<br><br> * [function]<br> * 数据库登陆<br><br> * [history]<br> * 2013/05/10 ver1.0 JiangJusheng<br> */ public class Lgn01Dialog extends javax.swing.JDialog { /** * serialVersionUID */ private static final long serialVersionUID = 1L; private JTextField jTextField1; private JTextField jTextField2; private JTextField jTextField3; private JPasswordField jTextField4; /** * 缺省构造函数 */ public Lgn01Dialog() { super(); initGUI(); setDbInfo(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { DbClient dbClient = Session.getDbClient(); if (dbClient != null) { dbClient.close(); } } }); } /** * 创建画面 */ private void initGUI() { JPanel jPanel1 = new JPanel(); getContentPane().add(jPanel1, BorderLayout.CENTER); jPanel1.setLayout(null); JButton jButton1 = new JButton(); jPanel1.add(jButton1); jButton1.setText("Cancel"); jButton1.setBounds(100, 200, 85, 30); jButton1.addActionListener(new AbstractActionListener() { @Override protected void doActionPerformed(ActionEvent e) { DbClient dbClient = Session.getDbClient(); if (dbClient != null) { dbClient.close(); } setVisible(false); } }); JButton jBtnConnect = new JButton(); jPanel1.add(jBtnConnect); jBtnConnect.setText("Connect"); jBtnConnect.setBounds(320, 200, 85, 30); jBtnConnect.addActionListener(new ConnActionListener()); JLabel jLabel1 = new JLabel(); jPanel1.add(jLabel1); jLabel1.setText("Alias"); jLabel1.setBounds(20, 20, 70, 20); JLabel jLabel2 = new JLabel(); jPanel1.add(jLabel2); jLabel2.setText("Db Url"); jLabel2.setBounds(20, 60, 70, 20); JLabel jLabel3 = new JLabel(); jPanel1.add(jLabel3); jLabel3.setText("User Name"); jLabel3.setBounds(20, 100, 70, 20); JLabel jLabel4 = new JLabel(); jPanel1.add(jLabel4); jLabel4.setText("Password"); jLabel4.setBounds(20, 140, 70, 20); jTextField1 = new JTextField(); jPanel1.add(jTextField1); jTextField1.setBounds(100, 20, 300, 25); jTextField2 = new JTextField(); jPanel1.add(jTextField2); jTextField2.setBounds(100, 60, 470, 25); jTextField3 = new JTextField(); jPanel1.add(jTextField3); jTextField3.setBounds(100, 100, 150, 25); jTextField4 = new JPasswordField(); jPanel1.add(jTextField4); jTextField4.setBounds(100, 140, 150, 25); setSize(600, 300); setLocationRelativeTo(null); setModal(true); } /** * 在登陆画面显示数据库连接信息 */ private void setDbInfo() { FavrBean favrInfo = Session.getCurrFavrInfo(); if (favrInfo != null) { // 如果是从点击快捷方式而来 jTextField1.setText(favrInfo.name); jTextField2.setText(favrInfo.url); jTextField3.setText(SecuUtil.decryptBASE64(favrInfo.user)); jTextField4.setText(SecuUtil.decryptBASE64(favrInfo.password)); } else { ConnBean connInfo = Session.getCurrConnInfo(); jTextField1.setText(connInfo.name); jTextField2.setText(connInfo.sampleUrl); jTextField3.setText(""); jTextField4.setText(""); } } /** * 登陆数据库事件监听器 */ private class ConnActionListener extends AbstractActionListener { @Override protected void doActionPerformed(ActionEvent e) { if (Session.getDbClient() != null) { // 已存在数据库连接 return; } // 数据库URL String item2 = jTextField2.getText(); // 用户名 String item3 = jTextField3.getText(); // 密码 String item4 = new String(jTextField4.getPassword()); // 将用户的数据库信息保存到缓存 FavrBean favrInfo = Session.getCurrFavrInfo(); ConnBean connInfo = null; if (favrInfo != null) { // 如果是从点击快捷方式而来 // 用户可能会修改连接信息 connInfo = PropUtil.getDbConnInfo(favrInfo.driverId); } else { // 直接选择数据库方式 // 用户可能会修改连接信息 connInfo = Session.getCurrConnInfo(); } String actionCls = connInfo.action; if (favrInfo.wrapperUrl != null) { if (favrInfo.wrapperUrl.startsWith("http")) { actionCls = DbClient4HttpWrapperImpl.class.getName(); } else if (favrInfo.wrapperUrl.startsWith("tcpip")) { actionCls = DbClient4TcpWrapperImpl.class.getName(); } } DbClient dbClient = DbClientFactory.createDbClient(actionCls); Session.setDbClient(dbClient); // if (dbClient instanceof DbClient4SQLiteImpl) { // // TODO --特殊情况:连接手机上的sqlite时需要再修正一次连接URL // AppUIAdapter.setUIObj(AppUIAdapter.DbUrlTxtField, jTextField2); // } String[] connArgs = null; if (favrInfo.wrapperUrl == null) { connArgs = new String[] { connInfo.driver, item2, item3, item4 }; } else { connArgs = new String[] { connInfo.driver, item2, item3, item4, favrInfo.wrapperUrl, Integer.toString(connInfo.driverid) }; } if (!dbClient.start(connArgs)) { Msg01Dialog.showMsgDialog(40005); return; } dbClient.setPageSize(Session.PageDataLimit); // 显示数据库内容:表、视图等等 List<String> objList = dbClient.getCatalogList(); if (objList != null && objList.size() > 0) { JTree jTree1 = (JTree) AppUIAdapter.getUIObj(AppUIAdapter.TableTreeUIObj); ObjectsTreeModel treeModel = (ObjectsTreeModel) jTree1.getModel(); treeModel.loadList(objList); treeModel.reload(); // 关闭登陆画面 setVisible(false); } ((Frame) AppUIAdapter.getUIObj(AppUIAdapter.AppMainGUI)).setTitle(Session.APP_TITLE + " -- " + item2); } } }
[ "jiangjs2009@5148ee1e-757b-46d0-8d9b-0dc10d80715d" ]
jiangjs2009@5148ee1e-757b-46d0-8d9b-0dc10d80715d
d47b987f44125e8f1c210a5f9db3219df235bdf7
3fd0d23e6b459b1cdb8b9c0c5c5cd46a3b0302e9
/common/src/main/java/com/roger/grab/base/common/framework/MessageException.java
0391310e94f8755b6d5f5325cf239b29771a7ffd
[]
no_license
Rogerlxp/grab
f21d182c35eb6956bc16f91f6a8510db5e6dd41e
3f9a9918d0b4538dffcff78b6c673168f6897c69
refs/heads/master
2020-03-30T00:55:17.594070
2018-11-27T06:26:30
2018-11-27T06:26:30
150,550,371
0
1
null
null
null
null
UTF-8
Java
false
false
192
java
package com.roger.grab.base.common.framework; public class MessageException extends RuntimeException { /** * */ private static final long serialVersionUID = -7268467705294209641L; }
[ "xiaoping@meizu.com" ]
xiaoping@meizu.com
04b1254fa031597a795ccb81f584784110e7475a
5ca37c9faccc82d9d0b83ecd1dac176d8cfa7261
/voice/src/main/java/com/fotile/voice/socket/bean/ResponseInfo.java
acf7173b3d0eca6a3a7c3295b427115af6043e1d
[]
no_license
yhx810971230/x1.i
9c04a80a57fa7148e74d28b22917800db203ff70
775531627a54c21f768c616a6ac708e25c98200f
refs/heads/master
2022-04-23T00:37:31.330912
2020-04-17T09:47:12
2020-04-17T09:47:12
256,391,924
0
1
null
null
null
null
UTF-8
Java
false
false
2,291
java
/* * ************************************************************ * 文件:ResponseInfo.java 模块:voice 项目:X1.I * 作者:coiliaspp * 杭州方太智能科技有限公司 https://www.fotile.com * Copyright (c) 2019 * ************************************************************ */ package com.fotile.voice.socket.bean; public class ResponseInfo { private String type; private String ap_connected; private int home_id; private String ssid; private String key; private String session; private int auth_mode; public ResponseInfo() {} public ResponseInfo(String type, String ap_connected, int home_id, String ssid, String key, int auth_mode, String session) { this.type = type; this.ap_connected = ap_connected; this.home_id = home_id; this.ssid = ssid; this.key = key; this.session = session; this.auth_mode = auth_mode; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getAp_connected() { return ap_connected; } public void setAp_connected(String ap_connected) { this.ap_connected = ap_connected; } public int getHome_id() { return home_id; } public void setHome_id(int home_id) { this.home_id = home_id; } public String getSsid() { return ssid; } public void setSsid(String ssid) { this.ssid = ssid; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getSession() { return session; } public void setSession(String session) { this.session = session; } public int getAuth_mode() { return auth_mode; } public void setAuth_mode(int auth_mode) { this.auth_mode = auth_mode; } @Override public String toString() { return "ResponseInfo{" + "type='" + type + '\'' + ", ap_connected='" + ap_connected + '\'' + ", home_id=" + home_id + ", ssid='" + ssid + '\'' + ", key='" + key + '\'' + ", session='" + session + '\'' + ", auth_mode=" + auth_mode + '}'; } }
[ "810971230@qq.com" ]
810971230@qq.com
01870c57dc23f852b4425287ba00730018d559bd
84949d2f56005cebdf3b039036d9e043285ab2ac
/BCSM17/src/page/Loginpage.java
caa161d37e9f924053e75f2775d77a67214ddd83
[]
no_license
Manasa411/BCSM17
907a63ccf2dbeeb3996f60c25f66e02c805a9b0c
4d4ea0fd81145868ff38efb78d9867d0c3c4011c
refs/heads/master
2021-04-15T04:09:41.224742
2018-03-24T04:20:42
2018-03-24T04:20:42
126,484,378
0
0
null
null
null
null
UTF-8
Java
false
false
1,311
java
package page; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Reporter; @SuppressWarnings("unused") public class Loginpage { @FindBy(id="username") private WebElement unTB; @FindBy(name="pwd") private WebElement pwTB; @FindBy(xpath="//div[.= 'Login ']") private WebElement loginBTN; //@FindBy(xpath="//span[contains(.,'invalid')]") //private WebElement errmsg; public Loginpage(WebDriver driver) { PageFactory.initElements(driver, this); } public void setusername(String un) { unTB.sendKeys(un); } public void setpassword(String pw) { pwTB.sendKeys(pw); } public void clickloginBTN() { loginBTN.click(); } /*public void verifyErrmsgIsDisplayed(WebDriver driver) { WebDriverWait wait=new WebDriverWait(driver,10); try { wait.until(ExpectedConditions.visibilityOf(errmsg)); Reporter.log("pass: err msg is displayed", true); } catch(Exception e) { Reporter.log("fail:err msg is not displayed",true); } }*/ }
[ "37699272+Manasa411@users.noreply.github.com" ]
37699272+Manasa411@users.noreply.github.com
fba5fea56561dab23a9caa2a4286b07f3b9fffac
8602aec34df53a057bccc2f9012dca93e358ad14
/spring-learning/src/main/java/com/example/annotation/SelfService.java
83bf291ed226665abc1c348282d55dbc69e35b08
[]
no_license
linjia1993912/learning
c19da340103975df9b53b0d4467cb0af4d89b381
e57dc491c5331ed483d7f154cc15de0a78f6cb55
refs/heads/master
2023-05-04T16:00:28.292720
2021-05-20T07:38:54
2021-05-20T07:38:54
287,243,331
0
0
null
null
null
null
UTF-8
Java
false
false
424
java
package com.example.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @Description:自定义注解 service 注入bean容器 * 模拟@Service * @Author: linJia * @Date: 2020/8/18 14:59 */ @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface SelfService { }
[ "57213312+linjia1993912@users.noreply.github.com" ]
57213312+linjia1993912@users.noreply.github.com
e85c1256d8cfffd381e60ad7b615f0a87e847a42
a8946b8b8451f6aa793ade8be017d7eca341c122
/src/drug/service/DrugService.java
c2b80b90dba6f322b92013287c9ee5bf1621cb7c
[]
no_license
2223408299/javaweb-
f1e960f6853f5d279bd2311e242a69e22434a823
b67e3c916cb38af70e52701599bb3b4f0634f84f
refs/heads/master
2023-07-12T20:36:40.816051
2021-08-22T08:16:59
2021-08-22T08:16:59
398,747,827
1
0
null
null
null
null
UTF-8
Java
false
false
4,261
java
package drug.service; import drug.dao.DrugDao; import drug.domain.Drug; import pager.PageBean; import java.sql.SQLException; import java.util.List; public class DrugService { private DrugDao drugDao = new DrugDao(); /** * 按销量查询热门商品 * @return */ public List<Drug> findHotDrug2() { try { return drugDao.findHotDrug2(); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 按销量查询热门商品 * @return */ public List<Drug> findHotDrug() { try { return drugDao.findHotDrug(); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 批量上下架功能 * @param drugIds */ public void batchOpdrug(String drugIds,int state) { try { drugDao.batchOpdrug(drugIds,state); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 批量删除功能 * @param drugIds */ public void batchDelete(String drugIds) { try { drugDao.batchDelete(drugIds); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 加载药品 * @param drugid * @return */ public Drug load(String drugid) { try { return drugDao.findByDrugid(drugid); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 按分类查 * @param cid * @param pc * @return */ public PageBean<Drug> findByCategory(String cid, int pc,String condition3) { try { return drugDao.findByCategory(cid, pc,condition3); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 按药名模糊查询 * @param drugName * @param pc * @return */ public PageBean<Drug> findBydrugName(String drugName, int pc,String condition3) { try { return drugDao.findBydrugName(drugName, pc,condition3); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 降序 * @param condition * @param pc * @return */ public PageBean<Drug> findBydrugDesc(String condition, String condition2,int pc, String condition3) { try { return drugDao.findBydrugDesc(condition,condition2, pc,condition3); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 升序 * @param condition * @param pc * @return */ public PageBean<Drug> findByAsc(String condition, String condition2,int pc, String condition3) { try { return drugDao.findByAsc(condition,condition2, pc,condition3); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 多条件组合查询 * @param criteria * @param pc * @return */ public PageBean<Drug> findByCombination(Drug criteria, int pc,String condition, String condition3) { try { return drugDao.findByCombination(criteria, pc,condition,condition3); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 查找所有药品 * @param pc * @return */ public PageBean<Drug> findAllDrug(int pc,String condition3) { try { return drugDao.findAllDrug(pc,condition3); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 删除药品 * @param drugId */ public void delete(String drugId) { try { drugDao.delete(drugId); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 上下架药品 */ public void updateState(String drugId ,String condition3) { try { drugDao.updateState(drugId,condition3); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 修改药品 * @param drug */ public void edit(Drug drug) { try { drugDao.edit(drug); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 返回当前分类下药品个数 * @param cid * @return */ public int findBookCountByCategory(String cid) { try { return drugDao.findDrugCountByCategory(cid); } catch(SQLException e) { throw new RuntimeException(e); } } /** * 添加药品 * @param drug */ public void add(Drug drug) { try { drugDao.add(drug); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 更换药品图片 * @param drug */ public void upPicture(Drug drug) { try { drugDao.upPicture(drug); } catch (SQLException e) { throw new RuntimeException(e); } } }
[ "2223408299@qq.com" ]
2223408299@qq.com
5304ac2177c7b8686437b523ba2b678167713a1b
e196779c3862f0ce675731015f296d64ceaccb4d
/sleuth-server/src/main/java/com/test/sleuth/server/controller/TestController.java
60c17b953d4b4a95957a772386f00c4ca6183ec2
[]
no_license
rlopezgiron/sleuth
ffb3bc33e6f57e89cdc3cb998c10ace8c07bc358
0531d33e5def380a0e272aa1bb304f4385ddf8be
refs/heads/master
2021-05-18T18:40:21.622465
2020-03-30T16:31:38
2020-03-30T16:31:38
251,363,626
0
0
null
null
null
null
UTF-8
Java
false
false
615
java
package com.test.sleuth.server.controller; import java.util.List; import org.springframework.http.ResponseEntity; import com.test.sleuth.server.model.TestItem; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; @Api(tags = {"Resource Public Test"}) @SwaggerDefinition(tags = { @Tag(name = "Resource Public Test", description = "Public: rest controller") }) public interface TestController { @ApiOperation(value = "Public: Get all test items") ResponseEntity<List<TestItem>> findAll(); }
[ "roberto.lopez.giron@accenture.com" ]
roberto.lopez.giron@accenture.com
a84351e97e5a41b6e9b26d0651d992bd242ca506
5d49ae6a19be6c7b6cbd3cde8b9fef1c290441e1
/src/main/java/br/com/magna/buymedicine/model/Comprador.java
f11e7e4e74484a67765419537a8bd6ed0cd1870a
[]
no_license
KeviinSouza/Buy-medicine
6aa6fce0361e2b746fe0dee9e6dbc4d1e5b8255b
cb087b5aa874ada883666f56cfb4eb6f2735ae81
refs/heads/master
2023-04-29T06:31:39.531477
2021-05-26T00:54:17
2021-05-26T00:54:17
366,217,746
0
0
null
null
null
null
UTF-8
Java
false
false
657
java
package br.com.magna.buymedicine.model; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "comprador") public class Comprador { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String nome; @OneToMany(mappedBy = "comprador") private List<Unidade> unidade; public Long getId() { return id; } public String getNome() { return nome; } public List<Unidade> getUnidade() { return unidade; } }
[ "kevinsou113@gmail.com" ]
kevinsou113@gmail.com
54ebcee0504ddd00429963c8fc383dbcee122ce8
d97ba7b8872f1d1f51b8f1dc07597d7c81a83e02
/src/main/generated/org/tridas/schema/NormalTridasDatingType.java
8adfb4f813301b335e5b821c06ab5fa1bdcad178
[]
no_license
petebrew/tridasjlib
b316d30fb9741b4ad8158c7201905606bda6a8cb
2dbab46a83dfa15d6a5b789b7db36af67940c3cf
refs/heads/master
2020-12-24T14:53:03.804176
2020-08-19T20:25:51
2020-08-19T20:25:51
40,012,856
0
0
null
null
null
null
UTF-8
Java
false
false
1,491
java
package org.tridas.schema; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for normalTridasDatingType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="normalTridasDatingType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="absolute"/> * &lt;enumeration value="dated with uncertainty"/> * &lt;enumeration value="relative"/> * &lt;enumeration value="radiocarbon"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "normalTridasDatingType") @XmlEnum public enum NormalTridasDatingType { @XmlEnumValue("absolute") ABSOLUTE("absolute"), @XmlEnumValue("dated with uncertainty") DATED_WITH_UNCERTAINTY("dated with uncertainty"), @XmlEnumValue("relative") RELATIVE("relative"), @XmlEnumValue("radiocarbon") RADIOCARBON("radiocarbon"); private final String value; NormalTridasDatingType(String v) { value = v; } public String value() { return value; } public static NormalTridasDatingType fromValue(String v) { for (NormalTridasDatingType c: NormalTridasDatingType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
[ "p.brewer@ltrr.arizona.edu" ]
p.brewer@ltrr.arizona.edu
2a68198433d8c27acd3b5dbda26bdfd6f36ca36b
1d8f9045942de8ee57d72e1d35ee954413fbae25
/docroot/WEB-INF/src/vn/gt/tichhop/report/PermissionForTransit/PermissionForTransitModel.java
f2e60993a5005bfa68945a73e9d0323614f6eda1
[]
no_license
longdm10/TichHopGiaoThong-portlet
0a3dab1a876d8c2394ea59fcc810ec5561a5a3d0
e97d7663ca0ef4da19e9792c78fefd87104d2b54
refs/heads/master
2021-01-10T07:38:08.114614
2016-04-01T07:39:08
2016-04-01T07:39:08
54,985,263
0
0
null
null
null
null
UTF-8
Java
false
false
641
java
package vn.gt.tichhop.report.PermissionForTransit; import vn.gt.dao.noticeandmessage.model.impl.IssuePermissionForTransitImpl; /* Report GIAY PHEP QUA CANH -- MAU SO 15 */ public class PermissionForTransitModel extends IssuePermissionForTransitImpl { private String maritimeNameVN; private String maritimeName; public String getMaritimeNameVN() { return maritimeNameVN; } public void setMaritimeNameVN(String maritimeNameVN) { this.maritimeNameVN = maritimeNameVN; } public String getMaritimeName() { return maritimeName; } public void setMaritimeName(String maritimeName) { this.maritimeName = maritimeName; } }
[ "longdm10@gmail.com" ]
longdm10@gmail.com
52968d87792f8de965b06b9aa08aa2dfc89a97ac
039ad35e98df8370b0291bcf8424ef604018736f
/DecoratorPattern/src/com/guru/Main/Main.java
8a68e02e1944fb0aee2778c15b08210d5fe89c70
[]
no_license
Gurunath-lohar/guru-java-projects
2f50d44a7e4032706bfba5d885673b967cb238c5
51b3a7d090817848dcb46550135bf99ec3de2005
refs/heads/master
2020-06-04T06:05:28.857420
2015-10-29T14:37:58
2015-10-29T14:37:58
15,857,954
0
0
null
2015-10-29T14:37:59
2014-01-13T04:31:06
null
UTF-8
Java
false
false
971
java
package com.guru.Main; import com.guru.components.AbstractComponent; import com.guru.components.PlainCoffee; import com.guru.components.PlainTea; import com.guru.decorators.AbstractDecorator; import com.guru.decorators.BrazilCoffee; import com.guru.decorators.CongoTea; public class Main { public static void main(String [] args) { AbstractComponent component1 = new PlainCoffee(); AbstractComponent component2 = new PlainTea(); AbstractDecorator splCoffee = new BrazilCoffee(component1); AbstractDecorator splTea = new CongoTea(component2); System.out.println("Description :"+component1.getDescription()+" Cost :"+component1.getCost()); System.out.println("Description :"+splCoffee.getDescription()+" Cost :"+splCoffee.getCost()); System.out.println("Description :"+component2.getDescription()+" Cost :"+component2.getCost()); System.out.println("Description :"+splTea.getDescription()+" Cost :"+splTea.getCost()); } }
[ "gurunath.lohar@gmail.com" ]
gurunath.lohar@gmail.com
346b7e24b6244f7bd07c429f432e14c896ed1505
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/LANG-36b-1-24-SPEA2-WeightedSum:TestLen:CallDiversity/org/apache/commons/lang3/math/NumberUtils_ESTest.java
bc1965de55a1ec81d7fd5bc249379e9350fb5946
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
950
java
/* * This file was automatically generated by EvoSuite * Mon Apr 06 14:36:49 UTC 2020 */ package org.apache.commons.lang3.math; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import org.apache.commons.lang3.math.NumberUtils; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true) public class NumberUtils_ESTest extends NumberUtils_ESTest_scaffolding { @Test(timeout = 4000) public void test0() throws Throwable { try { NumberUtils.createNumber("pc(W]"); fail("Expecting exception: NumberFormatException"); } catch(NumberFormatException e) { // // pc(W] is not a valid number. // verifyException("org.apache.commons.lang3.math.NumberUtils", e); } } }
[ "pouria.derakhshanfar@gmail.com" ]
pouria.derakhshanfar@gmail.com
efd2f5f2e3061c3847cd381491d0f7df397eb754
ff0ef1f13dd44ae456c6fdf6ab769f344fae5946
/src/igraf/moduloJanelasAuxiliares/visao/integral/JanelaIntegral.java
a43d99ae2849ab2bb490b1de8bf26134d58d0d47
[]
no_license
LInE-IME-USP/igraf_java
8e11fedd1fa546e39149197ae4a929a7f862faa9
081d8690d73989225eade44faa1f037cb1bfbfb2
refs/heads/master
2021-01-10T19:41:07.302707
2014-07-16T17:55:25
2014-07-16T17:55:25
null
0
0
null
null
null
null
ISO-8859-1
Java
false
false
3,965
java
/* * iGraf - Interactive Graphics on the Internet: http://www.matematica.br/igraf * * Free interactive solutions to teach and learn * * iMath Project: http://www.matematica.br * LInE http://line.ime.usp.br * * @author RP, LOB * * @version intiatl in 04/07/2006 * * @description * * @see * * @credits * This source is free and provided by iMath Project (University of São Paulo - Brazil). In order to contribute, please * contact the iMath coordinator Leônidas O. Brandão. * * O código fonte deste programa é livre e desenvolvido pelo projeto iMática (Universidade de São Paulo). Para contribuir, * por favor contate o coordenador do projeto iMatica, professor Leônidas O. Brandão. * */ package igraf.moduloJanelasAuxiliares.visao.integral; import java.awt.Choice; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Panel; import java.awt.TextField; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import difusor.i18N.LanguageUpdatable; import igraf.basico.io.ResourceReader; import igraf.basico.util.Utilitarios; import igraf.moduloJanelasAuxiliares.controle.JanelaIntegralController; import igraf.moduloSuperior.controle.entrada.Analisa; public class JanelaIntegral extends Frame implements LanguageUpdatable { // This class has a reference to all functions in constructions // JanelaIntegralController.java: Vector listaDesenho, listaFuncao private JanelaIntegralController janelaIntegralController; private PainelIntegral painelIntegral; private PainelOpcoesIntegracao painelOpcoesIntegracao; private Panel painelAuxiliar; private double delta = 0.02, from = 0, to = 1; private final int ESQUERDA = 37, DIREITA = 39, BAIXO = 40, CIMA = 38; public JanelaIntegral (JanelaIntegralController janelaIntegralController) { super(ResourceReader.msg("janIntegTit")); this.janelaIntegralController = janelaIntegralController; painelIntegral = new PainelIntegral(janelaIntegralController); painelOpcoesIntegracao = new PainelOpcoesIntegracao(painelIntegral); setLayout(new GridLayout(1,2)); painelAuxiliar = new Panel(new GridLayout(1,2)) { public Dimension getPreferredSize() { return new Dimension(396, 200); } }; painelAuxiliar.add(painelIntegral); painelAuxiliar.add(painelOpcoesIntegracao); add(painelAuxiliar); pack(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent arg0) { setVisible(false); dispose(); } }); setVisible(true); } public Choice getChoiceUm () { return painelIntegral.cp1.getChoice(); } public Choice getChoiceDois () { return painelIntegral.cp2.getChoice(); } // Ouvidor para as setas direcionais dos TextFields do painel integral public void keyPressed (KeyEvent e) { int keyCode = e.getKeyCode(); TextField tf = (TextField)e.getSource(); double value = getValue(tf); if (keyCode == ESQUERDA || keyCode == BAIXO) tf.setText(Utilitarios.precisao(value -= delta)); if (keyCode == DIREITA || keyCode == CIMA) tf.setText(Utilitarios.precisao(value += delta)); if (tf.getName().equals("inf")) from = value; if (tf.getName().equals("sup")) to = value; } public double getValue (TextField tf) { String s = tf.getText(); s = Analisa.verificaConstante(s); try { return new Double(s).doubleValue(); } catch (NumberFormatException e) { return 0; } } public double getFrom () { return from; } public double getTo () { return to; } public void keyReleased (KeyEvent e) { } public void keyTyped (KeyEvent e) { } public void updateLabels () { setTitle(ResourceReader.msg("janIntegTit")); painelIntegral.updateLabels(); painelOpcoesIntegracao.updateLabels(); } }
[ "leo@ime.usp.br" ]
leo@ime.usp.br
326ed3bf7f8ba9261b15644a3903f0ba96042cdb
eb16c122151770dbc534c12056f68d775cd9b7a8
/1688/11FileReading/11FileReading/gen/com/example/applicationflow/BuildConfig.java
3d899ea25fdb8351471e50cc0c207b693364999d
[]
no_license
mikechen88/java
648fca3a432c61208a88250d9c4bdfcb5d8c1507
f065826d997e9d659193973ad3e64041f36aaa4b
refs/heads/master
2021-01-19T22:29:29.047778
2013-10-19T16:55:47
2013-10-19T16:55:47
13,703,462
1
0
null
null
null
null
UTF-8
Java
false
false
169
java
/** Automatically generated file. DO NOT MODIFY */ package com.example.applicationflow; public final class BuildConfig { public final static boolean DEBUG = true; }
[ "feng16898@yahoo.com" ]
feng16898@yahoo.com
c61115a9a84b426f4a6c0a12b0ac6df55f0567e2
e1b9a89e73e0c20c336fcf6bdaac1a1a32f0565c
/project-1/src/main/java/com/revature/model/Role.java
4a5925ef04956c53bae4904e856c2f1b3edf49dc
[]
no_license
quincy-roman/project-1-ERS-roman-q
2be13ff6cb1f009b829c86bc8fec53cbc6387509
a1ffa7f6a213fef740e2931f195c2993c332c3ca
refs/heads/main
2023-01-24T11:11:31.313075
2020-12-02T22:09:37
2020-12-02T22:09:37
318,002,987
0
0
null
null
null
null
UTF-8
Java
false
false
1,033
java
package com.revature.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name="Roles") public class Role { @Id @Column(name="role_id") @GeneratedValue(strategy=GenerationType.AUTO) private int roleId; //TODO this might need some fixing. @Column(name="role_name", unique=true, nullable=false) private String roleName; @OneToOne(mappedBy="role", fetch=FetchType.LAZY) private Users user; public Role() {} public Role(int roleId, String roleName) { super(); this.roleId = roleId; this.roleName = roleName; } public int getRoleId() { return roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } }
[ "qjroman@gmail.com" ]
qjroman@gmail.com
e7ba75f985c6a8dcf2179e259dde38135dc254e1
1426ad90429756b79de8dc788110be110f0431b6
/src/main/java/engine/engineAi.java
22a218106e870cde70aaaaa70d5b07745f9e6819
[]
no_license
noNhead/matches20
36f94bba4ed8b7a5d309d6aa29fc46718ddf4952
e6f361a047eff430e32926b1e21cd56c8b3b8c65
refs/heads/master
2023-04-27T10:38:59.284701
2020-03-11T11:24:23
2020-03-11T11:24:23
245,875,887
0
0
null
2023-04-17T19:36:43
2020-03-08T19:36:05
Java
UTF-8
Java
false
false
339
java
package engine; public interface EngineAi { /**поиск нужного хода * * @param numberOfMatches количество спичек на сейчас * @return возвращает количество спичек, которое нужно взять */ int findSolution(int numberOfMatches); }
[ "sun495fun@gmail.com" ]
sun495fun@gmail.com
2cb206710bc0497068a0d833988acb3d6291abba
fa5667a259ec2ffc704e7746b69273563ce8ef53
/app/src/main/java/zxing/QrCodeUtil.java
c7a6970308feabd67f6a4a610916338353df812d
[]
no_license
lzq1083520149/saoyisaodemo
1d74acefe1f192e92afdc9e39c49c47ac20945e3
5789e5a05447dd73d7251dd7d00486bf9490782a
refs/heads/master
2021-01-15T14:58:38.134296
2016-09-20T10:02:58
2016-09-20T10:02:59
68,698,707
2
0
null
null
null
null
UTF-8
Java
false
false
2,021
java
package zxing; import android.graphics.Bitmap; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import java.util.Hashtable; /** * Created by Administrator on 2016/7/14. */ public class QrCodeUtil { /** * 生成二维码图片 * @param content * @param width * @param height * @return */ public static Bitmap generateQrCode(String content, int width, int height) { try { //判断content合法性 if (content == null || "".equals(content) || content.length() < 1) { return null; } Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //图像数据转换,使用了矩阵转换 BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); int[] pixels = new int[width * height]; //下面这里按照二维码的算法,逐个生成二维码的图片, //两个for循环是图片横列扫描的结果 for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (bitMatrix.get(x, y)) { pixels[y * width + x] = 0xff000000; } else { pixels[y * width + x] = 0xffffffff; } } } //生成二维码图片的格式,使用ARGB_8888 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); //显示到一个ImageView上面 return bitmap; } catch (WriterException e) { e.printStackTrace(); } return null; } }
[ "1083520149@qq.com" ]
1083520149@qq.com
cbe248beb309e9e09101906059332aef123a7dcb
3d4a26fa06a1c2ed4cdad087ac689d0d4f002868
/workspace/jdbc/src/Calculator2/Calculator2.java
10565d56dab61628ba66250f37ab61064c0fce34
[]
no_license
jang4562/lesson
7d4c1e05cc3c39da184aca33d4e23148115f0b14
f206cda0a81134659604b0f47c1a42d7fba685d5
refs/heads/master
2020-04-14T10:37:06.342480
2019-02-22T03:42:51
2019-02-22T03:42:51
163,787,988
0
0
null
null
null
null
UHC
Java
false
false
16,224
java
package Calculator2; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JTextField; import java.awt.Font; import javax.swing.SwingConstants; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JProgressBar; public class Calculator2 { private JFrame frmCalculatordemo; private JTextField textDisplay; double firstNumber; // 각종 연산자 버튼을 눌렀을때 기존에 출력창에있는값을 저장하기위해 만든 숫자타입double(소수타입) 숫자변수 double secondNumber;// 각종 연산자 버튼을 누른후 새로 나오는 출력창에 값들을 저장하기위해 만든 숫자타입double(소수타입) 숫자변수 double result; // 결과물들을 저장할 숫자변수 String operations; // 각종 연산자들을 구분하기위한 변수 String answer; // 출력용 연산 결과인 result 값을 문자열로 변환 저장하는 변수(result가 소숫점 소수열이라서) /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Calculator2 window = new Calculator2(); window.frmCalculatordemo.setVisible(true); // 타이틀 이름조정하면 자동으로 추가됨 } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Calculator2() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frmCalculatordemo = new JFrame(); frmCalculatordemo.setResizable(false); frmCalculatordemo.setTitle("CalculatorDemo"); // 타이틀 이름조정 frmCalculatordemo.setBounds(100, 100, 290, 460); // 사이즈조정 300x460 으로 frmCalculatordemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmCalculatordemo.getContentPane().setLayout(null); // 레이아웃을 자유롭게 잡아주는 앱솔루트 레이아웃 textDisplay = new JTextField(); // 텍스트필드 생성자 textDisplay.setHorizontalAlignment(SwingConstants.RIGHT); textDisplay.setFont(new Font("Tahoma", Font.BOLD, 20)); // 텍스트필드에대한 텍스트 속성지정 textDisplay.setBounds(15, 10, 255, 50); // 레이아웃에대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(textDisplay); // 겟콘텐츠페인에 현재 텍스트필드를 추가 textDisplay.setColumns(10); // ~~~~~~~~~~~~ ROW 1 ~~~~~~~~~~~~~ 1행 JButton btnBackSpace = new JButton("BS"); // 백스페이스 버튼 생성 btnBackSpace.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String backspace = null; // 새로게 만들어질(마지막 자리수를 지운)문자열 // 지울 문자열의 길이가 0보다 클때만 발동할 if문 작성 if(textDisplay.getText().length() > 0){ // 기존에있는 스트링창을 새로 만들어줌(꼭만들필요는없고 있다는것을보여주기위함 그러나 편함 ex) textDisplay.getText() 일일이 넣어주긴 불편) StringBuilder strB = new StringBuilder(textDisplay.getText()); // 위에서 만든 스트링창에 위치를지정해지운다(deleteCharAt)어디를?(textDisplay.getText().length() - 1)이건 문자를 길이로바꾸어 지움 // deleteCharAt라는 메소드는 String에 없다 그렇기때문에 StringBuilder를 써준것 strB.deleteCharAt(textDisplay.getText().length() - 1); // strB가 StringBuilder로 지정되있기때문에 다시 문자열(toString)으로 바꿔준걸 backspace에 저장 backspace = strB.toString(); // 저장한 문자열(backspace)를 계산창(textDisplay)에 출력 textDisplay.setText(backspace); } } }); btnBackSpace.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btnBackSpace.setBounds(15, 80, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btnBackSpace); JButton btnClear = new JButton("C"); // 클리어 버튼 생성 btnClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Clear 의 경우 문자열(EnterNumber)를 출력하는경우라 초기화시켜주면되기때문에 "";있지만 // 간편하게만드는방법으로 textDisplay.setText(null 또는 "");을 쓴다. //String EnterNumber = ""; //textDisplay.setText(EnterNumber); textDisplay.setText(null); } }); btnClear.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btnClear.setBounds(80, 80, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btnClear); JButton btnRemainder = new JButton("%"); // 나누기(리마인더) 버튼 생성 btnRemainder.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 클래스를 만들며 지정한 firstNumber에 저장(계산창에 저장된 텍스트를 가져와서,parseDouble(숫자.소수로변환하는함수) parseInt도있다) firstNumber = Double.parseDouble(textDisplay.getText()); // 연산자를 누르고 firstNumber를 저장했기떄문에 계산창을 초기화 textDisplay.setText(null); // 나누기했다는 계산을하기위해 문자열에 % 을 저장 operations = "%"; } }); btnRemainder.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btnRemainder.setBounds(145, 80, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btnRemainder); JButton btnPlus = new JButton("+"); // 플러스 버튼 생성 btnPlus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { firstNumber = Double.parseDouble(textDisplay.getText()); textDisplay.setText(null); operations = "+"; } }); btnPlus.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btnPlus.setBounds(210, 80, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btnPlus); // ~~~~~~~~~~~~ ROW 2 ~~~~~~~~~~~~~ 2행 JButton btn7 = new JButton("7"); // 버튼7 버튼 생성 // 액션리스너 (디자인에서 오른쪽마우스 액션 으로생성,또는 *더블클릭*으로 생성 btn7.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 디스플레이창에 이미 입력된 문자열(숫자)과 버튼의 텍스르를 결합 // 계산창(textDisplay)에 btn7(7버튼)의! 텍스트를 가져와 결합 // 가져온 문자열(위에 합친 문자들)을 다시 계산창(textDisplay)에 출력 String EnterNumber = textDisplay.getText() + btn7.getText(); textDisplay.setText(EnterNumber); } }); btn7.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btn7.setBounds(15, 145, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btn7); JButton btn8 = new JButton("8"); // 버튼8 버튼 생성 btn8.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EnterNumber = textDisplay.getText() + btn8.getText(); textDisplay.setText(EnterNumber); } }); btn8.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btn8.setBounds(80, 145, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btn8); JButton btn9 = new JButton("9"); // 버튼9 버튼 생성 btn9.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EnterNumber = textDisplay.getText() + btn9.getText(); textDisplay.setText(EnterNumber); } }); btn9.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btn9.setBounds(145, 145, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btn9); JButton btnMinus = new JButton("-"); // 마이너스 버튼 생성 btnMinus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { firstNumber = Double.parseDouble(textDisplay.getText()); textDisplay.setText(null); operations = "-"; } }); btnMinus.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btnMinus.setBounds(210, 145, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btnMinus); // ~~~~~~~~~~~~ ROW 3 ~~~~~~~~~~~~~ 3행 JButton btn4 = new JButton("4"); // 버튼4 버튼 생성 btn4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EnterNumber = textDisplay.getText() + btn4.getText(); textDisplay.setText(EnterNumber); } }); btn4.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btn4.setBounds(15, 210, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btn4); JButton btn5 = new JButton("5"); // 버튼5 버튼 생성 btn5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EnterNumber = textDisplay.getText() + btn5.getText(); textDisplay.setText(EnterNumber); } }); btn5.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btn5.setBounds(80, 210, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btn5); JButton btn6 = new JButton("6"); // 버튼6 버튼 생성 btn6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EnterNumber = textDisplay.getText() + btn6.getText(); textDisplay.setText(EnterNumber); } }); btn6.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btn6.setBounds(145, 210, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btn6); JButton btnMutiply = new JButton("*"); // 곱하기(멀티플) 버튼 생성 btnMutiply.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { firstNumber = Double.parseDouble(textDisplay.getText()); textDisplay.setText(null); operations = "*"; } }); btnMutiply.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btnMutiply.setBounds(210, 210, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btnMutiply); // ~~~~~~~~~~~~ ROW 4 ~~~~~~~~~~~~~ 4행 JButton btn1 = new JButton("1"); // 버튼1 버튼 생성 btn1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EnterNumber = textDisplay.getText() + btn1.getText(); textDisplay.setText(EnterNumber); } }); btn1.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btn1.setBounds(15, 275, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btn1); JButton btn2 = new JButton("2"); // 버튼2 버튼 생성 btn2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EnterNumber = textDisplay.getText() + btn2.getText(); textDisplay.setText(EnterNumber); } }); btn2.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btn2.setBounds(80, 275, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btn2); JButton btn3 = new JButton("3"); // 버튼3 버튼 생성 btn3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EnterNumber = textDisplay.getText() + btn3.getText(); textDisplay.setText(EnterNumber); } }); btn3.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btn3.setBounds(145, 275, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btn3); JButton btndivide = new JButton("/"); // 나누기 버튼 생성 btndivide.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { firstNumber = Double.parseDouble(textDisplay.getText()); textDisplay.setText(null); operations = "/"; } }); btndivide.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btndivide.setBounds(210, 275, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btndivide); // ~~~~~~~~~~~~ ROW 5 ~~~~~~~~~~~~~ 5행 JButton btn0 = new JButton("0"); // 버튼0 버튼 생성 btn0.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EnterNumber = textDisplay.getText() + btn0.getText(); textDisplay.setText(EnterNumber); } }); btn0.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btn0.setBounds(15, 340, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btn0); JButton btnDot = new JButton("."); // 소수점 버튼 생성 btnDot.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EnterNumber = textDisplay.getText() + btnDot.getText(); textDisplay.setText(EnterNumber); } }); btnDot.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btnDot.setBounds(80, 340, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btnDot); JButton btnConvert = new JButton("\u00B1"); // 뒤집기(-1*) 버튼 생성 btnConvert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double ops = Double.parseDouble(String.valueOf(textDisplay.getText())); //ops = -ops; 이것을 써도됨 ops = ops * (-1); // toString을 써도된다 textDisplay.setText(String.valueOf(ops)); } }); btnConvert.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btnConvert.setBounds(145, 340, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btnConvert); JButton btnEqual = new JButton("="); // 결과출력(=) 버튼 생성 btnEqual.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // String answer; 이미 전역변수를 넣어줫기때문에 지역변수로는 안넣어줘도된다 secondNumber = Double.parseDouble(textDisplay.getText()); // 값 연산자버튼에 넣어줫어줫던 operations들을 토대로 if문또는 스위치 문 을만들어 계산값을 정해줄수있다 if(operations == "+"){ result = firstNumber + secondNumber; answer = String.format("%.2f", result); textDisplay.setText(answer); }// end of if("+") else if(operations == "-"){ result = firstNumber - secondNumber; answer = String.format("%.2f", result); textDisplay.setText(answer); }// end of if("-") else if(operations == "*"){ result = firstNumber * secondNumber; answer = String.format("%.2f", result); textDisplay.setText(answer); }// end of if("*") else if(operations == "/"){ result = firstNumber / secondNumber; answer = String.format("%.2f", result); textDisplay.setText(answer); }// end of if("/") else if(operations == "%"){ result = firstNumber % secondNumber; answer = String.format("%.2f", result); textDisplay.setText(answer); }// end of if("+")% };// end of actionPerFormde() }); btnEqual.setFont(new Font("Tahoma", Font.BOLD, 18)); // 버튼에 속성 지정 btnEqual.setBounds(210, 340, 60, 60); // 레이아웃에 대한 위치 및 크기조정 frmCalculatordemo.getContentPane().add(btnEqual); } }
[ "hss0736@naver.com" ]
hss0736@naver.com
8f6b121b03019d08a71ae59d826345a8dc99a332
c6fbb371c4cd720bdff2a059e1e447a0b02e3ad8
/src/main/java/kr/ac/hansung/controller/OfferController.java
ccd446d6a85856b7c2bbbd60f2a9256745e97643
[]
no_license
jingyu94/SpringMVC-2
0468d41b89e95cc69b16093b8366f2766b8de0eb
f85615686c85dd7876f2bba1ca4443c8af6d009d
refs/heads/master
2020-04-11T18:42:26.415169
2018-12-16T14:46:08
2018-12-16T14:46:08
162,008,662
0
0
null
null
null
null
UTF-8
Java
false
false
1,382
java
package kr.ac.hansung.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import kr.ac.hansung.model.FinishClass; import kr.ac.hansung.model.Offer; import kr.ac.hansung.service.FinishClassService; import kr.ac.hansung.service.OfferService; @Controller public class OfferController { @Autowired private OfferService offerService; private FinishClassService finishClassService; @RequestMapping("/offers") public String showOffers(Model model) { List<Offer> offers = offerService.getCurrent(); model.addAttribute("offers", offers); return "offers"; } @RequestMapping("/createoffer") public String createOffer(Model model) { model.addAttribute("offer", new Offer()); return "createoffer"; } @RequestMapping("/docreate") public String docreate(Model model, Offer offer) { offerService.insert(offer); return "offercreated"; } ///////////////////////// @RequestMapping("/finishclasses") public String finishclasses(Model model) { List<FinishClass> finishClasses = finishClassService.getCurrent(); model.addAttribute("finishClasses", finishClasses); return "finishClasses"; } }
[ "anatls12@naver.com" ]
anatls12@naver.com
b4ba8bd8781a5dac1f61c96faec05a47e97a2126
4c50629d4662bef314bb91401117b7153279aded
/app/src/test/java/com/acadgild/balu/acd_an_session_1_assignment_3_main/ExampleUnitTest.java
bd06afabb4eb6529943b5565aa7d9b569b0346d8
[]
no_license
pbalachandra/ACD_AN_Session_1_Assignment_3_Main
2f3078c7a25ae862bbcd209f640d47ff2f69ac1b
88278083086deed5c2c937578ab94173b68cee1f
refs/heads/master
2021-01-10T05:25:46.698403
2016-03-30T10:31:13
2016-03-30T10:31:13
55,049,027
0
0
null
null
null
null
UTF-8
Java
false
false
345
java
package com.acadgild.balu.acd_an_session_1_assignment_3_main; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "balachandra.p@gmail.com" ]
balachandra.p@gmail.com
f50347cb1b69369dfc74c449db998f88ec8ec578
43c670f6a2058301e7a21a1e411b504906263584
/TogetherServer/src/main/java/com/exfantasy/server/controller/FileController.java
505039fefbd86970b1076b93adcf69cb1e484496
[]
no_license
eklan/TogetherServer
c3c3e31e26be5e3670dff52a265afa8bf01fbce9
c5a03b99df7d8297de6d89b9970871366c954611
refs/heads/master
2021-01-17T21:03:21.012110
2015-10-29T03:25:24
2015-10-29T03:25:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,273
java
package com.exfantasy.server.controller; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping(value = "/file") public class FileController { private static final Logger logger = LoggerFactory.getLogger(MailController.class); @Value("${store.file.path}") private String STORE_FILE_PATH; @RequestMapping(value = "/upload", method = RequestMethod.GET) public String fileUpload(Model model) { return "file_upload"; } @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { if (!STORE_FILE_PATH.endsWith("/")) { STORE_FILE_PATH += "/"; } if (!file.isEmpty()) { BufferedOutputStream stream = null; try { String originalFilename = file.getOriginalFilename(); String extName = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length()); byte[] bytes = file.getBytes(); stream = new BufferedOutputStream(new FileOutputStream(new File(STORE_FILE_PATH + name + extName))); stream.write(bytes); return "You successfully uploaded " + name + "!"; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } finally { try { stream.close(); } catch (IOException e) { logger.error("IOException raised while closing IOStream, err-msg: <" + e.getMessage() + ">"); } } } else { return "You failed to upload " + name + " because the file was empty."; } } }
[ "tommy.yeh1112@gmail.com" ]
tommy.yeh1112@gmail.com
7cdcb4c2a9dc5dcdf2af33c3bfe1ca8ab5e01954
7fafb0db67d98da647d2d0c362d7250674abde5b
/app/src/main/java/com/myandroid/HongjungTrip/MainActivity.java
69ba07ed709d2ca3e1a4d60feff5e439dd6af5c7
[]
no_license
HongJungKim-dev/TripClone
6f313abf275cd6773c283a565bbc6a208ccf57d9
f2f945d6ddeb2d40f0b66f91542f611447174d1e
refs/heads/master
2023-02-09T23:57:15.466249
2021-01-06T10:22:30
2021-01-06T10:22:30
327,274,351
0
0
null
null
null
null
UTF-8
Java
false
false
951
java
package com.myandroid.HongjungTrip; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.WindowManager; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ); } public void myListener1(View Target){ Intent intent = new Intent(getApplicationContext(), LoginActivity.class); startActivity(intent);//인텐트 시작 } public void myListener2(View Target){ Intent intent = new Intent(getApplicationContext(), SignUpActivity.class); startActivity(intent);//인텐트 시작 } }
[ "hongjung.kim.dev.gmail.com" ]
hongjung.kim.dev.gmail.com
70418e78a83c6a197c6a4d91ae3e720de80ee4d5
d99e6aa93171fafe1aa0bb39b16c1cc3b63c87f1
/stress/src/main/java/com/stress/sub0/sub7/sub5/Class2138.java
6467f855de75513f1e25a220b438e22d1844a4ff
[]
no_license
jtransc/jtransc-examples
291c9f91c143661c1776ddb7a359790caa70a37b
f44979531ac1de72d7af52545c4a9ef0783a0d5b
refs/heads/master
2021-01-17T13:19:55.535947
2017-09-13T06:31:25
2017-09-13T06:31:25
51,407,684
14
4
null
2017-07-04T10:18:40
2016-02-09T23:11:45
Java
UTF-8
Java
false
false
394
java
package com.stress.sub0.sub7.sub5; import com.jtransc.annotation.JTranscKeep; @JTranscKeep public class Class2138 { public static final String static_const_2138_0 = "Hi, my num is 2138 0"; static int static_field_2138_0; int member_2138_0; public void method2138() { System.out.println(static_const_2138_0); } public void method2138_1(int p0, String p1) { System.out.println(p1); } }
[ "soywiz@gmail.com" ]
soywiz@gmail.com
3b8560f5486d82bfa82008ada19b6af5cd4c9992
fed7d8c0148a2319254349c364ed9462cd5caf52
/app/src/androidTest/java/com/example/edu/mysensorlist_1122/ExampleInstrumentedTest.java
927304a44c621bf14d1cf01a0b8876abee862641
[]
no_license
onepo1/MySensorList_1122
27e58732e4780038742426e7018fe52beee510f6
7ceefb70c7f586adeac145048cd2c1dac6ac1bcf
refs/heads/master
2020-04-07T18:56:33.844654
2018-11-22T02:12:37
2018-11-22T02:12:37
158,630,197
0
0
null
null
null
null
UTF-8
Java
false
false
750
java
package com.example.edu.mysensorlist_1122; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.edu.mysensorlist_1122", appContext.getPackageName()); } }
[ "1po@korea.com" ]
1po@korea.com
e642134a825a27a85cfa3a5eced90a9d4ab93cce
ee1a0e9b8877f74d11b4122540de1c21ac5deeee
/cap/basic/IdentityEx.java
9022700ddf85214f9cbed719534db6ef7380d384
[]
no_license
samiksha0102/Capg1234
e80255ca657e92fa0195b39c5b6908c080a68e4e
aed99c22dc6afacc06ff676d18c0b520a1bb6dc7
refs/heads/master
2022-02-25T00:33:39.092748
2019-08-07T18:59:20
2019-08-07T18:59:20
195,807,304
0
0
null
null
null
null
UTF-8
Java
false
false
929
java
package com.cap.basic; import java.util.IdentityHashMap; public class IdentityEx { public static void main(String args[]) { IdentityHashMap<String, String> identityMap = new IdentityHashMap<String, String>(); identityMap.put("sony", "bravia"); identityMap.put(new String("sony"), "mobile"); //size of identityMap should be 2 here because two strings are different objects System.out.println("Size of IdentityHashMap: " + identityMap.size()); System.out.println("IdentityHashMap: " + identityMap); identityMap.put("sony", "videogame"); //size of identityMap still should be 2 because "sony" and "sony" is same object System.out.println("Size of IdentityHashMap: " + identityMap.size()); System.out.println("IdentityHashMap: " + identityMap); } }
[ "noreply@github.com" ]
samiksha0102.noreply@github.com
353584f2b4d15d20272d17371b3c07401cc061bd
e668491212798988e9af58082e3496a06894a6d7
/app/src/main/java/com/ruanyun/australianews/di/module/ApplicationModule.java
9378c3fe24128ac1de4becd58be4f3e8a545dc0e
[]
no_license
bulb0011/AustraliaNews
6d9e168ebac47b91535d504a47c3f254ecfd3760
252bd71d8f4b2963cdadff0265a23f2adfd7942c
refs/heads/master
2022-11-21T05:35:03.226587
2020-07-06T07:01:28
2020-07-06T07:01:28
265,116,880
0
1
null
null
null
null
UTF-8
Java
false
false
391
java
package com.ruanyun.australianews.di.module; import android.content.Context; import com.ruanyun.australianews.App; import dagger.Binds; import dagger.Module; /** * description: * <p/> * Created by ycw on 2018/11/20. */ @Module public abstract class ApplicationModule { //expose Application as an injectable context @Binds abstract Context bindContext(App application); }
[ "386021847@qq.com" ]
386021847@qq.com
835a1e4639662b7bef5e0f5956cd169462a148b5
70b269d0be32f6b4248686dc90dce0441d994ed5
/MyLoops/src/collections3/Animal.java
58267259ad73e063a3025618a560f02a8c8e2a81
[]
no_license
chakaiduany/FirstRepo
64fbd79eeaa2b7875bb5e4d39c652c505f2983cc
5d1f4de3d88e39cadc056600c5776a6427524248
refs/heads/master
2022-08-08T22:44:44.992709
2020-06-01T13:21:48
2020-06-01T13:21:48
267,691,009
0
0
null
null
null
null
UTF-8
Java
false
false
1,128
java
package collections3; public class Animal { String name; int age; public Animal(String name, int age) { super(); this.name = name; this.age = age; } public int futureAge() { return this.age + 20; } public void shoutName() { String x = this.name; System.out.println("MY NAME IS " + x.toUpperCase()); } public void choppedName() { String x = this.name; System.out.println(x.substring(2)); } public String anotherNameMethod() { String x = this.name; return x.substring(2,4); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Animal other = (Animal) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
[ "chakai.duany@gmail.com" ]
chakai.duany@gmail.com
dd4100dcd806b17e2609c62fb5dd104ba81254a7
547ce6bc1a8dc41d3ffa94c53911d0d001eebd41
/Calculator.java
2ff96b028608a5d43086016d6922e969e8f998dd
[]
no_license
guswnsdn116/vvvvv
70a2c802440b671b77603cecc475905028dc7278
d5d0e201bd6fdd69235e8bafaf4e6c683e6186d4
refs/heads/master
2020-05-23T22:32:56.415427
2019-05-16T08:16:43
2019-05-16T08:16:43
186,976,333
0
0
null
null
null
null
UTF-8
Java
false
false
2,797
java
package sdsadasdasdasd; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Calculator extends JFrame implements ActionListener { private JPanel panel; private JTextField display; private JButton[] buttons; private String[] labels = { "Backspace", "", "", "CE", "C", "7", "8", "9", "/", "sqrt", "4", "5", "6", "x", "%", "1", "2", "3", "-", "1/x", "0", "-/+", ".", "+", "=", }; private double result = 0; private String operator = "="; private boolean startOfNumber = true; public Calculator() { display = new JTextField(35); panel = new JPanel(); display.setText("0.0"); panel.setLayout(new GridLayout(0, 5, 3, 3)); buttons = new JButton[25]; int index = 0; for (int rows = 0; rows < 5; rows++) { for (int cols = 0; cols < 5; cols++) { buttons[index] = new JButton(labels[index]); if (cols >= 3) buttons[index].setForeground(Color.red); else buttons[index].setForeground(Color.blue); buttons[index].setBackground(Color.yellow); panel.add(buttons[index]); buttons[index].addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.charAt(0) == 'C') { startOfNumber = true; result = 0; operator = "="; display.setText("0.0"); } else if (command.charAt(0) >= '0' && command.charAt(0) <= '9' || command.equals(".")) { if (startOfNumber == true) display.setText(command); else display.setText(display.getText() + command); startOfNumber = false; } else { if (startOfNumber) { if (command.equals("-")) { display.setText(command); startOfNumber = false; } else operator = command; } else { double x = Double.parseDouble(display.getText()); calculate(x); operator = command; startOfNumber = true; } } } }); index++; } } add(display, BorderLayout.NORTH); add(panel, BorderLayout.CENTER); setVisible(true); pack(); } private void calculate(double n) { if (operator.equals("+")) result += n; else if (operator.equals("-")) result -= n; else if (operator.equals("*")) result *= n; else if (operator.equals("/")) result /= n; else if (operator.equals("=")) result = n; display.setText("" + result); } public static void main(String args[]) { Calculator s = new Calculator(); } }
[ "noreply@github.com" ]
guswnsdn116.noreply@github.com
8fea2a6c79ae2fab1a5f719bb2c3f71d28f3efa2
ef2aab378eee6102b7b1a1a0b07b8b35b1193d4b
/Daisy2017/src/missdaisy/loops/Navigation.java
fb7bf629ce7d0a9d832c9720508344eab953b92f
[]
no_license
Team341/FRC2017-Public
4c068644dfc04b854d90425a61a72a4890e36fb7
5ae341adbf3c8ae7684d6ea9145f60f62243a288
refs/heads/master
2021-05-15T03:20:24.279013
2018-01-02T13:41:20
2018-01-02T13:41:20
114,270,606
1
1
null
null
null
null
UTF-8
Java
false
false
5,963
java
package missdaisy.loops; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import missdaisy.Constants; import missdaisy.Vision; import missdaisy.utilities.DaisyMath; /** * The representation of the location, heading (angle), speed, and distance (traveled) of the robot * * @author jrussell */ public class Navigation { private static Navigation navigationInstance; private Vision mVision; // Sensors private Encoder mLeftDriveEncoder; private Encoder mRightDriveEncoder; private AHRS mGyro; // Navigational state private double x = 0.0; // positive from driver facing center of the field private double y = 0.0; // positive from driver looking left private double theta0 = 0.0; // anti-clockwise from center of field to left private double thetaLast = 0.0; private double leftEncoderLast = 0.0; private double rightEncoderLast = 0.0; private double mApproxTargetAngle = 0.0; public static Navigation getInstance() { if (navigationInstance == null) navigationInstance = new Navigation(); return navigationInstance; } private Navigation() { mLeftDriveEncoder = new Encoder(Constants.DigitalInputs.DRIVE_LEFT_ENCODER_1, Constants.DigitalInputs.DRIVE_LEFT_ENCODER_2); mRightDriveEncoder = new Encoder(Constants.DigitalInputs.DRIVE_RIGHT_ENCODER_1, Constants.DigitalInputs.DRIVE_RIGHT_ENCODER_2); mLeftDriveEncoder.setDistancePerPulse(Constants.Properties.DRIVE_DISTANCE_PER_PULSE); mRightDriveEncoder.setDistancePerPulse(Constants.Properties.DRIVE_DISTANCE_PER_PULSE); mVision = Vision.getInstance(); try { /* Communicate w/navX MXP via the MXP SPI Bus. */ /* Alternatively: I2C.Port.kMXP, SerialPort.Port.kMXP or SerialPort.Port.kUSB */ /* See http://navx-mxp.kauailabs.com/guidance/selecting-an-interface/ for details. */ mGyro = new AHRS(SPI.Port.kMXP); } catch (RuntimeException ex) { DriverStation.reportError("Error instantiating navX MXP: " + ex.getMessage(), true); } } /** * Reset your current location to specified coordinates * * @param x desired x coordinate * @param y desired y coordinate * @param theta desired robot heading (angle) */ public synchronized void resetRobotPosition(double x, double y, double theta) { mApproxTargetAngle = DaisyMath.boundAngle0to360Degrees((mApproxTargetAngle - getHeadingInDegrees()) + theta); this.x = x; this.y = y; theta0 = theta; thetaLast = theta; mLeftDriveEncoder.reset(); mRightDriveEncoder.reset(); mGyro.reset(); } public void resetEncoders() { mLeftDriveEncoder.reset(); mRightDriveEncoder.reset(); } public synchronized double getApproxTargetAngle() { return mApproxTargetAngle; } public synchronized void setApproxTargetAngle(double newAngle) { mApproxTargetAngle = DaisyMath.boundAngle0to360Degrees(newAngle); } /** * @return the current x coordinate of the robot */ public synchronized double getXinInches() { return x; } /** * @return the current y coordinate of the robot */ public synchronized double getYinInches() { return y; } /** * @return the current angle of the robot */ public double getHeadingInDegrees() { return DaisyMath.boundAngle0to360Degrees(thetaLast + theta0); } public synchronized void run() { if (mVision.seesTarget()) { setApproxTargetAngle(mVision.getAzimuth()); } // Read sensors double left = mLeftDriveEncoder.getDistance(); double right = mRightDriveEncoder.getDistance(); // getRoll = the robots pitch // getPitch = the robots roll double yaw = DaisyMath.boundAngle0to360Degrees(mGyro.getYaw() + theta0); // the distance the drive has gone since last cycle double distance = ((left + right) - (leftEncoderLast + rightEncoderLast)) / 2.0; /* * if( (left-leftEncoderLast == 0.0) && (right-rightEncoderLast == 0.0) ) { // Fuse encoders * with gyro to prevent drift gyro.resetYaw(); theta0 = DaisyMath.boundAngle0to360Degrees(theta0 * + thetaLast); theta = thetaLast = 0.0; } */ double thetaRad = Math.toRadians(yaw); // calculate the current x + y coordinates, based on the distance traveled the angle turned x += distance * Math.cos(thetaRad); y += distance * Math.sin(thetaRad); leftEncoderLast = left; rightEncoderLast = right; thetaLast = yaw; SmartDashboard.putNumber("heading", yaw); } public double getLeftEncoderDistance() { return mLeftDriveEncoder.getDistance(); } public double getRightEncoderDistance() { return -1.0 * mRightDriveEncoder.getDistance(); } public double getLeftEncoderRate() { return mLeftDriveEncoder.getRate(); } public double getRightEncoderRate() { return mRightDriveEncoder.getRate(); } /** * Uses the distance the robot moves per one shaft rotation to calculate the speed of the robot * * @return the speed in units/sec, defined by the setDistancePerpulse. */ public double getAverageEncoderRate() { double average = (getLeftEncoderRate() + getRightEncoderRate()) / 2; return average; } /** * Uses the distance the robot moves per one shaft rotation and the number of rotations to * calculate distance traveled. * * @return The distance traveled in units, defined by the setDistancePerPulse */ public double getAverageEncoderDistance() { double average = (getLeftEncoderDistance() + getRightEncoderDistance()) / 2; return average; } public void logToDashboard() { SmartDashboard.putNumber("LeftEncoderRate", getLeftEncoderRate()); SmartDashboard.putNumber("RightEncoderRate", getRightEncoderRate()); SmartDashboard.putNumber("Distance", getAverageEncoderDistance()); } }
[ "ajn5049" ]
ajn5049
900881a9b9c9e485a299df7df3044820a6f1a628
8c8e8a6af5c59a05a288f10c9604a2087dd783c0
/SIGC/src/main/java/ec/com/sigc/controlador/TableBackController.java
846575d3a1be509222fea84e4921ba3e5774927f
[]
no_license
levillagran/SIGC
1044889c85aa0fe2315124d74574774cc8be54ca
3872fceb1ced463feeb1fbcae3adb8b191c16dcf
refs/heads/master
2021-01-04T22:04:12.394687
2020-05-23T19:51:57
2020-05-23T19:51:57
240,777,081
0
0
null
null
null
null
UTF-8
Java
false
false
2,158
java
package ec.com.sigc.controlador; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import ec.com.sigc.entidad.BackOffice; import ec.com.sigc.entidad.User; import ec.com.sigc.servicio.BackOfficeService; import ec.com.sigc.servicio.UserServicio; @Controller public class TableBackController { @Autowired @Qualifier("userServicio") private UserServicio userServicio; @Autowired @Qualifier("backOfficeService") private BackOfficeService backOfficeService; @GetMapping("/tableBack") @ResponseBody public ModelAndView showForm(String username) { ModelAndView mav = new ModelAndView("tableBack"); mav.addObject("contacts", backOfficeService.findAllBack()); mav.addObject("username", username); return mav; } @GetMapping("/editBack") @ResponseBody public ModelAndView showEditAdminForm(Integer backId, String username) { ModelAndView mav = new ModelAndView("editBack"); if (backId != null) { mav.addObject("back", backOfficeService.findBack(backId)); } mav.addObject("username", username); return mav; } @PostMapping("/saveBack") public ModelAndView saveAdmin(BackOffice back, String username) { ModelAndView mav = new ModelAndView("dashboardAdmin"); User user = back.getUserId(); user.setRoleId(userServicio.findRoleById(3)); back.setUserId(user); backOfficeService.saveBack(back); mav.addObject("username", username); return mav; } @GetMapping("/findBack") @ResponseBody public User findOne(Integer id) { return userServicio.findAdmin(id); } @GetMapping("/cancelBack") public String cancel() { return "redirect:/dashboardAdmin"; } @GetMapping("/deleteBack") public String deleteCountry(Integer adminId) { //userServicio.deletAdmin(userServicio.findAdmin(adminId)); return "redirect:/dashboardAdmin"; } }
[ "leninsasos@hotmail.com" ]
leninsasos@hotmail.com
f8cc37568bc7cc7361cf26a3d657eecb040e2421
9af4318864ae7dafb379e785aa11895a726e395a
/myfristjavaprogram/src/homeWork06_04_2019/DigitsSomeChallenge_4.java
d6e36f642698d7f91de5dffb14ac09d3b85d66db
[]
no_license
parthkumaresh/first-java
f463c6054a8607436f095f44c09c632b6b959692
97a27f31cfc84bec8a482efcb6bc6a02765581e6
refs/heads/master
2020-05-01T06:03:47.400464
2019-04-25T20:49:50
2019-04-25T20:49:50
177,319,619
0
0
null
null
null
null
UTF-8
Java
false
false
524
java
package homeWork06_04_2019; import java.util.Scanner; public class DigitsSomeChallenge_4 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input an integer: "); int digits = in.nextInt(); System.out.println("The sum is " + sumDigits(digits)); } public static int sumDigits(long n) { int result = 0; while(n > 0) { result += n % 10; n /= 10; } return result; } }
[ "minalp999@gmail.com" ]
minalp999@gmail.com
b999ccac1d2e46294ef51aebfd35ca2831659cef
a17dd1e9f5db1c06e960099c13a5b70474d90683
/app-back/src/main/java/jp/co/sint/webshop/web/bean/back/catalog/GiftBean.java
2318df94e91307ff374e439851ac9f3c93fcbc27
[]
no_license
giagiigi/ec_ps
4e404afc0fc149c9614d0abf63ec2ed31d10bebb
6eb19f4d14b6f3a08bfc2c68c33392015f344cdd
refs/heads/master
2020-12-14T07:20:24.784195
2015-02-09T10:00:44
2015-02-09T10:00:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,342
java
package jp.co.sint.webshop.web.bean.back.catalog; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import jp.co.sint.webshop.code.CodeAttribute; import jp.co.sint.webshop.data.attribute.AlphaNum2; import jp.co.sint.webshop.data.attribute.Bool; import jp.co.sint.webshop.data.attribute.Currency; import jp.co.sint.webshop.data.attribute.Digit; import jp.co.sint.webshop.data.attribute.Length; import jp.co.sint.webshop.data.attribute.Metadata; import jp.co.sint.webshop.data.attribute.Precision; import jp.co.sint.webshop.data.attribute.Range; import jp.co.sint.webshop.data.attribute.Required; import jp.co.sint.webshop.data.domain.TaxType; import jp.co.sint.webshop.utility.ArrayUtil; import jp.co.sint.webshop.utility.DateUtil; import jp.co.sint.webshop.web.bean.back.UIBackBean; import jp.co.sint.webshop.web.text.back.Messages; import jp.co.sint.webshop.web.webutility.RequestParameter; import jp.co.sint.webshop.web.webutility.WebConstantCode; /** * U1040310:ギフトのデータモデルです。 * * @author System Integrator Corp. */ public class GiftBean extends UIBackBean { /** serial version uid */ private static final long serialVersionUID = 1L; private GiftDetailBean edit = new GiftDetailBean(); private List<GiftDetailBean> list = new ArrayList<GiftDetailBean>(); private String fileUrl; private String mode; private List<CodeAttribute> shopList = new ArrayList<CodeAttribute>(); @Required @Metadata(name = "ショップ") private String searchShopCode; private boolean displaySearchButton = false; private boolean displayEditTable = false; private boolean displayUploadTable = false; private boolean displaySelectButton = false; private boolean displayRegisterButton = false; private boolean displayUpdateButton = false; private String giftCodeDisplayMode = WebConstantCode.DISPLAY_HIDDEN; private TaxType[] taxType = TaxType.values(); private List<CodeAttribute> giftImageList = new ArrayList<CodeAttribute>(); /** * U1040310:ギフトのサブモデルです。 * * @author System Integrator Corp. */ public static class GiftDetailBean implements Serializable { /** serial version uid */ private static final long serialVersionUID = 1L; /** ショップコード */ @Length(16) @AlphaNum2 @Metadata(name = "ショップコード", order = 1) private String shopCode; /** ギフトコード */ @Required @Length(16) @AlphaNum2 @Metadata(name = "ギフトコード", order = 2) private String giftCode; /** ギフト名 */ @Required @Length(40) @Metadata(name = "ギフト名", order = 3) private String giftName; /** 説明 */ @Length(200) @Metadata(name = "説明", order = 4) private String giftDescription; /** 価格 */ @Required @Length(11) @Currency @Range(min = 0, max = 99999999) @Precision(precision = 10, scale = 2) @Metadata(name = "価格", order = 5) private String giftPrice; /** 表示順 */ @Length(8) @Digit @Range(min = 0, max = 99999999) @Metadata(name = "表示順", order = 6) private String displayOrder; /** 消費税区分 */ @Required @Length(1) @Metadata(name = "消費税区分", order = 7) private String giftTaxType; /** 表示区分 */ @Required @Length(1) @Bool @Metadata(name = "表示区分", order = 8) private String displayFlg; private String giftImageUrl; private Date updateDatetime; private boolean displayDeleteButton = false; /** * giftImageUrlを取得します。 * * @return giftImageUrl */ public String getGiftImageUrl() { return giftImageUrl; } /** * giftImageUrlを設定します。 * * @param giftImageUrl * giftImageUrl */ public void setGiftImageUrl(String giftImageUrl) { this.giftImageUrl = giftImageUrl; } /** * displayFlgを取得します。 * * @return displayFlg */ public String getDisplayFlg() { return displayFlg; } /** * displayOrderを取得します。 * * @return displayOrder */ public String getDisplayOrder() { return displayOrder; } /** * giftCodeを取得します。 * * @return giftCode */ public String getGiftCode() { return giftCode; } /** * giftDescriptionを取得します。 * * @return giftDescription */ public String getGiftDescription() { return giftDescription; } /** * giftNameを取得します。 * * @return giftName */ public String getGiftName() { return giftName; } /** * giftPriceを取得します。 * * @return giftPrice */ public String getGiftPrice() { return giftPrice; } /** * giftTaxTypeを取得します。 * * @return giftTaxType */ public String getGiftTaxType() { return giftTaxType; } /** * shopCodeを取得します。 * * @return shopCode */ public String getShopCode() { return shopCode; } /** * displayFlgを設定します。 * * @param displayFlg * displayFlg */ public void setDisplayFlg(String displayFlg) { this.displayFlg = displayFlg; } /** * displayOrderを設定します。 * * @param displayOrder * displayOrder */ public void setDisplayOrder(String displayOrder) { this.displayOrder = displayOrder; } /** * giftCodeを設定します。 * * @param giftCode * giftCode */ public void setGiftCode(String giftCode) { this.giftCode = giftCode; } /** * giftDescriptionを設定します。 * * @param giftDescription * giftDescription */ public void setGiftDescription(String giftDescription) { this.giftDescription = giftDescription; } /** * giftNameを設定します。 * * @param giftName * giftName */ public void setGiftName(String giftName) { this.giftName = giftName; } /** * giftPriceを設定します。 * * @param giftPrice * giftPrice */ public void setGiftPrice(String giftPrice) { this.giftPrice = giftPrice; } /** * giftTaxTypeを設定します。 * * @param giftTaxType * giftTaxType */ public void setGiftTaxType(String giftTaxType) { this.giftTaxType = giftTaxType; } /** * shopCodeを設定します。 * * @param shopCode * shopCode */ public void setShopCode(String shopCode) { this.shopCode = shopCode; } /** * updateDatetimeを取得します。 * * @return updateDatetime */ public Date getUpdateDatetime() { return DateUtil.immutableCopy(updateDatetime); } /** * updateDatetimeを設定します。 * * @param updateDatetime * updateDatetime */ public void setUpdateDatetime(Date updateDatetime) { this.updateDatetime = DateUtil.immutableCopy(updateDatetime); } /** * displayDeleteButtonを取得します。 * * @return displayDeleteButton */ public boolean isDisplayDeleteButton() { return displayDeleteButton; } /** * displayDeleteButtonを設定します。 * * @param displayDeleteButton * displayDeleteButton */ public void setDisplayDeleteButton(boolean displayDeleteButton) { this.displayDeleteButton = displayDeleteButton; } } /** * fileUrlを取得します。 * * @return fileUrl */ public String getFileUrl() { return fileUrl; } /** * modeを取得します。 * * @return mode */ public String getMode() { return mode; } /** * fileUrlを設定します。 * * @param fileUrl * fileUrl */ public void setFileUrl(String fileUrl) { this.fileUrl = fileUrl; } /** * modeを設定します。 * * @param mode * mode */ public void setMode(String mode) { this.mode = mode; } /** * CategoryDetailBeanを取得します。 * * @return CategoryDetailBean */ public GiftDetailBean getEdit() { return edit; } /** * ギフト一覧を取得します。 * * @return List */ public List<GiftDetailBean> getList() { return list; } /** * GiftDetailBeanを設定します。 * * @param edit * ギフト情報 */ public void setEdit(GiftDetailBean edit) { this.edit = edit; } /** * ギフト一覧を設定します。 * * @param list * ギフト一覧 */ public void setList(List<GiftDetailBean> list) { this.list = list; } /** * searchShopCodeを取得します。 * * @return searchShopCode */ public String getSearchShopCode() { return searchShopCode; } /** * shopListを取得します。 * * @return shopList */ public List<CodeAttribute> getShopList() { return shopList; } /** * searchShopCodeを設定します。 * * @param searchShopCode * searchShopCode */ public void setSearchShopCode(String searchShopCode) { this.searchShopCode = searchShopCode; } /** * shopListを設定します。 * * @param shopList * shopList */ public void setShopList(List<CodeAttribute> shopList) { this.shopList = shopList; } /** * displayEditTableを取得します。 * * @return displayEditTable */ public boolean isDisplayEditTable() { return displayEditTable; } /** * displaySearchButtonを取得します。 * * @return displaySearchButton */ public boolean isDisplaySearchButton() { return displaySearchButton; } /** * displaySelectButtonを取得します。 * * @return displaySelectButton */ public boolean isDisplaySelectButton() { return displaySelectButton; } /** * displayEditTableを設定します。 * * @param displayEditTable * displayEditTable */ public void setDisplayEditTable(boolean displayEditTable) { this.displayEditTable = displayEditTable; } /** * displaySearchButtonを設定します。 * * @param displaySearchButton * displaySearchButton */ public void setDisplaySearchButton(boolean displaySearchButton) { this.displaySearchButton = displaySearchButton; } /** * displaySelectButtonを設定します。 * * @param displaySelectButton * displaySelectButton */ public void setDisplaySelectButton(boolean displaySelectButton) { this.displaySelectButton = displaySelectButton; } /** * displayRegisterButtonを取得します。 * * @return displayRegisterButton */ public boolean isDisplayRegisterButton() { return displayRegisterButton; } /** * displayUpdateButtonを取得します。 * * @return displayUpdateButton */ public boolean isDisplayUpdateButton() { return displayUpdateButton; } /** * displayRegisterButtonを設定します。 * * @param displayRegisterButton * displayRegisterButton */ public void setDisplayRegisterButton(boolean displayRegisterButton) { this.displayRegisterButton = displayRegisterButton; } /** * displayUpdateButtonを設定します。 * * @param displayUpdateButton * displayUpdateButton */ public void setDisplayUpdateButton(boolean displayUpdateButton) { this.displayUpdateButton = displayUpdateButton; } /** * サブJSPを設定します。 */ @Override public void setSubJspId() { } /** * リクエストパラメータから値を取得します。 * * @param reqparam * リクエストパラメータ */ public void createAttributes(RequestParameter reqparam) { this.setSearchShopCode(reqparam.get("searchShopCode")); reqparam.copy(edit); } /** * モジュールIDを取得します。 * * @return モジュールID */ public String getModuleId() { return "U1040310"; } /** * モジュール名を取得します。 * * @return モジュール名 */ public String getModuleName() { return Messages.getString("web.bean.back.catalog.GiftBean.0"); } /** * giftCodeDisplayModeを取得します。 * * @return giftCodeDisplayMode */ public String getGiftCodeDisplayMode() { return giftCodeDisplayMode; } /** * giftCodeDisplayModeを設定します。 * * @param giftCodeDisplayMode * giftCodeDisplayMode */ public void setGiftCodeDisplayMode(String giftCodeDisplayMode) { this.giftCodeDisplayMode = giftCodeDisplayMode; } /** * displayUploadTableを取得します。 * * @return displayUploadTable displayUploadTable */ public boolean isDisplayUploadTable() { return displayUploadTable; } /** * displayUploadTableを設定します。 * * @param displayUploadTable * displayUploadTable */ public void setDisplayUploadTable(boolean displayUploadTable) { this.displayUploadTable = displayUploadTable; } /** * taxTypeを取得します。 * * @return the taxType */ public TaxType[] getTaxType() { return ArrayUtil.immutableCopy(taxType); } /** * taxTypeを設定します。 * * @param taxType * taxType */ public void setTaxType(TaxType[] taxType) { this.taxType = ArrayUtil.immutableCopy(taxType); } /** * giftImageListを取得します。 * * @return giftImageList */ public List<CodeAttribute> getGiftImageList() { return giftImageList; } /** * giftImageListを設定します。 * * @param giftImageList * giftImageList */ public void setGiftImageList(List<CodeAttribute> giftImageList) { this.giftImageList = giftImageList; } }
[ "fengperfect@126.com" ]
fengperfect@126.com
0324458643b5790cc58e5cfefee9d55d513f5eea
93f315fee18f8c97f6dad2a5d693778ca19691bf
/src/math/Tribonacci.java
87153f419a1023b55120580e04a9580f1b4102b4
[]
no_license
AlexhahahaDrag/arithmetic
34f8e0b135a5f747e04546f81b6365a2a7208040
92232fd1758963bc964bea0759e8f0852b3cdaa0
refs/heads/master
2023-08-31T07:13:12.184136
2023-08-22T05:56:58
2023-08-22T05:56:58
170,278,495
2
0
null
null
null
null
UTF-8
Java
false
false
1,339
java
package math; /** *description: * 1137. 第 N 个泰波那契数 * 泰波那契序列 Tn 定义如下: * * T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2 * * 给你整数 n,请返回第 n 个泰波那契数 Tn 的值。 * * * * 示例 1: * * 输入:n = 4 * 输出:4 * 解释: * T_3 = 0 + 1 + 1 = 2 * T_4 = 1 + 1 + 2 = 4 * 示例 2: * * 输入:n = 25 * 输出:1389537 * * * 提示: * * 0 <= n <= 37 * 答案保证是一个 32 位整数,即 answer <= 2^31 - 1。 *author: alex *createDate: 2022/2/10 17:42 *version: 1.0.0 */ public class Tribonacci { public int tribonacci(int n) { switch (n) { case 0 : return 0; case 1: case 2: return 1; default: int a = 0; int b = 1; int c = 1; int d = 0; while(n-- > 2) { d = a + b + c; a = b; b = c; c = d; } return d; } } public static void main(String[] args) { int n = 25;//1389537 Tribonacci tribonacci = new Tribonacci(); System.out.println(tribonacci.tribonacci(n)); } }
[ "734663446@qq.com" ]
734663446@qq.com
76daf004132a6d0f0cdf4581a786c202e01af0e4
5d76b555a3614ab0f156bcad357e45c94d121e2d
/src/com/fasterxml/jackson/databind/JsonSerializer.java
39b7059fb986ced323727e2882ba160ab8dfa933
[]
no_license
BinSlashBash/xcrumby
8e09282387e2e82d12957d22fa1bb0322f6e6227
5b8b1cc8537ae1cfb59448d37b6efca01dded347
refs/heads/master
2016-09-01T05:58:46.144411
2016-02-15T13:23:25
2016-02-15T13:23:25
51,755,603
5
1
null
null
null
null
UTF-8
Java
false
false
2,395
java
package com.fasterxml.jackson.databind; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.util.NameTransformer; import java.io.IOException; public abstract class JsonSerializer<T> implements JsonFormatVisitable { public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper paramJsonFormatVisitorWrapper, JavaType paramJavaType) throws JsonMappingException { if (paramJsonFormatVisitorWrapper != null) { paramJsonFormatVisitorWrapper.expectAnyFormat(paramJavaType); } } public JsonSerializer<?> getDelegatee() { return null; } public Class<T> handledType() { return null; } public boolean isEmpty(T paramT) { return paramT == null; } public boolean isUnwrappingSerializer() { return false; } public JsonSerializer<T> replaceDelegatee(JsonSerializer<?> paramJsonSerializer) { throw new UnsupportedOperationException(); } public abstract void serialize(T paramT, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider) throws IOException, JsonProcessingException; public void serializeWithType(T paramT, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider, TypeSerializer paramTypeSerializer) throws IOException, JsonProcessingException { paramSerializerProvider = handledType(); paramJsonGenerator = paramSerializerProvider; if (paramSerializerProvider == null) { paramJsonGenerator = paramT.getClass(); } throw new UnsupportedOperationException("Type id handling not implemented for type " + paramJsonGenerator.getName()); } public JsonSerializer<T> unwrappingSerializer(NameTransformer paramNameTransformer) { return this; } public boolean usesObjectId() { return false; } public static abstract class None extends JsonSerializer<Object> {} } /* Location: /home/dev/Downloads/apk/dex2jar-2.0/crumby-dex2jar.jar!/com/fasterxml/jackson/databind/JsonSerializer.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "binslashbash@otaking.top" ]
binslashbash@otaking.top
0ebfbbb0ce2fb473e2a1f56a7dac83e68c7af7ff
add5be3b93d0160b8c63fcdbea0c41d291b56a27
/Packages/Cipher.java
24d4213edfacac3ea2e160cc6e82f755b3aa088e
[]
no_license
charlsbabbage/Decrypt-Machine
3c56275cbefa99ba2e2169d8952d3d5ed631693b
cbf671bb6901acdeb96577e01cac2b01baf25c9f
refs/heads/master
2021-01-18T17:01:53.096912
2017-04-24T16:37:31
2017-04-24T16:37:31
86,781,570
0
0
null
2017-03-31T05:31:44
2017-03-31T05:31:44
null
UTF-8
Java
false
false
1,333
java
package cipher; /** * * @author hpoje */ public abstract class Cipher { private String cipher, plainText; protected String newtxt = ""; protected Cipher(){ } protected Cipher(String cypherText){ cipher = cypherText; } protected void setCipherText(){ cipher = this.newtxt; } public void setPlainText(String pt){ plainText = pt; } public String getPlainText(){ return plainText; } public String getCipherText(){ return cipher; } public abstract void encrypt(); public abstract void decrypt(); public String toString(){ return cipher; } protected void reset(){ newtxt = "hi"; } protected char[] get1DAlphabitsArray(){ char[] alphabits = new char[26]; char letters = 'A'; for(int u = 0; u < alphabits.length; u++){ alphabits[u] = letters; letters++; } return alphabits; } protected String[][] get2DAlphabitsArray(){ String[][] alphabit = {{"a", "b", "c", "d", "e"}, {"f", "g", "h", "ij", "k"}, {"l", "m", "n", "o", "p"}, {"q", "r", "s", "t", "u"}, {"v", "w", "x", "y", "z"}}; return alphabit; } }
[ "noreply@github.com" ]
charlsbabbage.noreply@github.com
e885fdef7a8af6678959d5185728faa1e8f3f87d
35b31f2d291d2b2d36febff5ca5690bcadbc5176
/Baekjoon/Main_B_2667_단지번호붙이기_bfs.java
095956ef752527bbce166a94538762150ca26bb0
[]
no_license
soohyun0907/Algorithm
8ba1a6ddf3d531cd9dbf0560422cd9d27f31376b
a4c7177c76d733db36c1bb5c22832a1d3998423e
refs/heads/master
2020-12-21T16:32:36.297184
2020-11-24T14:57:41
2020-11-24T14:57:41
236,490,436
3
0
null
null
null
null
UTF-8
Java
false
false
2,426
java
package com.ssafy.ws; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.StringTokenizer; class Town { int x; int y; public Town(int x, int y) { this.x = x; this.y = y; } } public class Main_B_2667_단지번호붙이기_bfs { static int N, house = 0, town = 0; static int[][] map; static boolean[][] visited; static List<Integer> houseArray = new ArrayList<>(); static int[] deltaX = { -1, 0, 1, 0 }; // 상, 우, 하, 좌 static int[] deltaY = { 0, 1, 0, -1 }; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); StringBuilder answer = new StringBuilder(); // N = 지도의 크기 N = Integer.parseInt(st.nextToken()); map = new int[N][N]; visited = new boolean[N][N]; for (int i = 0; i < N; i++) { String str = in.readLine(); for (int j = 0; j < N; j++) { map[i][j] = str.charAt(j) - 48; } } // bfs for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (map[i][j] == 1 && !visited[i][j]) { house = 0; bfs(i, j); houseArray.add(house); town++; } } } Collections.sort(houseArray); answer.append(town).append("\n"); for (int i = 0; i < houseArray.size(); i++) { answer.append(houseArray.get(i)).append("\n"); } System.out.println(answer); in.close(); } // bfs - 주변을 탐색해서 1을 만나면 큐에 넣어놓고 큐에서 차례가 오면 그 때 주변 다시 탐색하는 형식 private static void bfs(int i, int j) { Queue<Town> queue = new LinkedList<Town>(); visited[i][j] = true; Town town = new Town(i, j); queue.offer(town); house++; int currentX, currentY; while (!queue.isEmpty()) { currentX = queue.peek().x; currentY = queue.poll().y; for (int n = 0; n < deltaX.length; n++) { int nextX = currentX + deltaX[n]; int nextY = currentY + deltaY[n]; if (nextX < 0 || nextX >= N || nextY < 0 || nextY >= N) continue; if (map[nextX][nextY] == 1 && !visited[nextX][nextY]) { visited[nextX][nextY] = true; town = new Town(nextX, nextY); queue.offer(town); house++; } } } } }
[ "soohyun0907@naver.com" ]
soohyun0907@naver.com
d388d1bb43e0580810b017a434e29777a3e69b12
84f84d423644dc31541bd4749fcacacaf17940f9
/modules/core/src/com/company/ams/service/NewServiceBean.java
e3f669882e486f75299e95e64b7df5270d78ea95
[]
no_license
Elangovan22/Asset_Management
2a5ae06ad347d86093f90e84aef24487bbdd0177
b7ca3c5e5b471486bede02d04d89636b878d10a1
refs/heads/master
2021-01-11T16:45:08.942989
2017-04-04T15:35:37
2017-04-04T15:35:37
79,666,582
0
0
null
2017-02-21T06:53:12
2017-01-21T19:07:01
Java
UTF-8
Java
false
false
6,032
java
package com.company.ams.service; import org.springframework.stereotype.Service; import com.haulmont.cuba.core.EntityManager; import com.haulmont.cuba.core.Persistence; import com.haulmont.cuba.core.Transaction; import com.haulmont.cuba.core.Query; import com.haulmont.cuba.core.app.UniqueNumbersAPI; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.security.entity.EntityOp; import com.haulmont.cuba.security.entity.PermissionType; import com.company.ams.entity.Asset; import com.company.ams.entity.NewAsset; import com.company.ams.entity.Instance; import com.company.ams.entity.AssetAllocated; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import javax.inject.Inject; import java.util.ArrayList; import java.util.Collection; @Service(NewService.NAME) public class NewServiceBean implements NewService { @Inject private Persistence persistence; @Inject private UniqueNumbersAPI uniqueNumbers; @Inject private Security security; @Inject private Metadata metadata; @Override @Transactional public Collection<Instance> createInstances(NewAsset asset, Integer amount,String vv,Integer tm,String user,String dt,String datt) { checkPermission(EntityOp.CREATE); // Due to the @Transactional annotation a new transaction is started right before the method is called and // committed after leaving the method Collection<Instance> instances = new ArrayList<>(); Instance instance = metadata.create(Instance.class); instance.setUser(user); instance.setName(vv); instance.setAssetid(asset.getAssetid()); instance.setCompany(asset.getCompany()); instance.setModelname(asset.getModelname()); instance.setTotalquantity(asset.getAvailablequantity()); instance.setNeededquantity(amount); instance.setTeamviewer(tm); instance.setRequestedtime(dt); instance.setAssetneededdate(datt); persistence.getEntityManager().persist(instance); instances.add(instance); return instances; } @Override public Collection<Instance> calculate(Instance insta,int assetid,int totalnumber) { checkPermission(EntityOp.UPDATE); Instance instance = metadata.create(Instance.class); Collection<Instance> instances = new ArrayList<>(); // Explicit transaction control try (Transaction tx = persistence.createTransaction()) { EntityManager em = persistence.getEntityManager(); Query query = em.createQuery("update ams$Instance u set u.totalquantity = :totalnumber where u.assetid = :assetid"); query.setParameter("assetid", assetid); query.setParameter("totalnumber", totalnumber); query.executeUpdate(); //tx.commit(); //for (BookInstance booksInstance : bookInstances) { // Instance instance = em.merge(instance, //instanceView); // Return the updated instance // mergedInstances.add(instance); //} tx.commit(); } //persistence.getEntityManager().persist(instance); //instances.add(instance); return instances; } @Override public Collection<NewAsset> updatequantity(int assetid,int totalnumber) { checkPermission(EntityOp.UPDATE); NewAsset instance = metadata.create(NewAsset.class); Collection<NewAsset> instances = new ArrayList<>(); // Explicit transaction control try (Transaction tx = persistence.createTransaction()) { EntityManager em = persistence.getEntityManager(); Query query = em.createQuery("update ams$NewAsset u set u.availablequantity = :totalnumber where u.assetid = :assetid"); query.setParameter("assetid", assetid); query.setParameter("totalnumber", totalnumber); query.executeUpdate(); //tx.commit(); //for (BookInstance booksInstance : bookInstances) { // Instance instance = em.merge(instance, //instanceView); // Return the updated instance // mergedInstances.add(instance); //} tx.commit(); } //persistence.getEntityManager().persist(instance); //instances.add(instance); return instances; } @Override @Transactional public Collection<AssetAllocated> allocated(Instance asset) { checkPermission(EntityOp.CREATE); // Due to the @Transactional annotation a new transaction is started right before the method is called and // committed after leaving the method Collection<AssetAllocated> alloc = new ArrayList<>(); AssetAllocated instance = metadata.create(AssetAllocated.class); instance.setUser(asset.getUser()); instance.setName(asset.getName()); instance.setAssetid(asset.getAssetid()); instance.setCompany(asset.getCompany()); instance.setModelname(asset.getModelname()); instance.setQuantity(asset.getNeededquantity()); persistence.getEntityManager().persist(instance); alloc.add(instance); return alloc; } /*@Override public Collection<Instance> calculate(Instance insta) { checkPermission(EntityOp.CREATE); Collection<Instance> instances = new ArrayList<>(); Instance instance = metadata.create(Instance.class); instance.setTotalquantity(insta.getTotalquantity()-insta.getNeededquantity()); persistence.getEntityManager().persist(instance); instances.add(instance); return instances; }*/ private void checkPermission(EntityOp op) { if (!security.isEntityOpPermitted(Instance.class, op)) { throw new AccessDeniedException(PermissionType.ENTITY_OP, Instance.class.getSimpleName()); } } }
[ "elangshoba@gmail.com" ]
elangshoba@gmail.com
36c00486ba7f17c0a7e4d7e5d1418037c7e0d3c0
ae27390fb9b4783b43ec8b4d17076e920b446379
/Pessoa.java
929f6b3e58b2e5326bf12e4ea0272562407c3fc3
[]
no_license
pliniojmo/java
994e9ebbe511277f522c0482ac648ddeb24fce27
4b6b441afbfea16a472b80a1808d78f9731b9d7c
refs/heads/main
2023-02-25T11:16:02.995992
2021-01-27T15:27:58
2021-01-27T15:27:58
333,464,023
0
0
null
null
null
null
UTF-8
Java
false
false
852
java
import java.time.LocalDate; import java.time.Period; public class Pessoa { private String nome; private LocalDate dataNascimento; public Pessoa (String nome, int ano, int mes, int dia){ this.nome = nome; this.dataNascimento = LocalDate.of(ano,mes,dia); } public int calcularIdade(){ return Period.between(dataNascimento,LocalDate.now()).getYears(); } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public LocalDate getDataNascimento() { return dataNascimento; } @Override public String toString() { return "Pessoa [ " + "nome ='" + nome + '\'' + ", Data de Nascimento= " + dataNascimento + ", Idade: " + calcularIdade() + " ]"; } }
[ "plinio.oliveira@gmail.com" ]
plinio.oliveira@gmail.com
d6416385cf8fa8c040cea804c19bb95282cafd42
c3997d32b83ce41e15e4b933113bf762e68da750
/2d-Array/TransposeMatrix.java
af9a34cd627a0faaff851955270920781cfbc926
[]
no_license
AdishiSood/Java
a9501d958cacbe3e8b05ebe1d3b11bfac43341ac
f3190be2f4e6d03988a05f80ead56a84764049d9
refs/heads/main
2023-04-29T12:26:53.450375
2021-05-19T13:49:44
2021-05-19T13:49:44
317,133,576
5
1
null
null
null
null
UTF-8
Java
false
false
1,182
java
/* Java Program to transpose matrix Converting rows of a matrix into columns and columns of a matrix into row is called transpose of a matrix. */ import java.util.Scanner; public class TransposeMatrix { public static void main(String args[]) { int i, j; System.out.println("Enter total rows and columns: "); Scanner s = new Scanner(System.in); int row = s.nextInt(); int column = s.nextInt(); int array[][] = new int[row][column]; System.out.println("Enter matrix:"); for(i = 0; i < row; i++) { for(j = 0; j < column; j++) { array[i][j] = s.nextInt(); System.out.print(" "); } } System.out.println("The above matrix before Transpose is "); for(i = 0; i < row; i++) { for(j = 0; j < column; j++) { System.out.print(array[i][j]+" "); } System.out.println(" "); } System.out.println("The above matrix after Transpose is "); for(i = 0; i < column; i++) { for(j = 0; j < row; j++) { System.out.print(array[j][i]+" "); } System.out.println(" "); } } }
[ "noreply@github.com" ]
AdishiSood.noreply@github.com
3b8e9c7852a550bcb5e2ded0f0d1d458e1f1fb8b
31114997d93510ec15779e878fccad47a620564a
/go-mobiles/kingthy-back-order-pojo/src/main/java/com/kingthy/request/UpdateMaterielCategoryReq.java
3ca7b8080dd4e91999223ced45b43530bd68cad8
[]
no_license
stanvl/golang
f81bfc96a4a895e9c43c8080c8072b76edadae37
b62c084cd2e0d69216dadda7d48054bea5a2332e
refs/heads/master
2020-04-05T06:39:45.482345
2017-12-07T08:54:59
2017-12-07T08:54:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
487
java
package com.kingthy.request; import lombok.Data; import lombok.ToString; import java.io.Serializable; /** * UpdateMaterielCategoryReq(描述其作用) * <p> * @author 赵生辉 2017年07月14日 18:14 * * @version 1.0.0 */ @Data @ToString public class UpdateMaterielCategoryReq implements Serializable { private static final long serialVersionUID = 1L; private String className; private Boolean status; private String description; private String uuid; }
[ "xm.narutom@gmail.com" ]
xm.narutom@gmail.com
e1c1fe6527f83e91376e81474aee2c56ac9b1e3a
9f3771ce8228b47f57a33a56d12a03be82ad35cd
/aliyun-java-sdk-rsimganalys/src/main/java/com/aliyuncs/rsimganalys/model/v20190801/AccessTokenResponse.java
113b5dc914ef6f6a27079fe564d57ad44ec4068b
[ "Apache-2.0" ]
permissive
KononikhinDanila/aliyun-openapi-java-sdk
70fd4f0044e8edd701057e855d59453ae194d6bc
da6463926eb765e16e657399ea81cceb65ce8b99
refs/heads/master
2023-03-08T13:31:12.946303
2021-02-24T01:52:54
2021-02-24T01:52:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,442
java
/* * 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.aliyuncs.rsimganalys.model.v20190801; import com.aliyuncs.AcsResponse; import com.aliyuncs.rsimganalys.transform.v20190801.AccessTokenResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class AccessTokenResponse extends AcsResponse { private String requestId; private String data; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getData() { return this.data; } public void setData(String data) { this.data = data; } @Override public AccessTokenResponse getInstance(UnmarshallerContext context) { return AccessTokenResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
d89376a92c01903cfffe1265454d3f15605853b0
d67a1deeec4c50d1006ff20032ec0594fe9e50f6
/app/src/main/java/com/example/memoapp/MainActivity.java
7c601d866e31f5b7ba77ff8f30bc62c73758ba07
[]
no_license
komy00789/MemoApp
49e692834cc63716847082f8a997979364508183
178a648eee392e5367123b8b4c8a8520f7a972a7
refs/heads/master
2021-01-04T06:55:06.859229
2020-03-19T05:55:49
2020-03-19T05:55:49
240,438,921
0
0
null
null
null
null
UTF-8
Java
false
false
7,659
java
package com.example.memoapp; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * nyanさんの。リサイクラービューについて * https://akira-watson.com/android/recyclerview.html * Qiita.同じくリサイクラービューについて * https://qiita.com/naoi/items/f8a19d6278147e98bbc2 */ public class MainActivity extends AppCompatActivity { //Logcat private static final String TAG = "MainActivity"; // DatabaseHelperクラス宣言 static DatabaseHelper helper = null; // SimpleAdapter宣言 static SimpleAdapter adapter = null; // ArrayListの定義 static final ArrayList<Map<String, String>> memoList = new ArrayList<>(); // SELECT文 static String sql = "SELECT * FROM memo_DB"; // classの宣言 DeleteDialogFragment dialogFragment; // 再描画用フラグ boolean flag = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_floating); // フローティングボタン FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new FloatingButton()); // DBから値を取得 if (helper == null) { helper = new DatabaseHelper(this); } // DB処理 getDB(); flag = false; // ListViewの取得 ListView lv = findViewById(R.id.lv); // リスト項目をクリックした時の処理 lv.setOnItemClickListener(new ListItemClickListener()); // リスト項目を長押しクリックした時の処理 lv.setOnItemLongClickListener(new ListItemLongClickListener()); } /** * DB設定用メソッド */ public void getDB (){ //データベースを取得する SQLiteDatabase db = helper.getWritableDatabase(); // DB処理 try { // rawQueryでデータを取得 Cursor c = db.rawQuery(sql, null); // Cursorの先頭行があるかどうか確認、移動 boolean next = c.moveToFirst(); // 取得した全ての行を設定 while (next) { // 取得したカラムの順番(0から始まる)と型を指定してデータを取得する // String uuidNum = c.getString(1); String memoTxt = c.getString(2); String dayTxt = c.getString(3); // リストに表示するのは10文字まで // if(uuidNum.length() >= 10){ // uuidNum = uuidNum.substring(0, 11) + "..."; // } if (memoTxt.length() > 10){ memoTxt = memoTxt.substring(0, 11) + "..."; } // 値を設定 Map<String,String> data = new HashMap<>(); // data.put("uuid",uuidNum); data.put("date",dayTxt); data.put("memo",memoTxt); memoList.add(data); next = c.moveToNext(); } }catch (Exception e){ e.printStackTrace(); } finally { db.close(); } // SimpleAdapter生成 String[] from = {"memo","date"}; int[] to = {android.R.id.text1, android.R.id.text2}; adapter = new SimpleAdapter(this, memoList, android.R.layout.simple_list_item_2, from,to); // ListView取得 ListView lv = findViewById(R.id.lv); lv.setAdapter(adapter); } /** * MainActivityへ戻った際の処理 */ @Override protected void onResume() { super.onResume(); // Flagがtrueの際、処理が行われる if (flag) { // 画面情報の削除処理 memoList.clear(); // 再描画のため呼び出し getDB(); } flag = true; } /** * floatingButton用リスナ、画面遷移 */ private class FloatingButton implements View.OnClickListener { @Override public void onClick(View v) { // Intentの生成 Intent intent = new Intent(MainActivity.this, MemoActivity.class); intent.putExtra("uuid", ""); // 第2画面を起動 startActivity(intent); // トースト Toast.makeText(MainActivity.this, "新規作成", Toast.LENGTH_SHORT).show(); } } /** * リスト項目をクリックした時の処理 */ public class ListItemClickListener implements AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //データベースを取得する SQLiteDatabase db = helper.getWritableDatabase(); // rawQueryでデータを取得 Cursor c = db.rawQuery(sql, null); c.moveToFirst(); // 値の取得用変数の初期化 int count = 0; String getID = ""; String uuID = ""; String memoDb = ""; String dayDb = ""; // 値を取得 while (id+1 != count){ getID = c.getString(c.getColumnIndex("_id")); uuID = c.getString(c.getColumnIndex("uuid")); memoDb = c.getString(c.getColumnIndex("memo")); dayDb = c.getString(c.getColumnIndex("date")); count++; c.moveToNext(); } db.close(); // インテント作成 第二引数にはパッケージ名からの指定で、遷移先クラスを指定 Intent intent = new Intent(MainActivity.this, MemoActivity.class); intent.putExtra("_id", getID); intent.putExtra("uuid", uuID); intent.putExtra("memo", memoDb); // activityの起動 startActivity(intent); } } /** * リスト項目を長押しクリックした時削除する処理 */ public class ListItemLongClickListener implements AdapterView.OnItemLongClickListener{ @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { // FragmentManagerの取得 FragmentManager fragmentManager = getSupportFragmentManager(); // FragmentClassの初期化 dialogFragment = new DeleteDialogFragment(MainActivity.this, adapter,memoList,position); // ダイアログを表示 dialogFragment.show(fragmentManager, "DeleteDialogFragment"); // trueにすることで通常のクリックイベントを発生させない return true; } } }
[ "hatomugi00789@gmail.com" ]
hatomugi00789@gmail.com
8bf9869a56f2cea454dc29d97a7672483d66b6b4
59941f02133b3fcbc59312b2a1d51fabe1ce4136
/BASEDEDATOS/src/main/java/tata/db/Dato.java
b7869e1842007206f275080419c6959784253cf9
[]
no_license
felipepoblete/BASEDATOS
b1e3c3861c8994cf3abf241591a5ccdf4a58e5fd
9cb69f4d0bb7ce8c04e19842f5a75808f71b33fd
refs/heads/master
2022-02-06T09:32:53.614329
2019-07-02T21:20:14
2019-07-02T21:20:14
194,926,005
0
0
null
2022-01-21T23:26:33
2019-07-02T19:51:50
Java
UTF-8
Java
false
false
561
java
package tata.db; public class Dato { /**************** ATRIBUTOS *********************/ private String id; private Object data; /**************** CONSTRUCTORES *********************/ public Dato(String id, Object data) { this.id = id; this.data = data; } /**************** GETTERS Y SETTERS *********************/ public String getId() { return id; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public String toString() { return "Dato [id=" + id + ", data=" + data + "]"; } }
[ "felipepobletecarrasco@gmail.com" ]
felipepobletecarrasco@gmail.com
1863f4596c494454069e0451e2b597af0af351ad
5222ace285ecbe0d6a21d2c6b2c7a9f83d078d5b
/src/cn/ac/iscas/metrics/TaskMetricsImage.java
bcb7a94893d51871a35f0c2860b17308ea683d72
[]
no_license
JerryLead/PerformanceAnalysis
38beed4364c98370a7fde4f95287480798f5d686
a956f82fed44b001231086ca743530fb76fae8c5
refs/heads/master
2021-01-16T18:06:35.121347
2013-08-21T14:59:54
2013-08-21T14:59:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,943
java
package cn.ac.iscas.metrics; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import cn.ac.iscas.util.PNGTerminal; import com.panayotis.gnuplot.JavaPlot; import com.panayotis.gnuplot.dataset.GenericDataSet; import com.panayotis.gnuplot.plot.DataSetPlot; import com.panayotis.gnuplot.style.Style; public class TaskMetricsImage { public static List<ArrayList<String>> parse(File metricsFile) { List<ArrayList<String>> listlist = new ArrayList<ArrayList<String>>(); try { BufferedReader reader = new BufferedReader(new FileReader(metricsFile)); String line; while ((line = reader.readLine()) != null) { if (line.length() == 0 || line.charAt(0) == '#') continue; String parameters[] = line.trim().split("\\s+"); if (parameters.length == 16) // 16 parameters totally listlist.add(TaskMetrics.generateArrayList(parameters)); } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return listlist; } public static BufferedImage plotCpuAndIO(List<ArrayList<String>> list) { JavaPlot p = new JavaPlot(); p.setTitle("CPU and IO Metrics, PID = " + list.get(0).get(1)); p.getAxis("x").setLabel("Time (sec)");//, "Arial", 20); p.getAxis("y").setLabel("Utilization (%)"); p.set("xdata", "time"); p.set("timefmt", "'%H:%M:%S'"); p.set("format", "x '%M:%S'"); p.set("style", "data lines"); p.setKey(JavaPlot.Key.TOP_LEFT); GenericDataSet dataSet = new GenericDataSet(true); dataSet.addAll(list); DataSetPlot plot = new DataSetPlot(dataSet); plot.setTitle("usr"); plot.getPlotStyle().setStyle(Style.LINES); plot.set("using", "1:3"); p.addPlot(plot); plot = new DataSetPlot(dataSet); plot.setTitle("system"); plot.getPlotStyle().setStyle(Style.LINES); plot.set("using", "1:4"); p.addPlot(plot); //float[][] guest = transfer(list, 0, 4); //DataSetPlot guestPlot = new DataSetPlot(guest); //guestPlot.setTitle("guest"); //p.addPlot(guestPlot); plot = new DataSetPlot(dataSet); plot.setTitle("CPU"); plot.getPlotStyle().setStyle(Style.FILLEDCURVES); plot.set("using", "1:6"); plot.getPlotStyle().set("y1=0"); plot.getPlotStyle().set("lc", "rgb 'gray'"); p.addPlot(plot); p.set("y2label", "'Read/Write (KB)'"); p.set("ytics", "nomirror"); p.set("y2tics", ""); plot = new DataSetPlot(dataSet); plot.setTitle("kB_rd"); plot.getPlotStyle().setStyle(Style.LINES); plot.set("using", "1:13"); plot.getPlotStyle().setLineWidth(2); plot.set("axis x1y2"); p.addPlot(plot); plot = new DataSetPlot(dataSet); plot.setTitle("kB_wr"); plot.set("using", "1:14"); plot.getPlotStyle().setStyle(Style.LINES); plot.getPlotStyle().setLineWidth(2); plot.getPlotStyle().setLineType(7); plot.set("axis x1y2"); p.addPlot(plot); p.set("style", "fill transparent solid 0.2 noborder"); PNGTerminal t = new PNGTerminal(900, 480); p.setTerminal(t); p.setPersist(false); p.plot(); return t.getImage(); } public static BufferedImage plotMEM(List<ArrayList<String>> list) { JavaPlot p = new JavaPlot(); p.set("xdata", "time"); p.set("timefmt", "'%H:%M:%S'"); p.set("format", "x '%M:%S'"); p.set("style", "data lines"); p.setTitle("Memory Metrics, PID = " + list.get(0).get(1)); p.getAxis("x").setLabel("Time (sec)");//, "Arial", 20); p.getAxis("y").setLabel("Memory (MB)"); //p.getAxis("x").setBoundaries(0, list.get(list.size() - 1).getTime()); p.setKey(JavaPlot.Key.TOP_LEFT); GenericDataSet dataSet = new GenericDataSet(true); dataSet.addAll(list); DataSetPlot plot = new DataSetPlot(dataSet); plot.set("using", "1:10"); plot.setTitle("VSZ"); plot.getPlotStyle().setStyle(Style.LINES); plot.getPlotStyle().setLineWidth(2); p.addPlot(plot); plot = new DataSetPlot(dataSet); plot.set("using", "1:11"); plot.setTitle("RSS"); plot.getPlotStyle().setStyle(Style.LINES); plot.getPlotStyle().setLineWidth(2); p.addPlot(plot); PNGTerminal t = new PNGTerminal(); p.setTerminal(t); p.setPersist(false); p.plot(); return t.getImage(); } }
[ "leadxulijie@gmail.com" ]
leadxulijie@gmail.com
3dee5b9c2245a25e0b70b0669c8c36981b044d3c
694d574b989e75282326153d51bd85cb8b83fb9f
/google-ads/src/main/java/com/google/ads/googleads/v2/enums/UserListNumberRuleItemOperatorEnum.java
eb61df1a416711ff5da775f6c0ac365a763dbc78
[ "Apache-2.0" ]
permissive
tikivn/google-ads-java
99201ef20efd52f884d651755eb5a3634e951e9b
1456d890e5c6efc5fad6bd276b4a3cd877175418
refs/heads/master
2023-08-03T13:02:40.730269
2020-07-17T16:33:40
2020-07-17T16:33:40
280,845,720
0
0
Apache-2.0
2023-07-23T23:39:26
2020-07-19T10:51:35
null
UTF-8
Java
false
true
22,021
java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v2/enums/user_list_number_rule_item_operator.proto package com.google.ads.googleads.v2.enums; /** * <pre> * Supported rule operator for number type. * </pre> * * Protobuf type {@code google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum} */ public final class UserListNumberRuleItemOperatorEnum extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum) UserListNumberRuleItemOperatorEnumOrBuilder { private static final long serialVersionUID = 0L; // Use UserListNumberRuleItemOperatorEnum.newBuilder() to construct. private UserListNumberRuleItemOperatorEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UserListNumberRuleItemOperatorEnum() { } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private UserListNumberRuleItemOperatorEnum( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorProto.internal_static_google_ads_googleads_v2_enums_UserListNumberRuleItemOperatorEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorProto.internal_static_google_ads_googleads_v2_enums_UserListNumberRuleItemOperatorEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum.class, com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum.Builder.class); } /** * <pre> * Enum describing possible user list number rule item operators. * </pre> * * Protobuf enum {@code google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator} */ public enum UserListNumberRuleItemOperator implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ UNSPECIFIED(0), /** * <pre> * Used for return value only. Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ UNKNOWN(1), /** * <pre> * Greater than. * </pre> * * <code>GREATER_THAN = 2;</code> */ GREATER_THAN(2), /** * <pre> * Greater than or equal. * </pre> * * <code>GREATER_THAN_OR_EQUAL = 3;</code> */ GREATER_THAN_OR_EQUAL(3), /** * <pre> * Equals. * </pre> * * <code>EQUALS = 4;</code> */ EQUALS(4), /** * <pre> * Not equals. * </pre> * * <code>NOT_EQUALS = 5;</code> */ NOT_EQUALS(5), /** * <pre> * Less than. * </pre> * * <code>LESS_THAN = 6;</code> */ LESS_THAN(6), /** * <pre> * Less than or equal. * </pre> * * <code>LESS_THAN_OR_EQUAL = 7;</code> */ LESS_THAN_OR_EQUAL(7), UNRECOGNIZED(-1), ; /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ public static final int UNSPECIFIED_VALUE = 0; /** * <pre> * Used for return value only. Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ public static final int UNKNOWN_VALUE = 1; /** * <pre> * Greater than. * </pre> * * <code>GREATER_THAN = 2;</code> */ public static final int GREATER_THAN_VALUE = 2; /** * <pre> * Greater than or equal. * </pre> * * <code>GREATER_THAN_OR_EQUAL = 3;</code> */ public static final int GREATER_THAN_OR_EQUAL_VALUE = 3; /** * <pre> * Equals. * </pre> * * <code>EQUALS = 4;</code> */ public static final int EQUALS_VALUE = 4; /** * <pre> * Not equals. * </pre> * * <code>NOT_EQUALS = 5;</code> */ public static final int NOT_EQUALS_VALUE = 5; /** * <pre> * Less than. * </pre> * * <code>LESS_THAN = 6;</code> */ public static final int LESS_THAN_VALUE = 6; /** * <pre> * Less than or equal. * </pre> * * <code>LESS_THAN_OR_EQUAL = 7;</code> */ public static final int LESS_THAN_OR_EQUAL_VALUE = 7; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static UserListNumberRuleItemOperator valueOf(int value) { return forNumber(value); } public static UserListNumberRuleItemOperator forNumber(int value) { switch (value) { case 0: return UNSPECIFIED; case 1: return UNKNOWN; case 2: return GREATER_THAN; case 3: return GREATER_THAN_OR_EQUAL; case 4: return EQUALS; case 5: return NOT_EQUALS; case 6: return LESS_THAN; case 7: return LESS_THAN_OR_EQUAL; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<UserListNumberRuleItemOperator> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< UserListNumberRuleItemOperator> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<UserListNumberRuleItemOperator>() { public UserListNumberRuleItemOperator findValueByNumber(int number) { return UserListNumberRuleItemOperator.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum.getDescriptor().getEnumTypes().get(0); } private static final UserListNumberRuleItemOperator[] VALUES = values(); public static UserListNumberRuleItemOperator valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private UserListNumberRuleItemOperator(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator) } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum)) { return super.equals(obj); } com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum other = (com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Supported rule operator for number type. * </pre> * * Protobuf type {@code google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum) com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnumOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorProto.internal_static_google_ads_googleads_v2_enums_UserListNumberRuleItemOperatorEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorProto.internal_static_google_ads_googleads_v2_enums_UserListNumberRuleItemOperatorEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum.class, com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum.Builder.class); } // Construct using com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorProto.internal_static_google_ads_googleads_v2_enums_UserListNumberRuleItemOperatorEnum_descriptor; } @java.lang.Override public com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum getDefaultInstanceForType() { return com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum build() { com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum buildPartial() { com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum result = new com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum) { return mergeFrom((com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum other) { if (other == com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum) private static final com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum(); } public static com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UserListNumberRuleItemOperatorEnum> PARSER = new com.google.protobuf.AbstractParser<UserListNumberRuleItemOperatorEnum>() { @java.lang.Override public UserListNumberRuleItemOperatorEnum parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new UserListNumberRuleItemOperatorEnum(input, extensionRegistry); } }; public static com.google.protobuf.Parser<UserListNumberRuleItemOperatorEnum> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UserListNumberRuleItemOperatorEnum> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v2.enums.UserListNumberRuleItemOperatorEnum getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
[ "devchas@google.com" ]
devchas@google.com
c524a5051015891b253a2aad72bd1020194b947f
85edd183a4f394d3425d9a0f49b3258036839c20
/18_Algorithms/src/test/java/abstract_class/AbstractSortArrayClass.java
a59ef6f579db8e09d69dcb40afd0eae64fc587b7
[]
no_license
Timzmei/java_basics
962978275ec2b61d36af22877f0c5cf6065c74fe
d3072cf629b821723c9d9fb133e56bfaa7759064
refs/heads/master
2023-03-21T01:19:15.418982
2021-03-08T19:46:38
2021-03-08T19:46:38
345,752,573
1
0
null
null
null
null
UTF-8
Java
false
false
1,927
java
package abstract_class; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Random; public abstract class AbstractSortArrayClass { public abstract void sortArray(int[] array); @Test @DisplayName("Пустой массив") public void emptyArrayTest(){ int[] expected = new int[0]; int[] actual = new int[0]; sortArray(actual); Assertions.assertArrayEquals(expected, actual); } @Test @DisplayName("Не отсортированный случайный массив") public void unsortedArray(){ Random random = new Random(); int n = random.nextInt(100); int[] act = new int[n]; int[] exp = new int[n]; for (int i = 0; i < n; i++){ int val = random.nextInt(); act[i] = val; exp[i] = val; } sortArray(act); Arrays.sort(exp); Assertions.assertArrayEquals(exp, act); } @Test @DisplayName("Массив из одинаковых значений") public void sortedEqualsValueArray(){ int val = new Random().nextInt(); int n = 10; int[] act = new int[n]; int[] exp = new int[n]; for (int i = 0; i < n; i++) { act[i] = val; exp[i] = val; } sortArray(act); Assertions.assertArrayEquals(exp, act); } @Test @DisplayName("Отсортированный массив") public void sortedArray(){ int n = 10; int[] act = new int[n]; int[] exp = new int[n]; for (int i = 0; i < n; i++) { act[i] = i; exp[i] = i; } sortArray(act); Assertions.assertArrayEquals(exp, act); } }
[ "timur.guliev@gmail.com" ]
timur.guliev@gmail.com
4b306667c2d690b5a1f71fbd504b9e7e50cf627d
adf9c086845999bfcfd7b1b4778f46ef60d7c3f3
/reactor-tutorial/src/test/java/com/example/lesson/FluxSupplierTest.java
31c5915fc52b373bce22ad60a12687d09f116b3d
[ "Apache-2.0" ]
permissive
mike-neck/java-til
aec4b3c01bcfe4e5fcf6de938bbe045cfb2dec88
97829e7c519c5ee27b33b097042479c580694c38
refs/heads/master
2021-01-21T17:29:35.382313
2018-11-04T14:11:50
2018-11-04T14:11:50
91,956,578
0
0
null
null
null
null
UTF-8
Java
false
false
2,513
java
/* * Copyright 2018 Shinya Mochida * * Licensed under the Apache License,Version2.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.example.lesson; import com.example.ParameterSupplier; import com.example.annotations.Lesson; import com.example.lesson.api.FluxSupplier; import org.eclipse.collections.impl.factory.Iterables; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import reactor.test.StepVerifier; import java.time.Duration; import java.time.temporal.ChronoUnit; @Lesson(1) @ExtendWith({ ParameterSupplier.class }) class FluxSupplierTest { @Test void emptyFlux(final FluxSupplier fluxSupplier) { StepVerifier.create(fluxSupplier.emptyFlux()) .expectComplete() .verify(); } @Test void fromValues(final FluxSupplier fluxSupplier) { StepVerifier.create(fluxSupplier.fromValues("foo", "bar", "baz")) .expectNext("foo") .expectNext("bar") .expectNext("baz") .verifyComplete(); } @Test void fromIterable(final FluxSupplier fluxSupplier) { StepVerifier.create(fluxSupplier.fromIterable(Iterables.iList("foo", "bar", "baz"))) .expectNext("foo", "bar", "baz") .verifyComplete(); } @Test void error(final FluxSupplier fluxSupplier) { StepVerifier.create(fluxSupplier.error()) .expectError(IllegalStateException.class) .verify(); } @Test void interval(final FluxSupplier fluxSupplier) { StepVerifier.create(fluxSupplier.interval(10L, ChronoUnit.MILLIS)) .expectNext(0L) .thenAwait(Duration.ofMillis(10L)) .expectNext(1L) .thenAwait(Duration.ofMillis(10L)) .expectNextCount(8L) .verifyComplete(); StepVerifier.create(fluxSupplier.interval(100L, ChronoUnit.MILLIS)) .expectNextCount(10) .verifyComplete(); } }
[ "jkrt3333@gmail.com" ]
jkrt3333@gmail.com
505443036e02437eb83f9fbd91d2609d2004d481
d5b2f5a800d1aa977f6ecff91326cc6b9f118ced
/app/src/main/java/com/reframe/lapp/views/MainActivity.java
4711839362737000c8759bf087909ac50be19ebb
[]
no_license
jaambee/lapcode
9215ac1c96606f5596cabd0635b512ef6197eb6c
ee2b320f0c0672bf210c7f578d15e24ad35e2b25
refs/heads/master
2021-01-01T15:58:25.195639
2017-11-07T06:52:59
2017-11-07T06:53:00
97,748,648
0
0
null
null
null
null
UTF-8
Java
false
false
3,691
java
package com.reframe.lapp.views; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.view.ViewPager; import android.util.Log; import com.manaschaudhari.android_mvvm.ViewModel; import com.reframe.lapp.R; import com.reframe.lapp.adapters.MainNavigationAdapter; import com.reframe.lapp.base.BaseActivity; import com.reframe.lapp.constants.Notifications; import com.reframe.lapp.network.LappService; import com.reframe.lapp.viewmodels.MainViewModel; import com.reframe.lapp.views.main.EvaluationsFragment; import com.reframe.lapp.views.main.EvolutionFragment; import com.reframe.lapp.views.main.ProfileFragment; import com.reframe.lapp.views.main.TutorialFragment; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx_fcm.internal.RxFcm; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uploadDeviceToken(); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation); viewPager.setOffscreenPageLimit(4); MainNavigationAdapter adapter = new MainNavigationAdapter(this,getSupportFragmentManager()); adapter.addPage(TutorialFragment.newInstance()); adapter.addPage(EvaluationsFragment.newInstance()); adapter.addPage(EvolutionFragment.newInstance()); adapter.addPage(ProfileFragment.newInstance()); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (!bottomNavigationView.getMenu().getItem(viewPager.getCurrentItem()).isChecked()) bottomNavigationView.getMenu().getItem(viewPager.getCurrentItem()).setChecked(true); } @Override public void onPageScrollStateChanged(int state) { } }); bottomNavigationView.setOnNavigationItemSelectedListener(item -> { switch (item.getItemId()) { case R.id.action_tutorials: Log.d("MENU", "TUTORIALES"); viewPager.setCurrentItem(0); return true; case R.id.action_evaluations: Log.d("MENU", "EVALUACIONES"); viewPager.setCurrentItem(1); return true; case R.id.action_evolution: Log.d("MENU", "EVOLUCION"); viewPager.setCurrentItem(2); return true; case R.id.action_profile: Log.d("MENU", "PROFILE"); viewPager.setCurrentItem(3); return true; } return false; }); if(getIntent().getStringExtra("notification_type")!=null){ String type = getIntent().getStringExtra("notification_type"); if(type.equals(Notifications.NEW_LEVEL)) getNavigator().showSweetAlert("FELICITACIONES", "Haz subido de nivel!"); } } @NonNull @Override protected ViewModel createViewModel() { return new MainViewModel(getNavigator()); } @Override protected int getLayoutId() { return R.layout.activity_main; } }
[ "aldo@jaambee.com" ]
aldo@jaambee.com
e38d842a951633876378be014ff69f4be1895b4f
f46c7449e684be7a9c1e48b14d0911ee2d3f4822
/alura-dominando-collections/gerenciador-de-cursos/src/br/com/gerenciador/TestandoListas.java
710a65cf73eb7dc4a75629c8a2eadc7afa6a7b2f
[]
no_license
valbercarreiro/aulas_alura
fed3aeddbfe3e63cd5a71c1d16349fdde9d8d2fc
12f39c87e8e15a2005629ed641adf91e18618b5d
refs/heads/master
2020-04-04T04:03:48.194103
2017-03-31T18:41:33
2017-03-31T18:41:33
55,258,422
0
0
null
null
null
null
UTF-8
Java
false
false
1,254
java
/** * */ package br.com.gerenciador; import java.util.ArrayList; import java.util.Collections; /** * @author Valber Paulino * */ public class TestandoListas { public static void main(String[] args) { String aula1 = "Java 8: Tire proveito dos novos recursos da linguagem"; String aula2 = "Bootstrap: velocidade no front-end"; String aula3 = "Angular JS: crie webapps poderosas"; ArrayList<String> aulas = new ArrayList<>(); aulas.add(aula1); aulas.add(aula2); aulas.add(aula3); System.out.println(aulas); aulas.remove(0); System.out.println(aulas); for (String aula : aulas) { System.out.println("Aula: "+aula); } String primeiraAula = aulas.get(0); System.out.println("A primeira aula é: "+primeiraAula); aulas.forEach(aula -> { System.out.println("percorrendo :" + aula); }); aulas.add("Aumentando nosso conhecimento"); System.out.println(aulas); Collections.sort(aulas); System.out.println("Depois de ordenado: "+aulas); for(int i=0; i <= aulas.size(); i++){ System.out.println(aulas.get(i)); } } }
[ "valbercarreiro@gmail.com" ]
valbercarreiro@gmail.com
330e4eb5b4174d4ea55fa68b0cdbe6aa7038e58d
785f92468b22c5c2b11515d39a0972abba4b6acf
/fluent-mybatis/src/main/java/cn/org/atool/fluent/mybatis/base/splice/FreeWrapperHelper.java
a80d6a02c5ed3455ac2da3279de199f6fc825106
[ "Apache-2.0" ]
permissive
Akon1993/fluent-mybatis
13a195999da507cafd05dcd304f547e7c6561e74
0f72c6cad8e5044b210cbc1502c8a62db577c3d9
refs/heads/master
2023-08-03T02:29:14.085594
2021-09-13T14:43:24
2021-09-13T14:43:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,460
java
package cn.org.atool.fluent.mybatis.base.splice; import cn.org.atool.fluent.mybatis.base.model.FieldMapping; import cn.org.atool.fluent.mybatis.functions.IAggregate; import cn.org.atool.fluent.mybatis.segment.*; /** * FreeWrapperHelper * * @author darui.wu */ final class FreeWrapperHelper { public interface ISegment<R> { R set(FieldMapping fieldMapping); } /** * select字段设置 */ public static final class Selector extends SelectorBase<Selector, FreeQuery> implements ISegment<Selector> { public Selector(FreeQuery query) { super(query); } protected Selector(Selector selector, IAggregate aggregate) { super(selector, aggregate); } @Override protected Selector aggregateSegment(IAggregate aggregate) { return new Selector(this, aggregate); } public Selector avg(String column, String alias) { String _column = BaseWrapperHelper.appendAlias(column, super.wrapper); this.applyAs(String.format("AVG(%s)", _column), alias); return this; } public Selector sum(String column, String alias) { String _column = BaseWrapperHelper.appendAlias(column, super.wrapper); this.applyAs(String.format("SUM(%s)", _column), alias); return this; } public Selector max(String column, String alias) { String _column = BaseWrapperHelper.appendAlias(column, super.wrapper); this.applyAs(String.format("MAX(%s)", _column), alias); return this; } public Selector min(String column, String alias) { String _column = BaseWrapperHelper.appendAlias(column, super.wrapper); this.applyAs(String.format("MIN(%s)", _column), alias); return this; } } /** * query where条件设置 */ public static class QueryWhere extends WhereBase<QueryWhere, FreeQuery, FreeQuery> { public QueryWhere(FreeQuery query) { super(query); } private QueryWhere(FreeQuery query, QueryWhere where) { super(query, where); } @Override protected QueryWhere buildOr(QueryWhere and) { return new QueryWhere((FreeQuery) this.wrapper, and); } } /** * update where条件设置 */ public static class UpdateWhere extends WhereBase<UpdateWhere, FreeUpdate, FreeQuery> { public UpdateWhere(FreeUpdate updater) { super(updater); } private UpdateWhere(FreeUpdate updater, UpdateWhere where) { super(updater, where); } @Override protected UpdateWhere buildOr(UpdateWhere and) { return new UpdateWhere((FreeUpdate) this.wrapper, and); } } /** * 分组设置 */ public static final class GroupBy extends GroupByBase<GroupBy, FreeQuery> implements ISegment<GroupBy> { public GroupBy(FreeQuery query) { super(query); } } /** * 分组Having条件设置 */ public static final class Having extends HavingBase<Having, FreeQuery> implements ISegment<HavingOperator<Having>> { public Having(FreeQuery query) { super(query); } protected Having(Having having, IAggregate aggregate) { super(having, aggregate); } @Override protected Having aggregateSegment(IAggregate aggregate) { return new Having(this, aggregate); } } /** * Query OrderBy设置 */ public static final class QueryOrderBy extends OrderByBase<QueryOrderBy, FreeQuery> implements ISegment<OrderByApply<QueryOrderBy, FreeQuery>> { public QueryOrderBy(FreeQuery query) { super(query); } } /** * Update OrderBy设置 */ public static final class UpdateOrderBy extends OrderByBase<UpdateOrderBy, FreeUpdate> implements ISegment<OrderByApply<UpdateOrderBy, FreeUpdate>> { public UpdateOrderBy(FreeUpdate updater) { super(updater); } } /** * Update set 设置 */ public static final class UpdateSetter extends UpdateBase<UpdateSetter, FreeUpdate> implements ISegment<UpdateApply<UpdateSetter, FreeUpdate>> { public UpdateSetter(FreeUpdate updater) { super(updater); } } }
[ "darui.wu@163.com" ]
darui.wu@163.com
f59c251f5eefe73d33f908160304894b9203cf64
08163e25f2f3026ae2d203a4972b3d2bcbd571fe
/AdvKursM.f2/src/main/java/application/Payment.java
c9d38fac4f3e3fc1369fc2ddf7602d2473586a10
[]
no_license
RomanKalmutskiy/advCW
0d30283ad8dd2f11584f5c147c84be07bef2d9a9
ecbfd911757061ce4f88872fdf89ee65684488ec
refs/heads/master
2021-05-04T15:31:37.783236
2018-02-04T22:53:28
2018-02-04T22:53:28
120,230,616
0
0
null
null
null
null
UTF-8
Java
false
false
1,400
java
package application; import java.sql.Date; public class Payment { Date date1; Double elq; Double gq; Double hvq; Double cwq; Double ela; Double ga; Double hwa; Double cwa; public Payment(Date date1, Double elq, Double gq, Double hvq, Double cwq, Double ela, Double ga, Double hwa, Double cwa) { this.date1 = date1; this.elq = elq; this.gq = gq; this.hvq = hvq; this.cwq = cwq; this.ela = ela; this.ga = ga; this.hwa = hwa; this.cwa = cwa; } public Payment() { } public Date getDate1() { return date1; } public void setDate1(Date date1) { this.date1 = date1; } public Double getElq() { return elq; } public void setElq(Double elq) { this.elq = elq; } public Double getGq() { return gq; } public void setGq(Double gq) { this.gq = gq; } public Double getHvq() { return hvq; } public void setHvq(Double hvq) { this.hvq = hvq; } public Double getCwq() { return cwq; } public void setCwq(Double cwq) { this.cwq = cwq; } public Double getEla() { return ela; } public void setEla(Double ela) { this.ela = ela; } public Double getGa() { return ga; } public void setGa(Double ga) { this.ga = ga; } public Double getHwa() { return hwa; } public void setHwa(Double hwa) { this.hwa = hwa; } public Double getCwa() { return cwa; } public void setCwa(Double cwa) { this.cwa = cwa; } }
[ "roman.ak18@gmail.com" ]
roman.ak18@gmail.com
20ff4599d1705f66c8792ed484e571833b9b29e6
6a658c50856b2b21cc9eed63417b8d66886e76b6
/src/main/java/com/google/ical/compat/javautil/DateIteratorFactory.java
d7bfc6d703556f72713a688811e8c8fb20532c65
[ "Apache-2.0" ]
permissive
martinm1000/google-rfc-2445
6c8dcede3368b60b562741ebd782ab08a932f6d3
cb021a495d604d8ee2dce90f7ebb7320c1dd81e5
refs/heads/master
2021-07-17T12:50:50.720354
2021-03-21T03:26:07
2021-03-21T03:26:07
54,151,081
0
0
Apache-2.0
2021-03-21T03:26:08
2016-03-17T20:58:52
Java
UTF-8
Java
false
false
5,885
java
// Copyright (C) 2006 Google 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 com.google.ical.compat.javautil; import com.google.ical.iter.RecurrenceIterable; import com.google.ical.iter.RecurrenceIterator; import com.google.ical.iter.RecurrenceIteratorFactory; import com.google.ical.util.TimeUtils; import com.google.ical.values.DateTimeValueImpl; import com.google.ical.values.DateValue; import com.google.ical.values.DateValueImpl; import com.google.ical.values.TimeValue; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; /** * a factory for converting RRULEs and RDATEs into * <code>Iterator&lt;Date&gt;</code> and <code>Iterable&lt;Date&gt;</code>. * * @see RecurrenceIteratorFactory * * @author mikesamuel+svn@gmail.com (Mike Samuel) */ public class DateIteratorFactory { /** * given a block of RRULE, EXRULE, RDATE, and EXDATE content lines, parse * them into a single date iterator. * @param rdata RRULE, EXRULE, RDATE, and EXDATE lines. * @param start the first occurrence of the series. * @param tzid the local timezone -- used to interpret start and any dates in * RDATE and EXDATE lines that don't have TZID params. * @param strict true if any failure to parse should result in a * ParseException. false causes bad content lines to be logged and ignored. */ public static DateIterator createDateIterator( String rdata, Date start, TimeZone tzid, boolean strict) throws ParseException { return new RecurrenceIteratorWrapper( RecurrenceIteratorFactory.createRecurrenceIterator( rdata, dateToDateValue(start, true), tzid, strict)); } /** * given a block of RRULE, EXRULE, RDATE, and EXDATE content lines, parse * them into a single date iterable. * @param rdata RRULE, EXRULE, RDATE, and EXDATE lines. * @param start the first occurrence of the series. * @param tzid the local timezone -- used to interpret start and any dates in * RDATE and EXDATE lines that don't have TZID params. * @param strict true if any failure to parse should result in a * ParseException. false causes bad content lines to be logged and ignored. */ public static DateIterable createDateIterable( String rdata, Date start, TimeZone tzid, boolean strict) throws ParseException { return new RecurrenceIterableWrapper( RecurrenceIteratorFactory.createRecurrenceIterable( rdata, dateToDateValue(start, true), tzid, strict)); } /** * creates a date iterator given a recurrence iterator from * {@link com.google.ical.iter.RecurrenceIteratorFactory}. */ public static DateIterator createDateIterator(RecurrenceIterator rit) { return new RecurrenceIteratorWrapper(rit); } private static final class RecurrenceIterableWrapper implements DateIterable { private final RecurrenceIterable it; public RecurrenceIterableWrapper(RecurrenceIterable it) { this.it = it; } public DateIterator iterator() { return new RecurrenceIteratorWrapper(it.iterator()); } } private static final class RecurrenceIteratorWrapper implements DateIterator { private final RecurrenceIterator it; RecurrenceIteratorWrapper(RecurrenceIterator it) { this.it = it; } public boolean hasNext() { return it.hasNext(); } public Date next() { return dateValueToDate(it.next()); } public void remove() { throw new UnsupportedOperationException(); } public void advanceTo(Date d) { // we need to treat midnight as a date value so that passing in // dateValueToDate(<some-date-value>) will not advance past any // occurrences of some-date-value in the iterator. it.advanceTo(dateToDateValue(d, true)); } } static Date dateValueToDate(DateValue dvUtc) { GregorianCalendar c = new GregorianCalendar(TimeUtils.utcTimezone()); c.clear(); if (dvUtc instanceof TimeValue) { TimeValue tvUtc = (TimeValue) dvUtc; c.set(dvUtc.year(), dvUtc.month() - 1, // java.util's dates are zero-indexed dvUtc.day(), tvUtc.hour(), tvUtc.minute(), tvUtc.second()); } else { c.set(dvUtc.year(), dvUtc.month() - 1, // java.util's dates are zero-indexed dvUtc.day(), 0, 0, 0); } return c.getTime(); } static DateValue dateToDateValue(Date date, boolean midnightAsDate) { GregorianCalendar c = new GregorianCalendar(TimeUtils.utcTimezone()); c.setTime(date); int h = c.get(Calendar.HOUR_OF_DAY), m = c.get(Calendar.MINUTE), s = c.get(Calendar.SECOND); if (midnightAsDate && 0 == (h | m | s)) { return new DateValueImpl(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH)); } else { return new DateTimeValueImpl(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), h, m, s); } } private DateIteratorFactory() { // uninstantiable } }
[ "mikesamuel@fd5481be-f41e-0410-be1a-333349ab0b29" ]
mikesamuel@fd5481be-f41e-0410-be1a-333349ab0b29
ca8cca19a1c5cb32594a12431b3e26a1fc818b2c
49553c3ee27e6ce762ae3ca7e2751a2588cc78dd
/src/test/java/de/griesser/outfit/decider/impl/DmnOutfitDeciderTest.java
4dbcfbb13d055bbb4065f6679474061505e572b0
[]
no_license
nadegegriesser/outfit-service
c68b9b23666fb6e43d9e8546f13e6926690d8442
91f91107a2130aec9ef08c8b3aeae2471fc17d91
refs/heads/master
2020-04-11T15:57:42.283952
2019-01-31T19:17:15
2019-01-31T19:17:15
161,908,733
0
0
null
null
null
null
UTF-8
Java
false
false
1,984
java
package de.griesser.outfit.decider.impl; import de.griesser.outfit.decider.api.Decision; import de.griesser.outfit.decider.api.OutfitDecider; import de.griesser.outfit.decider.api.Variables; import de.griesser.outfit.decider.config.DeciderProperties; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class DmnOutfitDeciderTest { private static final String DECISION_FILENAME = "decision.dmn"; private static final String DECISION_KEY = "decision"; /* o Level 1: x > 26 °C o Level 2: 21 < x <= 26 °C o Level 3: 15 < x <= 21 °C o Level 4: 5 < x <= 15 °C o Level 5: x <= 5 °C */ @Parameters public static Collection<Object[]> data() { return Arrays.stream(new Object[][]{ {26.1d, 1}, {26d, 2}, {21.1d, 2}, {21d, 3}, {15.1d, 3}, {15d, 4}, {5.1d, 4}, {5d, 5} }).map(elem -> new Object[]{new Variables((double) elem[0]), new Decision((int) elem[1])}) .collect(Collectors.toList()); } private static OutfitDecider outfitDecider; private Variables variables; private Decision expectedDecision; public DmnOutfitDeciderTest(Variables variables, Decision decision) { this.variables = variables; this.expectedDecision = decision; } @BeforeClass public static void setUp() throws IOException { DeciderProperties props = new DeciderProperties(); props.setDecisionFilename(DECISION_FILENAME); props.setDecisionKey(DECISION_KEY); outfitDecider = new DmnOutfitDecider(props); } @Test public void test() { assertEquals(expectedDecision, outfitDecider.getDecision(variables)); } }
[ "nadege.griesser@1und1.de" ]
nadege.griesser@1und1.de
93afcbda260fccb3a660b3da2f3cf42d0dc015e9
ed08fab7286d20981402236623aaa4e760987652
/sso-sdk/src/main/java/com/zhaizq/sso/sdk/domain/SsoConfig.java
9a3bb28bccc7fa76397152149304f0812df4e754
[]
no_license
ggboy-shakalaka/sso
bd8a85ed2466f4b95d8a4d3f9e63835b9e4c1460
8c3645dc81ef1f10c196f08029a0efb454eb10f5
refs/heads/master
2023-05-28T08:05:55.227393
2023-03-01T12:52:17
2023-03-01T12:52:17
230,929,044
1
0
null
2023-05-23T20:16:37
2019-12-30T14:24:13
Java
UTF-8
Java
false
false
363
java
package com.zhaizq.sso.sdk.domain; import lombok.Data; @Data public class SsoConfig { private String server = "http://localhost:8080/api"; private String host = "http://localhost:8081"; private String setToken = "/setToken"; private String app = "demo"; private String privateKey = ""; private String[] ignore = {"/uncheck", "/api"}; }
[ "switch2018@outlook.com" ]
switch2018@outlook.com
29e6dd87e4c15f46f603757211562464d80062d9
b14592fcbee1557f9e54572cb27f4139c363d920
/src/main/java/br/com/auttar/common/errorhandling/GenericExceptionMapper.java
d567fcd24c216137854dac4a9ef0aef073860072
[]
no_license
eduardocastroouriques/java-ee-util
dc221bc25614ab998544ccdbafa8961eeb4a4308
a74c8666e855421edf621d5ca16ec5c86893c3a5
refs/heads/master
2021-05-13T11:40:04.525430
2018-07-31T17:27:59
2018-07-31T17:27:59
117,134,477
0
0
null
null
null
null
UTF-8
Java
false
false
1,723
java
package br.com.auttar.common.errorhandling; import java.io.PrintWriter; import java.io.StringWriter; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import br.com.auttar.common.constants.AppConstants; import br.com.auttar.common.constants.LogConstants; import br.com.auttar.common.model.ObjectDataModel; @Provider public class GenericExceptionMapper implements ExceptionMapper<Throwable> { private Logger logger = LogManager.getLogger(LogConstants.ERRORHANDLING_LOGGER_NAME); public GenericExceptionMapper(){} public Response toResponse(Throwable ex) { logger.error(ex.getMessage(), ex); ObjectDataModel<?> objectDataModel = new ObjectDataModel<>(); setHttpStatus(ex, objectDataModel); objectDataModel.setCode(AppConstants.RESPONSE_CODE_GENERIC_ERROR); objectDataModel.setMessage(ex.getMessage()); StringWriter errorStackTrace = new StringWriter(); ex.printStackTrace(new PrintWriter(errorStackTrace)); return Response.status(objectDataModel.getStatus()) .entity(objectDataModel) .type(MediaType.APPLICATION_JSON) .build(); } private void setHttpStatus(Throwable ex, ObjectDataModel<?> objectDataModel) { if(ex instanceof WebApplicationException ) { //NICE way to combine both of methods, say it in the blog objectDataModel.setStatus(((WebApplicationException)ex).getResponse().getStatus()); } else { objectDataModel.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); //defaults to internal server error 500 } } }
[ "eduardo.ouriques@ntconsult.com.br" ]
eduardo.ouriques@ntconsult.com.br
f6cf07722c1e51f1ee459c528eda028f1c8d301b
a33aac97878b2cb15677be26e308cbc46e2862d2
/data/libgdx/btGenericMemoryPool_setAllocated_sizes.java
c59d5c608e499a2608a61255a1bf9cdc1c7ceb06
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
168
java
public void setAllocated_sizes(SWIGTYPE_p_size_t value) { CollisionJNI.btGenericMemoryPool_allocated_sizes_set(swigCPtr, this, SWIGTYPE_p_size_t.getCPtr(value)); }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com
032857387f2a1de19894e6de5f3a123eab1a6a49
fc3bdb97041dfd651e51ebb4be9fb4304cfc6d34
/InsertionSort.java
f3c60cae1673b9f86695d2cc395d78dea644608a
[]
no_license
USF-CS245-09-2018/practice-assignment-04-xfeng23
c05cb94a9498dc75fb401caf9857d77c599d2593
33455dbafdb3542740f41c3feecc349c61ae83c4
refs/heads/master
2020-03-28T17:56:09.496106
2018-09-14T20:54:12
2018-09-14T20:54:12
148,837,176
0
0
null
null
null
null
UTF-8
Java
false
false
399
java
public class InsertionSort implements SortingAlgorithm { @Override public void sort(int[] a) { // TODO Auto-generated method stub for (int i = 1; i < a.length; i++) { int value = a[i]; int tempIndex = i; while (tempIndex > 0 && value < a[tempIndex - 1]) { a[tempIndex] = a[tempIndex - 1]; tempIndex = tempIndex - 1; } a[tempIndex] = value; } } }
[ "xfeng23@usfca.edu" ]
xfeng23@usfca.edu
bf61dd17ab706f44cd7309dc90b1e1f727a3240a
ddc1785ca20b71a444cb4a59ece8bc28bbb61b83
/src/main/java/pgrela/eulerproblem/problem65/ConvergentsOfE.java
0cefbe41d17fb27fe3a78e35dc14c0b5784b9bea
[]
no_license
pgrela/eulerproblem
9d9b35960d5645b4aca130d2f93f716440ad3d93
062c3bcf1786497f3d22cc988ac42d65c4a2ff9a
refs/heads/master
2021-01-22T03:39:33.259618
2019-04-23T14:59:40
2019-04-23T14:59:53
24,839,195
0
0
null
null
null
null
UTF-8
Java
false
false
1,137
java
package pgrela.eulerproblem.problem65; import pgrela.eulerproblem.common.EulerSolver; import java.math.BigDecimal; import java.util.Iterator; import java.util.stream.Stream; import static java.math.BigDecimal.valueOf; import static java.util.stream.IntStream.iterate; import static pgrela.eulerproblem.common.SolutionRunner.printSolution; public class ConvergentsOfE implements EulerSolver { public static void main(String[] args) { printSolution(ConvergentsOfE.class); } public long solve() { Iterator<BigDecimal> e = iterate(100, i -> i - 1).map(i -> i % 3 == 0 ? i / 3 * 2 : 1).mapToObj(BigDecimal::valueOf).iterator(); return Stream.iterate(factor(valueOf(1), valueOf(0)), p -> factor(p[0].multiply(e.next()).add(p[1]), p[0])) .skip(99) .map(p -> p[0].multiply(valueOf(2)).add(p[1])) .findFirst().get() .toString().chars() .map(a -> a - '0') .sum(); } BigDecimal[] factor(BigDecimal nominator, BigDecimal denominator) { return new BigDecimal[]{nominator, denominator}; } }
[ "patrykgrela@gmail.com" ]
patrykgrela@gmail.com
9eae7ab4a9eaf9314eb8c3126010b8a578a3248f
393ec5a3996084f5c2a64acd6ffc834f0cd458ee
/manager/workflow/src/org/kit/common/data/workinstruction/WorkInstruction.java
e7796e01424b2d695553c0153a81c0a8d9a85aa4
[ "MIT" ]
permissive
hasder/workflow
ee910ab13cb6d94526d18954fa67805e8d7ab823
66d9a1787a279fb176df67c35097ce4a1780eb9d
refs/heads/master
2021-05-10T17:41:32.012591
2018-06-10T10:27:42
2018-06-10T10:27:42
118,611,408
0
1
null
null
null
null
UTF-8
Java
false
false
2,544
java
package org.kit.common.data.workinstruction; import java.util.ArrayList; import org.kit.common.senml.SenMLPack; import org.kit.common.senml.SenMLRecord; import com.google.gson.Gson; public class WorkInstruction { String id; int type; int quantity; String description; EquipmentSpecification specification; public String toJsonString() { return new Gson().toJson(this); } public boolean fromJsonString(String json) { if(json != null) { WorkInstruction temp = new Gson().fromJson(json, WorkInstruction.class); this.id = temp.getId(); this.type = temp.getType(); this.quantity = temp.getQuantity(); this.description = temp.getDescription(); this.specification = temp.getSpecification(); } return true; } @SuppressWarnings("unused") private String toSenMLString() { SenMLPack senMLPack = new SenMLPack(); ArrayList<SenMLRecord> records = new ArrayList<SenMLRecord>(); records.add(new SenMLRecord("id", id)); records.add(new SenMLRecord("type", type)); //records.add(new SenMLRecord("specification", specification)); records.add(new SenMLRecord("quantity", quantity)); senMLPack.addRecords(records); return senMLPack.toJSON(); } @SuppressWarnings("unused") private boolean fromSenMLPack(String senMLString) { return fromSenMLPack(SenMLPack.fromJSON(senMLString)); } private boolean fromSenMLPack(SenMLPack senMLPack) { try { if(senMLPack != null) { id = senMLPack.getRecordByName("id").getVs(); type = senMLPack.getRecordByName("type").getV(); //specification = senMLPack.getRecordByName("specification").getVs(); quantity = senMLPack.getRecordByName("quantity").getV(); } else { return false; } } catch(Exception e) { //e.printStackTrace(); System.err.println("ERR: Invalid WorkInstruction!"); return false; } return true; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public EquipmentSpecification getSpecification() { return specification; } public void setSpecification(EquipmentSpecification specification) { this.specification = specification; } }
[ "hderhamy@gmail.com" ]
hderhamy@gmail.com
b9ac575e04a265354347f6983fea3a4c6c809ecf
8faa4b0928e25ede593d058a75f5dc6baca5be71
/src/main/java/com/mycompany/myapp/config/CacheConfiguration.java
54cb5c54dbc9df7dce924c697a342c70e0473387
[]
no_license
chinto0503/jhipster-sample-application
5d0d29c79ef1d43ed84efe316ca0c9974faa68b6
61fd8f7238ccce407fdaedcd2f96662e0303917e
refs/heads/main
2023-02-06T01:34:15.557881
2020-12-17T03:55:03
2020-12-17T03:55:03
322,174,204
0
0
null
2020-12-17T04:11:06
2020-12-17T03:54:41
Java
UTF-8
Java
false
false
5,651
java
package com.mycompany.myapp.config; import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.config.cache.PrefixedKeyGenerator; import java.net.URI; import java.util.concurrent.TimeUnit; import javax.cache.configuration.MutableConfiguration; import javax.cache.expiry.CreatedExpiryPolicy; import javax.cache.expiry.Duration; import org.hibernate.cache.jcache.ConfigSettings; import org.redisson.Redisson; import org.redisson.config.ClusterServersConfig; import org.redisson.config.Config; import org.redisson.config.SingleServerConfig; import org.redisson.jcache.configuration.RedissonConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer; import org.springframework.boot.info.BuildProperties; import org.springframework.boot.info.GitProperties; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.context.annotation.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableCaching public class CacheConfiguration { private GitProperties gitProperties; private BuildProperties buildProperties; @Bean public javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration(JHipsterProperties jHipsterProperties) { MutableConfiguration<Object, Object> jcacheConfig = new MutableConfiguration<>(); URI redisUri = URI.create(jHipsterProperties.getCache().getRedis().getServer()[0]); Config config = new Config(); if (jHipsterProperties.getCache().getRedis().isCluster()) { ClusterServersConfig clusterServersConfig = config .useClusterServers() .setMasterConnectionPoolSize(jHipsterProperties.getCache().getRedis().getConnectionPoolSize()) .setMasterConnectionMinimumIdleSize(jHipsterProperties.getCache().getRedis().getConnectionMinimumIdleSize()) .setSubscriptionConnectionPoolSize(jHipsterProperties.getCache().getRedis().getSubscriptionConnectionPoolSize()) .addNodeAddress(jHipsterProperties.getCache().getRedis().getServer()); if (redisUri.getUserInfo() != null) { clusterServersConfig.setPassword(redisUri.getUserInfo().substring(redisUri.getUserInfo().indexOf(':') + 1)); } } else { SingleServerConfig singleServerConfig = config .useSingleServer() .setConnectionPoolSize(jHipsterProperties.getCache().getRedis().getConnectionPoolSize()) .setConnectionMinimumIdleSize(jHipsterProperties.getCache().getRedis().getConnectionMinimumIdleSize()) .setSubscriptionConnectionPoolSize(jHipsterProperties.getCache().getRedis().getSubscriptionConnectionPoolSize()) .setAddress(jHipsterProperties.getCache().getRedis().getServer()[0]); if (redisUri.getUserInfo() != null) { singleServerConfig.setPassword(redisUri.getUserInfo().substring(redisUri.getUserInfo().indexOf(':') + 1)); } } jcacheConfig.setStatisticsEnabled(true); jcacheConfig.setExpiryPolicyFactory( CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, jHipsterProperties.getCache().getRedis().getExpiration())) ); return RedissonConfiguration.fromInstance(Redisson.create(config), jcacheConfig); } @Bean public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(javax.cache.CacheManager cm) { return hibernateProperties -> hibernateProperties.put(ConfigSettings.CACHE_MANAGER, cm); } @Bean public JCacheManagerCustomizer cacheManagerCustomizer(javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration) { return cm -> { createCache(cm, com.mycompany.myapp.repository.UserRepository.USERS_BY_LOGIN_CACHE, jcacheConfiguration); createCache(cm, com.mycompany.myapp.repository.UserRepository.USERS_BY_EMAIL_CACHE, jcacheConfiguration); createCache(cm, com.mycompany.myapp.domain.User.class.getName(), jcacheConfiguration); createCache(cm, com.mycompany.myapp.domain.Authority.class.getName(), jcacheConfiguration); createCache(cm, com.mycompany.myapp.domain.User.class.getName() + ".authorities", jcacheConfiguration); // jhipster-needle-redis-add-entry }; } private void createCache( javax.cache.CacheManager cm, String cacheName, javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration ) { javax.cache.Cache<Object, Object> cache = cm.getCache(cacheName); if (cache == null) { cm.createCache(cacheName, jcacheConfiguration); } } @Autowired(required = false) public void setGitProperties(GitProperties gitProperties) { this.gitProperties = gitProperties; } @Autowired(required = false) public void setBuildProperties(BuildProperties buildProperties) { this.buildProperties = buildProperties; } @Bean public KeyGenerator keyGenerator() { return new PrefixedKeyGenerator(this.gitProperties, this.buildProperties); } }
[ "jhipster-bot@jhipster.tech" ]
jhipster-bot@jhipster.tech
87b95a0ca13eba72fdce8574132ef329095b6b30
c1cf3c35ba95d6c0fa6ae785a224887ad4ed1eb8
/src/main/java/com/ljm/security/controller/HelloController.java
1535b94394b6998cc37b330a6c5887e43c8bee6b
[]
no_license
syhcgo/security
38d035e18aa0ce89ff3abd3ce310ed3239f2b5f4
9fd4e004f5caebc31e0ad95cd37679854f070c3f
refs/heads/master
2022-07-10T02:37:33.696170
2019-06-17T15:00:25
2019-06-17T15:00:25
188,652,610
0
0
null
2022-06-17T02:09:51
2019-05-26T07:24:25
Java
UTF-8
Java
false
false
301
java
package com.ljm.security.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "hello,man!"; } }
[ "qixiazhen@qq.com" ]
qixiazhen@qq.com
3f5dbb68c1a3b014724cdce719a11dc4839d6e8d
115dc60ff26a0b4ced2bb5b73cb0f291985459e7
/src/AssetList.java
cfa39b56effa7fde6748322f0dd521fee38f647e
[]
no_license
Kavindugayashan123/Fix-Assets-Management-Software
ba39c28704650cc4581878fd5d0667cd30e673f3
d4b72c270f5972d5ad9e94125612b96713669e76
refs/heads/master
2020-09-27T21:36:53.788299
2019-12-08T06:56:49
2019-12-08T06:56:49
226,615,174
1
0
null
null
null
null
UTF-8
Java
false
false
26,600
java
import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import java.util.Vector; import MyClasses.Database; import java.sql.ResultSet; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.time.LocalDate; import javax.swing.JOptionPane; import java.lang.NullPointerException; /* * 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 ASUS */ public class AssetList extends javax.swing.JFrame { Database db = new Database(); Database db2 = new Database(); /** * Creates new form AssetList */ public AssetList() { initComponents(); showAssembleAsset(); showDirectAsset(); ShowOndayTBLDetails(); ShowAnydayTBLDetails(); Date(); // showPrice(); } public void showDirectAsset(){ try { db.connection(); ResultSet rs1; String sql = "SELECT AssetNo,AssetName,purchased_date,Life_Time,price FROM direct_purchased"; rs1 = db.selectQuery(sql); while(rs1.next()) { String AssetNo = rs1.getString("AssetNo"); String AssetName = rs1.getString("AssetName"); String PurchasedDate = rs1.getString("purchased_date"); String price = rs1.getString("price"); String category = "Direct purchased"; String lifeTime = rs1.getString("Life_Time"); Object[] content = {AssetNo,AssetName,PurchasedDate,category,lifeTime,price}; DefaultTableModel model = (DefaultTableModel) JTable1.getModel(); model.addRow(content); }} catch(Exception e){ JOptionPane.showMessageDialog(null, e.getMessage()); } } public void showAssembleAsset(){ try{ db.connection(); ResultSet rs1; String sql = "SELECT AssetNo,AssetName,DateOfAssemble,Life_Time,totalPrice FROM assemble_asset"; rs1 = db.selectQuery(sql); while(rs1.next()) { String AssetNo = rs1.getString("AssetNo"); String AssetName = rs1.getString("AssetName"); String AssembledDate = rs1.getString("DateOfAssemble"); String category = "Assembled Asset"; String lifeTime = rs1.getString("Life_Time"); String totPrice = rs1.getString("totalPrice"); Object[] content = {AssetNo,AssetName,AssembledDate,category,lifeTime,totPrice}; DefaultTableModel model = (DefaultTableModel) JTable1.getModel(); model.addRow(content); } } catch(Exception e){ JOptionPane.showMessageDialog(null, e.getMessage()); } } public void Date(){ int rows = jTbleOnday.getRowCount(); for(int row = 0; row<rows; row++){ String pattern = "yyyy-MM-30"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat.format(new Date()); DefaultTableModel model = (DefaultTableModel)jTbleOnday.getModel(); model.setValueAt(date, row, 2); } } public void ShowOndayTBLDetails(){ int rows = JTable1.getRowCount(); for(int row = 0; row<rows; row++) { String AssetNo = (String)JTable1.getValueAt(row, 0); String AssetName = (String)JTable1.getValueAt(row, 1); DefaultTableModel model = (DefaultTableModel)jTbleOnday.getModel(); Object[] content = {AssetNo, AssetName}; model.addRow(content); }} public void ShowAnydayTBLDetails(){ int rows = JTable1.getRowCount(); for(int row = 0; row<rows; row++) { String AssetNo = (String)JTable1.getValueAt(row, 0); String AssetName = (String)JTable1.getValueAt(row, 1); DefaultTableModel model = (DefaultTableModel)jTbleAnyday.getModel(); Object[] content = {AssetNo, AssetName}; model.addRow(content); }} /** * * @param AssetNo * @param AssetName * @param PurchasedDate * @param price * @param category */ /* AssetList(String AssetNo, String AssetName, String PurchasedDate, String price, String category) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void showAssembledAssetList(String va1,String va2,String va3,String va4,String va5) { initComponents(); this.AssetNo=va1; this.AssetName=va2; this.PurchasedDate=va3; this.category=va4; this.price=va5; va4="Assemble Asset"; AddDataToTable(); } void AddDataToTable(){ DefaultTbaleModel dt = (DefaultTbaleModel) JTable1.getModel(); Vector v = new Vector(); v.add(AssetNo); v.add(AssetName); v.add(PurchasedDate); v.add(category); v.add(price); dt.addRow(v); }*/ /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); JTable1 = new javax.swing.JTable(); btnCalTotDep = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); btnBack = new javax.swing.JButton(); Logout = new javax.swing.JButton(); btnAssemble1 = new javax.swing.JButton(); btnDirect1 = new javax.swing.JButton(); btnAssetList = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTbleAnyday = new javax.swing.JTable(); jScrollPane3 = new javax.swing.JScrollPane(); jTbleOnday = new javax.swing.JTable(); jLabel4 = new javax.swing.JLabel(); DteChoser1 = new com.toedter.calendar.JDateChooser(); jTextField4 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); btnCalTotDep2 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); jLabel1.setFont(new java.awt.Font("Dialog", 1, 36)); // NOI18N jLabel1.setText("ASSET LIST"); getContentPane().add(jLabel1); jLabel1.setBounds(390, 10, 280, 50); JTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "AssetNo ", "AssetName", "Date", "Category", "Life Time", "Price" } ) { Class[] types = new Class [] { java.lang.Object.class, java.lang.Object.class, java.lang.Long.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane1.setViewportView(JTable1); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(40, 140, 850, 260); btnCalTotDep.setBackground(new java.awt.Color(0, 153, 153)); btnCalTotDep.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N btnCalTotDep.setText("Calculate Total Depreciate"); btnCalTotDep.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnCalTotDep.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCalTotDepActionPerformed(evt); } }); getContentPane().add(btnCalTotDep); btnCalTotDep.setBounds(40, 770, 210, 50); jPanel1.setBackground(new java.awt.Color(102, 102, 102)); jPanel1.setForeground(new java.awt.Color(102, 0, 204)); btnBack.setBackground(new java.awt.Color(153, 153, 153)); btnBack.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N btnBack.setText("Back"); btnBack.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBackActionPerformed(evt); } }); Logout.setBackground(new java.awt.Color(153, 153, 153)); Logout.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N Logout.setText("Logout"); Logout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LogoutActionPerformed(evt); } }); btnAssemble1.setBackground(new java.awt.Color(153, 153, 153)); btnAssemble1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N btnAssemble1.setText("Assemble Asset List"); btnAssemble1.setActionCommand("Assemble Asset list"); btnAssemble1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAssemble1ActionPerformed(evt); } }); btnDirect1.setBackground(new java.awt.Color(153, 153, 153)); btnDirect1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N btnDirect1.setText("Direct Purchased List"); btnDirect1.setActionCommand(""); btnDirect1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDirect1ActionPerformed(evt); } }); btnAssetList.setBackground(new java.awt.Color(153, 153, 153)); btnAssetList.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N btnAssetList.setText("Dispose Asset"); btnAssetList.setActionCommand(""); btnAssetList.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAssetListActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(btnBack, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(92, 92, 92) .addComponent(btnAssemble1) .addGap(102, 102, 102) .addComponent(btnDirect1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 129, Short.MAX_VALUE) .addComponent(btnAssetList, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(111, 111, 111) .addComponent(Logout, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(221, 221, 221)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Logout, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnAssetList, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnBack, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnAssemble1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnDirect1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) ); getContentPane().add(jPanel1); jPanel1.setBounds(-10, 70, 1320, 40); jButton3.setBackground(new java.awt.Color(153, 153, 153)); jButton3.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jButton3.setText("Save Asset List"); jButton3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); getContentPane().add(jButton3); jButton3.setBounds(900, 140, 150, 60); jTbleAnyday.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "AssetNo", "Asset Name", "Depreciate Amount" } )); jScrollPane2.setViewportView(jTbleAnyday); getContentPane().add(jScrollPane2); jScrollPane2.setBounds(740, 500, 540, 250); jTbleOnday.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "AssetNo", "Asset Name", "DepriciateDate", "Depreciate Amount" } )); jScrollPane3.setViewportView(jTbleOnday); getContentPane().add(jScrollPane3); jScrollPane3.setBounds(40, 500, 570, 250); jLabel4.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 153, 0)); jLabel4.setText("Select a Date"); getContentPane().add(jLabel4); jLabel4.setBounds(880, 450, 120, 30); getContentPane().add(DteChoser1); DteChoser1.setBounds(1030, 440, 250, 40); getContentPane().add(jTextField4); jTextField4.setBounds(510, 770, 100, 30); getContentPane().add(jTextField3); jTextField3.setBounds(1140, 770, 140, 30); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel5.setForeground(new java.awt.Color(204, 204, 0)); jLabel5.setText("Total Depreciate Amount"); getContentPane().add(jLabel5); jLabel5.setBounds(910, 770, 240, 30); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel6.setForeground(new java.awt.Color(204, 204, 0)); jLabel6.setText("Total Depreciate Amount"); getContentPane().add(jLabel6); jLabel6.setBounds(270, 760, 230, 50); btnCalTotDep2.setBackground(new java.awt.Color(0, 153, 153)); btnCalTotDep2.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N btnCalTotDep2.setText("Calculate Total Depreciate"); btnCalTotDep2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnCalTotDep2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCalTotDep2ActionPerformed(evt); } }); getContentPane().add(btnCalTotDep2); btnCalTotDep2.setBounds(700, 770, 210, 50); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/appvantage-digital-automotive-solutions-business-intelligence.jpg"))); // NOI18N getContentPane().add(jLabel2); jLabel2.setBounds(0, 0, 1310, 870); setSize(new java.awt.Dimension(1321, 908)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed new admin().setVisible(true); this.dispose(); }//GEN-LAST:event_btnBackActionPerformed private void LogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogoutActionPerformed new signup().setVisible(true); this.dispose(); }//GEN-LAST:event_LogoutActionPerformed private void btnCalTotDepActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCalTotDepActionPerformed DefaultTableModel model = (DefaultTableModel)JTable1.getModel(); int rows = JTable1.getRowCount(); try{ for(int row=0;row<=rows;row++){ String lifetime = (String) model.getValueAt(row, 4); int lifetimei = Integer.parseInt(lifetime ); String price = (String) model.getValueAt(row, 5); double pricei = Double.parseDouble(price); String date = (String)model.getValueAt(row, 2); DefaultTableModel model2 = (DefaultTableModel)jTbleOnday.getModel(); String Depdate = (String)model2.getValueAt(row, 2); DateFormat formatter; Date dd1; Date dd2; formatter = new SimpleDateFormat("yyyy-MM-dd"); dd1 = (Date)formatter.parse(date); dd2 = (Date)formatter.parse(Depdate); long diff = dd2.getTime() - dd1.getTime(); long sec = diff / 1000 % 60; long min = diff/(60*1000) % 60; long hours = diff /(60*60*1000); long days = hours/24; long months = days/30; //JOptionPane.showMessageDialog(null,days ); double amt; double tot = 0.0; amt =((pricei/(lifetimei*365))*days) ; double roundAmt = Math.round(amt*100)/100; String roundAmtS = String.valueOf(roundAmt); tot=tot+roundAmt; model2.setValueAt(roundAmtS, row, 3); String tots = String.valueOf(tot); jTextField4.setText(tots); } } catch(Exception e) { //JOptionPane.showMessageDialog(this,e.getMessage()); } }//GEN-LAST:event_btnCalTotDepActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed db.connection(); String txtVAlue = jTextField4.getText(); if("".equals(txtVAlue)){ JOptionPane.showMessageDialog(null,"Please Calculate On Month Depreciation"); } else{ try{ int rows = JTable1.getRowCount(); for(int row = 0; row<rows; row++) { String AssetNo = (String)JTable1.getValueAt(row, 0); String AssetName = (String)JTable1.getValueAt(row, 1); String date = (String)JTable1.getValueAt(row, 2); String category = (String)JTable1.getValueAt(row, 3); String price = (String)JTable1.getValueAt(row, 5); String DepDate = (String)jTbleOnday.getValueAt(row, 2); String DepAmt = (String)jTbleOnday.getValueAt(row, 3); String DepAmount = String.valueOf(DepAmt) ; // String wrkngPRogNo = jTextField2.getText(); String sql = "INSERT INTO depreciated_assetlist(AssetNo,AssetName,Date,Category,price,Depreciate_Date,Depreciate_Amt) VALUES('"+AssetNo+"','"+AssetName+"','"+date+"','"+category+"','"+price+"','"+DepDate+"','"+DepAmount+"')"; int i = db.updateQuery(sql); if(i>0) // {JOptionPane.showMessageDialog(null,"Successfully added!"); // } if(i<0) { JOptionPane.showMessageDialog(null,"Not entered"); } } for(int row = 0; row<rows; row++){ String AssetNo = (String)JTable1.getValueAt(row, 0); String AssetName = (String)JTable1.getValueAt(row, 1); String date = (String)JTable1.getValueAt(row, 2); String category = (String)JTable1.getValueAt(row, 3); String price = (String)JTable1.getValueAt(row, 5); String sql = "INSERT INTO assets_header_table(AssetNo,AssetName,Date,Category,price) VALUES('"+AssetNo+"','"+AssetName+"','"+date+"','"+category+"','"+price+"')"; int i = db.updateQuery(sql); if(i<0) { JOptionPane.showMessageDialog(null,"Not entered"); } } JOptionPane.showMessageDialog(null,"Successfully added!"); } catch(Exception e) { JOptionPane.showMessageDialog(this,e.getMessage()); }} }//GEN-LAST:event_jButton3ActionPerformed private void btnAssemble1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAssemble1ActionPerformed new AssembledAssetList().setVisible(true); this.dispose(); }//GEN-LAST:event_btnAssemble1ActionPerformed private void btnDirect1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDirect1ActionPerformed new DirectPurchasedAssetList().setVisible(true); this.dispose(); }//GEN-LAST:event_btnDirect1ActionPerformed private void btnAssetListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAssetListActionPerformed new dispose().setVisible(true); this.dispose(); }//GEN-LAST:event_btnAssetListActionPerformed private void btnCalTotDep2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCalTotDep2ActionPerformed DefaultTableModel model = (DefaultTableModel)JTable1.getModel(); int rows = JTable1.getRowCount(); try{ for(int row=0;row<=rows;row++){ String lifetime = (String) model.getValueAt(row, 4); int lifetimei = Integer.parseInt(lifetime ); String price = (String) model.getValueAt(row, 5); double pricei = Double.parseDouble(price); String date = (String)model.getValueAt(row, 2); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String Depdate = sdf.format(DteChoser1.getDate()); DefaultTableModel model2 = (DefaultTableModel)jTbleAnyday.getModel(); // String Depdatei = (String)model2.getValueAt(row, 2); DateFormat formatter; Date dd1; Date dd2; formatter = new SimpleDateFormat("yyyy-MM-dd"); dd1 = (Date)formatter.parse(date); dd2 = (Date)formatter.parse(Depdate); long diff = dd2.getTime() - dd1.getTime(); long sec = diff / 1000 % 60; long min = diff/(60*1000) % 60; long hours = diff /(60*60*1000); long days = hours/24; long months = days/30; //JOptionPane.showMessageDialog(null,days ); double amt; double tot = 0.0; amt =((pricei/(lifetimei*365))*days) ; double roundAmt = Math.round(amt*100)/100; String roundAmtS = String.valueOf(roundAmt); model2.setValueAt(roundAmtS, row, 2); tot=tot+roundAmt; String tots = String.valueOf(tot); jTextField3.setText(tots); } } catch(Exception e) { //JOptionPane.showMessageDialog(this,e.getMessage()); } }//GEN-LAST:event_btnCalTotDep2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AssetList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AssetList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AssetList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AssetList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AssetList().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private com.toedter.calendar.JDateChooser DteChoser1; public javax.swing.JTable JTable1; private javax.swing.JButton Logout; private javax.swing.JButton btnAssemble1; private javax.swing.JButton btnAssetList; private javax.swing.JButton btnBack; private javax.swing.JButton btnCalTotDep; private javax.swing.JButton btnCalTotDep2; private javax.swing.JButton btnDirect1; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JTable jTbleAnyday; private javax.swing.JTable jTbleOnday; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; // End of variables declaration//GEN-END:variables }
[ "noreply@github.com" ]
Kavindugayashan123.noreply@github.com