blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
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
684M
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
132 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
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
cd10c6329a85a6f9658dd667a8f0feca8aa62c4a
2e570d6dcabfd987a6413dc84e3015073d9f918c
/src/DVD.java
cab0c64fc82f9ca361d3e03f869ab1331e210bd2
[]
no_license
iskandarbestprogrammer/universalPult1
d5ec459d54a97efc27917187f5f287c31616eb4b
b2976c183030bca209df182b65662b2d7869267f
refs/heads/master
2021-09-28T00:53:12.032817
2018-11-13T00:33:56
2018-11-13T00:33:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
140
java
public class DVD extends Device { public DVD(String name, String model,boolean zustand ){ super ( name, model,false); } }
[ "iskandarchik1995@gmail.com" ]
iskandarchik1995@gmail.com
99592a4a6b24a513bae5619b39321d9276af7fb2
ddf0d861a600e9271198ed43be705debae15bafd
/CompetitiveProgrammingSolution/Implementation/MXMEDIAN.java
f4718cd0e54b0629eb572e776371aa54b504fa30
[]
no_license
bibhuty-did-this/MyCodes
79feea385b055edc776d4a9d5aedbb79a9eb55f4
2b8c1d4bd3088fc28820145e3953af79417c387f
refs/heads/master
2023-02-28T09:20:36.500579
2021-02-07T17:17:54
2021-02-07T17:17:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
682
java
/** * Author: o_panda_o * Email: emailofpanda@yahoo.com */ import java.util.Arrays; import java.util.Scanner; public class MXMEDIAN { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t=in.nextInt(); while(t-->0){ int n=in.nextInt(); int a[]=new int[2*n+1]; for(int i=1;i<=2*n;++i) a[i]=in.nextInt(); Arrays.sort(a,1,2*n+1); System.out.println(a[n+(n+1)/2]); for(int i=1;i<=n;++i){ System.out.print(a[i]+" "+a[n+i]+" "); } System.out.println(); } } }
[ "bibhuty.nit@gmail.com" ]
bibhuty.nit@gmail.com
213b0bac288603f01a7a9483a4d7d82818a31592
c08bed806e621d9c0813ec3f2e8fd4566ece9ad6
/src/com/makina/collect/android/activities/FormEntryActivity.java
601f8343fd9f149dc87ce29d437ebf0bfc6ca01a
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "Apache-2.0" ]
permissive
guisalmon/ODK_collect
b3ae726dabdf0639e8c71d279cae87f225f8c5a7
f6a807e8b9eb7d4e043a1c182e441e0b3fd5e493
refs/heads/master
2021-01-17T06:19:11.012426
2013-07-22T16:13:37
2013-07-22T16:13:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
84,170
java
/* * Copyright (C) 2009 University of Washington * * 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.makina.collect.android.activities; import java.io.File; import java.io.FileFilter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.Locale; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.form.api.FormEntryCaption; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.model.xform.XFormsModule; import org.javarosa.xpath.XPathTypeMismatchException; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.provider.MediaStore.MediaColumns; import android.text.InputFilter; import android.text.Spanned; import android.util.DisplayMetrics; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.makina.collect.android.R; import com.makina.collect.android.application.Collect; import com.makina.collect.android.listeners.AdvanceToNextListener; import com.makina.collect.android.listeners.FormLoaderListener; import com.makina.collect.android.listeners.FormSavedListener; import com.makina.collect.android.listeners.WidgetAnsweredListener; import com.makina.collect.android.logic.FormController; import com.makina.collect.android.logic.FormController.FailedConstraint; import com.makina.collect.android.logic.PropertyManager; import com.makina.collect.android.preferences.AdminPreferencesActivity; import com.makina.collect.android.preferences.PreferencesActivity; import com.makina.collect.android.provider.FormsProviderAPI.FormsColumns; import com.makina.collect.android.provider.InstanceProviderAPI; import com.makina.collect.android.provider.InstanceProviderAPI.InstanceColumns; import com.makina.collect.android.tasks.FormLoaderTask; import com.makina.collect.android.tasks.SaveToDiskTask; import com.makina.collect.android.utilities.FileUtils; import com.makina.collect.android.utilities.MediaUtils; import com.makina.collect.android.views.ODKView; import com.makina.collect.android.widgets.QuestionWidget; /** * FormEntryActivity is responsible for displaying questions, animating * transitions between questions, and allowing the user to enter data. * * @author Carl Hartung (carlhartung@gmail.com) */ public class FormEntryActivity extends SherlockActivity implements AnimationListener, FormLoaderListener, FormSavedListener, AdvanceToNextListener, OnGestureListener, WidgetAnsweredListener { private static final String t = "FormEntryActivity"; // save with every swipe forward or back. Timings indicate this takes .25 // seconds. // if it ever becomes an issue, this value can be changed to save every n'th // screen. private static final int SAVEPOINT_INTERVAL = 1; // Defines for FormEntryActivity private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private static final boolean EVALUATE_CONSTRAINTS = true; private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false; // Request codes for returning data from specified intent. public static final int IMAGE_CAPTURE = 1; public static final int BARCODE_CAPTURE = 2; public static final int AUDIO_CAPTURE = 3; public static final int VIDEO_CAPTURE = 4; public static final int LOCATION_CAPTURE = 5; public static final int HIERARCHY_ACTIVITY = 6; public static final int IMAGE_CHOOSER = 7; public static final int AUDIO_CHOOSER = 8; public static final int VIDEO_CHOOSER = 9; public static final int EX_STRING_CAPTURE = 10; public static final int EX_INT_CAPTURE = 11; public static final int EX_DECIMAL_CAPTURE = 12; public static final int DRAW_IMAGE = 13; public static final int SIGNATURE_CAPTURE = 14; public static final int ANNOTATE_IMAGE = 15; // Extra returned from gp activity public static final String LOCATION_RESULT = "LOCATION_RESULT"; public static final String KEY_INSTANCES = "instances"; public static final String KEY_SUCCESS = "success"; public static final String KEY_ERROR = "error"; // Identifies the gp of the form used to launch form entry public static final String KEY_FORMPATH = "formpath"; // Identifies whether this is a new form, or reloading a form after a screen // rotation (or similar) private static final String NEWFORM = "newform"; // these are only processed if we shut down and are restoring after an // external intent fires public static final String KEY_INSTANCEPATH = "instancepath"; public static final String KEY_XPATH = "xpath"; public static final String KEY_XPATH_WAITING_FOR_DATA = "xpathwaiting"; private static final int MENU_LANGUAGES = Menu.FIRST; private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1; private static final int MENU_SAVE = Menu.FIRST + 2; private static final int PROGRESS_DIALOG = 1; private static final int SAVING_DIALOG = 2; // Random ID private static final int DELETE_REPEAT = 654321; private String mFormPath; private GestureDetector mGestureDetector; private Animation mInAnimation; private Animation mOutAnimation; private ScrollView mStaleView = null; private LinearLayout mQuestionHolder; private ScrollView mCurrentView; private AlertDialog mAlertDialog; private ProgressDialog mProgressDialog; private String mErrorMessage; private Menu menu; private int mY; // used to limit forward/backward swipes to one per question private boolean mBeenSwiped = false; private int viewCount = 0; private FormLoaderTask mFormLoaderTask; private SaveToDiskTask mSaveToDiskTask; private ImageButton mNextButton; private ImageButton mBackButton; private boolean mAnswersChanged; private boolean mToFormChooser; enum AnimationType { LEFT, RIGHT, FADE, NONE } private SharedPreferences mAdminPreferences; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i("FormEntryActivity", "onCreate"); // must be at the beginning of any activity that can be called from an // external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.form_entry); setTitle(getString(R.string.loading_form)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Intent intent = getIntent(); if (intent != null && intent.getExtras() != null) { if (intent.hasExtra("newForm")){ mToFormChooser = true; } }else{ mToFormChooser = false; } mBeenSwiped = false; mAlertDialog = null; mCurrentView = null; mInAnimation = null; mOutAnimation = null; mGestureDetector = new GestureDetector(this); mQuestionHolder = (LinearLayout) findViewById(R.id.questionholder); // get admin preference settings mAdminPreferences = getSharedPreferences( AdminPreferencesActivity.ADMIN_PREFERENCES, 0); mNextButton = (ImageButton) findViewById(R.id.form_forward_button); mNextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBeenSwiped = true; showNextView(); } }); mBackButton = (ImageButton) findViewById(R.id.form_back_button); mBackButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBeenSwiped = true; showPreviousView(); } }); // Load JavaRosa modules. needed to restore forms. new XFormsModule().registerModule(); // needed to override rms property manager org.javarosa.core.services.PropertyManager .setPropertyManager(new PropertyManager(getApplicationContext())); String startingXPath = null; String waitingXPath = null; String instancePath = null; Boolean newForm = true; if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_FORMPATH)) { mFormPath = savedInstanceState.getString(KEY_FORMPATH); } if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) { instancePath = savedInstanceState.getString(KEY_INSTANCEPATH); } if (savedInstanceState.containsKey(KEY_XPATH)) { startingXPath = savedInstanceState.getString(KEY_XPATH); Log.i(t, "startingXPath is: " + startingXPath); } if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) { waitingXPath = savedInstanceState .getString(KEY_XPATH_WAITING_FOR_DATA); Log.i(t, "waitingXPath is: " + waitingXPath); } if (savedInstanceState.containsKey(NEWFORM)) { newForm = savedInstanceState.getBoolean(NEWFORM, true); } if (savedInstanceState.containsKey(KEY_ERROR)) { mErrorMessage = savedInstanceState.getString(KEY_ERROR); } } // If a parse error message is showing then nothing else is loaded // Dialogs mid form just disappear on rotation. if (mErrorMessage != null) { createErrorDialog(mErrorMessage, EXIT); return; } // Check to see if this is a screen flip or a new form load. Object data = getLastNonConfigurationInstance(); if (data instanceof FormLoaderTask) { mFormLoaderTask = (FormLoaderTask) data; } else if (data instanceof SaveToDiskTask) { mSaveToDiskTask = (SaveToDiskTask) data; } else if (data == null) { if (!newForm) { if (Collect.getInstance().getFormController() != null) { refreshCurrentView(); } else { Log.w(t, "Reloading form and restoring state."); // we need to launch the form loader to load the form // controller... mFormLoaderTask = new FormLoaderTask(instancePath, startingXPath, waitingXPath); Collect.getInstance().getActivityLogger() .logAction(this, "formReloaded", mFormPath); // TODO: this doesn' work (dialog does not get removed): // showDialog(PROGRESS_DIALOG); // show dialog before we execute... mFormLoaderTask.execute(mFormPath); } return; } // Not a restart from a screen orientation change (or other). Collect.getInstance().setFormController(null); if (intent != null) { Uri uri = intent.getData(); if (getContentResolver().getType(uri) == InstanceColumns.CONTENT_ITEM_TYPE) { // get the formId and version for this instance... String jrFormId = null; String jrVersion = null; { Cursor instanceCursor = null; try { instanceCursor = getContentResolver().query(uri, null, null, null, null); if (instanceCursor.getCount() != 1) { this.createErrorDialog("Bad URI: " + uri, EXIT); return; } else { instanceCursor.moveToFirst(); instancePath = instanceCursor .getString(instanceCursor .getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); Collect.getInstance() .getActivityLogger() .logAction(this, "instanceLoaded", instancePath); jrFormId = instanceCursor .getString(instanceCursor .getColumnIndex(InstanceColumns.JR_FORM_ID)); int idxJrVersion = instanceCursor .getColumnIndex(InstanceColumns.JR_VERSION); jrVersion = instanceCursor.isNull(idxJrVersion) ? null : instanceCursor .getString(idxJrVersion); } } finally { if (instanceCursor != null) { instanceCursor.close(); } } } String[] selectionArgs; String selection; if (jrVersion == null) { selectionArgs = new String[] { jrFormId }; selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + " IS NULL"; } else { selectionArgs = new String[] { jrFormId, jrVersion }; selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + "=?"; } { Cursor formCursor = null; try { formCursor = getContentResolver().query( FormsColumns.CONTENT_URI, null, selection, selectionArgs, null); if (formCursor.getCount() == 1) { formCursor.moveToFirst(); mFormPath = formCursor .getString(formCursor .getColumnIndex(FormsColumns.FORM_FILE_PATH)); } else if (formCursor.getCount() < 1) { this.createErrorDialog( getString( R.string.parent_form_not_present, jrFormId) + ((jrVersion == null) ? "" : "\n" + getString(R.string.version) + " " + jrVersion), EXIT); return; } else if (formCursor.getCount() > 1) { // still take the first entry, but warn that // there are multiple rows. // user will need to hand-edit the SQLite // database to fix it. formCursor.moveToFirst(); mFormPath = formCursor .getString(formCursor .getColumnIndex(FormsColumns.FORM_FILE_PATH)); this.createErrorDialog( "Multiple matching form definitions exist", DO_NOT_EXIT); } } finally { if (formCursor != null) { formCursor.close(); } } } } else if (getContentResolver().getType(uri) == FormsColumns.CONTENT_ITEM_TYPE) { Cursor c = null; try { c = getContentResolver().query(uri, null, null, null, null); if (c.getCount() != 1) { this.createErrorDialog("Bad URI: " + uri, EXIT); return; } else { c.moveToFirst(); mFormPath = c .getString(c .getColumnIndex(FormsColumns.FORM_FILE_PATH)); // This is the fill-blank-form code path. // See if there is a savepoint for this form that // has never been // explicitly saved // by the user. If there is, open this savepoint // (resume this filled-in // form). // Savepoints for forms that were explicitly saved // will be recovered // when that // explicitly saved instance is edited via // edit-saved-form. final String filePrefix = mFormPath.substring( mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')) + "_"; final String fileSuffix = ".xml.save"; File cacheDir = new File(Collect.CACHE_PATH); File[] files = cacheDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { String name = pathname.getName(); return name.startsWith(filePrefix) && name.endsWith(fileSuffix); } }); // see if any of these savepoints are for a // filled-in form that has never been // explicitly saved by the user... for (int i = 0; i < files.length; ++i) { File candidate = files[i]; String instanceDirName = candidate.getName() .substring( 0, candidate.getName().length() - fileSuffix.length()); File instanceDir = new File( Collect.INSTANCES_PATH + File.separator + instanceDirName); File instanceFile = new File(instanceDir, instanceDirName + ".xml"); if (instanceDir.exists() && instanceDir.isDirectory() && !instanceFile.exists()) { // yes! -- use this savepoint file instancePath = instanceFile .getAbsolutePath(); break; } } } } finally { if (c != null) { c.close(); } } } else { Log.e(t, "unrecognized URI"); this.createErrorDialog("unrecognized URI: " + uri, EXIT); return; } mFormLoaderTask = new FormLoaderTask(instancePath, null, null); Collect.getInstance().getActivityLogger() .logAction(this, "formLoaded", mFormPath); showDialog(PROGRESS_DIALOG); // show dialog before we execute... mFormLoaderTask.execute(mFormPath); } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_FORMPATH, mFormPath); FormController formController = Collect.getInstance() .getFormController(); if (formController != null) { outState.putString(KEY_INSTANCEPATH, formController .getInstancePath().getAbsolutePath()); outState.putString(KEY_XPATH, formController.getXPath(formController.getFormIndex())); FormIndex waiting = formController.getIndexWaitingForData(); if (waiting != null) { outState.putString(KEY_XPATH_WAITING_FOR_DATA, formController.getXPath(waiting)); } // save the instance to a temp path... SaveToDiskTask.blockingExportTempData(); } outState.putBoolean(NEWFORM, false); outState.putString(KEY_ERROR, mErrorMessage); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); FormController formController = Collect.getInstance() .getFormController(); if (formController == null) { // we must be in the midst of a reload of the FormController. // try to save this callback data to the FormLoaderTask if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) { mFormLoaderTask.setActivityResult(requestCode, resultCode, intent); } else { Log.e(t, "Got an activityResult without any pending form loader"); } return; } if (resultCode == RESULT_CANCELED) { // request was canceled... if (requestCode != HIERARCHY_ACTIVITY) { ((ODKView) mCurrentView).cancelWaitingForBinaryData(); } return; } switch (requestCode) { case BARCODE_CAPTURE: String sb = intent.getStringExtra("SCAN_RESULT"); ((ODKView) mCurrentView).setBinaryData(sb); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case EX_STRING_CAPTURE: String sv = intent.getStringExtra("value"); ((ODKView) mCurrentView).setBinaryData(sv); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case EX_INT_CAPTURE: Integer iv = intent.getIntExtra("value", 0); ((ODKView) mCurrentView).setBinaryData(iv); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case EX_DECIMAL_CAPTURE: Double dv = intent.getDoubleExtra("value", 0.0); ((ODKView) mCurrentView).setBinaryData(dv); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case DRAW_IMAGE: case ANNOTATE_IMAGE: case SIGNATURE_CAPTURE: case IMAGE_CAPTURE: /* * We saved the image to the tempfile_path, but we really want it to * be in: /sdcard/odk/instances/[current instnace]/something.jpg so * we move it there before inserting it into the content provider. * Once the android image capture bug gets fixed, (read, we move on * from Android 1.6) we want to handle images the audio and video */ // The intent is empty, but we know we saved the image to the temp // file File fi = new File(Collect.TMPFILE_PATH); String mInstanceFolder = formController.getInstancePath() .getParent(); String s = mInstanceFolder + File.separator + System.currentTimeMillis() + ".jpg"; File nf = new File(s); if (!fi.renameTo(nf)) { Log.e(t, "Failed to rename " + fi.getAbsolutePath()); } else { Log.i(t, "renamed " + fi.getAbsolutePath() + " to " + nf.getAbsolutePath()); } ((ODKView) mCurrentView).setBinaryData(nf); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case IMAGE_CHOOSER: /* * We have a saved image somewhere, but we really want it to be in: * /sdcard/odk/instances/[current instnace]/something.jpg so we move * it there before inserting it into the content provider. Once the * android image capture bug gets fixed, (read, we move on from * Android 1.6) we want to handle images the audio and video */ // get gp of chosen file String sourceImagePath = null; Uri selectedImage = intent.getData(); if (selectedImage.toString().startsWith("file")) { sourceImagePath = selectedImage.toString().substring(6); } else { String[] projection = { MediaColumns.DATA }; Cursor cursor = null; try { cursor = getContentResolver().query(selectedImage, projection, null, null, null); int column_index = cursor .getColumnIndexOrThrow(MediaColumns.DATA); cursor.moveToFirst(); sourceImagePath = cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } } // Copy file to sdcard String mInstanceFolder1 = formController.getInstancePath() .getParent(); String destImagePath = mInstanceFolder1 + File.separator + System.currentTimeMillis() + ".jpg"; File source = new File(sourceImagePath); File newImage = new File(destImagePath); FileUtils.copyFile(source, newImage); ((ODKView) mCurrentView).setBinaryData(newImage); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); if (formController.indexIsInFieldList()){ updateView(); } break; case AUDIO_CAPTURE: case VIDEO_CAPTURE: case AUDIO_CHOOSER: case VIDEO_CHOOSER: // For audio/video capture/chooser, we get the URI from the content // provider // then the widget copies the file and makes a new entry in the // content provider. Uri media = intent.getData(); ((ODKView) mCurrentView).setBinaryData(media); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); if (formController.indexIsInFieldList()){ updateView(); } break; case LOCATION_CAPTURE: String sl = intent.getStringExtra(LOCATION_RESULT); ((ODKView) mCurrentView).setBinaryData(sl); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case HIERARCHY_ACTIVITY: // We may have jumped to a new index in hierarchy activity, so // refresh break; } refreshCurrentView(); } /** * Refreshes the current view. the controller and the displayed view can get * out of sync due to dialogs and restarts caused by screen orientation * changes, so they're resynchronized here. */ public void refreshCurrentView() { FormController formController = Collect.getInstance() .getFormController(); int event = formController.getEvent(); // When we refresh, repeat dialog state isn't maintained, so step back // to the previous // question. // Also, if we're within a group labeled 'field list', step back to the // beginning of that // group. // That is, skip backwards over repeat prompts, groups that are not // field-lists, // repeat events, and indexes in field-lists that is not the containing // group. if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) { createRepeatDialog(); } else { ScrollView current = createView(event, false); showView(current, AnimationType.FADE); } //update menu cause of sherlock bar supportInvalidateOptionsMenu(); } @Override public boolean onCreateOptionsMenu(Menu menu) { System.out.println("FormEntryActivity : onCreateOptionsMenu"); getSupportMenuInflater().inflate(R.menu.menu_form_entry, menu); menu.add(0, 0, 0, getString(R.string.refresh)).setIcon( R.drawable.ic_menu_refresh).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); this.menu = menu; return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { FormController formController = Collect.getInstance() .getFormController(); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onPrepareOptionsMenu", "show"); menu.removeItem(MENU_LANGUAGES); menu.removeItem(MENU_HIERARCHY_VIEW); menu.removeItem(MENU_SAVE); if (mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_CHANGE_LANGUAGE, true)) { boolean enabled = false; if (formController != null) enabled = (formController.getLanguages() == null || formController .getLanguages().length == 1) ? false : true; menu.add(0, MENU_LANGUAGES, 0, getString(R.string.change_language)) .setIcon(R.drawable.ic_menu_start_conversation) .setEnabled(enabled); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { FormController formController = Collect.getInstance() .getFormController(); switch (item.getItemId()) { case 0: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "Refresh ODKView"); if (mCurrentView != null){ updateView(); } return true; case MENU_LANGUAGES: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_LANGUAGES"); createLanguageDialog(); return true; case R.id.save_form: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_SAVE"); // don't exit saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null); return true; case R.id.hierachy_view: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_HIERARCHY_VIEW"); if (formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY); return true; case R.id.preferences_entry: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_PREFERENCES"); Intent pref = new Intent(this, PreferencesActivity.class); startActivity(pref); return true; case android.R.id.home: // This is called when the Home (Up) button is pressed // in the Action Bar. Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit"); createQuitDialog(); return true; } return super.onOptionsItemSelected(item); } /** * Attempt to save the answer(s) in the current screen to into the data * model. * * @param evaluateConstraints * @return false if any error occurs while saving (constraint violated, * etc...), true otherwise. */ private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) { FormController formController = Collect.getInstance() .getFormController(); // only try to save if the current event is a question or a field-list // group if (formController.currentPromptIsQuestion()) { LinkedHashMap<FormIndex, IAnswerData> answers = ((ODKView) mCurrentView) .getAnswers(); FailedConstraint constraint = formController.saveAllScreenAnswers( answers, evaluateConstraints); if (constraint != null) { createConstraintToast(constraint.index, constraint.status); return false; } } return true; } /** * Clears the answer on the screen. */ private void clearAnswer(QuestionWidget qw) { if ( qw.getAnswer() != null) { qw.clearAnswer(); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onCreateContextMenu", "show"); FormController formController = Collect.getInstance() .getFormController(); menu.add(0, v.getId(), 0, getString(R.string.clear_answer)); if (formController.indexContainsRepeatableGroup()) { menu.add(0, DELETE_REPEAT, 0, getString(R.string.delete_repeat)); } menu.setHeaderTitle(getString(R.string.edit_prompt)); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { /* * We don't have the right view here, so we store the View's ID as the * item ID and loop through the possible views to find the one the user * clicked on. */ for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) { if (item.getItemId() == qw.getId()) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onContextItemSelected", "createClearDialog", qw.getPrompt().getIndex()); createClearDialog(qw); } } if (item.getItemId() == DELETE_REPEAT) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onContextItemSelected", "createDeleteRepeatConfirmDialog"); createDeleteRepeatConfirmDialog(); } return super.onContextItemSelected(item); } /** * If we're loading, then we pass the loading thread to our next instance. */ @Override public Object onRetainNonConfigurationInstance() { FormController formController = Collect.getInstance() .getFormController(); // if a form is loading, pass the loader task if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) return mFormLoaderTask; // if a form is writing to disk, pass the save to disk task if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED) return mSaveToDiskTask; // mFormEntryController is static so we don't need to pass it. if (formController != null && formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } return null; } /** * Creates a view given the View type and an event * * @param event * @param advancingPage * -- true if this results from advancing through the form * @return newly created View */ private ScrollView createView(int event, boolean advancingPage) { FormController formController = Collect.getInstance() .getFormController(); setTitle(getString(R.string.app_name) + " > " + formController.getFormTitle()); switch (event) { case FormEntryController.EVENT_BEGINNING_OF_FORM: ScrollView startView = (ScrollView) View .inflate(this, R.layout.form_entry_start, null); setTitle(getString(R.string.app_name) + " > " + formController.getFormTitle()); Drawable image = null; File mediaFolder = formController.getMediaFolder(); String mediaDir = mediaFolder.getAbsolutePath(); BitmapDrawable bitImage = null; // attempt to load the form-specific logo... // this is arbitrarily silly bitImage = new BitmapDrawable(mediaDir + File.separator + "form_logo.png"); if (bitImage != null && bitImage.getBitmap() != null && bitImage.getIntrinsicHeight() > 0 && bitImage.getIntrinsicWidth() > 0) { image = bitImage; } if (image == null) { // show the opendatakit zig... // image = // getResources().getDrawable(R.drawable.opendatakit_zig); ((ImageView) startView.findViewById(R.id.form_start_bling)) .setVisibility(View.GONE); } else { ImageView v = ((ImageView) startView .findViewById(R.id.form_start_bling)); v.setImageDrawable(image); v.setContentDescription(formController.getFormTitle()); } // change start screen based on navigation prefs String navigationChoice = PreferenceManager.getDefaultSharedPreferences(this).getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION); Boolean useSwipe = false; Boolean useButtons = false; ImageView ia = ((ImageView) startView.findViewById(R.id.image_advance)); TextView d = ((TextView) startView.findViewById(R.id.description)); if (navigationChoice != null) { if (navigationChoice.contains(PreferencesActivity.NAVIGATION_SWIPE)) { useSwipe = true; } if (navigationChoice.contains(PreferencesActivity.NAVIGATION_BUTTONS)) { useButtons = true; } } if (useSwipe && !useButtons) { d.setText(getString(R.string.swipe_instructions, formController.getFormTitle())); } else if (useButtons && !useSwipe) { ia.setVisibility(View.GONE); d.setText(getString(R.string.buttons_instructions, formController.getFormTitle())); } else { d.setText(getString(R.string.swipe_buttons_instructions, formController.getFormTitle())); } if (mBackButton.isShown()) { mBackButton.setEnabled(false); } if (mNextButton.isShown()) { mNextButton.setEnabled(true); } return startView; case FormEntryController.EVENT_END_OF_FORM: ScrollView endView = (ScrollView) View.inflate(this, R.layout.form_entry_end, null); ((TextView) endView.findViewById(R.id.description)) .setText(getString(R.string.save_enter_data_description, formController.getFormTitle())); // checkbox for if finished or ready to send final CheckBox instanceComplete = ((CheckBox) endView .findViewById(R.id.mark_finished)); instanceComplete.setChecked(isInstanceComplete(true)); if (!mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_MARK_AS_FINALIZED, true)) { instanceComplete.setVisibility(View.GONE); } // edittext to change the displayed name of the instance final EditText saveAs = (EditText) endView .findViewById(R.id.save_name); // disallow carriage returns in the name InputFilter returnFilter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (Character.getType((source.charAt(i))) == Character.CONTROL) { return ""; } } return null; } }; saveAs.setFilters(new InputFilter[] { returnFilter }); String saveName = formController.getSubmissionMetadata().instanceName; if (saveName == null) { //TODO Default saveAs text should be previous save name // no meta/instanceName field in the form -- see if we have a // name for this instance from a previous save attempt... if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) { Uri instanceUri = getIntent().getData(); Cursor instance = null; try { instance = getContentResolver().query(instanceUri, null, null, null, null); if (instance.getCount() == 1) { instance.moveToFirst(); saveName = instance .getString(instance .getColumnIndex(InstanceColumns.DISPLAY_NAME)); } } finally { if (instance != null) { instance.close(); } } } // present the prompt to allow user to name the form TextView sa = (TextView) endView .findViewById(R.id.save_form_as); sa.setVisibility(View.VISIBLE); // TODO if savename != null don"t need to initialize it if (saveName == null || saveName.length() == 0){ saveName = formController.getFormTitle(); } saveAs.setText(saveName); saveAs.setEnabled(true); saveAs.setVisibility(View.VISIBLE); } else { // if instanceName is defined in form, this is the name -- no // revisions // display only the name, not the prompt, and disable edits TextView sa = (TextView) endView .findViewById(R.id.save_form_as); sa.setVisibility(View.GONE); saveAs.setText(saveName); saveAs.setEnabled(false); saveAs.setBackgroundColor(Color.WHITE); saveAs.setVisibility(View.VISIBLE); } // override the visibility settings based upon admin preferences if (!mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_SAVE_AS, true)) { saveAs.setVisibility(View.GONE); TextView sa = (TextView) endView .findViewById(R.id.save_form_as); sa.setVisibility(View.GONE); } // Create 'save' button ((Button) endView.findViewById(R.id.save_exit_button)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance() .getActivityLogger() .logInstanceAction( this, "createView.saveAndExit", instanceComplete.isChecked() ? "saveAsComplete" : "saveIncomplete"); // Form is marked as 'saved' here. if (saveAs.getText().length() < 1) { Toast.makeText(FormEntryActivity.this, R.string.save_as_error, Toast.LENGTH_SHORT).show(); } else { saveDataToDisk(EXIT, instanceComplete .isChecked(), saveAs.getText() .toString()); } } }); if (mBackButton.isShown()) { mBackButton.setEnabled(true); } if (mNextButton.isShown()) { mNextButton.setEnabled(false); } return endView; case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_GROUP: case FormEntryController.EVENT_REPEAT: ODKView odkv = null; // should only be a group here if the event_group is a field-list try { FormEntryPrompt[] prompts = formController.getQuestionPrompts(); FormEntryCaption[] groups = formController .getGroupsForCurrentIndex(); odkv = new ODKView(this, this, formController.getQuestionPrompts(), groups, advancingPage); Log.i(t, "created view for group " + (groups.length > 0 ? groups[groups.length - 1] .getLongText() : "[top]") + " " + (prompts.length > 0 ? prompts[0] .getQuestionText() : "[no question]")); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); e.printStackTrace(); // this is badness to avoid a crash. event = formController.stepToNextScreenEvent(); return createView(event, advancingPage); } // Makes a "clear answer" menu pop up on long-click for (QuestionWidget qw : odkv.getWidgets()) { if (!qw.getPrompt().isReadOnly()) { registerForContextMenu(qw); } } if (mBackButton.isShown() && mNextButton.isShown()) { mBackButton.setEnabled(true); mNextButton.setEnabled(true); } return odkv; default: createErrorDialog("Internal error: step to prompt failed", EXIT); Log.e(t, "Attempted to create a view that does not exist."); // this is badness to avoid a crash. event = formController.stepToNextScreenEvent(); return createView(event, advancingPage); } } @Override public boolean dispatchTouchEvent(MotionEvent mv) { boolean handled = mGestureDetector.onTouchEvent(mv); if (!handled) { return super.dispatchTouchEvent(mv); } return handled; // this is always true } /** * Determines what should be displayed on the screen. Possible options are: * a question, an ask repeat dialog, or the submit screen. Also saves * answers to the data model after checking constraints. */ private void showNextView() { FormController formController = Collect.getInstance() .getFormController(); if (formController.currentPromptIsQuestion()) { if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) { // A constraint was violated so a dialog should be showing. mBeenSwiped = false; return; } } ScrollView next; int event = formController.stepToNextScreenEvent(); switch (event) { case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_GROUP: // create a savepoint if ((++viewCount) % SAVEPOINT_INTERVAL == 0) { SaveToDiskTask.blockingExportTempData(); } next = createView(event, true); showView(next, AnimationType.RIGHT); break; case FormEntryController.EVENT_END_OF_FORM: case FormEntryController.EVENT_REPEAT: next = createView(event, true); showView(next, AnimationType.RIGHT); break; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: createRepeatDialog(); break; case FormEntryController.EVENT_REPEAT_JUNCTURE: Log.i(t, "repeat juncture: " + formController.getFormIndex().getReference()); // skip repeat junctures until we implement them break; default: Log.w(t, "JavaRosa added a new EVENT type and didn't tell us... shame on them."); break; } } @Override public void updateView() { Log.i(getClass().getName(), "UpdateView " + Boolean.toString(mAnswersChanged)); FormController formController = Collect.getInstance() .getFormController(); if (formController.indexIsInFieldList()&&mAnswersChanged){ if (formController.currentPromptIsQuestion()) { if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) { // A constraint was violated so a dialog should be showing. return; } } ScrollView view = mCurrentView; mY = view.getScrollY(); ScrollView newView; int event = formController.getEvent(); switch (event) { case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_GROUP: // create a savepoint if ((++viewCount) % SAVEPOINT_INTERVAL == 0) { SaveToDiskTask.blockingExportTempData(); } newView = createView(event, true); showView(newView, AnimationType.NONE); break; case FormEntryController.EVENT_END_OF_FORM: case FormEntryController.EVENT_REPEAT: newView = createView(event, true); showView(newView, AnimationType.NONE); break; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: createRepeatDialog(); break; case FormEntryController.EVENT_REPEAT_JUNCTURE: Log.i(t, "repeat juncture: " + formController.getFormIndex().getReference()); // skip repeat junctures until we implement them break; default: Log.w(t, "JavaRosa added a new EVENT type and didn't tell us... shame on them."); break; } } } /** * Determines what should be displayed between a question, or the start * screen and displays the appropriate view. Also saves answers to the data * model without checking constraints. */ private void showPreviousView() { FormController formController = Collect.getInstance() .getFormController(); // The answer is saved on a back swipe, but question constraints are // ignored. if (formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } if (formController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) { int event = formController.stepToPreviousScreenEvent(); if (event == FormEntryController.EVENT_BEGINNING_OF_FORM || event == FormEntryController.EVENT_GROUP || event == FormEntryController.EVENT_QUESTION) { // create savepoint if ((++viewCount) % SAVEPOINT_INTERVAL == 0) { SaveToDiskTask.blockingExportTempData(); } } ScrollView next = createView(event, false); showView(next, AnimationType.LEFT); } else { mBeenSwiped = false; } } /** * Displays the View specified by the parameter 'next', animating both the * current view and next appropriately given the AnimationType. Also updates * the progress bar. */ public void showView(ScrollView next, AnimationType from) { if (from != AnimationType.NONE){ // disable notifications... if (mInAnimation != null) { mInAnimation.setAnimationListener(null); } if (mOutAnimation != null) { mOutAnimation.setAnimationListener(null); } // logging of the view being shown is already done, as this was handled // by createView() switch (from) { case RIGHT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out); break; case LEFT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out); break; case FADE: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out); break; } // complete setup for animations... mInAnimation.setAnimationListener(this); mOutAnimation.setAnimationListener(this); }else{ mInAnimation = null; mOutAnimation = null; } // drop keyboard before transition... if (mCurrentView != null) { InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(), 0); } RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); // adjust which view is in the layout container... mStaleView = mCurrentView; mCurrentView = next; mQuestionHolder.addView(mCurrentView, lp); mAnimationCompletionSet = 0; if (mStaleView != null) { if (from != AnimationType.NONE){ // start OutAnimation for transition... mStaleView.startAnimation(mOutAnimation); } // and remove the old view (MUST occur after start of animation!!!) mQuestionHolder.removeView(mStaleView); } else { mAnimationCompletionSet = 2; } // start InAnimation for transition... if (from != AnimationType.NONE){ mCurrentView.startAnimation(mInAnimation); } String logString = ""; switch (from) { case RIGHT: logString = "next"; break; case LEFT: logString = "previous"; break; case FADE: logString = "refresh"; break; case NONE: logString = "update"; break; } Log.e("FormEntryActivity", "scroll y : "+mY); mCurrentView.post(new Runnable() { public void run() { mCurrentView.scrollTo(0, mY); } }); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "showView", logString); } // Hopefully someday we can use managed dialogs when the bugs are fixed /* * Ideally, we'd like to use Android to manage dialogs with onCreateDialog() * and onPrepareDialog(), but dialogs with dynamic content are broken in 1.5 * (cupcake). We do use managed dialogs for our static loading * ProgressDialog. The main issue we noticed and are waiting to see fixed * is: onPrepareDialog() is not called after a screen orientation change. * http://code.google.com/p/android/issues/detail?id=1639 */ // /** * Creates and displays a dialog displaying the violated constraint. */ private void createConstraintToast(FormIndex index, int saveStatus) { FormController formController = Collect.getInstance() .getFormController(); String constraintText = formController.getQuestionPrompt(index) .getConstraintText(); switch (saveStatus) { case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createConstraintToast.ANSWER_CONSTRAINT_VIOLATED", "show", index); if (constraintText == null) { constraintText = formController.getQuestionPrompt(index) .getSpecialFormQuestionText("constraintMsg"); if (constraintText == null) { constraintText = getString(R.string.invalid_answer_error); } } break; case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createConstraintToast.ANSWER_REQUIRED_BUT_EMPTY", "show", index); constraintText = formController.getQuestionPrompt(index) .getSpecialFormQuestionText("requiredMsg"); if (constraintText == null) { constraintText = getString(R.string.required_answer_error); } break; } showCustomToast(constraintText, Toast.LENGTH_SHORT); } /** * Creates a toast with the specified message. * * @param message */ private void showCustomToast(String message, int duration) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_view, null); // set the text in the view TextView tv = (TextView) view.findViewById(R.id.message); tv.setText(message); Toast t = new Toast(this); t.setView(view); t.setDuration(duration); t.setGravity(Gravity.CENTER, 0, 0); t.show(); } /** * Creates and displays a dialog asking the user if they'd like to create a * repeat of the current group. */ private void createRepeatDialog() { FormController formController = Collect.getInstance() .getFormController(); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createRepeatDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); DialogInterface.OnClickListener repeatListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { FormController formController = Collect.getInstance() .getFormController(); switch (i) { case DialogInterface.BUTTON1: // yes, repeat Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createRepeatDialog", "addRepeat"); try { formController.newRepeat(); } catch (XPathTypeMismatchException e) { FormEntryActivity.this.createErrorDialog( e.getMessage(), EXIT); return; } if (!formController.indexIsInFieldList()) { // we are at a REPEAT event that does not have a // field-list appearance // step to the next visible field... // which could be the start of a new repeat group... showNextView(); } else { // we are at a REPEAT event that has a field-list // appearance // just display this REPEAT event's group. refreshCurrentView(); } break; case DialogInterface.BUTTON2: // no, no repeat Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createRepeatDialog", "showNext"); showNextView(); break; } } }; if (formController.getLastRepeatCount() > 0) { mAlertDialog.setTitle(getString(R.string.leaving_repeat_ask)); mAlertDialog.setMessage(getString(R.string.add_another_repeat, formController.getLastGroupText())); mAlertDialog.setButton(getString(R.string.add_another), repeatListener); mAlertDialog.setButton2(getString(R.string.leave_repeat_yes), repeatListener); } else { mAlertDialog.setTitle(getString(R.string.entering_repeat_ask)); mAlertDialog.setMessage(getString(R.string.add_repeat, formController.getLastGroupText())); mAlertDialog.setButton(getString(R.string.entering_repeat), repeatListener); mAlertDialog.setButton2(getString(R.string.add_repeat_no), repeatListener); } mAlertDialog.setCancelable(false); mBeenSwiped = false; mAlertDialog.show(); } /** * Creates and displays dialog with the given errorMsg. */ private void createErrorDialog(String errorMsg, final boolean shouldExit) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createErrorDialog", "show." + Boolean.toString(shouldExit)); mErrorMessage = errorMsg; mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setTitle(getString(R.string.error_occured)); mAlertDialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createErrorDialog", "OK"); if (shouldExit) { finish(); } break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), errorListener); mBeenSwiped = false; mAlertDialog.show(); } /** * Creates a confirm/cancel dialog for deleting repeats. */ private void createDeleteRepeatConfirmDialog() { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createDeleteRepeatConfirmDialog", "show"); FormController formController = Collect.getInstance() .getFormController(); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); String name = formController.getLastRepeatedGroupName(); int repeatcount = formController.getLastRepeatedGroupRepeatCount(); if (repeatcount != -1) { name += " (" + (repeatcount + 1) + ")"; } mAlertDialog.setTitle(getString(R.string.delete_repeat_ask)); mAlertDialog .setMessage(getString(R.string.delete_repeat_confirm, name)); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { FormController formController = Collect.getInstance() .getFormController(); switch (i) { case DialogInterface.BUTTON1: // yes Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createDeleteRepeatConfirmDialog", "OK"); formController.deleteRepeat(); showPreviousView(); break; case DialogInterface.BUTTON2: // no Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createDeleteRepeatConfirmDialog", "cancel"); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.discard_group), quitListener); mAlertDialog.setButton2(getString(R.string.delete_repeat_no), quitListener); mAlertDialog.show(); } /** * Saves data and writes it to disk. If exit is set, program will exit after * save completes. Complete indicates whether the user has marked the * instances as complete. If updatedSaveName is non-null, the instances * content provider is updated with the new name */ private boolean saveDataToDisk(boolean exit, boolean complete, String updatedSaveName) { // save current answer if (!saveAnswersForCurrentScreen(complete)) { Toast.makeText(this, getString(R.string.data_saved_error), Toast.LENGTH_SHORT).show(); return false; } mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName); mSaveToDiskTask.setFormSavedListener(this); showDialog(SAVING_DIALOG); // show dialog before we execute... mSaveToDiskTask.execute(); return true; } /** * Create a dialog with options to save and exit, save, or quit without * saving */ private void createQuitDialog() { FormController formController = Collect.getInstance() .getFormController(); String[] items; if (mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_MID, true)) { String[] two = { getString(R.string.keep_changes), getString(R.string.do_not_save) }; items = two; } else { String[] one = { getString(R.string.do_not_save) }; items = one; } Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createQuitDialog", "show"); mAlertDialog = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle( getString(R.string.quit_application, formController.getFormTitle())) .setNeutralButton(getString(R.string.do_not_exit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "cancel"); dialog.cancel(); } }) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // save and exit // this is slightly complicated because if the // option is disabled in // the admin menu, then case 0 actually becomes // 'discard and exit' // whereas if it's enabled it's 'save and exit' if (mAdminPreferences .getBoolean( AdminPreferencesActivity.KEY_SAVE_MID, true)) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "saveAndExit"); saveDataToDisk(EXIT, isInstanceComplete(false), null); } else { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "discardAndExit"); removeTempInstance(); finishReturnInstance(); } break; case 1: // discard changes and exit Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "discardAndExit"); removeTempInstance(); finishReturnInstance(); break; case 2:// do nothing Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "cancel"); break; } } }).create(); mAlertDialog.show(); } /** * this method cleans up unneeded files when the user selects 'discard and * exit' */ private void removeTempInstance() { FormController formController = Collect.getInstance() .getFormController(); // attempt to remove any scratch file File temp = SaveToDiskTask.savepointFile(formController .getInstancePath()); if (temp.exists()) { temp.delete(); } String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { formController.getInstancePath() .getAbsolutePath() }; boolean erase = false; { Cursor c = null; try { c = getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); erase = (c.getCount() < 1); } finally { if (c != null) { c.close(); } } } // if it's not already saved, erase everything if (erase) { // delete media first String instanceFolder = formController.getInstancePath() .getParent(); Log.i(t, "attempting to delete: " + instanceFolder); int images = MediaUtils .deleteImagesInFolderFromMediaProvider(formController .getInstancePath().getParentFile()); int audio = MediaUtils .deleteAudioInFolderFromMediaProvider(formController .getInstancePath().getParentFile()); int video = MediaUtils .deleteVideoInFolderFromMediaProvider(formController .getInstancePath().getParentFile()); Log.i(t, "removed from content providers: " + images + " image files, " + audio + " audio files," + " and " + video + " video files."); File f = new File(instanceFolder); if (f.exists() && f.isDirectory()) { for (File del : f.listFiles()) { Log.i(t, "deleting file: " + del.getAbsolutePath()); del.delete(); } f.delete(); } } } /** * Confirm clear answer dialog */ private void createClearDialog(final QuestionWidget qw) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createClearDialog", "show", qw.getPrompt().getIndex()); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setTitle(getString(R.string.clear_answer_ask)); String question = qw.getPrompt().getLongText(); if (question == null) { question = ""; } if (question.length() > 50) { question = question.substring(0, 50) + "..."; } mAlertDialog.setMessage(getString(R.string.clearanswer_confirm, question)); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: // yes Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createClearDialog", "clearAnswer", qw.getPrompt().getIndex()); clearAnswer(qw); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case DialogInterface.BUTTON2: // no Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createClearDialog", "cancel", qw.getPrompt().getIndex()); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog .setButton(getString(R.string.discard_answer), quitListener); mAlertDialog.setButton2(getString(R.string.clear_answer_no), quitListener); mAlertDialog.show(); } /** * Creates and displays a dialog allowing the user to set the language for * the form. */ private void createLanguageDialog() { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createLanguageDialog", "show"); FormController formController = Collect.getInstance() .getFormController(); final String[] languages = formController.getLanguages(); int selected = -1; if (languages != null) { String language = formController.getLanguage(); for (int i = 0; i < languages.length; i++) { if (language.equals(languages[i])) { selected = i; } } } mAlertDialog = new AlertDialog.Builder(this) .setSingleChoiceItems(languages, selected, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { FormController formController = Collect .getInstance().getFormController(); // Update the language in the content provider // when selecting a new // language ContentValues values = new ContentValues(); values.put(FormsColumns.LANGUAGE, languages[whichButton]); String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; int updated = getContentResolver().update( FormsColumns.CONTENT_URI, values, selection, selectArgs); Log.i(t, "Updated language to: " + languages[whichButton] + " in " + updated + " rows"); Collect.getInstance() .getActivityLogger() .logInstanceAction( this, "createLanguageDialog", "changeLanguage." + languages[whichButton]); formController .setLanguage(languages[whichButton]); dialog.dismiss(); if (formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } refreshCurrentView(); } }) .setTitle(getString(R.string.change_language)) .setNegativeButton(getString(R.string.do_not_change), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createLanguageDialog", "cancel"); } }).create(); mAlertDialog.show(); } /** * We use Android's dialog management for loading/saving progress dialogs */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case PROGRESS_DIALOG: Log.e(t, "Creating PROGRESS_DIALOG"); Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.PROGRESS_DIALOG", "show"); mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.PROGRESS_DIALOG", "cancel"); dialog.dismiss(); mFormLoaderTask.setFormLoaderListener(null); FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); finish(); } }; mProgressDialog.setIcon(android.R.drawable.ic_dialog_info); mProgressDialog.setTitle(getString(R.string.loading_form)); mProgressDialog.setMessage(getString(R.string.please_wait)); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.setButton(getString(R.string.cancel_loading_form), loadingButtonListener); return mProgressDialog; case SAVING_DIALOG: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.SAVING_DIALOG", "show"); mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener savingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.SAVING_DIALOG", "cancel"); dialog.dismiss(); mSaveToDiskTask.setFormSavedListener(null); SaveToDiskTask t = mSaveToDiskTask; mSaveToDiskTask = null; t.cancel(true); } }; mProgressDialog.setIcon(android.R.drawable.ic_dialog_info); mProgressDialog.setTitle(getString(R.string.saving_form)); mProgressDialog.setMessage(getString(R.string.please_wait)); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.setButton(getString(R.string.cancel), savingButtonListener); mProgressDialog.setButton(getString(R.string.cancel_saving_form), savingButtonListener); return mProgressDialog; } return null; } /** * Dismiss any showing dialogs that we manually manage. */ private void dismissDialogs() { Log.e(t, "Dismiss dialogs"); if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } } @Override protected void onPause() { FormController formController = Collect.getInstance() .getFormController(); dismissDialogs(); // make sure we're not already saving to disk. if we are, currentPrompt // is getting constantly updated if (mSaveToDiskTask == null || mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { if (mCurrentView != null && formController != null && formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } } super.onPause(); } @Override protected void onResume() { super.onResume(); FormController formController = Collect.getInstance() .getFormController(); Collect.getInstance().getActivityLogger().open(); if (mFormLoaderTask != null) { mFormLoaderTask.setFormLoaderListener(this); if (formController == null && mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { FormController fec = mFormLoaderTask.getFormController(); if (fec != null) { loadingComplete(mFormLoaderTask); } else { dismissDialog(PROGRESS_DIALOG); FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); // there is no formController -- fire MainMenu activity? startActivity(new Intent(this, MainMenuActivity.class)); } } } else { refreshCurrentView(); } if (mSaveToDiskTask != null) { mSaveToDiskTask.setFormSavedListener(this); } if (mErrorMessage != null && (mAlertDialog != null && !mAlertDialog.isShowing())) { createErrorDialog(mErrorMessage, EXIT); return; } // only check the buttons if it's enabled in preferences SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); String navigation = sharedPreferences.getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION); Boolean showButtons = false; if (navigation.contains(PreferencesActivity.NAVIGATION_BUTTONS)) { showButtons = true; } if (showButtons) { mBackButton.setVisibility(View.VISIBLE); mNextButton.setVisibility(View.VISIBLE); } else { mBackButton.setVisibility(View.GONE); mNextButton.setVisibility(View.GONE); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit"); createQuitDialog(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.isAltPressed() && !mBeenSwiped) { mBeenSwiped = true; Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_RIGHT", "showNext"); showNextView(); return true; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (event.isAltPressed() && !mBeenSwiped) { mBeenSwiped = true; Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_LEFT", "showPrevious"); showPreviousView(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { if (mFormLoaderTask != null) { mFormLoaderTask.setFormLoaderListener(null); // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. // but only if it's done, otherwise the thread never returns if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); } } if (mSaveToDiskTask != null) { mSaveToDiskTask.setFormSavedListener(null); // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(true); mSaveToDiskTask = null; } } super.onDestroy(); } private int mAnimationCompletionSet = 0; private void afterAllAnimations() { Log.i(t, "afterAllAnimations"); if (mStaleView != null) { if (mStaleView instanceof ODKView) { // http://code.google.com/p/android/issues/detail?id=8488 ((ODKView) mStaleView).recycleDrawables(); } mStaleView = null; } if (mCurrentView instanceof ODKView) { ((ODKView) mCurrentView).setFocus(this); } mBeenSwiped = false; } @Override public void onAnimationEnd(Animation animation) { Log.i(t, "onAnimationEnd " + ((animation == mInAnimation) ? "in" : ((animation == mOutAnimation) ? "out" : "other"))); if (mInAnimation == animation) { mAnimationCompletionSet |= 1; } else if (mOutAnimation == animation) { mAnimationCompletionSet |= 2; } else { Log.e(t, "Unexpected animation"); } if (mAnimationCompletionSet == 3) { this.afterAllAnimations(); } } @Override public void onAnimationRepeat(Animation animation) { // Added by AnimationListener interface. Log.i(t, "onAnimationRepeat " + ((animation == mInAnimation) ? "in" : ((animation == mOutAnimation) ? "out" : "other"))); } @Override public void onAnimationStart(Animation animation) { // Added by AnimationListener interface. Log.i(t, "onAnimationStart " + ((animation == mInAnimation) ? "in" : ((animation == mOutAnimation) ? "out" : "other"))); } /** * loadingComplete() is called by FormLoaderTask once it has finished * loading a form. */ @Override public void loadingComplete(FormLoaderTask task) { dismissDialog(PROGRESS_DIALOG); FormController formController = task.getFormController(); boolean pendingActivityResult = task.hasPendingActivityResult(); boolean hasUsedSavepoint = task.hasUsedSavepoint(); int requestCode = task.getRequestCode(); // these are bogus if // pendingActivityResult is // false int resultCode = task.getResultCode(); Intent intent = task.getIntent(); mFormLoaderTask.setFormLoaderListener(null); FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); Collect.getInstance().setFormController(formController); //updateMenu // Set the language if one has already been set in the past String[] languageTest = formController.getLanguages(); if (languageTest != null) { String defaultLanguage = formController.getLanguage(); String newLanguage = ""; String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; Cursor c = null; try { c = getContentResolver().query(FormsColumns.CONTENT_URI, null, selection, selectArgs, null); if (c.getCount() == 1) { c.moveToFirst(); newLanguage = c.getString(c .getColumnIndex(FormsColumns.LANGUAGE)); } } finally { if (c != null) { c.close(); } } // if somehow we end up with a bad language, set it to the default try { formController.setLanguage(newLanguage); } catch (Exception e) { formController.setLanguage(defaultLanguage); } } if (pendingActivityResult) { // set the current view to whatever group we were at... refreshCurrentView(); // process the pending activity request... onActivityResult(requestCode, resultCode, intent); return; } // it can be a normal flow for a pending activity result to restore from // a savepoint // (the call flow handled by the above if statement). For all other use // cases, the // user should be notified, as it means they wandered off doing other // things then // returned to ODK Collect and chose Edit Saved Form, but that the // savepoint for that // form is newer than the last saved version of their form data. if (hasUsedSavepoint) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(FormEntryActivity.this, getString(R.string.savepoint_used), Toast.LENGTH_LONG).show(); } }); } // Set saved answer path if (formController.getInstancePath() == null) { // Create new answer folder. String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.ENGLISH).format(Calendar.getInstance().getTime()); String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')); String path = Collect.INSTANCES_PATH + File.separator + file + "_" + time; if (FileUtils.createFolder(path)) { formController.setInstancePath(new File(path + File.separator + file + "_" + time + ".xml")); } } else { Intent reqIntent = getIntent(); boolean showFirst = reqIntent.getBooleanExtra("start", false); if (!showFirst) { // we've just loaded a saved form, so start in the hierarchy // view Intent i = new Intent(this, FormHierarchyActivity.class); i.putExtra("isSavedForm", true); if (mToFormChooser){ i.putExtra("toFormChooser", true); } startActivity(i); return; // so we don't show the intro screen before jumping to // the hierarchy } } refreshCurrentView(); } /** * called by the FormLoaderTask if something goes wrong. */ @Override public void loadingError(String errorMsg) { dismissDialog(PROGRESS_DIALOG); if (errorMsg != null) { createErrorDialog(errorMsg, EXIT); } else { createErrorDialog(getString(R.string.parse_error), EXIT); } } /** * Called by SavetoDiskTask if everything saves correctly. */ @Override public void savingComplete(int saveStatus) { dismissDialog(SAVING_DIALOG); switch (saveStatus) { case SaveToDiskTask.SAVED: Toast.makeText(this, getString(R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); sendSavedBroadcast(); break; case SaveToDiskTask.SAVED_AND_EXIT: Toast.makeText(this, getString(R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); sendSavedBroadcast(); finishReturnInstance(); break; case SaveToDiskTask.SAVE_ERROR: Toast.makeText(this, getString(R.string.data_saved_error), Toast.LENGTH_LONG).show(); break; case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: refreshCurrentView(); // an answer constraint was violated, so do a 'swipe' to the next // question to display the proper toast(s) next(); break; } } /** * Attempts to save an answer to the specified index. * * @param answer * @param index * @param evaluateConstraints * @return status as determined in FormEntryController */ public int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) { FormController formController = Collect.getInstance() .getFormController(); if (evaluateConstraints) { return formController.answerQuestion(index, answer); } else { formController.saveAnswer(index, answer); return FormEntryController.ANSWER_OK; } } /** * Checks the database to determine if the current instance being edited has * already been 'marked completed'. A form can be 'unmarked' complete and * then resaved. * * @return true if form has been marked completed, false otherwise. */ private boolean isInstanceComplete(boolean end) { FormController formController = Collect.getInstance() .getFormController(); // default to false if we're mid form boolean complete = false; // if we're at the end of the form, then check the preferences if (end) { // First get the value from the preferences SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); complete = sharedPreferences.getBoolean( PreferencesActivity.KEY_COMPLETED_DEFAULT, true); } // Then see if we've already marked this form as complete before String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { formController.getInstancePath() .getAbsolutePath() }; Cursor c = null; try { c = getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); String status = c.getString(c .getColumnIndex(InstanceColumns.STATUS)); if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) { complete = true; } } } finally { if (c != null) { c.close(); } } return complete; } public void next() { if (!mBeenSwiped) { mBeenSwiped = true; showNextView(); } } /** * Returns the instance that was just filled out to the calling activity, if * requested. */ private void finishReturnInstance() { FormController formController = Collect.getInstance() .getFormController(); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) { // caller is waiting on a picked form String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { formController.getInstancePath() .getAbsolutePath() }; Cursor c = null; try { c = getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { // should only be one... c.moveToFirst(); String id = c.getString(c .getColumnIndex(BaseColumns._ID)); Uri instance = Uri.withAppendedPath( InstanceColumns.CONTENT_URI, id); setResult(RESULT_OK, new Intent().setData(instance)); } } finally { if (c != null) { c.close(); } } } finish(); } @Override public boolean onDown(MotionEvent e) { return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // only check the swipe if it's enabled in preferences SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); String navigation = sharedPreferences.getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.NAVIGATION_SWIPE); Boolean doSwipe = false; if (navigation.contains(PreferencesActivity.NAVIGATION_SWIPE)) { doSwipe = true; } if (doSwipe) { // Looks for user swipes. If the user has swiped, move to the // appropriate screen. // for all screens a swipe is left/right of at least // .25" and up/down of less than .25" // OR left/right of > .5" DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int xPixelLimit = (int) (dm.xdpi * .25); int yPixelLimit = (int) (dm.ydpi * .25); if (mCurrentView instanceof ODKView) { if (((ODKView) mCurrentView).suppressFlingGesture(e1, e2, velocityX, velocityY)) { return false; } } if (mBeenSwiped) { return false; } if ((Math.abs(e1.getX() - e2.getX()) > xPixelLimit && Math.abs(e1 .getY() - e2.getY()) < yPixelLimit) || Math.abs(e1.getX() - e2.getX()) > xPixelLimit * 2) { mBeenSwiped = true; if (velocityX > 0) { if (e1.getX() > e2.getX()) { Log.e(t, "showNextView VelocityX is bogus! " + e1.getX() + " > " + e2.getX()); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onFling", "showNext"); showNextView(); } else { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onFling", "showPrevious"); showPreviousView(); } } else { if (e1.getX() < e2.getX()) { Log.e(t, "showPreviousView VelocityX is bogus! " + e1.getX() + " < " + e2.getX()); Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onFling", "showPrevious"); showPreviousView(); } else { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onFling", "showNext"); showNextView(); } } return true; } } return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // The onFling() captures the 'up' event so our view thinks it gets long // pressed. // We don't wnat that, so cancel it. mCurrentView.cancelLongPress(); return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void advance() { next(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void sendSavedBroadcast() { Intent i = new Intent(); i.setAction("com.makina.collect.android.FormSaved"); this.sendBroadcast(i); } @Override public void setAnswerChange(boolean hasChanged) { Log.i(getClass().getName(), "setAnswerChange " + Boolean.toString(hasChanged)); mAnswersChanged = hasChanged; } }
[ "guillaume.salmon.ext@makina-corpus.com" ]
guillaume.salmon.ext@makina-corpus.com
5e40b48331c0dc4ec4b1820a09164b9109481a3e
e8e748cda5fe567637403da01c3f2658174fd579
/app/src/main/java/com/t3h/whiyew/appt3h/abstractclass/WakeLocker.java
76f17acd9b5645116ca65bdf7ec4857119bdff21
[]
no_license
dragoon1251996/AppT3h_
82b265fa29248d44a4e30bd485e9779778be03c6
684907ca59ab95878508075811140f6d752c4ebb
refs/heads/master
2021-01-19T17:33:18.409204
2017-04-15T06:45:14
2017-04-15T06:45:14
88,328,793
0
0
null
null
null
null
UTF-8
Java
false
false
694
java
package com.t3h.whiyew.appt3h.abstractclass; import android.content.Context; import android.os.PowerManager; public abstract class WakeLocker { private static PowerManager.WakeLock wakeLock; public static void acquire(Context ctx) { if (wakeLock != null) wakeLock.release(); PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, ""); wakeLock.acquire(); } public static void release() { if (wakeLock != null) wakeLock.release(); wakeLock = null; } }
[ "whiyew@gmail.com" ]
whiyew@gmail.com
d2f7dbebe10c0446344dcf86967012392cff2b4e
97ead6dfbe1a6b569be08f7cd247161bc0a73121
/io/src/main/java/com/redshape/io/net/auth/impl/providers/SimpleProvider.java
24df4ccac120d6cefec76fbfeac3eb71d02e8356
[ "Apache-2.0" ]
permissive
Redshape/Redshape-AS
19f54bc0d54061b0302a7b3f63e600afb01168ea
cf3492919a35b868bc7045b35d38e74a3a2b8c01
refs/heads/master
2021-01-17T05:17:31.881177
2012-09-05T13:49:50
2012-09-05T13:49:50
1,390,510
0
0
null
null
null
null
UTF-8
Java
false
false
457
java
package com.redshape.io.net.auth.impl.providers; import com.redshape.io.net.auth.AbstractCredentialsProvider; /** * Created by IntelliJ IDEA. * User: user * Date: Nov 12, 2010 * Time: 1:06:38 PM * To change this template use File | Settings | File Templates. */ public class SimpleProvider extends AbstractCredentialsProvider { public SimpleProvider() { super(); } public boolean isInitialized() { return true; } }
[ "self@nikelin.ru" ]
self@nikelin.ru
226cd95b06c2da60be39b5dd739c62e659a35bfb
8a787e93fea9c334122441717f15bd2f772e3843
/odfdom/src/main/java/org/odftoolkit/odfdom/dom/element/style/StyleListLevelPropertiesElement.java
564406526550eb1291e974f49759e90466b27bd7
[ "Apache-2.0", "BSD-3-Clause", "MIT", "W3C", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference" ]
permissive
apache/odftoolkit
296ea9335bfdd78aa94829c915a6e9c24e5b5166
99975f3be40fc1c428167a3db7a9a63038acfa9f
refs/heads/trunk
2023-07-02T16:30:24.946067
2018-10-02T11:11:40
2018-10-02T11:11:40
5,212,656
39
45
Apache-2.0
2018-04-11T11:57:17
2012-07-28T07:00:12
Java
UTF-8
Java
false
false
17,051
java
/************************************************************************ * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * * Use is subject to license terms. * * 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. You can also * obtain a copy of the License at http://odftoolkit.org/docs/license.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************/ /* * This file is automatically generated. * Don't edit manually. */ package org.odftoolkit.odfdom.dom.element.style; import org.odftoolkit.odfdom.pkg.OdfElement; import org.odftoolkit.odfdom.dom.style.props.OdfStyleProperty; import org.odftoolkit.odfdom.dom.style.props.OdfStylePropertiesSet; import org.odftoolkit.odfdom.pkg.ElementVisitor; import org.odftoolkit.odfdom.pkg.OdfFileDom; import org.odftoolkit.odfdom.pkg.OdfName; import org.odftoolkit.odfdom.dom.OdfDocumentNamespace; import org.odftoolkit.odfdom.dom.DefaultElementVisitor; import org.odftoolkit.odfdom.dom.attribute.fo.FoHeightAttribute; import org.odftoolkit.odfdom.dom.attribute.fo.FoTextAlignAttribute; import org.odftoolkit.odfdom.dom.attribute.fo.FoWidthAttribute; import org.odftoolkit.odfdom.dom.attribute.style.StyleFontNameAttribute; import org.odftoolkit.odfdom.dom.attribute.style.StyleVerticalPosAttribute; import org.odftoolkit.odfdom.dom.attribute.style.StyleVerticalRelAttribute; import org.odftoolkit.odfdom.dom.attribute.svg.SvgYAttribute; import org.odftoolkit.odfdom.dom.attribute.text.TextListLevelPositionAndSpaceModeAttribute; import org.odftoolkit.odfdom.dom.attribute.text.TextMinLabelDistanceAttribute; import org.odftoolkit.odfdom.dom.attribute.text.TextMinLabelWidthAttribute; import org.odftoolkit.odfdom.dom.attribute.text.TextSpaceBeforeAttribute; import org.odftoolkit.odfdom.dom.element.OdfStylePropertiesBase; /** * DOM implementation of OpenDocument element {@odf.element style:list-level-properties}. * */ public class StyleListLevelPropertiesElement extends OdfStylePropertiesBase { public static final OdfName ELEMENT_NAME = OdfName.newName(OdfDocumentNamespace.STYLE, "list-level-properties"); /** * Create the instance of <code>StyleListLevelPropertiesElement</code> * * @param ownerDoc The type is <code>OdfFileDom</code> */ public StyleListLevelPropertiesElement(OdfFileDom ownerDoc) { super(ownerDoc, ELEMENT_NAME); } /** * Get the element name * * @return return <code>OdfName</code> the name of element {@odf.element style:list-level-properties}. */ public OdfName getOdfName() { return ELEMENT_NAME; } public final static OdfStyleProperty Height = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.FO, "height")); public final static OdfStyleProperty TextAlign = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.FO, "text-align")); public final static OdfStyleProperty Width = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.FO, "width")); public final static OdfStyleProperty FontName = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.STYLE, "font-name")); public final static OdfStyleProperty VerticalPos = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.STYLE, "vertical-pos")); public final static OdfStyleProperty VerticalRel = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.STYLE, "vertical-rel")); public final static OdfStyleProperty Y = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.SVG, "y")); public final static OdfStyleProperty ListLevelPositionAndSpaceMode = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.TEXT, "list-level-position-and-space-mode")); public final static OdfStyleProperty MinLabelDistance = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.TEXT, "min-label-distance")); public final static OdfStyleProperty MinLabelWidth = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.TEXT, "min-label-width")); public final static OdfStyleProperty SpaceBefore = OdfStyleProperty.get(OdfStylePropertiesSet.ListLevelProperties, OdfName.newName(OdfDocumentNamespace.TEXT, "space-before")); /** * Receives the value of the ODFDOM attribute representation <code>FoHeightAttribute</code> , See {@odf.attribute fo:height} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getFoHeightAttribute() { FoHeightAttribute attr = (FoHeightAttribute) getOdfAttribute(OdfDocumentNamespace.FO, "height"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>FoHeightAttribute</code> , See {@odf.attribute fo:height} * * @param foHeightValue The type is <code>String</code> */ public void setFoHeightAttribute(String foHeightValue) { FoHeightAttribute attr = new FoHeightAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(foHeightValue); } /** * Receives the value of the ODFDOM attribute representation <code>FoTextAlignAttribute</code> , See {@odf.attribute fo:text-align} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getFoTextAlignAttribute() { FoTextAlignAttribute attr = (FoTextAlignAttribute) getOdfAttribute(OdfDocumentNamespace.FO, "text-align"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>FoTextAlignAttribute</code> , See {@odf.attribute fo:text-align} * * @param foTextAlignValue The type is <code>String</code> */ public void setFoTextAlignAttribute(String foTextAlignValue) { FoTextAlignAttribute attr = new FoTextAlignAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(foTextAlignValue); } /** * Receives the value of the ODFDOM attribute representation <code>FoWidthAttribute</code> , See {@odf.attribute fo:width} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getFoWidthAttribute() { FoWidthAttribute attr = (FoWidthAttribute) getOdfAttribute(OdfDocumentNamespace.FO, "width"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>FoWidthAttribute</code> , See {@odf.attribute fo:width} * * @param foWidthValue The type is <code>String</code> */ public void setFoWidthAttribute(String foWidthValue) { FoWidthAttribute attr = new FoWidthAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(foWidthValue); } /** * Receives the value of the ODFDOM attribute representation <code>StyleFontNameAttribute</code> , See {@odf.attribute style:font-name} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getStyleFontNameAttribute() { StyleFontNameAttribute attr = (StyleFontNameAttribute) getOdfAttribute(OdfDocumentNamespace.STYLE, "font-name"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>StyleFontNameAttribute</code> , See {@odf.attribute style:font-name} * * @param styleFontNameValue The type is <code>String</code> */ public void setStyleFontNameAttribute(String styleFontNameValue) { StyleFontNameAttribute attr = new StyleFontNameAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(styleFontNameValue); } /** * Receives the value of the ODFDOM attribute representation <code>StyleVerticalPosAttribute</code> , See {@odf.attribute style:vertical-pos} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getStyleVerticalPosAttribute() { StyleVerticalPosAttribute attr = (StyleVerticalPosAttribute) getOdfAttribute(OdfDocumentNamespace.STYLE, "vertical-pos"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>StyleVerticalPosAttribute</code> , See {@odf.attribute style:vertical-pos} * * @param styleVerticalPosValue The type is <code>String</code> */ public void setStyleVerticalPosAttribute(String styleVerticalPosValue) { StyleVerticalPosAttribute attr = new StyleVerticalPosAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(styleVerticalPosValue); } /** * Receives the value of the ODFDOM attribute representation <code>StyleVerticalRelAttribute</code> , See {@odf.attribute style:vertical-rel} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getStyleVerticalRelAttribute() { StyleVerticalRelAttribute attr = (StyleVerticalRelAttribute) getOdfAttribute(OdfDocumentNamespace.STYLE, "vertical-rel"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>StyleVerticalRelAttribute</code> , See {@odf.attribute style:vertical-rel} * * @param styleVerticalRelValue The type is <code>String</code> */ public void setStyleVerticalRelAttribute(String styleVerticalRelValue) { StyleVerticalRelAttribute attr = new StyleVerticalRelAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(styleVerticalRelValue); } /** * Receives the value of the ODFDOM attribute representation <code>SvgYAttribute</code> , See {@odf.attribute svg:y} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getSvgYAttribute() { SvgYAttribute attr = (SvgYAttribute) getOdfAttribute(OdfDocumentNamespace.SVG, "y"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>SvgYAttribute</code> , See {@odf.attribute svg:y} * * @param svgYValue The type is <code>String</code> */ public void setSvgYAttribute(String svgYValue) { SvgYAttribute attr = new SvgYAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(svgYValue); } /** * Receives the value of the ODFDOM attribute representation <code>TextListLevelPositionAndSpaceModeAttribute</code> , See {@odf.attribute text:list-level-position-and-space-mode} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getTextListLevelPositionAndSpaceModeAttribute() { TextListLevelPositionAndSpaceModeAttribute attr = (TextListLevelPositionAndSpaceModeAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "list-level-position-and-space-mode"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>TextListLevelPositionAndSpaceModeAttribute</code> , See {@odf.attribute text:list-level-position-and-space-mode} * * @param textListLevelPositionAndSpaceModeValue The type is <code>String</code> */ public void setTextListLevelPositionAndSpaceModeAttribute(String textListLevelPositionAndSpaceModeValue) { TextListLevelPositionAndSpaceModeAttribute attr = new TextListLevelPositionAndSpaceModeAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(textListLevelPositionAndSpaceModeValue); } /** * Receives the value of the ODFDOM attribute representation <code>TextMinLabelDistanceAttribute</code> , See {@odf.attribute text:min-label-distance} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getTextMinLabelDistanceAttribute() { TextMinLabelDistanceAttribute attr = (TextMinLabelDistanceAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "min-label-distance"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>TextMinLabelDistanceAttribute</code> , See {@odf.attribute text:min-label-distance} * * @param textMinLabelDistanceValue The type is <code>String</code> */ public void setTextMinLabelDistanceAttribute(String textMinLabelDistanceValue) { TextMinLabelDistanceAttribute attr = new TextMinLabelDistanceAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(textMinLabelDistanceValue); } /** * Receives the value of the ODFDOM attribute representation <code>TextMinLabelWidthAttribute</code> , See {@odf.attribute text:min-label-width} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getTextMinLabelWidthAttribute() { TextMinLabelWidthAttribute attr = (TextMinLabelWidthAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "min-label-width"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>TextMinLabelWidthAttribute</code> , See {@odf.attribute text:min-label-width} * * @param textMinLabelWidthValue The type is <code>String</code> */ public void setTextMinLabelWidthAttribute(String textMinLabelWidthValue) { TextMinLabelWidthAttribute attr = new TextMinLabelWidthAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(textMinLabelWidthValue); } /** * Receives the value of the ODFDOM attribute representation <code>TextSpaceBeforeAttribute</code> , See {@odf.attribute text:space-before} * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getTextSpaceBeforeAttribute() { TextSpaceBeforeAttribute attr = (TextSpaceBeforeAttribute) getOdfAttribute(OdfDocumentNamespace.TEXT, "space-before"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>TextSpaceBeforeAttribute</code> , See {@odf.attribute text:space-before} * * @param textSpaceBeforeValue The type is <code>String</code> */ public void setTextSpaceBeforeAttribute(String textSpaceBeforeValue) { TextSpaceBeforeAttribute attr = new TextSpaceBeforeAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(textSpaceBeforeValue); } /** * Create child element {@odf.element style:list-level-label-alignment}. * * @param textLabelFollowedByValue the <code>String</code> value of <code>TextLabelFollowedByAttribute</code>, see {@odf.attribute text:label-followed-by} at specification * Child element is new in Odf 1.2 * * @return the element {@odf.element style:list-level-label-alignment} */ public StyleListLevelLabelAlignmentElement newStyleListLevelLabelAlignmentElement(String textLabelFollowedByValue) { StyleListLevelLabelAlignmentElement styleListLevelLabelAlignment = ((OdfFileDom) this.ownerDocument).newOdfElement(StyleListLevelLabelAlignmentElement.class); styleListLevelLabelAlignment.setTextLabelFollowedByAttribute(textLabelFollowedByValue); this.appendChild(styleListLevelLabelAlignment); return styleListLevelLabelAlignment; } @Override public void accept(ElementVisitor visitor) { if (visitor instanceof DefaultElementVisitor) { DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor; defaultVisitor.visit(this); } else { visitor.visit(this); } } }
[ "dev-null@apache.org" ]
dev-null@apache.org
255761c1d12d200fcff3d185739fe34a86ca9738
ee731d0acfb6dc9465d6842245ba91a02ef93fcc
/date-time/src/date1/DateDemo3.java
8d97e7c2c5c82f6756739105d1db132dfc69a156
[]
no_license
siwolsmu89/J_HTA_java_workspace
6a668c421c5ada7b792be0ee0a94b3232bd109ca
43b0bae8e5b7cb68513d8670b136f098d7b8a4e1
refs/heads/master
2022-11-18T17:23:29.458359
2020-07-20T08:57:02
2020-07-20T08:57:02
258,408,262
2
0
null
null
null
null
UTF-8
Java
false
false
1,134
java
package date1; import java.text.SimpleDateFormat; import java.util.Date; public class DateDemo3 { public static void main(String[] args) { /* * Date를 지정된 형식의 문자열로 변환하기 */ Date today = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy년 M월 d일(EEEE) Hmss"); String formatedText = df.format(today); System.out.println(formatedText); } /* * 패턴 출력내용 출력값 비고 * --------------------------------------------------------- * yyyy 년 2020 * MM 월 04 1~9월을 01~09로 표시 * M 월 4 1~9월을 1~9로 표시 (10월부터는 10~12로 표시됨) * dd 일 06 * d 일 6 * yyyy-MM-dd 2020-04-06 * yyyy.M.d. 2020.4.6. * yyyy년 M월 d일 2020년 4월 6일 * * EEEE 요일 월요일 영어로는 Monday * E, EEE 요일 월 영어로는 M, MON * a 오전/오후 오전 * H, HH 24시간제(0~23시) 1, 01 * h, hh 12시간제(1~12시) 1, 01 * m, mm 분(0~59) 1, 01 * s, ss 초(0~59) 1, 01 * */ }
[ "siwol_smuire89@naver.com" ]
siwol_smuire89@naver.com
3ffe9aa011a2b3766cbf77d67433c12a98b07ba5
c885ef92397be9d54b87741f01557f61d3f794f3
/tests-without-trycatch/Gson-15/com.google.gson.stream.JsonWriter/BBC-F0-opt-90/11/com/google/gson/stream/JsonWriter_ESTest_scaffolding.java
a2e4c7e98c26e17a8ed57b1513f27967165075a6
[ "CC-BY-4.0", "MIT" ]
permissive
pderakhshanfar/EMSE-BBC-experiment
f60ac5f7664dd9a85f755a00a57ec12c7551e8c6
fea1a92c2e7ba7080b8529e2052259c9b697bbda
refs/heads/main
2022-11-25T00:39:58.983828
2022-04-12T16:04:26
2022-04-12T16:04:26
309,335,889
0
1
null
2021-11-05T11:18:43
2020-11-02T10:30:38
null
UTF-8
Java
false
false
3,181
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Wed Oct 20 23:47:18 GMT 2021 */ package com.google.gson.stream; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; import org.evosuite.runtime.sandbox.Sandbox; import org.evosuite.runtime.sandbox.Sandbox.SandboxMode; @EvoSuiteClassExclude public class JsonWriter_ESTest_scaffolding { @org.junit.Rule public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); @BeforeClass public static void initEvoSuiteFramework() { org.evosuite.runtime.RuntimeSettings.className = "com.google.gson.stream.JsonWriter"; org.evosuite.runtime.GuiSupport.initialize(); org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); org.evosuite.runtime.classhandling.JDKClassResetter.init(); setSystemProperties(); initializeClasses(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); } @Before public void initTestCase(){ threadStopper.storeCurrentThreads(); threadStopper.startRecordingTime(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); org.evosuite.runtime.GuiSupport.setHeadless(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); org.evosuite.runtime.agent.InstrumentingAgent.activate(); } @After public void doneWithTestCase(){ threadStopper.killAndJoinClientThreads(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); org.evosuite.runtime.classhandling.JDKClassResetter.reset(); resetClasses(); org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); } public static void setSystemProperties() { /*No java.lang.System property to set*/ } private static void initializeClasses() { org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(JsonWriter_ESTest_scaffolding.class.getClassLoader() , "com.google.gson.stream.JsonWriter" ); } private static void resetClasses() { org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(JsonWriter_ESTest_scaffolding.class.getClassLoader()); org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( "com.google.gson.stream.JsonWriter" ); } }
[ "pouria.derakhshanfar@gmail.com" ]
pouria.derakhshanfar@gmail.com
2906e3a792aa694547e1021308bc3712346d067c
13c711fed6fbc21dfc1ae491c34338f30d98420c
/src/main/java/com/imooc/sell/VO/ProductInfoVO.java
af838391996824d1fd9a31f8bbf3db9d876231dd
[]
no_license
HeKinKin/Sell
c0e383ac97e3bf36d36a68cd246cf512887c66fb
ba7c3e421e08b8fc551bcff6101b4c75580d67d0
refs/heads/master
2020-04-26T01:58:28.382580
2019-03-01T02:45:51
2019-03-01T02:45:51
173,220,941
0
0
null
null
null
null
UTF-8
Java
false
false
541
java
package com.imooc.sell.VO; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.math.BigDecimal; /** * 商品详情 * @author hexin * @date 2019/02/26 */ @Data public class ProductInfoVO { @JsonProperty("id") private String productId; @JsonProperty("name") private String productName; @JsonProperty("price") private BigDecimal productPrice; @JsonProperty("description") private String productDescription; @JsonProperty("icon") private String productIcon; }
[ "hexin@yazuo.com" ]
hexin@yazuo.com
c6bb9aa396df4ded34f7ded725043b8e3f130582
41760a8dfd14b925f0f1c79b12a7acd76d2f6338
/slick2d-core/src/main/java/org/newdawn/slick/GameContainer.java
eacbd8cd4988d7ea5c6d546101674c7e68f66ee3
[ "BSD-3-Clause" ]
permissive
vertingo/slick2d-maven
5f81af6955819c72d8764d92124d630786dfb464
45fbe42573c87183c76a20a6f6ec4019989e16f6
refs/heads/master
2020-04-12T17:08:39.296310
2018-12-20T22:46:42
2018-12-20T22:46:42
162,636,031
0
0
BSD-3-Clause
2018-12-20T22:05:47
2018-12-20T22:05:47
null
UTF-8
Java
false
false
23,601
java
package org.newdawn.slick; import java.io.IOException; import java.util.Properties; import org.lwjgl.LWJGLException; import org.lwjgl.Sys; import org.lwjgl.input.Cursor; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.Drawable; import org.lwjgl.opengl.Pbuffer; import org.lwjgl.opengl.PixelFormat; import org.newdawn.slick.gui.GUIContext; import org.newdawn.slick.openal.SoundStore; import org.newdawn.slick.opengl.CursorLoader; import org.newdawn.slick.opengl.ImageData; import org.newdawn.slick.opengl.renderer.Renderer; import org.newdawn.slick.opengl.renderer.SGL; import org.newdawn.slick.util.Log; import org.newdawn.slick.util.ResourceLoader; /** * A generic game container that handles the game loop, fps recording and * managing the input system * * @author kevin */ public abstract class GameContainer implements GUIContext { /** The renderer to use for all GL operations */ protected static SGL GL = Renderer.get(); /** The shared drawable if any */ protected static Drawable SHARED_DRAWABLE; /** The time the last frame was rendered */ protected long lastFrame; /** The last time the FPS recorded */ protected long lastFPS; /** The last recorded FPS */ protected int recordedFPS; /** The current count of FPS */ protected int fps; /** True if we're currently running the game loop */ protected boolean running = true; /** The width of the display */ protected int width; /** The height of the display */ protected int height; /** The game being managed */ protected Game game; /** The default font to use in the graphics context */ private Font defaultFont; /** The graphics context to be passed to the game */ private Graphics graphics; /** The input system to pass to the game */ protected Input input; /** The FPS we want to lock to */ protected int targetFPS = -1; /** True if we should show the fps */ private boolean showFPS = true; /** The minimum logic update interval */ protected long minimumLogicInterval = 1; /** The stored delta */ protected long storedDelta; /** The maximum logic update interval */ protected long maximumLogicInterval = 0; /** The last game started */ protected Game lastGame; /** True if we should clear the screen each frame */ protected boolean clearEachFrame = true; /** True if the game is paused */ protected boolean paused; /** True if we should force exit */ protected boolean forceExit = true; /** True if vsync has been requested */ protected boolean vsync; /** Smoothed deltas requested */ protected boolean smoothDeltas; /** The number of samples we'll attempt through hardware */ protected int samples; /** True if this context supports multisample */ protected boolean supportsMultiSample; /** True if we should render when not focused */ protected boolean alwaysRender; /** True if we require stencil bits */ protected static boolean stencil; /** * Create a new game container wrapping a given game * * @param game The game to be wrapped */ protected GameContainer(Game game) { this.game = game; lastFrame = getTime(); getBuildVersion(); Log.checkVerboseLogSetting(); } public static void enableStencil() { stencil = true; } /** * Set the default font that will be intialised in the graphics held in this container * * @param font The font to use as default */ public void setDefaultFont(Font font) { if (font != null) { this.defaultFont = font; } else { Log.warn("Please provide a non null font"); } } /** * Indicate whether we want to try to use fullscreen multisampling. This will * give antialiasing across the whole scene using a hardware feature. * * @param samples The number of samples to attempt (2 is safe) */ public void setMultiSample(int samples) { this.samples = samples; } /** * Check if this hardware can support multi-sampling * * @return True if the hardware supports multi-sampling */ public boolean supportsMultiSample() { return supportsMultiSample; } /** * The number of samples we're attempting to performing using * hardware multisampling * * @return The number of samples requested */ public int getSamples() { return samples; } /** * Indicate if we should force exitting the VM at the end * of the game (default = true) * * @param forceExit True if we should force the VM exit */ public void setForceExit(boolean forceExit) { this.forceExit = forceExit; } /** * Indicate if we want to smooth deltas. This feature will report * a delta based on the FPS not the time passed. This works well with * vsync. * * @param smoothDeltas True if we should report smooth deltas */ public void setSmoothDeltas(boolean smoothDeltas) { this.smoothDeltas = smoothDeltas; } /** * Check if the display is in fullscreen mode * * @return True if the display is in fullscreen mode */ public boolean isFullscreen() { return false; } /** * Get the aspect ratio of the screen * * @return The aspect ratio of the display */ public float getAspectRatio() { return getWidth() / getHeight(); } /** * Indicate whether we want to be in fullscreen mode. Note that the current * display mode must be valid as a fullscreen mode for this to work * * @param fullscreen True if we want to be in fullscreen mode * @throws SlickException Indicates we failed to change the display mode */ public void setFullscreen(boolean fullscreen) throws SlickException { } /** * Enable shared OpenGL context. After calling this all containers created * will shared a single parent context * * @throws SlickException Indicates a failure to create the shared drawable */ public static void enableSharedContext() throws SlickException { try { SHARED_DRAWABLE = new Pbuffer(64, 64, new PixelFormat(8, 0, 0), null); } catch (LWJGLException e) { throw new SlickException("Unable to create the pbuffer used for shard context, buffers not supported", e); } } /** * Get the context shared by all containers * * @return The context shared by all the containers or null if shared context isn't enabled */ public static Drawable getSharedContext() { return SHARED_DRAWABLE; } /** * Indicate if we should clear the screen at the beginning of each frame. If you're * rendering to the whole screen each frame then setting this to false can give * some performance improvements * * @param clear True if the the screen should be cleared each frame */ public void setClearEachFrame(boolean clear) { this.clearEachFrame = clear; } /** * Renitialise the game and the context in which it's being rendered * * @throws SlickException Indicates a failure rerun initialisation routines */ public void reinit() throws SlickException { } /** * Pause the game - i.e. suspend updates */ public void pause() { setPaused(true); } /** * Resumt the game - i.e. continue updates */ public void resume() { setPaused(false); } /** * Check if the container is currently paused. * * @return True if the container is paused */ public boolean isPaused() { return paused; } /** * Indicates if the game should be paused, i.e. if updates * should be propogated through to the game. * * @param paused True if the game should be paused */ public void setPaused(boolean paused) { this.paused = paused; } /** * True if this container should render when it has focus * * @return True if this container should render when it has focus */ public boolean getAlwaysRender () { return alwaysRender; } /** * Indicate whether we want this container to render when it has focus * * @param alwaysRender True if this container should render when it has focus */ public void setAlwaysRender (boolean alwaysRender) { this.alwaysRender = alwaysRender; } /** * Get the build number of slick * * @return The build number of slick */ public static int getBuildVersion() { try { Properties props = new Properties(); props.load(ResourceLoader.getResourceAsStream("version")); int build = Integer.parseInt(props.getProperty("build")); Log.info("Slick Build #"+build); return build; } catch (Exception e) { Log.error("Unable to determine Slick build number"); return -1; } } /** * Get the default system font * * @return The default system font */ public Font getDefaultFont() { return defaultFont; } /** * Check if sound effects are enabled * * @return True if sound effects are enabled */ public boolean isSoundOn() { return SoundStore.get().soundsOn(); } /** * Check if music is enabled * * @return True if music is enabled */ public boolean isMusicOn() { return SoundStore.get().musicOn(); } /** * Indicate whether music should be enabled * * @param on True if music should be enabled */ public void setMusicOn(boolean on) { SoundStore.get().setMusicOn(on); } /** * Indicate whether sound effects should be enabled * * @param on True if sound effects should be enabled */ public void setSoundOn(boolean on) { SoundStore.get().setSoundsOn(on); } /** * Retrieve the current default volume for music * @return the current default volume for music */ public float getMusicVolume() { return SoundStore.get().getMusicVolume(); } /** * Retrieve the current default volume for sound fx * @return the current default volume for sound fx */ public float getSoundVolume() { return SoundStore.get().getSoundVolume(); } /** * Set the default volume for sound fx * @param volume the new default value for sound fx volume */ public void setSoundVolume(float volume) { SoundStore.get().setSoundVolume(volume); } /** * Set the default volume for music * @param volume the new default value for music volume */ public void setMusicVolume(float volume) { SoundStore.get().setMusicVolume(volume); } /** * Get the width of the standard screen resolution * * @return The screen width */ public abstract int getScreenWidth(); /** * Get the height of the standard screen resolution * * @return The screen height */ public abstract int getScreenHeight(); /** * Get the width of the game canvas * * @return The width of the game canvas */ public int getWidth() { return width; } /** * Get the height of the game canvas * * @return The height of the game canvas */ public int getHeight() { return height; } /** * Set the icon to be displayed if possible in this type of * container * * @param ref The reference to the icon to be displayed * @throws SlickException Indicates a failure to load the icon */ public abstract void setIcon(String ref) throws SlickException; /** * Set the icons to be used for this application. Note that the size of the icon * defines how it will be used. Important ones to note * * Windows window icon must be 16x16 * Windows alt-tab icon must be 24x24 or 32x32 depending on Windows version (XP=32) * * @param refs The reference to the icon to be displayed * @throws SlickException Indicates a failure to load the icon */ public abstract void setIcons(String[] refs) throws SlickException; /** * Get the accurate system time * * @return The system time in milliseconds */ public long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } /** * Sleep for a given period * * @param milliseconds The period to sleep for in milliseconds */ public void sleep(int milliseconds) { long target = getTime()+milliseconds; while (getTime() < target) { try { Thread.sleep(1); } catch (Exception e) {} } } /** * Set the mouse cursor to be displayed - this is a hardware cursor and hence * shouldn't have any impact on FPS. * * @param ref The location of the image to be loaded for the cursor * @param hotSpotX The x coordinate of the hotspot within the cursor image * @param hotSpotY The y coordinate of the hotspot within the cursor image * @throws SlickException Indicates a failure to load the cursor image or create the hardware cursor */ public abstract void setMouseCursor(String ref, int hotSpotX, int hotSpotY) throws SlickException; /** * Set the mouse cursor to be displayed - this is a hardware cursor and hence * shouldn't have any impact on FPS. * * @param data The image data from which the cursor can be construted * @param hotSpotX The x coordinate of the hotspot within the cursor image * @param hotSpotY The y coordinate of the hotspot within the cursor image * @throws SlickException Indicates a failure to load the cursor image or create the hardware cursor */ public abstract void setMouseCursor(ImageData data, int hotSpotX, int hotSpotY) throws SlickException; /** * Set the mouse cursor based on the contents of the image. Note that this will not take * account of render state type changes to images (rotation and such). If these effects * are required it is recommended that an offscreen buffer be used to produce an appropriate * image. An offscreen buffer will always be used to produce the new cursor and as such * this operation an be very expensive * * @param image The image to use as the cursor * @param hotSpotX The x coordinate of the hotspot within the cursor image * @param hotSpotY The y coordinate of the hotspot within the cursor image * @throws SlickException Indicates a failure to load the cursor image or create the hardware cursor */ public abstract void setMouseCursor(Image image, int hotSpotX, int hotSpotY) throws SlickException; /** * Set the mouse cursor to be displayed - this is a hardware cursor and hence * shouldn't have any impact on FPS. * * @param cursor The cursor to use * @param hotSpotX The x coordinate of the hotspot within the cursor image * @param hotSpotY The y coordinate of the hotspot within the cursor image * @throws SlickException Indicates a failure to load the cursor image or create the hardware cursor */ public abstract void setMouseCursor(Cursor cursor, int hotSpotX, int hotSpotY) throws SlickException; /** * Get a cursor based on a image reference on the classpath. The image * is assumed to be a set/strip of cursor animation frames running from top to * bottom. * * @param ref The reference to the image to be loaded * @param x The x-coordinate of the cursor hotspot (left -> right) * @param y The y-coordinate of the cursor hotspot (bottom -> top) * @param width The x width of the cursor * @param height The y height of the cursor * @param cursorDelays image delays between changing frames in animation * * @throws SlickException Indicates a failure to load the image or a failure to create the hardware cursor */ public void setAnimatedMouseCursor(String ref, int x, int y, int width, int height, int[] cursorDelays) throws SlickException { try { Cursor cursor; cursor = CursorLoader.get().getAnimatedCursor(ref, x, y, width, height, cursorDelays); setMouseCursor(cursor, x, y); } catch (IOException e) { throw new SlickException("Failed to set mouse cursor", e); } catch (LWJGLException e) { throw new SlickException("Failed to set mouse cursor", e); } } /** * Set the default mouse cursor - i.e. the original cursor before any native * cursor was set */ public abstract void setDefaultMouseCursor(); /** * Get the input system * * @return The input system available to this game container */ public Input getInput() { return input; } /** * Get the current recorded FPS (frames per second) * * @return The current FPS */ public int getFPS() { return recordedFPS; } /** * Indicate whether mouse cursor should be grabbed or not * * @param grabbed True if mouse cursor should be grabbed */ public abstract void setMouseGrabbed(boolean grabbed); /** * Check if the mouse cursor is current grabbed. This will cause it not * to be seen. * * @return True if the mouse is currently grabbed */ public abstract boolean isMouseGrabbed(); /** * Retrieve the time taken to render the last frame, i.e. the change in time - delta. * * @return The time taken to render the last frame */ protected int getDelta() { long time = getTime(); int delta = (int) (time - lastFrame); lastFrame = time; return delta; } /** * Updated the FPS counter */ protected void updateFPS() { if (getTime() - lastFPS > 1000) { lastFPS = getTime(); recordedFPS = fps; fps = 0; } fps++; } /** * Set the minimum amount of time in milliseonds that has to * pass before update() is called on the container game. This gives * a way to limit logic updates compared to renders. * * @param interval The minimum interval between logic updates */ public void setMinimumLogicUpdateInterval(int interval) { minimumLogicInterval = interval; } /** * Set the maximum amount of time in milliseconds that can passed * into the update method. Useful for collision detection without * sweeping. * * @param interval The maximum interval between logic updates */ public void setMaximumLogicUpdateInterval(int interval) { maximumLogicInterval = interval; } /** * Update and render the game * * @param delta The change in time since last update and render * @throws SlickException Indicates an internal fault to the game. */ protected void updateAndRender(int delta) throws SlickException { if (smoothDeltas) { if (getFPS() != 0) { delta = 1000 / getFPS(); } } input.poll(width, height); Music.poll(delta); if (!paused) { storedDelta += delta; if (storedDelta >= minimumLogicInterval) { try { if (maximumLogicInterval != 0) { long cycles = storedDelta / maximumLogicInterval; for (int i=0;i<cycles;i++) { game.update(this, (int) maximumLogicInterval); } int remainder = (int) (storedDelta % maximumLogicInterval); if (remainder > minimumLogicInterval) { game.update(this, (int) (remainder % maximumLogicInterval)); storedDelta = 0; } else { storedDelta = remainder; } } else { game.update(this, (int) storedDelta); storedDelta = 0; } } catch (Throwable e) { Log.error(e); throw new SlickException("Game.update() failure - check the game code."); } } } else { game.update(this, 0); } if (hasFocus() || getAlwaysRender()) { if (clearEachFrame) { GL.glClear(SGL.GL_COLOR_BUFFER_BIT | SGL.GL_DEPTH_BUFFER_BIT); } GL.glLoadIdentity(); graphics.resetTransform(); graphics.resetFont(); graphics.resetLineWidth(); graphics.setAntiAlias(false); try { game.render(this, graphics); } catch (Throwable e) { Log.error(e); throw new SlickException("Game.render() failure - check the game code."); } graphics.resetTransform(); if (showFPS) { defaultFont.drawString(10, 10, "FPS: "+recordedFPS); } GL.flush(); } if (targetFPS != -1) { Display.sync(targetFPS); } } /** * Indicate if the display should update only when the game is visible * (the default is true) * * @param updateOnlyWhenVisible True if we should updated only when the display is visible */ public void setUpdateOnlyWhenVisible(boolean updateOnlyWhenVisible) { } /** * Check if this game is only updating when visible to the user (default = true) * * @return True if the game is only updated when the display is visible */ public boolean isUpdatingOnlyWhenVisible() { return true; } /** * Initialise the GL context */ protected void initGL() { Log.info("Starting display "+width+"x"+height); GL.initDisplay(width, height); if (input == null) { input = new Input(height); } input.init(height); // no need to remove listeners? //input.removeAllListeners(); if (game instanceof InputListener) { input.removeListener((InputListener) game); input.addListener((InputListener) game); } if (graphics != null) { graphics.setDimensions(getWidth(), getHeight()); } lastGame = game; } /** * Initialise the system components, OpenGL and OpenAL. * * @throws SlickException Indicates a failure to create a native handler */ protected void initSystem() throws SlickException { initGL(); setMusicVolume(1.0f); setSoundVolume(1.0f); graphics = new Graphics(width, height); defaultFont = graphics.getFont(); } /** * Enter the orthographic mode */ protected void enterOrtho() { enterOrtho(width, height); } /** * Indicate whether the container should show the FPS * * @param show True if the container should show the FPS */ public void setShowFPS(boolean show) { showFPS = show; } /** * Check if the FPS is currently showing * * @return True if the FPS is showing */ public boolean isShowingFPS() { return showFPS; } /** * Set the target fps we're hoping to get * * @param fps The target fps we're hoping to get */ public void setTargetFrameRate(int fps) { targetFPS = fps; } /** * Indicate whether the display should be synced to the * vertical refresh (stops tearing) * * @param vsync True if we want to sync to vertical refresh */ public void setVSync(boolean vsync) { this.vsync = vsync; Display.setVSyncEnabled(vsync); } /** * True if vsync is requested * * @return True if vsync is requested */ public boolean isVSyncRequested() { return vsync; } /** * True if the game is running * * @return True if the game is running */ protected boolean running() { return running; } /** * Inidcate we want verbose logging * * @param verbose True if we want verbose logging (INFO and DEBUG) */ public void setVerbose(boolean verbose) { Log.setVerbose(verbose); } /** * Cause the game to exit and shutdown cleanly */ public void exit() { running = false; } /** * Check if the game currently has focus * * @return True if the game currently has focus */ public abstract boolean hasFocus(); /** * Get the graphics context used by this container. Note that this * value may vary over the life time of the game. * * @return The graphics context used by this container */ public Graphics getGraphics() { return graphics; } /** * Enter the orthographic mode * * @param xsize The size of the panel being used * @param ysize The size of the panel being used */ protected void enterOrtho(int xsize, int ysize) { GL.enterOrtho(xsize, ysize); } }
[ "nicolas+github@guillaumin.me" ]
nicolas+github@guillaumin.me
73b78fea87e0e143f0c326b92c6efb9f946694b9
4c6b527307881d13804ead88aa53cb04845f5f8c
/lib/objectify-2.2.1/src/com/googlecode/objectify/ObjectifyOpts.java
f4a5fd6d52899f7d8519f7dbc699e43242790100
[ "MIT" ]
permissive
sflores/Prendamigo
f49c6d8dc4b51c00e5e7b330555f7442836f1c1d
764b1831f2cfdcc43cee830ec2d3f2dc46de1baf
refs/heads/master
2021-03-13T00:06:27.153098
2011-01-15T00:44:34
2011-01-15T00:44:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,395
java
package com.googlecode.objectify; import com.google.appengine.api.datastore.ReadPolicy.Consistency; /** * <p>The options available when creating an Objectify instance.</p> * * <p>The default options are:</p> * * <ul> * <li>Do NOT begin a transaction.</li> * <li>Do NOT use a session cache.</li> * <li>DO use a global cache.</li> * <li>Use STRONG consistency.</li> * <li>Apply no deadline to calls.</li> * </ul> * * @author Jeff Schnitzer <jeff@infohazard.org> */ public class ObjectifyOpts { boolean beginTransaction; boolean sessionCache = false; boolean globalCache = true; Consistency consistency = Consistency.STRONG; Double deadline; /** Gets the current value of beginTransaction */ public boolean getBeginTransaction() { return this.beginTransaction; } /** * Sets whether or not the Objectify instance will start a transaction. If * true, the instance will hold a transaction that must be rolled back or * committed. */ public ObjectifyOpts setBeginTransaction(boolean value) { this.beginTransaction = value; return this; } /** Gets whether or not the Objectify instance will maintain a session cache */ public boolean getSessionCache() { return this.sessionCache; } /** * Sets whether or not the Objectify instance will maintain a session cache. * If true, all entities fetched from the datastore (or the 2nd level memcache) * will be stored as-is in a hashmap within the Objectify instance. Repeated * get()s or queries for the same entity will return the same object. */ public ObjectifyOpts setSessionCache(boolean value) { this.sessionCache = value; return this; } /** Gets whether or not the Objectify instance will use a 2nd-level memcache */ public boolean getGlobalCache() { return this.globalCache; } /** * Sets whether or not the Objectify instance will use a 2nd-level memcache. * If true, Objectify will obey the @Cached annotation on entity classes, * saving entity data to the GAE memcache service. Fetches from the datastore * for @Cached entities will look in the memcache service first. This cache * is shared across all versions of your application across the entire GAE * cluster. */ public ObjectifyOpts setGlobalCache(boolean value) { this.globalCache = value; return this; } /** Gets the initial consistency setting for the Objectify instance */ public Consistency getConsistency() { return this.consistency; } /** * Sets the initial consistency value for the Objectify instance. See the * <a href="http://code.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/ReadPolicy.Consistency.html">Appengine Docs</a> * for an explanation of Consistency. */ public ObjectifyOpts setConsistency(Consistency value) { if (value == null) throw new IllegalArgumentException("Consistency cannot be null"); this.consistency = value; return this; } /** Gets the deadline for datastore calls, in seconds */ public Double getDeadline() { return this.deadline; } /** * Sets a limit, in seconds, for datastore calls. If datastore calls take longer * than this amount, an exception will be thrown. * * @param value can be null to indicate no deadline (other than the standard whole * request deadline of 30s). */ public ObjectifyOpts setDeadline(Double value) { this.deadline = value; return this; } }
[ "sflores@prendamigo.com" ]
sflores@prendamigo.com
bf2387efc8a9e3bca220e297313037b44657fec6
396384ae649e04f1644730d8f8b8bb5ac36b1cab
/iot_spring/src/main/java/com/iot/spring/dao/NaverTransDAO.java
fd59cf3506e662d9c7bf1a04d498bfa92e13f303
[]
no_license
jiyungg/Spring
8aff80d511080f7c81f0f27cb8213f54bc89eb78
f5ffc4bd4ea88680a0a077d857054a1f4edcd25d
refs/heads/master
2021-09-06T21:25:23.850934
2018-02-11T16:45:47
2018-02-11T16:45:47
119,961,831
0
0
null
null
null
null
UTF-8
Java
false
false
158
java
package com.iot.spring.dao; import java.io.IOException; public interface NaverTransDAO { public String getText(String text)throws IOException ; }
[ "DJA@DJA-PC" ]
DJA@DJA-PC
902e41bbffe365f65cfbdfcbb371625faad427c0
e9d3f2be6be67823129bf7b30c01dd896043b41c
/kr.re.etri.tpl/src/kr/re/etri/tpl/script/actions/RulerBreakpointAction.java
8db6d29b884b000cd485bb9ec5634a5855e22b01
[]
no_license
OPRoS/TaskEditor
d248e131b0d7bac0002c41f52a9c6baea1096e86
5c3827868d8f77f02375910b38772127ba841d18
refs/heads/master
2020-04-05T08:19:46.058409
2013-08-27T05:31:01
2013-08-27T05:31:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
136
java
package kr.re.etri.tpl.script.actions; import org.eclipse.jface.action.Action; public class RulerBreakpointAction extends Action { }
[ "yudonguk@naver.com" ]
yudonguk@naver.com
3804b8390a2677d082fcfd1b4b80cfa51bbe663f
893f83189700fefeba216e6899d42097cc0bec70
/clones/clones/src/main/java/weka/filters/unsupervised/attribute/NumericToNominal.java
926c8210295468f9e1fe226ce6a66a4b4819fcff
[ "MIT" ]
permissive
pseudoPixels/SciWorCS
79249198b3dd2a2653d4401d0f028f2180338371
e1738c8b838c71b18598ceca29d7c487c76f876b
refs/heads/master
2021-06-10T01:08:30.242094
2018-12-06T18:53:34
2018-12-06T18:53:34
140,774,351
0
1
MIT
2021-06-01T22:23:47
2018-07-12T23:33:53
Python
UTF-8
Java
false
false
13,230
java
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * NumericToNominal.java * Copyright (C) 2006 University of Waikato, Hamilton, New Zealand */ package weka.filters.unsupervised.attribute; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Vector; import weka.core.Attribute; import weka.core.Capabilities; import weka.core.Capabilities.Capability; import weka.core.FastVector; import weka.core.Instance; import weka.core.Instances; import weka.core.Option; import weka.core.Range; import weka.core.RevisionUtils; import weka.core.SparseInstance; import weka.core.Utils; import weka.filters.SimpleBatchFilter; /** * <!-- globalinfo-start --> A filter for turning numeric attributes into * nominal ones. Unlike discretization, it just takes all numeric values and * adds them to the list of nominal values of that attribute. Useful after CSV * imports, to enforce certain attributes to become nominal, e.g., the class * attribute, containing values from 1 to 5. * <p/> * <!-- globalinfo-end --> * * <!-- options-start --> Valid options are: * <p/> * * <pre> * -R &lt;col1,col2-col4,...&gt; * Specifies list of columns to Discretize. First and last are valid indexes. * (default: first-last) * </pre> * * <pre> * -V * Invert matching sense of column indexes. * </pre> * * <!-- options-end --> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 10988 $ */ public class NumericToNominal extends SimpleBatchFilter { /** for serialization */ private static final long serialVersionUID = -6614630932899796239L; /** the maximum number of decimals to use */ protected final static int MAX_DECIMALS = 6; /** Stores which columns to turn into nominals */ protected Range m_Cols = new Range("first-last"); /** The default columns to turn into nominals */ protected String m_DefaultCols = "first-last"; /** * Returns a string describing this filter * * @return a description of the filter suitable for displaying in the * explorer/experimenter gui */ @Override public String globalInfo() { return "A filter for turning numeric attributes into nominal ones. Unlike " + "discretization, it just takes all numeric values and adds them to " + "the list of nominal values of that attribute. Useful after CSV " + "imports, to enforce certain attributes to become nominal, e.g., " + "the class attribute, containing values from 1 to 5."; } /** * Gets an enumeration describing the available options. * * @return an enumeration of all the available options. */ @Override public Enumeration listOptions() { Vector result = new Vector(); result.addElement(new Option( "\tSpecifies list of columns to Discretize. First" + " and last are valid indexes.\n" + "\t(default: first-last)", "R", 1, "-R <col1,col2-col4,...>")); result.addElement(new Option( "\tInvert matching sense of column indexes.", "V", 0, "-V")); return result.elements(); } /** * Parses a given list of options. * <p/> * * <!-- options-start --> Valid options are: * <p/> * * <pre> * -R &lt;col1,col2-col4,...&gt; * Specifies list of columns to Discretize. First and last are valid indexes. * (default: first-last) * </pre> * * <pre> * -V * Invert matching sense of column indexes. * </pre> * * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ @Override public void setOptions(String[] options) throws Exception { String tmpStr; super.setOptions(options); setInvertSelection(Utils.getFlag('V', options)); tmpStr = Utils.getOption('R', options); if (tmpStr.length() != 0) { setAttributeIndices(tmpStr); } else { setAttributeIndices(m_DefaultCols); } if (getInputFormat() != null) { setInputFormat(getInputFormat()); } } /** * Gets the current settings of the filter. * * @return an array of strings suitable for passing to setOptions */ @Override public String[] getOptions() { int i; Vector result; String[] options; result = new Vector(); options = super.getOptions(); for (i = 0; i < options.length; i++) { result.add(options[i]); } if (!getAttributeIndices().equals("")) { result.add("-R"); result.add(getAttributeIndices()); } if (getInvertSelection()) { result.add("-V"); } return (String[]) result.toArray(new String[result.size()]); } /** * Returns the tip text for this property * * @return tip text for this property suitable for displaying in the * explorer/experimenter gui */ public String invertSelectionTipText() { return "Set attribute selection mode. If false, only selected" + " (numeric) attributes in the range will be 'nominalized'; if" + " true, only non-selected attributes will be 'nominalized'."; } /** * Gets whether the supplied columns are to be worked on or the others. * * @return true if the supplied columns will be worked on */ public boolean getInvertSelection() { return m_Cols.getInvert(); } /** * Sets whether selected columns should be worked on or all the others apart * from these. If true all the other columns are considered for * "nominalization". * * @param value the new invert setting */ public void setInvertSelection(boolean value) { m_Cols.setInvert(value); } /** * Returns the tip text for this property * * @return tip text for this property suitable for displaying in the * explorer/experimenter gui */ public String attributeIndicesTipText() { return "Specify range of attributes to act on." + " This is a comma separated list of attribute indices, with" + " \"first\" and \"last\" valid values. Specify an inclusive" + " range with \"-\". E.g: \"first-3,5,6-10,last\"."; } /** * Gets the current range selection * * @return a string containing a comma separated list of ranges */ public String getAttributeIndices() { return m_Cols.getRanges(); } /** * Sets which attributes are to be "nominalized" (only numeric attributes * among the selection will be transformed). * * @param value a string representing the list of attributes. Since the string * will typically come from a user, attributes are indexed from 1. <br> * eg: first-3,5,6-last * @throws IllegalArgumentException if an invalid range list is supplied */ public void setAttributeIndices(String value) { m_Cols.setRanges(value); } /** * Sets which attributes are to be transoformed to nominal. (only numeric * attributes among the selection will be transformed). * * @param value an array containing indexes of attributes to nominalize. Since * the array will typically come from a program, attributes are * indexed from 0. * @throws IllegalArgumentException if an invalid set of ranges is supplied */ public void setAttributeIndicesArray(int[] value) { setAttributeIndices(Range.indicesToRangeList(value)); } /** * Returns the Capabilities of this filter. * * @return the capabilities of this object * @see Capabilities */ @Override public Capabilities getCapabilities() { Capabilities result = super.getCapabilities(); result.disableAll(); // attributes result.enableAllAttributes(); result.enable(Capability.MISSING_VALUES); // class result.enableAllClasses(); result.enable(Capability.MISSING_CLASS_VALUES); result.enable(Capability.NO_CLASS); return result; } /** * Determines the output format based on the input format and returns this. In * case the output format cannot be returned immediately, i.e., * immediateOutputFormat() returns false, then this method will be called from * batchFinished(). * * @param inputFormat the input format to base the output format on * @return the output format * @throws Exception in case the determination goes wrong * @see #hasImmediateOutputFormat() * @see #batchFinished() */ @Override protected Instances determineOutputFormat(Instances inputFormat) throws Exception { Instances data; Instances result; FastVector atts; FastVector values; HashSet hash; int i; int n; boolean isDate; Instance inst; Vector sorted; m_Cols.setUpper(inputFormat.numAttributes() - 1); data = new Instances(inputFormat); atts = new FastVector(); for (i = 0; i < data.numAttributes(); i++) { if (!m_Cols.isInRange(i) || !data.attribute(i).isNumeric()) { atts.addElement(data.attribute(i)); continue; } // date attribute? isDate = (data.attribute(i).type() == Attribute.DATE); // determine all available attribtues in dataset hash = new HashSet(); for (n = 0; n < data.numInstances(); n++) { inst = data.instance(n); if (inst.isMissing(i)) { continue; } if (isDate) { hash.add(inst.stringValue(i)); } else { hash.add(new Double(inst.value(i))); } } // sort values sorted = new Vector(); for (Object o : hash) { sorted.add(o); } Collections.sort(sorted); // create attribute from sorted values values = new FastVector(); for (Object o : sorted) { if (isDate) { values.addElement( o.toString()); } else { values.addElement( Utils.doubleToString(((Double) o).doubleValue(), MAX_DECIMALS)); } } Attribute newAtt = new Attribute(data.attribute(i).name(), values); newAtt.setWeight(data.attribute(i).weight()); atts.addElement(newAtt); } result = new Instances(inputFormat.relationName(), atts, 0); result.setClassIndex(inputFormat.classIndex()); return result; } /** * Processes the given data (may change the provided dataset) and returns the * modified version. This method is called in batchFinished(). * * @param instances the data to process * @return the modified data * @throws Exception in case the processing goes wrong * @see #batchFinished() */ @Override protected Instances process(Instances instances) throws Exception { Instances result; int i; int n; double[] values; String value; Instance inst; Instance newInst; // we need the complete input data! if (!isFirstBatchDone()) { setOutputFormat(determineOutputFormat(getInputFormat())); } result = new Instances(getOutputFormat()); for (i = 0; i < instances.numInstances(); i++) { inst = instances.instance(i); values = inst.toDoubleArray(); for (n = 0; n < values.length; n++) { if (!m_Cols.isInRange(n) || !instances.attribute(n).isNumeric() || inst.isMissing(n)) { continue; } // get index of value if (instances.attribute(n).type() == Attribute.DATE) { value = inst.stringValue(n); } else { value = Utils.doubleToString(inst.value(n), MAX_DECIMALS); } int index = result.attribute(n).indexOfValue(value); if (index == -1) { values[n] = Instance.missingValue(); } else { values[n] = index; } } // generate new instance if (inst instanceof SparseInstance) { newInst = new SparseInstance(inst.weight(), values); } else { newInst = new Instance(inst.weight(), values); } // copy possible string, relational values newInst.setDataset(getOutputFormat()); copyValues(newInst, false, inst.dataset(), getOutputFormat()); result.add(newInst); } return result; } /** * Returns the revision string. * * @return the revision */ @Override public String getRevision() { return RevisionUtils.extract("$Revision: 10988 $"); } /** * Runs the filter with the given parameters. Use -h to list options. * * @param args the commandline options */ public static void main(String[] args) { runFilter(new NumericToNominal(), args); } }
[ "golam.mostaeen@usask.ca" ]
golam.mostaeen@usask.ca
6249e31c248bb4e391f3b4dc8c930356eebaf633
a14d6f062012132b46138efffd1eb11bfe568aa7
/test/unitTests/ControllerTest.java
6e718adec097ac1aea322643aa91d1c3c5903a22
[]
no_license
benetal/SudokuSolver_Alan_David
f40fe62f8384df3aff20d1cffc96f08b11ccd510
d108437d5b1ab58f3b6dd61f6a661ca587282eac
refs/heads/master
2022-10-28T21:41:32.781723
2020-06-11T16:33:26
2020-06-11T16:33:26
268,727,761
0
0
null
null
null
null
UTF-8
Java
false
false
141
java
package unitTests; import org.junit.jupiter.api.Test; class ControllerTest { @Test void testIfJsonFileOutputIsTrue() { } }
[ "alan.benetal.benet@gmail.com" ]
alan.benetal.benet@gmail.com
37da3b3cdff87dd970c4f5e74412276e986fcbab
e8bab894e6fc517b7de14ae93e6ecafd5ba69880
/src/com/launcher/simulator/Simulator.java
1f20b3e8194cb2050220ca4df03756f25f702ebe
[]
no_license
HRossouw42/avaj-launcher
a4adb9291ae8332624693f0a4314108ab0370734
37479bc1c1ac0f5c2fdb964ad0c9ff5458bf9b81
refs/heads/master
2020-06-09T18:35:43.959455
2019-07-08T08:39:46
2019-07-08T08:39:46
193,485,515
0
1
null
null
null
null
UTF-8
Java
false
false
3,176
java
package com.launcher.simulator; import com.launcher.simulator.vehicles.AircraftFactory; import com.launcher.simulator.vehicles.Flyable; import com.launcher.weather.WeatherTower; import java.io.*; import java.util.ArrayList; import java.util.List; public class Simulator { private static WeatherTower weatherTower; private static List<Flyable> flyablesList = new ArrayList<>(); public static void main(String[] args) throws FileNotFoundException { System.out.println("Scanning Simulations File"); if (args.length != 1) { System.out.println("Failed"); return; } //clears file first PrintWriter pw = new PrintWriter("simulation.txt"); pw.close(); // The name of the file to open. // In this case the first argument in java starts at [0] System.out.println("Reading from file: " + args[0]); String fileName = args[0]; try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); String line = reader.readLine(); if (line != null) { weatherTower = new WeatherTower(); //System.out.println("New WeatherTower: " + weatherTower); int simulations = Integer.parseInt(line.split(" ")[0]); if (simulations < 0) { //System.out.println("Simulation count " + simulations + " invalid."); System.exit(1); } //System.out.println("Simulation count " + simulations); while ((line = reader.readLine()) != null) { Flyable flyable = AircraftFactory.newAircraft( line.split(" ")[0], line.split(" ")[1], Integer.parseInt(line.split(" ")[2]), Integer.parseInt(line.split(" ")[3]), Integer.parseInt(line.split(" ")[4])); flyablesList.add(flyable); //System.out.println(flyablesList); } for (Flyable flyable : flyablesList) { //System.out.println(flyable); flyable.registerTower(weatherTower); } for (int i = 1; i <= simulations; i++) { System.out.println("Simulation # " + i); weatherTower.writeToFile("write", "Simulation # " + i + "\n"); weatherTower.changeWeather(); } reader.close(); } } catch (FileNotFoundException ex) { System.out.println( "Unable to open file '" + fileName + "'"); } catch (IOException ex) { System.out.println( "Error reading file '" + fileName + "'"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println( "Choose a simulation file" ); } finally { System.out.println("Simulations ended."); } } }
[ "hrossouw@student.wethinkcode.co.za" ]
hrossouw@student.wethinkcode.co.za
2335e36ebffd3953254e410bd12c84610fd6e630
525bef1c13d03393ec176faf7ea0b5025abe85c7
/work/jspc/java/org/jivesoftware/openfire/admin/group_002dsummary_jsp.java
9ab250a00b036d2c5d6b56a5a693667f8f75e29d
[]
no_license
UniqueJoker11/openfire
b3d5a6c8b8f62376975252f4168fbd9a337a1ef6
10dc456abe50e85688ad3033bf7ca705fdbc70f4
refs/heads/master
2016-09-12T10:14:57.417200
2016-04-28T08:39:02
2016-04-28T08:39:02
57,284,626
0
0
null
null
null
null
UTF-8
Java
false
false
37,326
java
/* * Generated by the Jasper component of Apache Tomcat * Version: JspC/ApacheTomcat8 * Generated at: 2016-04-28 05:15:33 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.jivesoftware.openfire.admin; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import org.jivesoftware.util.*; import java.util.*; import org.jivesoftware.openfire.group.*; import java.net.URLEncoder; public final class group_002dsummary_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public void _jspInit() { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } public void _jspDestroy() { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.release(); } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\n\n\n\n\n\n\n"); org.jivesoftware.util.WebManager webManager = null; webManager = (org.jivesoftware.util.WebManager) _jspx_page_context.getAttribute("webManager", javax.servlet.jsp.PageContext.PAGE_SCOPE); if (webManager == null){ webManager = new org.jivesoftware.util.WebManager(); _jspx_page_context.setAttribute("webManager", webManager, javax.servlet.jsp.PageContext.PAGE_SCOPE); } out.write('\n'); webManager.init(request, response, session, application, out ); out.write("\n\n<html>\n <head>\n <title>"); if (_jspx_meth_fmt_005fmessage_005f0(_jspx_page_context)) return; out.write("</title>\n <meta name=\"pageID\" content=\"group-summary\"/>\n <meta name=\"helpPage\" content=\"about_users_and_groups.html\"/>\n </head>\n <body>\n\n"); // Get parameters int start = ParamUtils.getIntParameter(request,"start",0); int range = ParamUtils.getIntParameter(request,"range",webManager.getRowsPerPage("group-summary", 15)); if (request.getParameter("range") != null) { webManager.setRowsPerPage("group-summary", range); } int groupCount = webManager.getGroupManager().getGroupCount(); Collection<Group> groups = webManager.getGroupManager().getGroups(start, range); String search = null; if (webManager.getGroupManager().isSearchSupported() && request.getParameter("search") != null && !request.getParameter("search").trim().equals("")) { search = request.getParameter("search"); // Santize variables to prevent vulnerabilities search = StringUtils.escapeHTMLTags(search); // Use the search terms to get the list of groups and group count. groups = webManager.getGroupManager().search(search, start, range); // Get the count as a search for *all* groups. That will let us do pagination even // though it's a bummer to execute the search twice. groupCount = webManager.getGroupManager().search(search).size(); } // paginator vars int numPages = (int)Math.ceil((double)groupCount/(double)range); int curPage = (start/range) + 1; out.write('\n'); out.write('\n'); if (request.getParameter("deletesuccess") != null) { out.write("\n\n <div class=\"jive-success\">\n <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n <tbody>\n <tr><td class=\"jive-icon\"><img src=\"images/success-16x16.gif\" width=\"16\" height=\"16\" border=\"0\" alt=\"\"></td>\n <td class=\"jive-icon-label\">\n "); if (_jspx_meth_fmt_005fmessage_005f1(_jspx_page_context)) return; out.write("\n </td></tr>\n </tbody>\n </table>\n </div><br>\n\n"); } out.write('\n'); out.write('\n'); if (webManager.getGroupManager().isSearchSupported()) { out.write("\n\n<form action=\"group-summary.jsp\" method=\"get\" name=\"searchForm\">\n<table border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">\n <tr>\n <td valign=\"bottom\">\n"); if (_jspx_meth_fmt_005fmessage_005f2(_jspx_page_context)) return; out.write(" <b>"); out.print( groupCount ); out.write("</b>\n"); if (numPages > 1) { out.write("\n\n , "); if (_jspx_meth_fmt_005fmessage_005f3(_jspx_page_context)) return; out.write(' '); out.print( LocaleUtils.getLocalizedNumber(start+1) ); out.write('-'); out.print( LocaleUtils.getLocalizedNumber(start+range > groupCount ? groupCount:start+range) ); out.write('\n'); out.write('\n'); } out.write("\n </td>\n <td align=\"right\" valign=\"bottom\">\n "); if (_jspx_meth_fmt_005fmessage_005f4(_jspx_page_context)) return; out.write(": <input type=\"text\" size=\"30\" maxlength=\"150\" name=\"search\" value=\""); out.print( ((search!=null) ? search : "") ); out.write("\">\n </td>\n </tr>\n</table>\n</form>\n\n<script language=\"JavaScript\" type=\"text/javascript\">\ndocument.searchForm.search.focus();\n</script>\n\n"); } // Otherwise, searching is not supported. else { out.write("\n <p>\n "); if (_jspx_meth_fmt_005fmessage_005f5(_jspx_page_context)) return; out.write(" <b>"); out.print( groupCount ); out.write("</b>\n "); if (numPages > 1) { out.write("\n\n , "); if (_jspx_meth_fmt_005fmessage_005f6(_jspx_page_context)) return; out.write(' '); out.print( (start+1) ); out.write('-'); out.print( (start+range) ); out.write("\n\n "); } out.write("\n </p>\n"); } out.write('\n'); out.write('\n'); if (numPages > 1) { out.write("\n\n <p>\n "); if (_jspx_meth_fmt_005fmessage_005f7(_jspx_page_context)) return; out.write("\n [\n "); for (int i=0; i<numPages; i++) { String sep = ((i+1)<numPages) ? " " : ""; boolean isCurrent = (i+1) == curPage; out.write("\n <a href=\"group-summary.jsp?start="); out.print( (i*range) ); out.print( search!=null? "&search=" + URLEncoder.encode(search, "UTF-8") : ""); out.write("\"\n class=\""); out.print( ((isCurrent) ? "jive-current" : "") ); out.write("\"\n >"); out.print( (i+1) ); out.write("</a>"); out.print( sep ); out.write("\n\n "); } out.write("\n ]\n </p>\n\n"); } out.write("\n\n<div class=\"jive-table\">\n<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n<thead>\n <tr>\n <th>&nbsp;</th>\n <th nowrap>"); if (_jspx_meth_fmt_005fmessage_005f8(_jspx_page_context)) return; out.write("</th>\n <th nowrap>"); if (_jspx_meth_fmt_005fmessage_005f9(_jspx_page_context)) return; out.write("</th>\n <th nowrap>"); if (_jspx_meth_fmt_005fmessage_005f10(_jspx_page_context)) return; out.write("</th>\n "); // Only show edit and delete options if the groups aren't read-only. if (!webManager.getGroupManager().isReadOnly()) { out.write("\n <th nowrap>"); if (_jspx_meth_fmt_005fmessage_005f11(_jspx_page_context)) return; out.write("</th>\n <th nowrap>"); if (_jspx_meth_fmt_005fmessage_005f12(_jspx_page_context)) return; out.write("</th>\n "); } out.write("\n </tr>\n</thead>\n<tbody>\n\n"); // Print the list of groups if (groups.isEmpty()) { out.write("\n <tr>\n <td align=\"center\" colspan=\"6\">\n "); if (_jspx_meth_fmt_005fmessage_005f13(_jspx_page_context)) return; out.write("\n </td>\n </tr>\n\n"); } int i = start; for (Group group : groups) { String groupName = URLEncoder.encode(group.getName(), "UTF-8"); i++; out.write("\n <tr class=\"jive-"); out.print( (((i%2)==0) ? "even" : "odd") ); out.write("\">\n <td width=\"1%\" valign=\"top\">\n "); out.print( i ); out.write("\n </td>\n <td width=\"60%\">\n <a href=\"group-edit.jsp?group="); out.print( groupName ); out.write('"'); out.write('>'); out.print( StringUtils.escapeHTMLTags(group.getName()) ); out.write("</a>\n "); if (group.getDescription() != null) { out.write("\n <br>\n <span class=\"jive-description\">\n "); out.print( StringUtils.escapeHTMLTags(group.getDescription()) ); out.write("\n </span>\n "); } out.write("\n </td>\n <td width=\"10%\" align=\"center\">\n "); out.print( group.getMembers().size() ); out.write("\n </td>\n <td width=\"10%\" align=\"center\">\n "); out.print( group.getAdmins().size() ); out.write("\n </td>\n "); // Only show edit and delete options if the groups aren't read-only. if (!webManager.getGroupManager().isReadOnly()) { out.write("\n <td width=\"1%\" align=\"center\">\n <a href=\"group-edit.jsp?group="); out.print( groupName ); out.write("\"\n title="); if (_jspx_meth_fmt_005fmessage_005f14(_jspx_page_context)) return; out.write("\n ><img src=\"images/edit-16x16.gif\" width=\"16\" height=\"16\" border=\"0\" alt=\"\"></a>\n </td>\n <td width=\"1%\" align=\"center\" style=\"border-right:1px #ccc solid;\">\n <a href=\"group-delete.jsp?group="); out.print( groupName ); out.write("\"\n title="); if (_jspx_meth_fmt_005fmessage_005f15(_jspx_page_context)) return; out.write("\n ><img src=\"images/delete-16x16.gif\" width=\"16\" height=\"16\" border=\"0\" alt=\"\"></a>\n </td>\n "); } out.write("\n </tr>\n\n"); } out.write("\n</tbody>\n</table>\n</div>\n\n"); if (numPages > 1) { out.write("\n <br>\n <p>\n "); if (_jspx_meth_fmt_005fmessage_005f16(_jspx_page_context)) return; out.write("\n [\n "); for (i=0; i<numPages; i++) { String sep = ((i+1)<numPages) ? " " : ""; boolean isCurrent = (i+1) == curPage; out.write("\n <a href=\"group-summary.jsp?start="); out.print( (i*range) ); out.print( search!=null? "&search=" + URLEncoder.encode(search, "UTF-8") : ""); out.write("\"\n class=\""); out.print( ((isCurrent) ? "jive-current" : "") ); out.write("\"\n >"); out.print( (i+1) ); out.write("</a>"); out.print( sep ); out.write("\n\n "); } out.write("\n ]\n </p>\n\n"); } out.write("\n\n </body>\n</html>\n"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_fmt_005fmessage_005f0(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f0.setParent(null); // /group-summary.jsp(35,15) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f0.setKey("group.summary.title"); int _jspx_eval_fmt_005fmessage_005f0 = _jspx_th_fmt_005fmessage_005f0.doStartTag(); if (_jspx_th_fmt_005fmessage_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f0); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f0); return false; } private boolean _jspx_meth_fmt_005fmessage_005f1(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f1 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f1.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f1.setParent(null); // /group-summary.jsp(78,8) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f1.setKey("group.summary.delete_group"); int _jspx_eval_fmt_005fmessage_005f1 = _jspx_th_fmt_005fmessage_005f1.doStartTag(); if (_jspx_th_fmt_005fmessage_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f1); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f1); return false; } private boolean _jspx_meth_fmt_005fmessage_005f2(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f2 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f2.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f2.setParent(null); // /group-summary.jsp(92,0) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f2.setKey("group.summary.total_group"); int _jspx_eval_fmt_005fmessage_005f2 = _jspx_th_fmt_005fmessage_005f2.doStartTag(); if (_jspx_th_fmt_005fmessage_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f2); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f2); return false; } private boolean _jspx_meth_fmt_005fmessage_005f3(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f3 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f3.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f3.setParent(null); // /group-summary.jsp(95,6) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f3.setKey("global.showing"); int _jspx_eval_fmt_005fmessage_005f3 = _jspx_th_fmt_005fmessage_005f3.doStartTag(); if (_jspx_th_fmt_005fmessage_005f3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f3); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f3); return false; } private boolean _jspx_meth_fmt_005fmessage_005f4(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f4 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f4.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f4.setParent(null); // /group-summary.jsp(100,3) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f4.setKey("group.summary.search"); int _jspx_eval_fmt_005fmessage_005f4 = _jspx_th_fmt_005fmessage_005f4.doStartTag(); if (_jspx_th_fmt_005fmessage_005f4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f4); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f4); return false; } private boolean _jspx_meth_fmt_005fmessage_005f5(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f5 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f5.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f5.setParent(null); // /group-summary.jsp(115,4) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f5.setKey("group.summary.total_group"); int _jspx_eval_fmt_005fmessage_005f5 = _jspx_th_fmt_005fmessage_005f5.doStartTag(); if (_jspx_th_fmt_005fmessage_005f5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f5); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f5); return false; } private boolean _jspx_meth_fmt_005fmessage_005f6(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f6 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f6.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f6.setParent(null); // /group-summary.jsp(118,10) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f6.setKey("global.showing"); int _jspx_eval_fmt_005fmessage_005f6 = _jspx_th_fmt_005fmessage_005f6.doStartTag(); if (_jspx_th_fmt_005fmessage_005f6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f6); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f6); return false; } private boolean _jspx_meth_fmt_005fmessage_005f7(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f7 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f7.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f7.setParent(null); // /group-summary.jsp(127,4) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f7.setKey("global.pages"); int _jspx_eval_fmt_005fmessage_005f7 = _jspx_th_fmt_005fmessage_005f7.doStartTag(); if (_jspx_th_fmt_005fmessage_005f7.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f7); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f7); return false; } private boolean _jspx_meth_fmt_005fmessage_005f8(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f8 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f8.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f8.setParent(null); // /group-summary.jsp(148,19) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f8.setKey("group.summary.page_name"); int _jspx_eval_fmt_005fmessage_005f8 = _jspx_th_fmt_005fmessage_005f8.doStartTag(); if (_jspx_th_fmt_005fmessage_005f8.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f8); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f8); return false; } private boolean _jspx_meth_fmt_005fmessage_005f9(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f9 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f9.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f9.setParent(null); // /group-summary.jsp(149,19) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f9.setKey("group.summary.page_member"); int _jspx_eval_fmt_005fmessage_005f9 = _jspx_th_fmt_005fmessage_005f9.doStartTag(); if (_jspx_th_fmt_005fmessage_005f9.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f9); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f9); return false; } private boolean _jspx_meth_fmt_005fmessage_005f10(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f10 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f10.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f10.setParent(null); // /group-summary.jsp(150,19) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f10.setKey("group.summary.page_admin"); int _jspx_eval_fmt_005fmessage_005f10 = _jspx_th_fmt_005fmessage_005f10.doStartTag(); if (_jspx_th_fmt_005fmessage_005f10.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f10); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f10); return false; } private boolean _jspx_meth_fmt_005fmessage_005f11(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f11 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f11.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f11.setParent(null); // /group-summary.jsp(153,19) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f11.setKey("group.summary.page_edit"); int _jspx_eval_fmt_005fmessage_005f11 = _jspx_th_fmt_005fmessage_005f11.doStartTag(); if (_jspx_th_fmt_005fmessage_005f11.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f11); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f11); return false; } private boolean _jspx_meth_fmt_005fmessage_005f12(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f12 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f12.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f12.setParent(null); // /group-summary.jsp(154,19) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f12.setKey("global.delete"); int _jspx_eval_fmt_005fmessage_005f12 = _jspx_th_fmt_005fmessage_005f12.doStartTag(); if (_jspx_th_fmt_005fmessage_005f12.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f12); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f12); return false; } private boolean _jspx_meth_fmt_005fmessage_005f13(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f13 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f13.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f13.setParent(null); // /group-summary.jsp(165,12) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f13.setKey("group.summary.no_groups"); int _jspx_eval_fmt_005fmessage_005f13 = _jspx_th_fmt_005fmessage_005f13.doStartTag(); if (_jspx_th_fmt_005fmessage_005f13.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f13); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f13); return false; } private boolean _jspx_meth_fmt_005fmessage_005f14(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f14 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f14.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f14.setParent(null); // /group-summary.jsp(199,19) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f14.setKey("global.click_edit"); int _jspx_eval_fmt_005fmessage_005f14 = _jspx_th_fmt_005fmessage_005f14.doStartTag(); if (_jspx_th_fmt_005fmessage_005f14.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f14); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f14); return false; } private boolean _jspx_meth_fmt_005fmessage_005f15(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f15 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f15.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f15.setParent(null); // /group-summary.jsp(204,19) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f15.setKey("global.click_delete"); int _jspx_eval_fmt_005fmessage_005f15 = _jspx_th_fmt_005fmessage_005f15.doStartTag(); if (_jspx_th_fmt_005fmessage_005f15.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f15); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f15); return false; } private boolean _jspx_meth_fmt_005fmessage_005f16(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message org.apache.taglibs.standard.tag.rt.fmt.MessageTag _jspx_th_fmt_005fmessage_005f16 = (org.apache.taglibs.standard.tag.rt.fmt.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.MessageTag.class); _jspx_th_fmt_005fmessage_005f16.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f16.setParent(null); // /group-summary.jsp(220,4) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f16.setKey("global.pages"); int _jspx_eval_fmt_005fmessage_005f16 = _jspx_th_fmt_005fmessage_005f16.doStartTag(); if (_jspx_th_fmt_005fmessage_005f16.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f16); return true; } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f16); return false; } }
[ "yongyuandexiaochou@126.com" ]
yongyuandexiaochou@126.com
f2a7627abbc89bf151af7f888043c7a7154409f7
c988bae694f2da6805fdd650f2018e0da1a0a867
/Network/AddUser_hanwei/src/edu/cornell/opencomm/network/sp11/NetworkServices.java
54bc06914c2621ddf91ac7993f591a52908fc061
[]
no_license
moki80/OpenCommAndroid
b51254be041cd505e260fffe128c7b1c43fdba02
dcacf6def62eb79899375b521b260b8cf2e28864
refs/heads/master
2021-01-23T12:05:46.811360
2011-09-03T15:45:11
2011-09-03T15:45:11
1,588,908
1
0
null
null
null
null
UTF-8
Java
false
false
231
java
package edu.cornell.opencomm.network.sp11; public class NetworkServices { public static final String KEY_ADDUSERNAME = "addUsername"; public static final String ACTION_ADDUSER = "edu.cornell.opencomm.network.ACTION_ADDUSER"; }
[ "hk643@cornell.edu" ]
hk643@cornell.edu
08e3d19602e801ffbba1edf410a9c9f87cdddd3e
81d770f03b6bd67750bd161938e7ad13ce62e7e0
/src/main/java/com/store/storeapp/StoreappApplication.java
35a336d69825202c995aa45795b4d91173ac0287
[]
no_license
peterReilly11/storeapp
a4edaccb6740708934299202f458e6f5947e6192
727a9e7d3a9e953a071b4dc5c3252597ecc412c6
refs/heads/master
2023-04-04T07:55:36.302147
2021-04-16T20:48:00
2021-04-16T20:48:00
317,007,218
0
0
null
2021-04-16T20:48:01
2020-11-29T17:39:00
TypeScript
UTF-8
Java
false
false
1,613
java
package com.store.storeapp; /*import com.store.storeapp.model.Cart; import com.store.storeapp.model.CartItem; import java.util.Date; import java.util.stream.Stream; import com.store.storeapp.repository.CartItemRepository; import com.store.storeapp.repository.CartRepository; import com.store.storeapp.service.CartItemService; import com.store.storeapp.service.CartService; import org.springframework.boot.ApplicationRunner;*/ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; // import org.springframework.context.annotation.Bean; @SpringBootApplication public class StoreappApplication { public static void main(String[] args) { SpringApplication.run(StoreappApplication.class, args); } /* @Bean ApplicationRunner init(CartService cartService, CartItemService cartItemService, CartRepository cartRepository, CartItemRepository cartItemRepository) { Cart cart = cartService.createCart(); cart.setDeliveryCity("Chicago"); cart.setOrderPlaced(false); cart.setEmail("peter.reilly11@gmail.com"); Stream.of("Andromeda Galaxy", "Milky Way", "Earth").forEach(name -> { CartItem cartItem = new CartItem(); cartItem.setCart(cart); cartItem.setDateTimeCreated(new Date()); cartItem.setItemName(name); cartItem.setItemDescription(name + " Description"); cartItem.setItemURL(name + ".com"); cart.addCartItem(cartItem); }); cartService.putCart(cart); return args -> { cartRepository.findAll().forEach(System.out::println); cartItemRepository.findAll().forEach(System.out::println); }; } */ }
[ "peter.reilly11@gmail.com" ]
peter.reilly11@gmail.com
67f47e46f90790e601b285428f8f7baadeeeeba6
3b38f0b0d968f650a88f8cd5efb4d5e3e846a034
/src/main/java/br/com/sirius/gerador/repository/GeradorLicencaRepository.java
e2bd725aec7babaa3cf1738ccc8d450b68f8ee95
[]
no_license
juniormoraisjr/projetoGeradorLicenca
3392e710f47adf137224a0ed8aa344c5dc65b23e
0d7151e6f02cbcae654476a7c721ae28d236ba7e
refs/heads/master
2020-04-20T03:02:33.909414
2019-03-18T18:22:33
2019-03-18T18:22:33
168,586,973
0
1
null
null
null
null
UTF-8
Java
false
false
271
java
package br.com.sirius.gerador.repository; import org.springframework.data.mongodb.repository.MongoRepository; import br.com.sirius.gerador.repository.entity.GeradorLicenca; public interface GeradorLicencaRepository extends MongoRepository<GeradorLicenca, String> { }
[ "junior.morais@yahoo.com.br" ]
junior.morais@yahoo.com.br
35bbbe801cf3b0aea2054b9516cc7b270c0666a5
eb545aabffbbd6f1a4aa9b44f82e2b9bf877b72d
/src/com/ym/iadpush/manage/services/tissue/IMenuMgr.java
44c7e3af582df2818538ac5f0a9f260055d3edbc
[]
no_license
wangshuodong/lj_estate_manage
b0f005687667ee52c2dbfe2fb883fab91516b475
d6578662f9845f7c507709d59af0d543cc1dd3eb
refs/heads/master
2021-07-23T23:45:00.780154
2017-11-05T13:57:44
2017-11-05T13:57:44
105,353,557
1
0
null
null
null
null
UTF-8
Java
false
false
616
java
package com.ym.iadpush.manage.services.tissue; import java.util.List; import java.util.Map; import com.ym.iadpush.manage.entity.SysMenus; public interface IMenuMgr { public List<SysMenus> getAllMenus(Map<String, Object> paramsMap); public int updateMenu(SysMenus menu); public int insertMenu(SysMenus menu); public int deleteMenu(int menuId); public List<Map<String,String>> getParentMenus(); public SysMenus selectByPrimaryKey(Integer menuId); public int selectTotalRecord(Map<String, Object> paramsMap); public int countByMenuName(String menuName); }
[ "wawngshuodong2004@163.com" ]
wawngshuodong2004@163.com
ef323bce5cbe249a08f8aff4ee85ca0ea53526fc
9be0fb0644ee8088b21942155a826bb03aa6f212
/manager/src/main/java/com/hmxy/manager/service/shareMeet/impl/SharerMeettingServiceImpl.java
6076c4ed2f8cb6ec44902092b2cea87252e601da
[]
no_license
youzizzz/hmxy-manager
03600210c741046b4c41f55942498f9ab05bfc5d
e856aa213ea8469f266715f79420a786cd509d09
refs/heads/master
2020-04-04T16:17:51.268223
2018-11-16T08:45:51
2018-11-16T08:45:51
156,072,090
0
0
null
null
null
null
UTF-8
Java
false
false
2,245
java
package com.hmxy.manager.service.shareMeet.impl; import com.hmxy.dto.SharerMeettingDTO; import com.hmxy.http.HttpStatusEnum; import com.hmxy.http.Response; import com.hmxy.manager.dao.shareMeet.SysSharerMeettingDao; import com.hmxy.manager.service.shareMeet.SharerMeettingService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @discripeion: * @author: liangj * @date: 2018/11/13 17:26 */ @Service public class SharerMeettingServiceImpl implements SharerMeettingService { @Autowired private SysSharerMeettingDao sysSharerMeettingDao; @Override public Response<String> sharerMeettingAdd(SharerMeettingDTO sharerMeettingDTO) { Map<String,Object> map = new HashMap<String,Object>(); if (StringUtils.isNotBlank(sharerMeettingDTO.getSharerId())){ map.put("sharerId",sharerMeettingDTO.getSharerId()); } else { return new Response<String>().setStatusCode(HttpStatusEnum.error.getCode()).setMessage("分享者不能为空"); } if (StringUtils.isNotBlank(sharerMeettingDTO.getMettingId())){ map.put("mettingId",sharerMeettingDTO.getMettingId()); } else { return new Response<String>().setStatusCode(HttpStatusEnum.error.getCode()).setMessage("分享会不能为空"); } List<SharerMeettingDTO> list = new ArrayList<SharerMeettingDTO>(); list = sysSharerMeettingDao.getSharerMeettingList(map); if(null!=list&&list.size()>0){ return new Response<String>().setStatusCode(HttpStatusEnum.error.getCode()).setMessage("已经用此分享者"); } int count = 0; count = sysSharerMeettingDao.sharerMeettingAdd(sharerMeettingDTO); if(count<1){ return new Response<String>().setStatusCode(HttpStatusEnum.error.getCode()).setMessage("新增分享者和分享会信息失败"); } return new Response<String>().setStatusCode(HttpStatusEnum.success.getCode()).setMessage("新增分享者和分享会信息成功"); } }
[ "liangj@yuminsoft.com" ]
liangj@yuminsoft.com
ebb7c141f95ba5da4ef879149bbb5f41913ec89b
777ef1c11b577a9029995ac05fa36747c0d227d1
/src/main/java/com/slabs/insight/repository/EmployeeRepository.java
05564c58c783dd04b631d26dff79382fb6b7a5d0
[]
no_license
sunieldalal/insightapp
94bb498c2b8044ef7ace365a154de9a34a48ab96
d85753fa18410d25df0ff18e5abe19dec3b0214e
refs/heads/master
2020-04-06T06:04:34.852571
2017-07-19T05:56:42
2017-07-19T05:56:42
73,662,291
0
0
null
null
null
null
UTF-8
Java
false
false
388
java
package com.slabs.insight.repository; import java.util.List; import com.slabs.insight.domain.Employee; public interface EmployeeRepository { Employee createEmployee(Employee Employee); Employee getEmployeeById(Long IdPersonId); List<Employee> getAllEmployees(); Employee updateEmployee(Employee Employee); boolean deleteEmployeeById(Long IdPersonId); }
[ "sdalal@financialengines.com" ]
sdalal@financialengines.com
08e659cc4754871563181aa2c63825f032038126
81a392df9154206216bf954a8650240428123e0c
/src/main/java/fr/ippon/contest/puissance4/checker/VerticalChecker.java
2dc08e36137158f3ec4836d43dd1d6bae10e1373
[]
no_license
jlamby/finna-be-wallhack
5fceff1dbca32bc7c95d17baff9f8b2441fd0f11
b1b4688437afdd9755848e36fa7ed8d138ff9581
refs/heads/master
2016-09-06T09:29:46.305377
2015-03-25T15:00:00
2015-03-25T15:00:00
32,525,035
1
0
null
null
null
null
UTF-8
Java
false
false
673
java
package fr.ippon.contest.puissance4.checker; import java.util.ArrayList; import java.util.List; import fr.ippon.contest.puissance4.GameConstants; import fr.ippon.contest.puissance4.Puissance4; /** * @author jlamby * */ public class VerticalChecker extends BaseChecker { public VerticalChecker(Puissance4 game) { super(game); } @Override public boolean check(int startLine, int startRow) { List<Character> slice = new ArrayList<>(); for (int lineIndex = 0; lineIndex < GameConstants.MAX_LINES; lineIndex++) { slice.add(game.getOccupant(lineIndex, startRow)); } return checkSlice(slice); } }
[ "jlamby@tp.michelin.com" ]
jlamby@tp.michelin.com
f79f346cbb4fd2d3eddd83bc8c89112c5606defb
35abb8d8d40fe8ddf00931b106c10110cf66525c
/app/src/main/java/com/domain/apps/snapadeal/unbescape/json/JsonEscapeUtil.java
cd02ecd636bbb0eaf75867f6de40fb42143b4d0c
[]
no_license
tj4752/Snap_A_Deal
1cb01c087945256b0754a46db5f3b239e0ee75ed
259ec8fee8de98ab15687c34a70dfd79b341a0c4
refs/heads/master
2022-09-23T20:42:14.623867
2020-06-02T10:37:12
2020-06-02T10:37:12
268,166,866
0
0
null
null
null
null
UTF-8
Java
false
false
27,000
java
/* * ============================================================================= * * Copyright (c) 2014, The UNBESCAPE team (http://www.unbescape.org) * * 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.domain.apps.snapadeal.unbescape.json; import java.io.IOException; import java.io.Writer; import java.util.Arrays; /** * <p> * Internal class in charge of performing the real escape/unescape operations. * </p> * * @author Daniel Fern&aacute;ndez * @since 1.0.0 */ final class JsonEscapeUtil { /* * JSON ESCAPE/UNESCAPE OPERATIONS * ------------------------------- * * See: http://www.ietf.org/rfc/rfc4627.txt * http://timelessrepo.com/json-isnt-a-javascript-subset * http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/ * * (Note that, in the following examples, and in order to avoid escape problems during the compilation * of this class, the backslash symbol is replaced by '%') * * - SINGLE ESCAPE CHARACTERS (SECs): * U+0008 -> %b * U+0009 -> %t * U+000A -> %n * U+000C -> %f * U+000D -> %r * U+0022 -> %" * U+005C -> %% * U+002F -> %/ [ONLY USED WHEN / APPEARS IN </, IN ORDER TO AVOID ISSUES INSIDE <script> TAGS] * - UNICODE ESCAPE [UHEXA] * Characters <= U+FFFF: %u???? * Characters > U+FFFF : %u????%u???? (surrogate character pair) * %u{?*} [NOT USED - Possible syntax for ECMAScript 6] * * * ------------------------ * NOTE: JSON is NOT equivalent to the JavaScript Object Literal notation. JSON is just a format for * data interchange that happens to have a syntax that is ALMOST A SUBSET of the JavaScript Object * Literal notation (U+2028 and U+2029 LineTerminators are allowed in JSON but not in JavaScript). * ------------------------ * */ /* * Prefixes defined for use in escape and unescape operations */ private static final char ESCAPE_PREFIX = '\\'; private static final char ESCAPE_UHEXA_PREFIX2 = 'u'; private static final char[] ESCAPE_UHEXA_PREFIX = "\\u".toCharArray(); /* * Structured for holding the 'escape level' assigned to chars (not codepoints) up to ESCAPE_LEVELS_LEN. * - The last position of the ESCAPE_LEVELS array will be used for determining the level of all * codepoints >= (ESCAPE_LEVELS_LEN - 1) */ private static final char ESCAPE_LEVELS_LEN = 0x9f + 2; // Last relevant char to be indexed is 0x9f private static final byte[] ESCAPE_LEVELS; /* * Small utility char arrays for hexadecimal conversion. */ private static char[] HEXA_CHARS_UPPER = "0123456789ABCDEF".toCharArray(); private static char[] HEXA_CHARS_LOWER = "0123456789abcdef".toCharArray(); /* * Structures for holding the Single Escape Characters */ private static int SEC_CHARS_LEN = '\\' + 1; // 0x5C + 1 = 0x5D private static char SEC_CHARS_NO_SEC = '*'; private static char[] SEC_CHARS; static { /* * Initialize Single Escape Characters */ SEC_CHARS = new char[SEC_CHARS_LEN]; Arrays.fill(SEC_CHARS, SEC_CHARS_NO_SEC); SEC_CHARS[0x08] = 'b'; SEC_CHARS[0x09] = 't'; SEC_CHARS[0x0A] = 'n'; SEC_CHARS[0x0C] = 'f'; SEC_CHARS[0x0D] = 'r'; SEC_CHARS[0x22] = '"'; SEC_CHARS[0x5C] = '\\'; // slash (solidus) character: will only be escaped if in '</' SEC_CHARS[0x2F] = '/'; /* * Initialization of escape levels. * Defined levels : * * - Level 1 : Basic escape set * - Level 2 : Basic escape set plus all non-ASCII * - Level 3 : All non-alphanumeric characters * - Level 4 : All characters * */ ESCAPE_LEVELS = new byte[ESCAPE_LEVELS_LEN]; /* * Everything is level 3 unless contrary indication. */ Arrays.fill(ESCAPE_LEVELS, (byte) 3); /* * Everything non-ASCII is level 2 unless contrary indication. */ for (char c = 0x80; c < ESCAPE_LEVELS_LEN; c++) { ESCAPE_LEVELS[c] = 2; } /* * Alphanumeric characters are level 4. */ for (char c = 'A'; c <= 'Z'; c++) { ESCAPE_LEVELS[c] = 4; } for (char c = 'a'; c <= 'z'; c++) { ESCAPE_LEVELS[c] = 4; } for (char c = '0'; c <= '9'; c++) { ESCAPE_LEVELS[c] = 4; } /* * Simple Escape Character will be level 1 (always escaped) */ ESCAPE_LEVELS[0x08] = 1; ESCAPE_LEVELS[0x09] = 1; ESCAPE_LEVELS[0x0A] = 1; ESCAPE_LEVELS[0x0C] = 1; ESCAPE_LEVELS[0x0D] = 1; ESCAPE_LEVELS[0x22] = 1; ESCAPE_LEVELS[0x5C] = 1; // slash (solidus) character: will only be escaped if in '</', but we signal it as level 1 anyway ESCAPE_LEVELS[0x2F] = 1; /* * JSON defines one ranges of non-displayable, control characters: U+0000 to U+001F. * Additionally, the U+007F to U+009F range is also escaped (which is allowed). */ for (char c = 0x00; c <= 0x1F; c++) { ESCAPE_LEVELS[c] = 1; } for (char c = 0x7F; c <= 0x9F; c++) { ESCAPE_LEVELS[c] = 1; } } private JsonEscapeUtil() { super(); } static char[] toUHexa(final int codepoint) { final char[] result = new char[4]; result[3] = HEXA_CHARS_UPPER[codepoint % 0x10]; result[2] = HEXA_CHARS_UPPER[(codepoint >>> 4) % 0x10]; result[1] = HEXA_CHARS_UPPER[(codepoint >>> 8) % 0x10]; result[0] = HEXA_CHARS_UPPER[(codepoint >>> 12) % 0x10]; return result; } /* * Perform an escape operation, based on String, according to the specified level and type. */ static String escape(final String text, final JsonEscapeType escapeType, final JsonEscapeLevel escapeLevel) { if (text == null) { return null; } final int level = escapeLevel.getEscapeLevel(); final boolean useSECs = escapeType.getUseSECs(); StringBuilder strBuilder = null; final int offset = 0; final int max = text.length(); int readOffset = offset; for (int i = offset; i < max; i++) { final int codepoint = Character.codePointAt(text, i); /* * Shortcut: most characters will be ASCII/Alphanumeric, and we won't need to do anything at * all for them */ if (codepoint <= (ESCAPE_LEVELS_LEN - 2) && level < ESCAPE_LEVELS[codepoint]) { continue; } /* * Check whether the character is a slash (solidus). In such case, only escape if it * appears after a '<' ('</') or level >= 3 (non alphanumeric) */ if (codepoint == '/' && level < 3 && (i == offset || text.charAt(i - 1) != '<')) { continue; } /* * Shortcut: we might not want to escape non-ASCII chars at all either. */ if (codepoint > (ESCAPE_LEVELS_LEN - 2) && level < ESCAPE_LEVELS[ESCAPE_LEVELS_LEN - 1]) { if (Character.charCount(codepoint) > 1) { // This is to compensate that we are actually escaping two char[] positions with a single codepoint. i++; } continue; } /* * At this point we know for sure we will need some kind of escape, so we * can increase the offset and initialize the string builder if needed, along with * copying to it all the contents pending up to this point. */ if (strBuilder == null) { strBuilder = new StringBuilder(max + 20); } if (i - readOffset > 0) { strBuilder.append(text, readOffset, i); } if (Character.charCount(codepoint) > 1) { // This is to compensate that we are actually reading two char[] positions with a single codepoint. i++; } readOffset = i + 1; /* * ----------------------------------------------------------------------------------------- * * Peform the real escape, attending the different combinations of SECs and UHEXA * * ----------------------------------------------------------------------------------------- */ if (useSECs && codepoint < SEC_CHARS_LEN) { // We will try to use a SEC final char sec = SEC_CHARS[codepoint]; if (sec != SEC_CHARS_NO_SEC) { // SEC found! just write it and go for the next char strBuilder.append(ESCAPE_PREFIX); strBuilder.append(sec); continue; } } /* * No SEC-escape was possible, so we need uhexa escape. */ if (Character.charCount(codepoint) > 1) { final char[] codepointChars = Character.toChars(codepoint); strBuilder.append(ESCAPE_UHEXA_PREFIX); strBuilder.append(toUHexa(codepointChars[0])); strBuilder.append(ESCAPE_UHEXA_PREFIX); strBuilder.append(toUHexa(codepointChars[1])); continue; } strBuilder.append(ESCAPE_UHEXA_PREFIX); strBuilder.append(toUHexa(codepoint)); } /* * ----------------------------------------------------------------------------------------------- * Final cleaning: return the original String object if no escape was actually needed. Otherwise * append the remaining unescaped text to the string builder and return. * ----------------------------------------------------------------------------------------------- */ if (strBuilder == null) { return text; } if (max - readOffset > 0) { strBuilder.append(text, readOffset, max); } return strBuilder.toString(); } /* * Perform an escape operation, based on char[], according to the specified level and type. */ static void escape(final char[] text, final int offset, final int len, final Writer writer, final JsonEscapeType escapeType, final JsonEscapeLevel escapeLevel) throws IOException { if (text == null || text.length == 0) { return; } final int level = escapeLevel.getEscapeLevel(); final boolean useSECs = escapeType.getUseSECs(); final int max = (offset + len); int readOffset = offset; for (int i = offset; i < max; i++) { final int codepoint = Character.codePointAt(text, i); /* * Shortcut: most characters will be ASCII/Alphanumeric, and we won't need to do anything at * all for them */ if (codepoint <= (ESCAPE_LEVELS_LEN - 2) && level < ESCAPE_LEVELS[codepoint]) { continue; } /* * Check whether the character is a slash (solidus). In such case, only escape if it * appears after a '<' ('</') or level >= 3 (non alphanumeric) */ if (codepoint == '/' && level < 3 && (i == offset || text[i - 1] != '<')) { continue; } /* * Shortcut: we might not want to escape non-ASCII chars at all either. */ if (codepoint > (ESCAPE_LEVELS_LEN - 2) && level < ESCAPE_LEVELS[ESCAPE_LEVELS_LEN - 1]) { if (Character.charCount(codepoint) > 1) { // This is to compensate that we are actually escaping two char[] positions with a single codepoint. i++; } continue; } /* * At this point we know for sure we will need some kind of escape, so we * can write all the contents pending up to this point. */ if (i - readOffset > 0) { writer.write(text, readOffset, (i - readOffset)); } if (Character.charCount(codepoint) > 1) { // This is to compensate that we are actually reading two char[] positions with a single codepoint. i++; } readOffset = i + 1; /* * ----------------------------------------------------------------------------------------- * * Peform the real escape, attending the different combinations of SECs and UHEXA * * ----------------------------------------------------------------------------------------- */ if (useSECs && codepoint < SEC_CHARS_LEN) { // We will try to use a SEC final char sec = SEC_CHARS[codepoint]; if (sec != SEC_CHARS_NO_SEC) { // SEC found! just write it and go for the next char writer.write(ESCAPE_PREFIX); writer.write(sec); continue; } } /* * No SEC-escape was possible, so we need uhexa escape. */ if (Character.charCount(codepoint) > 1) { final char[] codepointChars = Character.toChars(codepoint); writer.write(ESCAPE_UHEXA_PREFIX); writer.write(toUHexa(codepointChars[0])); writer.write(ESCAPE_UHEXA_PREFIX); writer.write(toUHexa(codepointChars[1])); continue; } writer.write(ESCAPE_UHEXA_PREFIX); writer.write(toUHexa(codepoint)); } /* * ----------------------------------------------------------------------------------------------- * Final cleaning: return the original String object if no escape was actually needed. Otherwise * append the remaining unescaped text to the string builder and return. * ----------------------------------------------------------------------------------------------- */ if (max - readOffset > 0) { writer.write(text, readOffset, (max - readOffset)); } } /* * This methods (the two versions) are used instead of Integer.parseInt(str,radix) in order to avoid the need * to create substrings of the text being unescaped to feed such method. * - No need to check all chars are within the radix limits - reference parsing code will already have done so. */ static int parseIntFromReference(final String text, final int start, final int end, final int radix) { int result = 0; for (int i = start; i < end; i++) { final char c = text.charAt(i); int n = -1; for (int j = 0; j < HEXA_CHARS_UPPER.length; j++) { if (c == HEXA_CHARS_UPPER[j] || c == HEXA_CHARS_LOWER[j]) { n = j; break; } } result = (radix * result) + n; } return result; } static int parseIntFromReference(final char[] text, final int start, final int end, final int radix) { int result = 0; for (int i = start; i < end; i++) { final char c = text[i]; int n = -1; for (int j = 0; j < HEXA_CHARS_UPPER.length; j++) { if (c == HEXA_CHARS_UPPER[j] || c == HEXA_CHARS_LOWER[j]) { n = j; break; } } result = (radix * result) + n; } return result; } /* * Perform an unescape operation based on String. */ static String unescape(final String text) { if (text == null) { return null; } StringBuilder strBuilder = null; final int offset = 0; final int max = text.length(); int readOffset = offset; int referenceOffset = offset; for (int i = offset; i < max; i++) { final char c = text.charAt(i); /* * Check the need for an unescape operation at this point */ if (c != ESCAPE_PREFIX || (i + 1) >= max) { continue; } int codepoint = -1; if (c == ESCAPE_PREFIX) { final char c1 = text.charAt(i + 1); switch (c1) { case 'b': codepoint = 0x08; referenceOffset = i + 1; break; case 't': codepoint = 0x09; referenceOffset = i + 1; break; case 'n': codepoint = 0x0A; referenceOffset = i + 1; break; case 'f': codepoint = 0x0C; referenceOffset = i + 1; break; case 'r': codepoint = 0x0D; referenceOffset = i + 1; break; case '"': codepoint = 0x22; referenceOffset = i + 1; break; case '\\': codepoint = 0x5C; referenceOffset = i + 1; break; case '/': codepoint = 0x2F; referenceOffset = i + 1; break; } if (codepoint == -1) { if (c1 == ESCAPE_UHEXA_PREFIX2) { // This can be a uhexa escape, we need exactly four more characters int f = i + 2; while (f < (i + 6) && f < max) { final char cf = text.charAt(f); if (!((cf >= '0' && cf <= '9') || (cf >= 'A' && cf <= 'F') || (cf >= 'a' && cf <= 'f'))) { break; } f++; } if ((f - (i + 2)) < 4) { // We weren't able to consume the required four hexa chars, leave it as slash+'u', which // is invalid, and let the corresponding JSON parser fail. i++; continue; } codepoint = parseIntFromReference(text, i + 2, f, 16); // Fast-forward to the first char after the parsed codepoint referenceOffset = f - 1; // Don't continue here, just let the unescape code below do its job } else { // Other escape sequences are not allowed by JSON. So we leave it as is // and expect the corresponding JSON parser to fail. i++; continue; } } } /* * At this point we know for sure we will need some kind of unescape, so we * can increase the offset and initialize the string builder if needed, along with * copying to it all the contents pending up to this point. */ if (strBuilder == null) { strBuilder = new StringBuilder(max + 5); } if (i - readOffset > 0) { strBuilder.append(text, readOffset, i); } i = referenceOffset; readOffset = i + 1; /* * -------------------------- * * Peform the real unescape * * -------------------------- */ if (codepoint > '\uFFFF') { strBuilder.append(Character.toChars(codepoint)); } else { strBuilder.append((char) codepoint); } } /* * ----------------------------------------------------------------------------------------------- * Final cleaning: return the original String object if no unescape was actually needed. Otherwise * append the remaining escaped text to the string builder and return. * ----------------------------------------------------------------------------------------------- */ if (strBuilder == null) { return text; } if (max - readOffset > 0) { strBuilder.append(text, readOffset, max); } return strBuilder.toString(); } /* * Perform an unescape operation based on char[]. */ static void unescape(final char[] text, final int offset, final int len, final Writer writer) throws IOException { if (text == null) { return; } final int max = (offset + len); int readOffset = offset; int referenceOffset = offset; for (int i = offset; i < max; i++) { final char c = text[i]; /* * Check the need for an unescape operation at this point */ if (c != ESCAPE_PREFIX || (i + 1) >= max) { continue; } int codepoint = -1; if (c == ESCAPE_PREFIX) { final char c1 = text[i + 1]; switch (c1) { case 'b': codepoint = 0x08; referenceOffset = i + 1; break; case 't': codepoint = 0x09; referenceOffset = i + 1; break; case 'n': codepoint = 0x0A; referenceOffset = i + 1; break; case 'f': codepoint = 0x0C; referenceOffset = i + 1; break; case 'r': codepoint = 0x0D; referenceOffset = i + 1; break; case '"': codepoint = 0x22; referenceOffset = i + 1; break; case '\\': codepoint = 0x5C; referenceOffset = i + 1; break; case '/': codepoint = 0x2F; referenceOffset = i + 1; break; } if (codepoint == -1) { if (c1 == ESCAPE_UHEXA_PREFIX2) { // This can be a uhexa escape, we need exactly four more characters int f = i + 2; while (f < (i + 6) && f < max) { final char cf = text[f]; if (!((cf >= '0' && cf <= '9') || (cf >= 'A' && cf <= 'F') || (cf >= 'a' && cf <= 'f'))) { break; } f++; } if ((f - (i + 2)) < 4) { // We weren't able to consume the required four hexa chars, leave it as slash+'u', which // is invalid, and let the corresponding JSON parser fail. i++; continue; } codepoint = parseIntFromReference(text, i + 2, f, 16); // Fast-forward to the first char after the parsed codepoint referenceOffset = f - 1; // Don't continue here, just let the unescape code below do its job } else { // Other escape sequences are not allowed by JSON. So we leave it as is // and expect the corresponding JSON parser to fail. i++; continue; } } } /* * At this point we know for sure we will need some kind of unescape, so we * write all the contents pending up to this point. */ if (i - readOffset > 0) { writer.write(text, readOffset, (i - readOffset)); } i = referenceOffset; readOffset = i + 1; /* * -------------------------- * * Peform the real unescape * * -------------------------- */ if (codepoint > '\uFFFF') { writer.write(Character.toChars(codepoint)); } else { writer.write((char) codepoint); } } /* * ----------------------------------------------------------------------------------------------- * Final cleaning: writer the remaining escaped text and return. * ----------------------------------------------------------------------------------------------- */ if (max - readOffset > 0) { writer.write(text, readOffset, (max - readOffset)); } } }
[ "tanujsinghkushwah@gmail.com" ]
tanujsinghkushwah@gmail.com
a630ae4b6e49b642da151f0691e86175b7953346
4d4cc1d1ddadcf1b416a9c3d9b69046e9d4b2f20
/src/com/sys/action/school/ClassRoomAction.java
90aabb8624559fcd17ebfb7cc07fc41ec48b69ba
[]
no_license
zfaster/schoolFriend
9ba36780f708e6ed11012ef226504b37e5a0d953
cf64a7f467178cd1eddb64adcb3300fa238db931
refs/heads/master
2021-01-18T22:20:55.814645
2017-04-03T07:09:19
2017-04-03T07:09:19
87,046,727
0
0
null
null
null
null
UTF-8
Java
false
false
1,790
java
package com.sys.action.school; import com.sys.bean.school.ClassRoom; import com.sys.bean.school.Student; import com.sys.service.base.DAO; import com.sys.web.action.BaseAction; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import javax.annotation.Resource; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; @Controller @Scope("prototype") public class ClassRoomAction extends BaseAction<ClassRoom> { private String actionPath = "control/school/classRoom"; private String roomName; @Override public String execute() throws Exception { LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>(); orderBy.put("id", "desc"); StringBuffer whereSql = new StringBuffer(" 1 = 1 "); List<Object> params = new ArrayList<Object>(); if(roomName != null && !"".equals(roomName)){ whereSql.append("and o.name like ? "); params.add("%"+roomName+"%"); } pm = baseService.findScrollData( orderBy,whereSql.toString(),params.toArray()); setPageInfo(); return SUCCESS; } @Resource(name="classRoomService") public void setBaseService(DAO baseService) { this.baseService = baseService; } public String getActionPath() { return actionPath; } public void setActionPath(String actionPath) { this.actionPath = actionPath; } public String getRoomName() { return roomName; } public void setRoomName(String roomName) { try { this.roomName = new String(roomName.getBytes("iso8859-1"),"utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
[ "634075513@qq.com" ]
634075513@qq.com
385b19c182c1f25e3396e4fef38667703bbe5896
3bc62f2a6d32df436e99507fa315938bc16652b1
/web/jslint/src/main/java/com/intellij/lang/javascript/linter/jslint/JSLintConfigurable.java
65978b49ca715487ae6e221013e218a51d8c51eb
[ "Apache-2.0" ]
permissive
JetBrains/intellij-obsolete-plugins
7abf3f10603e7fe42b9982b49171de839870e535
3e388a1f9ae5195dc538df0d3008841c61f11aef
refs/heads/master
2023-09-04T05:22:46.470136
2023-06-11T16:42:37
2023-06-11T16:42:37
184,035,533
19
29
Apache-2.0
2023-07-30T14:23:05
2019-04-29T08:54:54
Java
UTF-8
Java
false
false
899
java
package com.intellij.lang.javascript.linter.jslint; import com.intellij.lang.javascript.linter.JSLinterBaseView; import com.intellij.lang.javascript.linter.JSLinterConfigurable; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; /** * @author Sergey Simonchik */ public class JSLintConfigurable extends JSLinterConfigurable<JSLintState> { public JSLintConfigurable(@NotNull Project project) { super(project, JSLintConfiguration.class, false); } @Nls @Override public String getDisplayName() { return JSLintBundle.message("settings.javascript.linters.jslint.configurable.name"); } @NotNull @Override public String getId() { return "Settings.JavaScript.Linters.JSLint"; } @NotNull @Override protected JSLinterBaseView<JSLintState> createView() { return new JSLintView(); } }
[ "sergey.simonchik@jetbrains.com" ]
sergey.simonchik@jetbrains.com
17b971de6757e425bc3a1fefc74f42a0ac4a3695
bd338733a8cb5df8cd3cba62359eb57a4cce4307
/sp04-orderservice/src/main/java/com/example/sp04/Sp04OrderserviceApplication.java
ada5c4aed97fa1d24999ae69ccc911537797c282
[]
no_license
DregonTO/DREGON
f6d3433545da8b2e8a378d6fc5d89768827d8ce6
3ddd165e4e535eaf0144a14be61016593c5b7bce
refs/heads/master
2021-07-11T04:05:09.959196
2020-07-18T04:01:49
2020-07-18T04:01:49
174,089,204
0
0
null
2020-07-18T04:13:44
2019-03-06T06:55:08
Java
UTF-8
Java
false
false
780
java
package com.example.sp04; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; //@EnableCircuitBreaker //@EnableDiscoveryClient //@SpringBootApplication @SpringCloudApplication @EnableFeignClients public class Sp04OrderserviceApplication { public static void main(String[] args) { SpringApplication.run(Sp04OrderserviceApplication.class, args); } }
[ "1793686603@qq.com" ]
1793686603@qq.com
c2118fa2cb81608bfc2a41efcce3f1d9bd07a730
578282fda3816b99896672483bdb1741bbe4944c
/pmalek_project/src/main/java/com/project/pmalek_project/repository/model/BookOrder.java
d24cc3e1124d8cd706e26f56903ab2d3a4956293
[]
no_license
Pawelkrs90/UMCS_DB_SPRING_PROJEKT1
811b3e44dbca5e8ead9dd28077aecd868a9e0a8e
99b34ffa59a8094cc7ded9896905defbe7b8a35e
refs/heads/master
2021-04-15T04:09:35.789091
2018-03-21T15:48:41
2018-03-21T15:48:41
126,164,228
0
0
null
null
null
null
UTF-8
Java
false
false
1,755
java
package com.project.pmalek_project.repository.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; //@Getter //@Setter //@NoArgsConstructor //@AllArgsConstructor @ToString public class BookOrder { private Long id; private Long bookId; private Long userId; private LocalDate bookingDate; private String type; public interface Type{ public static final String RENT = "R"; public static final String BUY = "B"; public static final String DESTROY = "D"; } public BookOrder() { } public BookOrder(Long id, Long bookId, Long userId, LocalDate bookingDate, String type) { this.id = id; this.bookId = bookId; this.userId = userId; this.bookingDate = bookingDate; this.type = type; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getBookId() { return bookId; } public void setBookId(Long bookId) { this.bookId = bookId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public LocalDate getBookingDate() { return bookingDate; } public void setBookingDate(LocalDate bookingDate) { this.bookingDate = bookingDate; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
[ "pawel.malek@comarch.com" ]
pawel.malek@comarch.com
9f2f44a5f74de27ea8cb62816c4f1adef1361f13
2b18d962352d1adf2f1ee0f1e7e02492b77f6f52
/src/main/java/com/caozhihu/tmall/service/UserService.java
26c5307ec59c10270caf748bba24c66251c39e98
[]
no_license
jmfnku/Tmall_SSM
1f7f26d79ed512e5fffd5a05a56878bb8ee96739
773fec9b1e69556252b9fe82ed4f5e38a0c3e285
refs/heads/master
2020-12-31T23:24:21.721346
2020-02-15T12:20:47
2020-02-15T12:20:47
239,074,667
0
1
null
2020-02-08T05:26:40
2020-02-08T05:26:39
null
UTF-8
Java
false
false
247
java
package com.caozhihu.tmall.service; import com.caozhihu.tmall.pojo.User; import java.util.List; public interface UserService { void add(User c); void delete(int id); void update(User u); User get(int id); List list(); }
[ "czwbig@qq.com" ]
czwbig@qq.com
c6a3fa75bb56caa215a27dcf45e2546342b11ec2
433c537366a1f52d00bfa652126e00b060ff7102
/src/java/util/Collections.java
4ed1db617ad7a6c35fa3356aa93df6fa76b51eae
[ "Apache-2.0" ]
permissive
xiaoguiguo/DDJDK
2e5046d901c612351101d892c6529fd991255dfe
6dfbda57d4df7c60a2e79eb3c58386ae0c074119
refs/heads/main
2023-08-30T03:36:44.887020
2021-11-15T07:48:13
2021-11-15T07:48:13
421,699,313
0
0
null
null
null
null
UTF-8
Java
false
false
220,162
java
/* * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Array; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import jdk.internal.access.SharedSecrets; /** * This class consists exclusively of static methods that operate on or return * collections. It contains polymorphic algorithms that operate on * collections, "wrappers", which return a new collection backed by a * specified collection, and a few other odds and ends. * * <p>The methods of this class all throw a {@code NullPointerException} * if the collections or class objects provided to them are null. * * <p>The documentation for the polymorphic algorithms contained in this class * generally includes a brief description of the <i>implementation</i>. Such * descriptions should be regarded as <i>implementation notes</i>, rather than * parts of the <i>specification</i>. Implementors should feel free to * substitute other algorithms, so long as the specification itself is adhered * to. (For example, the algorithm used by {@code sort} does not have to be * a mergesort, but it does have to be <i>stable</i>.) * * <p>The "destructive" algorithms contained in this class, that is, the * algorithms that modify the collection on which they operate, are specified * to throw {@code UnsupportedOperationException} if the collection does not * support the appropriate mutation primitive(s), such as the {@code set} * method. These algorithms may, but are not required to, throw this * exception if an invocation would have no effect on the collection. For * example, invoking the {@code sort} method on an unmodifiable list that is * already sorted may or may not throw {@code UnsupportedOperationException}. * * <p>This class is a member of the * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework"> * Java Collections Framework</a>. * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see Set * @see List * @see Map * @since 1.2 */ public class Collections { // Suppresses default constructor, ensuring non-instantiability. private Collections() { } // Algorithms /* * Tuning parameters for algorithms - Many of the List algorithms have * two implementations, one of which is appropriate for RandomAccess * lists, the other for "sequential." Often, the random access variant * yields better performance on small sequential access lists. The * tuning parameters below determine the cutoff point for what constitutes * a "small" sequential access list for each algorithm. The values below * were empirically determined to work well for LinkedList. Hopefully * they should be reasonable for other sequential access List * implementations. Those doing performance work on this code would * do well to validate the values of these parameters from time to time. * (The first word of each tuning parameter name is the algorithm to which * it applies.) */ private static final int BINARYSEARCH_THRESHOLD = 5000; private static final int REVERSE_THRESHOLD = 18; private static final int SHUFFLE_THRESHOLD = 5; private static final int FILL_THRESHOLD = 25; private static final int ROTATE_THRESHOLD = 100; private static final int COPY_THRESHOLD = 10; private static final int REPLACEALL_THRESHOLD = 11; private static final int INDEXOFSUBLIST_THRESHOLD = 35; /** * Sorts the specified list into ascending order, according to the * {@linkplain Comparable natural ordering} of its elements. * All elements in the list must implement the {@link Comparable} * interface. Furthermore, all elements in the list must be * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} * must not throw a {@code ClassCastException} for any elements * {@code e1} and {@code e2} in the list). * * <p>This sort is guaranteed to be <i>stable</i>: equal elements will * not be reordered as a result of the sort. * * <p>The specified list must be modifiable, but need not be resizable. * * @implNote * This implementation defers to the {@link List#sort(Comparator)} * method using the specified list and a {@code null} comparator. * * @param <T> the class of the objects in the list * @param list the list to be sorted. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> (for example, strings and integers). * @throws UnsupportedOperationException if the specified list's * list-iterator does not support the {@code set} operation. * @throws IllegalArgumentException (optional) if the implementation * detects that the natural ordering of the list elements is * found to violate the {@link Comparable} contract * @see List#sort(Comparator) */ @SuppressWarnings("unchecked") public static <T extends Comparable<? super T>> void sort(List<T> list) { list.sort(null); } /** * Sorts the specified list according to the order induced by the * specified comparator. All elements in the list must be <i>mutually * comparable</i> using the specified comparator (that is, * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException} * for any elements {@code e1} and {@code e2} in the list). * * <p>This sort is guaranteed to be <i>stable</i>: equal elements will * not be reordered as a result of the sort. * * <p>The specified list must be modifiable, but need not be resizable. * * @implNote * This implementation defers to the {@link List#sort(Comparator)} * method using the specified list and comparator. * * @param <T> the class of the objects in the list * @param list the list to be sorted. * @param c the comparator to determine the order of the list. A * {@code null} value indicates that the elements' <i>natural * ordering</i> should be used. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> using the specified comparator. * @throws UnsupportedOperationException if the specified list's * list-iterator does not support the {@code set} operation. * @throws IllegalArgumentException (optional) if the comparator is * found to violate the {@link Comparator} contract * @see List#sort(Comparator) */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> void sort(List<T> list, Comparator<? super T> c) { list.sort(c); } /** * Searches the specified list for the specified object using the binary * search algorithm. The list must be sorted into ascending order * according to the {@linkplain Comparable natural ordering} of its * elements (as by the {@link #sort(List)} method) prior to making this * call. If it is not sorted, the results are undefined. If the list * contains multiple elements equal to the specified object, there is no * guarantee which one will be found. * * <p>This method runs in log(n) time for a "random access" list (which * provides near-constant-time positional access). If the specified list * does not implement the {@link RandomAccess} interface and is large, * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. * * @param <T> the class of the objects in the list * @param list the list to be searched. * @param key the key to be searched for. * @return the index of the search key, if it is contained in the list; * otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the list: the index of the first * element greater than the key, or {@code list.size()} if all * elements in the list are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> (for example, strings and * integers), or the search key is not mutually comparable * with the elements of the list. */ public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) { if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) return Collections.indexedBinarySearch(list, key); else return Collections.iteratorBinarySearch(list, key); } private static <T> int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) { int low = 0; int high = list.size()-1; while (low <= high) { int mid = (low + high) >>> 1; Comparable<? super T> midVal = list.get(mid); int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } private static <T> int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key) { int low = 0; int high = list.size()-1; ListIterator<? extends Comparable<? super T>> i = list.listIterator(); while (low <= high) { int mid = (low + high) >>> 1; Comparable<? super T> midVal = get(i, mid); int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } /** * Gets the ith element from the given list by repositioning the specified * list listIterator. */ private static <T> T get(ListIterator<? extends T> i, int index) { T obj = null; int pos = i.nextIndex(); if (pos <= index) { do { obj = i.next(); } while (pos++ < index); } else { do { obj = i.previous(); } while (--pos > index); } return obj; } /** * Searches the specified list for the specified object using the binary * search algorithm. The list must be sorted into ascending order * according to the specified comparator (as by the * {@link #sort(List, Comparator) sort(List, Comparator)} * method), prior to making this call. If it is * not sorted, the results are undefined. If the list contains multiple * elements equal to the specified object, there is no guarantee which one * will be found. * * <p>This method runs in log(n) time for a "random access" list (which * provides near-constant-time positional access). If the specified list * does not implement the {@link RandomAccess} interface and is large, * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. * * @param <T> the class of the objects in the list * @param list the list to be searched. * @param key the key to be searched for. * @param c the comparator by which the list is ordered. * A {@code null} value indicates that the elements' * {@linkplain Comparable natural ordering} should be used. * @return the index of the search key, if it is contained in the list; * otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the list: the index of the first * element greater than the key, or {@code list.size()} if all * elements in the list are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> using the specified comparator, * or the search key is not mutually comparable with the * elements of the list using this comparator. */ @SuppressWarnings("unchecked") public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) { if (c==null) return binarySearch((List<? extends Comparable<? super T>>) list, key); if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) return Collections.indexedBinarySearch(list, key, c); else return Collections.iteratorBinarySearch(list, key, c); } private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) { int low = 0; int high = l.size()-1; while (low <= high) { int mid = (low + high) >>> 1; T midVal = l.get(mid); int cmp = c.compare(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) { int low = 0; int high = l.size()-1; ListIterator<? extends T> i = l.listIterator(); while (low <= high) { int mid = (low + high) >>> 1; T midVal = get(i, mid); int cmp = c.compare(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } /** * Reverses the order of the elements in the specified list.<p> * * This method runs in linear time. * * @param list the list whose elements are to be reversed. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the {@code set} operation. */ @SuppressWarnings({"rawtypes", "unchecked"}) public static void reverse(List<?> list) { int size = list.size(); if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) { for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--) swap(list, i, j); } else { // instead of using a raw type here, it's possible to capture // the wildcard but it will require a call to a supplementary // private method ListIterator fwd = list.listIterator(); ListIterator rev = list.listIterator(size); for (int i=0, mid=list.size()>>1; i<mid; i++) { Object tmp = fwd.next(); fwd.set(rev.previous()); rev.set(tmp); } } } /** * Randomly permutes the specified list using a default source of * randomness. All permutations occur with approximately equal * likelihood. * * <p>The hedge "approximately" is used in the foregoing description because * default source of randomness is only approximately an unbiased source * of independently chosen bits. If it were a perfect source of randomly * chosen bits, then the algorithm would choose permutations with perfect * uniformity. * * <p>This implementation traverses the list backwards, from the last * element up to the second, repeatedly swapping a randomly selected element * into the "current position". Elements are randomly selected from the * portion of the list that runs from the first element to the current * position, inclusive. * * <p>This method runs in linear time. If the specified list does not * implement the {@link RandomAccess} interface and is large, this * implementation dumps the specified list into an array before shuffling * it, and dumps the shuffled array back into the list. This avoids the * quadratic behavior that would result from shuffling a "sequential * access" list in place. * * @param list the list to be shuffled. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the {@code set} operation. */ public static void shuffle(List<?> list) { Random rnd = r; if (rnd == null) r = rnd = new Random(); // harmless race. shuffle(list, rnd); } private static Random r; /** * Randomly permute the specified list using the specified source of * randomness. All permutations occur with equal likelihood * assuming that the source of randomness is fair.<p> * * This implementation traverses the list backwards, from the last element * up to the second, repeatedly swapping a randomly selected element into * the "current position". Elements are randomly selected from the * portion of the list that runs from the first element to the current * position, inclusive.<p> * * This method runs in linear time. If the specified list does not * implement the {@link RandomAccess} interface and is large, this * implementation dumps the specified list into an array before shuffling * it, and dumps the shuffled array back into the list. This avoids the * quadratic behavior that would result from shuffling a "sequential * access" list in place. * * @param list the list to be shuffled. * @param rnd the source of randomness to use to shuffle the list. * @throws UnsupportedOperationException if the specified list or its * list-iterator does not support the {@code set} operation. */ @SuppressWarnings({"rawtypes", "unchecked"}) public static void shuffle(List<?> list, Random rnd) { int size = list.size(); if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { for (int i=size; i>1; i--) swap(list, i-1, rnd.nextInt(i)); } else { Object[] arr = list.toArray(); // Shuffle array for (int i=size; i>1; i--) swap(arr, i-1, rnd.nextInt(i)); // Dump array back into list // instead of using a raw type here, it's possible to capture // the wildcard but it will require a call to a supplementary // private method ListIterator it = list.listIterator(); for (Object e : arr) { it.next(); it.set(e); } } } /** * Swaps the elements at the specified positions in the specified list. * (If the specified positions are equal, invoking this method leaves * the list unchanged.) * * @param list The list in which to swap elements. * @param i the index of one element to be swapped. * @param j the index of the other element to be swapped. * @throws IndexOutOfBoundsException if either {@code i} or {@code j} * is out of range (i &lt; 0 || i &gt;= list.size() * || j &lt; 0 || j &gt;= list.size()). * @since 1.4 */ @SuppressWarnings({"rawtypes", "unchecked"}) public static void swap(List<?> list, int i, int j) { // instead of using a raw type here, it's possible to capture // the wildcard but it will require a call to a supplementary // private method final List l = list; l.set(i, l.set(j, l.get(i))); } /** * Swaps the two specified elements in the specified array. */ private static void swap(Object[] arr, int i, int j) { Object tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } /** * Replaces all of the elements of the specified list with the specified * element. <p> * * This method runs in linear time. * * @param <T> the class of the objects in the list * @param list the list to be filled with the specified element. * @param obj The element with which to fill the specified list. * @throws UnsupportedOperationException if the specified list or its * list-iterator does not support the {@code set} operation. */ public static <T> void fill(List<? super T> list, T obj) { int size = list.size(); if (size < FILL_THRESHOLD || list instanceof RandomAccess) { for (int i=0; i<size; i++) list.set(i, obj); } else { ListIterator<? super T> itr = list.listIterator(); for (int i=0; i<size; i++) { itr.next(); itr.set(obj); } } } /** * Copies all of the elements from one list into another. After the * operation, the index of each copied element in the destination list * will be identical to its index in the source list. The destination * list's size must be greater than or equal to the source list's size. * If it is greater, the remaining elements in the destination list are * unaffected. <p> * * This method runs in linear time. * * @param <T> the class of the objects in the lists * @param dest The destination list. * @param src The source list. * @throws IndexOutOfBoundsException if the destination list is too small * to contain the entire source List. * @throws UnsupportedOperationException if the destination list's * list-iterator does not support the {@code set} operation. */ public static <T> void copy(List<? super T> dest, List<? extends T> src) { int srcSize = src.size(); if (srcSize > dest.size()) throw new IndexOutOfBoundsException("Source does not fit in dest"); if (srcSize < COPY_THRESHOLD || (src instanceof RandomAccess && dest instanceof RandomAccess)) { for (int i=0; i<srcSize; i++) dest.set(i, src.get(i)); } else { ListIterator<? super T> di=dest.listIterator(); ListIterator<? extends T> si=src.listIterator(); for (int i=0; i<srcSize; i++) { di.next(); di.set(si.next()); } } } /** * Returns the minimum element of the given collection, according to the * <i>natural ordering</i> of its elements. All elements in the * collection must implement the {@code Comparable} interface. * Furthermore, all elements in the collection must be <i>mutually * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and * {@code e2} in the collection).<p> * * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * * @param <T> the class of the objects in the collection * @param coll the collection whose minimum element is to be determined. * @return the minimum element of the given collection, according * to the <i>natural ordering</i> of its elements. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> (for example, strings and * integers). * @throws NoSuchElementException if the collection is empty. * @see Comparable */ public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) < 0) candidate = next; } return candidate; } /** * Returns the minimum element of the given collection, according to the * order induced by the specified comparator. All elements in the * collection must be <i>mutually comparable</i> by the specified * comparator (that is, {@code comp.compare(e1, e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and * {@code e2} in the collection).<p> * * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * * @param <T> the class of the objects in the collection * @param coll the collection whose minimum element is to be determined. * @param comp the comparator with which to determine the minimum element. * A {@code null} value indicates that the elements' <i>natural * ordering</i> should be used. * @return the minimum element of the given collection, according * to the specified comparator. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> using the specified comparator. * @throws NoSuchElementException if the collection is empty. * @see Comparable */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)min((Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) < 0) candidate = next; } return candidate; } /** * Returns the maximum element of the given collection, according to the * <i>natural ordering</i> of its elements. All elements in the * collection must implement the {@code Comparable} interface. * Furthermore, all elements in the collection must be <i>mutually * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and * {@code e2} in the collection).<p> * * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * * @param <T> the class of the objects in the collection * @param coll the collection whose maximum element is to be determined. * @return the maximum element of the given collection, according * to the <i>natural ordering</i> of its elements. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> (for example, strings and * integers). * @throws NoSuchElementException if the collection is empty. * @see Comparable */ public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) > 0) candidate = next; } return candidate; } /** * Returns the maximum element of the given collection, according to the * order induced by the specified comparator. All elements in the * collection must be <i>mutually comparable</i> by the specified * comparator (that is, {@code comp.compare(e1, e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and * {@code e2} in the collection).<p> * * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * * @param <T> the class of the objects in the collection * @param coll the collection whose maximum element is to be determined. * @param comp the comparator with which to determine the maximum element. * A {@code null} value indicates that the elements' <i>natural * ordering</i> should be used. * @return the maximum element of the given collection, according * to the specified comparator. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> using the specified comparator. * @throws NoSuchElementException if the collection is empty. * @see Comparable */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)max((Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) > 0) candidate = next; } return candidate; } /** * Rotates the elements in the specified list by the specified distance. * After calling this method, the element at index {@code i} will be * the element previously at index {@code (i - distance)} mod * {@code list.size()}, for all values of {@code i} between {@code 0} * and {@code list.size()-1}, inclusive. (This method has no effect on * the size of the list.) * * <p>For example, suppose {@code list} comprises{@code [t, a, n, k, s]}. * After invoking {@code Collections.rotate(list, 1)} (or * {@code Collections.rotate(list, -4)}), {@code list} will comprise * {@code [s, t, a, n, k]}. * * <p>Note that this method can usefully be applied to sublists to * move one or more elements within a list while preserving the * order of the remaining elements. For example, the following idiom * moves the element at index {@code j} forward to position * {@code k} (which must be greater than or equal to {@code j}): * <pre> * Collections.rotate(list.subList(j, k+1), -1); * </pre> * To make this concrete, suppose {@code list} comprises * {@code [a, b, c, d, e]}. To move the element at index {@code 1} * ({@code b}) forward two positions, perform the following invocation: * <pre> * Collections.rotate(l.subList(1, 4), -1); * </pre> * The resulting list is {@code [a, c, d, b, e]}. * * <p>To move more than one element forward, increase the absolute value * of the rotation distance. To move elements backward, use a positive * shift distance. * * <p>If the specified list is small or implements the {@link * RandomAccess} interface, this implementation exchanges the first * element into the location it should go, and then repeatedly exchanges * the displaced element into the location it should go until a displaced * element is swapped into the first element. If necessary, the process * is repeated on the second and successive elements, until the rotation * is complete. If the specified list is large and doesn't implement the * {@code RandomAccess} interface, this implementation breaks the * list into two sublist views around index {@code -distance mod size}. * Then the {@link #reverse(List)} method is invoked on each sublist view, * and finally it is invoked on the entire list. For a more complete * description of both algorithms, see Section 2.3 of Jon Bentley's * <i>Programming Pearls</i> (Addison-Wesley, 1986). * * @param list the list to be rotated. * @param distance the distance to rotate the list. There are no * constraints on this value; it may be zero, negative, or * greater than {@code list.size()}. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the {@code set} operation. * @since 1.4 */ public static void rotate(List<?> list, int distance) { if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD) rotate1(list, distance); else rotate2(list, distance); } private static <T> void rotate1(List<T> list, int distance) { int size = list.size(); if (size == 0) return; distance = distance % size; if (distance < 0) distance += size; if (distance == 0) return; for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) { T displaced = list.get(cycleStart); int i = cycleStart; do { i += distance; if (i >= size) i -= size; displaced = list.set(i, displaced); nMoved ++; } while (i != cycleStart); } } private static void rotate2(List<?> list, int distance) { int size = list.size(); if (size == 0) return; int mid = -distance % size; if (mid < 0) mid += size; if (mid == 0) return; reverse(list.subList(0, mid)); reverse(list.subList(mid, size)); reverse(list); } /** * Replaces all occurrences of one specified value in a list with another. * More formally, replaces with {@code newVal} each element {@code e} * in {@code list} such that * {@code (oldVal==null ? e==null : oldVal.equals(e))}. * (This method has no effect on the size of the list.) * * @param <T> the class of the objects in the list * @param list the list in which replacement is to occur. * @param oldVal the old value to be replaced. * @param newVal the new value with which {@code oldVal} is to be * replaced. * @return {@code true} if {@code list} contained one or more elements * {@code e} such that * {@code (oldVal==null ? e==null : oldVal.equals(e))}. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the {@code set} operation. * @since 1.4 */ public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) { boolean result = false; int size = list.size(); if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) { if (oldVal==null) { for (int i=0; i<size; i++) { if (list.get(i)==null) { list.set(i, newVal); result = true; } } } else { for (int i=0; i<size; i++) { if (oldVal.equals(list.get(i))) { list.set(i, newVal); result = true; } } } } else { ListIterator<T> itr=list.listIterator(); if (oldVal==null) { for (int i=0; i<size; i++) { if (itr.next()==null) { itr.set(newVal); result = true; } } } else { for (int i=0; i<size; i++) { if (oldVal.equals(itr.next())) { itr.set(newVal); result = true; } } } } return result; } /** * Returns the starting position of the first occurrence of the specified * target list within the specified source list, or -1 if there is no * such occurrence. More formally, returns the lowest index {@code i} * such that {@code source.subList(i, i+target.size()).equals(target)}, * or -1 if there is no such index. (Returns -1 if * {@code target.size() > source.size()}) * * <p>This implementation uses the "brute force" technique of scanning * over the source list, looking for a match with the target at each * location in turn. * * @param source the list in which to search for the first occurrence * of {@code target}. * @param target the list to search for as a subList of {@code source}. * @return the starting position of the first occurrence of the specified * target list within the specified source list, or -1 if there * is no such occurrence. * @since 1.4 */ public static int indexOfSubList(List<?> source, List<?> target) { int sourceSize = source.size(); int targetSize = target.size(); int maxCandidate = sourceSize - targetSize; if (sourceSize < INDEXOFSUBLIST_THRESHOLD || (source instanceof RandomAccess&&target instanceof RandomAccess)) { nextCand: for (int candidate = 0; candidate <= maxCandidate; candidate++) { for (int i=0, j=candidate; i<targetSize; i++, j++) if (!eq(target.get(i), source.get(j))) continue nextCand; // Element mismatch, try next cand return candidate; // All elements of candidate matched target } } else { // Iterator version of above algorithm ListIterator<?> si = source.listIterator(); nextCand: for (int candidate = 0; candidate <= maxCandidate; candidate++) { ListIterator<?> ti = target.listIterator(); for (int i=0; i<targetSize; i++) { if (!eq(ti.next(), si.next())) { // Back up source iterator to next candidate for (int j=0; j<i; j++) si.previous(); continue nextCand; } } return candidate; } } return -1; // No candidate matched the target } /** * Returns the starting position of the last occurrence of the specified * target list within the specified source list, or -1 if there is no such * occurrence. More formally, returns the highest index {@code i} * such that {@code source.subList(i, i+target.size()).equals(target)}, * or -1 if there is no such index. (Returns -1 if * {@code target.size() > source.size()}) * * <p>This implementation uses the "brute force" technique of iterating * over the source list, looking for a match with the target at each * location in turn. * * @param source the list in which to search for the last occurrence * of {@code target}. * @param target the list to search for as a subList of {@code source}. * @return the starting position of the last occurrence of the specified * target list within the specified source list, or -1 if there * is no such occurrence. * @since 1.4 */ public static int lastIndexOfSubList(List<?> source, List<?> target) { int sourceSize = source.size(); int targetSize = target.size(); int maxCandidate = sourceSize - targetSize; if (sourceSize < INDEXOFSUBLIST_THRESHOLD || source instanceof RandomAccess) { // Index access version nextCand: for (int candidate = maxCandidate; candidate >= 0; candidate--) { for (int i=0, j=candidate; i<targetSize; i++, j++) if (!eq(target.get(i), source.get(j))) continue nextCand; // Element mismatch, try next cand return candidate; // All elements of candidate matched target } } else { // Iterator version of above algorithm if (maxCandidate < 0) return -1; ListIterator<?> si = source.listIterator(maxCandidate); nextCand: for (int candidate = maxCandidate; candidate >= 0; candidate--) { ListIterator<?> ti = target.listIterator(); for (int i=0; i<targetSize; i++) { if (!eq(ti.next(), si.next())) { if (candidate != 0) { // Back up source iterator to next candidate for (int j=0; j<=i+1; j++) si.previous(); } continue nextCand; } } return candidate; } } return -1; // No candidate matched the target } // Unmodifiable Wrappers /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified collection. Query operations on the returned collection "read through" * to the specified collection, and attempts to modify the returned * collection, whether direct or via its iterator, result in an * {@code UnsupportedOperationException}.<p> * * The returned collection does <i>not</i> pass the hashCode and equals * operations through to the backing collection, but relies on * {@code Object}'s {@code equals} and {@code hashCode} methods. This * is necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list.<p> * * The returned collection will be serializable if the specified collection * is serializable. * * @param <T> the class of the objects in the collection * @param c the collection for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified collection. */ public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) { return new UnmodifiableCollection<>(c); } /** * @serial include */ static class UnmodifiableCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 1820017752578914078L; final Collection<? extends E> c; UnmodifiableCollection(Collection<? extends E> c) { if (c==null) throw new NullPointerException(); this.c = c; } public int size() {return c.size();} public boolean isEmpty() {return c.isEmpty();} public boolean contains(Object o) {return c.contains(o);} public Object[] toArray() {return c.toArray();} public <T> T[] toArray(T[] a) {return c.toArray(a);} public <T> T[] toArray(IntFunction<T[]> f) {return c.toArray(f);} public String toString() {return c.toString();} public Iterator<E> iterator() { return new Iterator<E>() { private final Iterator<? extends E> i = c.iterator(); public boolean hasNext() {return i.hasNext();} public E next() {return i.next();} public void remove() { throw new UnsupportedOperationException(); } @Override public void forEachRemaining(Consumer<? super E> action) { // Use backing collection version i.forEachRemaining(action); } }; } public boolean add(E e) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean containsAll(Collection<?> coll) { return c.containsAll(coll); } public boolean addAll(Collection<? extends E> coll) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection<?> coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection<?> coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) { c.forEach(action); } @Override public boolean removeIf(Predicate<? super E> filter) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @Override public Spliterator<E> spliterator() { return (Spliterator<E>)c.spliterator(); } @SuppressWarnings("unchecked") @Override public Stream<E> stream() { return (Stream<E>)c.stream(); } @SuppressWarnings("unchecked") @Override public Stream<E> parallelStream() { return (Stream<E>)c.parallelStream(); } } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified set. Query operations on the returned set "read through" to the specified * set, and attempts to modify the returned set, whether direct or via its * iterator, result in an {@code UnsupportedOperationException}.<p> * * The returned set will be serializable if the specified set * is serializable. * * @param <T> the class of the objects in the set * @param s the set for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified set. */ public static <T> Set<T> unmodifiableSet(Set<? extends T> s) { return new UnmodifiableSet<>(s); } /** * @serial include */ static class UnmodifiableSet<E> extends UnmodifiableCollection<E> implements Set<E>, Serializable { private static final long serialVersionUID = -9215047833775013803L; UnmodifiableSet(Set<? extends E> s) {super(s);} public boolean equals(Object o) {return o == this || c.equals(o);} public int hashCode() {return c.hashCode();} } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified sorted set. Query operations on the returned sorted set "read * through" to the specified sorted set. Attempts to modify the returned * sorted set, whether direct, via its iterator, or via its * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in * an {@code UnsupportedOperationException}.<p> * * The returned sorted set will be serializable if the specified sorted set * is serializable. * * @param <T> the class of the objects in the set * @param s the sorted set for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified sorted set. */ public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) { return new UnmodifiableSortedSet<>(s); } /** * @serial include */ static class UnmodifiableSortedSet<E> extends UnmodifiableSet<E> implements SortedSet<E>, Serializable { private static final long serialVersionUID = -4929149591599911165L; private final SortedSet<E> ss; UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;} public Comparator<? super E> comparator() {return ss.comparator();} public SortedSet<E> subSet(E fromElement, E toElement) { return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement)); } public SortedSet<E> headSet(E toElement) { return new UnmodifiableSortedSet<>(ss.headSet(toElement)); } public SortedSet<E> tailSet(E fromElement) { return new UnmodifiableSortedSet<>(ss.tailSet(fromElement)); } public E first() {return ss.first();} public E last() {return ss.last();} } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified navigable set. Query operations on the returned navigable set "read * through" to the specified navigable set. Attempts to modify the returned * navigable set, whether direct, via its iterator, or via its * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in * an {@code UnsupportedOperationException}.<p> * * The returned navigable set will be serializable if the specified * navigable set is serializable. * * @param <T> the class of the objects in the set * @param s the navigable set for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified navigable set * @since 1.8 */ public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) { return new UnmodifiableNavigableSet<>(s); } /** * Wraps a navigable set and disables all of the mutative operations. * * @param <E> type of elements * @serial include */ static class UnmodifiableNavigableSet<E> extends UnmodifiableSortedSet<E> implements NavigableSet<E>, Serializable { private static final long serialVersionUID = -6027448201786391929L; /** * A singleton empty unmodifiable navigable set used for * {@link #emptyNavigableSet()}. * * @param <E> type of elements, if there were any, and bounds */ private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E> implements Serializable { private static final long serialVersionUID = -6291252904449939134L; public EmptyNavigableSet() { super(new TreeSet<>()); } private Object readResolve() { return EMPTY_NAVIGABLE_SET; } } @SuppressWarnings("rawtypes") private static final NavigableSet<?> EMPTY_NAVIGABLE_SET = new EmptyNavigableSet<>(); /** * The instance we are protecting. */ private final NavigableSet<E> ns; UnmodifiableNavigableSet(NavigableSet<E> s) {super(s); ns = s;} public E lower(E e) { return ns.lower(e); } public E floor(E e) { return ns.floor(e); } public E ceiling(E e) { return ns.ceiling(e); } public E higher(E e) { return ns.higher(e); } public E pollFirst() { throw new UnsupportedOperationException(); } public E pollLast() { throw new UnsupportedOperationException(); } public NavigableSet<E> descendingSet() { return new UnmodifiableNavigableSet<>(ns.descendingSet()); } public Iterator<E> descendingIterator() { return descendingSet().iterator(); } public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new UnmodifiableNavigableSet<>( ns.subSet(fromElement, fromInclusive, toElement, toInclusive)); } public NavigableSet<E> headSet(E toElement, boolean inclusive) { return new UnmodifiableNavigableSet<>( ns.headSet(toElement, inclusive)); } public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new UnmodifiableNavigableSet<>( ns.tailSet(fromElement, inclusive)); } } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified list. Query operations on the returned list "read through" to the * specified list, and attempts to modify the returned list, whether * direct or via its iterator, result in an * {@code UnsupportedOperationException}.<p> * * The returned list will be serializable if the specified list * is serializable. Similarly, the returned list will implement * {@link RandomAccess} if the specified list does. * * @param <T> the class of the objects in the list * @param list the list for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified list. */ public static <T> List<T> unmodifiableList(List<? extends T> list) { return (list instanceof RandomAccess ? new UnmodifiableRandomAccessList<>(list) : new UnmodifiableList<>(list)); } /** * @serial include */ static class UnmodifiableList<E> extends UnmodifiableCollection<E> implements List<E> { private static final long serialVersionUID = -283967356065247728L; final List<? extends E> list; UnmodifiableList(List<? extends E> list) { super(list); this.list = list; } public boolean equals(Object o) {return o == this || list.equals(o);} public int hashCode() {return list.hashCode();} public E get(int index) {return list.get(index);} public E set(int index, E element) { throw new UnsupportedOperationException(); } public void add(int index, E element) { throw new UnsupportedOperationException(); } public E remove(int index) { throw new UnsupportedOperationException(); } public int indexOf(Object o) {return list.indexOf(o);} public int lastIndexOf(Object o) {return list.lastIndexOf(o);} public boolean addAll(int index, Collection<? extends E> c) { throw new UnsupportedOperationException(); } @Override public void replaceAll(UnaryOperator<E> operator) { throw new UnsupportedOperationException(); } @Override public void sort(Comparator<? super E> c) { throw new UnsupportedOperationException(); } public ListIterator<E> listIterator() {return listIterator(0);} public ListIterator<E> listIterator(final int index) { return new ListIterator<E>() { private final ListIterator<? extends E> i = list.listIterator(index); public boolean hasNext() {return i.hasNext();} public E next() {return i.next();} public boolean hasPrevious() {return i.hasPrevious();} public E previous() {return i.previous();} public int nextIndex() {return i.nextIndex();} public int previousIndex() {return i.previousIndex();} public void remove() { throw new UnsupportedOperationException(); } public void set(E e) { throw new UnsupportedOperationException(); } public void add(E e) { throw new UnsupportedOperationException(); } @Override public void forEachRemaining(Consumer<? super E> action) { i.forEachRemaining(action); } }; } public List<E> subList(int fromIndex, int toIndex) { return new UnmodifiableList<>(list.subList(fromIndex, toIndex)); } /** * UnmodifiableRandomAccessList instances are serialized as * UnmodifiableList instances to allow them to be deserialized * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList). * This method inverts the transformation. As a beneficial * side-effect, it also grafts the RandomAccess marker onto * UnmodifiableList instances that were serialized in pre-1.4 JREs. * * Note: Unfortunately, UnmodifiableRandomAccessList instances * serialized in 1.4.1 and deserialized in 1.4 will become * UnmodifiableList instances, as this method was missing in 1.4. */ private Object readResolve() { return (list instanceof RandomAccess ? new UnmodifiableRandomAccessList<>(list) : this); } } /** * @serial include */ static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E> implements RandomAccess { UnmodifiableRandomAccessList(List<? extends E> list) { super(list); } public List<E> subList(int fromIndex, int toIndex) { return new UnmodifiableRandomAccessList<>( list.subList(fromIndex, toIndex)); } private static final long serialVersionUID = -2542308836966382001L; /** * Allows instances to be deserialized in pre-1.4 JREs (which do * not have UnmodifiableRandomAccessList). UnmodifiableList has * a readResolve method that inverts this transformation upon * deserialization. */ private Object writeReplace() { return new UnmodifiableList<>(list); } } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified map. Query operations on the returned map "read through" * to the specified map, and attempts to modify the returned * map, whether direct or via its collection views, result in an * {@code UnsupportedOperationException}.<p> * * The returned map will be serializable if the specified map * is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the map for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified map. */ public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) { return new UnmodifiableMap<>(m); } /** * @serial include */ private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable { private static final long serialVersionUID = -1034234728574286014L; private final Map<? extends K, ? extends V> m; UnmodifiableMap(Map<? extends K, ? extends V> m) { if (m==null) throw new NullPointerException(); this.m = m; } public int size() {return m.size();} public boolean isEmpty() {return m.isEmpty();} public boolean containsKey(Object key) {return m.containsKey(key);} public boolean containsValue(Object val) {return m.containsValue(val);} public V get(Object key) {return m.get(key);} public V put(K key, V value) { throw new UnsupportedOperationException(); } public V remove(Object key) { throw new UnsupportedOperationException(); } public void putAll(Map<? extends K, ? extends V> m) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } private transient Set<K> keySet; private transient Set<Entry<K,V>> entrySet; private transient Collection<V> values; public Set<K> keySet() { if (keySet==null) keySet = unmodifiableSet(m.keySet()); return keySet; } public Set<Entry<K,V>> entrySet() { if (entrySet==null) entrySet = new UnmodifiableEntrySet<>(m.entrySet()); return entrySet; } public Collection<V> values() { if (values==null) values = unmodifiableCollection(m.values()); return values; } public boolean equals(Object o) {return o == this || m.equals(o);} public int hashCode() {return m.hashCode();} public String toString() {return m.toString();} // Override default methods in Map @Override @SuppressWarnings("unchecked") public V getOrDefault(Object k, V defaultValue) { // Safe cast as we don't change the value return ((Map<K, V>)m).getOrDefault(k, defaultValue); } @Override public void forEach(BiConsumer<? super K, ? super V> action) { m.forEach(action); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { throw new UnsupportedOperationException(); } @Override public V putIfAbsent(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException(); } @Override public V replace(K key, V value) { throw new UnsupportedOperationException(); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException(); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } /** * We need this class in addition to UnmodifiableSet as * Map.Entries themselves permit modification of the backing Map * via their setValue operation. This class is subtle: there are * many possible attacks that must be thwarted. * * @serial include */ static class UnmodifiableEntrySet<K,V> extends UnmodifiableSet<Entry<K,V>> { private static final long serialVersionUID = 7854390611657943733L; @SuppressWarnings({"unchecked", "rawtypes"}) UnmodifiableEntrySet(Set<? extends Entry<? extends K, ? extends V>> s) { // Need to cast to raw in order to work around a limitation in the type system super((Set)s); } static <K, V> Consumer<Entry<? extends K, ? extends V>> entryConsumer( Consumer<? super Entry<K, V>> action) { return e -> action.accept(new UnmodifiableEntry<>(e)); } public void forEach(Consumer<? super Entry<K, V>> action) { Objects.requireNonNull(action); c.forEach(entryConsumer(action)); } static final class UnmodifiableEntrySetSpliterator<K, V> implements Spliterator<Entry<K,V>> { final Spliterator<Entry<K, V>> s; UnmodifiableEntrySetSpliterator(Spliterator<Entry<K, V>> s) { this.s = s; } @Override public boolean tryAdvance(Consumer<? super Entry<K, V>> action) { Objects.requireNonNull(action); return s.tryAdvance(entryConsumer(action)); } @Override public void forEachRemaining(Consumer<? super Entry<K, V>> action) { Objects.requireNonNull(action); s.forEachRemaining(entryConsumer(action)); } @Override public Spliterator<Entry<K, V>> trySplit() { Spliterator<Entry<K, V>> split = s.trySplit(); return split == null ? null : new UnmodifiableEntrySetSpliterator<>(split); } @Override public long estimateSize() { return s.estimateSize(); } @Override public long getExactSizeIfKnown() { return s.getExactSizeIfKnown(); } @Override public int characteristics() { return s.characteristics(); } @Override public boolean hasCharacteristics(int characteristics) { return s.hasCharacteristics(characteristics); } @Override public Comparator<? super Entry<K, V>> getComparator() { return s.getComparator(); } } @SuppressWarnings("unchecked") public Spliterator<Entry<K,V>> spliterator() { return new UnmodifiableEntrySetSpliterator<>( (Spliterator<Entry<K, V>>) c.spliterator()); } @Override public Stream<Entry<K,V>> stream() { return StreamSupport.stream(spliterator(), false); } @Override public Stream<Entry<K,V>> parallelStream() { return StreamSupport.stream(spliterator(), true); } public Iterator<Entry<K,V>> iterator() { return new Iterator<Entry<K,V>>() { private final Iterator<? extends Entry<? extends K, ? extends V>> i = c.iterator(); public boolean hasNext() { return i.hasNext(); } public Entry<K,V> next() { return new UnmodifiableEntry<>(i.next()); } public void remove() { throw new UnsupportedOperationException(); } public void forEachRemaining(Consumer<? super Entry<K, V>> action) { i.forEachRemaining(entryConsumer(action)); } }; } @SuppressWarnings("unchecked") public Object[] toArray() { Object[] a = c.toArray(); for (int i=0; i<a.length; i++) a[i] = new UnmodifiableEntry<>((Entry<? extends K, ? extends V>)a[i]); return a; } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { // We don't pass a to c.toArray, to avoid window of // vulnerability wherein an unscrupulous multithreaded client // could get his hands on raw (unwrapped) Entries from c. Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0)); for (int i=0; i<arr.length; i++) arr[i] = new UnmodifiableEntry<>((Entry<? extends K, ? extends V>)arr[i]); if (arr.length > a.length) return (T[])arr; System.arraycopy(arr, 0, a, 0, arr.length); if (a.length > arr.length) a[arr.length] = null; return a; } /** * This method is overridden to protect the backing set against * an object with a nefarious equals function that senses * that the equality-candidate is Map.Entry and calls its * setValue method. */ public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; return c.contains( new UnmodifiableEntry<>((Entry<?,?>) o)); } /** * The next two methods are overridden to protect against * an unscrupulous List whose contains(Object o) method senses * when o is a Map.Entry, and calls o.setValue. */ public boolean containsAll(Collection<?> coll) { for (Object e : coll) { if (!contains(e)) // Invokes safe contains() above return false; } return true; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Set<?> s = (Set<?>) o; if (s.size() != c.size()) return false; return containsAll(s); // Invokes safe containsAll() above } /** * This "wrapper class" serves two purposes: it prevents * the client from modifying the backing Map, by short-circuiting * the setValue method, and it protects the backing Map against * an ill-behaved Map.Entry that attempts to modify another * Map Entry when asked to perform an equality check. */ private static class UnmodifiableEntry<K,V> implements Entry<K,V> { private Entry<? extends K, ? extends V> e; UnmodifiableEntry(Entry<? extends K, ? extends V> e) {this.e = Objects.requireNonNull(e);} public K getKey() {return e.getKey();} public V getValue() {return e.getValue();} public V setValue(V value) { throw new UnsupportedOperationException(); } public int hashCode() {return e.hashCode();} public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Map.Entry)) return false; Entry<?,?> t = (Entry<?,?>)o; return eq(e.getKey(), t.getKey()) && eq(e.getValue(), t.getValue()); } public String toString() {return e.toString();} } } } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified sorted map. Query operations on the returned sorted map "read through" * to the specified sorted map. Attempts to modify the returned * sorted map, whether direct, via its collection views, or via its * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in * an {@code UnsupportedOperationException}.<p> * * The returned sorted map will be serializable if the specified sorted map * is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the sorted map for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified sorted map. */ public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) { return new UnmodifiableSortedMap<>(m); } /** * @serial include */ static class UnmodifiableSortedMap<K,V> extends UnmodifiableMap<K,V> implements SortedMap<K,V>, Serializable { private static final long serialVersionUID = -8806743815996713206L; private final SortedMap<K, ? extends V> sm; UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m; } public Comparator<? super K> comparator() { return sm.comparator(); } public SortedMap<K,V> subMap(K fromKey, K toKey) { return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); } public SortedMap<K,V> headMap(K toKey) { return new UnmodifiableSortedMap<>(sm.headMap(toKey)); } public SortedMap<K,V> tailMap(K fromKey) { return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); } public K firstKey() { return sm.firstKey(); } public K lastKey() { return sm.lastKey(); } } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified navigable map. Query operations on the returned navigable map "read * through" to the specified navigable map. Attempts to modify the returned * navigable map, whether direct, via its collection views, or via its * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in * an {@code UnsupportedOperationException}.<p> * * The returned navigable map will be serializable if the specified * navigable map is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the navigable map for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified navigable map * @since 1.8 */ public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) { return new UnmodifiableNavigableMap<>(m); } /** * @serial include */ static class UnmodifiableNavigableMap<K,V> extends UnmodifiableSortedMap<K,V> implements NavigableMap<K,V>, Serializable { private static final long serialVersionUID = -4858195264774772197L; /** * A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve * to preserve singleton property. * * @param <K> type of keys, if there were any, and of bounds * @param <V> type of values, if there were any */ private static class EmptyNavigableMap<K,V> extends UnmodifiableNavigableMap<K,V> implements Serializable { private static final long serialVersionUID = -2239321462712562324L; EmptyNavigableMap() { super(new TreeMap<>()); } @Override public NavigableSet<K> navigableKeySet() { return emptyNavigableSet(); } private Object readResolve() { return EMPTY_NAVIGABLE_MAP; } } /** * Singleton for {@link emptyNavigableMap()} which is also immutable. */ private static final EmptyNavigableMap<?,?> EMPTY_NAVIGABLE_MAP = new EmptyNavigableMap<>(); /** * The instance we wrap and protect. */ private final NavigableMap<K, ? extends V> nm; UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {super(m); nm = m;} public K lowerKey(K key) { return nm.lowerKey(key); } public K floorKey(K key) { return nm.floorKey(key); } public K ceilingKey(K key) { return nm.ceilingKey(key); } public K higherKey(K key) { return nm.higherKey(key); } @SuppressWarnings("unchecked") public Entry<K, V> lowerEntry(K key) { Entry<K,V> lower = (Entry<K, V>) nm.lowerEntry(key); return (null != lower) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(lower) : null; } @SuppressWarnings("unchecked") public Entry<K, V> floorEntry(K key) { Entry<K,V> floor = (Entry<K, V>) nm.floorEntry(key); return (null != floor) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(floor) : null; } @SuppressWarnings("unchecked") public Entry<K, V> ceilingEntry(K key) { Entry<K,V> ceiling = (Entry<K, V>) nm.ceilingEntry(key); return (null != ceiling) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(ceiling) : null; } @SuppressWarnings("unchecked") public Entry<K, V> higherEntry(K key) { Entry<K,V> higher = (Entry<K, V>) nm.higherEntry(key); return (null != higher) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(higher) : null; } @SuppressWarnings("unchecked") public Entry<K, V> firstEntry() { Entry<K,V> first = (Entry<K, V>) nm.firstEntry(); return (null != first) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(first) : null; } @SuppressWarnings("unchecked") public Entry<K, V> lastEntry() { Entry<K,V> last = (Entry<K, V>) nm.lastEntry(); return (null != last) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(last) : null; } public Entry<K, V> pollFirstEntry() { throw new UnsupportedOperationException(); } public Entry<K, V> pollLastEntry() { throw new UnsupportedOperationException(); } public NavigableMap<K, V> descendingMap() { return unmodifiableNavigableMap(nm.descendingMap()); } public NavigableSet<K> navigableKeySet() { return unmodifiableNavigableSet(nm.navigableKeySet()); } public NavigableSet<K> descendingKeySet() { return unmodifiableNavigableSet(nm.descendingKeySet()); } public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return unmodifiableNavigableMap( nm.subMap(fromKey, fromInclusive, toKey, toInclusive)); } public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); } public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); } } // Synch Wrappers /** * Returns a synchronized (thread-safe) collection backed by the specified * collection. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing collection is accomplished * through the returned collection.<p> * * It is imperative that the user manually synchronize on the returned * collection when traversing it via {@link Iterator}, {@link Spliterator} * or {@link Stream}: * <pre> * Collection c = Collections.synchronizedCollection(myCollection); * ... * synchronized (c) { * Iterator i = c.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned collection does <i>not</i> pass the {@code hashCode} * and {@code equals} operations through to the backing collection, but * relies on {@code Object}'s equals and hashCode methods. This is * necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list.<p> * * The returned collection will be serializable if the specified collection * is serializable. * * @param <T> the class of the objects in the collection * @param c the collection to be "wrapped" in a synchronized collection. * @return a synchronized view of the specified collection. */ public static <T> Collection<T> synchronizedCollection(Collection<T> c) { return new SynchronizedCollection<>(c); } static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) { return new SynchronizedCollection<>(c, mutex); } /** * @serial include */ static class SynchronizedCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 3053995032091335093L; final Collection<E> c; // Backing Collection final Object mutex; // Object on which to synchronize SynchronizedCollection(Collection<E> c) { this.c = Objects.requireNonNull(c); mutex = this; } SynchronizedCollection(Collection<E> c, Object mutex) { this.c = Objects.requireNonNull(c); this.mutex = Objects.requireNonNull(mutex); } public int size() { synchronized (mutex) {return c.size();} } public boolean isEmpty() { synchronized (mutex) {return c.isEmpty();} } public boolean contains(Object o) { synchronized (mutex) {return c.contains(o);} } public Object[] toArray() { synchronized (mutex) {return c.toArray();} } public <T> T[] toArray(T[] a) { synchronized (mutex) {return c.toArray(a);} } public <T> T[] toArray(IntFunction<T[]> f) { synchronized (mutex) {return c.toArray(f);} } public Iterator<E> iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add(E e) { synchronized (mutex) {return c.add(e);} } public boolean remove(Object o) { synchronized (mutex) {return c.remove(o);} } public boolean containsAll(Collection<?> coll) { synchronized (mutex) {return c.containsAll(coll);} } public boolean addAll(Collection<? extends E> coll) { synchronized (mutex) {return c.addAll(coll);} } public boolean removeAll(Collection<?> coll) { synchronized (mutex) {return c.removeAll(coll);} } public boolean retainAll(Collection<?> coll) { synchronized (mutex) {return c.retainAll(coll);} } public void clear() { synchronized (mutex) {c.clear();} } public String toString() { synchronized (mutex) {return c.toString();} } // Override default methods in Collection @Override public void forEach(Consumer<? super E> consumer) { synchronized (mutex) {c.forEach(consumer);} } @Override public boolean removeIf(Predicate<? super E> filter) { synchronized (mutex) {return c.removeIf(filter);} } @Override public Spliterator<E> spliterator() { return c.spliterator(); // Must be manually synched by user! } @Override public Stream<E> stream() { return c.stream(); // Must be manually synched by user! } @Override public Stream<E> parallelStream() { return c.parallelStream(); // Must be manually synched by user! } private void writeObject(ObjectOutputStream s) throws IOException { synchronized (mutex) {s.defaultWriteObject();} } } /** * Returns a synchronized (thread-safe) set backed by the specified * set. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing set is accomplished * through the returned set.<p> * * It is imperative that the user manually synchronize on the returned * collection when traversing it via {@link Iterator}, {@link Spliterator} * or {@link Stream}: * <pre> * Set s = Collections.synchronizedSet(new HashSet()); * ... * synchronized (s) { * Iterator i = s.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned set will be serializable if the specified set is * serializable. * * @param <T> the class of the objects in the set * @param s the set to be "wrapped" in a synchronized set. * @return a synchronized view of the specified set. */ public static <T> Set<T> synchronizedSet(Set<T> s) { return new SynchronizedSet<>(s); } static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) { return new SynchronizedSet<>(s, mutex); } /** * @serial include */ static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> { private static final long serialVersionUID = 487447009682186044L; SynchronizedSet(Set<E> s) { super(s); } SynchronizedSet(Set<E> s, Object mutex) { super(s, mutex); } public boolean equals(Object o) { if (this == o) return true; synchronized (mutex) {return c.equals(o);} } public int hashCode() { synchronized (mutex) {return c.hashCode();} } } /** * Returns a synchronized (thread-safe) sorted set backed by the specified * sorted set. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing sorted set is accomplished * through the returned sorted set (or its views).<p> * * It is imperative that the user manually synchronize on the returned * sorted set when traversing it or any of its {@code subSet}, * {@code headSet}, or {@code tailSet} views via {@link Iterator}, * {@link Spliterator} or {@link Stream}: * <pre> * SortedSet s = Collections.synchronizedSortedSet(new TreeSet()); * ... * synchronized (s) { * Iterator i = s.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * or: * <pre> * SortedSet s = Collections.synchronizedSortedSet(new TreeSet()); * SortedSet s2 = s.headSet(foo); * ... * synchronized (s) { // Note: s, not s2!!! * Iterator i = s2.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned sorted set will be serializable if the specified * sorted set is serializable. * * @param <T> the class of the objects in the set * @param s the sorted set to be "wrapped" in a synchronized sorted set. * @return a synchronized view of the specified sorted set. */ public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) { return new SynchronizedSortedSet<>(s); } /** * @serial include */ static class SynchronizedSortedSet<E> extends SynchronizedSet<E> implements SortedSet<E> { private static final long serialVersionUID = 8695801310862127406L; private final SortedSet<E> ss; SynchronizedSortedSet(SortedSet<E> s) { super(s); ss = s; } SynchronizedSortedSet(SortedSet<E> s, Object mutex) { super(s, mutex); ss = s; } public Comparator<? super E> comparator() { synchronized (mutex) {return ss.comparator();} } public SortedSet<E> subSet(E fromElement, E toElement) { synchronized (mutex) { return new SynchronizedSortedSet<>( ss.subSet(fromElement, toElement), mutex); } } public SortedSet<E> headSet(E toElement) { synchronized (mutex) { return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex); } } public SortedSet<E> tailSet(E fromElement) { synchronized (mutex) { return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex); } } public E first() { synchronized (mutex) {return ss.first();} } public E last() { synchronized (mutex) {return ss.last();} } } /** * Returns a synchronized (thread-safe) navigable set backed by the * specified navigable set. In order to guarantee serial access, it is * critical that <strong>all</strong> access to the backing navigable set is * accomplished through the returned navigable set (or its views).<p> * * It is imperative that the user manually synchronize on the returned * navigable set when traversing it, or any of its {@code subSet}, * {@code headSet}, or {@code tailSet} views, via {@link Iterator}, * {@link Spliterator} or {@link Stream}: * <pre> * NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet()); * ... * synchronized (s) { * Iterator i = s.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * or: * <pre> * NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet()); * NavigableSet s2 = s.headSet(foo, true); * ... * synchronized (s) { // Note: s, not s2!!! * Iterator i = s2.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned navigable set will be serializable if the specified * navigable set is serializable. * * @param <T> the class of the objects in the set * @param s the navigable set to be "wrapped" in a synchronized navigable * set * @return a synchronized view of the specified navigable set * @since 1.8 */ public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) { return new SynchronizedNavigableSet<>(s); } /** * @serial include */ static class SynchronizedNavigableSet<E> extends SynchronizedSortedSet<E> implements NavigableSet<E> { private static final long serialVersionUID = -5505529816273629798L; private final NavigableSet<E> ns; SynchronizedNavigableSet(NavigableSet<E> s) { super(s); ns = s; } SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) { super(s, mutex); ns = s; } public E lower(E e) { synchronized (mutex) {return ns.lower(e);} } public E floor(E e) { synchronized (mutex) {return ns.floor(e);} } public E ceiling(E e) { synchronized (mutex) {return ns.ceiling(e);} } public E higher(E e) { synchronized (mutex) {return ns.higher(e);} } public E pollFirst() { synchronized (mutex) {return ns.pollFirst();} } public E pollLast() { synchronized (mutex) {return ns.pollLast();} } public NavigableSet<E> descendingSet() { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex); } } public Iterator<E> descendingIterator() { synchronized (mutex) { return descendingSet().iterator(); } } public NavigableSet<E> subSet(E fromElement, E toElement) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex); } } public NavigableSet<E> headSet(E toElement) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex); } } public NavigableSet<E> tailSet(E fromElement) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, true), mutex); } } public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); } } public NavigableSet<E> headSet(E toElement, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex); } } public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive), mutex); } } } /** * Returns a synchronized (thread-safe) list backed by the specified * list. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing list is accomplished * through the returned list.<p> * * It is imperative that the user manually synchronize on the returned * list when traversing it via {@link Iterator}, {@link Spliterator} * or {@link Stream}: * <pre> * List list = Collections.synchronizedList(new ArrayList()); * ... * synchronized (list) { * Iterator i = list.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned list will be serializable if the specified list is * serializable. * * @param <T> the class of the objects in the list * @param list the list to be "wrapped" in a synchronized list. * @return a synchronized view of the specified list. */ public static <T> List<T> synchronizedList(List<T> list) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : new SynchronizedList<>(list)); } static <T> List<T> synchronizedList(List<T> list, Object mutex) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list, mutex) : new SynchronizedList<>(list, mutex)); } /** * @serial include */ static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> { private static final long serialVersionUID = -7754090372962971524L; final List<E> list; SynchronizedList(List<E> list) { super(list); this.list = list; } SynchronizedList(List<E> list, Object mutex) { super(list, mutex); this.list = list; } public boolean equals(Object o) { if (this == o) return true; synchronized (mutex) {return list.equals(o);} } public int hashCode() { synchronized (mutex) {return list.hashCode();} } public E get(int index) { synchronized (mutex) {return list.get(index);} } public E set(int index, E element) { synchronized (mutex) {return list.set(index, element);} } public void add(int index, E element) { synchronized (mutex) {list.add(index, element);} } public E remove(int index) { synchronized (mutex) {return list.remove(index);} } public int indexOf(Object o) { synchronized (mutex) {return list.indexOf(o);} } public int lastIndexOf(Object o) { synchronized (mutex) {return list.lastIndexOf(o);} } public boolean addAll(int index, Collection<? extends E> c) { synchronized (mutex) {return list.addAll(index, c);} } public ListIterator<E> listIterator() { return list.listIterator(); // Must be manually synched by user } public ListIterator<E> listIterator(int index) { return list.listIterator(index); // Must be manually synched by user } public List<E> subList(int fromIndex, int toIndex) { synchronized (mutex) { return new SynchronizedList<>(list.subList(fromIndex, toIndex), mutex); } } @Override public void replaceAll(UnaryOperator<E> operator) { synchronized (mutex) {list.replaceAll(operator);} } @Override public void sort(Comparator<? super E> c) { synchronized (mutex) {list.sort(c);} } /** * SynchronizedRandomAccessList instances are serialized as * SynchronizedList instances to allow them to be deserialized * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList). * This method inverts the transformation. As a beneficial * side-effect, it also grafts the RandomAccess marker onto * SynchronizedList instances that were serialized in pre-1.4 JREs. * * Note: Unfortunately, SynchronizedRandomAccessList instances * serialized in 1.4.1 and deserialized in 1.4 will become * SynchronizedList instances, as this method was missing in 1.4. */ private Object readResolve() { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : this); } } /** * @serial include */ static class SynchronizedRandomAccessList<E> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list) { super(list); } SynchronizedRandomAccessList(List<E> list, Object mutex) { super(list, mutex); } public List<E> subList(int fromIndex, int toIndex) { synchronized (mutex) { return new SynchronizedRandomAccessList<>( list.subList(fromIndex, toIndex), mutex); } } private static final long serialVersionUID = 1530674583602358482L; /** * Allows instances to be deserialized in pre-1.4 JREs (which do * not have SynchronizedRandomAccessList). SynchronizedList has * a readResolve method that inverts this transformation upon * deserialization. */ private Object writeReplace() { return new SynchronizedList<>(list); } } /** * Returns a synchronized (thread-safe) map backed by the specified * map. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing map is accomplished * through the returned map.<p> * * It is imperative that the user manually synchronize on the returned * map when traversing any of its collection views via {@link Iterator}, * {@link Spliterator} or {@link Stream}: * <pre> * Map m = Collections.synchronizedMap(new HashMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned map will be serializable if the specified map is * serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the map to be "wrapped" in a synchronized map. * @return a synchronized view of the specified map. */ public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) { return new SynchronizedMap<>(m); } /** * @serial include */ private static class SynchronizedMap<K,V> implements Map<K,V>, Serializable { private static final long serialVersionUID = 1978198479659022715L; private final Map<K,V> m; // Backing Map final Object mutex; // Object on which to synchronize SynchronizedMap(Map<K,V> m) { this.m = Objects.requireNonNull(m); mutex = this; } SynchronizedMap(Map<K,V> m, Object mutex) { this.m = m; this.mutex = mutex; } public int size() { synchronized (mutex) {return m.size();} } public boolean isEmpty() { synchronized (mutex) {return m.isEmpty();} } public boolean containsKey(Object key) { synchronized (mutex) {return m.containsKey(key);} } public boolean containsValue(Object value) { synchronized (mutex) {return m.containsValue(value);} } public V get(Object key) { synchronized (mutex) {return m.get(key);} } public V put(K key, V value) { synchronized (mutex) {return m.put(key, value);} } public V remove(Object key) { synchronized (mutex) {return m.remove(key);} } public void putAll(Map<? extends K, ? extends V> map) { synchronized (mutex) {m.putAll(map);} } public void clear() { synchronized (mutex) {m.clear();} } private transient Set<K> keySet; private transient Set<Entry<K,V>> entrySet; private transient Collection<V> values; public Set<K> keySet() { synchronized (mutex) { if (keySet==null) keySet = new SynchronizedSet<>(m.keySet(), mutex); return keySet; } } public Set<Entry<K,V>> entrySet() { synchronized (mutex) { if (entrySet==null) entrySet = new SynchronizedSet<>(m.entrySet(), mutex); return entrySet; } } public Collection<V> values() { synchronized (mutex) { if (values==null) values = new SynchronizedCollection<>(m.values(), mutex); return values; } } public boolean equals(Object o) { if (this == o) return true; synchronized (mutex) {return m.equals(o);} } public int hashCode() { synchronized (mutex) {return m.hashCode();} } public String toString() { synchronized (mutex) {return m.toString();} } // Override default methods in Map @Override public V getOrDefault(Object k, V defaultValue) { synchronized (mutex) {return m.getOrDefault(k, defaultValue);} } @Override public void forEach(BiConsumer<? super K, ? super V> action) { synchronized (mutex) {m.forEach(action);} } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { synchronized (mutex) {m.replaceAll(function);} } @Override public V putIfAbsent(K key, V value) { synchronized (mutex) {return m.putIfAbsent(key, value);} } @Override public boolean remove(Object key, Object value) { synchronized (mutex) {return m.remove(key, value);} } @Override public boolean replace(K key, V oldValue, V newValue) { synchronized (mutex) {return m.replace(key, oldValue, newValue);} } @Override public V replace(K key, V value) { synchronized (mutex) {return m.replace(key, value);} } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { synchronized (mutex) {return m.computeIfAbsent(key, mappingFunction);} } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { synchronized (mutex) {return m.computeIfPresent(key, remappingFunction);} } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { synchronized (mutex) {return m.compute(key, remappingFunction);} } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { synchronized (mutex) {return m.merge(key, value, remappingFunction);} } private void writeObject(ObjectOutputStream s) throws IOException { synchronized (mutex) {s.defaultWriteObject();} } } /** * Returns a synchronized (thread-safe) sorted map backed by the specified * sorted map. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing sorted map is accomplished * through the returned sorted map (or its views).<p> * * It is imperative that the user manually synchronize on the returned * sorted map when traversing any of its collection views, or the * collections views of any of its {@code subMap}, {@code headMap} or * {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or * {@link Stream}: * <pre> * SortedMap m = Collections.synchronizedSortedMap(new TreeMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * or: * <pre> * SortedMap m = Collections.synchronizedSortedMap(new TreeMap()); * SortedMap m2 = m.subMap(foo, bar); * ... * Set s2 = m2.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not m2 or s2! * Iterator i = s2.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned sorted map will be serializable if the specified * sorted map is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the sorted map to be "wrapped" in a synchronized sorted map. * @return a synchronized view of the specified sorted map. */ public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) { return new SynchronizedSortedMap<>(m); } /** * @serial include */ static class SynchronizedSortedMap<K,V> extends SynchronizedMap<K,V> implements SortedMap<K,V> { private static final long serialVersionUID = -8798146769416483793L; private final SortedMap<K,V> sm; SynchronizedSortedMap(SortedMap<K,V> m) { super(m); sm = m; } SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) { super(m, mutex); sm = m; } public Comparator<? super K> comparator() { synchronized (mutex) {return sm.comparator();} } public SortedMap<K,V> subMap(K fromKey, K toKey) { synchronized (mutex) { return new SynchronizedSortedMap<>( sm.subMap(fromKey, toKey), mutex); } } public SortedMap<K,V> headMap(K toKey) { synchronized (mutex) { return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex); } } public SortedMap<K,V> tailMap(K fromKey) { synchronized (mutex) { return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex); } } public K firstKey() { synchronized (mutex) {return sm.firstKey();} } public K lastKey() { synchronized (mutex) {return sm.lastKey();} } } /** * Returns a synchronized (thread-safe) navigable map backed by the * specified navigable map. In order to guarantee serial access, it is * critical that <strong>all</strong> access to the backing navigable map is * accomplished through the returned navigable map (or its views).<p> * * It is imperative that the user manually synchronize on the returned * navigable map when traversing any of its collection views, or the * collections views of any of its {@code subMap}, {@code headMap} or * {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or * {@link Stream}: * <pre> * NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * or: * <pre> * NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap()); * NavigableMap m2 = m.subMap(foo, true, bar, false); * ... * Set s2 = m2.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not m2 or s2! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned navigable map will be serializable if the specified * navigable map is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the navigable map to be "wrapped" in a synchronized navigable * map * @return a synchronized view of the specified navigable map. * @since 1.8 */ public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) { return new SynchronizedNavigableMap<>(m); } /** * A synchronized NavigableMap. * * @serial include */ static class SynchronizedNavigableMap<K,V> extends SynchronizedSortedMap<K,V> implements NavigableMap<K,V> { private static final long serialVersionUID = 699392247599746807L; private final NavigableMap<K,V> nm; SynchronizedNavigableMap(NavigableMap<K,V> m) { super(m); nm = m; } SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) { super(m, mutex); nm = m; } public Entry<K, V> lowerEntry(K key) { synchronized (mutex) { return nm.lowerEntry(key); } } public K lowerKey(K key) { synchronized (mutex) { return nm.lowerKey(key); } } public Entry<K, V> floorEntry(K key) { synchronized (mutex) { return nm.floorEntry(key); } } public K floorKey(K key) { synchronized (mutex) { return nm.floorKey(key); } } public Entry<K, V> ceilingEntry(K key) { synchronized (mutex) { return nm.ceilingEntry(key); } } public K ceilingKey(K key) { synchronized (mutex) { return nm.ceilingKey(key); } } public Entry<K, V> higherEntry(K key) { synchronized (mutex) { return nm.higherEntry(key); } } public K higherKey(K key) { synchronized (mutex) { return nm.higherKey(key); } } public Entry<K, V> firstEntry() { synchronized (mutex) { return nm.firstEntry(); } } public Entry<K, V> lastEntry() { synchronized (mutex) { return nm.lastEntry(); } } public Entry<K, V> pollFirstEntry() { synchronized (mutex) { return nm.pollFirstEntry(); } } public Entry<K, V> pollLastEntry() { synchronized (mutex) { return nm.pollLastEntry(); } } public NavigableMap<K, V> descendingMap() { synchronized (mutex) { return new SynchronizedNavigableMap<>(nm.descendingMap(), mutex); } } public NavigableSet<K> keySet() { return navigableKeySet(); } public NavigableSet<K> navigableKeySet() { synchronized (mutex) { return new SynchronizedNavigableSet<>(nm.navigableKeySet(), mutex); } } public NavigableSet<K> descendingKeySet() { synchronized (mutex) { return new SynchronizedNavigableSet<>(nm.descendingKeySet(), mutex); } } public SortedMap<K,V> subMap(K fromKey, K toKey) { synchronized (mutex) { return new SynchronizedNavigableMap<>( nm.subMap(fromKey, true, toKey, false), mutex); } } public SortedMap<K,V> headMap(K toKey) { synchronized (mutex) { return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex); } } public SortedMap<K,V> tailMap(K fromKey) { synchronized (mutex) { return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex); } } public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { synchronized (mutex) { return new SynchronizedNavigableMap<>( nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableMap<>( nm.headMap(toKey, inclusive), mutex); } } public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableMap<>( nm.tailMap(fromKey, inclusive), mutex); } } } // Dynamically typesafe collection wrappers /** * Returns a dynamically typesafe view of the specified collection. * Any attempt to insert an element of the wrong type will result in an * immediate {@link ClassCastException}. Assuming a collection * contains no incorrectly typed elements prior to the time a * dynamically typesafe view is generated, and that all subsequent * access to the collection takes place through the view, it is * <i>guaranteed</i> that the collection cannot contain an incorrectly * typed element. * * <p>The generics mechanism in the language provides compile-time * (static) type checking, but it is possible to defeat this mechanism * with unchecked casts. Usually this is not a problem, as the compiler * issues warnings on all such unchecked operations. There are, however, * times when static type checking alone is not sufficient. For example, * suppose a collection is passed to a third-party library and it is * imperative that the library code not corrupt the collection by * inserting an element of the wrong type. * * <p>Another use of dynamically typesafe views is debugging. Suppose a * program fails with a {@code ClassCastException}, indicating that an * incorrectly typed element was put into a parameterized collection. * Unfortunately, the exception can occur at any time after the erroneous * element is inserted, so it typically provides little or no information * as to the real source of the problem. If the problem is reproducible, * one can quickly determine its source by temporarily modifying the * program to wrap the collection with a dynamically typesafe view. * For example, this declaration: * <pre> {@code * Collection<String> c = new HashSet<>(); * }</pre> * may be replaced temporarily by this one: * <pre> {@code * Collection<String> c = Collections.checkedCollection( * new HashSet<>(), String.class); * }</pre> * Running the program again will cause it to fail at the point where * an incorrectly typed element is inserted into the collection, clearly * identifying the source of the problem. Once the problem is fixed, the * modified declaration may be reverted back to the original. * * <p>The returned collection does <i>not</i> pass the hashCode and equals * operations through to the backing collection, but relies on * {@code Object}'s {@code equals} and {@code hashCode} methods. This * is necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list. * * <p>The returned collection will be serializable if the specified * collection is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned collection permits insertion of null elements * whenever the backing collection does. * * @param <E> the class of the objects in the collection * @param c the collection for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code c} is permitted to hold * @return a dynamically typesafe view of the specified collection * @since 1.5 */ public static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type) { return new CheckedCollection<>(c, type); } @SuppressWarnings("unchecked") static <T> T[] zeroLengthArray(Class<T> type) { return (T[]) Array.newInstance(type, 0); } /** * @serial include */ static class CheckedCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 1578914078182001775L; final Collection<E> c; final Class<E> type; @SuppressWarnings("unchecked") E typeCheck(Object o) { if (o != null && !type.isInstance(o)) throw new ClassCastException(badElementMsg(o)); return (E) o; } private String badElementMsg(Object o) { return "Attempt to insert " + o.getClass() + " element into collection with element type " + type; } CheckedCollection(Collection<E> c, Class<E> type) { this.c = Objects.requireNonNull(c, "c"); this.type = Objects.requireNonNull(type, "type"); } public int size() { return c.size(); } public boolean isEmpty() { return c.isEmpty(); } public boolean contains(Object o) { return c.contains(o); } public Object[] toArray() { return c.toArray(); } public <T> T[] toArray(T[] a) { return c.toArray(a); } public <T> T[] toArray(IntFunction<T[]> f) { return c.toArray(f); } public String toString() { return c.toString(); } public boolean remove(Object o) { return c.remove(o); } public void clear() { c.clear(); } public boolean containsAll(Collection<?> coll) { return c.containsAll(coll); } public boolean removeAll(Collection<?> coll) { return c.removeAll(coll); } public boolean retainAll(Collection<?> coll) { return c.retainAll(coll); } public Iterator<E> iterator() { // JDK-6363904 - unwrapped iterator could be typecast to // ListIterator with unsafe set() final Iterator<E> it = c.iterator(); return new Iterator<E>() { public boolean hasNext() { return it.hasNext(); } public E next() { return it.next(); } public void remove() { it.remove(); } public void forEachRemaining(Consumer<? super E> action) { it.forEachRemaining(action); } }; } public boolean add(E e) { return c.add(typeCheck(e)); } private E[] zeroLengthElementArray; // Lazily initialized private E[] zeroLengthElementArray() { return zeroLengthElementArray != null ? zeroLengthElementArray : (zeroLengthElementArray = zeroLengthArray(type)); } @SuppressWarnings("unchecked") Collection<E> checkedCopyOf(Collection<? extends E> coll) { Object[] a; try { E[] z = zeroLengthElementArray(); a = coll.toArray(z); // Defend against coll violating the toArray contract if (a.getClass() != z.getClass()) a = Arrays.copyOf(a, a.length, z.getClass()); } catch (ArrayStoreException ignore) { // To get better and consistent diagnostics, // we call typeCheck explicitly on each element. // We call clone() to defend against coll retaining a // reference to the returned array and storing a bad // element into it after it has been type checked. a = coll.toArray().clone(); for (Object o : a) typeCheck(o); } // A slight abuse of the type system, but safe here. return (Collection<E>) Arrays.asList(a); } public boolean addAll(Collection<? extends E> coll) { // Doing things this way insulates us from concurrent changes // in the contents of coll and provides all-or-nothing // semantics (which we wouldn't get if we type-checked each // element as we added it) return c.addAll(checkedCopyOf(coll)); } // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) {c.forEach(action);} @Override public boolean removeIf(Predicate<? super E> filter) { return c.removeIf(filter); } @Override public Spliterator<E> spliterator() {return c.spliterator();} @Override public Stream<E> stream() {return c.stream();} @Override public Stream<E> parallelStream() {return c.parallelStream();} } /** * Returns a dynamically typesafe view of the specified queue. * Any attempt to insert an element of the wrong type will result in * an immediate {@link ClassCastException}. Assuming a queue contains * no incorrectly typed elements prior to the time a dynamically typesafe * view is generated, and that all subsequent access to the queue * takes place through the view, it is <i>guaranteed</i> that the * queue cannot contain an incorrectly typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned queue will be serializable if the specified queue * is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned queue permits insertion of {@code null} elements * whenever the backing queue does. * * @param <E> the class of the objects in the queue * @param queue the queue for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code queue} is permitted to hold * @return a dynamically typesafe view of the specified queue * @since 1.8 */ public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type) { return new CheckedQueue<>(queue, type); } /** * @serial include */ static class CheckedQueue<E> extends CheckedCollection<E> implements Queue<E>, Serializable { private static final long serialVersionUID = 1433151992604707767L; final Queue<E> queue; CheckedQueue(Queue<E> queue, Class<E> elementType) { super(queue, elementType); this.queue = queue; } public E element() {return queue.element();} public boolean equals(Object o) {return o == this || c.equals(o);} public int hashCode() {return c.hashCode();} public E peek() {return queue.peek();} public E poll() {return queue.poll();} public E remove() {return queue.remove();} public boolean offer(E e) {return queue.offer(typeCheck(e));} } /** * Returns a dynamically typesafe view of the specified set. * Any attempt to insert an element of the wrong type will result in * an immediate {@link ClassCastException}. Assuming a set contains * no incorrectly typed elements prior to the time a dynamically typesafe * view is generated, and that all subsequent access to the set * takes place through the view, it is <i>guaranteed</i> that the * set cannot contain an incorrectly typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned set will be serializable if the specified set is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned set permits insertion of null elements whenever * the backing set does. * * @param <E> the class of the objects in the set * @param s the set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold * @return a dynamically typesafe view of the specified set * @since 1.5 */ public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) { return new CheckedSet<>(s, type); } /** * @serial include */ static class CheckedSet<E> extends CheckedCollection<E> implements Set<E>, Serializable { private static final long serialVersionUID = 4694047833775013803L; CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); } public boolean equals(Object o) { return o == this || c.equals(o); } public int hashCode() { return c.hashCode(); } } /** * Returns a dynamically typesafe view of the specified sorted set. * Any attempt to insert an element of the wrong type will result in an * immediate {@link ClassCastException}. Assuming a sorted set * contains no incorrectly typed elements prior to the time a * dynamically typesafe view is generated, and that all subsequent * access to the sorted set takes place through the view, it is * <i>guaranteed</i> that the sorted set cannot contain an incorrectly * typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned sorted set will be serializable if the specified sorted * set is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned sorted set permits insertion of null elements * whenever the backing sorted set does. * * @param <E> the class of the objects in the set * @param s the sorted set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold * @return a dynamically typesafe view of the specified sorted set * @since 1.5 */ public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s, Class<E> type) { return new CheckedSortedSet<>(s, type); } /** * @serial include */ static class CheckedSortedSet<E> extends CheckedSet<E> implements SortedSet<E>, Serializable { private static final long serialVersionUID = 1599911165492914959L; private final SortedSet<E> ss; CheckedSortedSet(SortedSet<E> s, Class<E> type) { super(s, type); ss = s; } public Comparator<? super E> comparator() { return ss.comparator(); } public E first() { return ss.first(); } public E last() { return ss.last(); } public SortedSet<E> subSet(E fromElement, E toElement) { return checkedSortedSet(ss.subSet(fromElement,toElement), type); } public SortedSet<E> headSet(E toElement) { return checkedSortedSet(ss.headSet(toElement), type); } public SortedSet<E> tailSet(E fromElement) { return checkedSortedSet(ss.tailSet(fromElement), type); } } /** * Returns a dynamically typesafe view of the specified navigable set. * Any attempt to insert an element of the wrong type will result in an * immediate {@link ClassCastException}. Assuming a navigable set * contains no incorrectly typed elements prior to the time a * dynamically typesafe view is generated, and that all subsequent * access to the navigable set takes place through the view, it is * <em>guaranteed</em> that the navigable set cannot contain an incorrectly * typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned navigable set will be serializable if the specified * navigable set is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned navigable set permits insertion of null elements * whenever the backing sorted set does. * * @param <E> the class of the objects in the set * @param s the navigable set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold * @return a dynamically typesafe view of the specified navigable set * @since 1.8 */ public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s, Class<E> type) { return new CheckedNavigableSet<>(s, type); } /** * @serial include */ static class CheckedNavigableSet<E> extends CheckedSortedSet<E> implements NavigableSet<E>, Serializable { private static final long serialVersionUID = -5429120189805438922L; private final NavigableSet<E> ns; CheckedNavigableSet(NavigableSet<E> s, Class<E> type) { super(s, type); ns = s; } public E lower(E e) { return ns.lower(e); } public E floor(E e) { return ns.floor(e); } public E ceiling(E e) { return ns.ceiling(e); } public E higher(E e) { return ns.higher(e); } public E pollFirst() { return ns.pollFirst(); } public E pollLast() {return ns.pollLast(); } public NavigableSet<E> descendingSet() { return checkedNavigableSet(ns.descendingSet(), type); } public Iterator<E> descendingIterator() {return checkedNavigableSet(ns.descendingSet(), type).iterator(); } public NavigableSet<E> subSet(E fromElement, E toElement) { return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type); } public NavigableSet<E> headSet(E toElement) { return checkedNavigableSet(ns.headSet(toElement, false), type); } public NavigableSet<E> tailSet(E fromElement) { return checkedNavigableSet(ns.tailSet(fromElement, true), type); } public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type); } public NavigableSet<E> headSet(E toElement, boolean inclusive) { return checkedNavigableSet(ns.headSet(toElement, inclusive), type); } public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type); } } /** * Returns a dynamically typesafe view of the specified list. * Any attempt to insert an element of the wrong type will result in * an immediate {@link ClassCastException}. Assuming a list contains * no incorrectly typed elements prior to the time a dynamically typesafe * view is generated, and that all subsequent access to the list * takes place through the view, it is <i>guaranteed</i> that the * list cannot contain an incorrectly typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned list will be serializable if the specified list * is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned list permits insertion of null elements whenever * the backing list does. * * @param <E> the class of the objects in the list * @param list the list for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code list} is permitted to hold * @return a dynamically typesafe view of the specified list * @since 1.5 */ public static <E> List<E> checkedList(List<E> list, Class<E> type) { return (list instanceof RandomAccess ? new CheckedRandomAccessList<>(list, type) : new CheckedList<>(list, type)); } /** * @serial include */ static class CheckedList<E> extends CheckedCollection<E> implements List<E> { private static final long serialVersionUID = 65247728283967356L; final List<E> list; CheckedList(List<E> list, Class<E> type) { super(list, type); this.list = list; } public boolean equals(Object o) { return o == this || list.equals(o); } public int hashCode() { return list.hashCode(); } public E get(int index) { return list.get(index); } public E remove(int index) { return list.remove(index); } public int indexOf(Object o) { return list.indexOf(o); } public int lastIndexOf(Object o) { return list.lastIndexOf(o); } public E set(int index, E element) { return list.set(index, typeCheck(element)); } public void add(int index, E element) { list.add(index, typeCheck(element)); } public boolean addAll(int index, Collection<? extends E> c) { return list.addAll(index, checkedCopyOf(c)); } public ListIterator<E> listIterator() { return listIterator(0); } public ListIterator<E> listIterator(final int index) { final ListIterator<E> i = list.listIterator(index); return new ListIterator<E>() { public boolean hasNext() { return i.hasNext(); } public E next() { return i.next(); } public boolean hasPrevious() { return i.hasPrevious(); } public E previous() { return i.previous(); } public int nextIndex() { return i.nextIndex(); } public int previousIndex() { return i.previousIndex(); } public void remove() { i.remove(); } public void set(E e) { i.set(typeCheck(e)); } public void add(E e) { i.add(typeCheck(e)); } @Override public void forEachRemaining(Consumer<? super E> action) { i.forEachRemaining(action); } }; } public List<E> subList(int fromIndex, int toIndex) { return new CheckedList<>(list.subList(fromIndex, toIndex), type); } /** * {@inheritDoc} * * @throws ClassCastException if the class of an element returned by the * operator prevents it from being added to this collection. The * exception may be thrown after some elements of the list have * already been replaced. */ @Override public void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); list.replaceAll(e -> typeCheck(operator.apply(e))); } @Override public void sort(Comparator<? super E> c) { list.sort(c); } } /** * @serial include */ static class CheckedRandomAccessList<E> extends CheckedList<E> implements RandomAccess { private static final long serialVersionUID = 1638200125423088369L; CheckedRandomAccessList(List<E> list, Class<E> type) { super(list, type); } public List<E> subList(int fromIndex, int toIndex) { return new CheckedRandomAccessList<>( list.subList(fromIndex, toIndex), type); } } /** * Returns a dynamically typesafe view of the specified map. * Any attempt to insert a mapping whose key or value have the wrong * type will result in an immediate {@link ClassCastException}. * Similarly, any attempt to modify the value currently associated with * a key will result in an immediate {@link ClassCastException}, * whether the modification is attempted directly through the map * itself, or through a {@link Map.Entry} instance obtained from the * map's {@link Map#entrySet() entry set} view. * * <p>Assuming a map contains no incorrectly typed keys or values * prior to the time a dynamically typesafe view is generated, and * that all subsequent access to the map takes place through the view * (or one of its collection views), it is <i>guaranteed</i> that the * map cannot contain an incorrectly typed key or value. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned map will be serializable if the specified map is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned map permits insertion of null keys or values * whenever the backing map does. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold * @param valueType the type of value that {@code m} is permitted to hold * @return a dynamically typesafe view of the specified map * @since 1.5 */ public static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) { return new CheckedMap<>(m, keyType, valueType); } /** * @serial include */ private static class CheckedMap<K,V> implements Map<K,V>, Serializable { private static final long serialVersionUID = 5742860141034234728L; private final Map<K, V> m; final Class<K> keyType; final Class<V> valueType; private void typeCheck(Object key, Object value) { if (key != null && !keyType.isInstance(key)) throw new ClassCastException(badKeyMsg(key)); if (value != null && !valueType.isInstance(value)) throw new ClassCastException(badValueMsg(value)); } private BiFunction<? super K, ? super V, ? extends V> typeCheck( BiFunction<? super K, ? super V, ? extends V> func) { Objects.requireNonNull(func); return (k, v) -> { V newValue = func.apply(k, v); typeCheck(k, newValue); return newValue; }; } private String badKeyMsg(Object key) { return "Attempt to insert " + key.getClass() + " key into map with key type " + keyType; } private String badValueMsg(Object value) { return "Attempt to insert " + value.getClass() + " value into map with value type " + valueType; } CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) { this.m = Objects.requireNonNull(m); this.keyType = Objects.requireNonNull(keyType); this.valueType = Objects.requireNonNull(valueType); } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean containsKey(Object key) { return m.containsKey(key); } public boolean containsValue(Object v) { return m.containsValue(v); } public V get(Object key) { return m.get(key); } public V remove(Object key) { return m.remove(key); } public void clear() { m.clear(); } public Set<K> keySet() { return m.keySet(); } public Collection<V> values() { return m.values(); } public boolean equals(Object o) { return o == this || m.equals(o); } public int hashCode() { return m.hashCode(); } public String toString() { return m.toString(); } public V put(K key, V value) { typeCheck(key, value); return m.put(key, value); } @SuppressWarnings("unchecked") public void putAll(Map<? extends K, ? extends V> t) { // Satisfy the following goals: // - good diagnostics in case of type mismatch // - all-or-nothing semantics // - protection from malicious t // - correct behavior if t is a concurrent map Object[] entries = t.entrySet().toArray(); List<Entry<K,V>> checked = new ArrayList<>(entries.length); for (Object o : entries) { Entry<?,?> e = (Entry<?,?>) o; Object k = e.getKey(); Object v = e.getValue(); typeCheck(k, v); checked.add( new AbstractMap.SimpleImmutableEntry<>((K)k, (V)v)); } for (Entry<K,V> e : checked) m.put(e.getKey(), e.getValue()); } private transient Set<Entry<K,V>> entrySet; public Set<Entry<K,V>> entrySet() { if (entrySet==null) entrySet = new CheckedEntrySet<>(m.entrySet(), valueType); return entrySet; } // Override default methods in Map @Override public void forEach(BiConsumer<? super K, ? super V> action) { m.forEach(action); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { m.replaceAll(typeCheck(function)); } @Override public V putIfAbsent(K key, V value) { typeCheck(key, value); return m.putIfAbsent(key, value); } @Override public boolean remove(Object key, Object value) { return m.remove(key, value); } @Override public boolean replace(K key, V oldValue, V newValue) { typeCheck(key, newValue); return m.replace(key, oldValue, newValue); } @Override public V replace(K key, V value) { typeCheck(key, value); return m.replace(key, value); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { Objects.requireNonNull(mappingFunction); return m.computeIfAbsent(key, k -> { V value = mappingFunction.apply(k); typeCheck(k, value); return value; }); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return m.computeIfPresent(key, typeCheck(remappingFunction)); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return m.compute(key, typeCheck(remappingFunction)); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); return m.merge(key, value, (v1, v2) -> { V newValue = remappingFunction.apply(v1, v2); typeCheck(null, newValue); return newValue; }); } /** * We need this class in addition to CheckedSet as Map.Entry permits * modification of the backing Map via the setValue operation. This * class is subtle: there are many possible attacks that must be * thwarted. * * @serial exclude */ static class CheckedEntrySet<K,V> implements Set<Entry<K,V>> { private final Set<Entry<K,V>> s; private final Class<V> valueType; CheckedEntrySet(Set<Entry<K, V>> s, Class<V> valueType) { this.s = s; this.valueType = valueType; } public int size() { return s.size(); } public boolean isEmpty() { return s.isEmpty(); } public String toString() { return s.toString(); } public int hashCode() { return s.hashCode(); } public void clear() { s.clear(); } public boolean add(Entry<K, V> e) { throw new UnsupportedOperationException(); } public boolean addAll(Collection<? extends Entry<K, V>> coll) { throw new UnsupportedOperationException(); } public Iterator<Entry<K,V>> iterator() { final Iterator<Entry<K, V>> i = s.iterator(); return new Iterator<Entry<K,V>>() { public boolean hasNext() { return i.hasNext(); } public void remove() { i.remove(); } public Entry<K,V> next() { return checkedEntry(i.next(), valueType); } public void forEachRemaining(Consumer<? super Entry<K, V>> action) { i.forEachRemaining( e -> action.accept(checkedEntry(e, valueType))); } }; } @SuppressWarnings("unchecked") public Object[] toArray() { Object[] source = s.toArray(); /* * Ensure that we don't get an ArrayStoreException even if * s.toArray returns an array of something other than Object */ Object[] dest = (source.getClass() == Object[].class) ? source : new Object[source.length]; for (int i = 0; i < source.length; i++) dest[i] = checkedEntry((Entry<K,V>)source[i], valueType); return dest; } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { // We don't pass a to s.toArray, to avoid window of // vulnerability wherein an unscrupulous multithreaded client // could get his hands on raw (unwrapped) Entries from s. T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0)); for (int i=0; i<arr.length; i++) arr[i] = (T) checkedEntry((Entry<K,V>)arr[i], valueType); if (arr.length > a.length) return arr; System.arraycopy(arr, 0, a, 0, arr.length); if (a.length > arr.length) a[arr.length] = null; return a; } /** * This method is overridden to protect the backing set against * an object with a nefarious equals function that senses * that the equality-candidate is Map.Entry and calls its * setValue method. */ public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Entry<?,?> e = (Entry<?,?>) o; return s.contains( (e instanceof CheckedEntry) ? e : checkedEntry(e, valueType)); } /** * The bulk collection methods are overridden to protect * against an unscrupulous collection whose contains(Object o) * method senses when o is a Map.Entry, and calls o.setValue. */ public boolean containsAll(Collection<?> c) { for (Object o : c) if (!contains(o)) // Invokes safe contains() above return false; return true; } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; return s.remove(new AbstractMap.SimpleImmutableEntry <>((Entry<?,?>)o)); } public boolean removeAll(Collection<?> c) { return batchRemove(c, false); } public boolean retainAll(Collection<?> c) { return batchRemove(c, true); } private boolean batchRemove(Collection<?> c, boolean complement) { Objects.requireNonNull(c); boolean modified = false; Iterator<Entry<K,V>> it = iterator(); while (it.hasNext()) { if (c.contains(it.next()) != complement) { it.remove(); modified = true; } } return modified; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Set<?> that = (Set<?>) o; return that.size() == s.size() && containsAll(that); // Invokes safe containsAll() above } static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Entry<K,V> e, Class<T> valueType) { return new CheckedEntry<>(e, valueType); } /** * This "wrapper class" serves two purposes: it prevents * the client from modifying the backing Map, by short-circuiting * the setValue method, and it protects the backing Map against * an ill-behaved Map.Entry that attempts to modify another * Map.Entry when asked to perform an equality check. */ private static class CheckedEntry<K,V,T> implements Entry<K,V> { private final Entry<K, V> e; private final Class<T> valueType; CheckedEntry(Entry<K, V> e, Class<T> valueType) { this.e = Objects.requireNonNull(e); this.valueType = Objects.requireNonNull(valueType); } public K getKey() { return e.getKey(); } public V getValue() { return e.getValue(); } public int hashCode() { return e.hashCode(); } public String toString() { return e.toString(); } public V setValue(V value) { if (value != null && !valueType.isInstance(value)) throw new ClassCastException(badValueMsg(value)); return e.setValue(value); } private String badValueMsg(Object value) { return "Attempt to insert " + value.getClass() + " value into map with value type " + valueType; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map.Entry)) return false; return e.equals(new AbstractMap.SimpleImmutableEntry <>((Entry<?,?>)o)); } } } } /** * Returns a dynamically typesafe view of the specified sorted map. * Any attempt to insert a mapping whose key or value have the wrong * type will result in an immediate {@link ClassCastException}. * Similarly, any attempt to modify the value currently associated with * a key will result in an immediate {@link ClassCastException}, * whether the modification is attempted directly through the map * itself, or through a {@link Map.Entry} instance obtained from the * map's {@link Map#entrySet() entry set} view. * * <p>Assuming a map contains no incorrectly typed keys or values * prior to the time a dynamically typesafe view is generated, and * that all subsequent access to the map takes place through the view * (or one of its collection views), it is <i>guaranteed</i> that the * map cannot contain an incorrectly typed key or value. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned map will be serializable if the specified map is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned map permits insertion of null keys or values * whenever the backing map does. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold * @param valueType the type of value that {@code m} is permitted to hold * @return a dynamically typesafe view of the specified map * @since 1.5 */ public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m, Class<K> keyType, Class<V> valueType) { return new CheckedSortedMap<>(m, keyType, valueType); } /** * @serial include */ static class CheckedSortedMap<K,V> extends CheckedMap<K,V> implements SortedMap<K,V>, Serializable { private static final long serialVersionUID = 1599671320688067438L; private final SortedMap<K, V> sm; CheckedSortedMap(SortedMap<K, V> m, Class<K> keyType, Class<V> valueType) { super(m, keyType, valueType); sm = m; } public Comparator<? super K> comparator() { return sm.comparator(); } public K firstKey() { return sm.firstKey(); } public K lastKey() { return sm.lastKey(); } public SortedMap<K,V> subMap(K fromKey, K toKey) { return checkedSortedMap(sm.subMap(fromKey, toKey), keyType, valueType); } public SortedMap<K,V> headMap(K toKey) { return checkedSortedMap(sm.headMap(toKey), keyType, valueType); } public SortedMap<K,V> tailMap(K fromKey) { return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType); } } /** * Returns a dynamically typesafe view of the specified navigable map. * Any attempt to insert a mapping whose key or value have the wrong * type will result in an immediate {@link ClassCastException}. * Similarly, any attempt to modify the value currently associated with * a key will result in an immediate {@link ClassCastException}, * whether the modification is attempted directly through the map * itself, or through a {@link Map.Entry} instance obtained from the * map's {@link Map#entrySet() entry set} view. * * <p>Assuming a map contains no incorrectly typed keys or values * prior to the time a dynamically typesafe view is generated, and * that all subsequent access to the map takes place through the view * (or one of its collection views), it is <em>guaranteed</em> that the * map cannot contain an incorrectly typed key or value. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned map will be serializable if the specified map is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned map permits insertion of null keys or values * whenever the backing map does. * * @param <K> type of map keys * @param <V> type of map values * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold * @param valueType the type of value that {@code m} is permitted to hold * @return a dynamically typesafe view of the specified map * @since 1.8 */ public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m, Class<K> keyType, Class<V> valueType) { return new CheckedNavigableMap<>(m, keyType, valueType); } /** * @serial include */ static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V> implements NavigableMap<K,V>, Serializable { private static final long serialVersionUID = -4852462692372534096L; private final NavigableMap<K, V> nm; CheckedNavigableMap(NavigableMap<K, V> m, Class<K> keyType, Class<V> valueType) { super(m, keyType, valueType); nm = m; } public Comparator<? super K> comparator() { return nm.comparator(); } public K firstKey() { return nm.firstKey(); } public K lastKey() { return nm.lastKey(); } public Entry<K, V> lowerEntry(K key) { Entry<K,V> lower = nm.lowerEntry(key); return (null != lower) ? new CheckedEntrySet.CheckedEntry<>(lower, valueType) : null; } public K lowerKey(K key) { return nm.lowerKey(key); } public Entry<K, V> floorEntry(K key) { Entry<K,V> floor = nm.floorEntry(key); return (null != floor) ? new CheckedEntrySet.CheckedEntry<>(floor, valueType) : null; } public K floorKey(K key) { return nm.floorKey(key); } public Entry<K, V> ceilingEntry(K key) { Entry<K,V> ceiling = nm.ceilingEntry(key); return (null != ceiling) ? new CheckedEntrySet.CheckedEntry<>(ceiling, valueType) : null; } public K ceilingKey(K key) { return nm.ceilingKey(key); } public Entry<K, V> higherEntry(K key) { Entry<K,V> higher = nm.higherEntry(key); return (null != higher) ? new CheckedEntrySet.CheckedEntry<>(higher, valueType) : null; } public K higherKey(K key) { return nm.higherKey(key); } public Entry<K, V> firstEntry() { Entry<K,V> first = nm.firstEntry(); return (null != first) ? new CheckedEntrySet.CheckedEntry<>(first, valueType) : null; } public Entry<K, V> lastEntry() { Entry<K,V> last = nm.lastEntry(); return (null != last) ? new CheckedEntrySet.CheckedEntry<>(last, valueType) : null; } public Entry<K, V> pollFirstEntry() { Entry<K,V> entry = nm.pollFirstEntry(); return (null == entry) ? null : new CheckedEntrySet.CheckedEntry<>(entry, valueType); } public Entry<K, V> pollLastEntry() { Entry<K,V> entry = nm.pollLastEntry(); return (null == entry) ? null : new CheckedEntrySet.CheckedEntry<>(entry, valueType); } public NavigableMap<K, V> descendingMap() { return checkedNavigableMap(nm.descendingMap(), keyType, valueType); } public NavigableSet<K> keySet() { return navigableKeySet(); } public NavigableSet<K> navigableKeySet() { return checkedNavigableSet(nm.navigableKeySet(), keyType); } public NavigableSet<K> descendingKeySet() { return checkedNavigableSet(nm.descendingKeySet(), keyType); } @Override public NavigableMap<K,V> subMap(K fromKey, K toKey) { return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false), keyType, valueType); } @Override public NavigableMap<K,V> headMap(K toKey) { return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType); } @Override public NavigableMap<K,V> tailMap(K fromKey) { return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType); } public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType); } public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType); } public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType); } } // Empty collections /** * Returns an iterator that has no elements. More precisely, * * <ul> * <li>{@link Iterator#hasNext hasNext} always returns {@code * false}.</li> * <li>{@link Iterator#next next} always throws {@link * NoSuchElementException}.</li> * <li>{@link Iterator#remove remove} always throws {@link * IllegalStateException}.</li> * </ul> * * <p>Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * * @param <T> type of elements, if there were any, in the iterator * @return an empty iterator * @since 1.7 */ @SuppressWarnings("unchecked") public static <T> Iterator<T> emptyIterator() { return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR; } private static class EmptyIterator<E> implements Iterator<E> { static final EmptyIterator<Object> EMPTY_ITERATOR = new EmptyIterator<>(); public boolean hasNext() { return false; } public E next() { throw new NoSuchElementException(); } public void remove() { throw new IllegalStateException(); } @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); } } /** * Returns a list iterator that has no elements. More precisely, * * <ul> * <li>{@link Iterator#hasNext hasNext} and {@link * ListIterator#hasPrevious hasPrevious} always return {@code * false}.</li> * <li>{@link Iterator#next next} and {@link ListIterator#previous * previous} always throw {@link NoSuchElementException}.</li> * <li>{@link Iterator#remove remove} and {@link ListIterator#set * set} always throw {@link IllegalStateException}.</li> * <li>{@link ListIterator#add add} always throws {@link * UnsupportedOperationException}.</li> * <li>{@link ListIterator#nextIndex nextIndex} always returns * {@code 0}.</li> * <li>{@link ListIterator#previousIndex previousIndex} always * returns {@code -1}.</li> * </ul> * * <p>Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * * @param <T> type of elements, if there were any, in the iterator * @return an empty list iterator * @since 1.7 */ @SuppressWarnings("unchecked") public static <T> ListIterator<T> emptyListIterator() { return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR; } private static class EmptyListIterator<E> extends EmptyIterator<E> implements ListIterator<E> { static final EmptyListIterator<Object> EMPTY_ITERATOR = new EmptyListIterator<>(); public boolean hasPrevious() { return false; } public E previous() { throw new NoSuchElementException(); } public int nextIndex() { return 0; } public int previousIndex() { return -1; } public void set(E e) { throw new IllegalStateException(); } public void add(E e) { throw new UnsupportedOperationException(); } } /** * Returns an enumeration that has no elements. More precisely, * * <ul> * <li>{@link Enumeration#hasMoreElements hasMoreElements} always * returns {@code false}.</li> * <li> {@link Enumeration#nextElement nextElement} always throws * {@link NoSuchElementException}.</li> * </ul> * * <p>Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * * @param <T> the class of the objects in the enumeration * @return an empty enumeration * @since 1.7 */ @SuppressWarnings("unchecked") public static <T> Enumeration<T> emptyEnumeration() { return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION; } private static class EmptyEnumeration<E> implements Enumeration<E> { static final EmptyEnumeration<Object> EMPTY_ENUMERATION = new EmptyEnumeration<>(); public boolean hasMoreElements() { return false; } public E nextElement() { throw new NoSuchElementException(); } public Iterator<E> asIterator() { return emptyIterator(); } } /** * The empty set (immutable). This set is serializable. * * @see #emptySet() */ @SuppressWarnings("rawtypes") public static final Set EMPTY_SET = new EmptySet<>(); /** * Returns an empty set (immutable). This set is serializable. * Unlike the like-named field, this method is parameterized. * * <p>This example illustrates the type-safe way to obtain an empty set: * <pre> * Set&lt;String&gt; s = Collections.emptySet(); * </pre> * @implNote Implementations of this method need not create a separate * {@code Set} object for each call. Using this method is likely to have * comparable cost to using the like-named field. (Unlike this method, the * field does not provide type safety.) * * @param <T> the class of the objects in the set * @return the empty set * * @see #EMPTY_SET * @since 1.5 */ @SuppressWarnings("unchecked") public static final <T> Set<T> emptySet() { return (Set<T>) EMPTY_SET; } /** * @serial include */ private static class EmptySet<E> extends AbstractSet<E> implements Serializable { private static final long serialVersionUID = 1582296315990362920L; public Iterator<E> iterator() { return emptyIterator(); } public int size() {return 0;} public boolean isEmpty() {return true;} public void clear() {} public boolean contains(Object obj) {return false;} public boolean containsAll(Collection<?> c) { return c.isEmpty(); } public Object[] toArray() { return new Object[0]; } public <T> T[] toArray(T[] a) { if (a.length > 0) a[0] = null; return a; } // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); } @Override public boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); return false; } @Override public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); } // Preserves singleton property private Object readResolve() { return EMPTY_SET; } @Override public int hashCode() { return 0; } } /** * Returns an empty sorted set (immutable). This set is serializable. * * <p>This example illustrates the type-safe way to obtain an empty * sorted set: * <pre> {@code * SortedSet<String> s = Collections.emptySortedSet(); * }</pre> * * @implNote Implementations of this method need not create a separate * {@code SortedSet} object for each call. * * @param <E> type of elements, if there were any, in the set * @return the empty sorted set * @since 1.8 */ @SuppressWarnings("unchecked") public static <E> SortedSet<E> emptySortedSet() { return (SortedSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET; } /** * Returns an empty navigable set (immutable). This set is serializable. * * <p>This example illustrates the type-safe way to obtain an empty * navigable set: * <pre> {@code * NavigableSet<String> s = Collections.emptyNavigableSet(); * }</pre> * * @implNote Implementations of this method need not * create a separate {@code NavigableSet} object for each call. * * @param <E> type of elements, if there were any, in the set * @return the empty navigable set * @since 1.8 */ @SuppressWarnings("unchecked") public static <E> NavigableSet<E> emptyNavigableSet() { return (NavigableSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET; } /** * The empty list (immutable). This list is serializable. * * @see #emptyList() */ @SuppressWarnings("rawtypes") public static final List EMPTY_LIST = new EmptyList<>(); /** * Returns an empty list (immutable). This list is serializable. * * <p>This example illustrates the type-safe way to obtain an empty list: * <pre> * List&lt;String&gt; s = Collections.emptyList(); * </pre> * * @implNote * Implementations of this method need not create a separate {@code List} * object for each call. Using this method is likely to have comparable * cost to using the like-named field. (Unlike this method, the field does * not provide type safety.) * * @param <T> type of elements, if there were any, in the list * @return an empty immutable list * * @see #EMPTY_LIST * @since 1.5 */ @SuppressWarnings("unchecked") public static final <T> List<T> emptyList() { return (List<T>) EMPTY_LIST; } /** * @serial include */ private static class EmptyList<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 8842843931221139166L; public Iterator<E> iterator() { return emptyIterator(); } public ListIterator<E> listIterator() { return emptyListIterator(); } public int size() {return 0;} public boolean isEmpty() {return true;} public void clear() {} public boolean contains(Object obj) {return false;} public boolean containsAll(Collection<?> c) { return c.isEmpty(); } public Object[] toArray() { return new Object[0]; } public <T> T[] toArray(T[] a) { if (a.length > 0) a[0] = null; return a; } public E get(int index) { throw new IndexOutOfBoundsException("Index: "+index); } public boolean equals(Object o) { return (o instanceof List) && ((List<?>)o).isEmpty(); } public int hashCode() { return 1; } @Override public boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); return false; } @Override public void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); } @Override public void sort(Comparator<? super E> c) { } // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); } @Override public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); } // Preserves singleton property private Object readResolve() { return EMPTY_LIST; } } /** * The empty map (immutable). This map is serializable. * * @see #emptyMap() * @since 1.3 */ @SuppressWarnings("rawtypes") public static final Map EMPTY_MAP = new EmptyMap<>(); /** * Returns an empty map (immutable). This map is serializable. * * <p>This example illustrates the type-safe way to obtain an empty map: * <pre> * Map&lt;String, Date&gt; s = Collections.emptyMap(); * </pre> * @implNote Implementations of this method need not create a separate * {@code Map} object for each call. Using this method is likely to have * comparable cost to using the like-named field. (Unlike this method, the * field does not provide type safety.) * * @param <K> the class of the map keys * @param <V> the class of the map values * @return an empty map * @see #EMPTY_MAP * @since 1.5 */ @SuppressWarnings("unchecked") public static final <K,V> Map<K,V> emptyMap() { return (Map<K,V>) EMPTY_MAP; } /** * Returns an empty sorted map (immutable). This map is serializable. * * <p>This example illustrates the type-safe way to obtain an empty map: * <pre> {@code * SortedMap<String, Date> s = Collections.emptySortedMap(); * }</pre> * * @implNote Implementations of this method need not create a separate * {@code SortedMap} object for each call. * * @param <K> the class of the map keys * @param <V> the class of the map values * @return an empty sorted map * @since 1.8 */ @SuppressWarnings("unchecked") public static final <K,V> SortedMap<K,V> emptySortedMap() { return (SortedMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP; } /** * Returns an empty navigable map (immutable). This map is serializable. * * <p>This example illustrates the type-safe way to obtain an empty map: * <pre> {@code * NavigableMap<String, Date> s = Collections.emptyNavigableMap(); * }</pre> * * @implNote Implementations of this method need not create a separate * {@code NavigableMap} object for each call. * * @param <K> the class of the map keys * @param <V> the class of the map values * @return an empty navigable map * @since 1.8 */ @SuppressWarnings("unchecked") public static final <K,V> NavigableMap<K,V> emptyNavigableMap() { return (NavigableMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP; } /** * @serial include */ private static class EmptyMap<K,V> extends AbstractMap<K,V> implements Serializable { private static final long serialVersionUID = 6428348081105594320L; public int size() {return 0;} public boolean isEmpty() {return true;} public void clear() {} public boolean containsKey(Object key) {return false;} public boolean containsValue(Object value) {return false;} public V get(Object key) {return null;} public Set<K> keySet() {return emptySet();} public Collection<V> values() {return emptySet();} public Set<Entry<K,V>> entrySet() {return emptySet();} public boolean equals(Object o) { return (o instanceof Map) && ((Map<?,?>)o).isEmpty(); } public int hashCode() {return 0;} // Override default methods in Map @Override @SuppressWarnings("unchecked") public V getOrDefault(Object k, V defaultValue) { return defaultValue; } @Override public void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { Objects.requireNonNull(function); } @Override public V putIfAbsent(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException(); } @Override public V replace(K key, V value) { throw new UnsupportedOperationException(); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException(); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } // Preserves singleton property private Object readResolve() { return EMPTY_MAP; } } // Singleton collections /** * Returns an immutable set containing only the specified object. * The returned set is serializable. * * @param <T> the class of the objects in the set * @param o the sole object to be stored in the returned set. * @return an immutable set containing only the specified object. */ public static <T> Set<T> singleton(T o) { return new SingletonSet<>(o); } static <E> Iterator<E> singletonIterator(final E e) { return new Iterator<E>() { private boolean hasNext = true; public boolean hasNext() { return hasNext; } public E next() { if (hasNext) { hasNext = false; return e; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); if (hasNext) { hasNext = false; action.accept(e); } } }; } /** * Creates a {@code Spliterator} with only the specified element * * @param <T> Type of elements * @return A singleton {@code Spliterator} */ static <T> Spliterator<T> singletonSpliterator(final T element) { return new Spliterator<T>() { long est = 1; @Override public Spliterator<T> trySplit() { return null; } @Override public boolean tryAdvance(Consumer<? super T> consumer) { Objects.requireNonNull(consumer); if (est > 0) { est--; consumer.accept(element); return true; } return false; } @Override public void forEachRemaining(Consumer<? super T> consumer) { tryAdvance(consumer); } @Override public long estimateSize() { return est; } @Override public int characteristics() { int value = (element != null) ? Spliterator.NONNULL : 0; return value | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE | Spliterator.DISTINCT | Spliterator.ORDERED; } }; } /** * @serial include */ private static class SingletonSet<E> extends AbstractSet<E> implements Serializable { private static final long serialVersionUID = 3193687207550431679L; private final E element; SingletonSet(E e) {element = e;} public Iterator<E> iterator() { return singletonIterator(element); } public int size() {return 1;} public boolean contains(Object o) {return eq(o, element);} // Override default methods for Collection @Override public void forEach(Consumer<? super E> action) { action.accept(element); } @Override public Spliterator<E> spliterator() { return singletonSpliterator(element); } @Override public boolean removeIf(Predicate<? super E> filter) { throw new UnsupportedOperationException(); } @Override public int hashCode() { return Objects.hashCode(element); } } /** * Returns an immutable list containing only the specified object. * The returned list is serializable. * * @param <T> the class of the objects in the list * @param o the sole object to be stored in the returned list. * @return an immutable list containing only the specified object. * @since 1.3 */ public static <T> List<T> singletonList(T o) { return new SingletonList<>(o); } /** * @serial include */ private static class SingletonList<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 3093736618740652951L; private final E element; SingletonList(E obj) {element = obj;} public Iterator<E> iterator() { return singletonIterator(element); } public int size() {return 1;} public boolean contains(Object obj) {return eq(obj, element);} public E get(int index) { if (index != 0) throw new IndexOutOfBoundsException("Index: "+index+", Size: 1"); return element; } // Override default methods for Collection @Override public void forEach(Consumer<? super E> action) { action.accept(element); } @Override public boolean removeIf(Predicate<? super E> filter) { throw new UnsupportedOperationException(); } @Override public void replaceAll(UnaryOperator<E> operator) { throw new UnsupportedOperationException(); } @Override public void sort(Comparator<? super E> c) { } @Override public Spliterator<E> spliterator() { return singletonSpliterator(element); } @Override public int hashCode() { return 31 + Objects.hashCode(element); } } /** * Returns an immutable map, mapping only the specified key to the * specified value. The returned map is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param key the sole key to be stored in the returned map. * @param value the value to which the returned map maps {@code key}. * @return an immutable map containing only the specified key-value * mapping. * @since 1.3 */ public static <K,V> Map<K,V> singletonMap(K key, V value) { return new SingletonMap<>(key, value); } /** * @serial include */ private static class SingletonMap<K,V> extends AbstractMap<K,V> implements Serializable { private static final long serialVersionUID = -6979724477215052911L; private final K k; private final V v; SingletonMap(K key, V value) { k = key; v = value; } public int size() {return 1;} public boolean isEmpty() {return false;} public boolean containsKey(Object key) {return eq(key, k);} public boolean containsValue(Object value) {return eq(value, v);} public V get(Object key) {return (eq(key, k) ? v : null);} private transient Set<K> keySet; private transient Set<Entry<K,V>> entrySet; private transient Collection<V> values; public Set<K> keySet() { if (keySet==null) keySet = singleton(k); return keySet; } public Set<Entry<K,V>> entrySet() { if (entrySet==null) entrySet = Collections.<Entry<K,V>>singleton( new SimpleImmutableEntry<>(k, v)); return entrySet; } public Collection<V> values() { if (values==null) values = singleton(v); return values; } // Override default methods in Map @Override public V getOrDefault(Object key, V defaultValue) { return eq(key, k) ? v : defaultValue; } @Override public void forEach(BiConsumer<? super K, ? super V> action) { action.accept(k, v); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { throw new UnsupportedOperationException(); } @Override public V putIfAbsent(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException(); } @Override public V replace(K key, V value) { throw new UnsupportedOperationException(); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException(); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public int hashCode() { return Objects.hashCode(k) ^ Objects.hashCode(v); } } // Miscellaneous /** * Returns an immutable list consisting of {@code n} copies of the * specified object. The newly allocated data object is tiny (it contains * a single reference to the data object). This method is useful in * combination with the {@code List.addAll} method to grow lists. * The returned list is serializable. * * @param <T> the class of the object to copy and of the objects * in the returned list. * @param n the number of elements in the returned list. * @param o the element to appear repeatedly in the returned list. * @return an immutable list consisting of {@code n} copies of the * specified object. * @throws IllegalArgumentException if {@code n < 0} * @see List#addAll(Collection) * @see List#addAll(int, Collection) */ public static <T> List<T> nCopies(int n, T o) { if (n < 0) throw new IllegalArgumentException("List length = " + n); return new CopiesList<>(n, o); } /** * @serial include */ private static class CopiesList<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 2739099268398711800L; final int n; final E element; CopiesList(int n, E e) { assert n >= 0; this.n = n; element = e; } public int size() { return n; } public boolean contains(Object obj) { return n != 0 && eq(obj, element); } public int indexOf(Object o) { return contains(o) ? 0 : -1; } public int lastIndexOf(Object o) { return contains(o) ? n - 1 : -1; } public E get(int index) { if (index < 0 || index >= n) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+n); return element; } public Object[] toArray() { final Object[] a = new Object[n]; if (element != null) Arrays.fill(a, 0, n, element); return a; } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { final int n = this.n; if (a.length < n) { a = (T[]) Array .newInstance(a.getClass().getComponentType(), n); if (element != null) Arrays.fill(a, 0, n, element); } else { Arrays.fill(a, 0, n, element); if (a.length > n) a[n] = null; } return a; } public List<E> subList(int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > n) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); return new CopiesList<>(toIndex - fromIndex, element); } @Override public int hashCode() { if (n == 0) return 1; // hashCode of n repeating elements is 31^n + elementHash * Sum(31^k, k = 0..n-1) // this implementation completes in O(log(n)) steps taking advantage of // 31^(2*n) = (31^n)^2 and Sum(31^k, k = 0..(2*n-1)) = Sum(31^k, k = 0..n-1) * (31^n + 1) int pow = 31; int sum = 1; for (int i = Integer.numberOfLeadingZeros(n) + 1; i < Integer.SIZE; i++) { sum *= pow + 1; pow *= pow; if ((n << i) < 0) { pow *= 31; sum = sum * 31 + 1; } } return pow + sum * (element == null ? 0 : element.hashCode()); } @Override public boolean equals(Object o) { if (o == this) return true; if (o instanceof CopiesList) { CopiesList<?> other = (CopiesList<?>) o; return n == other.n && (n == 0 || eq(element, other.element)); } if (!(o instanceof List)) return false; int remaining = n; E e = element; Iterator<?> itr = ((List<?>) o).iterator(); if (e == null) { while (itr.hasNext() && remaining-- > 0) { if (itr.next() != null) return false; } } else { while (itr.hasNext() && remaining-- > 0) { if (!e.equals(itr.next())) return false; } } return remaining == 0 && !itr.hasNext(); } // Override default methods in Collection @Override public Stream<E> stream() { return IntStream.range(0, n).mapToObj(i -> element); } @Override public Stream<E> parallelStream() { return IntStream.range(0, n).parallel().mapToObj(i -> element); } @Override public Spliterator<E> spliterator() { return stream().spliterator(); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); SharedSecrets.getJavaObjectInputStreamAccess().checkArray(ois, Object[].class, n); } } /** * Returns a comparator that imposes the reverse of the <em>natural * ordering</em> on a collection of objects that implement the * {@code Comparable} interface. (The natural ordering is the ordering * imposed by the objects' own {@code compareTo} method.) This enables a * simple idiom for sorting (or maintaining) collections (or arrays) of * objects that implement the {@code Comparable} interface in * reverse-natural-order. For example, suppose {@code a} is an array of * strings. Then: <pre> * Arrays.sort(a, Collections.reverseOrder()); * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p> * * The returned comparator is serializable. * * @param <T> the class of the objects compared by the comparator * @return A comparator that imposes the reverse of the <i>natural * ordering</i> on a collection of objects that implement * the {@code Comparable} interface. * @see Comparable */ @SuppressWarnings("unchecked") public static <T> Comparator<T> reverseOrder() { return (Comparator<T>) ReverseComparator.REVERSE_ORDER; } /** * @serial include */ private static class ReverseComparator implements Comparator<Comparable<Object>>, Serializable { private static final long serialVersionUID = 7207038068494060240L; static final ReverseComparator REVERSE_ORDER = new ReverseComparator(); public int compare(Comparable<Object> c1, Comparable<Object> c2) { return c2.compareTo(c1); } private Object readResolve() { return Collections.reverseOrder(); } @Override public Comparator<Comparable<Object>> reversed() { return Comparator.naturalOrder(); } } /** * Returns a comparator that imposes the reverse ordering of the specified * comparator. If the specified comparator is {@code null}, this method is * equivalent to {@link #reverseOrder()} (in other words, it returns a * comparator that imposes the reverse of the <em>natural ordering</em> on * a collection of objects that implement the Comparable interface). * * <p>The returned comparator is serializable (assuming the specified * comparator is also serializable or {@code null}). * * @param <T> the class of the objects compared by the comparator * @param cmp a comparator who's ordering is to be reversed by the returned * comparator or {@code null} * @return A comparator that imposes the reverse ordering of the * specified comparator. * @since 1.5 */ @SuppressWarnings("unchecked") public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) { if (cmp == null) { return (Comparator<T>) ReverseComparator.REVERSE_ORDER; } else if (cmp == ReverseComparator.REVERSE_ORDER) { return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE; } else if (cmp == Comparators.NaturalOrderComparator.INSTANCE) { return (Comparator<T>) ReverseComparator.REVERSE_ORDER; } else if (cmp instanceof ReverseComparator2) { return ((ReverseComparator2<T>) cmp).cmp; } else { return new ReverseComparator2<>(cmp); } } /** * @serial include */ private static class ReverseComparator2<T> implements Comparator<T>, Serializable { private static final long serialVersionUID = 4374092139857L; /** * The comparator specified in the static factory. This will never * be null, as the static factory returns a ReverseComparator * instance if its argument is null. * * @serial */ final Comparator<T> cmp; ReverseComparator2(Comparator<T> cmp) { assert cmp != null; this.cmp = cmp; } public int compare(T t1, T t2) { return cmp.compare(t2, t1); } public boolean equals(Object o) { return (o == this) || (o instanceof ReverseComparator2 && cmp.equals(((ReverseComparator2)o).cmp)); } public int hashCode() { return cmp.hashCode() ^ Integer.MIN_VALUE; } @Override public Comparator<T> reversed() { return cmp; } } /** * Returns an enumeration over the specified collection. This provides * interoperability with legacy APIs that require an enumeration * as input. * * <p>The iterator returned from a call to {@link Enumeration#asIterator()} * does not support removal of elements from the specified collection. This * is necessary to avoid unintentionally increasing the capabilities of the * returned enumeration. * * @param <T> the class of the objects in the collection * @param c the collection for which an enumeration is to be returned. * @return an enumeration over the specified collection. * @see Enumeration */ public static <T> Enumeration<T> enumeration(final Collection<T> c) { return new Enumeration<T>() { private final Iterator<T> i = c.iterator(); public boolean hasMoreElements() { return i.hasNext(); } public T nextElement() { return i.next(); } }; } /** * Returns an array list containing the elements returned by the * specified enumeration in the order they are returned by the * enumeration. This method provides interoperability between * legacy APIs that return enumerations and new APIs that require * collections. * * @param <T> the class of the objects returned by the enumeration * @param e enumeration providing elements for the returned * array list * @return an array list containing the elements returned * by the specified enumeration. * @since 1.4 * @see Enumeration * @see ArrayList */ public static <T> ArrayList<T> list(Enumeration<T> e) { ArrayList<T> l = new ArrayList<>(); while (e.hasMoreElements()) l.add(e.nextElement()); return l; } /** * Returns true if the specified arguments are equal, or both null. * * NB: Do not replace with Object.equals until JDK-8015417 is resolved. */ static boolean eq(Object o1, Object o2) { return o1==null ? o2==null : o1.equals(o2); } /** * Returns the number of elements in the specified collection equal to the * specified object. More formally, returns the number of elements * {@code e} in the collection such that * {@code Objects.equals(o, e)}. * * @param c the collection in which to determine the frequency * of {@code o} * @param o the object whose frequency is to be determined * @return the number of elements in {@code c} equal to {@code o} * @throws NullPointerException if {@code c} is null * @since 1.5 */ public static int frequency(Collection<?> c, Object o) { int result = 0; if (o == null) { for (Object e : c) if (e == null) result++; } else { for (Object e : c) if (o.equals(e)) result++; } return result; } /** * Returns {@code true} if the two specified collections have no * elements in common. * * <p>Care must be exercised if this method is used on collections that * do not comply with the general contract for {@code Collection}. * Implementations may elect to iterate over either collection and test * for containment in the other collection (or to perform any equivalent * computation). If either collection uses a nonstandard equality test * (as does a {@link SortedSet} whose ordering is not <em>compatible with * equals</em>, or the key set of an {@link IdentityHashMap}), both * collections must use the same nonstandard equality test, or the * result of this method is undefined. * * <p>Care must also be exercised when using collections that have * restrictions on the elements that they may contain. Collection * implementations are allowed to throw exceptions for any operation * involving elements they deem ineligible. For absolute safety the * specified collections should contain only elements which are * eligible elements for both collections. * * <p>Note that it is permissible to pass the same collection in both * parameters, in which case the method will return {@code true} if and * only if the collection is empty. * * @param c1 a collection * @param c2 a collection * @return {@code true} if the two specified collections have no * elements in common. * @throws NullPointerException if either collection is {@code null}. * @throws NullPointerException if one collection contains a {@code null} * element and {@code null} is not an eligible element for the other collection. * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws ClassCastException if one collection contains an element that is * of a type which is ineligible for the other collection. * (<a href="Collection.html#optional-restrictions">optional</a>) * @since 1.5 */ public static boolean disjoint(Collection<?> c1, Collection<?> c2) { // The collection to be used for contains(). Preference is given to // the collection who's contains() has lower O() complexity. Collection<?> contains = c2; // The collection to be iterated. If the collections' contains() impl // are of different O() complexity, the collection with slower // contains() will be used for iteration. For collections who's // contains() are of the same complexity then best performance is // achieved by iterating the smaller collection. Collection<?> iterate = c1; // Performance optimization cases. The heuristics: // 1. Generally iterate over c1. // 2. If c1 is a Set then iterate over c2. // 3. If either collection is empty then result is always true. // 4. Iterate over the smaller Collection. if (c1 instanceof Set) { // Use c1 for contains as a Set's contains() is expected to perform // better than O(N/2) iterate = c2; contains = c1; } else if (!(c2 instanceof Set)) { // Both are mere Collections. Iterate over smaller collection. // Example: If c1 contains 3 elements and c2 contains 50 elements and // assuming contains() requires ceiling(N/2) comparisons then // checking for all c1 elements in c2 would require 75 comparisons // (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring // 100 comparisons (50 * ceiling(3/2)). int c1size = c1.size(); int c2size = c2.size(); if (c1size == 0 || c2size == 0) { // At least one collection is empty. Nothing will match. return true; } if (c1size > c2size) { iterate = c2; contains = c1; } } for (Object e : iterate) { if (contains.contains(e)) { // Found a common element. Collections are not disjoint. return false; } } // No common elements were found. return true; } /** * Adds all of the specified elements to the specified collection. * Elements to be added may be specified individually or as an array. * The behavior of this convenience method is identical to that of * {@code c.addAll(Arrays.asList(elements))}, but this method is likely * to run significantly faster under most implementations. * * <p>When elements are specified individually, this method provides a * convenient way to add a few elements to an existing collection: * <pre> * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon"); * </pre> * * @param <T> the class of the elements to add and of the collection * @param c the collection into which {@code elements} are to be inserted * @param elements the elements to insert into {@code c} * @return {@code true} if the collection changed as a result of the call * @throws UnsupportedOperationException if {@code c} does not support * the {@code add} operation * @throws NullPointerException if {@code elements} contains one or more * null values and {@code c} does not permit null elements, or * if {@code c} or {@code elements} are {@code null} * @throws IllegalArgumentException if some property of a value in * {@code elements} prevents it from being added to {@code c} * @see Collection#addAll(Collection) * @since 1.5 */ @SafeVarargs public static <T> boolean addAll(Collection<? super T> c, T... elements) { boolean result = false; for (T element : elements) result |= c.add(element); return result; } /** * Returns a set backed by the specified map. The resulting set displays * the same ordering, concurrency, and performance characteristics as the * backing map. In essence, this factory method provides a {@link Set} * implementation corresponding to any {@link Map} implementation. There * is no need to use this method on a {@link Map} implementation that * already has a corresponding {@link Set} implementation (such as {@link * HashMap} or {@link TreeMap}). * * <p>Each method invocation on the set returned by this method results in * exactly one method invocation on the backing map or its {@code keySet} * view, with one exception. The {@code addAll} method is implemented * as a sequence of {@code put} invocations on the backing map. * * <p>The specified map must be empty at the time this method is invoked, * and should not be accessed directly after this method returns. These * conditions are ensured if the map is created empty, passed directly * to this method, and no reference to the map is retained, as illustrated * in the following code fragment: * <pre> * Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap( * new WeakHashMap&lt;Object, Boolean&gt;()); * </pre> * * @param <E> the class of the map keys and of the objects in the * returned set * @param map the backing map * @return the set backed by the map * @throws IllegalArgumentException if {@code map} is not empty * @since 1.6 */ public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) { return new SetFromMap<>(map); } /** * @serial include */ private static class SetFromMap<E> extends AbstractSet<E> implements Set<E>, Serializable { private final Map<E, Boolean> m; // The backing map private transient Set<E> s; // Its keySet SetFromMap(Map<E, Boolean> map) { if (!map.isEmpty()) throw new IllegalArgumentException("Map is non-empty"); m = map; s = map.keySet(); } public void clear() { m.clear(); } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean contains(Object o) { return m.containsKey(o); } public boolean remove(Object o) { return m.remove(o) != null; } public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; } public Iterator<E> iterator() { return s.iterator(); } public Object[] toArray() { return s.toArray(); } public <T> T[] toArray(T[] a) { return s.toArray(a); } public String toString() { return s.toString(); } public int hashCode() { return s.hashCode(); } public boolean equals(Object o) { return o == this || s.equals(o); } public boolean containsAll(Collection<?> c) {return s.containsAll(c);} public boolean removeAll(Collection<?> c) {return s.removeAll(c);} public boolean retainAll(Collection<?> c) {return s.retainAll(c);} // addAll is the only inherited implementation // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) { s.forEach(action); } @Override public boolean removeIf(Predicate<? super E> filter) { return s.removeIf(filter); } @Override public Spliterator<E> spliterator() {return s.spliterator();} @Override public Stream<E> stream() {return s.stream();} @Override public Stream<E> parallelStream() {return s.parallelStream();} private static final long serialVersionUID = 2454657854757543876L; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); s = m.keySet(); } } /** * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo) * {@link Queue}. Method {@code add} is mapped to {@code push}, * {@code remove} is mapped to {@code pop} and so on. This * view can be useful when you would like to use a method * requiring a {@code Queue} but you need Lifo ordering. * * <p>Each method invocation on the queue returned by this method * results in exactly one method invocation on the backing deque, with * one exception. The {@link Queue#addAll addAll} method is * implemented as a sequence of {@link Deque#addFirst addFirst} * invocations on the backing deque. * * @param <T> the class of the objects in the deque * @param deque the deque * @return the queue * @since 1.6 */ public static <T> Queue<T> asLifoQueue(Deque<T> deque) { return new AsLIFOQueue<>(Objects.requireNonNull(deque)); } /** * @serial include */ static class AsLIFOQueue<E> extends AbstractQueue<E> implements Queue<E>, Serializable { private static final long serialVersionUID = 1802017725587941708L; private final Deque<E> q; AsLIFOQueue(Deque<E> q) { this.q = q; } public boolean add(E e) { q.addFirst(e); return true; } public boolean offer(E e) { return q.offerFirst(e); } public E poll() { return q.pollFirst(); } public E remove() { return q.removeFirst(); } public E peek() { return q.peekFirst(); } public E element() { return q.getFirst(); } public void clear() { q.clear(); } public int size() { return q.size(); } public boolean isEmpty() { return q.isEmpty(); } public boolean contains(Object o) { return q.contains(o); } public boolean remove(Object o) { return q.remove(o); } public Iterator<E> iterator() { return q.iterator(); } public Object[] toArray() { return q.toArray(); } public <T> T[] toArray(T[] a) { return q.toArray(a); } public <T> T[] toArray(IntFunction<T[]> f) { return q.toArray(f); } public String toString() { return q.toString(); } public boolean containsAll(Collection<?> c) { return q.containsAll(c); } public boolean removeAll(Collection<?> c) { return q.removeAll(c); } public boolean retainAll(Collection<?> c) { return q.retainAll(c); } // We use inherited addAll; forwarding addAll would be wrong // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) {q.forEach(action);} @Override public boolean removeIf(Predicate<? super E> filter) { return q.removeIf(filter); } @Override public Spliterator<E> spliterator() {return q.spliterator();} @Override public Stream<E> stream() {return q.stream();} @Override public Stream<E> parallelStream() {return q.parallelStream();} } }
[ "BaronGui@paxsz.com" ]
BaronGui@paxsz.com
9a974735440adb9701d3bc6918b567c439fe563c
60f3386750a82dc3bb787ca599a80b5b5bd61964
/class11/Recap.java
beda0c7c27bbe154af6acce0f28f3db6cdc3c6fa
[]
no_license
hmusoev90/Java-withSyntax-
e97bad59da2ae2cba914019093cad8dacb2fc6b8
1811db89a576e42f2ebd1f9f5e34e415bd469443
refs/heads/master
2022-12-10T05:52:13.693205
2020-08-22T18:30:10
2020-08-22T18:30:10
286,250,350
0
0
null
null
null
null
UTF-8
Java
false
false
482
java
package com.syntax.class11; public class Recap { public static void main(String[] args) { int[] grades = new int[5]; int size = grades.length; System.out.println("Array size:" + size); grades[3] = 47; grades[2] = 94; grades[4] = 100; grades[0] = 70; grades[1] = 85; // What is the average of the class? int total = 0; for (int i = 0; i <= grades.length - 1; i++) { total += grades[i]; } System.out.println("Average:" + total / grades.length); } }
[ "hmusoev90" ]
hmusoev90
3eb898c029b0ee4bc1fd70d68d4a3fd9acdf98cb
c18ca0ee85f21ef5e9890db9bb70ab8bb114200a
/JAVA Prgramming/cam3/src/de/must/wuic/Inlay.java
cb6bbc89f127eed3bcac3f2abede7e81b6e08faa
[]
no_license
f1lm/MS-2014-Boise-State-University
a3032b8b9e13303cdb3b4cb0001eddfd0d1cbffe
9d87f14e48a5c51a8a3ebfb0e010a493faf70576
refs/heads/master
2020-04-15T15:17:48.031552
2015-03-18T01:37:30
2015-03-18T01:37:30
32,502,472
1
1
null
2015-03-19T05:19:57
2015-03-19T05:19:56
null
UTF-8
Java
false
false
3,445
java
/* * Copyright (c) 2004 Christoph Mueller. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY CHRISTOPH MUELLER ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CHRISTOPH MUELLER OR * HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package de.must.wuic; import java.awt.event.ActionListener; import javax.swing.JPanel; /** * Super class for all GUI sectors to be placed into ContainerFrames * @author Christoph Mueller */ public abstract class Inlay extends JPanel implements ActionListener { protected ContainerFrame ownerFrame; private String helpTopic; private String helpTarget; public Inlay(ContainerFrame ownerFrame) { this.ownerFrame = ownerFrame; } /** * Sets the component's context help. * @param helpTopic the context help's topic * @param helpTarget the context help's target */ public void setHelpContext(String helpTopic) { this.helpTopic = helpTopic; } /** * Sets the component's context help. * @param helpTopic the context help's topic * @param helpTarget the context help's target */ public void setHelpContext(String helpTopic, String helpTarget) { this.helpTopic = helpTopic; this.helpTarget = helpTarget; } /** * Returns the topic of the component's help context * @return the topic of the component's help context */ public String getHelpTopic() { return helpTopic; } /** * Returns the target of the component's help context * @return the target of the component's help context */ public String getHelpTarget() { return helpTarget; } /** * Returns a text in the corresponding language according to the locale * specific resource bundle of the package. * @param resourceKey the key of the resource to retrieve * @return the resource */ protected String getTranslation(String resourceKey) { return ownerFrame.getTranslation(resourceKey); } /** * Sets the message to be read by the user, which is presented in the status * label in this context. * @param message the message for the user */ protected void setMessage(String message) { ownerFrame.setMessage(message); } /** * Sets the message to be read by the user, it is not reseted by * generalActionEnding when action completed. Thus, the user is able to notify * the message without pressing a confirmation button. * @param messageToKeep the message for the user */ protected void setMessageToKeep(String messageToKeep) { ownerFrame.setMessageToKeep(messageToKeep); } }
[ "milsonmun@yahoo.com" ]
milsonmun@yahoo.com
b9141d0ada8341f441c15f3c5a5e69e993389de5
08093efebfe14bd0dccde51ad1f32378ba66edb7
/proyecto1/BarnesNobleDB.java
4a87589499760aa25f08b26e45fb8fbe7f299972
[]
no_license
Davidgarciacornejo01/sistemas-basados-conocimiento-DavidGarcia
414de0384f722a15feff570dc85ccd7c756e1655
debfdae884a4ba8537332b3b48efb1bbddd77c94
refs/heads/main
2023-06-11T20:56:01.855778
2021-06-20T03:29:32
2021-06-20T03:29:32
368,671,875
0
0
null
null
null
null
UTF-8
Java
false
false
7,588
java
package examples.proyecto1; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.*; public class BarnesNobleDB { // Librería de MySQL public String driver = "com.mysql.jdbc.Driver"; // Nombre de la base de datos public String database = "barnes_noble"; // Host public String hostname = "localhost"; // Puerto public String port = "3306"; // Ruta de nuestra base de datos (desactivamos el uso de SSL con "?useSSL=false") public String url = "jdbc:mysql://" + hostname + ":" + port + "/" + database + "?useSSL=false"; // Nombre de usuario public String username = "root"; // Clave de usuario public String password = ""; public Connection conexion = null; public BarnesNobleDB(){ conectarMySQL(); } public Connection conectarMySQL() { try { Class.forName(driver); conexion = DriverManager.getConnection(url, username, password); statement = conexion.createStatement(); //System.out.println("conectado"); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); System.out.println("no se conecto"); } return conexion; } Statement statement; public void setProductos(String nombre, String tipo, String precio,String elementosDisponibles) { try { statement.executeUpdate("insert into productos(nombre,tipo,precio,elementos_disponibles) values('"+nombre+"','"+tipo+"',"+precio+","+elementosDisponibles+")"); System.out.println("insertado"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getProdutos() { PreparedStatement preparedStatement; ResultSet resultSet; String sql="select * from productos"; String cadena=""; try { preparedStatement=conexion.prepareStatement(sql); resultSet=preparedStatement.executeQuery(); //Object[][] object=new Object[100][5]; //int contador=0; while(resultSet.next()) { /* System.out.println( "nombre: "+resultSet.getObject(1)+" tipo: "+ resultSet.getObject(2)+" precio: "+ resultSet.getObject(3)+" elementos disponibles: "+ resultSet.getObject(4));*/ cadena=cadena +":"+ resultSet.getObject(1) +","+ resultSet.getObject(2) +","+ resultSet.getObject(3) +","+ resultSet.getObject(4)+","+resultSet.getObject(5); //Administrador administrador=new Administrador(); //administrador.pasarDatos(object); } return cadena; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public void updateProductos(int elementos_disponibles,String id, String tipo) { try { statement.executeUpdate("update productos set elementos_disponibles="+elementos_disponibles+" where id_productos="+id+" and tipo='"+tipo+"'"); System.out.println("actualizado"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String[] buscarProducto(String nombre) { PreparedStatement preparedStatement; ResultSet resultSet; String sql="select * from productos where nombre='"+nombre+"'"; String[] array=new String[5]; try { preparedStatement=conexion.prepareStatement(sql); resultSet=preparedStatement.executeQuery(); while(resultSet.next()) { /* System.out.println( "id: "+resultSet.getObject(1)+" nombre: "+resultSet.getObject(2)+" tipo: "+ resultSet.getObject(3)+" precio: "+ resultSet.getObject(4)+" elementos disponibles: "+ resultSet.getObject(5));*/ array[0]=new String(); array[0] = resultSet.getObject(1).toString(); array[1]=new String(); array[1] = resultSet.getObject(2).toString(); array[2]=new String(); array[2] = resultSet.getObject(3).toString(); array[3]=new String(); array[3] = resultSet.getObject(4).toString(); array[4]=new String(); array[4] = resultSet.getObject(5).toString(); } return array; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public int dameContador(){ return contadorObjetos; } public void fijamosContador(int contador){ contadorObjetos=contador; } int contadorObjetos=0; public String[][] dameProductos(){ PreparedStatement preparedStatement; ResultSet resultSet; String sql="select * from productos"; String[][] matriz=new String[300][5]; int contador=0; try { preparedStatement=conexion.prepareStatement(sql); resultSet=preparedStatement.executeQuery(); while(resultSet.next()) { /* System.out.println( "id: "+resultSet.getObject(1)+" nombre: "+resultSet.getObject(2)+" tipo: "+ resultSet.getObject(3)+" precio: "+ resultSet.getObject(4)+" elementos disponibles: "+ resultSet.getObject(5));*/ matriz[contador][0]=new String(); matriz[contador][0] = resultSet.getObject(1).toString(); matriz[contador][1]=new String(); matriz[contador][1] = resultSet.getObject(2).toString(); matriz[contador][2]=new String(); matriz[contador][2] = resultSet.getObject(3).toString(); matriz[contador][3]=new String(); matriz[contador][3] = resultSet.getObject(4).toString(); matriz[contador][4]=new String(); matriz[contador++][4] = resultSet.getObject(5).toString(); } fijamosContador(contador); return matriz; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public void mostrarLista(){ PreparedStatement preparedStatement; ResultSet resultSet; String sql="select * from productos"; try { preparedStatement=conexion.prepareStatement(sql); resultSet=preparedStatement.executeQuery(); while(resultSet.next()) { System.out.println( "id: "+resultSet.getObject(1)+" nombre: "+resultSet.getObject(2)+" tipo: "+ resultSet.getObject(3)+" precio: "+ resultSet.getObject(4)+" elementos disponibles: "+ resultSet.getObject(5)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
[ "david.garcia0835@alumnos.udg.mx" ]
david.garcia0835@alumnos.udg.mx
0436f6b5257b23d49ac529aa490b42c7586260f3
a66d5eb37789895ac8c5bd247c0b7d02387b5ffe
/restli-client-testutils/src/test/java/com/linkedin/restli/client/testutils/test/TestMockResponseBuilder.java
3ab2bb19b067db83b6140a46799865b75dd6b16c
[ "Apache-2.0" ]
permissive
pdeloulay/rest.li
a4c01aca74d0a4d828c92accf83642d904260ff5
14da8444a00bd1bc6dffa6e20a072a9a5bd59448
refs/heads/master
2021-01-14T18:40:43.642717
2014-04-25T23:04:53
2014-04-25T23:04:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,788
java
/* Copyright (c) 2014 LinkedIn Corp. 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.linkedin.restli.client.testutils.test; import com.linkedin.restli.client.Response; import com.linkedin.restli.client.RestLiResponseException; import com.linkedin.restli.client.testutils.MockResponseBuilder; import com.linkedin.restli.common.RestConstants; import com.linkedin.restli.examples.greetings.api.Greeting; import com.linkedin.restli.internal.common.AllProtocolVersions; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.easymock.EasyMock; import org.testng.Assert; import org.testng.annotations.Test; /** * @author kparikh */ public class TestMockResponseBuilder { @Test public void testBuild() { MockResponseBuilder<Greeting> mockResponseBuilder = new MockResponseBuilder<Greeting>(); Greeting greeting = new Greeting().setId(1L).setMessage("message"); Map<String, String> headers = Collections.singletonMap("foo", "bar"); RestLiResponseException restLiResponseException = EasyMock.createMock(RestLiResponseException.class); EasyMock.expect(restLiResponseException.getErrorSource()).andReturn("foo").once(); EasyMock.replay(restLiResponseException); // build a response object using all the setters. This response does not make sense logically but the goal here // is to test that the builder is working correctly. mockResponseBuilder .setEntity(greeting) .setHeaders(headers) .setId("1") .setStatus(200) .setRestLiResponseException(restLiResponseException); Response<Greeting> response = mockResponseBuilder.build(); // when we build the Response the ID is put into the headers Map<String, String> builtHeaders = new HashMap<String, String>(headers); builtHeaders.put(RestConstants.HEADER_ID, "1"); builtHeaders.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString()); Assert.assertEquals(response.getEntity(), greeting); Assert.assertEquals(response.getHeaders(), builtHeaders); Assert.assertEquals(response.getStatus(), 200); Assert.assertEquals(response.getId(), "1"); Assert.assertEquals(response.getError().getErrorSource(), "foo"); } }
[ "kparikh@linkedin.com" ]
kparikh@linkedin.com
15fc546f73b54d5332d832c79b7d6935700bf5dd
ab6a72d62499a444d04ed2e172760418e270d9e9
/final/gra2/Bot.java
f9b1bd79dc25df124b78154f38e62287a475be58
[]
no_license
olislawiec/igudab
09f7bab25446b78eecaab8f9cdc1d208db858544
adc7db764de56f4065ebad0cc508c8a417a3e457
refs/heads/master
2021-01-10T05:54:39.947595
2014-11-21T11:07:45
2014-11-21T11:07:45
48,026,594
0
0
null
null
null
null
UTF-8
Java
false
false
5,367
java
package gra2; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.DataInputStream; import java.io.IOException; import java.net.Socket; import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; import javax.script.ScriptException; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.text.JTextComponent; import javax.swing.JLabel; import java.io.PrintStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.StringReader; import java.net.UnknownHostException; public class Bot implements Runnable { // The client socket private static Socket clientSocket1 = null; // The output stream private static PrintStream os1 = null; // The input stream private static DataInputStream is1 = null; private static BufferedReader inputLine1 = null; public static String texter1 = ""; public static int intTexter1 = 0; public static String host1 = ""; public static int portNumber1 = 8969; public static boolean closed1 = false; public static BufferedReader send(String msgFromClientToServer) { try { StringReader sr = new StringReader(msgFromClientToServer); BufferedReader br = new BufferedReader(sr); os1.println(br.readLine()); System.out.println(br.readLine() + "_syso5_sender"); return br; } catch (Exception e) { System.out.println("send(String msgFromClientToServer): " + e); e.printStackTrace(); } return null; } public static void main(String[] args) { try { clientSocket1 = new Socket(host1, portNumber1); inputLine1 = new BufferedReader(new InputStreamReader(System.in)); os1 = new PrintStream(clientSocket1.getOutputStream()); // to: // klient->serwer is1 = new DataInputStream(clientSocket1.getInputStream());// to: // serwer->klient } catch (UnknownHostException e) { System.err.println("Don't know about host " + host1); } catch (IOException e) { System.err .println("Couldn't get I/O for the connection to the host " + host1); System.exit(-3); } /* * If everything has been initialized then we want to write some data to * the socket we have opened a connection to on the port portNumber. */ if (clientSocket1 != null && os1 != null && is1 != null) { try { /* Create a thread to read from the server. */ new Thread(new Bot()).start(); while (!isClosed()) { os1.println(inputLine1.readLine().trim()); System.out.println(inputLine1.readLine()); // send("D1,2"); // send("BC"); System.out.println("petla"); // System.out.println(inputLine.readLine().trim()+"_syso1"); } System.out.println("po petli"); /* * Close the output stream, close the input stream, close the * socket. */ os1.close(); is1.close(); clientSocket1.close(); } catch (IOException e) { System.err.println("IOException: " + e); } } } @Override public void run() { /* * Keep on reading from the socket till we receive "Bye" from the * server. Once we received that then we want to break. */ String responseLine1 = ""; try { while ((responseLine1 = is1.readLine()) != null) { System.out.println(responseLine1 + "_syso3"); if (responseLine1.startsWith("H") && responseLine1.length() > 4) { String[] sparePart = splited(withoutRegx(lineWithoutLetter(responseLine1))); /* * for(int i=0; i<=sparePart.length-1;i++) { * System.out.println(sparePart[i]); } */ send("D1,2"); if (responseLine1.startsWith("H")) { send("BC"); } // System.out.println(responseLine1 + "_syso2"); // ekranLabelSetter(responseLineWithoutLetter); } else { send("D3,4"); send("BC"); } if (responseLine1.indexOf("Q ") != -1) { break; } if (responseLine1.indexOf("Server too busy. Try later.") != (-2)) { setClosed(false); } if (responseLine1.startsWith("BA")) { System.out.println("_syso4_widacBA?"); } } setClosed(true); } catch (IOException e) { System.err.println("IOException: " + e); } } public static String toStr(int x) { return Integer.toString(x); } public static int toInt(String xs) { return Integer.parseInt(xs); } /* * public void ekranCardsDealer(String[] respo) { if (respo.length < 5 && * respo.length > 3) { card1.setText(respo[0]); card2.setText(respo[1]); * card3.setText(respo[2]); card4.setText(respo[3]); } } */ public String[] splited(String splitMe) { String[] respo; respo = splitMe.split(","); return respo; } public String withoutRegx(String splitMe) { String[] regX; regX = splitMe.split(";"); return regX[0]; } public String lineWithoutLetter(String res) { String responseLineWithoutLetter = ""; responseLineWithoutLetter = res.substring(1); return responseLineWithoutLetter; } private static boolean isClosed() { // TODO Auto-generated method stub return closed1; } private void setClosed(boolean b) { closed1 = true; } }
[ "andrzej2275@gmail.com" ]
andrzej2275@gmail.com
8937e4ecfbd7279bf4a4e4fbe086acc31e2f3cab
88b9ac0589e8f20a8889df43e050308553b6dd0c
/app/src/main/java/com/funlisten/service/net/ZYOkHttpNetManager.java
58328b339b8401dfd02e01370e0b2141ed8a79bf
[]
no_license
zhouyongyang122/funListening
2efda77e40ea38ae4ba073b06bf987bd288a3c2b
1521174eba0ee9991c3d766a17d143f90c709ab8
refs/heads/master
2021-01-01T04:08:49.491994
2017-11-02T03:55:23
2017-11-02T03:55:23
97,130,090
0
1
null
null
null
null
UTF-8
Java
false
false
4,606
java
package com.funlisten.service.net; import android.text.TextUtils; import com.funlisten.utils.ZYLog; import com.google.gson.Gson; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Created by ZY on 17/4/13. */ public class ZYOkHttpNetManager { private static ZYOkHttpNetManager instance; private OkHttpClient mOkHttpClient; private boolean isCancle; private ZYOkHttpNetManager() { mOkHttpClient = new OkHttpClient.Builder() .connectTimeout(3000, TimeUnit.MILLISECONDS) .build(); } public static ZYOkHttpNetManager getInstance() { if (instance == null) { instance = new ZYOkHttpNetManager(); } return instance; } public void reset() { isCancle = false; } public void requestGet(final Class classBean, String url, final OkHttpNetListener listener) { if (TextUtils.isEmpty(url) || listener == null) { return; } try { final Request request = new Request.Builder() .url(url) .get() .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { ZYLog.e(ZYOkHttpNetManager.class.getSimpleName(), "onFailure: " + e.getMessage()); if (listener != null && !isCancle) { listener.onFailure("网络异常,请重新尝试"); } } @Override public void onResponse(Call call, Response response) throws IOException { if (listener != null && !isCancle) { try { listener.onSuccess(new Gson().fromJson(response.body().toString(), classBean)); } catch (Exception e) { ZYLog.e(ZYOkHttpNetManager.class.getSimpleName(), "onResponse-error: " + e.getMessage()); listener.onFailure("网络异常,请重新尝试"); } } } }); } catch (Exception e) { } } public void requestPost(final Class classBean, String url, Map<String, String> params, final OkHttpNetListener listener) { if (TextUtils.isEmpty(url) || listener == null) { return; } try { FormBody.Builder bodyBuilder = new FormBody.Builder(); for (Map.Entry<String, String> entry : params.entrySet()) { if (entry.getValue() != null) { bodyBuilder.add(entry.getKey(), entry.getValue()); } } Request request = new Request.Builder() .url(url) .post(bodyBuilder.build()) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { ZYLog.e(ZYOkHttpNetManager.class.getSimpleName(), "onFailure: " + e.getMessage()); if (listener != null && !isCancle) { listener.onFailure("网络异常,请重新尝试"); } } @Override public void onResponse(Call call, Response response) throws IOException { if (listener != null && !isCancle) { try { String result = response.body().string(); listener.onSuccess(new Gson().fromJson(result, classBean)); } catch (Exception e) { ZYLog.e(ZYOkHttpNetManager.class.getSimpleName(), "onResponse-error: " + e.getMessage()); listener.onFailure("网络异常,请重新尝试"); } } } }); } catch (Exception e) { } } public void cancle() { isCancle = true; mOkHttpClient.dispatcher().cancelAll(); } public interface OkHttpNetListener<T> { void onFailure(String message); void onSuccess(T response); } }
[ "zhouyongyang122@gmail.com" ]
zhouyongyang122@gmail.com
fdf1a7e3b5aa5c5c2efd48a85a81e5f56bcf372c
1b0f4dee2b239eccb0dc62057712804bd9d0178b
/src/test/java/com/xx_dev/apn/proxy/test/TestRemoteRuleGen.java
abf33bbdb5c1d69a99f3cb6653affac01d9e0a4b
[]
no_license
luwenbin006/apn-proxy
bc8dc1bdcf903d64b557ef1953bcb8dfd7494f59
97f1bdbed7d723472210a81e96db9bd7084fd743
refs/heads/master
2020-12-25T14:07:44.450697
2016-02-25T08:21:36
2016-02-25T08:21:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,287
java
/* * Copyright (c) 2014 The APN-PROXY Project * * The APN-PROXY Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.xx_dev.apn.proxy.test; import org.junit.Test; import java.io.FileNotFoundException; import java.util.Scanner; /** * @author xmx * @version $Id: com.xx_dev.apn.proxy.test.TestRemoteRuleGen 2014-12-31 18:38 (xmx) Exp $ */ public class TestRemoteRuleGen { @Test public void test() throws FileNotFoundException { Scanner in = new Scanner(TestRemoteRuleGen.class.getResourceAsStream("/domains.txt"), "UTF-8"); while (in.hasNextLine()) { String line = in.nextLine(); System.err.println("\t\t\t<original-host>"+line+"</original-host>"); } in.close(); } }
[ "xmxsuperstar@gmail.com" ]
xmxsuperstar@gmail.com
df4328703f95c18a533821a0f53d1c60cbdc8272
169f4b4cb60dc918bf0d8b8db1a7efdf5d4ebc23
/java-client/src/main/java/co/elastic/clients/elasticsearch/watcher/QueryWatchesResponse.java
958efe3e652894e8b40472a93cb2684ece94ccbb
[ "Apache-2.0" ]
permissive
PyJava1984/elasticsearch-java
387d2212cc0784c06d1a8af0d284f4ee2b1cf9b4
5c7c24d9dd33de37e00ca183b32ec5cb17ea8b17
refs/heads/main
2023-08-28T17:35:38.220152
2021-10-18T19:21:23
2021-10-18T19:21:23
419,573,301
1
0
null
null
null
null
UTF-8
Java
false
false
5,460
java
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ //---------------------------------------------------- // THIS CODE IS GENERATED. MANUAL EDITS WILL BE LOST. //---------------------------------------------------- package co.elastic.clients.elasticsearch.watcher; import co.elastic.clients.json.DelegatingDeserializer; import co.elastic.clients.json.JsonpDeserializable; import co.elastic.clients.json.JsonpDeserializer; import co.elastic.clients.json.JsonpMapper; import co.elastic.clients.json.JsonpSerializable; import co.elastic.clients.json.ObjectBuilderDeserializer; import co.elastic.clients.json.ObjectDeserializer; import co.elastic.clients.util.ModelTypeHelper; import co.elastic.clients.util.ObjectBuilder; import jakarta.json.stream.JsonGenerator; import java.lang.Integer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Function; import javax.annotation.Nullable; // typedef: watcher.query_watches.Response @JsonpDeserializable public final class QueryWatchesResponse implements JsonpSerializable { private final int count; private final List<QueryWatch> watches; // --------------------------------------------------------------------------------------------- public QueryWatchesResponse(Builder builder) { this.count = Objects.requireNonNull(builder.count, "count"); this.watches = ModelTypeHelper.unmodifiableNonNull(builder.watches, "watches"); } public QueryWatchesResponse(Function<Builder, Builder> fn) { this(fn.apply(new Builder())); } /** * Required - API name: {@code count} */ public int count() { return this.count; } /** * Required - API name: {@code watches} */ public List<QueryWatch> watches() { return this.watches; } /** * Serialize this object to JSON. */ public void serialize(JsonGenerator generator, JsonpMapper mapper) { generator.writeStartObject(); serializeInternal(generator, mapper); generator.writeEnd(); } protected void serializeInternal(JsonGenerator generator, JsonpMapper mapper) { generator.writeKey("count"); generator.write(this.count); generator.writeKey("watches"); generator.writeStartArray(); for (QueryWatch item0 : this.watches) { item0.serialize(generator, mapper); } generator.writeEnd(); } // --------------------------------------------------------------------------------------------- /** * Builder for {@link QueryWatchesResponse}. */ public static class Builder implements ObjectBuilder<QueryWatchesResponse> { private Integer count; private List<QueryWatch> watches; /** * Required - API name: {@code count} */ public Builder count(int value) { this.count = value; return this; } /** * Required - API name: {@code watches} */ public Builder watches(List<QueryWatch> value) { this.watches = value; return this; } /** * Required - API name: {@code watches} */ public Builder watches(QueryWatch... value) { this.watches = Arrays.asList(value); return this; } /** * Add a value to {@link #watches(List)}, creating the list if needed. */ public Builder addWatches(QueryWatch value) { if (this.watches == null) { this.watches = new ArrayList<>(); } this.watches.add(value); return this; } /** * Set {@link #watches(List)} to a singleton list. */ public Builder watches(Function<QueryWatch.Builder, ObjectBuilder<QueryWatch>> fn) { return this.watches(fn.apply(new QueryWatch.Builder()).build()); } /** * Add a value to {@link #watches(List)}, creating the list if needed. */ public Builder addWatches(Function<QueryWatch.Builder, ObjectBuilder<QueryWatch>> fn) { return this.addWatches(fn.apply(new QueryWatch.Builder()).build()); } /** * Builds a {@link QueryWatchesResponse}. * * @throws NullPointerException * if some of the required fields are null. */ public QueryWatchesResponse build() { return new QueryWatchesResponse(this); } } // --------------------------------------------------------------------------------------------- /** * Json deserializer for {@link QueryWatchesResponse} */ public static final JsonpDeserializer<QueryWatchesResponse> _DESERIALIZER = ObjectBuilderDeserializer .lazy(Builder::new, QueryWatchesResponse::setupQueryWatchesResponseDeserializer, Builder::build); protected static void setupQueryWatchesResponseDeserializer( DelegatingDeserializer<QueryWatchesResponse.Builder> op) { op.add(Builder::count, JsonpDeserializer.integerDeserializer(), "count"); op.add(Builder::watches, JsonpDeserializer.arrayDeserializer(QueryWatch._DESERIALIZER), "watches"); } }
[ "sylvain@elastic.co" ]
sylvain@elastic.co
b1f59cc71b4fd04f0322d0d8698cfe0ced7ec0bd
ff9e7ded0a566940aa7fab4f528d50b97cf84e66
/app/src/main/java/bj/vinylbrowser/utils/UtilsModule.java
2071055a3beacda17c3132835d34f64a2ff2d453
[ "MIT" ]
permissive
jbmlaird/DiscogsBrowser
e840a4b89de636d8f9b0ac875e7cc3a6f119fe79
23facb4e1ab156508e934ebc1fcd1d57b3255aba
refs/heads/master
2021-01-19T21:16:16.373854
2018-04-12T21:23:49
2018-04-12T21:23:49
82,479,889
24
2
null
2017-05-22T10:57:25
2017-02-19T18:25:27
Java
UTF-8
Java
false
false
875
java
package bj.vinylbrowser.utils; import bj.vinylbrowser.wrappers.DateUtilsWrapper; import bj.vinylbrowser.wrappers.SimpleDateFormatWrapper; import dagger.Module; import dagger.Provides; /** * Created by Josh Laird on 14/05/2017. */ @Module public class UtilsModule { @Provides protected ImageViewAnimator provideImageViewAnimator() { return new ImageViewAnimator(); } @Provides protected ArtistsBeautifier provideArtistsBeautifier() { return new ArtistsBeautifier(); } @Provides protected DiscogsScraper provideDiscogsScraper() { return new DiscogsScraper(); } @Provides protected DateFormatter provideDateFormatter(DateUtilsWrapper dateUtilsWrapper, SimpleDateFormatWrapper simpleDateFormatWrapper) { return new DateFormatter(dateUtilsWrapper, simpleDateFormatWrapper); } }
[ "jbmlaird@gmail.com" ]
jbmlaird@gmail.com
135ede5e4b2b48d23c1add825d13ccd1f854ecf6
eb97ee5d4f19d7bf028ae9a400642a8c644f8fe3
/tags/2011-12-23/seasar2-2.4.45/seasar2/s2-framework/src/main/java/org/seasar/framework/util/SerializeUtil.java
65e4e95b5a5ae6da2efbfc30686185427acf0e46
[ "Apache-2.0" ]
permissive
svn2github/s2container
54ca27cf0c1200a93e1cb88884eb8226a9be677d
625adc6c4e1396654a7297d00ec206c077a78696
refs/heads/master
2020-06-04T17:15:02.140847
2013-08-09T09:38:15
2013-08-09T09:38:15
10,850,644
0
1
null
null
null
null
UTF-8
Java
false
false
3,096
java
/* * Copyright 2004-2011 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.framework.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.seasar.framework.exception.ClassNotFoundRuntimeException; import org.seasar.framework.exception.IORuntimeException; /** * オブジェクトをシリアライズするためのユーティリティです。 * * @author higa * */ public class SerializeUtil { private static final int BYTE_ARRAY_SIZE = 8 * 1024; /** * インスタンスを構築します。 */ protected SerializeUtil() { } /** * オブジェクトをシリアライズできるかテストします。 * * @param o * @return * @throws IORuntimeException * @throws ClassNotFoundRuntimeException */ public static Object serialize(final Object o) throws IORuntimeException, ClassNotFoundRuntimeException { byte[] binary = fromObjectToBinary(o); return fromBinaryToObject(binary); } /** * オブジェクトをbyteの配列に変換します。 * * @param o * @return */ public static byte[] fromObjectToBinary(Object o) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream( BYTE_ARRAY_SIZE); ObjectOutputStream oos = new ObjectOutputStream(baos); try { oos.writeObject(o); } finally { oos.close(); } return baos.toByteArray(); } catch (IOException ex) { throw new IORuntimeException(ex); } } /** * byteの配列をオブジェクトに変換します。 * * @param binary * @return */ public static Object fromBinaryToObject(byte[] binary) { try { ByteArrayInputStream bais = new ByteArrayInputStream(binary); ObjectInputStream ois = new ObjectInputStream(bais); try { return ois.readObject(); } finally { ois.close(); } } catch (IOException ex) { throw new IORuntimeException(ex); } catch (ClassNotFoundException ex) { throw new ClassNotFoundRuntimeException(ex); } } }
[ "koichik@319488c0-e101-0410-93bc-b5e51f62721a" ]
koichik@319488c0-e101-0410-93bc-b5e51f62721a
5c8b186ed5df52801b76c942b32cf2a76ef9bcea
ca217730cff9435b03347587d61d2ef28b478f7e
/old/models/SCPModelRemoteDoorPC.java
883c4942637032a341b3c19eaa8e730728d9257d
[]
no_license
Ordinastie/SCPCraft
e8c4c78cc86ac0e7f364156058f35ce30adf059d
547a204bb14fc33adefb9926baca2f5188d89421
refs/heads/master
2023-07-18T19:50:59.231189
2014-03-21T23:59:54
2014-03-21T23:59:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,421
java
package SCPCraft.models; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import SCPCraft.mod_Others; public class SCPModelRemoteDoorPC extends ModelBase { //fields ModelRenderer Shape3; ModelRenderer Shape1; ModelRenderer Shape2; public SCPModelRemoteDoorPC() { textureWidth = 64; textureHeight = 64; Shape3 = new ModelRenderer(this, 0, 0); Shape3.addBox(0F, 0F, 0F, 14, 18, 12); Shape3.setRotationPoint(-7F, 6F, -6F); Shape3.setTextureSize(64, 64); Shape3.mirror = true; setRotation(Shape3, 0F, 0F, 0F); Shape1 = new ModelRenderer(this, 1, 32); Shape1.addBox(0F, 0F, 0F, 14, 16, 6); Shape1.setRotationPoint(-7F, -10F, 0F); Shape1.setTextureSize(64, 64); Shape1.mirror = true; setRotation(Shape1, 0F, 0F, 0F); Shape2 = new ModelRenderer(this, 1, 1); Shape2.addBox(0F, 0F, 0F, 1, 2, 1); Shape2.setTextureSize(64, 64); Shape2.mirror = true; if(mod_Others.remoteDoorActivate) { Shape2.setRotationPoint(3F, 4F, -4F); } else if(!mod_Others.remoteDoorActivate) { Shape2.setRotationPoint(5F, 4F, -4F); } setRotation(Shape2, 0F, 0F, 0F); } public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); setRotationAngles(f, f1, f2, f3, f4, f5, entity); Shape3.render(f5); Shape1.render(f5); Shape2.render(f5); if(mod_Others.remoteDoorActivate) { Shape2.setRotationPoint(3F, 4F, -4F); } else if(!mod_Others.remoteDoorActivate) { Shape2.setRotationPoint(5F, 4F, -4F); } } public void renderModel(float f1) { Shape3.render(f1); Shape1.render(f1); Shape2.render(f1); if(mod_Others.remoteDoorActivate) { Shape2.setRotationPoint(3F, 4F, -4F); } else if(!mod_Others.remoteDoorActivate) { Shape2.setRotationPoint(5F, 4F, -4F); } } private void setRotation(ModelRenderer model, float x, float y, float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); if(mod_Others.remoteDoorActivate) { Shape2.setRotationPoint(3F, 4F, -4F); } else if(!mod_Others.remoteDoorActivate) { Shape2.setRotationPoint(5F, 4F, -4F); } } }
[ "ntzrmtthihu777@gmail.com" ]
ntzrmtthihu777@gmail.com
b118fad44c5e03ff258a7cbf892ec24e86d49449
eab78489b4e4b59741c83e1ac26fec50bf146cd5
/core/java/src/mu/seccyber/core/web/OptRoutable.java
f956dfcc2dea4635752612246d32fb1f71ca0797
[]
no_license
AndreasKralj/SECMizzouCyberChallenge
e65758994de78437628a50d03c6ddf2dede11fad
c3efbd5fac5b4b68d7e5b05711fb25942b519972
refs/heads/master
2020-03-09T06:47:00.989573
2018-04-10T13:04:04
2018-04-10T13:04:04
128,648,136
0
0
null
null
null
null
UTF-8
Java
false
false
2,954
java
package mu.seccyber.core.web; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; import com.fasterxml.jackson.databind.module.SimpleModule; import mu.seccyber.core.opt.Optimizer; import mu.seccyber.core.policy.PolicyHandler; import mu.seccyber.core.web.impl.Action; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; import java.io.IOException; import java.util.List; /** * Created by dmitriichemodanov on 4/8/18. */ public class OptRoutable extends ServerResource { private static Optimizer opt = new Optimizer(); @Post("json") public String composeActions(String json) { try { List<Action> actions = jsonToActions(json); //Compose SC int[] actionsToApply = composeActionsInt(actions); for (int i=0; i< actionsToApply.length; i++) actions.get(i).setApply(actionsToApply[i] == 1); return actionToJson(actions); } catch (Exception ex) { ex.printStackTrace(); return ("{\"ERROR\" : \"exception during security action composition: " + ex.getMessage() + "\"}"); } } private int[] composeActionsInt(List<Action> acts) { double[] risks = new double[acts.size()]; double[] exec_times = new double[acts.size()]; for(int i=0; i<acts.size(); i++) { risks[i] = acts.get(i).getRisk(); exec_times[i] = acts.get(i).getExecTime(); } return opt.composeActions(acts.size(), risks, exec_times, PolicyHandler.getInstance().getRiskLvl()); } public static List<Action> jsonToActions(String json) throws IOException { /* SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyDeserializer( DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { if (beanDesc.getBeanClass() == YourClass.class) { return new YourClassDeserializer(deserializer); } return deserializer; }}); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(module); objectMapper.readValue(json, classType); */ System.out.println("Next JSON obtained: " + json); ObjectMapper mapper = new ObjectMapper(); //deserialize JSON objects return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, Action.class)); } public static String actionToJson(List<Action> acts) throws IOException { return new ObjectMapper().writeValueAsString(acts); } }
[ "dycbt4@mail.missouri.edu" ]
dycbt4@mail.missouri.edu
e9b1909c1435ac908a98f083b1990a1aafe25f51
9bd18af7626c9e09e409f9760d065e415d970a96
/gulimall-common/src/main/java/com/wxx/common/utils/RRException.java
f8ef000a0c86ddf668a07a1c5ec808268f2919e5
[ "Apache-2.0" ]
permissive
haywood2018/gulimall
4f46d15d90809a60fc4f023c63c48957706193a8
4457f8026001a68380067eacf3b53992a6e35533
refs/heads/master
2023-04-25T08:08:59.900206
2020-11-15T08:49:04
2020-11-15T08:49:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
977
java
/** * Copyright (c) 2016-2019 人人开源 All rights reserved. * * https://www.renren.io * * 版权所有,侵权必究! */ package com.wxx.common.utils; /** * 自定义异常 * * @author Mark sunlightcs@gmail.com */ public class RRException extends RuntimeException { private static final long serialVersionUID = 1L; private String msg; private int code = 500; public RRException(String msg) { super(msg); this.msg = msg; } public RRException(String msg, Throwable e) { super(msg, e); this.msg = msg; } public RRException(String msg, int code) { super(msg); this.msg = msg; this.code = code; } public RRException(String msg, int code, Throwable e) { super(msg, e); this.msg = msg; this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }
[ "91907@163.com" ]
91907@163.com
af688ef6d05b71996744d58f11d96641954694ee
dd82a2b15ab9e5df9432c607b02145c4cd2e5967
/app/src/androidTest/java/com/example/surbhimiglani/glidedemo/ExampleInstrumentedTest.java
ffb3933fee62b457fdd99a1d68dd161b44e8d278
[]
no_license
surbhimiglani/GlideDemo
278708e1ef091220b935293c16d43c37439382c1
74cd106974640ca6562dbb47a5c3d02c3a14666a
refs/heads/master
2020-03-27T12:23:00.596230
2018-08-29T04:09:30
2018-08-29T04:09:30
146,543,371
0
0
null
null
null
null
UTF-8
Java
false
false
774
java
package com.example.surbhimiglani.glidedemo; 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.*; /** * Instrumentation 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() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.surbhimiglani.glidedemo", appContext.getPackageName()); } }
[ "surbhimiglani2811@gmail.com" ]
surbhimiglani2811@gmail.com
397aff03c83d12d3c12f98358b081aa6de7f2c2f
2086231845095c5b789d718edd6e916d617d6fad
/HuJunMQ/src/demo05/Broker.java
df98e490ed36b818b2fcad5ecb7bcb6e0cb32afd
[ "MIT" ]
permissive
hujunchina/java-learning
86463d78f2b6c237c2789eaab4f312edccb1fd31
4051cf07f3c81e0b84953e182c4d6202050d8e50
refs/heads/master
2021-07-22T23:24:42.963504
2019-12-11T03:27:43
2019-12-11T03:27:43
224,174,966
0
0
MIT
2020-10-13T17:46:23
2019-11-26T11:23:27
Java
UTF-8
Java
false
false
3,688
java
package demo05; import java.io.IOException; import java.net.ServerSocket; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class Broker { private final static int MAX_SIZE = 100000; //保存消息的数据容器 protected final static BlockingQueue<byte[]> messageQueue = new ArrayBlockingQueue<byte[]>(MAX_SIZE); // 两个socket private ServerSocket publish_socket; private ServerSocket subscribe_socket; // 存储注册订阅者 public List<Topic> getTopicList() { return topicList; } public void setTopicList(List<Topic> topicList) { this.topicList = topicList; } // 存储主题和信息 private List<Topic> topicList = new ArrayList<Topic>(); private void log(String logs){ System.out.println("Broker: "+logs); } private static Set<String> topicName = new HashSet<String>(); private static Map<String, Topic> topicMap = new HashMap<String, Topic>(); public void publishSocket(){ try{ publish_socket = new ServerSocket(BrokerServer.PUBLISH_SERVICE_PORT); log("create publish socket server succeeded"); } catch (IOException e) { log("create publish socket failed"); e.printStackTrace(); } } public void subscribeSocket(){ try{ subscribe_socket = new ServerSocket(BrokerServer.SUBSCRIBE_SERVICE_PORT); log("create subscribe socket server succeeded"); } catch (IOException e) { log("create subscribe socket server failed"); e.printStackTrace(); } } // 保存消息,目前存储在内存中,后期持久化优化到文件中 public static void msgHandler(List<Topic> topics){ System.out.println("invoke"); for(Topic topic: topics){ TopicHandler.getTopics().add(topic.getTopic()); topicName.add(topic.getTopic()); System.out.println(topic.getTopic()); TopicHandler.addMap(topic.getTopic(), topic); topicMap.put(topic.getTopic(), topic); } } public static boolean hasTopic(String name){ if(topicName.contains(name)){ return true; }else{ return false; } } public static List<Topic> getTopicList(List<String> tnames){ List<Topic> rtTopic = null; for(String name : tnames){ if(hasTopic(name)){ Topic topic = topicMap.get(name); rtTopic.add(topic); } } return rtTopic; } public static Topic getTopic(String name){ return topicMap.get(name); } public static void setTopic(String name){ Topic topic = new Topic(); topic.setTopic(name); topicName.add(name); topicMap.put(name, topic); } // test run server public static void main(String[] args) { Broker broker = new Broker(); broker.publishSocket(); broker.subscribeSocket(); try{ while(true){ // 一个线程作为发布者socket server BrokerServer server = new BrokerServer(broker.publish_socket.accept()); new Thread(server).start(); // 另一个线程作为订阅者 socket server BrokerConsumer consumerServer = new BrokerConsumer(broker.subscribe_socket.accept()); new Thread(consumerServer).start(); } }catch (IOException e){ broker.log("socket server stopped"); e.printStackTrace(); } } }
[ "hujunchina@outlook" ]
hujunchina@outlook
a6c0f0cb857654c1291c694a851e13c41393d189
314b079fde501bf5d671e2d725f2f149e47765b3
/mysite-database/src/main/java/com/hehe/mysite/database/pojo/ConfigSms.java
5130373cc37155a339a5914512cfd2d8f601e85c
[]
no_license
TrickstTT/mysite
86bd9707a28158e54b20f48974affdeaf375cc5c
b0b93a419551ad0a76dec360dcfc7aa51fa6955a
refs/heads/master
2021-05-11T03:52:11.149796
2018-01-19T02:03:03
2018-01-19T02:03:03
117,926,543
0
0
null
null
null
null
UTF-8
Java
false
false
3,139
java
package com.hehe.mysite.database.pojo; import javax.persistence.*; @Table(name = "config_sms") public class ConfigSms { /** * 编号 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String id; /** * AccessId */ @Column(name = "sms_access_id") private String smsAccessId; /** * AccessKey */ @Column(name = "sms_access_key") private String smsAccessKey; /** * MNSEndpoint */ @Column(name = "sms_mns_endpoint") private String smsMnsEndpoint; /** * 主题 */ @Column(name = "sms_topic") private String smsTopic; /** * 签名 */ @Column(name = "sms_sign_name") private String smsSignName; /** * 测试手机 */ @Column(name = "test_number") private String testNumber; /** * 获取编号 * * @return id - 编号 */ public String getId() { return id; } /** * 设置编号 * * @param id 编号 */ public void setId(String id) { this.id = id; } /** * 获取AccessId * * @return sms_access_id - AccessId */ public String getSmsAccessId() { return smsAccessId; } /** * 设置AccessId * * @param smsAccessId AccessId */ public void setSmsAccessId(String smsAccessId) { this.smsAccessId = smsAccessId; } /** * 获取AccessKey * * @return sms_access_key - AccessKey */ public String getSmsAccessKey() { return smsAccessKey; } /** * 设置AccessKey * * @param smsAccessKey AccessKey */ public void setSmsAccessKey(String smsAccessKey) { this.smsAccessKey = smsAccessKey; } /** * 获取MNSEndpoint * * @return sms_mns_endpoint - MNSEndpoint */ public String getSmsMnsEndpoint() { return smsMnsEndpoint; } /** * 设置MNSEndpoint * * @param smsMnsEndpoint MNSEndpoint */ public void setSmsMnsEndpoint(String smsMnsEndpoint) { this.smsMnsEndpoint = smsMnsEndpoint; } /** * 获取主题 * * @return sms_topic - 主题 */ public String getSmsTopic() { return smsTopic; } /** * 设置主题 * * @param smsTopic 主题 */ public void setSmsTopic(String smsTopic) { this.smsTopic = smsTopic; } /** * 获取签名 * * @return sms_sign_name - 签名 */ public String getSmsSignName() { return smsSignName; } /** * 设置签名 * * @param smsSignName 签名 */ public void setSmsSignName(String smsSignName) { this.smsSignName = smsSignName; } /** * 获取测试手机 * * @return test_number - 测试手机 */ public String getTestNumber() { return testNumber; } /** * 设置测试手机 * * @param testNumber 测试手机 */ public void setTestNumber(String testNumber) { this.testNumber = testNumber; } }
[ "1509397017@qq.com" ]
1509397017@qq.com
34ce33475df5a5ca10d0e58db64baf8c1ea136dc
385142095beea3d06266a1895cb0266bc4ce236b
/src/main/java/com/groovybot/persistence/PMF.java
73a23bbbb57081c323d9f22dd52d92986fbde447
[ "Apache-2.0" ]
permissive
cretzel/groovybot
ac81d744d45797c5153ee8b1b7aa798fe073b4bd
47c46ccd7d1fbfd51d577a184dc71d83360c9602
refs/heads/master
2020-04-20T20:34:37.066372
2009-11-25T20:30:51
2009-11-25T20:30:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
546
java
package com.groovybot.persistence; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; public final class PMF { private static final PersistenceManagerFactory pmfInstance = JDOHelper .getPersistenceManagerFactory("transactions-optional"); private PMF() { } public static PersistenceManagerFactory get() { return pmfInstance; } public static PersistenceManager getPersistanceManager() { return get().getPersistenceManager(); } }
[ "nick.wiedenbrueck@gmail.com" ]
nick.wiedenbrueck@gmail.com
ec62ffd550e931dab3d8d27cbde7b113df0746ca
750186b94b8f631bf05a54000542e60be85ce127
/Scheme Interpreter/src/intermediate/Node.java
bf2330e2ec986d10b4886e35b2c7775ad8803bc7
[]
no_license
crrenteria/Scheme_Interpreter
70bae87962c0be0467bde01c1e747a0adb935eb1
b091aaa7e36d5aca94fe0fcc71b65e501ff4fb11
refs/heads/master
2020-05-29T09:07:57.748036
2014-04-17T06:59:32
2014-04-17T06:59:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
568
java
package intermediate; public class Node { String value; Node leftChild; Node rightChild; Node parent; public Node(String s) { value = s; leftChild = null; rightChild = null; parent = null; } public boolean hasLeftChild() { return (leftChild != null); } public boolean hasRightChild() { return (rightChild != null); } public String getValue() { return value; } public Node getParent() { return parent; } public Node getLeftChild() { return leftChild; } public Node getRightChild() { return rightChild; } }
[ "katharine.brinker@gmail.com" ]
katharine.brinker@gmail.com
a741a5ea661c803a3fdde32c72b2148ad576d28a
5024c8aab5936941dbffa81eb4002f71759d2732
/ChatClient/MouseConnectEvent.java
5eb2e6f965257a3e1349de85e5a2ce816c6802b2
[]
no_license
Palethorn/JChat
e1c0e1b82235856dc448a020d60d542edeb115d8
37d0fff874acec2db9c6220523f14d67df523bf3
refs/heads/master
2016-09-10T08:22:20.159153
2012-07-07T11:20:24
2012-07-07T11:20:24
3,113,143
2
0
null
null
null
null
UTF-8
Java
false
false
867
java
package app.ChatClient; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class MouseConnectEvent implements MouseListener { Singleton singleton; public MouseConnectEvent() { singleton = Singleton.Instance(); } @Override public void mouseClicked(MouseEvent e) { singleton.dispatchConnectEvent(); } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } }
[ "wizzard405@gmail.com" ]
wizzard405@gmail.com
5399ad473e996382fc15cb0006901040c1723942
ff0c33ccd3bbb8a080041fbdbb79e29989691747
/java.base/java/lang/reflect/Modifier.java
0bcfa7b971f0e2097ba8ae41da5c0894cfc0e90d
[]
no_license
jiecai58/jdk15
7d0f2e518e3f6669eb9ebb804f3c89bbfb2b51f0
b04691a72e51947df1b25c31175071f011cb9bbe
refs/heads/main
2023-02-25T00:30:30.407901
2021-01-29T04:48:33
2021-01-29T04:48:33
330,704,930
0
1
null
null
null
null
UTF-8
Java
false
false
15,802
java
/* * Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.lang.reflect; import java.util.StringJoiner; /** * The Modifier class provides {@code static} methods and * constants to decode class and member access modifiers. The sets of * modifiers are represented as integers with distinct bit positions * representing different modifiers. The values for the constants * representing the modifiers are taken from the tables in sections 4.1, 4.4, 4.5, and 4.7 of * <cite>The Java Virtual Machine Specification</cite>. * * @see Class#getModifiers() * @see Member#getModifiers() * * @author Nakul Saraiya * @author Kenneth Russell * @since 1.1 */ public class Modifier { /** * Do not call. */ private Modifier() {throw new AssertionError();} /** * Return {@code true} if the integer argument includes the * {@code public} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code public} modifier; {@code false} otherwise. */ public static boolean isPublic(int mod) { return (mod & PUBLIC) != 0; } /** * Return {@code true} if the integer argument includes the * {@code private} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code private} modifier; {@code false} otherwise. */ public static boolean isPrivate(int mod) { return (mod & PRIVATE) != 0; } /** * Return {@code true} if the integer argument includes the * {@code protected} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code protected} modifier; {@code false} otherwise. */ public static boolean isProtected(int mod) { return (mod & PROTECTED) != 0; } /** * Return {@code true} if the integer argument includes the * {@code static} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code static} modifier; {@code false} otherwise. */ public static boolean isStatic(int mod) { return (mod & STATIC) != 0; } /** * Return {@code true} if the integer argument includes the * {@code final} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code final} modifier; {@code false} otherwise. */ public static boolean isFinal(int mod) { return (mod & FINAL) != 0; } /** * Return {@code true} if the integer argument includes the * {@code synchronized} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code synchronized} modifier; {@code false} otherwise. */ public static boolean isSynchronized(int mod) { return (mod & SYNCHRONIZED) != 0; } /** * Return {@code true} if the integer argument includes the * {@code volatile} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code volatile} modifier; {@code false} otherwise. */ public static boolean isVolatile(int mod) { return (mod & VOLATILE) != 0; } /** * Return {@code true} if the integer argument includes the * {@code transient} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code transient} modifier; {@code false} otherwise. */ public static boolean isTransient(int mod) { return (mod & TRANSIENT) != 0; } /** * Return {@code true} if the integer argument includes the * {@code native} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code native} modifier; {@code false} otherwise. */ public static boolean isNative(int mod) { return (mod & NATIVE) != 0; } /** * Return {@code true} if the integer argument includes the * {@code interface} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code interface} modifier; {@code false} otherwise. */ public static boolean isInterface(int mod) { return (mod & INTERFACE) != 0; } /** * Return {@code true} if the integer argument includes the * {@code abstract} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code abstract} modifier; {@code false} otherwise. */ public static boolean isAbstract(int mod) { return (mod & ABSTRACT) != 0; } /** * Return {@code true} if the integer argument includes the * {@code strictfp} modifier, {@code false} otherwise. * * @param mod a set of modifiers * @return {@code true} if {@code mod} includes the * {@code strictfp} modifier; {@code false} otherwise. */ public static boolean isStrict(int mod) { return (mod & STRICT) != 0; } /** * Return a string describing the access modifier flags in * the specified modifier. For example: * <blockquote><pre> * public final synchronized strictfp * </pre></blockquote> * The modifier names are returned in an order consistent with the * suggested modifier orderings given in sections 8.1.1, 8.3.1, 8.4.3, 8.8.3, and 9.1.1 of * <cite>The Java Language Specification</cite>. * The full modifier ordering used by this method is: * <blockquote> {@code * public protected private abstract static final transient * volatile synchronized native strictfp * interface } </blockquote> * The {@code interface} modifier discussed in this class is * not a true modifier in the Java language and it appears after * all other modifiers listed by this method. This method may * return a string of modifiers that are not valid modifiers of a * Java entity; in other words, no checking is done on the * possible validity of the combination of modifiers represented * by the input. * * Note that to perform such checking for a known kind of entity, * such as a constructor or method, first AND the argument of * {@code toString} with the appropriate mask from a method like * {@link #constructorModifiers} or {@link #methodModifiers}. * * @param mod a set of modifiers * @return a string representation of the set of modifiers * represented by {@code mod} */ public static String toString(int mod) { StringJoiner sj = new StringJoiner(" "); if ((mod & PUBLIC) != 0) sj.add("public"); if ((mod & PROTECTED) != 0) sj.add("protected"); if ((mod & PRIVATE) != 0) sj.add("private"); /* Canonical order */ if ((mod & ABSTRACT) != 0) sj.add("abstract"); if ((mod & STATIC) != 0) sj.add("static"); if ((mod & FINAL) != 0) sj.add("final"); if ((mod & TRANSIENT) != 0) sj.add("transient"); if ((mod & VOLATILE) != 0) sj.add("volatile"); if ((mod & SYNCHRONIZED) != 0) sj.add("synchronized"); if ((mod & NATIVE) != 0) sj.add("native"); if ((mod & STRICT) != 0) sj.add("strictfp"); if ((mod & INTERFACE) != 0) sj.add("interface"); return sj.toString(); } /* * Access modifier flag constants from tables 4.1, 4.4, 4.5, and 4.7 of * <cite>The Java Virtual Machine Specification</cite> */ /** * The {@code int} value representing the {@code public} * modifier. */ public static final int PUBLIC = 0x00000001; /** * The {@code int} value representing the {@code private} * modifier. */ public static final int PRIVATE = 0x00000002; /** * The {@code int} value representing the {@code protected} * modifier. */ public static final int PROTECTED = 0x00000004; /** * The {@code int} value representing the {@code static} * modifier. */ public static final int STATIC = 0x00000008; /** * The {@code int} value representing the {@code final} * modifier. */ public static final int FINAL = 0x00000010; /** * The {@code int} value representing the {@code synchronized} * modifier. */ public static final int SYNCHRONIZED = 0x00000020; /** * The {@code int} value representing the {@code volatile} * modifier. */ public static final int VOLATILE = 0x00000040; /** * The {@code int} value representing the {@code transient} * modifier. */ public static final int TRANSIENT = 0x00000080; /** * The {@code int} value representing the {@code native} * modifier. */ public static final int NATIVE = 0x00000100; /** * The {@code int} value representing the {@code interface} * modifier. */ public static final int INTERFACE = 0x00000200; /** * The {@code int} value representing the {@code abstract} * modifier. */ public static final int ABSTRACT = 0x00000400; /** * The {@code int} value representing the {@code strictfp} * modifier. */ public static final int STRICT = 0x00000800; // Bits not (yet) exposed in the public API either because they // have different meanings for fields and methods and there is no // way to distinguish between the two in this class, or because // they are not Java programming language keywords static final int BRIDGE = 0x00000040; static final int VARARGS = 0x00000080; static final int SYNTHETIC = 0x00001000; static final int ANNOTATION = 0x00002000; static final int ENUM = 0x00004000; static final int MANDATED = 0x00008000; static boolean isSynthetic(int mod) { return (mod & SYNTHETIC) != 0; } static boolean isMandated(int mod) { return (mod & MANDATED) != 0; } // Note on the FOO_MODIFIERS fields and fooModifiers() methods: // the sets of modifiers are not guaranteed to be constants // across time and Java SE releases. Therefore, it would not be // appropriate to expose an external interface to this information // that would allow the values to be treated as Java-level // constants since the values could be constant folded and updates // to the sets of modifiers missed. Thus, the fooModifiers() // methods return an unchanging values for a given release, but a // value that can potentially change over time. /** * The Java source modifiers that can be applied to a class. * @jls 8.1.1 Class Modifiers */ private static final int CLASS_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.STRICT; /** * The Java source modifiers that can be applied to an interface. * @jls 9.1.1 Interface Modifiers */ private static final int INTERFACE_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | Modifier.ABSTRACT | Modifier.STATIC | Modifier.STRICT; /** * The Java source modifiers that can be applied to a constructor. * @jls 8.8.3 Constructor Modifiers */ private static final int CONSTRUCTOR_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; /** * The Java source modifiers that can be applied to a method. * @jls 8.4.3 Method Modifiers */ private static final int METHOD_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.STRICT; /** * The Java source modifiers that can be applied to a field. * @jls 8.3.1 Field Modifiers */ private static final int FIELD_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL | Modifier.TRANSIENT | Modifier.VOLATILE; /** * The Java source modifiers that can be applied to a method or constructor parameter. * @jls 8.4.1 Formal Parameters */ private static final int PARAMETER_MODIFIERS = Modifier.FINAL; static final int ACCESS_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; /** * Return an {@code int} value OR-ing together the source language * modifiers that can be applied to a class. * @return an {@code int} value OR-ing together the source language * modifiers that can be applied to a class. * * @jls 8.1.1 Class Modifiers * @since 1.7 */ public static int classModifiers() { return CLASS_MODIFIERS; } /** * Return an {@code int} value OR-ing together the source language * modifiers that can be applied to an interface. * @return an {@code int} value OR-ing together the source language * modifiers that can be applied to an interface. * * @jls 9.1.1 Interface Modifiers * @since 1.7 */ public static int interfaceModifiers() { return INTERFACE_MODIFIERS; } /** * Return an {@code int} value OR-ing together the source language * modifiers that can be applied to a constructor. * @return an {@code int} value OR-ing together the source language * modifiers that can be applied to a constructor. * * @jls 8.8.3 Constructor Modifiers * @since 1.7 */ public static int constructorModifiers() { return CONSTRUCTOR_MODIFIERS; } /** * Return an {@code int} value OR-ing together the source language * modifiers that can be applied to a method. * @return an {@code int} value OR-ing together the source language * modifiers that can be applied to a method. * * @jls 8.4.3 Method Modifiers * @since 1.7 */ public static int methodModifiers() { return METHOD_MODIFIERS; } /** * Return an {@code int} value OR-ing together the source language * modifiers that can be applied to a field. * @return an {@code int} value OR-ing together the source language * modifiers that can be applied to a field. * * @jls 8.3.1 Field Modifiers * @since 1.7 */ public static int fieldModifiers() { return FIELD_MODIFIERS; } /** * Return an {@code int} value OR-ing together the source language * modifiers that can be applied to a parameter. * @return an {@code int} value OR-ing together the source language * modifiers that can be applied to a parameter. * * @jls 8.4.1 Formal Parameters * @since 1.8 */ public static int parameterModifiers() { return PARAMETER_MODIFIERS; } }
[ "caijie2@tuhu.cn" ]
caijie2@tuhu.cn
61ef9338f5c9907db8207ffe52619e968d88fc61
1842bb0f3b60ed08b12def9159eb3033cf7283a3
/jmvp/src/main/java/com/soubw/jmvp/BaseUICallBackI.java
d6a63bf6bec3c1b48e12a9182043351f8521656e
[]
no_license
WX-JIN/JMvpDemo
1dd08ed908f396e75409e4866430df971e415c03
7230c297b4c7219beaf851b8375189bffde3928e
refs/heads/master
2020-04-06T07:10:29.895542
2016-08-27T08:02:51
2016-08-27T08:02:51
65,342,576
1
0
null
null
null
null
UTF-8
Java
false
false
1,098
java
package com.soubw.jmvp; import android.os.Handler; import android.os.Looper; /** * @author WX_JIN * @email wangxiaojin@soubw.com * @link http://soubw.com */ public abstract class BaseUICallBackI<T> implements BaseCallBackI<T> { private BaseViewI baseViewI; private Handler handler; public BaseUICallBackI(BaseViewI baseViewI) { this.baseViewI = baseViewI; handler = new Handler(Looper.getMainLooper()); } public void postUISuccess(final T t) { handler.post(new Runnable() { @Override public void run() { try { onSuccess(t); } catch (Exception e) { e.printStackTrace(); } } }); } public void postUIFail(final String msg) { handler.post(new Runnable() { @Override public void run() { try { onFail(msg); } catch (Exception e) { e.printStackTrace(); } } }); } }
[ "85268837@qq.com" ]
85268837@qq.com
cf40f74b0bd4935f536541c27c496beccfe6edef
9ec173c503d07f227e5f29a000a88f95f71df0cb
/src/main/java/com/neuedu/controller/ProductUpdateServlet.java
26167defcf878288b9091da1ed103f86c5d24c22
[]
no_license
cyxdy930719/webManager
c3e8683f95ad062b359ad772004417a552e53501
7ad287a8df50676ff3cbada0eef7f312266a6f69
refs/heads/master
2020-04-12T18:43:55.962180
2018-12-31T12:12:12
2018-12-31T12:12:12
162,685,889
0
0
null
null
null
null
UTF-8
Java
false
false
858
java
package com.neuedu.controller; import com.neuedu.pojo.Product; import com.neuedu.service.ProductServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/update") public class ProductUpdateServlet extends HttpServlet { private ProductServiceImpl service = new ProductServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int id = Integer.parseInt(req.getParameter("product_id")); Product p = service.getOne(id); req.setAttribute("p",p); req.getRequestDispatcher("WEB-INF/pages/update.jsp").forward(req,resp); } }
[ "cyxdy930719@163.com" ]
cyxdy930719@163.com
a4be61fe13a0140b258afb6bc1b8c646ccdad255
dcf8f9283093f16e79686d083f4496d1e7ae24d1
/build/dist/jpaint/src/main/java/model/persistence/ApplicationState.java
b1ea1b529671edd5f4112f09b71bfb7e95260031
[]
no_license
sljiang93/jpaint
85f41b409003a4ca832a7f29a05a9117f244afe8
113d49f7761eef5e97999b03a685a131005ea50b
refs/heads/master
2023-07-10T19:27:08.387068
2021-08-22T21:14:09
2021-08-22T21:14:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,500
java
package model.persistence; import model.*; import model.dialogs.DialogProvider; import model.interfaces.IApplicationState; import model.interfaces.IDialogProvider; import view.interfaces.IUiModule; import java.awt.Point; import java.io.Serializable; import controller.MouseClick; public class ApplicationState implements IApplicationState, Serializable { //private static final long serialVersionUID = -5545483996576839007L; private final IUiModule uiModule; private final IDialogProvider dialogProvider; private ShapeType activeShapeType; private ShapeColor activePrimaryColor; private ShapeColor activeSecondaryColor; private ShapeShadingType activeShapeShadingType; private StartAndEndPointMode activeStartAndEndPointMode; private Point startPoint; private Point endPoint; public ApplicationState(IUiModule uiModule) { this.uiModule = uiModule; this.dialogProvider = new DialogProvider(this); setDefaults(); } @Override public void setActiveShape() { activeShapeType = uiModule.getDialogResponse(dialogProvider.getChooseShapeDialog()); } @Override public void setActivePrimaryColor() { activePrimaryColor = uiModule.getDialogResponse(dialogProvider.getChoosePrimaryColorDialog()); } @Override public void setActiveSecondaryColor() { activeSecondaryColor = uiModule.getDialogResponse(dialogProvider.getChooseSecondaryColorDialog()); } @Override public void setActiveShadingType() { activeShapeShadingType = uiModule.getDialogResponse(dialogProvider.getChooseShadingTypeDialog()); } @Override public void setActiveStartAndEndPointMode() { activeStartAndEndPointMode = uiModule.getDialogResponse(dialogProvider.getChooseStartAndEndPointModeDialog()); } @Override public void CopyCommand() { } /*@Override public void DeleteCommand() { } @Override public void PasteCommand() { }*/ @Override public void UndoCommand() { } @Override public void RedoCommand() { } @Override public ShapeType getActiveShapeType() { return activeShapeType; } @Override public ShapeColor getActivePrimaryColor() { return activePrimaryColor; } @Override public ShapeColor getActiveSecondaryColor() { return activeSecondaryColor; } @Override public ShapeShadingType getActiveShapeShadingType() { return activeShapeShadingType; } @Override public StartAndEndPointMode getActiveStartAndEndPointMode() { return activeStartAndEndPointMode; } public Point getStartPoint(){ return startPoint; } public Point getEndPoint(){ return endPoint; } public Point getAdjustedStart(){ double startX = Math.min(startPoint.getX(), endPoint.getX()); double startY = Math.min(startPoint.getY(), endPoint.getY()); return new Point(); } public Point getAdjustedEnd(){ double endX = Math.max(startPoint.getX(), endPoint.getX()); double endY = Math.max(startPoint.getY(), endPoint.getY()); return new Point(); } private void setDefaults() { activeShapeType = ShapeType.ELLIPSE; activePrimaryColor = ShapeColor.BLUE; activeSecondaryColor = ShapeColor.GREEN; activeShapeShadingType = ShapeShadingType.FILLED_IN; activeStartAndEndPointMode = StartAndEndPointMode.DRAW; } }
[ "songlingjiang1993@gmail.com" ]
songlingjiang1993@gmail.com
690086d0e1d5a77136ccdfe379560559af8f588e
20c3000e7fe508533eaeb53d55c8b3d50abb10fa
/src/main/java/com/shaoyuanhu/chapter/one/t4/Run.java
4341e2cdf1dcf4dadfb8524e5a46aeeb9a7203ef
[]
no_license
shaoyuanhu/core-technology-of-java-multithread-programming
e23681356e33e79b15b51d32ba3b2717ab9b9997
df7b71acc25dcbf609ad2ac638849013a3d561a9
refs/heads/master
2021-05-10T17:00:00.434657
2018-01-30T06:26:45
2018-01-30T06:26:45
118,594,913
0
0
null
null
null
null
UTF-8
Java
false
false
879
java
package com.shaoyuanhu.chapter.one.t4; /** * @Author: ShaoYuanHu * @Description: 测试MyThread * @Date: Create in 2018-01-23 17:33 */ public class Run { public static void main(String[] args) { shardVariable(); } /** * 创建1个线程对象,将这个MyThread对象作为参数传递给五个Thread的构造,并分配不通的线程名称 * 因为只有一个MyThread对象,所以count变量对5个Thread线程是共享的 */ private static void shardVariable() { MyThread thread = new MyThread(); Thread a = new Thread(thread,"A"); Thread b = new Thread(thread,"B"); Thread c = new Thread(thread,"C"); Thread d = new Thread(thread,"D"); Thread e = new Thread(thread,"E"); a.start(); b.start(); c.start(); d.start(); e.start(); } }
[ "shaoyh2@lenovo.com" ]
shaoyh2@lenovo.com
1f4632402d0da0ce2123d4d84623ee7cc3aae24a
529149c9cb2135f3bc81874b753bd2c12d5a589b
/src/org/openrdf/query/algebra/evaluation/function/postgis/geometry/attribute/IsRectangle.java
2c88c00461c708520149cd9e5ed75592308d23c4
[ "Apache-2.0" ]
permissive
i3mainz/kiwi-postgis
5ce7a6794267e03044bcbda2d50e7c9ecc4c50bf
8b287fd3424c53892f945a7db21b590811bf20d4
refs/heads/master
2021-07-05T15:30:08.983530
2020-11-03T20:49:45
2020-11-03T20:49:45
200,048,925
1
0
null
null
null
null
UTF-8
Java
false
false
546
java
package org.openrdf.query.algebra.evaluation.function.postgis.geometry.attribute; import org.openrdf.model.vocabulary.POSTGIS; import org.locationtech.jts.geom.Geometry; import org.openrdf.query.algebra.evaluation.function.postgis.geometry.base.GeometricBinaryAttributeFunction; public class IsRectangle extends GeometricBinaryAttributeFunction { @Override public String getURI() { return POSTGIS.st_isRectangle.stringValue(); } @Override public boolean attribute(Geometry geom) { return geom.isRectangle(); } }
[ "timo.homburg@hs-mainz.de" ]
timo.homburg@hs-mainz.de
7d52f185a70f0a5d1a1e731848974a05635d9570
fc561a50cef3d4ac4bc9967160c71328e8677c83
/src/main/java/datastructures/trees/FindIfTreeisBST.java
64c942c81b2e3e6d2aadf8ff85d55d55d7770075
[]
no_license
Nemo24/algorithms
9108169dcf0712c7caf99892af143ce498d91c4d
3e67760fcaae5ea3bd267bd70f55cf9f739c731e
refs/heads/master
2021-01-17T09:14:02.183835
2019-09-29T10:09:41
2019-09-29T10:09:41
62,985,651
0
0
null
null
null
null
UTF-8
Java
false
false
2,064
java
package datastructures.trees; /** * Created by mm on 1/3/16. */ public class FindIfTreeisBST { int prev = Integer.MIN_VALUE; public boolean isBSTWrongApproach(BinaryTree tree){ if (tree == null) return false; return isBSTWrongApproach(tree.root); } private boolean isBSTWrongApproach(BinaryTreeNode root){ if (root == null) return true; if ((root.getLeft()!=null) && (root.getLeft().getData() > root.getData())) return false; if ((root.getRight()!=null) && (root.getRight().getData() < root.getData())) return false; return isBSTWrongApproach(root.getLeft()) && isBSTWrongApproach(root.getRight()); } public boolean isBST(BinaryTree tree){ if (tree == null) return false; prev = Integer.MIN_VALUE; return isBST(tree.root); } private boolean isBST(BinaryTreeNode root){ if (root == null) return true; boolean leftIsTrue = isBST(root.getLeft()); if (!leftIsTrue) return false; if (root.getData() < prev) return false; prev = root.getData(); return isBST(root.getRight()); } public static void main(String[] args) { BinaryTree tree1 = BinaryTreeCreatorHelper.getBinarySearchTreeWrong(); BinaryTree tree2 = BinaryTreeCreatorHelper.getBinarySearchTreeCorrect(); BinaryTree tree3 = BinaryTreeCreatorHelper.getBinarySearchTreeVeryWrong(); FindIfTreeisBST mm = new FindIfTreeisBST(); System.out.println("wrong approach"); System.out.println(mm.isBSTWrongApproach(tree1) + ":this should be false"); System.out.println(mm.isBSTWrongApproach(tree2) + ":this could be true"); System.out.println(mm.isBSTWrongApproach(tree3) + ":this should be false"); System.out.println(); System.out.println("right approach"); System.out.println(mm.isBST(tree1) + ":this should be false"); System.out.println(mm.isBST(tree2) + ":this could be true"); System.out.println(mm.isBST(tree3) + ":this should be false"); } }
[ "manohar.m@247-inc.com" ]
manohar.m@247-inc.com
16705f1a835242424dfe879d4c3e5125900c8743
91feacfea6bbcadd634dde42681dbba317e31f75
/src/main/java/com/creditharmony/fortune/utils/FileUtil.java
1d6314bf711d732406a67f7a0a3696202811b1e9
[]
no_license
sengeiou/chp-fortune
0d5ccc9b40568a622fa162dc609bd4ccfc358a9f
ac676cb5d8502269d2d44bf395206034f26b4e49
refs/heads/master
2020-05-16T02:53:13.475287
2017-07-06T07:31:26
2017-07-06T07:31:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
16,367
java
package com.creditharmony.fortune.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLConnection; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.FileCopyUtils; import org.springframework.web.multipart.MultipartFile; import com.creditharmony.common.util.FileUtils; import com.creditharmony.core.config.Global; import com.creditharmony.core.excel.util.ExportExcel; import com.creditharmony.core.fortune.type.ReportType; import com.creditharmony.core.users.util.UserUtils; import com.creditharmony.dm.bean.DocumentBean; import com.creditharmony.dm.file.util.Zip; import com.creditharmony.dm.service.DmService; import com.creditharmony.fortune.common.FileManagement; import com.creditharmony.fortune.common.ThreadPool; import com.creditharmony.fortune.common.entity.Attachment; import com.creditharmony.fortune.deduct.common.Constant; import com.creditharmony.fortune.deduct.service.DocumentSynthesis; import com.google.common.collect.Lists; /** * 文件操作工具类 * @Class Name FileUtil * @author zhujie * @Create In 2015年11月27日 */ public class FileUtil { /** * 日志对象 */ protected static Logger logger = LoggerFactory.getLogger(FileUtil.class); /** * 保存文件 * * @param file * 上传的文件 * @param fileType * 上传的文件类型 * @return Attachment:文件名,新文件名,存放根路径 * @throws IOException * @throws IllegalStateException */ public static Attachment saveFiles(MultipartFile file,String customerFile) throws IllegalStateException, IOException { Attachment attachment = FileUtil.saveFiles(file, customerFile, "tmp"); return attachment; } /** * 保存文件 * * @param file * 上传的文件 * @param fileType * 上传的文件类型 * @return Attachment:文件名,新文件名,存放根路径 * @throws IOException * @throws IllegalStateException */ public static Attachment saveFiles(MultipartFile file,String customerFile, String subFile) throws IllegalStateException, IOException { // 返回值,记录文件的原文件名和新文件名 Attachment savedFile = new Attachment(); // 上传文件名 String fileName = file.getOriginalFilename(); InputStream is = file.getInputStream(); savedFile.setAttaFilename(fileName);// 文件名 savedFile.setAttaNewfilename(fileName);// 新文件名 try { DocumentBean docbean = null; String user = UserUtils.getUserId(); DmService dmService = DmService.getInstance(); docbean = dmService.createDocument(fileName,is , DmService.BUSI_TYPE_FORTUNE, customerFile, subFile,user ); savedFile.setAttaFilepath(docbean.getDocId());// 存放根路径 } catch(RuntimeException e){ logger.error("[Fortune---->FileUtil:saveFiles()] exception: "+e.getMessage()); } catch (Exception e1) { e1.printStackTrace(); return savedFile; } return savedFile; } /** * * 2016年2月24日 * By 刘雄武 * @param response * @param seletive * @param type */ public static void fileDownloadby(HttpServletResponse response,Attachment seletive,String type) { // 根据附件ID检索附件信息 logger.info("fileDownload文件下载......"); DmService dmService = DmService.getInstance(); OutputStream os; try { response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + new String( seletive.getAttaFilename().getBytes("gb2312"), "ISO8859-1" ) +"\"")); os = response.getOutputStream(); dmService.download(os, seletive.getAttaFilepath()); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 从网盘读取并下载 * 2016年5月16日 * By 周俊 * @param response * @param strZipPath * @param strZipname */ public static void downFileToNetdisk(HttpServletResponse response, String filePath,String fileName) { try { // 放到缓冲流里面 InputStream ins = new FileInputStream(filePath); BufferedInputStream bins = new BufferedInputStream(ins); // 获取文件输出IO流 OutputStream outs = response.getOutputStream(); BufferedOutputStream bouts = new BufferedOutputStream(outs); // 设置response内容的类型 response.setContentType("application/x-msdownload"); // 设置头部信息 response.setHeader("Content-disposition","attachment;filename="+ new String( fileName.getBytes("GBK"), "ISO8859-1" )); int bytesRead = 0; byte[] buffer = new byte[1024]; // 开始向网络传输文件流 while ((bytesRead = bins.read(buffer, 0, 1024)) != -1) { bouts.write(buffer, 0, bytesRead); } //调用flush()方法 bouts.flush(); ins.close(); bins.close(); outs.close(); bouts.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 文件下载 * 2015年12月9日 * By 韩龙 * @param response * @param seletive Attachment实体类 * @param type 预览:preview 下载:download */ public static void fileDownload(HttpServletResponse response,Attachment seletive,String type) { // 根据附件ID检索附件信息 logger.info("fileDownload文件下载......"); File file = null; file = new File(FileUtils.path(Global.getConfig("uploadFilePath")+ "/" + seletive.getAttaFilepath())); if(!file.exists()){ String errorMessage; if(type.equalsIgnoreCase("preview")){ logger.info("没有文件预览"); errorMessage = "没有文件预览"; }else{ logger.info("没有文件下载"); errorMessage = "没有文件下载"; } try { // 文字回写 OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-16"))); outputStream.flush(); outputStream.close(); } catch (IOException e) { logger.error("文件读定错误"+e.getLocalizedMessage(),e); } return; } // 确定下载文件类型 String mimeType= URLConnection.guessContentTypeFromName(file.getName()); if(mimeType==null){ // 默认类型 mimeType = "application/octet-stream"; } response.setContentType(mimeType); if(type.equalsIgnoreCase("preview")){ // 预览模式 response.setHeader("Content-Disposition", String.format("inline; filename=\"" + seletive.getAttaFilename() +"\"")); }else{ // 其他模式:下载 response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + seletive.getAttaFilename() +"\"")); } response.setContentLength((int)file.length()); try { InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); // 文件转换成数据流输出,最后关闭输入,输出数据流 FileCopyUtils.copy(inputStream, response.getOutputStream()); } catch (IOException e) { logger.error("文件转换数据流出错"+e.getLocalizedMessage(),e); } } /** * 导出excel * 2015年12月9日 * By 韩龙 * @param dataList 导出数据列表 * @param cla 导出模板实体类 * @param fileName 导出文件名字 * @param response */ public static void exportExcel(List<?> dataList, Class<?> cla, String fileName, HttpServletResponse response) { // 构建导出excel对象 ExportExcel exportExcel = new ExportExcel(null, cla); // 设置导出数据源 exportExcel.setDataList(dataList); try { logger.info("写出文件到客户端" + fileName + ".xlsx"); // 写出文件到客户端 exportExcel.write(response, fileName + ".xlsx"); exportExcel.dispose(); } catch (IOException e) { e.printStackTrace(); logger.error("列表导出失败", e); } } /** * 批量下载文件zip * 2015年12月9日 * By 韩龙 * @param subs 文件列表 * @param fileName Global.USERFILES_BASE_URL路径 * @param type 文件类型 * @param response */ public static void zipFileDownload(File[] subs, String fileName,HttpServletResponse response){ ZipOutputStream zos=null; FileInputStream fis=null; try { // 设置Header信息 response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", "attachment; filename=" + getZipFilename(fileName) + ";filename*=UTF-8''" + getZipFilename(fileName)); zos = new ZipOutputStream(response.getOutputStream()); // 遍历文件 for (int i=0;i<subs.length;i++) { File f=subs[i]; try { zos.putNextEntry(new ZipEntry(f.getName())); fis = new FileInputStream(f); byte[] buffer = new byte[1024]; int r = 0; while ((r = fis.read(buffer)) != -1) { zos.write(buffer, 0, r); } fis.close(); } catch (IOException e) { logger.error("压缩文件"+f.getName()+"错误:"+e.getLocalizedMessage(),e); } } zos.flush(); zos.close(); } catch (IOException e1) { logger.error("压缩文件错误:"+e1.getLocalizedMessage(),e1); } } /** * 批量从文件服务器下载zip文件 * 2015年12月29日 * By 韩龙 * @param fileName * @param response * @param listAttachment */ public static void zipFileDownload(String fileName,HttpServletResponse response,List<Attachment> listAttachment){ OutputStream os = null; // 封装 List<String> docIds = Lists.newArrayList(); List<Attachment> docIdFiles = Lists.newArrayList(); for (Attachment a : listAttachment) { // 斜杠开头的是chp2.0的数据, if(a.getAttaFilepath().startsWith("/")){ docIdFiles.add(a); }else{ docIds.add(a.getAttaFilepath()); } } try { // response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + seletive.getAttaFilename() +"\"")); // 设置Header信息 // response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=" + getZipFilename(fileName) + ";filename*=UTF-8''" + getZipFilename(fileName)); os = response.getOutputStream(); Map<String,InputStream> map = new HashMap<String,InputStream>(); Map<String,InputStream> fileMap = new HashMap<String,InputStream>(); // 2.0文件是从网盘上下载 if(docIdFiles != null && docIdFiles.size() > 0){ for (Attachment attachment : docIdFiles) { // 放到缓冲流里面 InputStream ins = new FileInputStream(attachment.getAttaFilepath() + "."+attachment.getAttaFileType()); fileMap.put(attachment.getAttaNewfilename(), ins); } } if(docIds != null && docIds.size() > 0){ DmService dmService = DmService.getInstance(); // dmService.download(os, docIds); map = dmService.downloadDocuments(docIds); } map.putAll(fileMap); Zip.zipFiles(os, map); } catch (IOException e1) { logger.error("压缩文件错误:"+e1.getLocalizedMessage(),e1); }finally{ // 关闭流 // try { // os.flush(); // os.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } } /** * 下载压缩包文件名 * 2015年12月10日 * By 韩龙 * @return * @throws UnsupportedEncodingException */ private static String getZipFilename(String baseName) throws UnsupportedEncodingException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd_HH-mm-dd"); Date date = new Date(); String s = baseName +"_"+ sdf.format(date) + ".zip"; return java.net.URLEncoder.encode(s, "utf-8"); } /** * 合成文件 * 2016年1月11日 * By 韩龙 * @param filters * Map key:templateName模板名称 * :parameter 需要参数 * :lendCode 出借编号 * :attaTableId 所属表ID * :attaFlag 文件标识(cjxy:出借合同;bg:变更申请;zr:赎回申请;hkxy:委托划扣;zrsq:债权转让等等) * :attaFileOwner 所属表表名[可选] * :fileName 文件名[可选] * @return * @throws IOException */ public static int compositeFile(Map<String, Object> filters){ int result = 0; String makeFileName = filters.get("fileName")==null?"1":filters.get("fileName").toString(); String httpUrl = Constant.getProperties.get("template_cpt_url"); String signType = filters.get("signType")==null?"":filters.get("signType").toString(); // 获取参数模板Url if(filters.get("templateName") !=null ){ String fileName = Constant.getProperties.get(filters.get("templateName")); httpUrl = httpUrl.replace("reportlet=", "reportlet="+fileName); }else{ // 默认值:收款确认书 String fileName = Constant.getProperties.get(ReportType.SKQRS_HK.getCode()); httpUrl = httpUrl.replace("reportlet=", "reportlet="+fileName); } // 获取每个模板需要的参数,并拼接 String parameter = (String) (filters.get("parameter")==null ? "":filters.get("parameter")); httpUrl = httpUrl +"&"+parameter; //文件类型 String[] flieTypes; if(StringUtils.isNotBlank(StringExUtil.getTrimString(filters.get("flieType")))){ flieTypes = new String[]{filters.get("flieType").toString()}; }else{ // 获取配置要生成文件类型 flieTypes = Constant.getProperties.get("file_type").split(","); } ThreadPool threadPool =ThreadPool.getInstance(); List<Attachment> attachmentLst = new ArrayList<Attachment>(); List<HashMap<String, String>> rehttpList = new ArrayList<HashMap<String, String>>(); for (String flieType : flieTypes) { String rehttpUrl =""; // 获取线程池 String fileName = makeFileName + "." + flieType; Attachment attachment = new Attachment(); attachment.preInsert(); attachment.setAttaId(attachment.getId()); attachment.setAttaFilename(fileName); attachment.setAttaNewfilename(fileName); //出借编号或者客户编号,都存在此字段 attachment.setLoanCode(StringExUtil.getTrimString(filters.get("lendCode"))); attachment.setAttaFileType(flieType); attachment.setDictAttaFlag(StringExUtil.getTrimString(filters.get("attaFlag"))); attachment.setAttaTableId(StringExUtil.getTrimString(filters.get("attaTableId"))); attachment.setAttaFileOwner(StringExUtil.getTrimString(filters.get("attaFileOwner"))); //attachment.setFrom(StringExUtil.getTrimString(filters.get("from"))); attachment.setCreateTime(new Date()); attachment.setCreateBy(UserUtils.getUserId()); String reType = flieType; if(reType.equals("pdf")){ if(filters.containsKey("sendFlag") && filters.get("sendFlag").equals(com.creditharmony.fortune.creditor.matching.constant.Constant.SEND_FLAG_YES)){ attachment.setSendFlag(com.creditharmony.fortune.creditor.matching.constant.Constant.SEND_FLAG_YES); attachment.setTemplateType(filters.get("templateType").toString()); } } if(reType.equals("doc")){ reType = "word"; } attachmentLst.add(attachment); rehttpUrl = httpUrl + "&format="+reType; HashMap<String, String> fileParam = new HashMap<String, String>(); fileParam.put("rehttpUrl", rehttpUrl); fileParam.put("fileName", fileName); rehttpList.add(fileParam); result++; } // 文件合成用, Attachment discardAttachment = filters.get("attachment")==null ? null : (Attachment)filters.get("attachment"); // 放入线程 FileManagement fileManagement = new FileManagement(); DocumentSynthesis DocumentSynthesis = new DocumentSynthesis(attachmentLst,StringExUtil.getTrimString(filters.get("attaTableId")),discardAttachment,StringExUtil.getTrimString(filters.get("from")) ); fileManagement.before(rehttpList,signType,null,filters.get("customerCode").toString(),filters.get("lendCode").toString(), DocumentSynthesis); threadPool.addTask(fileManagement); return result; } }
[ "qiang.guo3@creditharmony.cn" ]
qiang.guo3@creditharmony.cn
b65465a640c0515529298beabc3311290df9cd4d
014986fe5cb02a9b84a395d1125aa83e7f384206
/src/main/java/app/bank/service/TestService.java
f664eaedea63d07a865580d934860ee8e55df733
[]
no_license
wysockikacper98/backend-bank
92a44b721941e25e789cd698d028458ed17fe7b5
4cda8841f60e4fe02219a3c8e029dc46ac7832d2
refs/heads/master
2023-02-27T08:45:35.636272
2021-02-01T13:43:06
2021-02-01T13:43:06
330,437,151
0
0
null
null
null
null
UTF-8
Java
false
false
1,779
java
package app.bank.service; import app.bank.dto.DataFromServer; import app.bank.dto.HerokuSendPayments; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.math.BigDecimal; import java.util.Arrays; @Service public class TestService { public void getDataTest() { RestTemplate restTemplate = new RestTemplate(); String fooResourceURL = "https://jednroz.herokuapp.com/get?id=12121212"; ResponseEntity<DataFromServer[]> response = restTemplate.getForEntity(fooResourceURL, DataFromServer[].class); DataFromServer[] data = response.getBody(); Arrays.stream(data).forEach(temp -> System.out.println(temp.getBankno())); if (response.getStatusCode() == HttpStatus.OK) { System.out.println("OK"); } } //TODO: Nie działa 503 Service Unavailable public void postDataTest() { String fooResourceUrl = "https://jednroz.herokuapp.com/send"; RestTemplate restTemplate = new RestTemplate(); HttpEntity<HerokuSendPayments> request = new HttpEntity<>(new HerokuSendPayments( BigDecimal.valueOf(66.00), "11 1111 1111 1111 1111 1111 1111", "Debited Test Address", "22 1212 1212 2222 2222 2222 2222", "Credited test Address", BigDecimal.valueOf(65.23), "Pierszy testowy przelew")); System.out.println("Przed heroku"); String heroku = restTemplate.postForObject(fooResourceUrl, request, String.class); System.out.println(heroku); } }
[ "wysockikacper98@gmail.com" ]
wysockikacper98@gmail.com
d10c850c934b662ccd37a278fac08f177df62700
f4051f7e6e36dfced76a5d53ad24e8b69902adf4
/health_parent/health_common/src/main/java/com/cwj/health/constant/RedisMessageConstant.java
834b2b14e54bd6168614266af74cab66c656b33a
[]
no_license
cwj584062461/health102
36ad0daff7473ec59e4c84caa0a34c8b01fbab60
5a48e47709a1923b6f90d9b9e2da8ee85a9c4ab3
refs/heads/master
2023-01-05T15:53:48.024084
2020-11-03T15:30:26
2020-11-03T15:30:26
306,558,916
0
0
null
null
null
null
UTF-8
Java
false
false
370
java
package com.cwj.health.constant; public interface RedisMessageConstant { static final String SENDTYPE_ORDER = "001";//用于缓存体检预约时发送的验证码 static final String SENDTYPE_LOGIN = "002";//用于缓存手机号快速登录时发送的验证码 static final String SENDTYPE_GETPWD = "003";//用于缓存找回密码时发送的验证码 }
[ "584062461@qq.com" ]
584062461@qq.com
6e24dfead9ad7e5d1b7a233a1c4fc54b946153e0
652efc4cdd206b77c5d5dccbdabd290a408a3ddd
/app/src/main/java/app/sunshine/juanjo/views/MyView.java
9800b650e744667be175ad0b671305acfea015d3
[ "Apache-2.0" ]
permissive
sasij/Weather-app
fb7658df9fe39d242330dfce61863d105e2e3b1a
cf03a6d8f7df47b7c31f68eda32a77fb9c9d6c8a
refs/heads/master
2016-09-06T17:43:20.293786
2015-02-01T15:57:26
2015-02-01T15:57:26
22,812,616
0
0
null
null
null
null
UTF-8
Java
false
false
530
java
package app.sunshine.juanjo.views; import android.content.Context; import android.util.AttributeSet; import android.view.View; /** * Created by juanjo on 28/08/14. */ public class MyView extends View { public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defaultStyle) { super(context, attrs, defaultStyle); } protected void onMeasure(int wMeasureSpec, int hMeasureSpec) { } }
[ "juanjo@JuanjosMac.local" ]
juanjo@JuanjosMac.local
4c020cca0df8a2988ab0614639dcef967e8dcc94
802801a14aa6a3059e4a870458bbf7d9531a89a3
/src/test/java/thread/Animal/Tortoise.java
336987a4f2ef8d5d71fbf4f4485bf7e80b9b240c
[]
no_license
myselfmjs/com-book-web
0fc629858a1a17ef80ab945428bae6e50222f04e
949d19a4f472e62b0b50b6c02d15aa89840ec8b9
refs/heads/master
2021-01-19T02:27:10.171257
2018-12-14T08:07:50
2018-12-14T08:07:50
84,404,031
0
0
null
null
null
null
UTF-8
Java
false
false
904
java
package thread.Animal; /** * @Author: majunsheng * @Date: 2018/4/9 **/ public class Tortoise extends Animal { public Tortoise() { setName("乌龟");// Thread的方法,给线程赋值名字 } // 重写running方法,编写乌龟的奔跑操作 @Override public void runing() { // 跑的距离 double dis = 0.1; length -= dis; if (length <= 0) { length = 0; System.out.println("乌龟获得了胜利"); // 让兔子不要在跑了 if (calltoback != null) { calltoback.win(); } }else{ System.out.println("乌龟跑了" + dis + "米,距离终点还有" + (double)Math.round(length*100)/100 + "米"); } try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }
[ "majunsheng@wondersgroup.com" ]
majunsheng@wondersgroup.com
1b0cbdc5cb25a7d2b66b94147eae26dd0f49450e
520ad8116be1df8b1f900afc631bc78c7f442482
/course/src/util/Calculator.java
add85605b2862f6ffeed7bce4019931f2546c31a
[]
no_license
igorney/javacourse
21a50d36874b6321ab31b87367cf5b87b981a5b7
4fefc4b3e58143fd6abf0ad691c4603f16aefd49
refs/heads/master
2021-05-21T17:08:34.192638
2020-04-29T03:37:51
2020-04-29T03:37:51
252,729,740
1
0
null
null
null
null
UTF-8
Java
false
false
250
java
package util; public class Calculator { public static final double PI = 3.14139; public static double circunference(double radius) { return 2*PI*radius; } public static double volume(double radius) { return 4*PI*radius*radius*radius/3; } }
[ "igorneysantos@gmail.com" ]
igorneysantos@gmail.com
4fe690f22cd73e8c32520355663716682747c6c9
71cf31218c77bae6cfb5e9633bb68972410f3f9e
/Test/de/hawhamburg/hibernate/tests/UniversityDaoTest.java
d41b7c7593ca793bb03f3b3e20c5ff577196790a
[ "Apache-2.0" ]
permissive
serious6/HibernateSimpleProject
aeabe6d167a63bc0669d9a500aca54e1bdf1380a
1a2bd10a87187e61b158fbd029008decf964c313
refs/heads/master
2021-01-02T08:51:46.310842
2014-03-26T20:29:01
2014-03-26T20:29:01
null
0
0
null
null
null
null
ISO-8859-1
Java
false
false
1,481
java
package de.hawhamburg.hibernate.tests; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import de.hawhamburg.hibernate.dao.UniversityDao; import de.hawhamburg.tables.Adress; import de.hawhamburg.tables.Student; import de.hawhamburg.tables.University; public class UniversityDaoTest { private UniversityDao universityDao; @Before public void setUp() throws Exception { this.universityDao = new UniversityDao(); } @After public void tearDown() throws Exception { } @Test public void addUniversity() { University university = new University(); university.setName("TUHH"); university.setAdress(new Adress("Schwarzenbergstraße", "93", "21073", "Hamburg")); universityDao.add(university); Assert.assertNotNull(university.getId()); } @Test public void populateUniversity() { University haw = new University(); haw.setName("HAW Hamburg"); haw.setAdress(new Adress("Berliner Tor", "5", "20099", "Hamburg")); Adress wg1 = new Adress("Jungfernstieg", "1", "20099", "Hamburg"); Student student1 = new Student(); student1.setAdress(wg1); student1.setFirstName("Paul"); student1.setLastName("Paulsen"); student1.setUniversity(haw); Student student2 = new Student(); student2.setAdress(wg1); student2.setFirstName("Paulina"); student2.setLastName("Paulinsen"); student2.setUniversity(haw); haw.addStudent(student1); haw.addStudent(student2); universityDao.add(haw); } }
[ "andre.behrens@haw-hamburg.de" ]
andre.behrens@haw-hamburg.de
b69e0fb47426583cf4ee3584580e9070f990dc5c
30b86c7a3fe6513a8003b5157dffd1f5dda08b38
/core/src/main/java/org/openstack4j/model/storage/block/builder/VolumeTypeBuilder.java
b5cee84239d0602de0e43c3c8de3c43c4ec09358
[ "Apache-2.0" ]
permissive
tanjin861117/openstack4j
c098a25529398855a1391f4d51fc28b687cb8cb6
b58da68654fc7570a3aee3f1eabdf9aef499a607
refs/heads/master
2020-04-06T17:29:04.079837
2018-11-13T13:17:20
2018-11-13T13:17:20
157,660,728
0
0
null
null
null
null
UTF-8
Java
false
false
765
java
package org.openstack4j.model.storage.block.builder; import java.util.Map; import org.openstack4j.common.Buildable.Builder; import org.openstack4j.model.storage.block.VolumeType; public interface VolumeTypeBuilder extends Builder<VolumeTypeBuilder, VolumeType> { /** * See {@link VolumeType#getName()} * * @param name the name of the volume type * @return VolumeTypeBuilder */ VolumeTypeBuilder name(String name); VolumeTypeBuilder description(String Description); /** * See {@link VolumeType#getExtraSpecs()} <b>Optional</b> * * @param extraSpecs Defining extra specs for the volume type as a key-value map. * @return VolumeTypeBuilder */ VolumeTypeBuilder extraSpecs(Map<String, String> extraSpecs); }
[ "tanjin@szzt.com.cn" ]
tanjin@szzt.com.cn
c531c899f34721d1fc4c3b875ca7fcaef97eeb3c
ef695a2d7ec188fd0f237b7647ac3c2c319ab9d2
/app/src/main/java/com/academy/shoplist/data/SingletonShopList.java
f9378aac35bc76339129541fcd5c65e27c106ef7
[]
no_license
JheromeSamson/Shoplist
0d50810a2ce9e9856089847f7b476c001aa9d435
369e25f30752a738bb27b6e62b2659b70b54ec5c
refs/heads/master
2021-03-25T22:14:22.979792
2020-04-02T15:07:38
2020-04-02T15:07:38
247,649,528
1
0
null
null
null
null
UTF-8
Java
false
false
953
java
package com.academy.shoplist.data; import com.academy.shoplist.bean.Prodotto; import java.util.ArrayList; public class SingletonShopList { public ArrayList<Prodotto> prodotto = new ArrayList<>(); private static SingletonShopList instance; public SingletonShopList(){} public static synchronized SingletonShopList getInstance() { if (instance == null){ synchronized (SingletonShopList.class){ if (instance == null) instance = new SingletonShopList(); } } return instance; } public void setProdotto(Prodotto prodotto) { this.prodotto.add(prodotto); } public Prodotto getProdottoByPosition(int position){ return prodotto.get(position); } public void removeProdotto(int position){ this.prodotto.remove(position); } public void setEdit(String toString, String toString1, int position) { } }
[ "jherome.samson90@gmail.com" ]
jherome.samson90@gmail.com
31fdf0cf886018e78898e6a5b01c6f3273889fa2
d26f11c1611b299e169e6a027f551a3deeecb534
/core/filesystem/org/fdesigner/filesystem/provider/FileInfo.java
dc5e844706afdd43119a7a4995058edaafd3dcf1
[]
no_license
WeControlTheFuture/fdesigner-ui
1bc401fd71a57985544220b9f9e42cf18db6491d
62efb51e57e5d7f25654e67ef8b2762311b766b6
refs/heads/master
2020-11-24T15:00:24.450846
2019-12-27T08:47:23
2019-12-27T08:47:23
228,199,674
0
0
null
null
null
null
UTF-8
Java
false
false
6,810
java
/******************************************************************************* * Copyright (c) 2005, 2015 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation * Martin Oberhuber (Wind River) - [170317] add symbolic link support to API *******************************************************************************/ package org.fdesigner.filesystem.provider; import org.fdesigner.filesystem.EFS; import org.fdesigner.filesystem.IFileInfo; import org.fdesigner.filesystem.internal.filesystem.local.LocalFileNativesManager; /** * This class should be used by file system providers in their implementation * of API methods that return {@link IFileInfo} objects. * * @since org.eclipse.core.filesystem 1.0 * @noextend This class is not intended to be subclassed by clients. */ public class FileInfo implements IFileInfo { /** * Internal attribute indicating if the file is a directory */ private static final int ATTRIBUTE_DIRECTORY = 1 << 0; /** * Internal attribute indicating if the file exists. */ private static final int ATTRIBUTE_EXISTS = 1 << 16; /** * Bit field of file attributes. Initialized to specify a writable resource. */ private int attributes = EFS.ATTRIBUTE_OWNER_WRITE | EFS.ATTRIBUTE_OWNER_READ; private int errorCode = NONE; /** * The last modified time. */ private long lastModified = EFS.NONE; /** * The file length. */ private long length = EFS.NONE; /** * The file name. */ private String name = ""; //$NON-NLS-1$ /** * The target file name if this is a symbolic link */ private String linkTarget = null; /** * Creates a new file information object with default values. */ public FileInfo() { super(); } /** * Creates a new file information object. All values except the file name * will have default values. * * @param name The name of this file */ public FileInfo(String name) { super(); this.name = name; } /** * Convenience method to clear a masked region of the attributes bit field. * * @param mask The mask to be cleared */ private void clear(int mask) { attributes &= ~mask; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { // We know this object is cloneable. return null; } } /** * @since 1.5 */ @Override public int compareTo(IFileInfo o) { return name.compareTo(o.getName()); } @Override public boolean exists() { return getAttribute(ATTRIBUTE_EXISTS); } /** * @since 1.4 */ @Override public int getError() { return errorCode; } @Override public boolean getAttribute(int attribute) { if (attribute == EFS.ATTRIBUTE_READ_ONLY && isAttributeSuported(EFS.ATTRIBUTE_OWNER_WRITE)) return (!isSet(EFS.ATTRIBUTE_OWNER_WRITE)) || isSet(EFS.ATTRIBUTE_IMMUTABLE); else if (attribute == EFS.ATTRIBUTE_EXECUTABLE && isAttributeSuported(EFS.ATTRIBUTE_OWNER_EXECUTE)) return isSet(EFS.ATTRIBUTE_OWNER_EXECUTE); else return isSet(attribute); } @Override public String getStringAttribute(int attribute) { if (attribute == EFS.ATTRIBUTE_LINK_TARGET) return this.linkTarget; return null; } @Override public long getLastModified() { return lastModified; } @Override public long getLength() { return length; } @Override public String getName() { return name; } @Override public boolean isDirectory() { return isSet(ATTRIBUTE_DIRECTORY); } private boolean isSet(long mask) { return (attributes & mask) != 0; } private void set(int mask) { attributes |= mask; } @Override public void setAttribute(int attribute, boolean value) { if (attribute == EFS.ATTRIBUTE_READ_ONLY && isAttributeSuported(EFS.ATTRIBUTE_OWNER_WRITE)) { if (value) { clear(EFS.ATTRIBUTE_OWNER_WRITE | EFS.ATTRIBUTE_OTHER_WRITE | EFS.ATTRIBUTE_GROUP_WRITE); set(EFS.ATTRIBUTE_IMMUTABLE); } else { set(EFS.ATTRIBUTE_OWNER_WRITE | EFS.ATTRIBUTE_OWNER_READ); clear(EFS.ATTRIBUTE_IMMUTABLE); } } else if (attribute == EFS.ATTRIBUTE_EXECUTABLE && isAttributeSuported(EFS.ATTRIBUTE_OWNER_EXECUTE)) { if (value) set(EFS.ATTRIBUTE_OWNER_EXECUTE); else clear(EFS.ATTRIBUTE_OWNER_EXECUTE | EFS.ATTRIBUTE_GROUP_EXECUTE | EFS.ATTRIBUTE_OTHER_EXECUTE); } else { if (value) set(attribute); else clear(attribute); } } private static boolean isAttributeSuported(int value) { return (LocalFileNativesManager.getSupportedAttributes() & value) != 0; } /** * Sets whether this is a file or directory. * * @param value <code>true</code> if this is a directory, and <code>false</code> * if this is a file. */ public void setDirectory(boolean value) { if (value) set(ATTRIBUTE_DIRECTORY); else clear(ATTRIBUTE_DIRECTORY); } /** * Sets whether this file or directory exists. * * @param value <code>true</code> if this file exists, and <code>false</code> * otherwise. */ public void setExists(boolean value) { if (value) set(ATTRIBUTE_EXISTS); else clear(ATTRIBUTE_EXISTS); } /** * Sets the error code indicating whether an I/O error was encountered when accessing the file. * * @param errorCode {@link IFileInfo#IO_ERROR} if this file has an I/O error, * and {@link IFileInfo#NONE} otherwise. * @since 1.4 */ public void setError(int errorCode) { this.errorCode = errorCode; } @Override public void setLastModified(long value) { lastModified = value; } /** * Sets the length of this file. A value of {@link EFS#NONE} * indicates the file does not exist, is a directory, or the length could not be computed. * * @param value the length of this file, or {@link EFS#NONE} */ public void setLength(long value) { this.length = value; } /** * Sets the name of this file. * * @param name The file name */ public void setName(String name) { if (name == null) throw new IllegalArgumentException(); this.name = name; } /** * Sets or clears a String attribute, e.g. symbolic link target. * * @param attribute The kind of attribute to set. Currently only * {@link EFS#ATTRIBUTE_LINK_TARGET} is supported. * @param value The String attribute, or <code>null</code> to clear * the attribute * @since org.eclipse.core.filesystem 1.1 */ public void setStringAttribute(int attribute, String value) { if (attribute == EFS.ATTRIBUTE_LINK_TARGET) this.linkTarget = value; } /** * For debugging purposes only. */ @Override public String toString() { return name; } }
[ "491676539@qq.com" ]
491676539@qq.com
ac9a453c01c57270d269cd4d12cb91d96d033644
d0760db729e7fe9e3839a5e432182f65dd654a0c
/JSF_OMS/src/java/consumo/campanasListar.java
2b573f9484727c14a6662d47074b2278946a7277
[]
no_license
PICA-2016/PICA_OMS
33220967ca3614c5c586c8e84048e000bd500d39
cf48b936301e604b0fb7140c89bfaad5ed191a41
refs/heads/master
2021-01-18T21:40:19.220002
2016-06-01T07:08:37
2016-06-01T07:08:37
52,056,977
0
0
null
null
null
null
UTF-8
Java
false
false
3,186
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 consumo; import com.pica.dss.campanas.AdministrarCampanas; import com.pica.dss.campanas.CampanaCons; import com.pica.dss.campanas.DataServiceFault; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.xml.ws.WebServiceRef; /** * * @author GermanO */ @ManagedBean(name="beanListarCampanas") //@Named(value = "beanConsultaProductos") @ViewScoped public class campanasListar implements java.io.Serializable { @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/10.85.0.100_9766/services/administrarCampanas.wsdl") private AdministrarCampanas service; private List<CampanaCons> listaCampanas; private String estado; private String campana; private String IDCAMPANA; @PostConstruct public void init() { listaCampanas = this.listaCampanas(); } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public List<CampanaCons> listaCampanas() { System.out.println("hola"); try { List<CampanaCons> lista = new ArrayList<>(); listaCampanas = wsConsultaCampana("A"); for (CampanaCons campanaCons : listaCampanas) { System.out.println("Campanas : " + campanaCons.getNOMBRE()); } } catch (DataServiceFault ex) { System.out.println("error"); } return listaCampanas; } private java.util.List<com.pica.dss.campanas.CampanaCons> wsConsultaCampana(java.lang.String estado) throws DataServiceFault { // Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe. // If the calling of port operations may lead to race condition some synchronization is required. com.pica.dss.campanas.AdministrarCampanasPortType port = service.getSOAP11Endpoint(); return port.wsConsultaCampana(estado); } public List<CampanaCons> getListaCampanas() { return listaCampanas; } public void setListaCampanas(List<CampanaCons> listaCampanas) { this.listaCampanas = listaCampanas; } public void action(String IDCAMPANA) { try { System.out.println("germano - "+IDCAMPANA); FacesContext.getCurrentInstance().getExternalContext().redirect("registrar_campanhias_productos.xhtml"); } catch (IOException ex) { // do something here } } public String getCampana() { return campana; } public void setCampana(String IDCAMPANA) { System.out.println("2 - IDCAMPANA "+IDCAMPANA); this.campana = IDCAMPANA; } }
[ "GermanO@GermanO-2.local" ]
GermanO@GermanO-2.local
e3bb6b46bc4068d76d188ad08e3b3dd2bfaf0680
09f245c2fe54c1d21230e5f95136f140cca19552
/app/src/test/java/com/example/lesson6ps/ExampleUnitTest.java
57f3a67a1970d5ff59bdfc61f186ed4fb4697bfd
[]
no_license
cheerful4ever/lesson6Ps
d9619ddf8b1b0065ab6de9a1e4e93cac6d16fbaa
59397d8962714ac0831ae1689fe1737cdf65d2c1
refs/heads/master
2022-09-22T19:41:06.381825
2020-05-28T15:28:14
2020-05-28T15:28:14
267,531,492
0
0
null
null
null
null
UTF-8
Java
false
false
382
java
package com.example.lesson6ps; 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() { assertEquals(4, 2 + 2); } }
[ "18016375@myrp.edu.sg" ]
18016375@myrp.edu.sg
443e5038db77d85d0780fbc210dacbd7a0bee40b
95e944448000c08dd3d6915abb468767c9f29d3c
/sources/com/p280ss/android/ugc/aweme/i18n/language/initial/C30486f.java
23a8f4f5b41234c3225695b3e82dbbad796f4bdf
[]
no_license
xrealm/tiktok-src
261b1faaf7b39d64bb7cb4106dc1a35963bd6868
90f305b5f981d39cfb313d75ab231326c9fca597
refs/heads/master
2022-11-12T06:43:07.401661
2020-07-04T20:21:12
2020-07-04T20:21:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
715
java
package com.p280ss.android.ugc.aweme.i18n.language.initial; import android.content.Context; import java.util.concurrent.Callable; /* renamed from: com.ss.android.ugc.aweme.i18n.language.initial.f */ final /* synthetic */ class C30486f implements Callable { /* renamed from: a */ private final C30483e f80095a; /* renamed from: b */ private final Context f80096b; /* renamed from: c */ private final String[] f80097c; C30486f(C30483e eVar, Context context, String[] strArr) { this.f80095a = eVar; this.f80096b = context; this.f80097c = strArr; } public final Object call() { return this.f80095a.mo80160a(this.f80096b, this.f80097c); } }
[ "65450641+Xyzdesk@users.noreply.github.com" ]
65450641+Xyzdesk@users.noreply.github.com
48c705f3b57973821d1920eccd44f17b432389be
b17e8b87a21877e2c0208065b0303de7cbec4a04
/OOPC/2102 Examples/dec01/BoxingTimingExample.java
43d642c09a4b93963728bc54ba2b7f7aa6eb3f01
[]
no_license
jaithakai91/egreer-wpi
63b799c7fc54cd638c35b8086d6cc71beb37e8f9
628122efb2b717c3906cafffdd1ba0f9ecea3136
refs/heads/master
2023-04-18T14:31:35.452030
2011-03-06T06:31:39
2011-03-06T06:31:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,014
java
package dec01; /** * Show timing issues for boxing/unboxing * * @author heineman */ public class BoxingTimingExample { /** * @param args */ public static void main(String[] args) { // What is the only visible difference here? Integer x, y; int a, b; long start, end; start = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { a = 99; b = 137; a = a + b; } end = System.currentTimeMillis(); System.out.println ("Time required for int arithmetic: " + (end - start)); // Is there any reason why it is 20x slower? Yes! start = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { x = 99; // equivalent to x = new Integer(99); y = 137; // equivalent to y = new Integer(137); x = x + y; // equivalent to x = new Integer (x.intValue() + y.intValue()); } end = System.currentTimeMillis(); System.out.println ("Time required for Integer arithmetic: " + (end - start)); } }
[ "greer.eric@gmail.com" ]
greer.eric@gmail.com
e0e4f7b990c9898e86ad13fd49bd72b05e7a01d4
ffab662510188b94ef74acf32463ed5d8ea192ee
/com.work.tour/src/com/tour/work/dao/DAO.java
3fcd8c19f7a1e129e699ac41448a0e92c19409cd
[]
no_license
better-space/first-jsp-project
fb6b3bc9ec58b0229a4ea96c778180e9f58801dc
5c769a01f58e21e22f66cbec8f8245ede9ff1895
refs/heads/master
2021-07-02T21:49:43.457732
2017-09-25T05:33:51
2017-09-25T05:33:51
104,705,413
1
0
null
null
null
null
GB18030
Java
false
false
1,065
java
/** package com.tour.work.dao; import java.sql.Connection; import java.sql.DriverManager; public class DAO { private Connection conn = null; public Connection getConn(){ try { Class.forName("com.hxtt.sql.access.AccessDriver"); String url = "jdbc:Access:/d:/Database/Database1.mdb"; conn = DriverManager.getConnection(url,"",""); } catch (Exception e) { e.printStackTrace(); } return conn; } } **/ //连接mysql package com.tour.work.dao; import java.sql.Connection; import java.sql.DriverManager; public class DAO { private Connection conn = null; public Connection getConn(){ String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/com.tour.work?useUnicode=true&characterEncoding=utf-8&useSSL=false"; String password = "suhe5059"; String user = "root"; try{ Class.forName(driver); conn = DriverManager.getConnection(url, user, password); if(conn!=null){ System.out.println("成功连接mysql数据库"); } }catch(Exception e){ e.printStackTrace(); } return conn; } }
[ "1758181331@qq.com" ]
1758181331@qq.com
9009f72daf419bc21eef09ed8b76a717eb2d10e8
ed9138bc0d1291163a386124fa467d52e0fb7f3f
/Pos2Books/src/se/budohoor/economics/pos2books/plugins/books/economic/types/CashBookGetData.java
1ba2885195c1e2ee7ae0c5194d4bf44cb659ec60
[]
no_license
odie37/pos-2-books
56a06439e9e072d8bea2e747d65ef3dad3349709
cbec64fef1d7abb48d948b3adc2f8be36e09cf19
refs/heads/master
2016-09-10T10:37:04.105489
2015-01-04T19:11:32
2015-01-04T19:11:32
28,779,078
0
0
null
null
null
null
UTF-8
Java
false
false
1,522
java
package se.budohoor.economics.pos2books.plugins.books.economic.types; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entityHandle" type="{http://e-conomic.com}CashBookHandle" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "entityHandle" }) @XmlRootElement(name = "CashBook_GetData") public class CashBookGetData { protected CashBookHandle entityHandle; /** * Gets the value of the entityHandle property. * * @return * possible object is * {@link CashBookHandle } * */ public CashBookHandle getEntityHandle() { return entityHandle; } /** * Sets the value of the entityHandle property. * * @param value * allowed object is * {@link CashBookHandle } * */ public void setEntityHandle(CashBookHandle value) { this.entityHandle = value; } }
[ "mattias.fritzson@gmail.com" ]
mattias.fritzson@gmail.com
c2fcf3b4fb6bd9e8e93e98a75875b43c666911c0
e8f1aa2776ea471c8857f13d579aef27a55ba2c8
/src/main/java/pl/kamilpchelka/codecool/datastructures/exceptions/StackOverflow.java
aa13ffc4bcc6fd00326325ccbcde53c5c604ab91
[]
no_license
KamilPchelka/Data-Structures-in-Java
8a35cbfca7595ab985bc175f8d89623f8c36c4ef
2703a2b3a10e0f2411db9aa2e6d2eef511260271
refs/heads/master
2020-03-13T00:07:42.530673
2018-04-26T11:36:01
2018-04-26T11:36:01
130,880,602
0
0
null
null
null
null
UTF-8
Java
false
false
111
java
package pl.kamilpchelka.codecool.datastructures.exceptions; public class StackOverflow extends Exception { }
[ "siemaeniu500@gmail.com" ]
siemaeniu500@gmail.com
f5a91c6b9483d354721c12899a80a351b8ddc35d
f7cb92ab608774e7384878cc591ddccd0bc46105
/EDA2/eda2/Bebida.java
35692c8efb2cf8bc4086f4ff5593d8bb7d0a54a3
[]
no_license
IgnacioCharlin/proyectoRestaurant
cca192b741d53c6dfeb2a2b9f50b8ad29a63d8a3
853cfa0ef25f5f3f3cc5a695b1326d877961fbbd
refs/heads/main
2023-03-12T22:37:55.414786
2021-03-08T18:59:28
2021-03-08T18:59:28
309,466,111
0
0
null
2020-11-07T20:35:56
2020-11-02T18:54:05
Java
UTF-8
Java
false
false
507
java
package eda2; public class Bebida extends Pedido { private String descripcion; private Double precio; public Bebida(String descripcion, Double precio) { super(); this.descripcion = descripcion; this.precio = precio; } protected String getDescripcion() { return descripcion; } protected void setDescripcion(String descripcion) { this.descripcion = descripcion; } protected Double getPrecio() { return precio; } protected void setPrecio(Double precio) { this.precio = precio; } }
[ "ignaciocharlin1995@gmail.com" ]
ignaciocharlin1995@gmail.com
3f78163239b134dee1a65d38d15666f25825f2a6
9a5636d97342cac48ba02ca424195c7aaed1d599
/DreamUp/src/com/dreamup/project/actions/SupportProList.java
022a14a61c45e4750dd3021fdba91f6485b49610
[]
no_license
plandosee14/DreamUp
bc38b1189c0542cc53cbeb57d89b933222d0bb87
16aabd6d057b356a702a4419d58e55fa3a66dd84
refs/heads/master
2021-01-12T18:10:08.986624
2016-11-07T09:28:04
2016-11-07T09:28:04
71,339,846
1
2
null
null
null
null
UHC
Java
false
false
1,203
java
package com.dreamup.project.actions; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.dreamup.project.dao.ProjectDAO; import com.dreamup.project.dto.ProjectDTO; public class SupportProList extends Action{ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("들어오나"); String m_id = request.getParameter("m_id"); System.out.println("m_id " + m_id ); ProjectDAO dao = new ProjectDAO(); List<ProjectDTO> supportProList; supportProList = dao.selectProjectById(m_id); for (int i = 0; i < supportProList.size(); i++) { System.out.println("여기라고 "); ProjectDTO project = new ProjectDTO(); project = supportProList.get(i); System.out.println(project.toString()); } request.setAttribute("supportProList", supportProList); return mapping.findForward("scs"); } }
[ "rcn115@naver.com" ]
rcn115@naver.com
a78c18cd3e92eeecb8f8218661c82408bc61b899
4877a49854457aa2495d470a5a0f38e4ba9a07d0
/src/main/java/com/restaurant/client/feign/MealFallback.java
52acdf02c3dc671ca3fbc7998ad474372d9afce9
[]
no_license
TulyakovYasha/restaurantclient
f5ae82fad34568759beb1fdc942bc4d211c1bc64
2c2200115608bfdea2122d0c09dac9fedfdbaa92
refs/heads/master
2020-08-20T02:14:39.929457
2019-10-18T08:17:01
2019-10-18T08:17:01
215,975,028
1
0
null
null
null
null
UTF-8
Java
false
false
614
java
package com.restaurant.client.feign; import api.dto.MealDTO; import com.restaurant.client.feign.client.RestaurantFeignClient; import org.springframework.stereotype.Component; @Component public class MealFallback implements RestaurantFeignClient { @Override public MealDTO save(MealDTO mealDTO) { return new MealDTO(); } @Override public MealDTO update(MealDTO mealDTO) { return new MealDTO(); } @Override public MealDTO get(String uuid) { return new MealDTO(); } @Override public boolean delete(String uuid) { return false; } }
[ "Yakov.Tulyakov@alfabank.kiev.ua" ]
Yakov.Tulyakov@alfabank.kiev.ua
09f2e60928f26e741a2197112ab804e008a0ef2f
0679d8f3c153ef1413385466f7d0c7ef7ec401b6
/src/test/java/com/entel/pageInterface/ILoginPage.java
e350037d62dbbbac56150cd54ff58457bac4c6ea
[]
no_license
Anand-qaselenium/entalProject
5d4f3239ed1d7bfef5738e15f4724ab1a6a10456
3a7c0d0e5985c5f48db69e8c97cf564eaeb27aec
refs/heads/master
2022-07-06T08:53:28.475959
2019-12-18T19:01:04
2019-12-18T19:01:04
219,269,046
0
0
null
2022-06-29T17:45:15
2019-11-03T09:00:55
HTML
UTF-8
Java
false
false
72
java
package com.entel.pageInterface; public interface ILoginPage { }
[ "anand.tna@gmail.com" ]
anand.tna@gmail.com
b3863374539fbdccc262dad495adc52fd20540cd
d72e8fe1730a4028c4f14a1892875c281df435cb
/app/src/main/java/test/com/badman/masque/UnpaidFragment.java
2fb21020fdff41b6fd4ba7c0dfd72757749ea601
[]
no_license
asifbu/Masque
4f29f66e4d83334340a719ce685cdf76f35085b1
70c5b2aa932c7e9fe350f7f9f09bccc7b9361a85
refs/heads/master
2020-12-23T14:01:09.106669
2020-03-03T22:29:27
2020-03-03T22:29:27
237,174,010
0
0
null
null
null
null
UTF-8
Java
false
false
123
java
package test.com.badman.masque; import android.support.v4.app.Fragment; public class UnpaidFragment extends Fragment { }
[ "asibulislam.cse3.bu@gmail.com" ]
asibulislam.cse3.bu@gmail.com
958656e506044a24304652d4a654094f54668fbd
704ac47a7ecd2b9f226c5d1b138822f1fcb5c65e
/app/src/androidTest/java/com/abhishek/listview/ExampleInstrumentedTest.java
eff8b616529b366e733ae8a63c43f38ffb7d2743
[]
no_license
abhishekhugetech/Listview-a
1e600b800025e8d9909cef70b94c908989f570fc
237073de8e44260060f4a2b57cb1bf2ca1c982c8
refs/heads/master
2020-03-16T15:29:47.791653
2018-05-09T11:59:25
2018-05-09T11:59:25
132,745,956
0
0
null
null
null
null
UTF-8
Java
false
false
726
java
package com.abhishek.listview; 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.abhishek.listview", appContext.getPackageName()); } }
[ "getexplanation@gmail.com" ]
getexplanation@gmail.com
c07386e3a0545c1df63c8bdd9010ddc248885524
85da22331a0a84b8caeedc63759085cb7f47a2bc
/src/by/tc/nb/bean/FindNoteByContentResponse.java
0ad4cd77e283729faa068ad8face204a82453e19
[]
no_license
davudmurtazin/Task3
17b41d4324ff3fd25da341a1bb2486154fbab614
45d923485d75d82193345047457544abf3459cdc
refs/heads/master
2021-01-11T04:55:20.146185
2016-10-06T08:40:39
2016-10-06T08:40:39
69,977,816
0
0
null
null
null
null
UTF-8
Java
false
false
348
java
package by.tc.nb.bean; import java.util.ArrayList; import by.tc.nb.bean.entity.Note; public class FindNoteByContentResponse extends Response { private ArrayList<Note> foundNotes; public ArrayList<Note> getFoundNotes() { return foundNotes; } public void setFoundNotes(ArrayList<Note> foundNotes) { this.foundNotes = foundNotes; } }
[ "dav.murtazin@gmail.com" ]
dav.murtazin@gmail.com
20473388ab6bebfe47143dea72bad7b3b1a0bb62
8016a44f22755c0f9a6624d36683832eb76649f8
/StubProgram.java
b15a579cca2732544fc76b92a46a13adb6a7f6b4
[]
no_license
BenHilderman/ISC4U-Unit-2-01
b83c54449f69ec165e795f300be151c9afb2ecf0
20d0c583437efa594642e56e78800ef76c4c940e
refs/heads/master
2022-04-10T02:20:23.731570
2020-03-24T17:26:12
2020-03-24T17:26:12
249,771,819
0
0
null
null
null
null
UTF-8
Java
false
false
987
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class StubProgram { /** * StubProgram uses MrCoxallStack. */ public static void main(String[] args) { // program lets users add items to the MrCoxallStack MrCoxallStack anStack = new MrCoxallStack(); String anItem; InputStreamReader r = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(r); Scanner input = new Scanner(System.in); System.out.println("Enter the amount of items you want in the stack:"); int stackNumber = input.nextInt(); for (int lockNumber = 0; lockNumber < stackNumber; lockNumber++) { System.out.println("Enter an item to the stack"); try { anItem = br.readLine(); anStack.push(anItem); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
[ "benjaminhilderman@mths.ca" ]
benjaminhilderman@mths.ca
35bca990a368f1fcfe52827bab00fde44563ebac
975bb97bb3ef51a53f2850b633fc0ab6efa27707
/src/main/java/net/kear/recipeorganizer/persistence/dto/RecipeMessageDto.java
cbdf95e192e7aea2215c0393047c907a2eccf38f
[]
no_license
lwkear/recipeorganizer
3fa06cca5a64125b80792cea2d4829296ea2f25e
c7e28dc7a70d482f4b86b1b396786b690f562b99
refs/heads/master
2020-04-05T13:15:27.455233
2018-11-19T15:12:50
2018-11-19T15:12:50
154,981,796
0
0
null
null
null
null
UTF-8
Java
false
false
2,725
java
package net.kear.recipeorganizer.persistence.dto; import java.io.Serializable; import java.util.Arrays; import net.kear.recipeorganizer.enums.ApprovalAction; import net.kear.recipeorganizer.enums.ApprovalReason; public class RecipeMessageDto implements Serializable { private static final long serialVersionUID = 1L; private long toUserId; private long recipeId; private String recipeName; private ApprovalAction action; private ApprovalReason[] reasons; private String message; public RecipeMessageDto() {} public RecipeMessageDto(long toUserId, long recipeId, String recipeName, ApprovalAction action, ApprovalReason[] reasons, String message) { super(); this.toUserId = toUserId; this.recipeId = recipeId; this.recipeName = recipeName; this.action = action; this.reasons = reasons; this.message = message; } public long getToUserId() { return toUserId; } public void setToUserId(long toUserId) { this.toUserId = toUserId; } public long getRecipeId() { return recipeId; } public void setRecipeId(long recipeId) { this.recipeId = recipeId; } public String getRecipeName() { return recipeName; } public void setRecipeName(String recipeName) { this.recipeName = recipeName; } public ApprovalAction getAction() { return action; } public void setAction(ApprovalAction action) { this.action = action; } public ApprovalReason[] getReasons() { return reasons; } public void setReasons(ApprovalReason[] reasons) { this.reasons = reasons; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((action == null) ? 0 : action.hashCode()); result = prime * result + (int) (recipeId ^ (recipeId >>> 32)); result = prime * result + (int) (toUserId ^ (toUserId >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RecipeMessageDto other = (RecipeMessageDto) obj; if (action != other.action) return false; if (recipeId != other.recipeId) return false; if (toUserId != other.toUserId) return false; return true; } @Override public String toString() { return "RecipeMessageDto [toUserId=" + toUserId + ", recipeId=" + recipeId + ", recipeName=" + recipeName + ", action=" + action + ", reasons=" + Arrays.toString(reasons) + ", message=" + message + "]"; } }
[ "kear.larry@gmail.com" ]
kear.larry@gmail.com
50fab60319807dba71739158a3e9b34c6cb42007
798f8e3a90e39c55eeebae251e0dc497c2ca8d91
/src/main/java/com/ss/editor/tree/generator/tree/node/BranchesParametersTreeNode.java
1ff29f6d3b8b3065733d6e0927cac1d2436ecd3b
[ "Apache-2.0" ]
permissive
JavaSaBr/jmb-tree-generator
39166cffc4dee38a986ee15aff259843059f6266
94ccb18b4824ccc9e1fa7bcb5bf243db6e1926ba
refs/heads/master
2021-01-20T06:47:07.781072
2018-05-21T03:41:46
2018-05-21T03:41:46
101,517,524
3
1
Apache-2.0
2018-05-21T03:39:18
2017-08-26T22:53:52
Java
UTF-8
Java
false
false
2,227
java
package com.ss.editor.tree.generator.tree.node; import com.ss.editor.annotation.FromAnyThread; import com.ss.editor.annotation.FxThread; import com.ss.editor.tree.generator.PluginMessages; import com.ss.editor.tree.generator.parameters.BranchesParameters; import com.ss.editor.tree.generator.tree.action.CreateBranchAction; import com.ss.editor.ui.control.tree.NodeTree; import com.ss.editor.ui.control.tree.node.TreeNode; import com.ss.rlib.common.util.array.Array; import com.ss.rlib.common.util.array.ArrayFactory; import javafx.collections.ObservableList; import javafx.scene.control.MenuItem; import org.jetbrains.annotations.NotNull; /** * The implementation of presentation branches parameters node in the {@link ParametersTreeNode} * * @author JavaSaBr */ public class BranchesParametersTreeNode extends ParametersTreeNode<BranchesParameters> { public BranchesParametersTreeNode(@NotNull BranchesParameters element, long objectId) { super(element, objectId); } @Override @FromAnyThread public @NotNull String getName() { return PluginMessages.TREE_GENERATOR_EDITOR_NODE_BRANCHES; } @Override @FxThread public @NotNull Array<TreeNode<?>> getChildren(@NotNull NodeTree<?> nodeTree) { var branchesParameters = getElement(); var treeParameters = branchesParameters.getTreeParameters(); var children = ArrayFactory.<TreeNode<?>>newArray(TreeNode.class); var branches = treeParameters.getBranches(); for (var branch : branches) { children.add(FACTORY_REGISTRY.createFor(branch)); } for (var i = 0; i < children.size(); i++) { var node = (BranchParametersTreeNode) children.get(i); node.setName(PluginMessages.TREE_GENERATOR_EDITOR_NODE_BRANCH + " #" + i); } return children; } @Override @FxThread public void fillContextMenu(@NotNull NodeTree<?> nodeTree, @NotNull ObservableList<MenuItem> items) { super.fillContextMenu(nodeTree, items); items.add(new CreateBranchAction(nodeTree, this)); } @Override @FxThread public boolean hasChildren(@NotNull NodeTree<?> nodeTree) { return true; } }
[ "javasabr@gmail.com" ]
javasabr@gmail.com
29c250f32a1df789a56ccce31059eeac33923ff5
0874d515fb8c23ae10bf140ee5336853bceafe0b
/l2j-universe-lindvior/Lindvior Source/gameserver/src/main/java/l2p/gameserver/model/base/EnchantSkillLearn.java
9f393b6c52d5400575b8d2c0aa5e09071d5187f7
[]
no_license
NotorionN/l2j-universe
8dfe529c4c1ecf0010faead9e74a07d0bc7fa380
4d05cbd54f5586bf13e248e9c853068d941f8e57
refs/heads/master
2020-12-24T16:15:10.425510
2013-11-23T19:35:35
2013-11-23T19:35:35
37,354,291
0
1
null
null
null
null
UTF-8
Java
false
false
11,164
java
package l2p.gameserver.model.base; import l2p.gameserver.model.Player; import l2p.gameserver.tables.SkillTable; public final class EnchantSkillLearn { // these two build the primary key private final int _id; private final int _level; // not needed, just for easier debug private final String _name; private final String _type; private final int _baseLvl; private final int _maxLvl; private final int _minSkillLevel; private int _costMul; public EnchantSkillLearn(int id, int lvl, String name, String type, int minSkillLvl, int baseLvl, int maxLvl) { _id = id; _level = lvl; _baseLvl = baseLvl; _maxLvl = maxLvl; _minSkillLevel = minSkillLvl; _name = name.intern(); _type = type.intern(); _costMul = _maxLvl == 15 ? 5 : 1; } /** * @return Returns the id. */ public int getId() { return _id; } /** * @return Returns the level. */ public int getLevel() { return _level; } /** * @return Returns the minLevel. */ public int getBaseLevel() { return _baseLvl; } /** * @return Returns the minSkillLevel. */ public int getMinSkillLevel() { return _minSkillLevel; } /** * @return Returns the name. */ public String getName() { return _name; } public int getCostMult() { return _costMul; } /** * @return Returns the spCost. */ /** * @return Returns the spCost. */ public int[] getCost() { if (_maxLvl == 10) return SkillTable.getInstance().getInfo(_id, 1).isOffensive() ? _priceAwakening[_level % 100] : _priceAwakening[_level % 100]; else return SkillTable.getInstance().getInfo(_id, 1).isOffensive() ? _priceCombat[_level % 100] : _priceBuff[_level % 100]; } /** * Шанс заточки скилов 2й профы */ private static final int[][] _chance = {{}, //76 77 78 79 80 81 82 83 84 85 {82, 92, 97, 97, 97, 97, 97, 97, 97, 97}, // 1 {80, 90, 95, 95, 95, 95, 95, 95, 95, 95}, // 2 {78, 88, 93, 93, 93, 93, 93, 93, 93, 93}, // 3 {52, 76, 86, 91, 91, 91, 91, 91, 91, 91}, // 4 {50, 74, 84, 89, 89, 89, 89, 89, 89, 89}, // 5 {48, 72, 82, 87, 87, 87, 87, 87, 87, 87}, // 6 {01, 46, 70, 80, 85, 85, 85, 85, 85, 85}, // 7 {01, 44, 68, 78, 83, 83, 83, 83, 83, 83}, // 8 {01, 42, 66, 76, 81, 81, 81, 81, 81, 81}, // 9 {01, 01, 40, 64, 74, 79, 79, 79, 79, 79}, // 10 {01, 01, 38, 62, 72, 77, 77, 77, 77, 77}, // 11 {01, 01, 36, 60, 70, 75, 75, 75, 75, 75}, // 12 {01, 01, 01, 34, 58, 68, 73, 73, 73, 73}, // 13 {01, 01, 01, 32, 56, 66, 71, 71, 71, 71}, // 14 {01, 01, 01, 30, 54, 64, 69, 69, 69, 69}, // 15 {01, 01, 01, 01, 28, 52, 62, 67, 67, 67}, // 16 {01, 01, 01, 01, 26, 50, 60, 65, 65, 65}, // 17 {01, 01, 01, 01, 24, 48, 58, 63, 63, 63}, // 18 {01, 01, 01, 01, 01, 22, 46, 56, 61, 61}, // 19 {01, 01, 01, 01, 01, 20, 44, 54, 59, 59}, // 20 {01, 01, 01, 01, 01, 18, 42, 52, 57, 57}, // 21 {01, 01, 01, 01, 01, 01, 16, 40, 50, 55}, // 22 {01, 01, 01, 01, 01, 01, 14, 38, 48, 53}, // 23 {01, 01, 01, 01, 01, 01, 12, 36, 46, 51}, // 24 {01, 01, 01, 01, 01, 01, 01, 10, 34, 44}, // 25 {01, 01, 01, 01, 01, 01, 01, 8, 32, 42}, // 26 {01, 01, 01, 01, 01, 01, 01, 06, 30, 40}, // 27 {01, 01, 01, 01, 01, 01, 01, 01, 04, 28}, // 28 {01, 01, 01, 01, 01, 01, 01, 01, 02, 26}, // 29 {01, 01, 01, 01, 01, 01, 01, 01, 02, 24}, // 30 }; /** * Шанс заточки скилов 3ей профы */ private static final int[][] _chance15 = {{}, //76 77 78 79 80 81 82 83 84 85 {18, 28, 38, 48, 58, 82, 92, 97, 97, 97}, // 1 {01, 01, 01, 46, 56, 80, 90, 95, 95, 95}, // 2 {01, 01, 01, 01, 54, 78, 88, 93, 93, 93}, // 3 {01, 01, 01, 01, 42, 52, 76, 86, 91, 91}, // 4 {01, 01, 01, 01, 01, 50, 74, 84, 89, 89}, // 5 {01, 01, 01, 01, 01, 48, 72, 82, 87, 87}, // 6 {01, 01, 01, 01, 01, 01, 46, 70, 80, 85}, // 7 {01, 01, 01, 01, 01, 01, 44, 68, 78, 83}, // 8 {01, 01, 01, 01, 01, 01, 42, 66, 76, 81}, // 9 {01, 01, 01, 01, 01, 01, 01, 40, 64, 74}, // 10 {01, 01, 01, 01, 01, 01, 01, 38, 62, 72}, // 11 {01, 01, 01, 01, 01, 01, 01, 36, 60, 70}, // 12 {01, 01, 01, 01, 01, 01, 01, 01, 34, 58}, // 13 {01, 01, 01, 01, 01, 01, 01, 01, 32, 56}, // 14 {01, 01, 01, 01, 01, 01, 01, 01, 30, 54}, // 15 }; /** * Шанс заточки скилов 4ей профы */ private static final int[][] _chance10 = {{}, //85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 {85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99},//1 {80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94},//2 {75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89},//3 {70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84},//4 {65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79},//5 {60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74},//6 {30, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69},//7 {25, 26, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64},//8 {20, 21, 22, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59},//9 {15, 16, 17, 18, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54},//10 }; /*TODO: Вынести в ХМЛ, на оффе около 10 видов комбанаций цен.*/ /** * Цена заточки скиллов 3й профессии */ private static final int[][] _priceBuff = {{}, // {51975, 352786}, // 1 {51975, 352786}, // 2 {51975, 352786}, // 3 {78435, 370279}, // 4 {78435, 370279}, // 5 {78435, 370279}, // 6 {105210, 388290}, // 7 {105210, 388290}, // 8 {105210, 388290}, // 9 {132300, 416514}, // 10 {132300, 416514}, // 11 {132300, 416514}, // 12 {159705, 435466}, // 13 {159705, 435466}, // 14 {159705, 435466}, // 15 {187425, 466445}, // 16 {187425, 466445}, // 17 {187425, 466445}, // 18 {215460, 487483}, // 19 {215460, 487483}, // 20 {215460, 487483}, // 21 {243810, 520215}, // 22 {243810, 520215}, // 23 {243810, 520215}, // 24 {272475, 542829}, // 25 {272475, 542829}, // 26 {272475, 542829}, // 27 {304500, 566426}, // 28, цифра неточная {304500, 566426}, // 29, цифра неточная {304500, 566426}, // 30, цифра неточная }; /*TODO: Вынести в ХМЛ, на оффе около 10 видов комбанаций цен.*/ /** * Цена заточки атакующих скиллов */ private static final int[][] _priceCombat = {{}, // {93555, 635014}, // 1 {93555, 635014}, // 2 {93555, 635014}, // 3 {141183, 666502}, // 4 {141183, 666502}, // 5 {141183, 666502}, // 6 {189378, 699010}, // 7 {189378, 699010}, // 8 {189378, 699010}, // 9 {238140, 749725}, // 10 {238140, 749725}, // 11 {238140, 749725}, // 12 {287469, 896981}, // 13 {287469, 896981}, // 14 {287469, 896981}, // 15 {337365, 959540}, // 16 {337365, 959540}, // 17 {337365, 959540}, // 18 {387828, 1002821}, // 19 {387828, 1002821}, // 20 {387828, 1002821}, // 21 {438858, 1070155}, // 22 {438858, 1070155}, // 23 {438858, 1070155}, // 24 {496601, 1142010}, // 25, цифра неточная {496601, 1142010}, // 26, цифра неточная {496601, 1142010}, // 27, цифра неточная {561939, 1218690}, // 28, цифра неточная {561939, 1218690}, // 29, цифра неточная {561939, 1218690}, // 30, цифра неточная }; /** * Цена заточки скилов 4ей профы */ private static final int[][] _priceAwakening = {{}, // {1332450, 2091345}, // 1 {3997349, 6274037}, // 2 {6662250, 10456729}, // 3 {9327150, 14639421}, // 4 {11992050, 18822133}, // 5 {14656950, 23004804}, // 6 {17321850, 27187496}, // 7 {19986750, 31370188}, // 8 {22651650, 35552880}, // 9 {25316550, 39735572}, // 10 }; /** * Шанс успешной заточки */ public int getRate(Player ply) { int level = _level % 100; int chance; switch (_maxLvl) { case 10: { chance = Math.min(_chance10[level].length - 1, ply.getLevel() - 85); return _chance10[level][chance]; } case 15: { chance = Math.min(_chance15[level].length - 1, ply.getLevel() - 76); return _chance15[level][chance]; } default: { chance = Math.min(_chance[level].length - 1, ply.getLevel() - 76); } } return _chance[level][chance]; } public int getMaxLevel() { return _maxLvl; } public String getType() { return _type; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + _id; result = PRIME * result + _level; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; if (!(obj instanceof EnchantSkillLearn)) return false; EnchantSkillLearn other = (EnchantSkillLearn) obj; return getId() == other.getId() && getLevel() == other.getLevel(); } }
[ "jmendezsr@gmail.com" ]
jmendezsr@gmail.com
c59d0fc446bc9055c3288c2074880cba6af6fe99
753f5a8f1d49cadbbab13aeb5c3a84df26b62a19
/app/src/main/java/com/geniuskid/accidentdetector/customViews/NoSwipeViewPager.java
9530d94365b0d74500c04a959d2a00f8178c1107
[]
no_license
itsgeniuS/AccidentDetector
1d81d8c9fe4c9c3434606901dee21a7fbd62525e
cdaf903612da113218d6cac8e88bf5b24d080e10
refs/heads/master
2022-01-28T12:34:31.484467
2019-06-25T16:36:45
2019-06-25T16:36:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,506
java
package com.geniuskid.accidentdetector.customViews; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.Scroller; import java.lang.reflect.Field; public class NoSwipeViewPager extends ViewPager { private String name = "mScroller"; private Context context; public NoSwipeViewPager(Context context) { super(context); this.context = context; setUpScroller(); } public NoSwipeViewPager(Context context, AttributeSet attributeSet) { super(context, attributeSet); setUpScroller(); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return false; } @Override public boolean onTouchEvent(MotionEvent ev) { return false; } private void setUpScroller() { try { Class<?> viewpager = ViewPager.class; Field scroller = viewpager.getDeclaredField(name); scroller.setAccessible(true); scroller.set(this, new MyScroller(context)); } catch (Exception e) { e.printStackTrace(); } } public class MyScroller extends Scroller { MyScroller(Context context) { super(context); } @Override public void startScroll(int startX, int startY, int dx, int dy, int duration) { super.startScroll(startX, startY, dx, dy, 350); } } }
[ "iamgeniuskid7@gmail.com" ]
iamgeniuskid7@gmail.com
5b13c9d7a1a8566c5483cf172e192652be484047
969a1bc148af6b2eebdef2a08ada9cef1fb460d4
/app/src/main/java/ashley/todolist/MainActivity.java
5e2ddbee05d8f6576a32fb66738a7551d6299412
[]
no_license
ashleylau/cs193a-homework-2
7086dd523c19bb7330abc5e1a1f248a46915c986
22729841fd8baae218f937a1c2d6f2281323dbe1
refs/heads/master
2021-01-10T13:58:39.893299
2016-01-25T02:01:46
2016-01-25T02:01:46
50,319,194
0
0
null
null
null
null
UTF-8
Java
false
false
3,398
java
package ashley.todolist; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener { private ArrayList<String> taskItems; private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Restores array list from previous state (if it exists), otherwise creates a new one if (savedInstanceState != null && savedInstanceState.containsKey("savedTasks")){ taskItems = savedInstanceState.getStringArrayList("savedTasks"); } else { taskItems = new ArrayList<>(); } //Initializes the adapter for the listview and the array list adapter = new ArrayAdapter<>( this, R.layout.tasklayout, R.id.task_Item, taskItems ); ListView taskList = (ListView) findViewById(R.id.task_List); taskList.setOnItemLongClickListener(this); taskList.setAdapter(adapter); } /* On pressing the add button, the text is gotten from the EditText field and that text is added to the array list of strings. */ public void addTask(View view) { EditText toDoField = (EditText) findViewById(R.id.userTask); String toDoTask = toDoField.getText().toString(); if (toDoTask.equals("")){ Toast.makeText(MainActivity.this, "Enter some text!", Toast.LENGTH_SHORT).show(); } else { taskItems.add(toDoTask); adapter.notifyDataSetChanged(); toDoField.setText(""); } } /* On a long click, the to-do task is deleted. A message is shown to indicate that to the user. */ @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, "Deleted: " + taskItems.get(position), Toast.LENGTH_SHORT).show(); taskItems.remove(position); adapter.notifyDataSetChanged(); return false; } /* Saves the tasks with the key "savedTasks" */ @Override protected void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putStringArrayList("savedTasks", taskItems); } /*Restores the to-do tasks upon restoration of the activity. This method * also recreates the adapter and list view. */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState){ super.onRestoreInstanceState(savedInstanceState); taskItems = savedInstanceState.getStringArrayList("savedTasks"); adapter = new ArrayAdapter<>( this, R.layout.tasklayout, R.id.task_Item, taskItems ); ListView taskList = (ListView) findViewById(R.id.task_List); taskList.setOnItemLongClickListener(this); taskList.setAdapter(adapter); } }
[ "ablau@stanford.edu" ]
ablau@stanford.edu
75c8d0c0f6f8f9898a363b91b65510ee591359dd
e56afd6c2bcc8d11524909aabeee200155bade02
/app03_library/app/src/main/java/com/choay/library/model/NaverBookDTO.java
f05302d2a5f062bf22251affe46e1b5ab3415deb
[ "Apache-2.0" ]
permissive
dkdud8140/Android
8ee93d000c77d0073add185ef30bb3fb3ce2b9f5
911a77afe19d21ee50f9f47de4e7fdebc62bb5c8
refs/heads/main
2023-07-28T03:26:52.972875
2021-08-23T04:57:57
2021-08-23T04:57:57
389,844,199
0
0
null
null
null
null
UTF-8
Java
false
false
1,851
java
package com.choay.library.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; /** * { * rss : "rss정보", * channer : "컨테이너", * . * . * . * items : [ * { * title : "title", * link : "link", * . * . * . * * } * ] * } */ @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor @Builder public class NaverBookDTO { private String title; // string 검색 결과 문서의 제목을 나타낸다. 제목에서 검색어와 일치하는 부분은 태그로 감싸져 있다. private String link; // string 검색 결과 문서의 하이퍼텍스트 link를 나타낸다. private String image; // string 썸네일 이미지의 URL이다. 이미지가 있는 경우만 나타납난다. private String author; // string 저자 정보이다. private String price; // integer 정가 정보이다. 절판도서 등으로 가격이 없으면 나타나지 않는다. private String discount; // integer 할인 가격 정보이다. 절판도서 등으로 가격이 없으면 나타나지 않는다. private String publisher; // string 출판사 정보이다. private String isbn; // integer ISBN 넘버이다. private String description; // string 검색 결과 문서의 내용을 요약한 패시지 정보이다. 문서 전체의 내용은 link를 따라가면 읽을 수 있다. 패시지에서 검색어와 일치하는 부분은 태그로 감싸져 있다. private String pubdate; // datetime 출간일 정보이다. }
[ "dkdud8140@gmail.com" ]
dkdud8140@gmail.com
8fa7dc7b6479fa8a426959f8e351ec8703541a95
69fd67c1ce860bfe1b92d655fb43083f01f41aa1
/src/TestIO/TestWriter.java
abcd9db045533c4d9f045d2757fe8240d1d28fbf
[]
no_license
maxomnis/java2
f53474e0c381608a3525a790a113dc13f90ffde4
741766c426fa0923e77bc93a9111a3ecf7152897
refs/heads/master
2021-04-09T12:01:59.796504
2020-12-02T07:12:18
2020-12-02T07:12:18
125,476,105
0
0
null
null
null
null
UTF-8
Java
false
false
542
java
package TestIO; import java.io.FileWriter; import java.io.IOException; public class TestWriter { public static void main(String[] args) throws IOException { try { FileWriter fw = new FileWriter("E:/java2/src/TestIO/popm.txt"); fw.write("李商隐\n"); fw.write("李商隐\n"); fw.write("李商隐\n"); fw.write("李商隐\n"); fw.write("李商隐\n"); }catch (Exception e) { e.printStackTrace(); } } }
[ "maxomnis@qq.com" ]
maxomnis@qq.com
336cc94ec30ad3eb15e53c47fdad65d77ecb13be
658596c850cc065b962dd7ff54c556f67fc60f95
/src/test/java/com/spencerwi/either/EitherTest.java
ad41b3909b09fa71c3b81eaca181b08830dba113
[ "MIT" ]
permissive
nokok/Either.java
d0f76936e0e376b6ac697fe5b84536fe3606b296
b54cf5941e62239bca542f8de484c57f203cb3ba
refs/heads/master
2020-12-20T19:57:28.367508
2019-06-27T12:54:40
2019-06-27T12:54:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,164
java
package com.spencerwi.either; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.util.NoSuchElementException; import static org.assertj.core.api.Assertions.assertThat; public class EitherTest { @Test public void canDecideWhichSideToBuild_givenSupplierMethods(){ Either<String, Integer> leftSupplied = Either.either(()->"test", ()->null); assertThat(leftSupplied).isInstanceOf(Either.Left.class); assertThat(leftSupplied.getLeft()).isEqualTo("test"); Either<String, Integer> rightSupplied = Either.either(()->null, ()->42); assertThat(rightSupplied).isInstanceOf(Either.Right.class); assertThat(rightSupplied.getRight()).isEqualTo(42); } @Test public void isRightBiased(){ Either<String,Integer> bothSupplied = Either.either(()->"test", ()->42); assertThat(bothSupplied).isInstanceOf(Either.Right.class); } @Nested @DisplayName("Either.Left") public class EitherLeftTest { @Test public void canBeBuiltAsLeft(){ Either<String, Integer> leftOnly = Either.left("test"); assertThat(leftOnly).isInstanceOf(Either.Left.class); } @Test public void returnsLeftValueWhenAsked(){ Either<String, Integer> leftOnly = Either.left("test"); assertThat(leftOnly.getLeft()).isEqualTo("test"); } @Test public void throwsWhenAskedForRight(){ Either<String, Integer> leftOnly = Either.left("test"); try { leftOnly.getRight(); } catch(NoSuchElementException e){ assertThat(e).hasMessageContaining("Tried to getRight from a Left"); } } @Test public void identifiesAsLeftAndNotAsRight(){ Either<String, Integer> leftOnly = Either.left("test"); assertThat(leftOnly.isLeft()).isTrue(); assertThat(leftOnly.isRight()).isFalse(); } @Test public void executesLeftTransformation_whenFolded(){ Either<String, Integer> leftOnly = Either.left("test"); String result = leftOnly.fold( (leftSide) -> leftSide.toUpperCase(), (rightSide) -> rightSide.toString() ); assertThat(result).isEqualTo("TEST"); } @Test public void executesLeftTransformation_whenMapped(){ Either<String, Integer> leftOnly = Either.left("test"); Either<String, Integer> result = leftOnly.map( (leftSide) -> leftSide.toUpperCase(), (rightSide) -> rightSide * 2 ); assertThat(result).isInstanceOf(Either.Left.class); assertThat(result.getLeft()).isEqualTo("TEST"); } @Test public void runsLeftConsumer_WhenRunIsCalled(){ Either<String, Integer> leftOnly = Either.left("test"); WrapperAroundBoolean leftHasBeenRun = new WrapperAroundBoolean(false); leftOnly.run( left -> { leftHasBeenRun.set(true); }, right -> { /* no-op */ } ); assertThat(leftHasBeenRun.get()).isEqualTo(true); } @Test public void isEqualToOtherLeftsHavingTheSameLeftValue(){ Either<String,Integer> leftIsTest = Either.left("test"); Either<String,Object> leftIsAlsoTest = Either.left("test"); assertThat(leftIsTest).isEqualTo(leftIsAlsoTest); } @Test public void isNotEqualToOtherLeftsHavingDifferentValues(){ Either<String,Integer> leftIsHello = Either.left("hello"); Either<String,Integer> leftIsWorld = Either.left("world"); assertThat(leftIsHello).isNotEqualTo(leftIsWorld); } @Test public void isNotEqualToObjectsOfOtherClasses_obviously(){ String hello = "hello"; Either<String,Integer> leftIsHello = Either.left(hello); assertThat(leftIsHello).isNotEqualTo(hello); } @Test public void hasSameHashCodeAsWrappedLeftValue(){ Either<String, Integer> leftOnly = Either.left("Test"); assertThat(leftOnly.hashCode()).isEqualTo(leftOnly.getLeft().hashCode()); } } @Nested @DisplayName("Either.Right") public class EitherRightTest { @Test public void canBeBuiltAsRight(){ Either<String, Integer> rightOnly = Either.right(42); assertThat(rightOnly).isInstanceOf(Either.Right.class); } @Test public void returnsRightValueWhenAsked(){ Either<String, Integer> rightOnly = Either.right(42); assertThat(rightOnly.getRight()).isEqualTo(42); } @Test public void throwsWhenAskedForLeft(){ Either<String, Integer> rightOnly = Either.right(42); try { rightOnly.getLeft(); }catch(NoSuchElementException e){ assertThat(e).hasMessageContaining("Tried to getLeft from a Right"); } } @Test public void identifiesAsRightAndNotAsLeft(){ Either<String, Integer> rightOnly = Either.right(42); assertThat(rightOnly.isRight()).isTrue(); assertThat(rightOnly.isLeft()).isFalse(); } @Test public void executesRightTransformation_whenFolded(){ Either<String, Integer> rightOnly = Either.right(42); String result = rightOnly.fold( (leftSide) -> leftSide.toUpperCase(), (rightSide) -> rightSide.toString() ); assertThat(result).isEqualTo("42"); } @Test public void executesRightTransformation_whenMapped(){ Either<String, Integer> rightOnly = Either.right(42); Either<String, Integer> result = rightOnly.map( (leftSide) -> leftSide.toUpperCase(), (rightSide) -> rightSide * 2 ); assertThat(result).isInstanceOf(Either.Right.class); assertThat(result.getRight()).isEqualTo(42*2); } @Test public void runsRightConsumer_WhenRunIsCalled(){ Either<String, Integer> rightOnly = Either.right(42); WrapperAroundBoolean rightHasBeenRun = new WrapperAroundBoolean(false); rightOnly.run( left -> { /* no-op */ }, right -> { rightHasBeenRun.set(true); } ); assertThat(rightHasBeenRun.get()).isEqualTo(true); } @Test public void isEqualToOtherRightsHavingTheSameRightValue(){ Either<String,Integer> rightIs42 = Either.right(42); Either<Object,Integer> rightIsAlso42 = Either.right(42); assertThat(rightIs42).isEqualTo(rightIsAlso42); } @Test public void isNotEqualToOtherRightsHavingDifferentValues(){ Either<String,Integer> rightIs42 = Either.right(42); Either<String,Integer> rightIs9001 = Either.right(9001); assertThat(rightIs42).isNotEqualTo(rightIs9001); } @Test public void isNotEqualToObjectsOfOtherClasses_obviously(){ Integer fortyTwo = 42; Either<String,Integer> rightIs42 = Either.right(fortyTwo); assertThat(rightIs42).isNotEqualTo(fortyTwo); } @Test public void hasSameHashCodeAsWrappedRightValue(){ Either<String, Integer> rightOnly = Either.right(42); assertThat(rightOnly.hashCode()).isEqualTo(rightOnly.getRight().hashCode()); } } public static class WrapperAroundBoolean { private boolean value; public WrapperAroundBoolean(){ this.value = false; } public WrapperAroundBoolean(boolean value) { this.value = value; } public void set(boolean value){ this.value = value; } public boolean get(){ return this.value; } } }
[ "spencerwi@gmail.com" ]
spencerwi@gmail.com
ae30019aaad3e9b5cfef1eec4d6e1df42119c9b0
7cb0d799781dee02c1653041fb71283593084c28
/app/src/main/java/com/kongtiaoapp/xxhj/adapter/MyZhenduanAdapter.java
46b32990e4952d1a5111183a280997c054685d18
[]
no_license
guochengabc/xxhj_project
2a7a41f000dc7c6512d93c83a641e6dd7a531a87
b6588be8e5c9436f88873e085a76c3241193a8c1
refs/heads/master
2020-09-21T13:09:44.562591
2020-01-19T09:17:05
2020-01-19T09:17:05
224,797,254
0
0
null
null
null
null
UTF-8
Java
false
false
2,031
java
package com.kongtiaoapp.xxhj.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.kongtiaoapp.xxhj.R; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by 桂飞 on 2016/11/4. */ public class MyZhenduanAdapter extends BaseAdapter { private List<String> list; private Context context; private List<Integer> list_image; public MyZhenduanAdapter( Context context) { this.context = context; notifyDataSetChanged(); } public void setList(List<String> list, List<Integer> list_image) { this.list = list; this.list_image = list_image; notifyDataSetChanged(); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolers viewholers = null; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.item_zhenduan, parent, false); viewholers = new ViewHolers(convertView); convertView.setTag(viewholers); } else { viewholers = (ViewHolers) convertView.getTag(); } viewholers.txt_zhenduan.setText(list.get(position).toString()); viewholers.image_summer.setImageResource(list_image.get(position)); return convertView; } class ViewHolers { @BindView(R.id.txt_zhenduan) TextView txt_zhenduan; @BindView(R.id.image_summer) ImageView image_summer; public ViewHolers(View view) { ButterKnife.bind(this, view); } } }
[ "guochengabc@163.com" ]
guochengabc@163.com
7906d09fd7e14d65e96211bf3ae73c3d35635b16
c8be6f80fdf7dcc2a71e29c9ae82d845a7a6eb88
/Algorithm/七大排序算法/SelectSort.java
ed11435646dbba85b86575f98d2359016f99dc4a
[]
no_license
cloudy-liu/BDSA
35be50ab83c39b86d2d213cfbcb9f5d23513d01f
af0ccbbe61e943cc60918f36e276a7e368105cf9
refs/heads/master
2021-06-11T07:08:30.724833
2021-03-21T15:12:16
2021-03-21T15:12:16
137,571,843
1
0
null
null
null
null
UTF-8
Java
false
false
1,206
java
/** * Author: cloudy * Date : 2018-6-14 */ package com.my.test; public class SelectSort extends BaseSort{ public void selectSort(int[] data) {//升序排序 int len = data.length; for (int i = 0; i < len; i++) { int minIndex = i; //初始化假定i为最小值的索引 for (int j = i + 1; j < len; j++) {//从 i+1处,开始寻找最小值的索引 if (data[minIndex] > data[j]) { minIndex = j; } } if (minIndex != i) { //比较一轮下来后,minIndex位置若发生变化,交换 swap(data, minIndex, i); } } } public static void main(String[] args) { for (int i = 0; i < BaseSort.data.length; i++) { BaseSort.beforeSort(BaseSort.data[i]); SelectSort sort = new SelectSort(); sort.selectSort(BaseSort.data[i]); BaseSort.afterSort(BaseSort.data[i]); } } } /* Before Sort 10 9 8 7 6 5 5 4 3 2 1 0 After Sort 0 1 2 3 4 5 5 6 7 8 9 10 Before Sort 1 2 3 4 5 5 6 7 After Sort 1 2 3 4 5 5 6 7 Before Sort 1 7 3 5 0 0 2 4 8 6 After Sort 0 0 1 2 3 4 5 6 7 8 */
[ "cloudy-liuu@gmail.com" ]
cloudy-liuu@gmail.com
6be5b83ff944c0abff326a3d2b3008116b765861
15400fe0b8a7f7e3b4fb368bae6d94b56f49d2f7
/src/com/sanushi/junit/basics/BankAccountTest.java
dc2a16794b41db515d8b45804f37b7bc961dd919
[]
no_license
Sanushi-Salgado/Java-Unit-Testing-With-JUnit
80a686a4d7b65f381c7c2d6d1c9fe06e1f18d7b4
381cd2baab0474cadb22567b4393ae8d9ee06535
refs/heads/master
2022-10-09T09:47:31.299979
2020-06-08T06:19:23
2020-06-08T06:19:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,328
java
package com.sanushi.junit.basics; import org.junit.*; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.fail; public class BankAccountTest { private static int count; private BankAccount bankAccount; @BeforeClass public static void beforeClass() { System.out.println("Starting to execute BankAccountTest. Count: " + count); } @Before public void setup() { bankAccount = new BankAccount("San", "Sal", 1000.00, BankAccount.CHECKING); System.out.println("Running Utilities test..."); } @Test public void deposit() throws Exception { // fail("This method has not yet been implemented"); double balance = bankAccount.deposit(200.00, true); assertEquals(1200.00, balance, 0); } @Test public void withdraw_branch() throws Exception { double balance = bankAccount.withdraw(600.00, true); assertEquals(400, balance, 0); } @Test (expected = IllegalArgumentException.class) public void withdraw_notBranch() throws Exception { // The test actually passes. We want the method to throw an IllegalArgumentException. bankAccount.withdraw(600.00, false); // In older versions of JUnit the following was done // try { // bankAccount.withdraw(600.00, true); // fail("Invalid withdrawal"); // }catch (IllegalArgumentException e){ // // } } @Test public void getBalance_deposit() throws Exception { bankAccount.deposit(200.00, true); assertEquals(1200.00, bankAccount.getBalance(), 0); } @Test public void getBalance_withdraw() throws Exception { bankAccount.withdraw(200.00, true); assertEquals(800.00, bankAccount.getBalance(), 0); } @Test public void isChecking_true() throws Exception { // assertEquals(true, bankAccount.isChecking()); assertTrue("This account is not Utilities checking account", bankAccount.isChecking()); } @After public void tearDown() { System.out.println("Count: " + count++); } @AfterClass public static void afterClass() { System.out.println("Completed executing BankAccountTest. Count: " + count); } }
[ "sanushisalgado@gmail.com" ]
sanushisalgado@gmail.com
22236ae35924b3b8e89e0e7bc0fc0f15aa3403d1
5f75cab8e7daf127e84fb7ac2cf4d2b77a232333
/src/main/java/com/OtherFunctionality/PreparedStatementDemo.java
da777f9377f35492415c83b67ba8e9695f272e5a
[]
no_license
qaamishra/Jdbc
cd931d2280fc4831e6ee8abb92f3c6473d6e87d8
a622bfcd20a81632ed584f05f763e74c48b578ec
refs/heads/master
2020-05-31T20:02:15.544700
2017-06-12T02:25:46
2017-06-12T02:25:46
94,046,851
0
0
null
null
null
null
UTF-8
Java
false
false
1,153
java
package com.OtherFunctionality; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; class PreparedStatementDemo { public static void main(String args[]) throws SQLException { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url="jdbc:odbc:mydsn1"; Properties p=new Properties(); p.put("user", "Rohit"); p.put("password","Kumar"); Connection con=DriverManager.getConnection(url,p); System.out.print("Connection Established...."); PreparedStatement ps= con.prepareStatement("insert into Employee (eid,ename,esal,edesg) values(?,?,?,?)"); System.out.println("hiii"); ps.setInt(1,109); ps.setString(2, "KIRRAANNN"); ps.setInt(3, 500000); ps.setString(4, "DIRECTOR"); System.out.println(" hiiiiiiiiiii"); int count = ps.executeUpdate(); System.out.println(" hiiiiiiiiiii"); System.out.println(count +"row(s) inserted"); //ps.close(); // stmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } }
[ "mishra.techie@gmail.com" ]
mishra.techie@gmail.com
dd71b452f09539ad25e0f47b2b568542b92a4ba2
500f87ac5a998010a9712d131c23578f62cce763
/app/src/main/java/com/example/sqlcipherexample/LogUtils.java
9661dde6692a158c19d17759f93d661265ed338d
[]
no_license
YogeshD25/Keystore-Demo
e8121b74770bdfb6394b868505f111141eb79d03
3d5319a6d9e0b16e450b1cd8220bc81d0f2bf19f
refs/heads/master
2020-12-13T21:25:25.455496
2020-01-21T10:57:25
2020-01-21T10:57:25
234,534,139
0
0
null
null
null
null
UTF-8
Java
false
false
282
java
package com.example.sqlcipherexample; import android.util.Log; public class LogUtils { public static final String tag = "Keystore API Android"; public static void debug( String message) { if (BuildConfig.DEBUG) { Log.d(tag, message); } } }
[ "dandeyogesh25@gmail.com" ]
dandeyogesh25@gmail.com
87049475f1bd5e3b3e2234317f75b3e12bfdd135
b6a1e0d93f51b037375beaf81975e255400cf1f8
/wear/src/main/java/com/kimjio/mealviewer/widget/SelectMenuAdapter.java
7bcf8fb77bf384dd3453bf149d5a9efcc1f092be
[]
no_license
Kimjio/MealViewer
ddb361bd337c552406efdba2b405a5b0d395363e
8c7704fce85a813b9ab2595d0a25fc6d2dd11f51
refs/heads/master
2021-07-06T06:05:45.231539
2020-09-20T09:23:54
2020-09-20T09:23:54
184,378,135
1
0
null
null
null
null
UTF-8
Java
false
false
9,424
java
package com.kimjio.mealviewer.widget; import android.app.Activity; import android.content.Intent; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Observer; import androidx.recyclerview.widget.RecyclerView; import androidx.wear.widget.WearableRecyclerView; import com.kimjio.handwritingfix.HandwritingHelper; import com.kimjio.mealviewer.R; import com.kimjio.mealviewer.activity.SchoolSearchActivity; import com.kimjio.mealviewer.activity.SubSelectActivity; public class SelectMenuAdapter extends WearableRecyclerView.Adapter<SelectMenuViewHolder> { private static final int REQ_COUNTRY = 2; private static final int REQ_SCHOOL_TYPE = 3; public static final int REQ_SEARCH = 4; private static final int TYPE_TITLE = 0; private static final int TYPE_EDITABLE = 1; private OpenSearchListener searchListener; private OpenSubMenuListener menuListener; private OnOpenOnPhoneClickListener oopListener; private MutableLiveData<CharSequence> countryData = new MutableLiveData<>(); private MutableLiveData<CharSequence> schoolTypeData = new MutableLiveData<>(); private Observer<CharSequence> countryObserver; private Observer<CharSequence> schoolTypeObserver; private Observer<CharSequence> searchObserver; private CharSequence country; private CharSequence schoolType = "0"; private CharSequence schoolName = ""; @Override @ViewType public int getItemViewType(int position) { if (position == 2) return TYPE_EDITABLE; return TYPE_TITLE; } @NonNull @Override public SelectMenuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, @ViewType int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.select_menu, parent, false); if (viewType == TYPE_EDITABLE) return new SelectMenuViewHolder(view, true); return new SelectMenuViewHolder(view); } @Override public void onBindViewHolder(@NonNull SelectMenuViewHolder holder, final int position) { holder.binding.title.setEnabled(true); holder.binding.wrapper.setEnabled(true); holder.binding.wrapper.setOnClickListener(null); switch (position) { case 0: holder.binding.title.setText(R.string.select_menu_country); countryData.observeForever(countryObserver = sequence -> { holder.binding.subTitle.setText(sequence); holder.binding.subTitle.setVisibility(View.VISIBLE); }); holder.binding.image.setImageResource(R.drawable.ic_rounded_location); holder.binding.wrapper.setOnClickListener(v -> { Intent intent = new Intent(v.getContext(), SubSelectActivity.class); intent.putExtra(SubSelectActivity.EXTRA_CURRENT_VALUE, country) .putExtra(SubSelectActivity.EXTRA_MENU_ICON, R.drawable.ic_rounded_location) .putExtra(SubSelectActivity.EXTRA_MENUS, R.array.country_educations) .putExtra(SubSelectActivity.EXTRA_MENU_VALUES, R.array.country_education_urls); if (menuListener != null) menuListener.openSubMenu(intent, REQ_COUNTRY); }); break; case 1: holder.binding.title.setText(R.string.select_menu_type); schoolTypeData.observeForever(schoolTypeObserver = sequence -> { holder.binding.subTitle.setText(sequence); holder.binding.subTitle.setVisibility(View.VISIBLE); }); if (schoolTypeData.getValue() == null) schoolTypeData.setValue(holder.itemView.getContext().getText(R.string.all)); holder.binding.image.setImageResource(R.drawable.ic_rounded_school); holder.binding.wrapper.setOnClickListener(v -> { Intent intent = new Intent(v.getContext(), SubSelectActivity.class); intent.putExtra(SubSelectActivity.EXTRA_CURRENT_VALUE, schoolType) .putExtra(SubSelectActivity.EXTRA_MENU_ICON, R.drawable.ic_rounded_school) .putExtra(SubSelectActivity.EXTRA_MENUS, R.array.school_type) .putExtra(SubSelectActivity.EXTRA_MENU_VALUES, SubSelectActivity.VALUE_IS_INDEX); if (menuListener != null) menuListener.openSubMenu(intent, REQ_SCHOOL_TYPE); }); break; case 2: holder.binding.titleEditable.setHint(R.string.hint_school_name); holder.binding.titleEditable.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { schoolName = s; } @Override public void afterTextChanged(Editable s) { } }); holder.binding.subTitle.setVisibility(View.GONE); new HandwritingHelper().attachToTextView(holder.binding.titleEditable); holder.binding.image.setImageResource(R.drawable.ic_rounded_school_name); break; case 3: holder.binding.title.setText(android.R.string.search_go); holder.binding.title.setEnabled(false); holder.binding.wrapper.setEnabled(false); countryData.observeForever(searchObserver = sequence -> { holder.binding.title.setEnabled(true); holder.binding.wrapper.setEnabled(true); }); holder.binding.subTitle.setVisibility(View.GONE); holder.binding.image.setImageResource(R.drawable.ic_rounded_search); holder.binding.wrapper.setOnClickListener(v -> { Intent intent = new Intent(v.getContext(), SchoolSearchActivity.class); intent.putExtra(SchoolSearchActivity.EXTRA_LOCAL_DOMAIN, country) .putExtra(SchoolSearchActivity.EXTRA_SCHOOL_TYPE, schoolType) .putExtra(SchoolSearchActivity.EXTRA_SCHOOL_NAME, schoolName); if (searchListener != null) searchListener.openSearch(intent, REQ_SEARCH); }); break; case 4: holder.binding.title.setText(R.string.common_open_on_phone); holder.binding.subTitle.setVisibility(View.GONE); holder.binding.image.setImageResource(R.drawable.ic_rounded_open_on_phone); holder.binding.wrapper.setOnClickListener(v -> { if (oopListener != null) oopListener.onOpenOnPhoneClick(); }); break; default: break; } } public void setOpenSubMenuListener(OpenSubMenuListener menuListener) { this.menuListener = menuListener; } public void setOpenSearchListener(OpenSearchListener searchListener) { this.searchListener = searchListener; } public void setOnOpenOnPhoneClickListener(OnOpenOnPhoneClickListener oopListener) { this.oopListener = oopListener; } @Override public int getItemCount() { /* 지역 타입 이름 Edit 검색 Butt OOP Butt */ return 5; } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { CharSequence title = data.getCharSequenceExtra(SubSelectActivity.RESULT_MENU_TITLE); CharSequence value = data.getCharSequenceExtra(SubSelectActivity.RESULT_MENU_VALUE); switch (requestCode) { case REQ_COUNTRY: country = value; countryData.setValue(title); break; case REQ_SCHOOL_TYPE: schoolType = value; schoolTypeData.setValue(title); break; } } } @Override public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); countryData.removeObserver(countryObserver); schoolTypeData.removeObserver(schoolTypeObserver); } public interface OpenSearchListener { void openSearch(Intent data, int requestCode); } public interface OpenSubMenuListener { void openSubMenu(Intent data, int requestCode); } public interface OnOpenOnPhoneClickListener { void onOpenOnPhoneClick(); } @IntDef({TYPE_TITLE, TYPE_EDITABLE}) private @interface ViewType { } }
[ "kimjioh0927@gmail.com" ]
kimjioh0927@gmail.com
24074af56e49f6ed84625d2b2777f73e46f30cbb
4688d19282b2b3b46fc7911d5d67eac0e87bbe24
/aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisanalytics/model/transform/DeleteApplicationInputProcessingConfigurationResultJsonUnmarshaller.java
cd1fc77d9c468010c56bb00fe7cc7008580699b3
[ "Apache-2.0" ]
permissive
emilva/aws-sdk-java
c123009b816963a8dc86469405b7e687602579ba
8fdbdbacdb289fdc0ede057015722b8f7a0d89dc
refs/heads/master
2021-05-13T17:39:35.101322
2018-12-12T13:11:42
2018-12-12T13:11:42
116,821,450
1
0
Apache-2.0
2018-09-19T04:17:41
2018-01-09T13:45:39
Java
UTF-8
Java
false
false
1,979
java
/* * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.kinesisanalytics.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.kinesisanalytics.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import static com.fasterxml.jackson.core.JsonToken.*; /** * DeleteApplicationInputProcessingConfigurationResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteApplicationInputProcessingConfigurationResultJsonUnmarshaller implements Unmarshaller<DeleteApplicationInputProcessingConfigurationResult, JsonUnmarshallerContext> { public DeleteApplicationInputProcessingConfigurationResult unmarshall(JsonUnmarshallerContext context) throws Exception { DeleteApplicationInputProcessingConfigurationResult deleteApplicationInputProcessingConfigurationResult = new DeleteApplicationInputProcessingConfigurationResult(); return deleteApplicationInputProcessingConfigurationResult; } private static DeleteApplicationInputProcessingConfigurationResultJsonUnmarshaller instance; public static DeleteApplicationInputProcessingConfigurationResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DeleteApplicationInputProcessingConfigurationResultJsonUnmarshaller(); return instance; } }
[ "" ]
f23cc9b695492b458ea6a6b24b98e5e3cafd2734
34ed6e0a773dd53c4a06cf4e8f0663418df6bb38
/src/main/java/de/herrlock/mfd/elements/Constant.java
d2bcfda9c61b26f145d7adb86f8cf6ff112698cc
[]
no_license
herrlock/MFDParser
f00ae1a4cf8c7c65f6069dfd9c5f27c0e3467dd4
71f692d27c7f578dc1aac2b8f55e269fcfc074d9
refs/heads/master
2016-09-05T16:06:32.578738
2015-12-06T23:29:09
2015-12-06T23:29:09
42,447,889
1
0
null
null
null
null
UTF-8
Java
false
false
1,864
java
package de.herrlock.mfd.elements; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jsoup.nodes.Element; import com.google.common.collect.ImmutableList; /** * A Constant has a type and a value. * * @author HerrLock */ public class Constant extends Component { private static final Logger logger = LogManager.getLogger(); private final String value; private final String datatype; private final List<Target> targets; /** * @param element */ public Constant( final Element element ) { super( element ); logger.entry(); Element constant = element.select( "> data > constant" ).first(); if ( constant == null ) { this.value = ""; this.datatype = ""; } else { this.value = element.attr( "value" ); this.datatype = element.attr( "datatype" ); } List<Target> targets = new ArrayList<>(); for ( Element target : element.select( " > targets > datapoint " ) ) { targets.add( new Target( target ) ); } this.targets = ImmutableList.copyOf( targets ); } public String getValue() { return this.value; } public String getDatatype() { return this.datatype; } public List<Target> getTargets() { return this.targets; } public static final class Target { private final int pos; private final int key; public Target( final Element e ) { this.pos = Integer.parseInt( e.attr( "pos" ) ); this.key = Integer.parseInt( e.attr( "key" ) ); } public int getPos() { return this.pos; } public int getKey() { return this.key; } } }
[ "herrlock@t-online.de" ]
herrlock@t-online.de
5aaa662fb247cc7e3c0f35c9d3fec1bdc65cabe7
b9c3b3cb54032ccf795bbabe4885b12f9f2a3a5e
/src/com/vins/tab/ReportBillsAdapter.java
04c73b0e74e788befa06e496809f9c0149cc2a9c
[]
no_license
vakeeel/BillShareApp
d343fb3054f48abc0ab1986d4e0bfc26bcf97168
766478e48fd51688d4d7746bf36b853bcb6124cf
refs/heads/master
2020-12-25T18:18:32.566478
2012-06-17T09:31:17
2012-06-17T09:31:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,413
java
package com.vins.tab; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.kumulos.android.jsonclient.Kumulos; import com.kumulos.android.jsonclient.ResponseHandler; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public class ReportBillsAdapter extends BaseAdapter { private Context context; private List<FriendsInfo> friendsInfo; private EditText amount; private TextView sharedAmount; public ArrayList<String> sharedPeople; int friendsParticipated = 0; public ReportBillsAdapter(Context context, List<FriendsInfo> friendsInfo, EditText amountTV, TextView sharedAmount) { this.context = context; this.friendsInfo = friendsInfo; this.amount = amountTV; this.sharedAmount = sharedAmount; sharedPeople = new ArrayList<String>(); } @Override public int getCount() { return friendsInfo.size(); } @Override public Object getItem(int position) { return friendsInfo.get(position); } @Override public long getItemId(int position) { return position; } public int pos = 0; @Override public View getView(int position, View convertView, ViewGroup parent) { FriendsInfo info = friendsInfo.get(position); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.reportbills_lv, null); } TextView userName = (TextView) convertView.findViewById(R.id.selectWhoParticipatedTVID); userName.setText(info.getUserEmail()); // Set the onClick Listener on this button final Button btnRemove = (Button) convertView.findViewById(R.id.addRemoveButton); btnRemove.setFocusableInTouchMode(false); btnRemove.setFocusable(false); btnRemove.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("on click"); System.out.println("amount on clicking = " + amount.getText().toString()); LinearLayout layout = (LinearLayout)v.getParent(); TextView tv = (TextView)layout.getChildAt(0); if(btnRemove.getText().toString().equalsIgnoreCase("add")) { friendsParticipated++; double sharedAmountValue = Double.valueOf(amount.getText().toString())/(double)friendsParticipated; sharedAmount.setText(new Double(Math.round(sharedAmountValue*100.0)/100.0).toString()); System.out.println("Add : " + tv.getText().toString()); System.out.println("selected item : " + ((ReportBillsActivity)context).selectedItem); sharedPeople.add(tv.getText().toString()); HashMap<String, String> params = new HashMap<String, String>(); params.put("billid", "xxx"); params.put("email", tv.getText().toString()); params.put("whopaid", ((ReportBillsActivity)context).selectedItem); params.put("amount", "0.0"); Kumulos.call("createShareRecord", params, new ResponseHandler() { @Override public void didCompleteWithResult(Object result) { btnRemove.setText("Remove"); } } ); } else { friendsParticipated--; btnRemove.setText("Add"); double sharedAmountValue = (friendsParticipated <= 0)? 0.0 : Double.valueOf(amount.getText().toString())/(double)friendsParticipated; sharedAmount.setText(new Double(Math.round(sharedAmountValue*100.0)/100.0).toString()); System.out.println("Remove : " + tv.getText().toString()); System.out.println("selected item : " + ((ReportBillsActivity)context).selectedItem); sharedPeople.remove(tv.getText().toString()); HashMap<String, String> params = new HashMap<String, String>(); params.put("billid", "xxx"); params.put("email", tv.getText().toString()); params.put("whopaid", ((ReportBillsActivity)context).selectedItem); Kumulos.call("deleteShareRecord", params, new ResponseHandler() { @Override public void didCompleteWithResult(Object result) { btnRemove.setText("Add"); } } ); } } }); btnRemove.setTag(info); return convertView; } }
[ "vakeeel@gmail.com" ]
vakeeel@gmail.com
d9f471d1af7b80308e236e7f4a2d30bdd847a2a8
d410836fc545fce7745d4c2142fa79abdc9f0611
/src/main/java/bandit/ThompsonSampling.java
57b0f8bc2c77c71ddf21a2ead2d04222af54b26b
[]
no_license
takun2s/bandit
038fb30d444e79b0e3f7b2db4943897b97911b10
8a8911422e67322bd5fd8b6d3608ba8855d4c9c0
refs/heads/master
2020-03-11T17:41:48.461565
2018-04-19T09:53:40
2018-04-19T09:53:40
130,154,492
1
0
null
null
null
null
UTF-8
Java
false
false
737
java
package bandit; import org.apache.commons.math3.distribution.BetaDistribution; /** * Created by takun on 17/04/2018. */ public class ThompsonSampling extends AbstractBandit { public ThompsonSampling(int k) { super(k); } public ThompsonSampling(int k, long seed) { super(k, seed); } protected double[] expections() { double x = random.nextDouble() ; double[] y = new double[k] ; for(int i = 0; i < k; i++) { double a = 1 + cumulateScore(i) ; double b = 1 + trial(i) - cumulateScore(i) ; BetaDistribution beta = new BetaDistribution(a, b) ; y[i] = beta.inverseCumulativeProbability(x) ; } return y ; } }
[ "yongjun.tian@tendcloud.com" ]
yongjun.tian@tendcloud.com