text
stringlengths
10
2.72M
import org.junit.Assert; import org.junit.Test; import java.util.Dictionary; public class ValidadorCustomPredicateTest { @Test public void garantirQueCustomPredicateNaoDeveRetornarInconsistenciasQuandoVerdadeiro() { Validador validador = new Validador(); final Integer n = 5; final String nome = "mauro"; final String sobreNome = "leal"; ICustomPredicate<String, String, Integer> predicado = (String s1, String s2, Integer i) -> s1 != null && s2 != null && s1.length() >= i && s1.length() > s2.length(); Dictionary<String, String> resultado = validador .garantirQue(predicado,nome, sobreNome, n, Mensagem.semIdentificador("Teste", "Valor inválido")) .obterResultado(); Assert.assertTrue(resultado.isEmpty()); } @Test public void garantirQueCustomPredicateDeveRetornarInconsistenciasQuandoFalso() { Validador validador = new Validador(); final Integer n = 5; final String nome = "mauro"; final String sobreNome = "silva"; ICustomPredicate<String, String, Integer> predicado = (String s1, String s2, Integer i) -> s1 != null && s2 != null && s1.length() >= i && s1.length() > s2.length(); Dictionary<String, String> resultado = validador .garantirQue(predicado,nome, sobreNome, n, Mensagem.semIdentificador("Teste", "Valor inválido")) .obterResultado(); Assert.assertNotNull(resultado.get("Teste")); } @Test public void naoPermitirQueCustomPredicateNaoDeveRetornarInconsistenciasQuandoVerdadeiro() { Validador validador = new Validador(); final Integer n = 5; final String nome = "mauro"; final String sobreNome = "leal"; ICustomPredicate<String, String, Integer> predicado = (String s1, String s2, Integer i) -> s1 == null || s2 == null || s1.length() < i || s1.length() <= s2.length(); Dictionary<String, String> resultado = validador .naoPermitirQue(predicado,nome, sobreNome, n, Mensagem.semIdentificador("Teste", "Valor inválido")) .obterResultado(); Assert.assertTrue(resultado.isEmpty()); } @Test public void naoPermitirQueCustomPredicateDeveRetornarInconsistenciasQuandoFalso() { Validador validador = new Validador(); final Integer n = 5; final String nome = "mauro"; final String sobreNome = "silva"; ICustomPredicate<String, String, Integer> predicado = (String s1, String s2, Integer i) -> s1 == null || s2 == null || s1.length() < i || s1.length() <= s2.length(); Dictionary<String, String> resultado = validador .naoPermitirQue(predicado,nome, sobreNome, n, Mensagem.semIdentificador("Teste", "Valor inválido")) .obterResultado(); Assert.assertNotNull(resultado.get("Teste")); } }
package com.example.demo.jpaTest.repository; import java.util.List; import org.springframework.stereotype.Repository; import org.springframework.data.jpa.repository.JpaRepository; import com.example.demo.jpaTest.vo.EmployeeVo; @Repository public interface EmployeeRepository extends JpaRepository<EmployeeVo, Long>{ public List<EmployeeVo> findByEmpNo(long empNo); }
package com.ispl.callses.Fragment; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.provider.ContactsContract; import android.support.v4.app.Fragment; import android.support.v4.widget.DrawerLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.ispl.callses.DB.SqliteDatabase; import com.ispl.callses.MainActivity; import com.ispl.callses.R; import com.ispl.callses.model.FriendContactModel; import com.ispl.callses.utils.CallessUtils; import com.obsez.android.lib.filechooser.ChooserDialog; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import yuku.ambilwarna.AmbilWarnaDialog; import static com.ispl.callses.utils.CallessUtils.mRegistrationLayout; import static com.ispl.callses.utils.CallessUtils.mSettingLayout; import static com.ispl.callses.utils.CallessUtils.rootPath; import static com.ispl.callses.utils.CallessUtils.sBackToMainScreen; import static com.ispl.callses.utils.CallessUtils.sIsSettingChecked; import static com.ispl.callses.utils.CallessUtils.sIsSpeakerChecked; import static com.ispl.callses.utils.CallessUtils.sMainHandler; import static com.ispl.callses.utils.CallessUtils.sMessageBoxText; import static com.ispl.callses.utils.CallessUtils.sMyCustomFontName; import static com.ispl.callses.utils.CallessUtils.sMyCustomFontSize; import static com.ispl.callses.utils.CallessUtils.sScanningInternalBox; import static com.ispl.callses.utils.CallessUtils.sSettingHandler; /** * Created by infinium on 01/08/17. String customFont = "snell-roundhand-black-script.ttf"; */ public class SettingFragment extends Fragment { private LinearLayout mSettingSubLL; private TextView mPhoneNumberTextColorTV, mPhoneNumberBackgroundColorTV, mPhoneNameTextColorTV, mPhoneNameBackgroundColorTV, mMessageShowTV; private EditText mMessageWriteET; private SharedPreferences sharedPreferencesColor, sharedPreferencesCustomFont, sharedPreferencesCustomFontSize; public static final String MyPreferencesColor = "MyPrefsColor", MyPreferencesCustomFont = "MyPrefesCusomFont", MyPreferencesCustomFontSize = "MyPrefesCusomFontSize"; Runnable runnable; int mSpinnerTimeItem = 0, mSpinnerCustomFontName = 0, mSpinnerCustomFontSize = 0, mSpinnerScannigMsgBoxValue = 0; String cambriaBold = "cambriaz.ttf", dancingScriptBold = "DancingScript-Bold.ttf", droidSerifRegular = "DroidSerif-Regular.ttf", fjallaOneRegular = "FjallaOne-Regular.ttf", gillSansMT = "gill-sans-mt.ttf", inconsolataRegular = "Inconsolata-Regular.ttf", lobsterRegular = "Lobster-Regular.ttf", montserratRegular = "Montserrat-Regular.ttf", myriadWebPro = "myriad-web-pro.ttf", snellRoundhandBlackScript = "snell-roundhand-black-script.ttf"; private SqliteDatabase mDatabase; private ProgressDialog mProgressDialog = null; private TextView mProgressTV; private Button mBackUpBtn, mCancelBtn; private String mRestorePath = null; private Dialog mDialog; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View layout_view = inflater.inflate(R.layout.fragment_setting, container, false); sMainHandler.removeCallbacksAndMessages(null); ((MainActivity) getActivity()).setPhoneCallVisibility(false); mSettingLayout.setTag("2"); mRegistrationLayout.setTag("1"); mDatabase = new SqliteDatabase(getContext()); Switch mMainSwitch = (Switch) layout_view.findViewById(R.id.setting_main_switch); Switch mInCallSpeakerSwitch = (Switch) layout_view.findViewById(R.id.in_call_speaker_switch); Spinner mTimeSpinner = (Spinner) layout_view.findViewById(R.id.time_select_spinner); Spinner mCustomFontSpinner = (Spinner) layout_view.findViewById(R.id.custom_font_spinner); Spinner mCustomFontSizeSpinner = (Spinner) layout_view.findViewById(R.id.custom_font_size_spinner); Spinner mScanningIntervalMsgboxSpinner = (Spinner) layout_view.findViewById(R.id.scanning_interval_msgbox_spinner); LinearLayout mPhoneNumberTextColorLL = (LinearLayout) layout_view.findViewById(R.id.phone_number_text_color_ll); LinearLayout mPhoneNumberBackgroundColorLL = (LinearLayout) layout_view.findViewById(R.id.phone_number_background_color_ll); LinearLayout mPhoneNameTextColorLL = (LinearLayout) layout_view.findViewById(R.id.phone_name_text_color_ll); LinearLayout mPhoneNameBackgroundColorLL = (LinearLayout) layout_view.findViewById(R.id.phone_name_background_color_ll); mSettingSubLL = (LinearLayout) layout_view.findViewById(R.id.setting_sub_ll); mPhoneNumberTextColorTV = (TextView) layout_view.findViewById(R.id.phone_number_text_color_picker); mPhoneNumberBackgroundColorTV = (TextView) layout_view.findViewById(R.id.phone_number_background_color_picker); mPhoneNameTextColorTV = (TextView) layout_view.findViewById(R.id.phone_name_text_color_picker); mPhoneNameBackgroundColorTV = (TextView) layout_view.findViewById(R.id.phone_name_bacground_color_picker); mMessageShowTV = (TextView) layout_view.findViewById(R.id.set_msg_box_write_unknown_person); mMessageWriteET = (EditText) layout_view.findViewById(R.id.msg_box_write_unknown_person); Button mBtnConfirmMsg = (Button) layout_view.findViewById(R.id.confirm_msg); Button mBtnResetMsg = (Button) layout_view.findViewById(R.id.reset_msg); Button mImpprtContactBtn = (Button) layout_view.findViewById(R.id.import_contact_btn); Button mBackUpFriendContactBtn = (Button) layout_view.findViewById(R.id.back_up_friend_contact_btn); Button mRestoreFriendContactBtn = (Button) layout_view.findViewById(R.id.restore_friend_contact_btn); sharedPreferencesColor = getActivity().getSharedPreferences(MyPreferencesColor, Context.MODE_PRIVATE); sharedPreferencesCustomFont = getActivity().getSharedPreferences(MyPreferencesCustomFont, Context.MODE_PRIVATE); sharedPreferencesCustomFontSize = getActivity().getSharedPreferences(MyPreferencesCustomFontSize, Context.MODE_PRIVATE); mMessageShowTV.setText(sMessageBoxText); if (sIsSettingChecked) { mMainSwitch.setChecked(true); setMainSwitchOn(mSettingSubLL, true); setTimer(true); } else { mMainSwitch.setChecked(false); setMainSwitchOn(mSettingSubLL, false); setTimer(false); } mMainSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { sIsSettingChecked = isChecked; SharedPreferences.Editor editor = sharedPreferencesCustomFontSize.edit(); editor.putBoolean("Setting_Switch", sIsSettingChecked); editor.apply(); if (sIsSettingChecked) { setMainSwitchOn(mSettingSubLL, true); setTimer(true); } else { setMainSwitchOn(mSettingSubLL, false); setTimer(false); } } }); if (sIsSpeakerChecked) { mInCallSpeakerSwitch.setChecked(true); } else { mInCallSpeakerSwitch.setChecked(false); } mInCallSpeakerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { sIsSpeakerChecked = isChecked; SharedPreferences.Editor editor = sharedPreferencesCustomFontSize.edit(); editor.putBoolean("In_Call_Speaker", sIsSpeakerChecked); editor.apply(); } }); List<Integer> backToMainList = new ArrayList<Integer>(); backToMainList.add(2); backToMainList.add(3); backToMainList.add(4); backToMainList.add(5); backToMainList.add(6); backToMainList.add(7); backToMainList.add(8); backToMainList.add(9); backToMainList.add(10); // Creating adapter for spinner for selecting seconds ArrayAdapter<Integer> backToMainAdapter = new ArrayAdapter<Integer>(getActivity(), android.R.layout.simple_spinner_item, backToMainList); // Drop down layout style - list view with radio button backToMainAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner mTimeSpinner.setAdapter(backToMainAdapter); int spinnerPositionBackToMain = backToMainAdapter.getPosition(sBackToMainScreen); mTimeSpinner.setSelection(spinnerPositionBackToMain); mTimeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { mSpinnerTimeItem = position; SharedPreferences.Editor editor = sharedPreferencesCustomFontSize.edit(); switch (mSpinnerTimeItem) { case 0: sBackToMainScreen = 2; editor.putInt("Back_To_Main", sBackToMainScreen); editor.apply(); break; case 1: sBackToMainScreen = 3; editor.putInt("Back_To_Main", sBackToMainScreen); editor.apply(); break; case 2: sBackToMainScreen = 4; editor.putInt("Back_To_Main", sBackToMainScreen); editor.apply(); break; case 3: sBackToMainScreen = 5; editor.putInt("Back_To_Main", sBackToMainScreen); editor.apply(); break; case 4: sBackToMainScreen = 6; editor.putInt("Back_To_Main", sBackToMainScreen); editor.apply(); break; case 5: sBackToMainScreen = 7; editor.putInt("Back_To_Main", sBackToMainScreen); editor.apply(); break; case 6: sBackToMainScreen = 8; editor.putInt("Back_To_Main", sBackToMainScreen); editor.apply(); break; case 7: sBackToMainScreen = 9; editor.putInt("Back_To_Main", sBackToMainScreen); editor.apply(); break; case 8: sBackToMainScreen = 10; editor.putInt("Back_To_Main", sBackToMainScreen); editor.apply(); break; } } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); List<String> customFontList = new ArrayList<String>(); customFontList.add(cambriaBold); customFontList.add(dancingScriptBold); customFontList.add(droidSerifRegular); customFontList.add(fjallaOneRegular); customFontList.add(gillSansMT); customFontList.add(inconsolataRegular); customFontList.add(lobsterRegular); customFontList.add(montserratRegular); customFontList.add(myriadWebPro); customFontList.add(snellRoundhandBlackScript); // Creating adapter for spinner for selecting seconds final ArrayAdapter<String> customFontAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, customFontList); // Drop down layout style - list view with radio button customFontAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner mCustomFontSpinner.setAdapter(customFontAdapter); int spinnerPositionName = customFontAdapter.getPosition(sMyCustomFontName); mCustomFontSpinner.setSelection(spinnerPositionName); mCustomFontSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View view, int position, long id) { SharedPreferences.Editor editor = sharedPreferencesCustomFont.edit(); mSpinnerCustomFontName = position; switch (mSpinnerCustomFontName) { case 0: sMyCustomFontName = cambriaBold; editor.putString("Custom_Font", sMyCustomFontName); editor.apply(); break; case 1: sMyCustomFontName = dancingScriptBold; editor.putString("Custom_Font", sMyCustomFontName); editor.apply(); break; case 2: sMyCustomFontName = droidSerifRegular; editor.putString("Custom_Font", sMyCustomFontName); editor.apply(); break; case 3: sMyCustomFontName = fjallaOneRegular; editor.putString("Custom_Font", sMyCustomFontName); editor.apply(); break; case 4: sMyCustomFontName = gillSansMT; editor.putString("Custom_Font", sMyCustomFontName); editor.apply(); break; case 5: sMyCustomFontName = inconsolataRegular; editor.putString("Custom_Font", sMyCustomFontName); editor.apply(); break; case 6: sMyCustomFontName = lobsterRegular; editor.putString("Custom_Font", sMyCustomFontName); editor.apply(); break; case 7: sMyCustomFontName = montserratRegular; editor.putString("Custom_Font", sMyCustomFontName); editor.apply(); break; case 8: sMyCustomFontName = myriadWebPro; editor.putString("Custom_Font", sMyCustomFontName); editor.apply(); break; case 9: sMyCustomFontName = snellRoundhandBlackScript; editor.putString("Custom_Font", sMyCustomFontName); editor.apply(); break; } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); List<Integer> fontSizeList = new ArrayList<Integer>(); fontSizeList.add(18); fontSizeList.add(20); fontSizeList.add(22); fontSizeList.add(25); fontSizeList.add(28); fontSizeList.add(30); fontSizeList.add(33); fontSizeList.add(37); // Creating adapter for spinner for selecting seconds ArrayAdapter<Integer> fontSizeAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, fontSizeList); // Drop down layout style - list view with radio button fontSizeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner mCustomFontSizeSpinner.setAdapter(fontSizeAdapter); int spinnerPositionSize = fontSizeAdapter.getPosition(sMyCustomFontSize); mCustomFontSizeSpinner.setSelection(spinnerPositionSize); mCustomFontSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { SharedPreferences.Editor editor = sharedPreferencesCustomFontSize.edit(); mSpinnerCustomFontSize = position; switch (mSpinnerCustomFontSize) { case 0: sMyCustomFontSize = 18; editor.putInt("Custom_Font_Size", sMyCustomFontSize); editor.apply(); break; case 1: sMyCustomFontSize = 20; editor.putInt("Custom_Font_Size", sMyCustomFontSize); editor.apply(); break; case 2: sMyCustomFontSize = 22; editor.putInt("Custom_Font_Size", sMyCustomFontSize); editor.apply(); break; case 3: sMyCustomFontSize = 25; editor.putInt("Custom_Font_Size", sMyCustomFontSize); editor.apply(); break; case 4: sMyCustomFontSize = 28; editor.putInt("Custom_Font_Size", sMyCustomFontSize); editor.apply(); break; case 5: sMyCustomFontSize = 30; editor.putInt("Custom_Font_Size", sMyCustomFontSize); editor.apply(); break; case 6: sMyCustomFontSize = 33; editor.putInt("Custom_Font_Size", sMyCustomFontSize); editor.apply(); break; case 7: sMyCustomFontSize = 37; editor.putInt("Custom_Font_Size", sMyCustomFontSize); editor.apply(); break; } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); List<Integer> msgBoxList = new ArrayList<Integer>(); msgBoxList.add(1); msgBoxList.add(2); msgBoxList.add(3); msgBoxList.add(4); msgBoxList.add(5); msgBoxList.add(6); msgBoxList.add(7); msgBoxList.add(8); msgBoxList.add(9); msgBoxList.add(10); // Creating adapter for spinner for selecting seconds ArrayAdapter<Integer> msgBoxAdapter = new ArrayAdapter<Integer>(getActivity(), android.R.layout.simple_spinner_item, msgBoxList); // Drop down layout style - list view with radio button msgBoxAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner mScanningIntervalMsgboxSpinner.setAdapter(msgBoxAdapter); int spinnerPositionMsgBox = msgBoxAdapter.getPosition(sScanningInternalBox); mScanningIntervalMsgboxSpinner.setSelection(spinnerPositionMsgBox); mScanningIntervalMsgboxSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View view, int position, long id) { SharedPreferences.Editor editor = sharedPreferencesCustomFontSize.edit(); mSpinnerScannigMsgBoxValue = position; switch (mSpinnerScannigMsgBoxValue) { case 0: sScanningInternalBox = 1; editor.putInt("Msg_Box", sScanningInternalBox); editor.apply(); break; case 1: sScanningInternalBox = 2; editor.putInt("Msg_Box", sScanningInternalBox); editor.apply(); break; case 2: sScanningInternalBox = 3; editor.putInt("Msg_Box", sScanningInternalBox); editor.apply(); break; case 3: sScanningInternalBox = 4; editor.putInt("Msg_Box", sScanningInternalBox); editor.apply(); break; case 4: sScanningInternalBox = 5; editor.putInt("Msg_Box", sScanningInternalBox); editor.apply(); break; case 5: sScanningInternalBox = 6; editor.putInt("Msg_Box", sScanningInternalBox); editor.apply(); break; case 6: sScanningInternalBox = 7; editor.putInt("Msg_Box", sScanningInternalBox); editor.apply(); break; case 7: sScanningInternalBox = 8; editor.putInt("Msg_Box", sScanningInternalBox); editor.apply(); break; case 8: sScanningInternalBox = 9; editor.putInt("Msg_Box", sScanningInternalBox); editor.apply(); break; case 9: sScanningInternalBox = 10; editor.putInt("Msg_Box", sScanningInternalBox); editor.apply(); break; } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); mBtnConfirmMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String msg = mMessageWriteET.getText().toString(); if (msg.matches("")) { Toast.makeText(getContext(), "Please enter message ", Toast.LENGTH_SHORT).show(); return; } SharedPreferences.Editor editor = sharedPreferencesCustomFontSize.edit(); sMessageBoxText = msg; mMessageWriteET.getText().clear(); editor.putString("Message_Box_Text", sMessageBoxText); mMessageShowTV.setText(sMessageBoxText); editor.apply(); InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } }); mBtnResetMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences.Editor editor = sharedPreferencesCustomFontSize.edit(); mMessageWriteET.getText().clear(); sMessageBoxText = "Unknown Person"; editor.putString("Message_Box_Text", sMessageBoxText); mMessageShowTV.setText(sMessageBoxText); editor.apply(); InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } }); if (CallessUtils.sPhoneTextColor == 0) { mPhoneNumberTextColorTV.setBackgroundColor(getActivity().getResources().getColor(R.color.black)); } else { mPhoneNumberTextColorTV.setBackgroundColor(CallessUtils.sPhoneTextColor); } if (CallessUtils.sPhoneTextBackground == 0) { mPhoneNumberBackgroundColorTV.setBackgroundColor(getActivity().getResources().getColor(R.color.orange)); } else { mPhoneNumberBackgroundColorTV.setBackgroundColor(CallessUtils.sPhoneTextBackground); } if (CallessUtils.sNameTextColor == 0) { mPhoneNameTextColorTV.setBackgroundColor(getActivity().getResources().getColor(R.color.black)); } else { mPhoneNameTextColorTV.setBackgroundColor(CallessUtils.sNameTextColor); } if (CallessUtils.sNameTextBackground == 0) { mPhoneNameBackgroundColorTV.setBackgroundColor(getActivity().getResources().getColor(R.color.orange)); } else { mPhoneNameBackgroundColorTV.setBackgroundColor(CallessUtils.sNameTextBackground); } mPhoneNumberTextColorLL.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CallessUtils.sBtnTAG = 1; colorPicker(); } }); mPhoneNumberBackgroundColorLL.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CallessUtils.sBtnTAG = 2; colorPicker(); } }); mPhoneNameTextColorLL.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CallessUtils.sBtnTAG = 3; colorPicker(); } }); mPhoneNameBackgroundColorLL.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CallessUtils.sBtnTAG = 4; colorPicker(); } }); mImpprtContactBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialog = new Dialog(getActivity()); mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mDialog.setContentView(R.layout.dialog_backup); mDialog.getWindow().setLayout(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.WRAP_CONTENT); mDialog.setCanceledOnTouchOutside(false); mBackUpBtn = (Button) mDialog.findViewById(R.id.backup_btn); mProgressTV = (TextView) mDialog.findViewById(R.id.progress_tv); mCancelBtn = (Button) mDialog.findViewById(R.id.cancel_btn); mCancelBtn.setVisibility(View.GONE); mBackUpBtn.setVisibility(View.GONE); ImportAsyncTaskRunner runner = new ImportAsyncTaskRunner(); runner.execute(); } }); mBackUpFriendContactBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialog = new Dialog(getActivity()); mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mDialog.setContentView(R.layout.dialog_backup); mDialog.getWindow().setLayout(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.WRAP_CONTENT); mDialog.setCanceledOnTouchOutside(false); mProgressTV = (TextView) mDialog.findViewById(R.id.progress_tv); mBackUpBtn = (Button) mDialog.findViewById(R.id.backup_btn); mCancelBtn = (Button) mDialog.findViewById(R.id.cancel_btn); mBackUpBtn.setVisibility(View.GONE); mCancelBtn.setVisibility(View.GONE); BackUpAsyncTaskRunner runner = new BackUpAsyncTaskRunner(); runner.execute(); } }); mRestoreFriendContactBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialog = new Dialog(getActivity()); mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mDialog.setContentView(R.layout.dialog_backup); mDialog.getWindow().setLayout(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.WRAP_CONTENT); mDialog.setCanceledOnTouchOutside(false); mProgressTV = (TextView) mDialog.findViewById(R.id.progress_tv); mBackUpBtn = (Button) mDialog.findViewById(R.id.backup_btn); mCancelBtn = (Button) mDialog.findViewById(R.id.cancel_btn); mBackUpBtn.setVisibility(View.GONE); mCancelBtn.setVisibility(View.GONE); new ChooserDialog().with(getActivity()) .withStartFile(String.valueOf(Environment.getExternalStorageDirectory())) .withChosenListener(new ChooserDialog.Result() { @Override public void onChoosePath(String path, File pathFile) { mRestorePath = path; RestoreAsyncTaskRunner runner = new RestoreAsyncTaskRunner(); runner.execute(); } }) .build() .show(); } }); return layout_view; } private class ImportAsyncTaskRunner extends AsyncTask<Void, Integer, Void> { @Override protected void onPreExecute() { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(getActivity()); mProgressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress_background)); mProgressDialog.setTitle("Please wait..."); mProgressDialog.setMessage("Contact is Importing ...!!"); mProgressDialog.setCancelable(false); mProgressDialog.show(); } } @Override protected Void doInBackground(Void... params) { int largestListOfOrderDB = mDatabase.getLargestListOfOrder(); int listofOrder = largestListOfOrderDB + 1; ContentResolver contentResolver = getContext().getContentResolver(); Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"); if (cursor.getCount() > 0) { while (cursor.moveToNext()) { String contactId, imageURI = "", contactName, contactMobile = "", contactHome = "", contactWork = ""; int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))); if (hasPhoneNumber > 0) { contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); if (contactName == null) contactName = ""; Cursor phoneCursor = contentResolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{contactId}, null); while (phoneCursor.moveToNext()) { int phoneType = phoneCursor.getInt(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)); switch (phoneType) { case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE: contactMobile = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); break; default: break; } } phoneCursor.close(); // GET IMAGE //------------------------------------------------------------------------------------------------------------------------ Cursor imageCursor = contentResolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{contactId}, null); if (imageCursor.moveToNext()) { imageURI = imageCursor.getString(imageCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI)); } imageCursor.close(); if (contactMobile.equals("") && contactHome.equals("") && contactWork.equals("")) { CallessUtils.v("Phone numger is :- No phone is there "); } else { String newPhoneNumber = contactMobile.replaceAll("[-*#./@%^() ]", ""); String phoneNumber = newPhoneNumber.substring(Math.max(newPhoneNumber.length() - 10, 0)); String listOfOrder = String.valueOf(listofOrder); if (!contactMobile.equals("")) { Boolean isCheck = mDatabase.isExist(phoneNumber); if (!isCheck) { FriendContactModel newFriendContact = new FriendContactModel(imageURI, phoneNumber, contactMobile, contactName, listOfOrder, ""); mDatabase.addFriendContact(newFriendContact); listofOrder++; } } } } } } cursor.close(); return null; } @Override protected void onPostExecute(Void result) { if (mProgressDialog != null) { if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); mProgressDialog = null; } } mDialog.show(); mProgressTV.setText("Importing Contact is Completed"); mCancelBtn.setVisibility(View.VISIBLE); mCancelBtn.setText("Close"); mCancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialog.dismiss(); } }); } } private class BackUpAsyncTaskRunner extends AsyncTask<Void, Integer, Void> { @Override protected void onPreExecute() { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(getActivity()); mProgressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress_background)); mProgressDialog.setTitle("Please wait..."); mProgressDialog.setMessage("Contact is Backing Up ...!!"); mProgressDialog.setCancelable(false); mProgressDialog.show(); } } @Override protected Void doInBackground(Void... params) { int progressStatus = 0; try { Element company = new Element("company"); Document doc = new Document(company); List<FriendContactModel> selectedFriendContactList = mDatabase.listProducts(); for (FriendContactModel model : selectedFriendContactList) { Element contact = new Element("contact"); String id = String.valueOf(model.getID()); contact.setAttribute(new Attribute("id", id)); contact.addContent(new Element("image").setText(model.getFriendImagePath())); contact.addContent(new Element("phone").setText(model.getFriendNumber())); contact.addContent(new Element("phone_show").setText(model.getFriendNumberShow())); contact.addContent(new Element("name").setText(model.getFriendName())); contact.addContent(new Element("list_order").setText(model.getFriendListOfOreder())); contact.addContent(new Element("record_message").setText(model.getFriendAudioMessage())); doc.getRootElement().addContent(contact); progressStatus++; try { Thread.sleep(100); } catch (Exception ignored) { } publishProgress(progressStatus * 100 / selectedFriendContactList.size()); } XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, new FileWriter(rootPath + "/Callses_BackUp.xml")); } catch (IOException io) { System.out.println(io.getMessage()); } return null; } @Override protected void onPostExecute(Void result) { if (mProgressDialog != null) { if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); mProgressDialog = null; } } mDialog.show(); mProgressTV.setText("BackUp Contact is Completed"); mBackUpBtn.setVisibility(View.VISIBLE); mCancelBtn.setVisibility(View.VISIBLE); mBackUpBtn.setText("Send Mail"); mBackUpBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent sendEmail = new Intent(Intent.ACTION_SEND); sendEmail.setType("plain/tex"); sendEmail = new Intent(Intent.ACTION_SENDTO, Uri.fromParts( "mailto", "", null)); sendEmail.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(rootPath + "/Callses_BackUp.xml"))); sendEmail.putExtra(Intent.EXTRA_SUBJECT, "Callses Back Up"); sendEmail.putExtra(Intent.EXTRA_TEXT, "This is contact backup file of Callses App."); startActivity(Intent.createChooser(sendEmail, "Email:")); mDialog.dismiss(); } }); mCancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialog.dismiss(); } }); } } private class RestoreAsyncTaskRunner extends AsyncTask<Void, Integer, Void> { @Override protected void onPreExecute() { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(getActivity()); mProgressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress_background)); mProgressDialog.setTitle("Please wait..."); mProgressDialog.setMessage("Contact is Restoring ...!!"); mProgressDialog.setCancelable(false); mProgressDialog.show(); } } @Override protected Void doInBackground(Void... params) { int progressStatus = 0; Boolean isContactAdded = false; SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(mRestorePath); try { Document document = (Document) builder.build(xmlFile); Element rootNode = document.getRootElement(); List list = rootNode.getChildren("contact"); for (int i = 0; i < list.size(); i++) { isContactAdded = true; Element node = (Element) list.get(i); String image = node.getChildText("image"); String name = node.getChildText("name"); String phone = node.getChildText("phone"); String phone_show = node.getChildText("phone_show"); String listOrder = node.getChildText("list_order"); String record_message = node.getChildText("record_message"); if (!phone.equals("")) { Boolean isCheck = mDatabase.isExist(phone); if (!isCheck) { FriendContactModel newFriendContact = new FriendContactModel(image, phone, phone_show, name, listOrder, record_message); mDatabase.addFriendContact(newFriendContact); } } progressStatus++; try { Thread.sleep(100); } catch (Exception ignored) { } publishProgress(progressStatus * 100 / list.size()); } } catch (IOException | JDOMException io) { System.out.println(io.getMessage()); } if (!isContactAdded) { publishProgress(100); } return null; } @Override protected void onPostExecute(Void result) { if (mProgressDialog != null) { if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); mProgressDialog = null; } } mDialog.show(); mProgressTV.setText("Restoring Contact is Completed"); mCancelBtn.setVisibility(View.VISIBLE); mCancelBtn.setText("Close"); mCancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialog.dismiss(); } }); } } @Override public void onDestroy() { super.onDestroy(); ((MainActivity) getActivity()).getColorFromPrefrances(); ((MainActivity) getActivity()).setPhoneCallData(); ((MainActivity) getActivity()).setPhoneCallVisibility(true); sSettingHandler.removeCallbacksAndMessages(null); mSettingLayout.setTag("1"); } public void colorPicker() { AmbilWarnaDialog dialog = new AmbilWarnaDialog(getActivity(), 0xff0000ff, new AmbilWarnaDialog.OnAmbilWarnaListener() { // Executes, when user click Cancel button @Override public void onCancel(AmbilWarnaDialog dialog) { } @Override public void onOk(AmbilWarnaDialog dialog, int color) { CallessUtils.sDefaultColor = color; setColor(); } }); dialog.show(); } public void setColor() { if (CallessUtils.sBtnTAG == 1) { mPhoneNumberTextColorTV.setBackgroundColor(CallessUtils.sDefaultColor); SharedPreferences.Editor editor = sharedPreferencesColor.edit(); editor.putInt("Phone_Text", CallessUtils.sDefaultColor); editor.apply(); } else if (CallessUtils.sBtnTAG == 2) { mPhoneNumberBackgroundColorTV.setBackgroundColor(CallessUtils.sDefaultColor); SharedPreferences.Editor editor = sharedPreferencesColor.edit(); editor.putInt("Phone_Background", CallessUtils.sDefaultColor); editor.apply(); } else if (CallessUtils.sBtnTAG == 3) { mPhoneNameTextColorTV.setBackgroundColor(CallessUtils.sDefaultColor); SharedPreferences.Editor editor = sharedPreferencesColor.edit(); editor.putInt("Name_Text", CallessUtils.sDefaultColor); editor.apply(); } else if (CallessUtils.sBtnTAG == 4) { mPhoneNameBackgroundColorTV.setBackgroundColor(CallessUtils.sDefaultColor); SharedPreferences.Editor editor = sharedPreferencesColor.edit(); editor.putInt("Name_Background", CallessUtils.sDefaultColor); editor.apply(); } } public void setTimer(Boolean enanle) { if (enanle) { sSettingHandler.removeCallbacksAndMessages(null); } else { runnable = new Runnable() { @Override public void run() { getFragmentManager().popBackStack(); } }; sSettingHandler.postDelayed(runnable, sBackToMainScreen * 1000); } } private static void setMainSwitchOn(ViewGroup layout, Boolean enable) { if (enable) { layout.setEnabled(true); for (int i = 0; i < layout.getChildCount(); i++) { View child = layout.getChildAt(i); if (child instanceof ViewGroup) { setMainSwitchOn((ViewGroup) child, true); } else { child.setEnabled(true); } } } else { layout.setEnabled(false); for (int i = 0; i < layout.getChildCount(); i++) { View child = layout.getChildAt(i); if (child instanceof ViewGroup) { setMainSwitchOn((ViewGroup) child, false); } else { child.setEnabled(false); } } } } }
package com.soft1841.map; import java.util.*; public class StudentTest { public static void main(String[] args) { List<Student> list1 = new ArrayList<>(); list1.add(new Student(1, "黄敬理")); list1.add(new Student(2, "袁腾飞")); List<Student> list2 = new ArrayList<>(); list2.add(new Student(3, "王欢乐")); list2.add(new Student(4, "孟妮")); Map<String, List<Student>> map = new HashMap<>(); map.put("男生", list1); map.put("女生", list2); System.out.println("********按性别输出结果********"); Iterator<Map.Entry<String, List<Student>>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, List<Student>> entry = iterator.next(); System.out.println(entry.getKey()); List<Student> list = entry.getValue(); for (Student s : list) { System.out.println(s.getId() + s.getName()); } } } }
package terusus.avro.protobuf; import com.google.protobuf.DescriptorProtos.*; import com.google.protobuf.Descriptors.*; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; public class ProtobufHelper { public static Descriptor getDescriptor(String descriptorFilename, String messageName) throws Exception { Descriptor result = null; File descriptorFile = new File(descriptorFilename); try (InputStream inputStream = new FileInputStream(descriptorFile)) { FileDescriptorSet fileDescriptorSet = FileDescriptorSet.parseFrom(inputStream); List<FileDescriptorProto> fileDescriptorProtoList = fileDescriptorSet.getFileList(); for (FileDescriptorProto fileDescriptorProto : fileDescriptorProtoList) { result = FileDescriptor .buildFrom(fileDescriptorProto, new FileDescriptor[0]) .findMessageTypeByName(messageName); } } return result; } }
package hw10.task1; public class Book implements Printable { private final String type = "Book"; private String title; public Book(String title) { this.title = title; } public String getType() { return type; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public void print() { System.out.printf("\n%s \n\tTitle:%s", getType(), getTitle()); } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public String toString() { return super.toString(); } }
import java.util.Scanner; /** * Created by saif on 14/09/2016. */ public class Jeu { public static void main(String [] args){ Scanner sc = new Scanner(System.in); System.out.println("Choisissez le nombre de joueurs : "); int choix_joueur=sc.nextInt(); while(choix_joueur < 2){ System.out.println("NoooooP"); System.out.println("Choisissez le nombre de joueurs : "); choix_joueur=sc.nextInt(); } Plateau p=new Plateau(choix_joueur); p.affichage(); while(true){ for(int i=0;i<p.getTab_joueur().length;i++){ System.out.println("A vous de jouer joueur n° : "+(i+1)); System.out.println("Precisez la direction parmi les suivantes : " + "NORD-SUD appuyez sur b et EST-OUEST appuyez sur g"); String d=sc.next(); Direction dir; System.out.print("Precisez les coordonnees i entre 1 et "+p.getTerrain().length+" : "); int k=sc.nextInt(); System.out.print("Precisez les coordonnees j entre 1 et "+p.getTerrain().length+" : "); int h=sc.nextInt(); if(p.getTerrain()[k-1][h-1].getRoute()!=null || p.getTerrain()[k-1][h-1].isVille()){ System.out.println("Rater, cette case est deja occupee. Vous avez ratez votre tour joueur n° "+(i+1)+" ;) "); continue; } if(p.case_Adjacente(k-1,h-1,p.getTab_joueur()[i])){ System.out.println("impossible de relier cette case car il existe 2 case adjacente d'un autre joueur"); while(p.case_Adjacente(k-1,h-1,p.getTab_joueur()[i])){ System.out.print("Precisez les coordonnees i entre 1 et "+p.getTerrain().length+" : "); k=sc.nextInt(); System.out.print("Precisez les coordonnees j entre 1 et "+p.getTerrain().length+" : "); h=sc.nextInt(); } } if(p.coordonnees_Possible(k-1,h-1)) { switch (d) { case "b": dir = Direction.NORD_SUD; if (p.coordonnees_Possible(k,h-1)){ Route route_bas = new Route(dir, p.getTab_joueur()[i], k-1, h-1); p.getTab_joueur()[i].ajouter_Route(route_bas); p.getTerrain()[k-1][h-1].setRoute(route_bas); //p.getTerrain()[k][h-1].setRoute(route_bas); break; } else{ System.out.println("Impossible de relier ces 2 cases NORD-SUD!"); return; } /*case "h": dir=Direction.SUD_NORD; if (p.coordonnees_Possible(k-2,h-1)){ Route route_bas = new Route(dir, p.getTab_joueur()[i], k-1, h-1); p.getTab_joueur()[i].ajouter_Route(route_bas); p.getTerrain()[k-1][h-1].setRoute(route_bas); p.getTerrain()[k-2][h-1].setRoute(route_bas); break; } else{ System.out.println("Impossible de relier ces 2 cases SUD-NORD!"); return; } case "d": dir = Direction.OUEST_EST; if (p.coordonnees_Possible(k-1,h)) { Route route_bas = new Route(dir, p.getTab_joueur()[i], k - 1, h - 1); p.getTab_joueur()[i].ajouter_Route(route_bas); p.getTerrain()[k - 1][h - 1].setRoute(route_bas); p.getTerrain()[k - 1][h].setRoute(route_bas); break; } else{ System.out.println("Impossible de relier ces 2 cases OUEST-EST!"); return; }*/ case "g": dir = Direction.EST_OUEST; if (p.coordonnees_Possible(k-1,h-2)){ Route route_gauche = new Route(dir, p.getTab_joueur()[i], k-1, h-1); p.getTab_joueur()[i].ajouter_Route(route_gauche); p.getTerrain()[k-1][h-1].setRoute(route_gauche); //p.getTerrain()[k-1][h-2].setRoute(route_gauche); break; } else{ System.out.println("Impossible de relier ces 2 cases EST-OUEST!"); return; } default: dir = null; break; } } else{ System.out.println("Coordonnees ne correspondent pas !"); return ; } p.affichage(); } } } }
package com.company; import java.util.ArrayList; import java.util.Date; import java.util.Random; class Miner { private Creator creator; private Block block; private int number; Miner(int number) { this.number = number; } void createBlock() { block = null; creator = new Creator(); creator.start(); } public void interruptCreator() { block = null; creator.interrupt(); } Block getBlock() { return block; } public class Creator extends Thread { @Override public void run() { Singleton blockchain = Singleton.getInstance(new ArrayList<>()); int id, magic; String previousBlock, hashBlock; long timestap, generatingTime; timestap = new Date().getTime(); id = blockchain.getBlocks().size(); if (id == 0) { previousBlock = "0"; } else previousBlock = blockchain.getBlocks().get(id - 1).getHashBlock(); System.out.println(previousBlock); do { magic = new Random().nextInt(100000000); hashBlock = new Sha256().applySha256(previousBlock + magic); } while (new Sha256().Proved(hashBlock, blockchain.getN())); generatingTime = (new Date().getTime() - timestap) / 1000; String threadName = Integer.toString(number); block = new Block(threadName, id, timestap, magic, previousBlock, hashBlock, generatingTime); } } }
package com.trump.auction.trade.model; import lombok.Data; import lombok.ToString; import java.io.Serializable; import java.util.Date; /** * @author Administrator * @date 2018/1/6 */ @Data @ToString public class RobotInfoModel implements Serializable{ /** * 主键 */ private Integer id; /** * 机器人名称 */ private String name; /** * 机器人地址 */ private String address; /** * 机器人状态 1停用 2 启用 */ private Integer status; /** * 开始时间 */ private Date sDate; /** * 结束时间 */ private Date eDate; /** * 机器人使用次数 */ private Integer numbers; /** * 机器人头像 */ private String headImg; }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.appcloud.provisioning.runtime; import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.*; import io.fabric8.kubernetes.api.model.extensions.*; import io.fabric8.kubernetes.client.AutoAdaptableKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.LogWatch; import io.fabric8.kubernetes.client.dsl.PrettyLoggable; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONObject; import org.wso2.appcloud.provisioning.runtime.Utils.KubernetesProvisioningUtils; import org.wso2.appcloud.provisioning.runtime.beans.*; import org.wso2.appcloud.provisioning.runtime.beans.Container; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; /** * This class will implement the runtime provisioning service specific to Kubernetes. */ public class KubernetesRuntimeProvisioningService implements RuntimeProvisioningService { private static final Log log = LogFactory.getLog(KubernetesRuntimeProvisioningService.class); private ApplicationContext applicationContext; private Namespace namespace; private ResourceQuotaLimit resourceQuotaLimit; public KubernetesRuntimeProvisioningService(ApplicationContext applicationContext, ResourceQuotaLimit resourceQuotaLimit) { this.applicationContext = applicationContext; this.namespace = KubernetesProvisioningUtils.getNameSpace(applicationContext); this.resourceQuotaLimit = resourceQuotaLimit; //Creating namespace in kubernetes if not available AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); NamespaceList namespaceList = kubernetesClient.namespaces().list(); boolean isNamespaceExists = false; for (Namespace ns : namespaceList.getItems()) { if (ns.getMetadata().getName().equals(this.namespace.getMetadata().getName())) { isNamespaceExists = true; if (log.isDebugEnabled()) { log.debug("Namespace found: " + ns.getMetadata().getName()); } break; } } if (!isNamespaceExists) { if (log.isDebugEnabled()) { log.debug("Namespace not available hence creating namespace: " + namespace.getMetadata().getName()); } kubernetesClient.namespaces().create(namespace); } } public KubernetesRuntimeProvisioningService(ApplicationContext applicationContext) { this.applicationContext = applicationContext; this.namespace = KubernetesProvisioningUtils.getNameSpace(applicationContext); //Creating namespace in kubernetes if not available AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); NamespaceList namespaceList = kubernetesClient.namespaces().list(); boolean isNamespaceExists = false; for (Namespace ns : namespaceList.getItems()) { if (ns.getMetadata().getName().equals(this.namespace.getMetadata().getName())) { isNamespaceExists = true; if (log.isDebugEnabled()) { log.debug("Namespace found: " + ns.getMetadata().getName()); } break; } } if (!isNamespaceExists) { if (log.isDebugEnabled()) { log.debug("Namespace not available hence creating namespace: " + namespace.getMetadata().getName()); } kubernetesClient.namespaces().create(namespace); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws RuntimeProvisioningException { } @Override public void createOrganization(TenantInfo tenantInfo) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); kubernetesClient.namespaces().create(this.namespace); kubernetesClient.close(); } @Override public void updateOrganization(TenantInfo tenantInfo) throws RuntimeProvisioningException { } @Override public void deleteOrganization(TenantInfo tenantInfo) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); kubernetesClient.namespaces().delete(this.namespace); kubernetesClient.close(); } @Override public void archiveOrganization(TenantInfo tenantInfo) throws RuntimeProvisioningException { } /** * Create Kubernetes Deployment and set of services according to the deployment configuration. * @param config deployment configuration * @return list of created service names * @throws RuntimeProvisioningException */ @Override public List<String> deployApplication(DeploymentConfig config) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubClient = null; List<Container> containers = config.getContainers(); ArrayList<io.fabric8.kubernetes.api.model.Container> kubContainerList = new ArrayList<>(); List<String> serviceNameList = new ArrayList<>(); String cpuLimitInt = resourceQuotaLimit.getCpuLimit(); String cpuLimit = cpuLimitInt.concat("m"); String cpuRequest = resourceQuotaLimit.getCpuRequest().concat("m"); String memoryLimitInt = resourceQuotaLimit.getMemoryLimit(); String memoryLimit = memoryLimitInt.concat("Mi"); String memoryRequest = resourceQuotaLimit.getMemoryRequest().concat("Mi"); try { //Deployment creation for (Container container : containers) { io.fabric8.kubernetes.api.model.Container kubContainer = new io.fabric8.kubernetes.api.model.Container(); kubContainer.setName(container.getContainerName()); kubContainer.setImage(container.getBaseImageName() + ":" + container.getBaseImageVersion()); kubContainer.setImagePullPolicy(KubernetesPovisioningConstants.IMAGE_PULL_POLICY_ALWAYS); ResourceRequirementsBuilder resourceRequirementsBuilder = new ResourceRequirementsBuilder(); ResourceRequirements resourceRequirement = resourceRequirementsBuilder .addToLimits("cpu", new Quantity(cpuLimit)) .addToRequests("cpu", new Quantity(cpuRequest)) .addToLimits("memory", new Quantity(memoryLimit)) .addToRequests("memory", new Quantity(memoryRequest)) .build(); kubContainer.setResources(resourceRequirement); //Checking whether the container is including volume mounts if(container.getVolumeMounts()!= null) { kubContainer.setVolumeMounts(container.getVolumeMounts()); } List<ContainerPort> containerPorts = new ArrayList<>(); List<ServiceProxy> serviceProxies = container.getServiceProxies(); if( serviceProxies != null && serviceProxies.size() > 0) { for (ServiceProxy serviceProxy : serviceProxies) { ContainerPort kubContainerPort = new ContainerPortBuilder() .withContainerPort(serviceProxy.getServiceBackendPort()) .build(); containerPorts.add(kubContainerPort); } } kubContainer.setPorts(containerPorts); if (container.getEnvVariables() != null) { List<EnvVar> envVarList = new ArrayList<>(); for (Map.Entry envVarEntry : container.getEnvVariables().entrySet()) { EnvVar envVar = new EnvVarBuilder() .withName((String) envVarEntry.getKey()) .withValue((String) envVarEntry.getValue()) .build(); envVarList.add(envVar); } kubContainer.setEnv(envVarList); } kubContainerList.add(kubContainer); } PodSpec podSpec = new PodSpecBuilder() .withContainers(kubContainerList) .withVolumes(config.getSecrets()) .build(); PodTemplateSpec podTemplateSpec = new PodTemplateSpecBuilder() .withMetadata(new ObjectMetaBuilder() .withLabels(KubernetesProvisioningUtils.getLableMap(applicationContext)) .build()) .withSpec(podSpec) .build(); DeploymentSpec deploymentSpec = new DeploymentSpecBuilder() .withReplicas(config.getReplicas()) .withTemplate(podTemplateSpec) .build(); Deployment deployment = new DeploymentBuilder() .withKind(KubernetesPovisioningConstants.KIND_DEPLOYMENT) .withMetadata(new ObjectMetaBuilder().withName(config.getDeploymentName().toLowerCase()).build()) .withSpec(deploymentSpec) .build(); //Service creation List<Service> serviceList = new ArrayList<>(); for (Container container : containers) { List<ServiceProxy> serviceProxies = container.getServiceProxies(); for (ServiceProxy serviceProxy : serviceProxies) { Service service = getService(serviceProxy); serviceList.add(service); } } kubClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); //create a new deployement with servies kubClient.inNamespace(namespace.getMetadata().getName()).extensions().deployments().create(deployment); for (Service service : serviceList) { kubClient.inNamespace(namespace.getMetadata().getName()).services().create(service); serviceNameList.add(service.getMetadata().getName()); } } catch (KubernetesClientException e) { String msg = "Error while creating Deployment : " + config.getDeploymentName(); log.error(msg, e); throw new RuntimeProvisioningException(msg, e); } finally { if (kubClient != null) { kubClient.close(); } } return serviceNameList; } /** * Get service with service port and service specification. * @param serviceProxy service information * @return K8s service */ private Service getService(ServiceProxy serviceProxy) { Map<String, String> annotationMap = new HashMap<String, String>(); annotationMap.put(KubernetesPovisioningConstants.ANNOTATION_KEY_HOST, serviceProxy.getAppHostURL()); //Check whether service is https and enable ssl term if (serviceProxy.getServicePort() == KubernetesPovisioningConstants.HTTPS_SERVICE_PORT) { annotationMap.put(KubernetesPovisioningConstants.ANNOTATION_KEY_SSL_TERM, KubernetesPovisioningConstants.ANNOTATION_VALUE_SSL_TERM); } //Enable cookie sticky session annotationMap.put(KubernetesPovisioningConstants.ANNOTATION_KEY_COOKIE_STICKY_SESSION, KubernetesPovisioningConstants.ANNOTATION_VALUE_COOKIE_STICKY_SESSION); ServicePort servicePorts = new ServicePortBuilder().withName(serviceProxy.getServiceName()) .withProtocol(serviceProxy.getServiceProtocol()) .withPort(serviceProxy.getServicePort()) .withTargetPort(new IntOrString(serviceProxy.getServiceBackendPort())).build(); ServiceSpec serviceSpec = new ServiceSpecBuilder() .withSelector(KubernetesProvisioningUtils.getLableMap(applicationContext)) .withPorts(servicePorts) .withSessionAffinity(KubernetesPovisioningConstants.SERVICE_SESSION_AFFINITY_MODE).build(); //Add tenantDomain to label map for the service Map<String, String> labelMap = KubernetesProvisioningUtils.getLableMap(applicationContext); labelMap.put("tenantDomain", applicationContext.getTenantInfo().getTenantDomain()); labelMap.put("exposure-level", applicationContext.getExposureLevel()); //Deployment Unique service name is built using deployment name and the service name. String serviceName = serviceProxy.getServiceName(); return new ServiceBuilder() .withKind(KubernetesPovisioningConstants.KIND_SERVICE) .withSpec(serviceSpec) .withMetadata(new ObjectMetaBuilder() .withName(serviceName.toLowerCase()) .withLabels(labelMap) .withAnnotations(annotationMap).build()).build(); } @Override public boolean getDeploymentStatus(DeploymentConfig config) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubClient = null; DeploymentStatus deploymentStatus = kubClient.inNamespace(namespace.getMetadata().getName()) .extensions().deployments().withName(config.getDeploymentName()).get().getStatus(); //Assuming AF does not do zero replica deployments if (deploymentStatus.getReplicas() > 0) { return true; } return false; } @Override public DeploymentLogStream streamRuntimeLogs() throws RuntimeProvisioningException { DeploymentLogStream deploymentLogStream = new DeploymentLogStream(); Map<String, BufferedReader> logOutPut = new HashMap<>(); AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); PodList podList = KubernetesProvisioningUtils.getPods(applicationContext); if (podList != null) { try { int podCounter = 1; Map<String, LogWatch> watches = new HashMap<>(); for (Pod pod : podList.getItems()) { for (io.fabric8.kubernetes.api.model.Container container : KubernetesHelper.getContainers(pod)) { String logWatchKey = container.getName(); if (log.isDebugEnabled()) { log.debug("Streaming logs in pod : " + pod.getMetadata().getName() + "-" + container .getName()); } LogWatch logs = kubernetesClient.pods().inNamespace(namespace.getMetadata().getName()) .withName(pod.getMetadata().getName()) .inContainer(container.getName()).watchLog(); //logStream should close by after the streaming done in front end //you can use closeLogStream() method in DeploymentStreamLogs BufferedReader logStream = new BufferedReader(new InputStreamReader(logs.getOutput())); logOutPut.put("Replica-" + podCounter + "-" + container.getName(), logStream); deploymentLogStream.setDeploymentLogs(logOutPut); watches.put(logWatchKey, logs); } podCounter++; } deploymentLogStream.setWatches(watches); } catch (KubernetesClientException e) { log.error("Error while streaming runtime logs for application : " + applicationContext.getId() + " tenant domain : " + applicationContext.getTenantInfo().getTenantDomain(), e); throw new RuntimeProvisioningException( "Error while streaming runtime logs for application : " + applicationContext.getId() + " tenant domain : " + applicationContext.getTenantInfo().getTenantDomain(), e); } } else { log.error("Pod list returned as null for application : " + applicationContext.getId() + " tenant domain : " + applicationContext.getTenantInfo().getTenantDomain()); throw new RuntimeProvisioningException( "Pod list returned as null for application : " + applicationContext.getId() + " tenant domain : " + applicationContext.getTenantInfo().getTenantDomain()); } return deploymentLogStream; } @Override public DeploymentLogs getRuntimeLogs(LogQuery query) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); DeploymentLogs deploymentLogs = new DeploymentLogs(); Map<String, String> logOutPut = new HashMap<>(); PrettyLoggable prettyLoggable; PrettyLoggable prettyLoggablePrev = null; PodList podList = KubernetesProvisioningUtils.getPods(applicationContext); if (podList != null) { try { int podCounter = 1; for (Pod pod : podList.getItems()) { for (io.fabric8.kubernetes.api.model.Container container : KubernetesHelper.getContainers(pod)) { //Get logs from last pod if restart count > 0 if(pod.getStatus().getContainerStatuses().size() > 0 && pod.getStatus().getContainerStatuses().get(0).getRestartCount() > 0) { prettyLoggablePrev = kubernetesClient.pods().inNamespace(namespace.getMetadata().getName()) .withName(pod.getMetadata().getName()).terminated(); } //Get logs from current pod if (query == null || (query.getDurationInHours() < 0 && query.getTailingLines() < 0)) { prettyLoggable = kubernetesClient.pods().inNamespace(namespace.getMetadata().getName()) .withName(pod.getMetadata().getName()).inContainer(container.getName()); } else if (query.getDurationInHours() < 0 && query.getTailingLines() > 0) { prettyLoggable = kubernetesClient.pods().inNamespace(namespace.getMetadata().getName()) .withName(pod.getMetadata().getName()).inContainer(container.getName()) .tailingLines(query.getTailingLines()); } else if (query.getDurationInHours() > 0 && query.getTailingLines() < 0) { prettyLoggable = kubernetesClient.pods().inNamespace(namespace.getMetadata().getName()) .withName(pod.getMetadata().getName()).inContainer(container.getName()) .sinceSeconds(query.getDurationInHours() * 3600); } else if (query.getDurationInHours() > 0 && query.getTailingLines() > 0) { prettyLoggable = kubernetesClient.pods().inNamespace(namespace.getMetadata().getName()) .withName(pod.getMetadata().getName()).inContainer(container.getName()) .sinceSeconds(query.getDurationInHours() * 3600) .tailingLines(query.getTailingLines()); } else { log.error("Error in log query while getting snapshot logs of application : " + applicationContext.getId() + " tenant domain : " + applicationContext .getTenantInfo().getTenantDomain()); throw new RuntimeProvisioningException( "Error in log query while getting snapshot logs of application : " + applicationContext.getId() + " tenant domain : " + applicationContext .getTenantInfo().getTenantDomain()); } if (log.isDebugEnabled()) { log.debug("Retrieving logs in pod : " + pod.getMetadata().getName() + "-" + container .getName()); } String logs = ""; if(prettyLoggablePrev != null) { logs = (String) prettyLoggablePrev.getLog(true); } logs += (String) prettyLoggable.getLog(true); logOutPut.put("Replica_" + podCounter + "_" + pod.getMetadata().getName(), logs); deploymentLogs.setDeploymentLogs(logOutPut); } podCounter++; } } catch (KubernetesClientException e) { log.error("Error while getting snapshot logs for application : " + applicationContext.getId() + " tenant domain : " + applicationContext.getTenantInfo().getTenantDomain(), e); throw new RuntimeProvisioningException( "Error while getting snapshot logs for application : " + applicationContext.getId() + " tenant domain : " + applicationContext.getTenantInfo().getTenantDomain(), e); } return deploymentLogs; } else { log.error("Pod list returned as null for application : " + applicationContext.getId() + " tenant domain : " + applicationContext.getTenantInfo().getTenantDomain()); throw new RuntimeProvisioningException( "Pod list returned as null for application : " + applicationContext.getId() + " tenant domain : " + applicationContext.getTenantInfo().getTenantDomain()); } } /** * Set runtime properties to kubernetes environment. * * @param runtimeProperties runtime properties * @param deploymentConfig includes deployment related details * @throws RuntimeProvisioningException */ @Override public void setRuntimeProperties(List<RuntimeProperty> runtimeProperties, DeploymentConfig deploymentConfig) throws RuntimeProvisioningException { runtimeProperties.addAll(getRuntimeProperties()); //list of secretes List secrets = new ArrayList(); //list of env variables HashMap<String, String> envVariables = new HashMap<>(); //create a instance of kubernetes client to invoke service call AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); List<VolumeMount> volumeMounts = new ArrayList<>(); for (RuntimeProperty runtimeProperty : runtimeProperties) { switch (runtimeProperty.getPropertyType()) { case SENSITIVE: if (log.isDebugEnabled()) { String message = "Creating property type secret for the application:" + applicationContext.getId() + " for the tenant domain:" + applicationContext.getTenantInfo().getTenantDomain(); log.debug(message); } Secret currentSecret = kubernetesClient.secrets().inNamespace(namespace.getMetadata().getName()) .withName(runtimeProperty.getName()).get(); //if secrete exists then replace the same secrete, otherwise create a new secrete if (currentSecret != null) { kubernetesClient.secrets().inNamespace(namespace.getMetadata().getName()) .withName(runtimeProperty.getName()).replace(currentSecret); } else { Secret secret = new SecretBuilder() .withKind(KubernetesPovisioningConstants.KIND_SECRETS) .withNewMetadata() .withNamespace(namespace.getMetadata().getName()) .withLabels(KubernetesProvisioningUtils.getLableMap(applicationContext)) .withName(runtimeProperty.getName()) .endMetadata().withData(runtimeProperty.getProperties()) .build(); kubernetesClient.secrets().create(secret); } Volume volume = new VolumeBuilder() .withName(runtimeProperty.getName()) .withNewSecret() .withSecretName(runtimeProperty.getName()) .endSecret() .build(); secrets.add(volume); //create volume mount for the secretes VolumeMount volumeMount = new VolumeMountBuilder() .withName(runtimeProperty.getName()) .withMountPath(KubernetesPovisioningConstants.VOLUME_MOUNT_PATH + runtimeProperty.getName()) .withReadOnly(true) .build(); volumeMounts.add(volumeMount); break; case ENVIRONMENT: if (log.isDebugEnabled()) { String message = "Creating property type environment for the application:" + applicationContext.getId() + " for the tenant domain : " + applicationContext.getTenantInfo().getTenantDomain(); log.debug(message); } envVariables.putAll(runtimeProperty.getProperties()); break; default: String message = "Runtime property type : " + runtimeProperty.getPropertyType() + " not supported."; throw new IllegalArgumentException(message); } } //Initially assume first container is the application and set volume mounts deploymentConfig.getContainers().get(0).setVolumeMounts(volumeMounts); //Set secretes to a pod deploymentConfig.setSecrets(secrets); //Initially assume first container is the application deploymentConfig.getContainers().get(0).setEnvVariables(envVariables); //Call deploy application to redeploy application with runtime properties deployApplication(deploymentConfig); } /** * Update runtime properties already defined in the application. * * @param runtimeProperties list of runtime properties * @param deploymentConfig includes deployment related details * @throws RuntimeProvisioningException */ @Override public void updateRuntimeProperties(List<RuntimeProperty> runtimeProperties, DeploymentConfig deploymentConfig) throws RuntimeProvisioningException { List secrets = new ArrayList(); Container container = new Container(); for (RuntimeProperty runtimeProperty : runtimeProperties) { switch (runtimeProperty.getPropertyType()) { case SENSITIVE: if (log.isDebugEnabled()) { String message = "Updating property type secret for the application:" + applicationContext.getId() + " for the tenant domain:" + applicationContext.getTenantInfo().getTenantDomain(); log.debug(message); } Secret secret = new SecretBuilder().withKind(KubernetesPovisioningConstants.KIND_SECRETS) .withNewMetadata() .withNamespace(namespace.getMetadata().getNamespace()) .withName(runtimeProperty.getName()) .endMetadata() .withData(runtimeProperty.getProperties()) .build(); AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); kubernetesClient.secrets().inNamespace(namespace.getMetadata().getName()) .withName(runtimeProperty.getName()).replace(secret); Volume volume = new VolumeBuilder() .withName(KubernetesPovisioningConstants.VOLUME_MOUNT) .withNewSecret() .withSecretName(runtimeProperty.getName()) .endSecret() .build(); secrets.add(volume); break; case ENVIRONMENT: if (log.isDebugEnabled()) { String message = "Updating property type environment for the application:" + applicationContext.getId() + " for the tenant domain:" + applicationContext.getTenantInfo().getTenantDomain(); log.debug(message); } //updating environment variables for container container.setEnvVariables(runtimeProperty.getProperties()); break; default: String message = "Runtime property type is not support, property type:" + runtimeProperty.getPropertyType(); throw new IllegalArgumentException(message); } } List<Container> containers = new ArrayList<>(); containers.add(container); deploymentConfig.setContainers(containers); //call application deployment to re deploy the application with update variables deployApplication(deploymentConfig); } /** * Provide runtime properties for given application context. * * @return list of runtime properties * @throws RuntimeProvisioningException */ @Override public List<RuntimeProperty> getRuntimeProperties() throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); SecretList secretList = kubernetesClient.secrets().inNamespace(namespace.getMetadata().getName()) .withLabels(KubernetesProvisioningUtils.getLableMap(applicationContext)).list(); List<RuntimeProperty> runtimeProperties = new ArrayList<>(); for (Secret secret : secretList.getItems()) { RuntimeProperty sensitiveRuntimeProperty = new RuntimeProperty(); sensitiveRuntimeProperty.setPropertyType(RuntimeProperty.PropertyType.SENSITIVE); sensitiveRuntimeProperty.setName(secret.getMetadata().getName()); sensitiveRuntimeProperty.setProperties(secret.getData()); runtimeProperties.add(sensitiveRuntimeProperty); } PodList podList = KubernetesProvisioningUtils.getPods(applicationContext); HashMap<String, String> data = new HashMap<>(); for (Pod pod : podList.getItems()) { //get only first container from the container list List<EnvVar> envVarList = pod.getSpec().getContainers().get(0).getEnv(); for (EnvVar envVar : envVarList) { data.put(envVar.getName(), envVar.getValue()); } RuntimeProperty environmentVariable = new RuntimeProperty(); environmentVariable.setPropertyType(RuntimeProperty.PropertyType.ENVIRONMENT); environmentVariable.setProperties(data); runtimeProperties.add(environmentVariable); } return runtimeProperties; } /** * add a set of custom domains for an application version. * This will create an ingress for each domain and each service. * * @param domains set of domains * @throws RuntimeProvisioningException */ @Override public boolean addCustomDomain(Set<String> domains) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); ServiceList serviceList = KubernetesProvisioningUtils.getServices(applicationContext); Ingress createdIng; boolean created = false; for (String domain : domains) { for (Service service : serviceList.getItems()) { Ingress ing = new IngressBuilder() .withKind(KubernetesPovisioningConstants.KIND_INGRESS) .withNewMetadata() .withName(KubernetesProvisioningUtils .createIngressMetaName(domain)) .withNamespace(namespace.getMetadata().getName()) .endMetadata() .withNewSpec() .withRules().addNewRule() .withHost(domain) .withNewHttp() .withPaths().addNewPath() .withNewBackend() .withServiceName(service.getMetadata().getName()) .withServicePort(new IntOrString(80)) .endBackend() .endPath() .endHttp() .endRule() .endSpec() .build(); createdIng = kubClient.extensions().ingress().inNamespace(namespace.getMetadata().getName()).create(ing); if(createdIng != null && KubernetesProvisioningUtils .createIngressMetaName(domain) .equals(createdIng.getMetadata().getName())){ created = true; log.info("Kubernetes ingress : " + ing + "created for service : " + service.getMetadata().getName()); }else{ created = false; log.error("Error occured while creating Kubernetes ingress : " + ing + "for service : " + service.getMetadata().getName()); } } } return created; } /** * update a certain domain by replacing the ingresses created for related services with new ingresses. * * @param oldDomain old domain name to be changed * @param newDomain new domain name to be changed to * @throws RuntimeProvisioningException */ @Override public boolean updateCustomDomain(String oldDomain, String newDomain) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); ServiceList serviceList = KubernetesProvisioningUtils.getServices(applicationContext); boolean deleted = false; boolean updated = false; Ingress createdIng; for (Service service : serviceList.getItems()) { String oldIngName = KubernetesProvisioningUtils .createIngressMetaName(oldDomain); String newIngName = KubernetesProvisioningUtils .createIngressMetaName(newDomain); Ingress oldIng = new IngressBuilder() .withKind(KubernetesPovisioningConstants.KIND_INGRESS) .withNewMetadata() .withName(oldIngName) .withNamespace(namespace.getMetadata().getName()) .endMetadata() .build(); Ingress newIng = new IngressBuilder() .withKind(KubernetesPovisioningConstants.KIND_INGRESS) .withNewMetadata() .withName(newIngName) .withNamespace(namespace.getMetadata().getName()) .endMetadata() .withNewSpec() .addNewRule() .withHost(newDomain) .withNewHttp() .addNewPath() .withNewBackend() .withServiceName(service.getMetadata().getName()) .withServicePort(new IntOrString(80)) .endBackend() .endPath() .endHttp() .endRule() .endSpec() .build(); deleted = kubClient.extensions().ingress().inNamespace(namespace.getMetadata().getName()).delete(oldIng); if(deleted) { createdIng = kubClient.extensions().ingress().inNamespace(namespace.getMetadata().getName()).create(newIng); if(createdIng != null && newIngName.equals(createdIng.getMetadata().getName())){ updated = true; }else{ updated = false; log.error("Error occured while creating Kubernetes ingress : " + newIng + "for service : " + service.getMetadata().getName()); } }else{ log.error("Error occured while deleting Kubernetes ingress : " + oldIng + "for service : " + service.getMetadata().getName()); } } return updated; } /** * get a set of custom domains for a particular applicaiton context. * * @return set of domains * @throws RuntimeProvisioningException */ @Override public Set<String> getCustomDomains() throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); Set<String> domains = new HashSet<>(); IngressList ingressList = kubClient.extensions().ingress(). inNamespace(namespace.getMetadata().getName()).list(); for (Ingress ingress : ingressList.getItems()){ domains.add(ingress.getSpec().getRules().get(0).getHost()); } return domains; } /** * delete a custom domain and delete the ingresses created for related services. * * @param domain domain name * @throws RuntimeProvisioningException */ @Override public boolean deleteCustomDomain(String domain) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); ServiceList serviceList = KubernetesProvisioningUtils.getServices(applicationContext); boolean deleted = false; for (Service service : serviceList.getItems()) { String ingName = KubernetesProvisioningUtils .createIngressMetaName(domain); Ingress ing = new IngressBuilder() .withKind(KubernetesPovisioningConstants.KIND_INGRESS) .withNewMetadata() .withName(ingName) .withNamespace(namespace.getMetadata().getName()) .endMetadata() .build(); deleted = kubClient.extensions().ingress().inNamespace(namespace.getMetadata().getName()).delete(ing); if(!deleted){ log.error("Error occurred while deleting Kubernetes ingress : " + ingName + "for service : " + service.getMetadata().getName()); } } return deleted; } @Override public boolean createDeploymentUrl(String environmentUrl) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); ServiceList serviceList = KubernetesProvisioningUtils.getServices(applicationContext); if (log.isDebugEnabled()){ log.debug("Deployment service List size: " + serviceList.getItems().size()); } Ingress createdIng; boolean created = false; String ingressPathStr = KubernetesProvisioningUtils.getDeploymentPath(applicationContext); if (log.isDebugEnabled()){ log.debug("Ingress path: " + ingressPathStr); } HTTPIngressPath ingressPath = new HTTPIngressPath(new IngressBackend(), KubernetesPovisioningConstants.DEFAULT_INGRESS_PATH); for (Service service : serviceList.getItems()) { if (log.isDebugEnabled()){ log.debug("Ingress creating for service: " + service.getMetadata().getName()); } String ingressName = environmentUrl + "-" + service.getMetadata().getName(); Ingress ing = new IngressBuilder() .withKind(KubernetesPovisioningConstants.KIND_INGRESS) .withNewMetadata() .withName(KubernetesProvisioningUtils.createIngressMetaName(ingressName)) .withNamespace(namespace.getMetadata().getName()) .withLabels(KubernetesProvisioningUtils.getLableMap(applicationContext)) .endMetadata() .withNewSpec() .withRules() .addNewRule() .withHost(environmentUrl) .withNewHttp() .withPaths() .addNewPathLike(ingressPath) .withNewBackend() .withServiceName(service.getMetadata().getName()) .withServicePort(new IntOrString(service.getSpec().getPorts().get(0).getPort())) .endBackend() .endPath() .endHttp() .endRule() .endSpec() .build(); createdIng = kubClient.extensions() .ingress() .inNamespace(namespace.getMetadata().getName()) .create(ing); if (createdIng != null && KubernetesProvisioningUtils .createIngressMetaName(ingressName) .equals(createdIng.getMetadata().getName())) { created = true; if (log.isDebugEnabled()){ log.debug("Kubernetes ingress : " + ing + "created for service : " + service.getMetadata().getName()); } } else { created = false; log.error("Error occurred while creating Kubernetes ingress : " + ing + "for service : " + service.getMetadata().getName()); } } return created; } /** * {@inheritDoc} */ @Override public boolean deleteDeployment() throws RuntimeProvisioningException { try { deleteK8sKind(KubernetesPovisioningConstants.KIND_DEPLOYMENT); KubernetesProvisioningUtils.waitForDeploymentToGetDeleted(applicationContext); deleteK8sKind(KubernetesPovisioningConstants.KIND_REPLICATION_CONTROLLER); KubernetesProvisioningUtils.waitForRCToGetDeleted(applicationContext); deleteK8sKind(KubernetesPovisioningConstants.KIND_POD); KubernetesProvisioningUtils.waitForPodToGetDeleted(applicationContext); deleteK8sKind(KubernetesPovisioningConstants.KIND_INGRESS); KubernetesProvisioningUtils.waitForIngressesToGetDeleted(applicationContext); deleteK8sKind(KubernetesPovisioningConstants.KIND_SECRETS); KubernetesProvisioningUtils.waitForSecretToGetDeleted(applicationContext); deleteK8sKind(KubernetesPovisioningConstants.KIND_SERVICE); KubernetesProvisioningUtils.waitForServiceToGetDeleted(applicationContext); return true; } catch (RuntimeProvisioningException e){ return false; } } /** * Delete K8s object for given kind with labels. * * @param k8sKind k8s object type */ public void deleteK8sKind(String k8sKind) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); String namespace = this.namespace.getMetadata().getName(); Map<String, String> labels = KubernetesProvisioningUtils.getDeleteLables(applicationContext); try { switch (k8sKind) { case KubernetesPovisioningConstants.KIND_REPLICATION_CONTROLLER: kubernetesClient.replicationControllers().inNamespace(namespace).withLabels(labels).delete(); break; case KubernetesPovisioningConstants.KIND_DEPLOYMENT: kubernetesClient.extensions().deployments().inNamespace(namespace).withLabels(labels).delete(); break; case KubernetesPovisioningConstants.KIND_POD: kubernetesClient.pods().inNamespace(namespace).withLabels(labels).delete(); break; case KubernetesPovisioningConstants.KIND_INGRESS: kubernetesClient.extensions().ingress().inNamespace(namespace).withLabels(labels).delete(); break; case KubernetesPovisioningConstants.KIND_SECRETS: kubernetesClient.secrets().inNamespace(namespace).withLabels(labels).delete(); break; case KubernetesPovisioningConstants.KIND_SERVICE: kubernetesClient.services().inNamespace(namespace).withLabels(labels).delete(); break; default: String message = "The kubernetes kind : " + k8sKind + " deletion is not supported"; throw new IllegalArgumentException(message); } } catch (KubernetesClientException e) { String message = "Error while deleting kubernetes kind : " + k8sKind + " from deployment"; log.error(message, e); throw new RuntimeProvisioningException(message, e); } } /** * {@inheritDoc} */ @Override public void deleteK8sKindByName(String k8sKind, String name) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); String namespace = this.namespace.getMetadata().getName(); if (log.isDebugEnabled()) { log.debug("Kubernetes kind : " + k8sKind + ", object name : " + name); } try { switch (k8sKind) { case KubernetesPovisioningConstants.KIND_REPLICATION_CONTROLLER: kubernetesClient.replicationControllers().inNamespace(namespace).withName(name).delete(); break; case KubernetesPovisioningConstants.KIND_DEPLOYMENT: kubernetesClient.extensions().deployments().inNamespace(namespace).withName(name).delete(); break; case KubernetesPovisioningConstants.KIND_POD: kubernetesClient.pods().inNamespace(namespace).withName(name).delete(); break; case KubernetesPovisioningConstants.KIND_INGRESS: kubernetesClient.extensions().ingress().inNamespace(namespace).withName(name).delete(); break; case KubernetesPovisioningConstants.KIND_SECRETS: kubernetesClient.secrets().inNamespace(namespace).withName(name).delete(); break; case KubernetesPovisioningConstants.KIND_SERVICE: kubernetesClient.services().inNamespace(namespace).withName(name).delete(); break; default: String message = "The kubernetes kind : " + k8sKind + " deletion is not supported"; throw new IllegalArgumentException(message); } } catch (KubernetesClientException e) { String message = "Error while deleting kubernetes kind : " + k8sKind + " with name : " + name + " from deployment"; log.error(message, e); throw new RuntimeProvisioningException(message, e); } } /** * {@inheritDoc} */ @Override public void createService(ServiceProxy serviceProxy) throws RuntimeProvisioningException { Service service = getService(serviceProxy); String namespace = this.namespace.getMetadata().getName(); try { AutoAdaptableKubernetesClient kubClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); kubClient.inNamespace(namespace).services().create(service); } catch (KubernetesClientException e) { String message = "Error while creating kubernetes kind service with namespace : " + namespace; log.error(message, e); throw new RuntimeProvisioningException(message, e); } } /** * {@inheritDoc} */ @Override public Map<String, String> getPodRestartCounts() throws RuntimeProvisioningException { Map<String, String> podRestartCounts = new HashMap<>(); PodList podList = KubernetesProvisioningUtils.getPods(applicationContext); if (podList != null) { int podCounter = 0; for (Pod pod : podList.getItems()) { if(pod.getStatus().getContainerStatuses().size() > 0) { podRestartCounts.put(String.valueOf(podCounter), String.valueOf(pod.getStatus().getContainerStatuses().get(0).getRestartCount())); } else { //In case query is done before the pod get fully created, //Restart count wont be available so returning 0 podRestartCounts.put(String.valueOf(podCounter), String.valueOf(0)); } podCounter++; } return podRestartCounts; } else { String message = "Could not find a pod associated with pod for application : " + applicationContext.getId() + ", version : " + applicationContext.getVersion(); log.error(message); throw new RuntimeProvisioningException(message); } } /** * {@inheritDoc} */ @Override public JSONArray getReplicaInfo() throws RuntimeProvisioningException { PodList podList = KubernetesProvisioningUtils.getPods(applicationContext); if (podList != null) { JSONArray jsonArray = new JSONArray(); for (Pod pod : podList.getItems()) { if(pod.getStatus().getContainerStatuses().size() > 0) { JSONObject jsonObject = new JSONObject(); jsonObject.put("podName", pod.getMetadata().getName()); jsonObject.put("restartCount", pod.getStatus().getContainerStatuses().get(0).getRestartCount()); jsonArray.put(jsonObject); } else { //In case query is done before the pod get fully created, //Restart count wont be available so returning 0 //Pod name return as empty JSONObject jsonObject = new JSONObject(); jsonObject.put("podName", ""); jsonObject.put("restartCount", String.valueOf(0)); jsonArray.put(jsonObject); } } return jsonArray; } else { String message = "Could not find a pod associated with pod for application : " + applicationContext.getId() + ", version : " + applicationContext.getVersion(); log.error(message); throw new RuntimeProvisioningException(message); } } /** * {@inheritDoc} */ @Override public void changeExposureLevelInServices(String serviceName, String exposureLevel, String lbHost) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); kubClient.services().inNamespace(this.namespace.getMetadata().getName()) .withName(serviceName).edit().editMetadata() .addToLabels("exposure-level", exposureLevel).endMetadata().done(); kubClient.services().inNamespace(this.namespace.getMetadata().getName()) .withName(serviceName).edit().editMetadata() .addToAnnotations("serviceloadbalancer/lb.host", lbHost).endMetadata().done(); } /** * {@inheritDoc} */ @Override public void updateKubernetesServiceWithLabel(String serviceName, String labelKey, String labelValue) throws RuntimeProvisioningException { String namespace = this.namespace.getMetadata().getName(); try { AutoAdaptableKubernetesClient kubClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); kubClient.services().inNamespace(namespace).withName(serviceName).edit().editMetadata() .addToLabels(labelKey, labelValue).endMetadata().done(); } catch (KubernetesClientException e) { String message = "Error while adding label to kubernetes kind service with service name: " + serviceName + " in namespace: " + namespace; log.error(message, e); throw new RuntimeProvisioningException(message, e); } } /** * {@inheritDoc} */ @Override public void createDeploymentAutoScalePolicy(String name) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); String namespace = this.namespace.getMetadata().getName(); HorizontalPodAutoscaler horizontalPodAutoscaler = new HorizontalPodAutoscalerBuilder() .withNewMetadata().withNamespace(namespace).withName(name).endMetadata() .withNewSpec().withMinReplicas(1).withMaxReplicas(5).withNewCpuUtilization(50) .withNewScaleRef().withName(name).withKind(KubernetesPovisioningConstants.KIND_DEPLOYMENT) .endScaleRef().endSpec() .build(); kubernetesClient.extensions().horizontalPodAutoscalers().inNamespace(namespace).create(horizontalPodAutoscaler); } /** * {@inheritDoc} */ @Override public void scaleDeployment(String name, int replicaCount) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); String namespace = this.namespace.getMetadata().getName(); kubernetesClient.extensions().deployments().inNamespace(namespace).withName(name).scale(replicaCount); } /** * {@inheritDoc} */ @Override public int getReplicasForDeployment(String name) throws RuntimeProvisioningException { AutoAdaptableKubernetesClient kubernetesClient = KubernetesProvisioningUtils.getFabric8KubernetesClient(); String namespace = this.namespace.getMetadata().getName(); int count = kubernetesClient.extensions().deployments().inNamespace(namespace).withName(name).get().getSpec() .getReplicas(); log.info("Replica count for deployment:" + name + ":" + count); return count; } }
import java.util.*; public class Hanoi { public static List<String> getSuccessor(String[] hanoi) { // TO DO // Implement the getSuccessor method List<String> result = new ArrayList<>(); String disc; String peg; String print = ""; for(int i = 0; i < hanoi.length; i++) { disc = Character.toString(hanoi[i].charAt(0)); if(disc.compareTo("0") != 0) { int i2,j2; if (i == 0) {i2 = i;} //bound checking else {i2 = i-1;} if (i+1>=hanoi.length) {j2 = hanoi.length-1;} else {j2 = i+1;} for( int j = i2 ; j <= j2; j++) {//ternary operator for bound checking //not same rod & valid move if(i != j) { if (hanoi[j].compareTo("0") == 0 || disc.compareTo(Character.toString(hanoi[j].charAt(0))) < 0) { for(int k = 0; k < hanoi.length; k++) { if(k == i) { //where the disc is from peg = hanoi[i].substring(1);//remove disc if(peg == null || peg.isEmpty()) peg = "0"; print += " " + peg; }else if( k == j) { //where the disc go if(hanoi[j].compareTo("0") == 0) //empty peg print += " " + disc; else print += " " + disc + hanoi[j]; //add disc }else{ print += " " + hanoi[k]; //store untouched peg } } result.add(print.trim()); print = ""; } } } } } return result; } public static void main(String[] args) { if (args.length < 3) { // String [] argsq = {"24","0","1","0","56","0","9"}; //test case // List<String> sucessors = getSuccessor(argsq); // for (int i = 0; i < sucessors.size(); i++) { // System.out.println(sucessors.get(i)); // } // return; } List<String> sucessors = getSuccessor(args); for (int i = 0; i < sucessors.size(); i++) { System.out.println(sucessors.get(i)); } } }
package com.gzy.paymentlistener.http; public class RequestBean { private double money; private String key; public RequestBean(double money, String key) { this.money = money; this.key = key; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
package com.rtw.myrpccore.client; import io.netty.channel.ChannelFuture; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicLong; /** * @author rtw * @since 2019-05-01 */ public class ChannelManager { public static CopyOnWriteArrayList<ChannelFuture> channelFutures = new CopyOnWriteArrayList<>(); // 循环遍历的ChannelFuture下标 private static AtomicLong index = new AtomicLong(0); public static void removeFuture(ChannelFuture channel) { channelFutures.remove(channel); } public static void addFuture(ChannelFuture channel) { channelFutures.add(channel); } public static void clear(ChannelFuture channel) { channelFutures.clear(); } public static ChannelFuture getByRandom() { if (index.intValue() >= channelFutures.size()) { // 当index的下标超过Future列表的话,则设置为0,从新开始 index.set(0); } ChannelFuture channelFuture = channelFutures.get(index.intValue()); if (channelFuture != null) { // 自增 index.incrementAndGet(); return channelFuture; } else { // 获取为空的话,表示出现多线程修改,那么在重试两次进行自增获取。 ChannelFuture channelFutureAgain; int i = 0; do { i++; if (index.intValue() >= channelFutures.size()) { // 当index的下标超过Future列表的话,则设置为0,从新开始 index.set(0); } channelFutureAgain = channelFutures.get(index.intValue()); index.incrementAndGet(); if (channelFutureAgain != null) { return channelFutureAgain; } } while (i >= 2); return null; } } }
package edu.erlm.epi.web.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.codahale.metrics.annotation.Timed; import edu.erlm.epi.repository.school.TopicRepository; import edu.erlm.epi.security.AuthoritiesConstants; import edu.erlm.epi.web.rest.util.HeaderUtil; @RestController @RequestMapping("/api") public class TopicResource { @Autowired TopicRepository topicRepository; @Secured(AuthoritiesConstants.ADMIN) @Timed @RequestMapping(path = "/topics/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> delete(@PathVariable Long id) { try{ topicRepository.delete(id); }catch(Exception exception){ return ResponseEntity.badRequest() .headers(HeaderUtil.createFailureAlert("topic-management", "can not be deleted", "can not be deleted")) .body(null); } return ResponseEntity.ok().build(); } }
/******************************************************************************* * Copyright 2014 See AUTHORS file. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 dk.sidereal.lumm.components.triggers; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Rectangle; import dk.sidereal.lumm.architecture.AbstractEvent; import dk.sidereal.lumm.architecture.Lumm; import dk.sidereal.lumm.architecture.LummObject; import dk.sidereal.lumm.architecture.concrete.ConcreteLummComponent; /** * Behavior that handles hovering over an area. Can handle being inside as well * as outside of the designated area. * * @author Claudiu Bele */ public class Hoverable extends ConcreteLummComponent { // region fields private Rectangle area; private AbstractEvent insideEvent; private AbstractEvent outsideEvent; private float offsetX, offsetY; private Sprite debugSprite; private static Sprite debugSpriteSource; // endregion fields // region constructors public Hoverable(LummObject obj) { super(obj); if (Lumm.debug.isEnabled()) this.debugSprite = new Sprite(debugSpriteSource); setDebugToggleKeys(Keys.SHIFT_LEFT, Keys.X); } @Override protected void initialiseClass() { if (!Lumm.debug.isEnabled()) return; debugSpriteSource = new Sprite(); debugSpriteSource.setColor(new Color(0.7f, 0, 1, 0.5f)); } // endregion constructors // region methods @Override public void onDebug() { debugSprite.setBounds(area.x, area.y, area.width, area.height); debugSprite.draw(object.getSceneLayer().spriteBatch); } @Override public void onUpdate() { // adapt the area based on the position of the object // so the position of the object is in the middle of the area area.x = object.position.getX() + offsetX; area.y = object.position.getY() + offsetY; // mouse click is inside the area of the object if (area.contains(object.getSceneLayer().mousePosition)) { if (insideEvent != null) insideEvent.run(); } else if (outsideEvent != null) outsideEvent.run(); } public Rectangle getArea() { return area; } public void setAreaSize(float width, float height) { offsetX = -width / 2; offsetY = -height / 2; this.area = new Rectangle(object.position.getX() - width / 2, object.position.getY() - height / 2, width, height); } public void setAreaSize(float width, float height, float offsetX, float offsetY) { this.offsetX = offsetX; this.offsetY = offsetY; this.area = new Rectangle(object.position.getX() + offsetX, object.position.getY() + offsetY, width, height); } public void setArea(Rectangle area) { this.area = area; } public AbstractEvent getEvent() { return insideEvent; } public void setEventOnInside(AbstractEvent event) { this.insideEvent = event; } public void setEventOnOutside(AbstractEvent event) { this.outsideEvent = event; } // endregion methods }
package com.example.songsbook; /** * Created by Promlert on 2017-11-16. */ public class Chord { public final int id; public final String name; public final String picture; public Chord(int id, String name, String picture) { this.id = id; this.name = name; this.picture = picture; } @Override public String toString() { return "คอร์ด " + name; } }
package xyz.ieden.customer.ribbon.server; /** * @author lianghongwei01 * @date 2018/9/28 16:03 */ public interface IHelloService { /** * 获取 home/index * * @return * @throws Exception */ String getHomeIndex() throws Exception; }
package com.donytar; import java.io.IOException; import java.sql.SQLException; public class Main { public static void main(String[] args) { try { SqlWorker database = new SqlWorker("jdbc:mysql://localhost/my_db", "root", "Nathyrra"); //database.addRow("Bobic", "Gringo Dolbig", "dog", "m"); //database.removeRow("Rnobic", "Bilbo Sumcin"); //database.updateName("Goshka", "Stepan Razin", "Gosha"); //database.showAll(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } try { Runtime.getRuntime().exec("mysqldump -u root -pNathyrra my_db -r //home/donytar/my_db.sql"); } catch (IOException e) { e.printStackTrace(); } } }
package cn.swsk.rgyxtqapp; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.swsk.rgyxtqapp.custom.ProgressDialog; import cn.swsk.rgyxtqapp.custom.topbar; import cn.swsk.rgyxtqapp.utils.JsonTools; import cn.swsk.rgyxtqapp.utils.PushUtils; /** * 指令列表 */ public class InstructionsListActivity extends Activity { private static final String TAG = "InstructionsListActivity"; private ProgressDialog dialog = null; //等待状态提示框 private List<HashMap<String, Object>> instructionsList; ListView list_instructions; // ListView控件 SimpleAdapter listItemAdapter; // ListView的适配器 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_instructions_list); init(); } /** * 初始化 */ private void init() { dialog = new ProgressDialog(InstructionsListActivity.this); //控件参数化 list_instructions = (ListView) findViewById(R.id.list_instructions); //设置标题栏 topbar mTopbar = (topbar) findViewById(R.id.instructionsListTopbar); mTopbar.setRightButtonIsvisable(false); mTopbar.setOnTopbarClickListener(new topbar.topbarClickListener() { @Override public void leftClick() { finish(); } @Override public void rightClick() { } }); //数据初始化 instructionsList = new ArrayList<HashMap<String, Object>>(); listItemAdapter = new SimpleAdapter(this, instructionsList, R.layout.activity_instructions_list_item, new String[]{"content", "sendDate"}, new int[]{R.id.lbl_instructions_list_title, R.id.lbl_instructions_list_info}); list_instructions.setAdapter(listItemAdapter); //控件事件绑定 list_instructions.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { HashMap<String, Object> map = instructionsList.get(position); Log.v(TAG, map.toString()); onShowDetails(map); } }); //获取方案列表 String path = "http://" + PushUtils.getServerIPText(this) + "/rgyx/appUser/findInstructionsList"; path += "?token=" + PushUtils.token; new TomAsyncTask().execute(path); } /** * 列表项单击事件 * @param map */ public void onShowDetails(HashMap<String, Object> map){ // Intent i = new Intent(); // i.setClass(InstructionsListActivity.this, InstructionsListItemActivity.class); // i.putExtra("instructionsId", map.get("id").toString()); // i.putExtra("sendDate", map.get("sendDate").toString()); // i.putExtra("content", map.get("content").toString()); // startActivity(i); // finish(); StringBuffer sb = new StringBuffer(); sb.append("时间:").append(map.get("sendDate").toString()).append("\n"); sb.append("内容:").append(map.get("content").toString()); AlertDialog myDialog = new AlertDialog.Builder(InstructionsListActivity.this).setTitle("指令") .setMessage(sb.toString()) .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton("关闭", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 点击“确认”后的操作 } }).show(); } /** * 异步加载方案列表 */ class TomAsyncTask extends AsyncTask<String, Void, Map<String, Object>> { @Override protected void onPreExecute() { super.onPreExecute(); dialog.showDialog(); //显示加载等待提示框 } @Override protected void onPostExecute(Map<String, Object> stringObjectMap) { dialog.cancelDialog();//关闭加载等待提示框 if (stringObjectMap == null) { Toast.makeText(InstructionsListActivity.this, "无法连接到服务器!", Toast.LENGTH_LONG).show(); return; } //获取状态值 String status = stringObjectMap.containsKey("status") ? stringObjectMap.get("status").toString() : ""; if ("1".equals(status)) { //获取返回的数据集合 List<HashMap<String, Object>> tempInstructionsList = (ArrayList<HashMap<String, Object>>) stringObjectMap.get("instructionsList"); if(tempInstructionsList != null && tempInstructionsList.size() > 0){ for (HashMap<String, Object> map : tempInstructionsList) { instructionsList.add(map); } listItemAdapter.notifyDataSetChanged(); //更新显示 }else{ Toast.makeText(InstructionsListActivity.this, "暂无数据!", Toast.LENGTH_LONG).show(); } } else if ("2".equals(status)) { Toast.makeText(InstructionsListActivity.this, stringObjectMap.get("errmsg").toString(), Toast.LENGTH_LONG).show(); } else if ("9999".equals(status)) { Toast.makeText(InstructionsListActivity.this, stringObjectMap.get("errmsg").toString(), Toast.LENGTH_LONG).show(); } else { Toast.makeText(InstructionsListActivity.this, "未知错误!", Toast.LENGTH_LONG).show(); } } @Override protected Map<String, Object> doInBackground(String... params) { String path = params[0]; try { String jsonString1 = cn.swsk.rgyxtqapp.utils.HttpUtils.getJsonContent(path); if (jsonString1 == null) { return null; } return JsonTools.getMap(jsonString1); } catch (Exception e) { Log.i(e.getMessage(), ""); } return null; } } }
package ui.RegistryUiTest; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.control.Label; import org.junit.*; import org.loadui.testfx.GuiTest; import org.testfx.api.FxRobot; import java.io.IOException; /** * Created by Алексей on 26.12.2016. */ public class RegistryUiTest extends GuiTest { private static FxRobot robot; private Label outputErrorText; @BeforeClass public static void createRobot() { robot = new FxRobot(); } @Before public void getOutputErrorText() { outputErrorText = find("#outputErrorText"); } @After public void clickResetField() { robot.clickOn("#reset"); } @Override protected Parent getRootNode() { Parent parent = null; try { parent = FXMLLoader.load(getClass().getResource("/fxml/Registry.fxml")); return parent; } catch (IOException ex) { // TODO ... } return parent; } @Test public void emptyLoginAndPasswordFieldTest() { robot.clickOn("#signUp").sleep(500); Assert.assertEquals(outputErrorText.getText(), "Не заполнены обязательные поля: Логин; Пароль; "); } @Test public void emptyLoginFieldTest() { robot.clickOn("#login").write("notEmptyLogin"); robot.clickOn("#signUp"); Assert.assertEquals(outputErrorText.getText(), "Не заполнены обязательные поля: Пароль; "); } @Test public void emptyPasswordFieldTest() { robot.clickOn("#password").write("tesPass"); robot.clickOn("#signUp"); Assert.assertEquals(outputErrorText.getText(), "Не заполнены обязательные поля: Логин; "); } }
package com.eagleshipperapi.controller; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.eagleshipperapi.bean.Rating; import com.eagleshipperapi.bean.Transporter; import com.eagleshipperapi.exception.ResourceNotFoundException; import com.eagleshipperapi.service.TransporterService; @RestController @RequestMapping("/transporter") public class TransporterController { @Autowired private TransporterService transporterService; //create Transporter @PostMapping("/") public ResponseEntity<Transporter> createNewTransporter(@RequestParam("file")MultipartFile file, @RequestParam("transporterId") String transporterId, @RequestParam("type") String type, @RequestParam("name")String name, @RequestParam("contactNumber")String contactNumber, @RequestParam("address")String address, @RequestParam("gstNumber")String gstNumber, @RequestParam("rating")String rating, @RequestParam("token")String token) throws ResourceNotFoundException, IOException { if(file.isEmpty()) throw new ResourceNotFoundException("image not found."); Transporter transporter = new Transporter(); transporter.setTransporterId(transporterId); transporter.setType(type); transporter.setName(name); transporter.setContactNumber(contactNumber); transporter.setAddress(address); if(gstNumber!=null) { transporter.setGstNumber(gstNumber); } transporter.setRating(rating); transporter.setToken(token); return new ResponseEntity<Transporter>(transporterService.createTransporter(transporter,file),HttpStatus.OK); } //get All transporter @GetMapping("/") public ResponseEntity<ArrayList<Transporter>> getTransporter() throws InterruptedException, ExecutionException{ return new ResponseEntity<ArrayList<Transporter>>(transporterService.getTransporter(),HttpStatus.OK); } //get Single Transporter by id @GetMapping("/{transporterId}") public ResponseEntity<Transporter> getTransporter(@PathVariable String transporterId) throws InterruptedException, ExecutionException, ResourceNotFoundException{ Transporter t = transporterService.getTransporter(transporterId); if(t==null) throw new ResourceNotFoundException("Transporter not exists"); return new ResponseEntity<Transporter>(t,HttpStatus.OK); } //delete Transporter by id @DeleteMapping("/{id}") public ResponseEntity<Transporter> deleteTransporter(@PathVariable String id) throws InterruptedException, ExecutionException, ResourceNotFoundException{ Transporter t = transporterService.deleteTransporter(id); if(t==null) throw new ResourceNotFoundException("Transporter not exists"); return new ResponseEntity<Transporter>(t,HttpStatus.OK); } //update Transporter @PostMapping("/update") public ResponseEntity<Transporter> updateTransporter(@RequestBody Transporter transporter) throws ResourceNotFoundException, IOException, InterruptedException, ExecutionException { Transporter t = transporterService.updateTransporter(transporter); if(t==null) throw new ResourceNotFoundException("Transporter not exists"); return new ResponseEntity<Transporter>(t,HttpStatus.OK); } //update Transporter image @PostMapping("/update/image") public ResponseEntity<Transporter> updateTransporter(@RequestParam("file")MultipartFile file,@RequestParam("transporterId") String transporterId) throws ResourceNotFoundException, IOException, InterruptedException, ExecutionException { Transporter t = transporterService.updateTransporter(transporterId, file); if(t==null) throw new ResourceNotFoundException("Transporter not exists"); return new ResponseEntity<Transporter>(t,HttpStatus.OK); } //create Rating @PostMapping("/rating/{transporterId}/{leadId}") public ResponseEntity<Rating> createRating(@PathVariable String transporterId,@PathVariable String leadId,@RequestBody Rating rating) throws ResourceNotFoundException, IOException, InterruptedException, ExecutionException { return new ResponseEntity<Rating>(transporterService.createRating(transporterId, leadId, rating),HttpStatus.OK); } //Get Rating of Single Transporter @GetMapping("/rating/{transporterId}") public ResponseEntity<ArrayList<Rating>> createRating(@PathVariable String transporterId) throws ResourceNotFoundException, IOException, InterruptedException, ExecutionException { return new ResponseEntity<ArrayList<Rating>>(transporterService.getTransporterRating(transporterId),HttpStatus.OK); } // get number of rating's and number of persons @GetMapping("/rating/number/{transporterId}") public ResponseEntity<ArrayList<Float>> getNumberOfRating(@PathVariable String transporterId) throws ResourceNotFoundException, IOException, InterruptedException, ExecutionException { return new ResponseEntity<ArrayList<Float>>(transporterService.getNumberOfRating(transporterId),HttpStatus.OK); } }
/* * Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.db.generic.reg; import java.util.List; import org.apache.ibatis.session.SqlSession; import pl.edu.icm.unity.db.generic.DependencyChangeListener; import pl.edu.icm.unity.db.generic.cred.CredentialHandler; import pl.edu.icm.unity.exceptions.EngineException; import pl.edu.icm.unity.exceptions.SchemaConsistencyException; import pl.edu.icm.unity.types.authn.CredentialDefinition; import pl.edu.icm.unity.types.registration.CredentialParamValue; import pl.edu.icm.unity.types.registration.RegistrationRequestStatus; import pl.edu.icm.unity.types.registration.UserRequestState; public class RequestCredentialChangeListener implements DependencyChangeListener<CredentialDefinition> { private RequestsSupplier supplier; public RequestCredentialChangeListener(RequestsSupplier supplier) { this.supplier = supplier; } @Override public String getDependencyObjectType() { return CredentialHandler.CREDENTIAL_OBJECT_TYPE; } @Override public void preAdd(CredentialDefinition newObject, SqlSession sql) throws EngineException { } @Override public void preUpdate(CredentialDefinition oldObject, CredentialDefinition updatedObject, SqlSession sql) throws EngineException { List<? extends UserRequestState<?>> requests = supplier.getRequests(sql); for (UserRequestState<?> req: requests) { if (req.getStatus() != RegistrationRequestStatus.pending) continue; for (CredentialParamValue crParam: req.getRequest().getCredentials()) { if (updatedObject.getName().equals(crParam.getCredentialId())) throw new SchemaConsistencyException("The modified credential is used" + "in a PENDING registration or enquiry request. " + "Please process all the requests using this credential " + "first and only then modify its settings. " + "Offending request: " + req.getRequestId()); } } } public void preRemove(CredentialDefinition removedObject, SqlSession sql) throws EngineException { //removal is protected by the form } }
/* * 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 trabalhotheobaldo; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; /** * * @author victo */ public class Alunos { private String nome; public static final String PROP_NOME = "nome"; public String getNome() { return nome; } public void setNome(String nome) { String oldNome = this.nome; this.nome = nome; propertyChangeSupport.firePropertyChange(PROP_NOME, oldNome, nome); } private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(listener); } private String email; public static final String PROP_EMAIL = "email"; public String getEmail() { return email; } public void setEmail(String email) { String oldEmail = this.email; this.email = email; propertyChangeSupport.firePropertyChange(PROP_EMAIL, oldEmail, email); } private String cidade; public static final String PROP_CIDADE = "cidade"; public String getCidade() { return cidade; } public void setCidade(String cidade) { String oldCidade = this.cidade; this.cidade = cidade; propertyChangeSupport.firePropertyChange(PROP_CIDADE, oldCidade, cidade); } private String uf; public static final String PROP_UF = "uf"; public String getUf() { return uf; } public void setUf(String uf) { String oldUf = this.uf; this.uf = uf; propertyChangeSupport.firePropertyChange(PROP_UF, oldUf, uf); } private int codigo; public static final String PROP_CODIGO = "codigo"; public int getCodigo() { return codigo; } public void setCodigo(int codigo) { int oldCodigo = this.codigo; this.codigo = codigo; propertyChangeSupport.firePropertyChange(PROP_CODIGO, oldCodigo, codigo); } }
package application; import application.securities.Security; import application.securities.SecurityRepository; import application.securities.prices.Price; import application.securities.prices.PriceRepository; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import java.math.BigDecimal; import java.nio.charset.Charset; import java.util.Date; import static org.hamcrest.Matchers.is; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class PriceControllerTest { @Autowired private MockMvc mvc; @Autowired private PriceRepository priceRepository; @Autowired private SecurityRepository securityRepository; private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); @Before public void setup() { Security sec1 = createSecurity("FOO"); Security sec2 = createSecurity("BAR"); createPrice(1514764700000L, sec1, 1.00); createPrice(1514764800001L, sec1, 1.00); createPrice(1517443200000L, sec1, 1.00); createPrice(1529020800000L, sec1, 1.00); createPrice(1514764800001L, sec2, 1.50); } @After public void tearDown() { priceRepository.deleteAllInBatch(); securityRepository.deleteAllInBatch(); } private Price createPrice(long date, Security security, double value) { Price price = new Price(new Date(date), security, BigDecimal.valueOf(value)); return priceRepository.save(price); } private Security createSecurity(String symbol) { return securityRepository.save(new Security(symbol)); } @Test public void getPricesWithNoParamsReturnsAllPrices() throws Exception { long securityId = securityRepository.findBySymbol("FOO").getId(); mvc.perform(get("/securities/" + securityId + "/prices")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", hasSize(4))) .andExpect(jsonPath("$[0].date", is(1514764700000L))) .andExpect(jsonPath("$[0].value", is(1.00))); } @Test public void getPricesThrows404WhenInvalidSecurityIdPassed() throws Exception { mvc.perform(get("/securities/1000/prices")) .andExpect(status().isNotFound()); } @Test public void getPricesWithDateParamsReturnsPricesBetweenDateRange() throws Exception { long securityId = securityRepository.findBySymbol("FOO").getId(); String paramString = "start=2018-01-01T00:00:00+00:00&end=2018-02-03T00:00:00+00:00"; mvc.perform(get("/securities/" + securityId + "/prices?" + paramString)) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(2))); } @Test public void getPricesWithInvalidStartDateParamReturns400Response() throws Exception { long securityId = securityRepository.findBySymbol("FOO").getId(); String paramString = "start=someInvalidDate"; mvc.perform(get("/securities/" + securityId + "/prices?" + paramString)) .andExpect(status().isBadRequest()); } @Test public void getPricesWithInvalidEndDateParamReturns400Response() throws Exception { long securityId = securityRepository.findBySymbol("FOO").getId(); String paramString = "end=someInvalidDate"; mvc.perform(get("/securities/" + securityId + "/prices?" + paramString)) .andExpect(status().isBadRequest()); } }
import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Scanner; public class Board { private int N; // Board dimension private int[][] goalBoard; protected int[][] blocks; private int[][] copyBoard ( int[][] source ) { int result[][] = new int[N][N]; for ( int i = 0; i < N; i++ ) { for ( int j = 0; j < N; j++) { result[i][j] = source[i][j]; } } return result; } private boolean isValid ( int row, int col) { return (( row >= 0 && row < N) && ( col >= 0 && col < N)); } public Board(int[][] _blocks) { // construct a board from an N-by-N array of blocks N = _blocks.length; this.blocks = copyBoard(_blocks); // Construct a goal board for Hamming function goalBoard = new int[N][N]; int value = 0; for ( int row = 0; row < N; row++ ) { for ( int col = 0; col < N; col++ ) { goalBoard[row][col] = ++value; } } goalBoard[N-1][N-1] = 0; // Set blank block } public int dimension() { // board dimension N return N; } public int hamming() { // number of blocks out of place int outOfPlace = 0; for ( int row = 0; row < N; row++ ) { for ( int col = 0; col < N; col++ ) { if ( blocks[row][col] != goalBoard[row][col]) outOfPlace++; } } return outOfPlace; } public int manhattan() { int outOfPlace = 0; for ( int i = 0; i < N; i++) { for ( int j = 0; j < N; j++) { int row = i; int col = j; // Fancy int nrow = (blocks[row][col]-1) / N; int ncol = (blocks[row][col]-1) % N; outOfPlace += Math.abs(nrow - row) + Math.abs(ncol - col); } } return outOfPlace; } public boolean isGoal() // is this board the goal board? { return ( this.hamming() == 0 ); } public Board twin() { // a board that is obtained by exchanging two adjacent blocks in the same col int[][] temp_board; temp_board = copyBoard(blocks); // If possible, switch first two in first row if ( temp_board[0][0] != 0 && temp_board[0][1] != 0 ) { int temp = temp_board[0][0]; temp_board[0][0] = temp_board[0][1]; temp_board[0][1] = temp; } else { int temp = temp_board [1][0]; temp_board[1][0] = temp_board [1][1]; temp_board[1][1] = temp; } Board twin = new Board(temp_board); return twin; } public boolean equals(Object y) { // does this board equal y? if ( y == this ) { return true; } if ( y == null ) return false; if (!(y instanceof Board)) return false; if (Arrays.deepEquals(this.blocks, ((Board)y).blocks)) return true; return false; } public Iterable<Board> neighbors() { // all neighboring boards List<Board> boards = new ArrayList<Board>(); int blank_col = 0, blank_row = 0; for (int i = 0; i < N; i++) { // Find location of blank block for (int j = 0; j < N; j++) { if (blocks[i][j] == 0) { blank_row = i; blank_col = j; } } } // for ( int i = ... try { // Now create all possible neighbors int col_shift[] = {-1, 1, 0, 0}; int row_shift[] = {0, 0, 1, -1}; for (int row = 0, col = 0; row < 4 && col < 4; col++, row++) { if (isValid((blank_col + col_shift[col]), (blank_row + row_shift[row]))) { // Create a board copy to work with int[][] temp; temp = copyBoard(blocks); // Swap around time int d_col = col_shift[col]; int d_row = row_shift[col]; temp[blank_row][blank_col] = temp[blank_row + d_row][blank_col + d_col]; temp[blank_row + d_row][blank_col + d_col] = 0; Board neighbor = new Board(temp); //System.out.println(neighbor.toString()); boards.add(neighbor); } } } catch ( NullPointerException e) { System.out.println("An NPE occurred in method neighbors:"); System.out.println(e.getMessage()); System.out.println(e.getCause()); } catch ( IndexOutOfBoundsException e) { System.out.print("An IOBE error occurred in method neighbors:"); System.out.println(e.getMessage()); } return boards; } public String toString() { // string representation of this board (in the output format specified below) String board_string = new String(""); for ( int row = 0; row < N; row++) { for ( int col = 0; col < N; col++) { int number = blocks[row][col]; board_string += Integer.toString(blocks[row][col]); } // for ( int col board_string += "\n"; } // for ( int row... return board_string; } public static void main(String[] args) throws IOException { // unit tests (not graded) java.util.Scanner in_scanner = new Scanner(System.in); System.out.print("Enter a filename: "); String filename = in_scanner.nextLine(); Path path = Paths.get(filename); try { // Open up the text file Scanner file_in = new Scanner(path); int test_N = file_in.nextInt(); int[][] test_blocks = new int[test_N][test_N]; for ( int i = 0; i < test_N; i++) { for (int j = 0; j < test_N; j++ ) { if ( file_in.hasNextInt() ) { test_blocks[i][j] = file_in.nextInt(); } } } // for ( int i... Board test_board = new Board(test_blocks); System.out.println("Equals itself?: " + test_board.equals(test_board)); Board twin_board = test_board.twin(); System.out.println("Twin board: \n" + twin_board.toString()); String test_string = test_board.toString(); System.out.println(test_string); System.out.print("Manhattan: "); System.out.println(test_board.manhattan()); System.out.print("Hamming: "); System.out.println(test_board.hamming()); System.out.println("Is goal:" + test_board.isGoal()); System.out.println("Testing neighbors..."); for ( Board board : test_board.neighbors() ) { String neighborString = board.toString(); System.out.println(neighborString); System.out.print("Manhattan: "); System.out.println(board.manhattan()); System.out.print("Hamming: "); System.out.println(board.hamming()); System.out.println("Is goal:" + board.isGoal()); System.out.println("Equals: " + board.equals(test_board)); } // Close resources in_scanner = null; path = null; file_in = null; } // try catch ( java.util.InputMismatchException e ) { System.out.println("\nCaught an exception when reading file: "); System.out.println(e.getMessage()); } finally { if ( in_scanner != null ) { in_scanner = null; } // if } // finally } // main }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vootoo.server.netty; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.core.CoreContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.vootoo.client.netty.ProtobufRequestGetter; import org.vootoo.client.netty.protocol.SolrProtocol; import org.vootoo.common.VootooException; import org.vootoo.server.RequestProcesser; import org.vootoo.server.Vootoo; import java.net.SocketAddress; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * @author chenlb on 2015-06-04 09:15. */ public abstract class SolrRequestRunner implements Runnable { private static final Logger logger = LoggerFactory.getLogger(SolrRequestRunner.class); private static final Logger queryLogger = LoggerFactory.getLogger(Vootoo.requestLogName("Query")); private static final Logger updateLogger = LoggerFactory.getLogger(Vootoo.requestLogName("Update")); private static final Logger rejectedLogger = LoggerFactory.getLogger(Vootoo.requestLogName("Rejected")); private CoreContainer coreContainer; private ProtobufRequestGetter solrRequest; private boolean isUpdate = false; private int queryDefaultTimeout = 2000; public SolrRequestRunner(CoreContainer coreContainer, ProtobufRequestGetter solrRequest) { this.coreContainer = coreContainer; this.solrRequest = solrRequest; } protected void putMDC() { MDC.put(Vootoo.MDC_NAME_RID, String.valueOf(solrRequest.getRid())); MDC.put(Vootoo.MDC_NAME_REQUEST_SIZE, String.valueOf(solrRequest.requestSize())); MDC.put(Vootoo.MDC_NAME_REQUEST_PATH, solrRequest.getPath()); } protected void putMDCWithExecuteTime(long executeTime) { MDC.put(Vootoo.MDC_NAME_EXECUTE_TIME, String.valueOf(executeTime)); } protected void putMDCWithWaitTime(long waitTime) { MDC.put(Vootoo.MDC_NAME_WAIT_TIME, String.valueOf(waitTime)); } protected void putMDCWithRemoteAddress(String remoteAddress) { MDC.put(Vootoo.MDC_NAME_REMOTE_ADDRESS, remoteAddress); } protected void clearMDC() { MDC.remove(Vootoo.MDC_NAME_RID); MDC.remove(Vootoo.MDC_NAME_REQUEST_SIZE); MDC.remove(Vootoo.MDC_NAME_REQUEST_PATH); MDC.remove(Vootoo.MDC_NAME_EXECUTE_TIME); MDC.remove(Vootoo.MDC_NAME_WAIT_TIME); MDC.remove(Vootoo.MDC_NAME_REMOTE_ADDRESS); } protected abstract String getSocketAddress(); @Override public void run() { clearMDC(); putMDC(); putMDCWithRemoteAddress(getSocketAddress()); ProtobufResponseSetter responseSetter = new ProtobufResponseSetter(solrRequest.getRid()); try { handleRequest(responseSetter, solrRequest); } catch (Throwable t) { responseSetter.addError(t); } finally { // write solr protocol response to channel writeProtocolResponse(responseSetter.buildProtocolResponse()); } } protected abstract void writeProtocolResponse(SolrProtocol.SolrResponse protocolResponse); protected void handleRequest(ProtobufResponseSetter responeSetter, ProtobufRequestGetter solrRequest) { long waitTime = solrRequest.useTime(); //mdc log wait in queue time putMDCWithWaitTime(waitTime); Logger myLogger = isUpdate ? updateLogger : queryLogger; SolrParams solrParams = solrRequest.getSolrParams(); int timeout = solrParams.getInt(CommonParams.TIME_ALLOWED, queryDefaultTimeout); if (waitTime > timeout) {//is timeout myLogger.warn("tip={} params={{}}", "Timeout_In_Queue", solrParams); throw new VootooException(VootooException.VootooErrorCode.TIMEOUT, "timeout stay in RequestQueue"); } if(myLogger.isDebugEnabled()) { myLogger.debug("tip={} params={{}}", "Start_Execute", solrRequest.getSolrParams()); } RequestProcesser requestHandler = new RequestProcesser(coreContainer, responeSetter); long st = System.currentTimeMillis(); requestHandler.handleRequest(solrRequest); long ut = System.currentTimeMillis() - st; //mdc log execute time putMDCWithExecuteTime(ut); //log if(responeSetter.getSolrQueryResponse() != null && responeSetter.getSolrQueryResponse().getToLog().size() > 0) { NamedList<Object> myToLog = responeSetter.getSolrQueryResponse().getToLog(); String plog = toLogString(myToLog); myLogger.info("{}", plog); } else { myLogger.info("params={{}}", solrParams); } } protected static final Set<String> toLogNames; static { Set<String> logNames = new HashSet<>(); logNames.add("params"); logNames.add("hits"); logNames.add("status"); logNames.add("QTime"); toLogNames = Collections.unmodifiableSet(logNames); } protected String toLogString(NamedList<Object> toLog) { StringBuilder sb = new StringBuilder(); for (int i=0; i<toLog.size(); i++) { String name = toLog.getName(i); if(!toLogNames.contains(name)) { continue; } Object val = toLog.getVal(i); if (name != null) { sb.append(name).append('='); } sb.append(val).append(' '); } return sb.toString(); } protected void logRejected() { clearMDC(); putMDC(); putMDCWithRemoteAddress(getSocketAddress()); rejectedLogger.warn("tip={} params={{}}", "Request_Rejected", solrRequest.getSolrParams()); } public void setIsUpdate(boolean isUpdate) { this.isUpdate = isUpdate; } }
package com.algorithm.tree; public class SumNumbers { static int sum = 0; public static int sumNumbers(TreeNode root) { if(root == null){ return 0; } dfs(root,0); return sum; } private static void dfs(TreeNode root, int father) { if(root == null){ return; } int cur = father*10 + root.val; if(root.left == null && root.right == null){ sum +=cur; return; } dfs(root.left,cur); dfs(root.right,cur); } public static void main(String[] args) { TreeNode treeNode = new TreeNode(4); treeNode.left = new TreeNode(9); treeNode.right = new TreeNode(0); treeNode.left.left = new TreeNode(5); treeNode.left.right = new TreeNode(1); sumNumbers2(treeNode); } static int sum2 = 0; public static int sumNumbers2(TreeNode root) { dfs2(root , new StringBuilder()); return sum2; } private static void dfs2(TreeNode root , StringBuilder stringBuilder) { if(root == null){ return; } StringBuilder temp = stringBuilder.append(root.val); if(root.left == null && root.right == null){ sum2 += Integer.valueOf(stringBuilder.toString()); return; } // StringBuilder temp = new StringBuilder(stringBuilder); dfs2(root.left,temp); dfs2(root.right,temp); } }
/* * Copyright (c) 2004 Steve Northover and Mike Wilson * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ package part3.fileexplorer; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; import java.io.*; /** * @author Steve Northover * * DeleteOperation performs a file delete operation. * If the file is a folder, then all files within the * folder are deleted as well as the folder. * * Thursday June 17, 2004. */ public class DeleteOperation extends FileOperation { /** * Constructs a new instance of a delete operation. * * @param shell the parent shell for the verify dialog * @param files an array of files for the operation */ public DeleteOperation (Shell shell, File [] files) { super (shell, files); } int computeTotal (File [] files) { /* Include the files that have already been deleted */ return count + countFiles (files); } /** * Deletes a file or folder. * * @param file * @return true if the operation was successful; false otherwise */ boolean delete (File file) { if (!check (file, false)) return false; if (file.isDirectory ()) { File [] files = file.listFiles (); for (int i=files.length-1; i>=0; --i) { if (!delete (files [i])) return false; } } else { if (!check (file, true)) return false; } return file.delete (); } String getText () { return FileExplorer.getMessage ("Deleting ..."); } String getMessage (File file) { return FileExplorer.getMessage ("Deleting {0}", new Object [] {file.getAbsolutePath ()}); } /** * Delete the files in the array. * * @param files the files for the operation * @return true if the operation was successful; false otherwise */ boolean operation (File [] files) { for (int i=0; i<files.length; i++) { if (!delete (files [i])) return false; } return true; } boolean verify () { MessageBox dialog = new MessageBox (shell, SWT.ICON_QUESTION | SWT.YES | SWT.NO); String names = ""; for (int i=0; i<files.length; i++) { names += " \"" + files [i] + "\"" + (i == files.length - 1 ? "" : ","); } dialog.setMessage ("DEBUG: Confirm delete " + files.length + " file(s): " + names + "?"); //bad nls return dialog.open () == SWT.YES; } }
package JavaExe; import java.util.Scanner; public class FourFourteen { public static void main(String[] args) { System.out.println("数値を入力してください"); Scanner stdInt = new Scanner(System.in); int number = stdInt.nextInt(); System.out.println("数値の合計を求めます"); int sum = 0; String sentense = ""; for (int i = 0; i <= number; i++) { sentense = sentense + "+" + i; sum = sum + i; } System.out.println("合計する式は" + sentense + "です"); System.out.println("合計は" + sum + "です"); } }
package com.saechimdaeki.chap04; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.reactive.ReactiveCrudRepository; import reactor.core.publisher.Flux; public interface ItemRepository extends ReactiveCrudRepository<Item, String> { Flux<Item> findByNameContaining(String partialName); @Query("{ 'name' : ?0, 'age' : }") Flux<Item> findItemsForCustomerMonthlyReport(); @Query(sort = "{ 'age' : -1", value = "{ 'name' : 'TV tray', 'age' : }") Flux<Item> findSortedStuffForWeeklyReport(); Flux<Item> findByNameContainingIgnoreCase(String partialName); Flux<Item> findByDescriptionContainingIgnoreCase(String partialName); Flux<Item> findByNameContainingAndDescriptionContainingAllIgnoreCase(String partialName, String partialDesc); Flux<Item> findByNameContainingOrDescriptionContainingAllIgnoreCase(String partialName, String partialDesc); }
package extraction; import image.PixelMap; import java.util.ArrayList; public class CovarianceMatrix { public static ArrayList<Integer[]> toVector( PixelMap pixMap ) { ArrayList<Integer[]> pixvector = new ArrayList<Integer[]> (); int width = pixMap.getWidth(); int height = pixMap.getHeight(); for(int i = 0; i < width; i++) { for(int j = 0; j < height; j++) { Integer ig[] = new Integer[3]; int[] pix = pixMap.getPixel(i, j); ig[0] = pix[0]; ig[1] = pix[1]; ig[2] = pix[2]; pixvector.add(ig); } } return pixvector; } public static Integer[] computeMean(ArrayList<Integer[]> pixvector) { Integer[] mean = new Integer[3]; for(int i = 0; i < pixvector.size(); i++) { Integer[] temp = pixvector.get(i); mean[0] += temp[0]; mean[1] += temp[1]; mean[2] += temp[2]; } for(int i = 0; i < 3; i++) { mean[i] /= pixvector.size(); } return mean; } public static double covariance (ArrayList<Integer[]> pixvector, Integer[] mean, int x, int y) { double covariance = 0f; for( int i = 0; i < 3; i++) { for( int j = 0; j < 3; j++) { covariance += (pixvector.get(x)[i] - mean[i]) * (pixvector.get(y)[j] - mean[j]); } } return covariance; } }
package com.arthur.bishi.wangyi0828; import java.util.Scanner; /** * @description: * @author: arthurji * @date: 2021/8/28 15:24 * @modifiedBy: * @version: 1.0 */ public class No3 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int[] nums = new int[n * m]; for (int i = 0; i < nums.length; i++) { nums[i] = scanner.nextInt(); } int q = scanner.nextInt(); for (int i = 0; i < q; i++) { int L = scanner.nextInt(); } } }
package com.txxlc.social.qq.connect; import com.txxlc.social.qq.api.service.QQ; import com.txxlc.social.qq.api.serviceimpl.QQImpl; import org.springframework.social.oauth2.AbstractOAuth2ServiceProvider; import org.springframework.social.oauth2.OAuth2Template; public class QQServiceProvider extends AbstractOAuth2ServiceProvider<QQ> { private String appId; private static final String URL_AUTHORIZE="https://graph.qq.com/oauth2.0/authorize"; private static final String URL_ACCESS_TOKEN="https://graph.qq.com/oauth2.0/token"; public QQServiceProvider(String appId,String appSecret) { super(new QQOauth2Template(appId,appSecret,URL_AUTHORIZE,URL_ACCESS_TOKEN)); this.appId=appId; } @Override public QQ getApi(String accessToken) { return new QQImpl(accessToken,appId); } }
package com.zjf.myself.codebase.fragment; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.view.ViewStub; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.RelativeLayout; import android.widget.TextView; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.util.StringUtil; import com.zjf.myself.codebase.view.LoadingView; public class WebviewFragment extends BaseFragment { private WebView webView; private LoadingView loadingView; public static final int TITLE_TYPE_MAIN=1; public static final int TITLE_TYPE_SECOND=2; public static final int TITLE_TYPE_NONE=0; String url,title; int titleType; public static WebviewFragment newInstance(String title,int titleType,String url) { WebviewFragment f = new WebviewFragment(); Bundle bundle=new Bundle(); bundle.putString("title", title); bundle.putString("url", url); bundle.putInt("titleType",titleType); f.setArguments(bundle); return f; } @Override protected void initView(Bundle bundle) { url = bundle.getString("url"); if (StringUtil.isNull(url)) { return; } title = bundle.getString("title"); if (StringUtil.isNull(title)) { return; } titleType = bundle.getInt("titleType", TITLE_TYPE_NONE); loadingView= (LoadingView) findViewById(R.id.loadingView); ViewStub vstubTitle = (ViewStub) findViewById(R.id.vstubTitle); if (titleType == TITLE_TYPE_MAIN) { vstubTitle.setLayoutResource(R.layout.layout_main_title); View v = vstubTitle.inflate(); v.setId(R.id.layoutTitle); TextView txtTitle = (TextView) findViewById(R.id.txtTitle); txtTitle.setText(title); int mainTileHeight = (int) getActivity().getResources().getDimension(R.dimen.main_title_height); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(-1, mainTileHeight); v.setLayoutParams(layoutParams); } else if (titleType == TITLE_TYPE_SECOND) { vstubTitle.setLayoutResource(R.layout.layout_second_title); View v = vstubTitle.inflate(); v.setId(R.id.layoutTitle); int tileHeight = (int) getActivity().getResources().getDimension(R.dimen.second_title_height); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(-1, tileHeight); v.setLayoutParams(layoutParams); TextView txtTitle = (TextView) findViewById(R.id.txtTitle); txtTitle.setText(title); findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getActivity().finish(); } }); } else { // vstubTitle.setLayoutResource(R.layout.layout_main_title); // // View v=vstubTitle.inflate(); } webView = (WebView) findViewById(R.id.web_view); RelativeLayout.LayoutParams webViewlayoutParams = new RelativeLayout.LayoutParams(-1, -1); webViewlayoutParams.addRule(RelativeLayout.BELOW,R.id.layoutTitle); WebSettings settings = webView.getSettings(); settings.setAppCacheEnabled(true); settings.setDatabaseEnabled(true); settings.setDomStorageEnabled(true);//开启DOM缓存,关闭的话H5自身的一些操作是无效的 settings.setCacheMode(WebSettings.LOAD_DEFAULT); webView.getSettings().setJavaScriptEnabled(true); // // webView.loadUrl(url); // //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为,使网页用WebView打开 // webView.setWebViewClient(new WebViewClient(){ //// @Override //// public boolean shouldOverrideUrlLoading(WebView view, String url) { //// // TODO Auto-generated method stub //// //返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器 //// view.loadUrl(url); //// return true; //// } // // @Override // public void onPageStarted(WebView view, String url, Bitmap favicon) // { // super.onPageStarted(view, url, favicon); //// new LoadingDialog().show(); // } // // @Override // public void onPageFinished(WebView view, String url) // { // super.onPageFinished(view, url); //// new LoadingDialog().dismiss(); // } // // }); // } // webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); loadingView.startLoading("正在加载,请稍后"); } @Override public void onPageFinished(WebView view, String url) { loadingView.onLoadingComplete(); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url);//当打开新的连接时,使用当前的webview,不使用系统其他浏览器 return true; } }); webView.loadUrl(url); } private void setTitle(String title){ if(titleType==TITLE_TYPE_SECOND){ findViewById(R.id.btnBack).setVisibility(View.GONE); } TextView txtTitle= (TextView) findViewById(R.id.txtTitle); txtTitle.setText(title); } @Override protected void initView() { } @Override protected int layoutId() { // TODO Auto-generated method stub return R.layout.webview; } }
package 泛型测试类项目; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * 测试证明, List<T>中可以添加任何T的子类 * @createTime 2018年3月12日 下午5:34:21 * @author MrWang */ public class TTest { public static void main(String[] args) { /*List<A> list = new ArrayList<>(); list.add(new B("hello")); System.out.println(list);*/ List<List> list = new ArrayList<>(); list.add(new ArrayList()); list.add(new LinkedList()); System.out.println(list); } static class A{ private String name; public A(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "A [name=" + name + "]"; } } static class B extends A{ public B(String name) { super(name); // TODO Auto-generated constructor stub } @Override public String toString() { return "B []"; } } }
package com.bofsoft.laio.customerservice.Adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.bofsoft.laio.customerservice.R; import com.bofsoft.laio.customerservice.Widget.LoadMoreRecyclerView; import java.util.List; import java.util.Map; /** * Created by szw on 2017/3/8. */ public class SmsWarningAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener { private final static int sum = 10; private List<Map<String, Object>> mValues; private boolean mIsStagger; // private IndexActivity indexActivity; public SmsWarningAdapter(List<Map<String, Object>> items) { mValues = items; } public void switchMode(boolean mIsStagger) { this.mIsStagger = mIsStagger; } public void setData(List<Map<String, Object>> datas) { mValues = datas; } public void addDatas(List<Map<String, Object>> datas, int time) { int start = time * sum; for (int i = start; i < datas.size(); i++) { mValues.add(i, datas.get(i)); } // mValues.addAll(datas); } private SmsWarningAdapter.OnRecyclerViewItemClickListener mOnItemClickListener = null; public void setOnItemClickListener(SmsWarningAdapter.OnRecyclerViewItemClickListener listener) { this.mOnItemClickListener = listener; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // indexActivity = (IndexActivity) parent.getContext(); if (viewType == LoadMoreRecyclerView.TYPE_STAGGER) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.fragment_item_staggel, parent, false); return new SmsWarningAdapter.StaggerViewHolder(view); } else { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.activity_smswarning_item, parent, false); view.setOnClickListener(this); return new SmsWarningAdapter.ViewHolder(view); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (mIsStagger) { SmsWarningAdapter.StaggerViewHolder staggerViewHolder = (SmsWarningAdapter.StaggerViewHolder) holder; staggerViewHolder.iconView.setVisibility(View.VISIBLE); // staggerViewHolder.mContentView.setText(mValues.get(position).License); } else { SmsWarningAdapter.ViewHolder mHolder = (SmsWarningAdapter.ViewHolder) holder; mHolder.mItem = mValues.get(position); mHolder.mView.setTag(mValues.get(position)); mHolder.tv_warningLicense.setText((String) mValues.get(position).get("ShowName")); mHolder.tv_warningMsg.setText((String) mValues.get(position).get("Msg")); mHolder.tv_warningDate.setText((String) mValues.get(position).get("Time")); } } @Override public void onClick(View v) { if (mOnItemClickListener != null) { //注意这里使用getTag方法获取数据 mOnItemClickListener.onItemClick(v, (Map<String, Object>) v.getTag()); } } @Override public int getItemCount() { return mValues.size(); } public class StaggerViewHolder extends RecyclerView.ViewHolder { public View mView; public View iconView; public TextView mContentView; public StaggerViewHolder(View itemView) { super(itemView); mView = itemView; iconView = itemView.findViewById(R.id.icon); mContentView = (TextView) itemView.findViewById(R.id.content); } } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public final TextView tv_warningLicense; public final TextView tv_warningMsg; public final TextView tv_warningDate; public Map<String, Object> mItem; public ViewHolder(View view) { super(view); mView = view; tv_warningLicense = (TextView) view.findViewById(R.id.tv_warningLicense); tv_warningMsg = (TextView) view.findViewById(R.id.tv_warningMsg); tv_warningDate = (TextView) view.findViewById(R.id.tv_warningDate); } @Override public String toString() { return super.toString() + " '" + tv_warningLicense.getText() + "'"; } } public interface OnRecyclerViewItemClickListener { void onItemClick(View view, Map<String, Object> data); } }
package com.basicRest; import org.testng.Assert; import org.testng.annotations.Test; import com.Files.Payload; import io.restassured.path.json.JsonPath; public class SumValidation { @Test public void check() { int sum=0; JsonPath jsp=new JsonPath(Payload.coursePrice()); int count=jsp.getInt("courses.size()"); for(int i=0;i<count;i++) { int prices=jsp.getInt("courses["+i+"].price"); int copies=jsp.getInt("courses["+i+"].copies"); int amount=prices*copies; System.out.println(amount); sum=sum+amount; } System.out.println(sum); int purchaseAmount =jsp.getInt("dashboard.purchaseAmount"); Assert.assertEquals(sum, purchaseAmount); } }
package com.hcl.neo.eloader.microservices.producer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import org.springframework.stereotype.Component; import com.hcl.neo.eloader.common.JsonApi; import com.hcl.neo.eloader.common.Logger; import com.hcl.neo.eloader.microservices.logger.ServiceLogger; import com.hcl.neo.eloader.microservices.params.ArchiveManager; import com.hcl.neo.eloader.microservices.params.BulkJobParams; import com.hcl.neo.eloader.microservices.params.BulkJobType; import com.hcl.neo.eloader.microservices.params.ExportContentParams; import com.hcl.neo.eloader.microservices.params.ExportMetadataParams; import com.hcl.neo.eloader.microservices.params.ImportContentParams; import com.hcl.neo.eloader.microservices.params.ImportMetadataParams; import com.hcl.neo.eloader.microservices.params.ImportParams; import com.hcl.neo.eloader.microservices.params.ObjectIdentity; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; /** * @author souvik.das * * This class is created to Push the details of newly created Job in activemq * */ @Component public class JMSProducer { protected final Log logger = LogFactory.getLog(getClass()); @Autowired private JmsTemplate bulkJobHeavyQueue; @Autowired private JmsTemplate bulkJobLightQueue; @Value("${heavyJobMinSize}") private String heavyJobMinSize; @Value("${jms.queue.heavyjobWrapper}") private String heavyJobDestination; @Value("${jms.queue.lightjobWrapper}") private String lightJobDestination; @Autowired private ArchiveManager archiveManager; public void queueJob(BulkJobParams params) throws Throwable { ServiceLogger.info(this, " + queueJob()"); sendImportWrapperMsg(params); ServiceLogger.info(this, " - queueJob()"); } public void sendImportWrapperMsg(final BulkJobParams params) throws Throwable { ServiceLogger.info(this, " + sendBulkJobMsg()"); long size = params.getPackageSize(); long minSize = Long.parseLong(heavyJobMinSize); if (BulkJobType.IMPORT.equals(params.getType()) || BulkJobType.INGESTION.equals(params.getType())) { final ImportParams operationParams = archiveManager.toImportParams(params); Logger.info(getClass(), JsonApi.toJson(operationParams)); Logger.info(getClass(), "operationParams - " + operationParams + "repo name -- " +operationParams.getRepository()); final ImportContentParams importContentParams = toImportContentParams(operationParams); ServiceLogger.info(this, " - sendBulkJobMsg() "+importContentParams.toString()); Logger.info(getClass(), importContentParams.toString()); System.out.println(JsonApi.toJson(importContentParams)); if (size > minSize) { bulkJobHeavyQueue.send(heavyJobDestination, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage message = session.createTextMessage(JsonApi.toJson(importContentParams)); return message; } }); } else { boolean flag = createLightJobQueue(JsonApi.toJson(importContentParams)); ServiceLogger.info(this, " - flag() "+flag); } ServiceLogger.info(this, " - sendBulkJobMsg() "); }else if(BulkJobType.IMPORT_METADATA.equals(params.getType())){ final ImportMetadataParams operationParams = archiveManager.toImportMetadataParams(params); ServiceLogger.info(this, " - sendBulkJobMsg() "+operationParams.toString()); Logger.info(getClass(), operationParams.toString()); if (size > minSize) { bulkJobHeavyQueue.send(heavyJobDestination, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage message = session.createTextMessage(JsonApi.toJson(operationParams)); return message; } }); } else { boolean flag = createLightJobQueue(JsonApi.toJson(operationParams)); ServiceLogger.info(this, " - flag() "+flag); } ServiceLogger.info(this, " - sendBulkJobMsg() "); }else if(BulkJobType.EXPORT_METADATA.equals(params.getType())){ final ExportMetadataParams operationParams = archiveManager.toExportMetadataParams(params); ServiceLogger.info(this, " - sendBulkJobMsg() "+operationParams.toString()); final ExportContentParams exportContentParams = toExportMetadataParams(operationParams); Logger.info(getClass(), exportContentParams.toString()); if (size > minSize) { bulkJobHeavyQueue.send(heavyJobDestination, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage message = session.createTextMessage(JsonApi.toJson(exportContentParams)); return message; } }); } else { boolean flag = createLightJobQueue(JsonApi.toJson(exportContentParams)); ServiceLogger.info(this, " - flag() "+flag); } ServiceLogger.info(this, " - sendBulkJobMsg() "); } } @HystrixCommand(fallbackMethod = "errorQueue") private boolean createLightJobQueue(final String messageText){ boolean flag = true; try{ bulkJobLightQueue.send(lightJobDestination, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { TextMessage message = session.createTextMessage(messageText); return message; } }); }catch(Throwable th){ flag = false; throw th; } return flag; } @SuppressWarnings("unused") private boolean errorLightJobQueue(final String message) throws Throwable{ ServiceLogger.info(this, " - fallback method for " + message +" . Not queued in activeMQ"); throw new Error("Error in queue"); } @SuppressWarnings({ "unchecked", "rawtypes" }) private ImportContentParams toImportContentParams(ImportParams operationParams){ ImportContentParams importContentParams = ImportContentParams.newObject(); importContentParams.setImportResourceFork(false); importContentParams.setObjectTypes(new HashMap()); importContentParams.setOwnerName(operationParams.getOwnerName()); ObjectIdentity destFolder = new ObjectIdentity(); destFolder.setObjectPath(operationParams.getRepositoryPath()); importContentParams.setDestFolder(destFolder); importContentParams.setSrcPathList(operationParams.getLocalPath()); importContentParams.setId((operationParams.getId() == null) ? 0 : operationParams.getId()); importContentParams.setRepository(operationParams.getRepository()); importContentParams.setJobType(operationParams.getJobType()); return importContentParams; } private ExportContentParams toExportMetadataParams(ExportMetadataParams params){ ExportContentParams exportContentParams = new ExportContentParams(); exportContentParams.setDestDir(params.getLocalPath()); List<ObjectIdentity> list = new ArrayList<ObjectIdentity>(); for(String path : params.getRepositoryPath()){ ObjectIdentity objectIdentity = new ObjectIdentity(); objectIdentity.setObjectPath(path); list.add(objectIdentity); } exportContentParams.setObjectList(list); exportContentParams.setId(params.getId()); exportContentParams.setRepository(params.getRepository()); return exportContentParams; } }
package jire.task; public abstract class CycledTask extends AbstractTask { private final int cycles; private int countdown; public CycledTask(int cycles) { this.cycles = countdown = cycles; } @Override public final boolean run() { if (--countdown < 1) { countdown = cycles; return super.run(); } return isRunning(); } }
package lab.tiyo.trigonometry; import android.test.AndroidTestCase; import junit.framework.Assert; import org.junit.Test; import lab.tiyo.fraction.models.Fraction; import lab.tiyo.fraction.models.FractionNumber; import lab.tiyo.fraction.models.TNumber; import lab.tiyo.trigonometry.helpers.MathHelper; /** * Created by root on 07/01/17. */ public class MathHelperProductIntegerTest extends AndroidTestCase { public void testIntegerNumberTypeInteger(){ /** * A * A * 2 * 2 */ TNumber t1a = new TNumber(); t1a.setType(TNumber.INTEGER_NUMBER); t1a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t1b = new TNumber(); t1b.setType(TNumber.INTEGER_NUMBER); t1b.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t1c = MathHelper.product(t1a, t1b); Assert.assertEquals(TNumber.INTEGER_NUMBER, t1c.getType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t1c.getIntegerNumber().getNumberType()); Assert.assertEquals(4.0, t1c.getValue()); Assert.assertEquals(4.0, t1c.getIntegerNumber().getIntegerValue()); Assert.assertEquals(4.0, t1c.getIntegerNumber().getDecimalValue()); /** * A * /A * 2 * /2 */ TNumber t2a = new TNumber(); t2a.setType(TNumber.INTEGER_NUMBER); t2a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t2b = new TNumber(); t2b.setType(TNumber.INTEGER_NUMBER); t2b.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t2c = MathHelper.product(t2a, t2b); Assert.assertEquals(TNumber.INTEGER_NUMBER, t2c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t2c.getIntegerNumber().getNumberType()); Assert.assertEquals(2 * Math.sqrt(2), t2c.getValue()); Assert.assertEquals(2.0, t2c.getIntegerNumber().getIntegerValue()); Assert.assertEquals(2,t2c.getIntegerNumber().getRootValue()); Assert.assertEquals(2 * Math.sqrt(2), t2c.getIntegerNumber().getDecimalValue()); /** * A * A/B * 2 * 2/2 */ TNumber t3a = new TNumber(); t3a.setType(TNumber.INTEGER_NUMBER); t3a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t3b = new TNumber(); t3b.setType(TNumber.INTEGER_NUMBER); t3b.setIntegerNumber(new FractionNumber(3, 0, 2, 2)); TNumber t3c = MathHelper.product(t3a, t3b); Assert.assertEquals(TNumber.INTEGER_NUMBER, t3c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t3c.getIntegerNumber().getNumberType()); Assert.assertEquals(4 * Math.sqrt(2), t3c.getValue()); Assert.assertEquals(4.0, t3c.getIntegerNumber().getIntegerValue()); Assert.assertEquals(2,t3c.getIntegerNumber().getRootValue()); Assert.assertEquals(4 * Math.sqrt(2), t3c.getIntegerNumber().getDecimalValue()); /** * (A) * (A // B) * 2 * 3 // 4 */ TNumber t4a = new TNumber(); t4a.setType(TNumber.INTEGER_NUMBER); t4a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t4b = new TNumber(); t4b.setType(TNumber.FRACTION_NUMBER); t4b.setFraction(new Fraction(new FractionNumber(1, 0, 3, 1), new FractionNumber(1, 0, 4, 1))); TNumber t4c = MathHelper.product(t4a, t4b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t4c.getType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t4c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t4c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(6.0 / 4.0, t4c.getValue()); Assert.assertEquals(6.0, t4c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(1,t4c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(6.0, t4c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(4.0, t4c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(1,t4c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(4.0, t4c.getFraction().getSecondFraction().getDecimalValue()); /** * (A) * (A // /B) * 2 * 3 // /4 */ TNumber t5a = new TNumber(); t5a.setType(TNumber.INTEGER_NUMBER); t5a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t5b = new TNumber(); t5b.setType(TNumber.FRACTION_NUMBER); t5b.setFraction(new Fraction(new FractionNumber(1, 0, 3, 1), new FractionNumber(2, 0, 1, 4))); TNumber t5c = MathHelper.product(t5a, t5b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t5c.getType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t5c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t5c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(6.0 / Math.sqrt(4), t5c.getValue()); Assert.assertEquals(6.0, t5c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(1,t5c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(6.0, t5c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(1.0, t5c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(4,t5c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(Math.sqrt(4), t5c.getFraction().getSecondFraction().getDecimalValue()); /** * (A) * (A // B/C) * 2 * 3 // 4/5 */ TNumber t6a = new TNumber(); t6a.setType(TNumber.INTEGER_NUMBER); t6a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t6b = new TNumber(); t6b.setType(TNumber.FRACTION_NUMBER); t6b.setFraction(new Fraction(new FractionNumber(1, 0, 3, 1), new FractionNumber(3, 0, 4, 5))); TNumber t6c = MathHelper.product(t6a, t6b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t6c.getType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t6c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t6c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(6.0 / (4.0 * Math.sqrt(5)), t6c.getValue()); Assert.assertEquals(6.0, t6c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(1,t6c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(6.0, t6c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(4.0, t6c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(5, t6c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(4 * Math.sqrt(5), t6c.getFraction().getSecondFraction().getDecimalValue()); /** * (A) * (/A // B) * 2 * /3 // 4 */ TNumber t7a = new TNumber(); t7a.setType(TNumber.INTEGER_NUMBER); t7a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t7b = new TNumber(); t7b.setType(TNumber.FRACTION_NUMBER); t7b.setFraction(new Fraction(new FractionNumber(2, 0, 1, 3), new FractionNumber(1, 0, 4, 1))); TNumber t7c = MathHelper.product(t7a, t7b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t7c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t7c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t7c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(2.0 * Math.sqrt(3.0) / 4.0, t7c.getValue()); Assert.assertEquals(2.0, t7c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(3,t7c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(2 * Math.sqrt(3), t7c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(4.0, t7c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(1, t7c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(4.0, t7c.getFraction().getSecondFraction().getDecimalValue()); /** * (A) * (/A // /B) * 2 * /3 // /4 */ TNumber t8a = new TNumber(); t8a.setType(TNumber.INTEGER_NUMBER); t8a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t8b = new TNumber(); t8b.setType(TNumber.FRACTION_NUMBER); t8b.setFraction(new Fraction(new FractionNumber(2, 0, 1, 3), new FractionNumber(2, 0, 1, 4))); TNumber t8c = MathHelper.product(t8a, t8b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t8c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t8c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t8c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(2.0 * Math.sqrt(3.0) / Math.sqrt(4), t8c.getValue()); Assert.assertEquals(2.0, t8c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(3,t8c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(2 * Math.sqrt(3), t8c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(1.0, t8c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(4, t8c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(Math.sqrt(4), t8c.getFraction().getSecondFraction().getDecimalValue()); /** * (A) * (/A // B/C) * 2 * /3 // 4/5 */ TNumber t9a = new TNumber(); t9a.setType(TNumber.INTEGER_NUMBER); t9a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t9b = new TNumber(); t9b.setType(TNumber.FRACTION_NUMBER); t9b.setFraction(new Fraction(new FractionNumber(1, 0, 1, 3), new FractionNumber(3, 0, 4, 5))); TNumber t9c = MathHelper.product(t9a, t9b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t9c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t9c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t9c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(2.0 * Math.sqrt(3.0) / (4.0 * Math.sqrt(5)), t9c.getValue()); Assert.assertEquals(2.0, t9c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(3,t9c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(2 * Math.sqrt(3), t9c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(4.0, t9c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(5, t9c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(4 * Math.sqrt(5), t9c.getFraction().getSecondFraction().getDecimalValue()); /** * (A) * (A/B // C) * 2 * 3/4 // 5 */ TNumber t10a = new TNumber(); t10a.setType(TNumber.INTEGER_NUMBER); t10a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t10b = new TNumber(); t10b.setType(TNumber.FRACTION_NUMBER); t10b.setFraction(new Fraction(new FractionNumber(2, 0, 3, 4), new FractionNumber(1, 0, 5, 1))); TNumber t10c = MathHelper.product(t10a, t10b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t10c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t10c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t10c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(6.0 * Math.sqrt(4.0) / 5.0, t10c.getValue()); Assert.assertEquals(6.0, t10c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(4,t10c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(6.0 * Math.sqrt(4), t10c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(5.0, t10c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(1, t10c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(5.0, t10c.getFraction().getSecondFraction().getDecimalValue()); /** * (A) * (A/B // /C) * 2 * 3/4 // /5 */ TNumber t11a = new TNumber(); t11a.setType(TNumber.INTEGER_NUMBER); t11a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t11b = new TNumber(); t11b.setType(TNumber.FRACTION_NUMBER); t11b.setFraction(new Fraction(new FractionNumber(3, 0, 3, 4), new FractionNumber(2, 0, 1, 5))); TNumber t11c = MathHelper.product(t11a, t11b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t11c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t11c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t11c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(6.0 * Math.sqrt(4.0) / Math.sqrt(5), t11c.getValue()); Assert.assertEquals(6.0, t11c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(4,t11c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(6.0 * Math.sqrt(4), t11c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(1.0, t11c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(5, t11c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(Math.sqrt(5), t11c.getFraction().getSecondFraction().getDecimalValue()); /** * (A) * (A/B // C/CD) * 2 * 3/4 // 5/6 */ TNumber t12a = new TNumber(); t12a.setType(TNumber.INTEGER_NUMBER); t12a.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t12b = new TNumber(); t12b.setType(TNumber.FRACTION_NUMBER); t12b.setFraction(new Fraction(new FractionNumber(3, 0, 3, 4), new FractionNumber(3, 0, 5, 6))); TNumber t12c = MathHelper.product(t12a, t12b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t12c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t12c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t12c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(6.0 * Math.sqrt(4.0) / (5.0 * Math.sqrt(6)), t12c.getValue()); Assert.assertEquals(6.0, t12c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(4,t12c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(6 * Math.sqrt(4), t12c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(5.0, t12c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(6, t12c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(5 * Math.sqrt(6), t12c.getFraction().getSecondFraction().getDecimalValue()); /** * /A * A * /2 * 2 */ TNumber t13a = new TNumber(); t13a.setType(TNumber.INTEGER_NUMBER); t13a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t13b = new TNumber(); t13b.setType(TNumber.INTEGER_NUMBER); t13b.setIntegerNumber(new FractionNumber(1, 0, 2, 1)); TNumber t13c = MathHelper.product(t13a, t13b); Assert.assertEquals(TNumber.INTEGER_NUMBER, t13c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t13c.getIntegerNumber().getNumberType()); Assert.assertEquals(2.0 * Math.sqrt(2), t13c.getValue()); Assert.assertEquals(2.0, t13c.getIntegerNumber().getIntegerValue()); Assert.assertEquals(2, t13c.getIntegerNumber().getRootValue()); /** * /A * /A * /2 * /2 */ TNumber t14a = new TNumber(); t14a.setType(TNumber.INTEGER_NUMBER); t14a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t14b = new TNumber(); t14b.setType(TNumber.INTEGER_NUMBER); t14b.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t14c = MathHelper.product(t14a, t14b); Assert.assertEquals(TNumber.INTEGER_NUMBER, t14c.getType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t14c.getIntegerNumber().getNumberType()); Assert.assertEquals(2.0, t14c.getValue()); Assert.assertEquals(1.0, t14c.getIntegerNumber().getIntegerValue()); Assert.assertEquals(4,t14c.getIntegerNumber().getRootValue()); Assert.assertEquals(2.0, t14c.getIntegerNumber().getDecimalValue()); /** * /A * A/B * /2 * 3/4 */ TNumber t15a = new TNumber(); t15a.setType(TNumber.INTEGER_NUMBER); t15a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t15b = new TNumber(); t15b.setType(TNumber.INTEGER_NUMBER); t15b.setIntegerNumber(new FractionNumber(3, 0, 3, 4)); TNumber t15c = MathHelper.product(t15a, t15b); Assert.assertEquals(TNumber.INTEGER_NUMBER, t15c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t15c.getIntegerNumber().getNumberType()); Assert.assertEquals(Math.sqrt(2) * 3 * Math.sqrt(4), t15c.getValue()); Assert.assertEquals(3.0, t15c.getIntegerNumber().getIntegerValue()); Assert.assertEquals(8,t15c.getIntegerNumber().getRootValue()); Assert.assertEquals(Math.sqrt(2) * 3 * Math.sqrt(4), t15c.getIntegerNumber().getDecimalValue()); /** * (/A) * (A // B) * /2 * 3 // 4 */ TNumber t16a = new TNumber(); t16a.setType(TNumber.INTEGER_NUMBER); t16a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t16b = new TNumber(); t16b.setType(TNumber.FRACTION_NUMBER); t16b.setFraction(new Fraction(new FractionNumber(1, 0, 3, 1), new FractionNumber(1, 0, 4, 1))); TNumber t16c = MathHelper.product(t16a, t16b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t16c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t16c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t16c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(Math.sqrt(2) * 3.0 / 4.0, t16c.getValue()); Assert.assertEquals(3.0, t16c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(2,t16c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(3 * Math.sqrt(2), t16c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(4.0, t16c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(1,t16c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(4.0, t16c.getFraction().getSecondFraction().getDecimalValue()); /** * (/A) * (A // /B) * /2 * 3 // /4 */ TNumber t17a = new TNumber(); t17a.setType(TNumber.INTEGER_NUMBER); t17a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t17b = new TNumber(); t17b.setType(TNumber.FRACTION_NUMBER); t17b.setFraction(new Fraction(new FractionNumber(1, 0, 3, 1), new FractionNumber(2, 0, 1, 4))); TNumber t17c = MathHelper.product(t17a, t17b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t17c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t17c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t17c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(Math.sqrt(2) * 3 / Math.sqrt(4), t17c.getValue()); Assert.assertEquals(3.0, t17c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(2,t17c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(Math.sqrt(2) * 3.0, t17c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(1.0, t17c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(4,t17c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(Math.sqrt(4), t17c.getFraction().getSecondFraction().getDecimalValue()); /** * (/A) * (B // C/D) * /2 * 3 // 4/5 */ TNumber t18a = new TNumber(); t18a.setType(TNumber.INTEGER_NUMBER); t18a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t18b = new TNumber(); t18b.setType(TNumber.FRACTION_NUMBER); t18b.setFraction(new Fraction(new FractionNumber(1, 0, 3, 1), new FractionNumber(3, 0, 4, 5))); TNumber t18c = MathHelper.product(t18a, t18b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t18c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t18c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t18c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(Math.sqrt(2) * 3 / (4.0 * Math.sqrt(5)), t18c.getValue()); Assert.assertEquals(3.0, t18c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(2,t18c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(Math.sqrt(2) * 3, t18c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(4.0, t18c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(5, t18c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(4 * Math.sqrt(5), t18c.getFraction().getSecondFraction().getDecimalValue()); /** * (/A) * (/B // C) * /2 * /3 // 4 */ TNumber t19a = new TNumber(); t19a.setType(TNumber.INTEGER_NUMBER); t19a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t19b = new TNumber(); t19b.setType(TNumber.FRACTION_NUMBER); t19b.setFraction(new Fraction(new FractionNumber(2, 0, 1, 3), new FractionNumber(1, 0, 4, 1))); TNumber t19c = MathHelper.product(t19a, t19b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t19c.getType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t19c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t19c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(Math.sqrt(6) / 4.0, t19c.getValue()); Assert.assertEquals(1.0, t19c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(6, t19c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(Math.sqrt(6), t19c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(4.0, t19c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(1, t19c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(4.0, t19c.getFraction().getSecondFraction().getDecimalValue()); /** * (/A) * (/B // /C) * /2 * (/3 // /4) */ TNumber t20a = new TNumber(); t20a.setType(TNumber.INTEGER_NUMBER); t20a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t20b = new TNumber(); t20b.setType(TNumber.FRACTION_NUMBER); t20b.setFraction(new Fraction(new FractionNumber(2, 0, 1, 3), new FractionNumber(2, 0, 1, 4))); TNumber t20c = MathHelper.product(t20a, t20b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t20c.getType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t20c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t20c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(Math.sqrt(6) / Math.sqrt(4), t20c.getValue()); Assert.assertEquals(1.0, t20c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(6, t20c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(Math.sqrt(6), t20c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(1.0, t20c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(4, t20c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(Math.sqrt(4), t20c.getFraction().getSecondFraction().getDecimalValue()); /** * (/A) * (/B // C/D) * /2 * (/3 // 4/5) */ TNumber t21a = new TNumber(); t21a.setType(TNumber.INTEGER_NUMBER); t21a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t21b = new TNumber(); t21b.setType(TNumber.FRACTION_NUMBER); t21b.setFraction(new Fraction(new FractionNumber(1, 0, 1, 3), new FractionNumber(3, 0, 4, 5))); TNumber t21c = MathHelper.product(t21a, t21b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t21c.getType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t21c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t21c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(Math.sqrt(6.0) / (4.0 * Math.sqrt(5)), t21c.getValue()); Assert.assertEquals(1.0, t21c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(6, t21c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(Math.sqrt(6), t21c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(4.0, t21c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(5, t21c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(4 * Math.sqrt(5), t21c.getFraction().getSecondFraction().getDecimalValue()); /** * (/A) * (B/C // D) * /2 * (3/4 // 5) */ TNumber t22a = new TNumber(); t22a.setType(TNumber.INTEGER_NUMBER); t22a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t22b = new TNumber(); t22b.setType(TNumber.FRACTION_NUMBER); t22b.setFraction(new Fraction(new FractionNumber(2, 0, 3, 4), new FractionNumber(1, 0, 5, 1))); TNumber t22c = MathHelper.product(t22a, t22b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t22c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t22c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t22c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(3.0 * Math.sqrt(8.0) / 5.0, t22c.getValue()); Assert.assertEquals(3.0, t22c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(8, t22c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(3.0 * Math.sqrt(8), t22c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(5.0, t22c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(1, t22c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(5.0, t22c.getFraction().getSecondFraction().getDecimalValue()); /** * (/A) * (B/C // /D) * /2 * (3/4 // /5) */ TNumber t23a = new TNumber(); t23a.setType(TNumber.INTEGER_NUMBER); t23a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t23b = new TNumber(); t23b.setType(TNumber.FRACTION_NUMBER); t23b.setFraction(new Fraction(new FractionNumber(3, 0, 3, 4), new FractionNumber(2, 0, 1, 5))); TNumber t23c = MathHelper.product(t23a, t23b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t23c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t23c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t23c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(3.0 * Math.sqrt(8.0) / Math.sqrt(5), t23c.getValue()); Assert.assertEquals(3.0, t23c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(8,t23c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(3 * Math.sqrt(8), t23c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(1.0, t23c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(5, t23c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(Math.sqrt(5), t23c.getFraction().getSecondFraction().getDecimalValue()); /** * (/A) * (B/C // D/E) * /2 * (3/4 // 5/6) */ TNumber t24a = new TNumber(); t24a.setType(TNumber.INTEGER_NUMBER); t24a.setIntegerNumber(new FractionNumber(2, 0, 1, 2)); TNumber t24b = new TNumber(); t24b.setType(TNumber.FRACTION_NUMBER); t24b.setFraction(new Fraction(new FractionNumber(3, 0, 3, 4), new FractionNumber(3, 0, 5, 6))); TNumber t24c = MathHelper.product(t24a, t24b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t24c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t24c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t24c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(3 * Math.sqrt(8) / (5.0 * Math.sqrt(6)), t24c.getValue()); Assert.assertEquals(3.0, t24c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(8, t24c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(3 * Math.sqrt(8), t24c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(5.0, t24c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(6, t24c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(5 * Math.sqrt(6), t24c.getFraction().getSecondFraction().getDecimalValue()); /** * A/B * C * 2/3 * 4 */ TNumber t25a = new TNumber(); t25a.setType(TNumber.INTEGER_NUMBER); t25a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t25b = new TNumber(); t25b.setType(TNumber.INTEGER_NUMBER); t25b.setIntegerNumber(new FractionNumber(1, 0, 4, 1)); TNumber t25c = MathHelper.product(t25a, t25b); Assert.assertEquals(TNumber.INTEGER_NUMBER, t25c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t25c.getIntegerNumber().getNumberType()); Assert.assertEquals(8.0 * Math.sqrt(3), t25c.getValue()); Assert.assertEquals(8.0, t25c.getIntegerNumber().getIntegerValue()); Assert.assertEquals(3, t25c.getIntegerNumber().getRootValue()); /** * A/B * /C * 2/3 * /4 */ TNumber t26a = new TNumber(); t26a.setType(TNumber.INTEGER_NUMBER); t26a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t26b = new TNumber(); t26b.setType(TNumber.INTEGER_NUMBER); t26b.setIntegerNumber(new FractionNumber(2, 0, 1, 4)); TNumber t26c = MathHelper.product(t26a, t26b); Assert.assertEquals(TNumber.INTEGER_NUMBER, t26c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t26c.getIntegerNumber().getNumberType()); Assert.assertEquals(2.0 * Math.sqrt(12), t26c.getValue()); Assert.assertEquals(2.0, t26c.getIntegerNumber().getIntegerValue()); Assert.assertEquals(12,t26c.getIntegerNumber().getRootValue()); Assert.assertEquals(2.0 * Math.sqrt(12), t26c.getIntegerNumber().getDecimalValue()); /** * A/B * C/D * 2/3 * 4/5 */ TNumber t27a = new TNumber(); t27a.setType(TNumber.INTEGER_NUMBER); t27a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t27b = new TNumber(); t27b.setType(TNumber.INTEGER_NUMBER); t27b.setIntegerNumber(new FractionNumber(3, 0, 4, 5)); TNumber t27c = MathHelper.product(t27a, t27b); Assert.assertEquals(TNumber.INTEGER_NUMBER, t27c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t27c.getIntegerNumber().getNumberType()); Assert.assertEquals(8.0 * Math.sqrt(15), t27c.getValue()); Assert.assertEquals(8.0, t27c.getIntegerNumber().getIntegerValue()); Assert.assertEquals(15,t27c.getIntegerNumber().getRootValue()); Assert.assertEquals(8 * Math.sqrt(15), t27c.getIntegerNumber().getDecimalValue()); /** * (A/B) * (A // B) * 2/3 * (4 // 5) */ TNumber t28a = new TNumber(); t28a.setType(TNumber.INTEGER_NUMBER); t28a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t28b = new TNumber(); t28b.setType(TNumber.FRACTION_NUMBER); t28b.setFraction(new Fraction(new FractionNumber(1, 0, 4, 1), new FractionNumber(1, 0, 5, 1))); TNumber t28c = MathHelper.product(t28a, t28b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t28c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t28c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t28c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(8 * Math.sqrt(3) / 5.0, t28c.getValue()); Assert.assertEquals(8.0, t28c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(3,t28c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(8 * Math.sqrt(3), t28c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(5.0, t28c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(1,t28c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(5.0, t28c.getFraction().getSecondFraction().getDecimalValue()); /** * (A/B) * (A // /B) * 2/3 * (4 // /5) */ TNumber t29a = new TNumber(); t29a.setType(TNumber.INTEGER_NUMBER); t29a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t29b = new TNumber(); t29b.setType(TNumber.FRACTION_NUMBER); t29b.setFraction(new Fraction(new FractionNumber(1, 0, 4, 1), new FractionNumber(2, 0, 1, 5))); TNumber t29c = MathHelper.product(t29a, t29b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t29c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t29c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t29c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(Math.sqrt(3) * 8 / Math.sqrt(5), t29c.getValue()); Assert.assertEquals(8.0, t29c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(3,t29c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(Math.sqrt(3) * 8.0, t29c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(1.0, t29c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(5,t29c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(Math.sqrt(5), t29c.getFraction().getSecondFraction().getDecimalValue()); /** * (A/B) * (C // D/E) * 2/3 * (4 // 5/6) */ TNumber t30a = new TNumber(); t30a.setType(TNumber.INTEGER_NUMBER); t30a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t30b = new TNumber(); t30b.setType(TNumber.FRACTION_NUMBER); t30b.setFraction(new Fraction(new FractionNumber(1, 0, 4, 1), new FractionNumber(3, 0, 5, 6))); TNumber t30c = MathHelper.product(t30a, t30b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t30c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t30c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t30c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(Math.sqrt(3) * 8 / (5.0 * Math.sqrt(6)), t30c.getValue()); Assert.assertEquals(8.0, t30c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(3, t30c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(Math.sqrt(3) * 8, t30c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(5.0, t30c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(6, t30c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(5 * Math.sqrt(6), t30c.getFraction().getSecondFraction().getDecimalValue()); /** * (A/B) * (/C // D) * 2/3 * (/4 // 5) */ TNumber t31a = new TNumber(); t31a.setType(TNumber.INTEGER_NUMBER); t31a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t31b = new TNumber(); t31b.setType(TNumber.FRACTION_NUMBER); t31b.setFraction(new Fraction(new FractionNumber(2, 0, 1, 4), new FractionNumber(1, 0, 5, 1))); TNumber t31c = MathHelper.product(t31a, t31b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t31c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t31c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t31c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(2 * Math.sqrt(12) / 5.0, t31c.getValue()); Assert.assertEquals(2.0, t31c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(12, t31c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(2 * Math.sqrt(12), t31c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(5.0, t31c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(1, t31c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(5.0, t31c.getFraction().getSecondFraction().getDecimalValue()); /** * (A/B) * (/C // /D) * 2/3 * (/4 // /5) */ TNumber t32a = new TNumber(); t32a.setType(TNumber.INTEGER_NUMBER); t32a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t32b = new TNumber(); t32b.setType(TNumber.FRACTION_NUMBER); t32b.setFraction(new Fraction(new FractionNumber(2, 0, 1, 4), new FractionNumber(2, 0, 1, 5))); TNumber t32c = MathHelper.product(t32a, t32b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t32c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t32c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t32c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(2 * Math.sqrt(12) / Math.sqrt(5), t32c.getValue()); Assert.assertEquals(2.0, t32c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(12, t32c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(2 * Math.sqrt(12), t32c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(1.0, t32c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(5, t32c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(Math.sqrt(5), t32c.getFraction().getSecondFraction().getDecimalValue()); /** * (A/B) * (/C // D/E) * 2/3 * (/4 // 5/6) */ TNumber t33a = new TNumber(); t33a.setType(TNumber.INTEGER_NUMBER); t33a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t33b = new TNumber(); t33b.setType(TNumber.FRACTION_NUMBER); t33b.setFraction(new Fraction(new FractionNumber(2, 0, 1, 4), new FractionNumber(3, 0, 5, 6))); TNumber t33c = MathHelper.product(t33a, t33b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t33c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t33c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t33c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(2 * Math.sqrt(12) / (5.0 * Math.sqrt(6)), t33c.getValue()); Assert.assertEquals(2.0, t33c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(12, t33c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(2 * Math.sqrt(12), t33c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(5.0, t33c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(6, t33c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(5 * Math.sqrt(6), t33c.getFraction().getSecondFraction().getDecimalValue()); /** * (A/B) * (B/C // D) * 2/3* (4/5 // 6) */ TNumber t34a = new TNumber(); t34a.setType(TNumber.INTEGER_NUMBER); t34a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t34b = new TNumber(); t34b.setType(TNumber.FRACTION_NUMBER); t34b.setFraction(new Fraction(new FractionNumber(3, 0, 4, 5), new FractionNumber(1, 0, 6, 1))); TNumber t34c = MathHelper.product(t34a, t34b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t34c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t34c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_TYPE, t34c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(8.0 * Math.sqrt(15.0) / 6.0, t34c.getValue()); Assert.assertEquals(8.0, t34c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(15, t34c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(8.0 * Math.sqrt(15), t34c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(6.0, t34c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(1, t34c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(6.0, t34c.getFraction().getSecondFraction().getDecimalValue()); /** * (A/B) * (C/D // /E) * 2/3 * (4/5 // /6) */ TNumber t35a = new TNumber(); t35a.setType(TNumber.INTEGER_NUMBER); t35a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t35b = new TNumber(); t35b.setType(TNumber.FRACTION_NUMBER); t35b.setFraction(new Fraction(new FractionNumber(3, 0, 4, 5), new FractionNumber(2, 0, 1, 6))); TNumber t35c = MathHelper.product(t35a, t35b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t35c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t35c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.ROOT_TYPE, t35c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(8.0 * Math.sqrt(15) / Math.sqrt(6), t35c.getValue()); Assert.assertEquals(8.0, t35c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(15,t35c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(8 * Math.sqrt(15), t35c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(1.0, t35c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(6, t35c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(Math.sqrt(6), t35c.getFraction().getSecondFraction().getDecimalValue()); /** * (A/B) * (C/D // E/F) * 2/3 * (4/5 // 6/7) */ TNumber t36a = new TNumber(); t36a.setType(TNumber.INTEGER_NUMBER); t36a.setIntegerNumber(new FractionNumber(3, 0, 2, 3)); TNumber t36b = new TNumber(); t36b.setType(TNumber.FRACTION_NUMBER); t36b.setFraction(new Fraction(new FractionNumber(3, 0, 4, 5), new FractionNumber(3, 0, 6, 7))); TNumber t36c = MathHelper.product(t36a, t36b); Assert.assertEquals(TNumber.FRACTION_NUMBER, t36c.getType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t36c.getFraction().getFirstFraction().getNumberType()); Assert.assertEquals(FractionNumber.INTEGER_ROOT_TYPE, t36c.getFraction().getSecondFraction().getNumberType()); Assert.assertEquals(8 * Math.sqrt(15) / (6.0 * Math.sqrt(7)), t36c.getValue()); Assert.assertEquals(8.0, t36c.getFraction().getFirstFraction().getIntegerValue()); Assert.assertEquals(15, t36c.getFraction().getFirstFraction().getRootValue()); Assert.assertEquals(8 * Math.sqrt(15), t36c.getFraction().getFirstFraction().getDecimalValue()); Assert.assertEquals(6.0, t36c.getFraction().getSecondFraction().getIntegerValue()); Assert.assertEquals(7, t36c.getFraction().getSecondFraction().getRootValue()); Assert.assertEquals(6 * Math.sqrt(7), t36c.getFraction().getSecondFraction().getDecimalValue()); } }
/** * 湖北安式软件有限公司 * Hubei Anssy Software Co., Ltd. * FILENAME : SmsInfoServer.java * PACKAGE : com.anssy.venturebar.app.server * CREATE DATE : 2016-8-28 * AUTHOR : make it * MODIFIED BY : * DESCRIPTION : */ package com.anssy.venturebar.app.server; import com.anssy.venturebar.app.dao.SmsInfoDao; import com.anssy.venturebar.app.entity.SmsInfoEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; /** * @author make it * @version SVN #V1# #2016-8-28# * APP_短信信息 */ @Service("smsInfoServer") public class SmsInfoServer { @Resource private SmsInfoDao smsInfoDao; /** * 保存短信信息 */ @Transactional(propagation = Propagation.REQUIRED) public void saveSMS(String mobile, String content, Long balance, String state) { try { SmsInfoEntity info = new SmsInfoEntity(); info.setSendTime(new Date()); info.setMobile(mobile); info.setContent(content); info.setBalance(balance); info.setState(state); smsInfoDao.insertSMSInfo(info); } catch (Exception e) { e.printStackTrace(); } } }
package net.skycraftmc.SkyQuest.quest; import java.util.List; import org.bukkit.entity.EntityType; import net.skycraftmc.SkyQuest.util.SkyQuestUtil; public class KillObjective extends Objective { private int progress = 0; private boolean completed = false; public KillObjective(String objective, String label, List<String> rewards, String text) { super(ObjectiveType.KILL, objective, label, rewards, text); } public void setComplete(boolean complete) { completed = complete; } public boolean getComplete() { return completed; } public EntityType getTargetType() { String[] tokens = objective.split("[:]",2); if(tokens.length != 2)return null; EntityType ct = SkyQuestUtil.getType(tokens[0]); return ct; } public boolean isComplete() { String[] tokens = objective.split("[:]",2); if(tokens.length != 2)return false; EntityType ct = SkyQuestUtil.getType(tokens[0]); if(ct == null)return false; int amount; try{amount = Integer.parseInt(tokens[1].replaceAll(" ", ""));}catch(NumberFormatException nfe){return false;} if(progress >= amount)return true; return false; } public String getParsedObjective() { String[] tokens = getObjective().split("[:]", 2); if(tokens.length != 2)return getObjective(); String[] st = tokens[0].split("[ ]+"); String m = Character.toUpperCase(st[0].charAt(0)) + st[0].substring(1).toLowerCase(); for(String x: st) { if(x.equalsIgnoreCase(st[0]))continue; m = m + " " + Character.toUpperCase(x.charAt(0)) + x.substring(1).toLowerCase(); } return tokens[1].trim() + " " + m; } public void setProgress(int i) { progress = i; } public int getProgress() { return progress; } public static KillObjective clone(KillObjective obj) { return new KillObjective(obj.getObjective(), obj.getLabel(), obj.getRewards(), obj.getText()); } public String getTarget() { return "Kill " + getParsedObjective() + (getProgress() >= 1 ? "s" : ""); } public int getRawTarget() { String tokens[] = getTarget().split("[ ]"); if(tokens.length <= 1)return 0; int i = 0; try{i = Integer.parseInt(tokens[1]);}catch(NumberFormatException nfe){return 0;} return i; } public String getProgressAsString() { String[] tokens = getObjective().split("[:]", 2); if(tokens.length != 2)return getProgress() + " creatures killed"; String[] st = tokens[0].split("[ ]+"); String m = Character.toUpperCase(st[0].charAt(0)) + st[0].substring(1).toLowerCase(); for(String x: st) { if(x.equalsIgnoreCase(st[0]))continue; m = m + " " + Character.toUpperCase(x.charAt(0)) + x.substring(1).toLowerCase(); } return getProgress() + " " + m + (getProgress() >= 1 ? "s killed" : " killed"); } }
package com.appirio.service.resourcefactory; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.appirio.eventsbus.api.client.EventConsumer; import com.appirio.eventsbus.api.client.EventProducer; import com.appirio.eventsbus.api.client.util.jsonevent.EventHandler; import com.appirio.service.MemberServiceConfiguration; import com.appirio.service.member.dao.MemberProfileDAO; import com.appirio.service.member.dao.MemberStatsDAO; import com.appirio.service.member.eventbus.EventBusServiceClient; import com.appirio.service.member.events.*; import com.appirio.service.member.manager.MemberProfileManager; import com.appirio.service.member.resources.MemberProfileResource; import com.appirio.service.supply.resources.ResourceFactory; import com.appirio.supply.SupplyException; import com.appirio.supply.dataaccess.FileInvocationHandler; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.setup.Environment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import javax.ws.rs.client.Client; /** * Factory for Member profile * * Version 1.1 - Topcoder Member Service - New Endpoint to Update Email Address Code Challenge v1.0 * - create MemberProfileManager with more configurations related to email verification * * @author rrecharla@appirio.com, TCCoder * @version 1.1 */ public class MemberProfileFactory implements ResourceFactory<MemberProfileResource> { /** * Logger */ Logger logger = LoggerFactory.getLogger(MemberProfileFactory.class); /** * Supply server configuration */ private MemberServiceConfiguration config; /** * Dropwizard environment */ private Environment env; /** * Simple constructor to initialize Supply server configuration and * environment * @param config Configuration for the supply server * @param env Environment for dropwizard */ public MemberProfileFactory(MemberServiceConfiguration config, Environment env) { this.config = config; this.env = env; } /** * Get MemberProfileResource object * @return MemberProfileResource Member profile resource * @throws SupplyException Exception for the supply */ @Override public MemberProfileResource getResourceInstance() throws SupplyException { AmazonDynamoDBClient client = new AmazonDynamoDBClient(); if(config.getDynamoDBUrl() != null && !config.getDynamoDBUrl().isEmpty()) { client.withEndpoint(config.getDynamoDBUrl()); } DynamoDBMapper mapper = new DynamoDBMapper(client); MemberProfileDAO memberProfileDAO = new MemberProfileDAO(mapper); MemberStatsDAO memberStatsDAO = new MemberStatsDAO(mapper); FileInvocationHandler fileInvocationHandler = new FileInvocationHandler(config.getFileServiceDomain()); EventProducer eventProducer = EventProducer.getInstance(); final Client apiClient = new JerseyClientBuilder(env).build(this.getClass().getName()); EventBusServiceClient eventBusServiceClient = new EventBusServiceClient(apiClient, this.config.getEventBusServiceClientConfig()); final MemberProfileManager memberProfileManager = new MemberProfileManager(memberProfileDAO, memberStatsDAO, config.getPhotoURLDomain(), fileInvocationHandler, eventProducer, eventBusServiceClient, this.config.getEmailVerificationConfig()); try { EventConsumer consumer = EventConsumer.getInstance(); Map<String, EventHandler> events = new HashMap<>(); events.put("event.user.created", new MemberCreationEventHandler(memberProfileDAO, eventProducer)); events.put("event.user.activated", new MemberActivationEventHandler(memberProfileDAO, eventProducer)); events.put("event.user.deactivated", new MemberDeactivationEventHandler(memberProfileDAO, eventProducer)); events.put("event.user.updated", new MemberUpdateEventHandler(memberProfileDAO, eventProducer)); MemberEventsClientManager eventClientManager = new MemberEventsClientManager(consumer, events); env.lifecycle().manage(eventClientManager); } catch (Exception e) { logger.error("Error in initializing communication with events bus " + e.getMessage()); throw new SupplyException(e); } return new MemberProfileResource(memberProfileManager); } }
package com.news.demo.model.MongoDbModel; import org.springframework.data.mongodb.core.mapping.Document; @Document(value = "CommdityDb") public class CommdityDb { private String name; private String type; private String state; private String image_url; private String title; private String userid; private String compliments; private String date; private String code; private String user_name; private String avatar_Url; public CommdityDb(){ super(); } public CommdityDb(String name, String type, String state, String image_url, String title, String userid, String compliments, String date, String code, String user_name, String avatar_Url) { this.name = name; this.type = type; this.state = state; this.image_url = image_url; this.title = title; this.userid = userid; this.compliments = compliments; this.date = date; this.code = code; this.user_name = user_name; this.avatar_Url = avatar_Url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getCompliments() { return compliments; } public void setCompliments(String compliments) { this.compliments = compliments; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public String getAvatar_Url() { return avatar_Url; } public void setAvatar_Url(String avatar_Url) { this.avatar_Url = avatar_Url; } }
package com.legaoyi.platform.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; /** * @author gaoshengbo */ @WebFilter(filterName = "securityServlet", urlPatterns = "*.do") public class SecurityServlet implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filter) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; HttpSession session = request.getSession(true); Object user = session.getAttribute("user");// 登录人角色 String url = request.getRequestURI(); // 判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转 if (user == null) { if (StringUtils.isNotEmpty(url) && !(url.endsWith("login.do") || url.endsWith("register.do"))) { //response.sendRedirect(request.getContextPath() + "/login.do"); java.io.PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<script>"); out.println("window.open ('" + request.getContextPath() + "/login.do','_top')"); out.println("</script>"); out.println("</html>"); return; } } req.setAttribute("user", user); filter.doFilter(req, resp); } @Override public void init(FilterConfig arg0) throws ServletException { } }
package com.xljt.freight.service.Impl; import com.xljt.freight.service.CarInfoService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.*; /** * The type Car info service impl test. * * @author xu * @date 2020.04.15 */ @SpringBootTest class CarInfoServiceImplTest { @Autowired private CarInfoService carInfoService; @Test void carInfoUpload() { carInfoService.carInfoUpload(); } }
package com.example.tejk.opengl_fingerpaint.meshes; import com.example.tejk.opengl_fingerpaint.meshes.drawing.DrawingAlgorithm; import com.example.tejk.opengl_fingerpaint.meshes.fbo.FBObject; import com.example.tejk.opengl_fingerpaint.models.ColorV4; public class BackgroundLayer { // Background private Texture texture; // FBO private FBObject fbo; public BackgroundLayer(int x, int y, int width, int height) { this.fbo = new FBObject(x, y, width, height); this.texture = new Texture(x, y, width, height, new ColorV4(1.0f, 1.0f, 1.0f, 1.0f), -1/*, R.drawable.white_background*/); } public void draw(float[] mvpMatrix) { long time = System.currentTimeMillis(); texture.draw(mvpMatrix); long now = System.currentTimeMillis(); System.out.println("Drawing texture took " + (now - time) + " ms"); } public void drawPath(float[] mvpMatrix, DrawingAlgorithm stroke) { long time = System.currentTimeMillis(); fbo.draw(mvpMatrix, stroke); long now = System.currentTimeMillis(); System.out.println("Drawing FBO took " + (now - time) + " ms"); } }
package com.oracle.curd.test; import com.oracle.curd.bean.Ckin; import com.oracle.curd.dao.CkinMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class CkinTest { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); @Autowired CkinMapper ckinMapper; @Test public void getAllTest(){ List<Ckin> ckins = ckinMapper.selectByExample(null); for (Ckin ckin : ckins) { System.out.println(ckin); } } @Test public void updateCkinTest(){ Ckin ckin = new Ckin(); ckin.setInid("6"); ckin.setProid("7"); ckin.setPname("炸鸡"); ckin.setNum(10); try { ckin.setIndate(sdf.parse("1982-01-01")); } catch (ParseException e) { e.printStackTrace(); } ckin.setMarks("82年的炸鸡"); ckinMapper.updateByPrimaryKey(ckin); } }
package com.example.api.web.rest; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import com.example.api.domain.Customer; import com.example.api.service.CustomerService; import javax.validation.Valid; @RestController @RequestMapping("/api/customers") public class CustomerController { private CustomerService service; @Autowired public CustomerController(CustomerService service) { this.service = service; } @GetMapping public List<Customer> findAll() { return service.findAll(); } @GetMapping ("/paginacao") public List<Customer> findAllPaging(@RequestParam int pagina, @RequestParam int tamanho){ return service.findAllPaging(pagina, tamanho); } @GetMapping("/{id}") public Customer findById(@PathVariable Long id) { return service.findById(id) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found")); } @PostMapping() public ResponseEntity<String> insertCustomer(@Valid @RequestBody Customer customer){ boolean isInserted = service.insertCustomer(customer); if(isInserted) return new ResponseEntity<>("", HttpStatus.CREATED); else return new ResponseEntity<>("", HttpStatus.OK); } @PutMapping() public ResponseEntity<String> updateCustomer(@Valid @RequestBody Customer customer){ service.updateCustomer(customer); return new ResponseEntity<>("", HttpStatus.OK); } @DeleteMapping("/{id}") public ResponseEntity<String> deleteCustomer(@PathVariable Long id){ service.deleteById(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } }
package com.league.football.services; public interface FootBallLeagueService { public static final String EMPTY_STRING=""; public static final String COMMA_STRING=","; public static final String COLLON_STRING=":"; public static final String ZERO_STRING="0"; public static final String ENCODE_UTF_STRING="utf-8"; public static final String COUNTRY_STRING="/?action=get_countries"; public static final String LEAGUE_STRING="/?action=get_leagues&country_id="; public static final String STANDINGS_STRING="/?action=get_standings&league_id="; public static final String APIKEY_STRING="&APIkey="; public static final String COUNTRY_NOT_FOUND_STRING="NO_COUNTRY_FOUND"; public static final String COUNTRY_OBJECT="countries"; public String getCountry(); public String getLeagues(String country_id); public String getStandings(String league_id); }
package com.diegocasas.festival; import android.app.ActionBar; import android.content.Intent; import android.support.v4.content.ContextCompat; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.diegocasas.festival.Adapter.CustomAdapter; import com.diegocasas.festival.Model.Item; import java.util.ArrayList; import java.util.List; public class Programa extends AppCompatActivity { RecyclerView recyclerView; RecyclerView.LayoutManager layoutManager; List<Item> items; CustomAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_programa); getSupportActionBar().setDisplayHomeAsUpEnabled(true); recyclerView = (RecyclerView)findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); initItem(); } @Override public boolean onSupportNavigateUp(){ finish(); return true; } private void initItem() { items = new ArrayList<>(); items.add(new Item(0,"New","FESTIVAL CULTURAL 1","https://www.zonaturistica.com/files/ferias/727/F5_727.jpg")); items.add(new Item(1,"Hot","FESTIVAL CULTURAL 2","https://www.zonaturistica.com/files/ferias/727/F5_727.jpg")); items.add(new Item(1,"Hot","FESTIVAL CULTURAL 3","https://www.zonaturistica.com/files/ferias/727/F5_727.jpg")); items.add(new Item(0,"New","FESTIVAL CULTURAL 4","https://www.zonaturistica.com/files/ferias/727/F5_727.jpg")); items.add(new Item(2,"","FESTIVAL CULTURAL 5","https://www.zonaturistica.com/files/ferias/727/F5_727.jpg")); adapter = new CustomAdapter(this, items); recyclerView.setAdapter(adapter); } public void evento(View view){ Intent intent = new Intent(Programa.this, Evento.class); startActivity(intent); } }
package aviao; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import enums.Fileira; import lombok.Getter; @Getter public class Aviao { List<Reserva> reservas = new ArrayList<>(); public Aviao(){ for(Fileira fileira: Fileira.values()) for(int i = 1; i<=31; i++) reservas.add(new Reserva(new Assento(fileira, i), false, null)); } public boolean reservarAssento(String assento, String pessoa){ assento = assento.toUpperCase(); Assento a = new Assento(Fileira.valueOf(assento.substring(0, 1)), Integer.parseInt(assento.substring(1))); for(Reserva b: reservas) if (b.getAssento().isAssento(a) && !b.reservado){ b.setReservado(true); b.setPessoa(pessoa); return true; } return false; } public boolean cancelarReserva(String assento){ assento = assento.toUpperCase(); Assento a = new Assento(Fileira.valueOf(assento.substring(0, 1)), Integer.parseInt(assento.substring(1))); for(Reserva b: reservas) if (b.getAssento().isAssento(a) && b.reservado){ b.setReservado(false); b.setPessoa(null); return true; } return false; } public void imprimirAssentosReservados(){ for(Reserva reserva:reservas) if(reserva.reservado) reserva.getAssento().imprimirAssento(); } public void imprimirAssentosReservadosOrdenado(){ List<Reserva> reservados = new ArrayList<>(); for(Reserva reserva:reservas) if(reserva.reservado) reservados.add(reserva); reservados.sort(null); for(Reserva reserva:reservados) reserva.imprimirReserva(); } public void imprimirDadosReserva(String assento){ assento = assento.toUpperCase(); Assento a = new Assento(Fileira.valueOf(assento.substring(0, 1)), Integer.parseInt(assento.substring(1))); for(Reserva b: reservas) if (b.getAssento().isAssento(a)){ b.imprimirReserva(); } } }
package com.sinodynamic.hkgta.dao.crm; import com.sinodynamic.hkgta.dao.IBaseDao; import com.sinodynamic.hkgta.entity.crm.CashvalueTopupHistory; public interface CashvalueTopupHistoryDao extends IBaseDao<CashvalueTopupHistory> { public void addCashvalueTopupHistory(CashvalueTopupHistory cth); }
package com.jgw.supercodeplatform.trace.pojo.antchain; /** * 蚂蚁区块链存储entity, 同NodeBlockChainInfo,仅去掉interfaceId */ public class AntChainInfo { private Long blockChainId; private String productId; private String productName; private String traceBatchInfoId; private String traceBatchName; private String functionId; private String functionName; // 上链节点信息id private Long nodeInfoId; // 上链节点信息 private String nodeInfo; // 区块号 private Long blockNo; private String blockHash; private String transactionHash; private String transactionTime; private String cmtTime; private String organizationId; private String organizationName; // 上链节点信息种是否包含对象 private Integer containObj; // 当前批次上链数量--不保存数据库 private Integer blockNum; private String sysId; public String getSysId() { return sysId; } public void setSysId(String sysId) { this.sysId = sysId; } public Long getBlockChainId() { return blockChainId; } public void setBlockChainId(Long blockChainId) { this.blockChainId = blockChainId; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getTraceBatchInfoId() { return traceBatchInfoId; } public void setTraceBatchInfoId(String traceBatchInfoId) { this.traceBatchInfoId = traceBatchInfoId; } public String getTraceBatchName() { return traceBatchName; } public void setTraceBatchName(String traceBatchName) { this.traceBatchName = traceBatchName; } public String getFunctionId() { return functionId; } public void setFunctionId(String functionId) { this.functionId = functionId; } public String getFunctionName() { return functionName; } public void setFunctionName(String functionName) { this.functionName = functionName; } public String getNodeInfo() { return nodeInfo; } public void setNodeInfo(String nodeInfo) { this.nodeInfo = nodeInfo; } public Long getBlockNo() { return blockNo; } public void setBlockNo(Long blockNo) { this.blockNo = blockNo; } public String getBlockHash() { return blockHash; } public void setBlockHash(String blockHash) { this.blockHash = blockHash; } public String getTransactionHash() { return transactionHash; } public void setTransactionHash(String transactionHash) { this.transactionHash = transactionHash; } public String getTransactionTime() { return transactionTime; } public void setTransactionTime(String transactionTime) { this.transactionTime = transactionTime; } public String getCmtTime() { return cmtTime; } public void setCmtTime(String cmtTime) { this.cmtTime = cmtTime; } public Integer getBlockNum() { return blockNum; } public void setBlockNum(Integer blockNum) { this.blockNum = blockNum; } public String getOrganizationId() { return organizationId; } public void setOrganizationId(String organizationId) { this.organizationId = organizationId; } public String getOrganizationName() { return organizationName; } public void setOrganizationName(String organizationName) { this.organizationName = organizationName; } public Integer getContainObj() { return containObj; } public void setContainObj(Integer containObj) { this.containObj = containObj; } public Long getNodeInfoId() { return nodeInfoId; } public void setNodeInfoId(Long nodeInfoId) { this.nodeInfoId = nodeInfoId; } }
package model.dto.hr; public class AuthInfoHR { String authId; String authPw; String authName; String authEmpNo; String authTchNo; public String getAuthId() { return authId; } public void setAuthId(String authId) { this.authId = authId; } public String getAuthPw() { return authPw; } public void setAuthPw(String authPw) { this.authPw = authPw; } public String getAuthName() { return authName; } public void setAuthName(String authName) { this.authName = authName; } public String getAuthEmpNo() { return authEmpNo; } public void setAuthEmpNo(String authEmpNo) { this.authEmpNo = authEmpNo; } public String getAuthTchNo() { return authTchNo; } public void setAuthTchNo(String authTchNo) { this.authTchNo = authTchNo; } }
package dubbo; import base.DemoService; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by zhaoyf * * 2015/10/12 */ public class Cosumer { public static void main(String[] args) throws Exception { System.out.println(Cosumer.class.getClassLoader().getResource("").getPath()); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"consumer.xml"}); context.start(); DemoService demoService = (DemoService)context.getBean("demoService1"); // 获取远程服务代理 String res = demoService.sayHello("world"); // 执行远程方法 System.out.println( res ); // 显示调用结果 } }
package com.soyun.travel; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class ChatRoomDAO { @Autowired SqlSessionTemplate mymy; public ChatRoomDTO select(String leader) { return mymy.selectOne("chatroomDAO.select",leader); } public ChatRoomDTO select(int num) { return mymy.selectOne("chatroomDAO.select",num); } public List<ChatRoomDTO> chatSelectAll() { return mymy.selectList("chatroomDAO.chatSelectAll"); } }
package kr.co.dao; import java.util.List; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import kr.co.domain.TestDTO; @Repository public class TestDAOImpl implements TestDAO{ @Inject private SqlSession sqlSession; private final String NS="kr.co.mapper.test"; @Override public List<TestDTO> list() { // TODO Auto-generated method stub return sqlSession.selectList(NS+".list"); } @Override public void insert(TestDTO dto) { // TODO Auto-generated method stub sqlSession.insert(NS+".insert",dto); } @Override public TestDTO selectByNum(int num) { // TODO Auto-generated method stub return sqlSession.selectOne(NS+".selectByNum", num); } @Override public void delete(int num) { // TODO Auto-generated method stub sqlSession.delete(NS+".delete", num); } @Override public TestDTO updateui(int num) { // TODO Auto-generated method stub return sqlSession.selectOne(NS+".updateui", num); } @Override public void update(TestDTO dto) { // TODO Auto-generated method stub sqlSession.update(NS+".update", dto); } }
package com.company.springer; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class TestCanvas { Canvas canvas; @Before public void initialize() { canvas = new Canvas(); } @Test public void testCanvasIsDefined() { assertNotNull("Should not be null", canvas); } @Test public void canCreateAnEmpty10x5Canvas() { canvas.createCanvas(10, 5); assertEquals(canvas.createRenderString(), "------------\n" + "| |\n" + "| |\n" + "| |\n" + "| |\n" + "| |\n" + "------------"); } @Test public void canDrawAPoint() { canvas.createCanvas(10, 5); canvas.drawPoint(1,1); assertEquals(canvas.createRenderString(), "------------\n" + "| |\n" + "| x |\n" + "| |\n" + "| |\n" + "| |\n" + "------------"); } @Test public void canDrawVerticalLine() { canvas.createCanvas(10, 5); canvas.drawLine(0, 0, 0 ,4); assertEquals(canvas.createRenderString(), "------------\n" + "|x |\n" + "|x |\n" + "|x |\n" + "|x |\n" + "|x |\n" + "------------"); } @Test public void canDrawHorizontalLine() { canvas.createCanvas(10, 5); canvas.drawLine(0, 0, 9 ,0); assertEquals(canvas.createRenderString(), "------------\n" + "|xxxxxxxxxx|\n" + "| |\n" + "| |\n" + "| |\n" + "| |\n" + "------------"); } @Test public void canDrawSquare() { canvas.createCanvas(10, 5); canvas.drawSquare(1,1,3,3); assertEquals(canvas.createRenderString(), "------------\n" + "| |\n" + "| xxx |\n" + "| x x |\n" + "| xxx |\n" + "| |\n" + "------------"); } @Test public void canBucketFill() { canvas.createCanvas(10, 5); canvas.drawSquare(1,1,6,3); canvas.bucketFill(0,0,"o", null); assertEquals(canvas.createRenderString(), "------------\n" + "|oooooooooo|\n" + "|oxxxxxxooo|\n" + "|ox xooo|\n" + "|oxxxxxxooo|\n" + "|oooooooooo|\n" + "------------"); } @Test public void canBucketFillInsideSquare() { canvas.createCanvas(10, 5); canvas.drawSquare(1,1,6,3); canvas.bucketFill(2,2,"M",null); assertEquals(canvas.createRenderString(), "------------\n" + "| |\n" + "| xxxxxx |\n" + "| xMMMMx |\n" + "| xxxxxx |\n" + "| |\n" + "------------"); } @Test public void canUndoLastAction() { canvas.createCanvas(10, 5); canvas.drawPoint(3,3); canvas.bucketFill(0,0,"P",null); canvas.undo(); assertEquals(canvas.createRenderString(), "------------\n" + "| |\n" + "| |\n" + "| |\n" + "| x |\n" + "| |\n" + "------------"); } @Test public void canClearTheCanvas() { canvas.createCanvas(10,5); canvas.bucketFill(0,0,"Z",null); canvas.clearCanvas(); assertEquals(canvas.createRenderString(), "------------\n" + "| |\n" + "| |\n" + "| |\n" + "| |\n" + "| |\n" + "------------"); } }
package utils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @version日志测试(可以连续输入不覆盖) * @author XuFankang * @Time:Jul 18, 2019 * TODO * */ public class printLog { public static Log log = LogFactory.getLog(printLog.class); public static void store(String str) { log.info(str); } public static void main(String[] args) { store("测试1"); } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow 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 3 of the License, or any later version. * * * * Data Crow 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, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.core.modules; import java.util.ArrayList; import java.util.Collection; import net.datacrow.console.ComponentFactory; import net.datacrow.core.DcRepository; import net.datacrow.core.objects.DcField; import net.datacrow.core.objects.DcObject; import net.datacrow.core.objects.Loan; import net.datacrow.core.plugin.InvalidPluginException; import net.datacrow.core.plugin.Plugins; import net.datacrow.core.security.SecurityCentre; import net.datacrow.settings.Settings; import org.apache.log4j.Logger; /** * Represents loan items. * * @author Robert Jan van der Waals */ public class LoanModule extends DcModule { private static Logger logger = Logger.getLogger(DcModule.class.getName()); private static final long serialVersionUID = -1777037389578494831L; public LoanModule(int index, boolean topModule, String name, String description, String objectName, String objectNamePlural, String tableName, String tableShortName) { super(index, topModule, name, description, objectName, objectNamePlural, tableName, tableShortName); } /** * Creates a new instance of this module. */ public LoanModule() { super(DcModules._LOAN, false, "Loan", "", "Loan", "Loans", "loans", "lo"); } @Override public boolean hasInsertView() { return false; } @Override public boolean hasSearchView() { return false; } @Override public boolean isEditingAllowed() { try { return SecurityCentre.getInstance().getUser().isAuthorized(Plugins.getInstance().get("Loan")); } catch (InvalidPluginException ipe) { logger.error(ipe, ipe); return false; } } /** * Indicates if this module is enabled. */ @Override public boolean isEnabled() { return DcModules.get(DcModules._CONTACTPERSON) != null ? DcModules.get(DcModules._CONTACTPERSON).isEnabled() : false; } /** * Retrieves the settings for this module. */ @Override public Settings getSettings() { setSetting(DcRepository.ModuleSettings.stTableColumnOrder, new int[] {Loan._C_CONTACTPERSONID, Loan._A_STARTDATE, Loan._B_ENDDATE}); return super.getSettings(); } /** * Creates a new instance of a loan. * @see Loan */ @Override public DcObject createItem() { return new Loan(); } /** * This module does not have any views and therefore this method has not having to do. */ @Override protected void initializeUI() {} @Override public int[] getSupportedViews() { return new int[] {}; } @Override public int[] getMinimalFields(Collection<Integer> include) { Collection<Integer> c = new ArrayList<Integer>(); if (include != null) c.addAll(include); if (!c.contains(Integer.valueOf(Loan._A_STARTDATE))) c.add(Integer.valueOf(Loan._A_STARTDATE)); if (!c.contains(Integer.valueOf(Loan._B_ENDDATE))) c.add(Integer.valueOf(Loan._B_ENDDATE)); if (!c.contains(Integer.valueOf(Loan._C_CONTACTPERSONID))) c.add(Integer.valueOf(Loan._C_CONTACTPERSONID)); if (!c.contains(Integer.valueOf(Loan._D_OBJECTID))) c.add(Integer.valueOf(Loan._D_OBJECTID)); if (!c.contains(Integer.valueOf(Loan._E_DUEDATE))) c.add(Integer.valueOf(Loan._E_DUEDATE)); return super.getMinimalFields(c); } /** * Initializes the default fields. */ @Override protected void initializeFields() { super.initializeFields(); addField(new DcField(Loan._A_STARTDATE, getIndex(), "Start date", false, true, false, false, 255, ComponentFactory._SHORTTEXTFIELD, getIndex(), DcRepository.ValueTypes._DATE, "StartDate")); addField(new DcField(Loan._B_ENDDATE, getIndex(), "End date", false, true, false, false, 255, ComponentFactory._SHORTTEXTFIELD, getIndex(), DcRepository.ValueTypes._DATE, "EndDate")); addField(new DcField(Loan._C_CONTACTPERSONID, getIndex(), "Contact Person", false, true, false, false, 36, ComponentFactory._SHORTTEXTFIELD, getIndex(), DcRepository.ValueTypes._STRING, "PersonID")); addField(new DcField(Loan._D_OBJECTID, getIndex(), "Object", false, true, false, false, 36, ComponentFactory._SHORTTEXTFIELD, getIndex(), DcRepository.ValueTypes._STRING, "ObjectID")); addField(new DcField(Loan._E_DUEDATE, getIndex(), "Due Date", false, true, false, false, 50, ComponentFactory._DATEFIELD, getIndex(), DcRepository.ValueTypes._DATE, "DueDate")); } @Override public boolean equals(Object o) { return (o instanceof LoanModule ? ((LoanModule) o).getIndex() == getIndex() : false); } }
package com.example.amr.apisapp; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { public static final String JSON_URL = "http://192.168.1.107/phpinandroid/showStudents.php"; private ListView listView; String email; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE); email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available"); Toast.makeText(MainActivity.this, email, Toast.LENGTH_SHORT).show(); sendRequest(); } private void sendRequest() { StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { showJSON(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("username", email); return parameters; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } private void showJSON(String json) { ParseJSON pj = new ParseJSON(json); pj.parseJSON(); CustomList cl = new CustomList(this, ParseJSON.ids, ParseJSON.names, ParseJSON.emails, ParseJSON.ages); listView.setAdapter(cl); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Intent intent = new Intent(MainActivity.this, DetailsActivity.class); String idd = ParseJSON.ids[position]; String first = ParseJSON.names[position]; String last = ParseJSON.emails[position]; String age = ParseJSON.ages[position]; Bundle b = new Bundle(); b.putString("ab", idd); b.putString("abab", first); b.putString("ababab", last); b.putString("abababab", age); intent.putExtras(b); startActivity(intent); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> arg0, View v, int index, long arg3) { Toast.makeText(MainActivity.this, ParseJSON.ids[index], Toast.LENGTH_SHORT).show(); return true; } }); } //Logout function private void logout() { //Creating an alert dialog to confirm logout AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("Are you sure you want to logout ?"); alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false); editor.putString(Config.EMAIL_SHARED_PREF, ""); editor.commit(); Intent intent = new Intent(MainActivity.this, Login.class); startActivity(intent); finish(); } }); alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); //Showing the alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int a = item.getItemId(); if (a == R.id.item1) { Intent intent = new Intent(getApplicationContext(), AddActivity.class); Bundle b = new Bundle(); b.putString("usernamee", email); intent.putExtras(b); startActivity(intent); return true; } if (a == R.id.item3) { sendRequest(); return true; } if (a == R.id.item4) { Intent intent = new Intent(getApplicationContext(), UpdateProfile.class); Bundle b = new Bundle(); b.putString("useremail", email); intent.putExtras(b); startActivity(intent); return true; } if (a == R.id.item5) { Intent intent = new Intent(getApplicationContext(), Searching.class); startActivity(intent); return true; } if (a == R.id.item2) { logout(); return true; } return super.onOptionsItemSelected(item); } }
package com.ass.dao; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.ass.model.Category; import com.ass.model.Product; import com.ass.modelQuery.TopSelling; public interface ProductDao extends JpaRepository<Product, Integer>{ // @Query("SELECT p FROM Product p ORDER BY p.promotions DESC") @Query(value = "select top 6 * from Products where Availabe = 1 order by Promotions desc", nativeQuery = true) List<Product> TopSale(); // @Query(value = "select top 6 Products.Id,Name,Image,Products.Price,Describe,Promotions,CategoryName,SUM(Quantity)\r\n" // + " from Products left outer join OrderDetails on Products.Id = OrderDetails.ProductId \r\n" // + " where Availabe = 1\r\n" // + " GROUP BY Products.Id,Name,Image,Products.Price,Describe,CategoryName,Promotions \r\n" // + " ORDER BY SUM(Quantity) DESC", // nativeQuery = true) // @Query(value = "SELECT ",nativeQuery = true) // List<TopSelling> TopSelling(); @Query("SELECT p FROM Product p WHERE p.category=:ct and p.avaliabe=true") List<Product> finProductCT(@Param("ct") Optional<Category> optional); }
package model; import java.sql.SQLException; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Test; import Database.DBConnection; public class ModelRunner { // specify how many threads(users) to create private final int USERS = 1; @Test public void runner() { long timeBefore = System.currentTimeMillis(); ArrayList<Long> responseTimes = new ArrayList<>(); // create threads ExecutorService thread_manager = Executors.newFixedThreadPool(USERS); DBConnection init = DBConnection.getInstance(); try { // clear all tables to initialise conditions init.ExecuteQuery("DELETE FROM bets;"); init.ExecuteQuery("DELETE FROM attempted_logins;"); init.ExecuteQuery("DELETE FROM PLAYERS;"); } catch (SQLException se) { se.printStackTrace(); } for (int i = 0; i < USERS; i++) { Runnable ptest = new Model(responseTimes); thread_manager.execute(ptest); } thread_manager.shutdown(); while (!thread_manager.isTerminated()) { // wait until executor service terminates safely } long timeAfter = System.currentTimeMillis(); long total = 0; for (int i = 0; i < responseTimes.size(); i++) { total += responseTimes.get(i); } System.out.println("Total execution time for the test: " + ((timeAfter - timeBefore) / 1000) + " seconds"); System.out.println("Average response time per page: " + (total / responseTimes.size()) + " milliseconds"); try { // clear all tables init.ExecuteQuery("DELETE FROM bets;"); init.ExecuteQuery("DELETE FROM attempted_logins;"); init.ExecuteQuery("DELETE FROM PLAYERS;"); } catch (SQLException se) { se.printStackTrace(); } } }
package com.corycharlton.bittrexapi.model; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") public class Currency { @SerializedName("BaseAddress") private String _baseAddress; @SerializedName("CoinType") private String _coinType; @SerializedName("Currency") private String _currency; @SerializedName("CurrencyLong") private String _currencyLong; @SerializedName("IsActive") private boolean _isActive; // Is this an int? @SerializedName("MinConfirmation") private double _minConfirmation; // Not sure what this type is @SerializedName("Notice") private String _notice; @SerializedName("TxFee") private double _txFee; private Currency() {} // Cannot be instantiated public String baseAddress() { return _baseAddress; } public String coinType() { return _coinType; } public String currency() { return _currency; } public String currencyLong() { return _currencyLong; } public boolean isActive() { return _isActive; } public double minConfirmation() { return _minConfirmation; } public String notice() { return _notice; } public double txFee() { return _txFee; } }
package lotro.web; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Map; import java.util.TreeMap; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import file.FileUtils; public class TopicPie { private static final Pattern PROPERTY = Pattern.compile ("(.+)=(.+)"); public static Map<Integer, String> readMap (final String path) { Map<Integer, String> map = new TreeMap<Integer, String>(); InputStream is = null; try { is = new FileInputStream (path); InputStreamReader isr = new InputStreamReader (is); BufferedReader br = new BufferedReader (isr); String line = null; while ((line = br.readLine()) != null) { Matcher m = PROPERTY.matcher (line); if (m.matches()) map.put (Integer.parseInt (m.group(2)), m.group(1)); } } catch (Exception x) { x.printStackTrace (System.err); } finally { FileUtils.close (is); } return map; } public static void main (String[] args) { String path = FileUtils.MY_DESK + File.separator + "WordCount.txt"; Map<Integer, String> map = readMap(path); for (Entry<Integer, String> entry : map.entrySet()) System.out.println (entry.getValue() + "\t" + entry.getKey()); } }
package com.example.dojo.controller; import java.util.ArrayList; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.example.dojo.Service.dojoService; import com.example.dojo.Service.ninjaService; import com.example.dojo.models.Dojos; import com.example.dojo.models.Ninjas; @Controller public class DojoController { private final dojoService dojoS; private final ninjaService ninjaS; public DojoController(dojoService dojoS , ninjaService ninjaS) { this.dojoS = dojoS; this.ninjaS = ninjaS; } @RequestMapping("/") public String main(@ModelAttribute ("dojo") Dojos dojo , Model model) { return "/main.jsp"; } @RequestMapping(value="/dojos", method=RequestMethod.POST) public String create(@Valid @ModelAttribute("dojo") Dojos dojo,Model model , BindingResult result){ if (result.hasErrors()) { return "/main.jsp"; } else { dojoS.create(dojo); return "redirect:/ninjas/new"; } } @RequestMapping("/dojos/{id}") public String show(@PathVariable("id") Long id,Model model) { Dojos d = dojoS.findDojo(id); Dojos alldn = dojoS.findDojo(id); model.addAttribute("name", d); ArrayList<Ninjas> allDN = ninjaS.findAllDojoNinjas(alldn); model.addAttribute("allDN", allDN); return "/show.jsp"; } }
package com.turios.activities.fragments.dialog; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import com.turios.util.Constants; public class GenericOkDialogFragment extends DialogFragment { public interface GenericOkDialogInterface { public void okClicked(); } private static GenericOkDialogInterface mDialogInterface; public static GenericOkDialogFragment newInstance( GenericOkDialogInterface dialogInterface, int title) { return GenericOkDialogFragment.newInstance(dialogInterface, title, -1, -1); } public static GenericOkDialogFragment newInstance( GenericOkDialogInterface dialogInterface, int title, int message) { return GenericOkDialogFragment.newInstance(dialogInterface, title, message, -1); } public static GenericOkDialogFragment newInstance( GenericOkDialogInterface dialogInterface, int title, int message, int icon) { mDialogInterface = dialogInterface; GenericOkDialogFragment frag = new GenericOkDialogFragment(); Bundle bundle = new Bundle(); bundle.putInt(Constants.EXTRA_TITLE, title); bundle.putInt(Constants.EXTRA_MESSAGE, message); bundle.putInt(Constants.EXTRA_ICON, icon); frag.setCancelable(false); frag.setArguments(bundle); return frag; } public GenericOkDialogFragment() { // Empty constructor required for DialogFragment } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { int title = getArguments().getInt(Constants.EXTRA_TITLE); int message = getArguments().getInt(Constants.EXTRA_MESSAGE); int icon = getArguments().getInt(Constants.EXTRA_ICON); AlertDialog.Builder alertBuilder = new AlertDialog.Builder( getActivity()).setCancelable(true).setPositiveButton( android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mDialogInterface.okClicked(); } }); if (title != -1) alertBuilder.setTitle(title); if (message != -1) alertBuilder.setMessage(message); if (icon != -1) alertBuilder.setIcon(icon); return alertBuilder.create(); } }
package com.yunhetong.sdk.base; import android.app.Application; import android.content.Context; import com.yunhetong.sdk.tool.YhtLog; import com.yunhetong.sdk.tool.YhtSPUtils; /** * Token登录凭证的管理类 * 单例 在app生命周期内存活 */ public final class TokenManager { private static final String TOKEN = "TOKEN_DATA"; private static final String TOKEN_TIME = "TOKEN_DATA_TIME"; private static final String TAG = TokenManager.class.getSimpleName(); private static TokenManager instance = new TokenManager(); private TokenManager() { } public static TokenManager getInstance() { return instance; } private Token mToken; private Context mContext; private Token.TokenListener mListener; public void initToken(Application application, String token) { if (null == mToken) { mToken = new Token(); } this.mContext = application.getApplicationContext(); mToken.init(token, 0); YhtSPUtils.put(mContext, TOKEN, mToken.getToken()); YhtSPUtils.put(mContext, TOKEN_TIME, mToken.getDate()); YhtLog.e(TAG, " YhtSPUtils: " + token + " token time: " + String.valueOf(mToken.getDate())); //登录凭证Token失效/过期 sendBroadCast(); } /** * Token过期发送广播 通知相关页面重新请求 */ private void sendBroadCast() { BroadcastUtil.sendBroadCast(mContext); } private Token getTokenBean() { if (null == mToken) { mToken = new Token(); String tkStr = YhtSPUtils.getString(mContext, TOKEN, " "); Long tkTime = YhtSPUtils.getLong(mContext, TOKEN_TIME, 0); mToken.init(tkStr, tkTime); } return mToken; } /** * 刷新凭证有效期 */ public void refreshToken() { getTokenBean().setDate(); } /** * 获取登录凭证 * * @return string */ public String getToken() { return getTokenBean().getToken(); } /** * 判断token 是否过期 * * @return boolean */ public boolean isOverdue() { // if ((System.currentTimeMillis() - this.getTokenBean().getDate()) > 1800000) return true; if ((System.currentTimeMillis() - this.getTokenBean().getDate()) > 1000000) return true;//超过十秒算超时 return false; } /** * 设置回调 * * @param listener */ public void setTokenListener(Token.TokenListener listener) { this.mListener = listener; } public Token.TokenListener getTokenListener() { return mListener; } }
package com.uiFramework.companyName.projectName.helper.assertion; import org.apache.log4j.Logger; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import com.uiFramework.companyName.projectName.helper.logger.LoggerHelper; public class VerificationHelper { private Logger log = LoggerHelper.getLogger(VerificationHelper.class); private WebDriver driver; public VerificationHelper(WebDriver driver) { this.driver = driver; } public boolean isDiplayed(WebElement element) { try { element.isDisplayed(); log.info("Element is present "+element.getText()); return true; } catch (Exception e) { log.error(element.toString() + " Element is not present " + e.getCause()); return false; } } public boolean isNotDiplayed(WebElement element) { try { element.isDisplayed(); log.info("Element is displayed"); return false; } catch (Exception e) { log.error(element.toString() + " Element is not displayed "); return true; } } public String readValueFromElement(WebElement element) { if (null == element) { log.info("WebElement is null.."); return null; } boolean status = isDiplayed(element); if (status) { log.info("element text is "+element.getText()); return element.getText(); } else { return null; } } public String getText(WebElement element) { if (null == element) { log.info("WebElement is null.."); return null; } boolean status = isDiplayed(element); if (status) { log.info("element text is "+element.getText()); return element.getText(); } else { return null; } } public String getTitle() { log.info("Page title is " +driver.getTitle()); return driver.getTitle(); } }
package pl.calculator.repository.messages; import java.util.ArrayList; import java.util.HashMap; public class ErrorMessages { private static HashMap<String, ArrayList<String>> mess = new HashMap<>(); public static void addMess(String id, String mes) { mess.computeIfAbsent(id, k -> new ArrayList<>()).add(mes); } public static void clear() { mess.clear(); } public static HashMap<String, ArrayList<String>> getMess() { return mess; } }
package main.util; import net.lingala.zip4j.core.ZipFile; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.UUID; public class UnZip { private ThreadPool threadPool; private List<String> mzFiles = new ArrayList<>(); private int count = 0; private String source; private boolean stop = false; private ZipFile zip = null; public void unZip(String zipFile) { if (!stop) { count++; resume(); doing(zipFile, false); } else { this.stopThread(); } } private void unZip(String zipFile, boolean recursive) { if (!stop) { count++; resume(); doing(zipFile, recursive); } else { this.stopThread(); } } private void doing(String zipFile, boolean recursive) { InputStream is; List<String> zipList = new ArrayList<>(); String newPath = null; byte[] buffer = new byte[2]; try { zip = new ZipFile(zipFile); // zip.setRunInThread(true); do { newPath = zip.getFile().getParent() + "\\" + UUID.randomUUID().toString(); } while (new File(newPath).exists()); if (source == null) { source = newPath; } if (!zip.isEncrypted()) { zip.extractAll(newPath); } } catch (Exception ignored) { } if (newPath != null) { File filesInZip = new File(newPath); if (filesInZip.listFiles() != null) { for (File f : Objects.requireNonNull(filesInZip.listFiles())) { if (f.isFile()) { try { is = new FileInputStream(f.getPath()); is.read(buffer); is.close(); FileFormats ff = FileFormat.compareFormat(new int[]{buffer[0], buffer[1]}); if (ff != null ) { switch (ff) { case ZIP: { zipList.add(f.getPath()); break; } case MZ: { mzFiles.add(f.getPath()); break; } } } } catch (Exception ignored) { } } else { getFilesToScan(f); } } } } if (recursive && zip != null) { zip.getFile().delete(); } for (String z : zipList) { this.unZip(z, true); } if (--count == 0) { stopThread(); } } private void getFilesToScan(File file) { InputStream is; byte[] buffer = new byte[2]; if (file.listFiles() != null) { for (File f : Objects.requireNonNull(file.listFiles())) { if (!stop) { if (f.isFile()) { try { is = new FileInputStream(f.getPath()); is.read(buffer); is.close(); FileFormats ff = FileFormat.compareFormat(new int[]{buffer[0], buffer[1]}); if (ff != null ) { switch (ff) { case MZ: { mzFiles.add(f.getPath()); break; } } } } catch (Exception ignored) { } } else { getFilesToScan(f); } } } } } private void resume() { if (threadPool == null || threadPool.isShutdown()) { threadPool = new ThreadPool(1, "unZip"); } } public void stopThread() { if (threadPool != null) { threadPool.shutdown(); threadPool = null; } } public void stop() { if (zip != null) { stopThread(); } this.stop = true; } public List<String> getFilesPath() { return mzFiles; } public void clearGarbage() { if (source != null) { try { deleteDirectoryWalkTree(Paths.get(source)); } catch (IOException e) { e.printStackTrace(); } } source = null; } public String getSource() { return source; } void deleteDirectoryWalkTree(Path path) throws IOException { FileVisitor visitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try { Files.delete(file); } catch (Exception ignored) { } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { try { Files.delete(file); } catch (Exception ignored) { } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { try { Files.delete(dir); } catch (Exception ignored) { } return FileVisitResult.CONTINUE; } }; Files.walkFileTree(path, visitor); } }
package Praticando; import java.util.Scanner; public class quadrado_area { public static void main(String[] args) { Scanner leitor = new Scanner(System.in); System.out.println("-------------------------------"); System.out.println("Digite o Lado do quadrado"); double lado = leitor.nextDouble(); double area = Math.pow(lado,2); double dobro = area * area; System.out.println("A area do quadrado é: "+area+"e o dobro é: "+ dobro); } }
package com.zantong.mobilecttx.weizhang.bean; import java.util.List; /** * Created by zhengyingbing on 17/5/5. */ public class ViolationCarInfo { private String carnum; private String enginenum; private String totalPrice; public boolean isExpanded; public void setExpanded(boolean expanded) { isExpanded = expanded; } public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } public String getTotalPrice() { return totalPrice; } public String getCarnum() { return carnum; } public void setCarnum(String carnum) { this.carnum = carnum; } public String getEnginenum() { return enginenum; } public void setEnginenum(String enginenum) { this.enginenum = enginenum; } public boolean isExpanded() { return isExpanded; } public ViolationCarInfo(String carnum, String enginenum, String totalPrice, boolean isExpanded) { this.carnum = carnum; this.enginenum = enginenum; this.totalPrice = totalPrice; this.isExpanded = false; } public ViolationCarInfo(){ } }
package frames; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JOptionPane; import java.awt.Color; import javax.swing.border.LineBorder; import javax.swing.table.DefaultTableModel; import db_operate.student_operate; import net.miginfocom.swing.MigLayout; import role_model.Course; import role_model.student; import javax.swing.JButton; import java.awt.event.ActionListener; import java.util.List; import java.util.Vector; import java.util.function.ObjDoubleConsumer; import java.awt.event.ActionEvent; import javax.swing.SwingConstants; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import java.awt.Font; import java.awt.ScrollPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.LayoutStyle.ComponentPlacement; public class StudentFrame extends MainFrame { public String selected_term; private JTextField textField; private JTextField textField_1; public JPanel panel_work_area;//右侧页面 //选课 //public JPanel xk_select_panel;// //public JPanel xk_input_panel; //public JPanel xk_course_panel; private JTextField textField_2; private JTextField textField_3; private JTextField textField_4; private JTextField textField_5; private JTextField textField_6; private JTextField textField_7; private JTable kjxk_out; private JTextField textField_8; private JTextField textField_9; private JTextField textField_10; private JTextField textField_11; private JTextField textField_12; private JTextField textField_13; //退课 private JTable infoShow; private JTextField Course_id_input; private JTextField Course_name_input; private JTable table; private JScrollPane scrollPane; private JTextField textField_14; private JTextField textField_15; private JTextField textField_16; private JTextField textField_17; private JTextField textField_18; private JTextField textField_19; private JTextField textField_20; private JTextField textField_21; private JTextField textField_22; private JTextField textField_23; private JTextField textField_24; private JTextField textField_25; private student user; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { student tmpStudent = new student(); tmpStudent.set_User_Id("1104"); StudentFrame frame = new StudentFrame(tmpStudent); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public StudentFrame(student stu) { jcombobox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String term=jcombobox.getSelectedItem().toString(); //System.out.println(term); selected_term=term; } }); //退出按钮 jbutton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); user=stu; getContentPane().setBackground(new Color(0, 191, 255)); jsplitpane.setBackground(new Color(240, 255, 255)); //panel_work_area=jsplitpane; //setBounds(100, 100, 450, 300); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //左侧 JPanel panel_left = new JPanel(); panel_left.setForeground(new Color(255, 255, 255)); panel_left.setBackground(new Color(128, 128, 128)); jsplitpane.setLeftComponent(panel_left); panel_left.setLayout(new MigLayout("", "[0px:2px:20px,grow 2][grow 2][0:2:20,grow 2]", "[40][10][40px][10][40][10][40][10][40][10][40][][]")); JButton btn_xk = new JButton("\u9009\u8BFE"); //btn_xk.setIcon(new ImageIcon("E:\\eclipsework\\course_selection_system\\src\\icon\\\u9009\u9879.png")); btn_xk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //出现xk_panel1 //先把上一次点击结果清除 panel_work_area.removeAll(); set_xk_select_panel(); jsplitpane.setRightComponent(panel_work_area); } }); btn_xk.setForeground(new Color(255, 255, 255)); btn_xk.setBackground(new Color(112, 128, 144)); panel_left.add(btn_xk, "cell 1 0,grow"); btn_xk.setOpaque(false);//设置按钮透明w JButton btn_tk = new JButton("\u9000\u8BFE"); btn_tk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { panel_work_area.removeAll(); set_tk_select_panel(); jsplitpane.setRightComponent(panel_work_area); } }); btn_tk.setIcon(new ImageIcon("E:\\eclipsework\\course_selection_system\\src\\icon\\\u9009\u9879.png")); btn_tk.setForeground(new Color(255, 255, 255)); btn_tk.setBackground(new Color(112, 128, 144)); panel_left.add(btn_tk, "cell 1 2,grow"); btn_tk.setOpaque(false);//设置按钮透明 btn_tk.setBorder(null); JButton btn_kccx = new JButton("\u8BFE\u7A0B\u67E5\u8BE2"); btn_kccx.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { panel_work_area.removeAll(); JScrollPane scrollPane = new JScrollPane(); infoShow = new JTable(); infoShow.setModel(new DefaultTableModel( new Object[][]{}, new Object [] {"课号","课名","教师姓名","上课时间","上课地点"} )); DefaultTableModel model = (DefaultTableModel) infoShow.getModel(); Vector<String[]> data = new student_operate().getChosenClass(stu.get_User_Id()); model.setRowCount(0); for(Object tmp[]:data) { model.addRow(tmp); } scrollPane.setViewportView(infoShow); jsplitpane.setRightComponent(scrollPane); } }); btn_kccx.setIcon(new ImageIcon("E:\\eclipsework\\course_selection_system\\src\\icon\\\u9009\u9879.png")); btn_kccx.setForeground(new Color(255, 255, 255)); btn_kccx.setBackground(new Color(112, 128, 144)); panel_left.add(btn_kccx, "cell 1 4,grow"); btn_kccx.setOpaque(false);//设置按钮透明 btn_kccx.setBorder(null); //右侧 JPanel panel_right = new JPanel(); panel_right.setBackground(new Color(224, 255, 255)); panel_right.setLayout(new MigLayout("", "[grow]", "[40px:40px:70px][100px:165px:180px][grow]")); panel_work_area=panel_right; // //jsplitpane.setRightComponent(panel_work_area); //出现xk_panel_2 } public void set_xk_select_panel() { //点击选课出现xk_panel_1 JPanel xk_panel_1 = new JPanel(); xk_panel_1.setBackground(new Color(248, 248, 255)); panel_work_area.add(xk_panel_1, "cell 0 0,grow"); xk_panel_1.setLayout(new MigLayout("", "[][5px:5px:10px][][5px:5px:10px][]", "[]")); JLabel lblNewLabel_1 = new JLabel(""); lblNewLabel_1.setIcon(new ImageIcon("E:\\eclipsework\\course_selection_system\\src\\icon\\\u7535\u8111.png")); xk_panel_1.add(lblNewLabel_1, "cell 0 0"); ButtonGroup group_select = new ButtonGroup();; JRadioButton rdbtnNewRadioButton = new JRadioButton("\u5FEB\u6377\u9009\u8BFE"); group_select.add(rdbtnNewRadioButton); rdbtnNewRadioButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //先将panel_work_area的下标为1的清空 //xk_input_panel.removeAll(); if(panel_work_area.getComponents().length>1) panel_work_area.remove(1); set_xk_input_panel(); //panel_work_area.add(xk_input_panel); jsplitpane.setRightComponent(panel_work_area); } }); rdbtnNewRadioButton.setBackground(new Color(248, 248, 255)); xk_panel_1.add(rdbtnNewRadioButton, "cell 2 0"); JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("\u6A21\u7CCA\u67E5\u8BE2"); group_select.add(rdbtnNewRadioButton_1); rdbtnNewRadioButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //先将panel_work_area的下标为1的清空 //xk_input_panel.removeAll(); if(panel_work_area.getComponents().length>1) panel_work_area.remove(1); set_mhcx_input(); //panel_work_area.add(xk_input_panel); jsplitpane.setRightComponent(panel_work_area); } }); rdbtnNewRadioButton_1.setBackground(new Color(248, 248, 255)); xk_panel_1.add(rdbtnNewRadioButton_1, "cell 4 0"); } public void set_tk_select_panel() { JPanel panel_tk = new JPanel(); jsplitpane.setRightComponent(panel_tk); panel_work_area.add(panel_tk, "cell 0 0,grow"); JLabel lblNewLabel_13 = new JLabel("\u8BFE\u7A0B\u53F7"); lblNewLabel_13.setFont(new Font("宋体", Font.PLAIN, 18)); JLabel lblNewLabel_13_1 = new JLabel("\u6559\u5E08\u53F7"); lblNewLabel_13_1.setFont(new Font("宋体", Font.PLAIN, 18)); JLabel lblNewLabel_13_1_1 = new JLabel("\u6559\u5E08\u53F7"); lblNewLabel_13_1_1.setFont(new Font("宋体", Font.PLAIN, 18)); JLabel lblNewLabel_13_2 = new JLabel("\u8BFE\u7A0B\u53F7"); lblNewLabel_13_2.setFont(new Font("宋体", Font.PLAIN, 18)); textField_14 = new JTextField(); textField_14.setColumns(10); textField_15 = new JTextField(); textField_15.setColumns(10); textField_16 = new JTextField(); textField_16.setColumns(10); textField_17 = new JTextField(); textField_17.setColumns(10); textField_18 = new JTextField(); textField_18.setColumns(10); textField_19 = new JTextField(); textField_19.setColumns(10); textField_20 = new JTextField(); textField_20.setColumns(10); textField_21 = new JTextField(); textField_21.setColumns(10); textField_22 = new JTextField(); textField_22.setColumns(10); textField_23 = new JTextField(); textField_23.setColumns(10); textField_24 = new JTextField(); textField_24.setColumns(10); textField_25 = new JTextField(); textField_25.setColumns(10); JLabel lblNewLabel_14 = new JLabel("1"); JLabel lblNewLabel_14_1 = new JLabel("2"); JLabel lblNewLabel_14_1_1 = new JLabel("3"); JLabel lblNewLabel_14_1_1_1 = new JLabel("4"); JLabel lblNewLabel_14_1_1_2 = new JLabel("5"); JLabel lblNewLabel_14_1_1_3 = new JLabel("6"); panel_tk.setBackground(new Color(224, 255, 255)); panel_tk.setLayout(new MigLayout("", "[28px][66px][66px][28px][66px][66px]", "[50px][21px][21px][21px][]")); panel_tk.add(lblNewLabel_13, "cell 1 0,alignx left,growy"); panel_tk.add(lblNewLabel_13_1, "cell 2 0,alignx center,aligny center"); panel_tk.add(lblNewLabel_13_1_1, "cell 5 0,alignx left,aligny center"); panel_tk.add(lblNewLabel_13_2, "cell 4 0,alignx left,growy"); panel_tk.add(textField_14, "cell 1 1,alignx left,aligny top"); panel_tk.add(textField_15, "cell 2 1,alignx left,aligny top"); panel_tk.add(textField_16, "cell 4 1,alignx left,aligny top"); panel_tk.add(textField_17, "cell 5 1,alignx left,aligny top"); panel_tk.add(textField_18, "cell 1 2,alignx left,aligny top"); panel_tk.add(textField_19, "cell 2 2,alignx left,aligny top"); panel_tk.add(textField_20, "cell 4 2,alignx left,aligny top"); panel_tk.add(textField_21, "cell 5 2,alignx left,aligny top"); panel_tk.add(textField_22, "cell 1 3,alignx left,aligny top"); panel_tk.add(textField_23, "cell 2 3,alignx left,aligny top"); panel_tk.add(textField_24, "cell 4 3,alignx left,aligny top"); panel_tk.add(textField_25, "cell 5 3,alignx left,aligny top"); panel_tk.add(lblNewLabel_14, "cell 0 1,grow"); panel_tk.add(lblNewLabel_14_1, "cell 0 2,growx,aligny top"); panel_tk.add(lblNewLabel_14_1_1, "cell 0 3,grow"); panel_tk.add(lblNewLabel_14_1_1_1, "cell 3 1,grow"); panel_tk.add(lblNewLabel_14_1_1_2, "cell 3 2,grow"); panel_tk.add(lblNewLabel_14_1_1_3, "cell 3 3,grow"); JButton tkButton = new JButton("\u9000\u8BFE"); tkButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean can = true; if(textField_14.getText().length()>1&&textField_15.getText().length()>1) { can=new student_operate().delete(user.get_User_Id(),textField_14.getText(),textField_15.getText()); } if(textField_16.getText().length()>1&&textField_17.getText().length()>1) { can=new student_operate().delete(user.get_User_Id(),textField_16.getText(),textField_17.getText()); } if(textField_18.getText().length()>1&&textField_19.getText().length()>1) { can=new student_operate().delete(user.get_User_Id(),textField_18.getText(),textField_19.getText()); } if(textField_20.getText().length()>1&&textField_21.getText().length()>1) { can=new student_operate().delete(user.get_User_Id(),textField_20.getText(),textField_21.getText()); } if(textField_22.getText().length()>1&&textField_23.getText().length()>1) { can=new student_operate().delete(user.get_User_Id(),textField_22.getText(),textField_23.getText()); } if(textField_24.getText().length()>1&&textField_25.getText().length()>1) { can=new student_operate().delete(user.get_User_Id(),textField_24.getText(),textField_25.getText()); } } }); panel_tk.add(tkButton, "cell 4 4"); JButton refresh = new JButton("\u91CD\u7F6E"); refresh.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textField_14.setText(""); textField_15.setText(""); textField_16.setText(""); textField_17.setText(""); textField_18.setText(""); textField_19.setText(""); textField_20.setText(""); textField_21.setText(""); textField_22.setText(""); textField_23.setText(""); textField_25.setText(""); textField_24.setText(""); } }); panel_tk.add(refresh, "cell 5 4"); } public void set_xk_input_panel() { //出现xk_panel_2 JPanel xk_panel_2 = new JPanel(); xk_panel_2.setBackground(new Color(248, 248, 255)); panel_work_area.add(xk_panel_2, "cell 0 1,grow"); xk_panel_2.setLayout(new MigLayout("", "[][80px:150px:170px,grow][40px:70px:90px][10px:15px:20px][80px:150px:170px,grow][40px:70px:90px]", "[][][][][]")); JLabel lblNewLabel_2 = new JLabel("\u8BFE\u7A0B\u53F7"); lblNewLabel_2.setFont(new Font("宋体", Font.BOLD, 18)); xk_panel_2.add(lblNewLabel_2, "cell 1 0,alignx center"); JLabel lblNewLabel_3 = new JLabel("\u6559\u5E08\u53F7"); lblNewLabel_3.setFont(new Font("宋体", Font.BOLD, 18)); xk_panel_2.add(lblNewLabel_3, "cell 2 0,alignx center"); JLabel lblNewLabel = new JLabel("\u8BFE\u7A0B\u53F7"); lblNewLabel.setFont(new Font("宋体", Font.BOLD, 18)); xk_panel_2.add(lblNewLabel, "cell 4 0,alignx center"); JLabel lblNewLabel_8 = new JLabel("\u6559\u5E08\u53F7"); lblNewLabel_8.setFont(new Font("宋体", Font.BOLD, 18)); xk_panel_2.add(lblNewLabel_8, "cell 5 0,alignx center"); JLabel lblNewLabel_4 = new JLabel("1"); xk_panel_2.add(lblNewLabel_4, "cell 0 1,alignx trailing"); textField_2 = new JTextField(); xk_panel_2.add(textField_2, "cell 1 1,growx"); textField_2.setColumns(10); textField_3 = new JTextField(); xk_panel_2.add(textField_3, "cell 2 1,growx"); textField_3.setColumns(10); JButton affirm = new JButton("\u786E\u5B9A"); affirm.setBackground(new Color(248, 248, 255));//设置按钮颜色 affirm.setIcon(new ImageIcon("E:\\eclipsework\\course_selection_system\\src\\icon\\\u786E\u5B9A.png")); affirm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("2"+textField_2.getText()); System.out.println("3"+textField_3.getText()); boolean can = true; if(textField_2.getText().length()>1&&textField_2.getText().length()>1) { can=new student_operate().addSelectedCourse(user.get_User_Id(),textField_2.getText(),textField_3.getText()); } System.out.println("4"+textField_4.getText()); System.out.println("5"+textField_5.getText()); if(textField_4.getText().length()>1&&textField_5.getText().length()>1) { can=new student_operate().addSelectedCourse(user.get_User_Id(),textField_4.getText(),textField_5.getText()); } System.out.println("6"+textField_6.getText()); System.out.println("7"+textField_7.getText()); if(textField_6.getText().length()>1&&textField_7.getText().length()>1) { can=new student_operate().addSelectedCourse(user.get_User_Id(),textField_6.getText(),textField_7.getText()); } System.out.println("8"+textField_8.getText()); System.out.println("9"+textField_9.getText()); if(textField_8.getText().length()>1&&textField_9.getText().length()>1) { can=new student_operate().addSelectedCourse(user.get_User_Id(),textField_8.getText(),textField_9.getText()); } System.out.println("10"+textField_10.getText()); System.out.println("11"+textField_11.getText()); if(textField_10.getText().length()>1&&textField_11.getText().length()>1) { can=new student_operate().addSelectedCourse(user.get_User_Id(),textField_10.getText(),textField_11.getText()); } System.out.println("12"+textField_12.getText()); System.out.println("13"+textField_13.getText()); if(textField_12.getText().length()>1&&textField_13.getText().length()>1) { can=new student_operate().addSelectedCourse(user.get_User_Id(),textField_12.getText(),textField_13.getText()); } } }); JLabel lblNewLabel_9 = new JLabel("2"); xk_panel_2.add(lblNewLabel_9, "cell 3 1,alignx right"); textField_8 = new JTextField(); xk_panel_2.add(textField_8, "cell 4 1,growx"); textField_8.setColumns(10); textField_9 = new JTextField(); xk_panel_2.add(textField_9, "cell 5 1,growx"); textField_9.setColumns(10); JLabel lblNewLabel_5 = new JLabel("3"); xk_panel_2.add(lblNewLabel_5, "cell 0 2,alignx trailing"); textField_4 = new JTextField(); xk_panel_2.add(textField_4, "cell 1 2,growx"); textField_4.setColumns(10); textField_5 = new JTextField(); xk_panel_2.add(textField_5, "cell 2 2,growx"); textField_5.setColumns(10); JLabel lblNewLabel_10 = new JLabel("4"); xk_panel_2.add(lblNewLabel_10, "cell 3 2,alignx right"); textField_10 = new JTextField(); xk_panel_2.add(textField_10, "cell 4 2,growx"); textField_10.setColumns(10); textField_11 = new JTextField(); xk_panel_2.add(textField_11, "cell 5 2,growx"); textField_11.setColumns(10); JLabel lblNewLabel_6 = new JLabel("5"); xk_panel_2.add(lblNewLabel_6, "cell 0 3,alignx trailing"); textField_6 = new JTextField(); xk_panel_2.add(textField_6, "cell 1 3,growx"); textField_6.setColumns(10); textField_7 = new JTextField(); xk_panel_2.add(textField_7, "cell 2 3,growx"); textField_7.setColumns(10); JLabel lblNewLabel_11 = new JLabel("6"); xk_panel_2.add(lblNewLabel_11, "cell 3 3,alignx right"); textField_12 = new JTextField(); xk_panel_2.add(textField_12, "cell 4 3,growx"); textField_12.setColumns(10); textField_13 = new JTextField(); xk_panel_2.add(textField_13, "cell 5 3,growx"); textField_13.setColumns(10); xk_panel_2.add(affirm, "flowx,cell 1 4"); JButton reset = new JButton("\u91CD\u7F6E"); reset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textField_2.setText(""); textField_3.setText(""); textField_4.setText(""); textField_5.setText(""); textField_6.setText(""); textField_7.setText(""); textField_8.setText(""); textField_9.setText(""); textField_10.setText(""); textField_11.setText(""); textField_12.setText(""); textField_13.setText(""); } }); reset.setBackground(new Color(248, 248, 255));//设置按钮颜色 reset.setIcon(new ImageIcon("E:\\eclipsework\\course_selection_system\\src\\icon\\\u91CD\u7F6E.png")); xk_panel_2.add(reset, "cell 1 4"); } public void set_course_panel() { //选课结果 JPanel xk_panel_3 = new JPanel(); xk_panel_3.setBackground(new Color(248, 248, 255)); panel_work_area.add(xk_panel_3, "cell 0 2,grow"); xk_panel_3.setLayout(new MigLayout("", "[grow]", "[][grow]")); JLabel lblNewLabel_7 = new JLabel("\u9009\u8BFE\u7ED3\u679C"); xk_panel_3.add(lblNewLabel_7, "cell 0 0"); kjxk_out = new JTable(); xk_panel_3.add(kjxk_out, "cell 0 1,grow"); } public void set_mhcx_input() { JPanel panel = new JPanel(); panel.setBackground(new Color(248, 248, 255)); panel_work_area.add(panel, "cell 0 1,grow"); JLabel lblNewLabel_12 = new JLabel("\u8BFE\u53F7:"); lblNewLabel_12.setFont(new Font("宋体", Font.BOLD, 18)); Course_id_input = new JTextField(); Course_id_input.setColumns(10); JLabel lblNewLabel_12_1 = new JLabel("\u8BFE\u540D:"); lblNewLabel_12_1.setFont(new Font("宋体", Font.BOLD, 18)); Course_name_input = new JTextField(); Course_name_input.setColumns(10); JButton FindButton = new JButton("\u67E5\u627E"); FindButton.setBackground(new Color(224, 255, 255)); FindButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String course_name=Course_name_input.getText(); String course_id=Course_id_input.getText(); course_name="'%"+course_name+"%'"; course_id="'%"+course_id+"%'"; List<Course> ans; ans=new student_operate().getCourseList(course_id,course_name); infoShow = new JTable(); infoShow.setModel(new DefaultTableModel( new Object[][]{}, new Object[] {"课号","课名","教师姓名","上课时间","上课地点"} )); DefaultTableModel model = (DefaultTableModel)infoShow.getModel(); model.setRowCount(0); for(Course tmp:ans) { String [] tmpStrings = new String[5]; tmpStrings[0] = tmp.getKh(); tmpStrings[1] = tmp.getKm(); tmpStrings[2] = tmp.getGh(); tmpStrings[3] = tmp.getSksj(); tmpStrings[4] = tmp.getSkdd(); model.addRow(tmpStrings); } if(panel_work_area.getComponents().length>2) panel_work_area.remove(2); set_mhcx_info(); //panel_work_area.add(xk_input_panel); jsplitpane.setRightComponent(panel_work_area); scrollPane.setViewportView(infoShow); } }); FindButton.setFont(new Font("宋体", Font.BOLD, 20)); panel.setLayout(new MigLayout("", "[45px:45px:50px,grow][100px:208px:250px,grow][10px:20px:30px,grow][50px:80px:100px,grow][]", "[20px:25px:30px,grow][10px:15px:20px][20px:25px:30px,grow]")); panel.add(lblNewLabel_12_1, "cell 0 2,alignx right,growy"); panel.add(Course_name_input, "cell 1 2,grow"); panel.add(lblNewLabel_12, "cell 0 0,alignx right,growy"); panel.add(Course_id_input, "cell 1 0,grow"); panel.add(FindButton, "cell 3 0 1 3,grow"); } public void set_mhcx_info() { scrollPane = new JScrollPane(); panel_work_area.add(scrollPane, "cell 0 2,grow"); table = new JTable(); scrollPane.setViewportView(table); } }
package com.metinkale.prayerapp.compass.classes.math; import android.support.annotation.NonNull; public class Util { /** * Converts a double to a value between 0 and 360 * * @param x * @return double in 0-360 range */ public static float floatrev(double x) { return (float) (x - (Math.floor(x / 360.0f) * 360.0f)); } /** * Derive distance between 3d vector a,b * * @param a * @param b * @return */ public static float calcDistance(@NonNull Vector3 a, @NonNull Vector3 b) { return (float) Math.sqrt(((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y)) + ((a.z - b.z) * (a.z - b.z))); } /** * calculates the encompassing circle radius for sides a,b,c of a triangle * * @param a * @param b * @param c * @return */ public static float calcRadius(float a, float b, float c) { return (float) ((a * b * c) / Math.sqrt((a + b + c) * ((a - b) + c) * ((a + b) - c) * ((b + c) - a))); } /** * Calculates the angle A given length a and circle radius r, according to * the law of sines ([a/sin(A) = 2R], thus [A = arcsin(a/2r)]) * * @param a * @param r * @return angle A in radians */ public static float calcAngle(float a, float r) { return (float) Math.asin(a / (2 * r)); } /** * Calculates the angle A given length a and circle radius r, according to * the law of sines ([a/sin(A) = 2R], thus [A = arcsin(a/2r)]) * * @param a * @param r * @return angle A in radians */ public static float calcAngleClamp(float a, float r) { return (float) Math.asin(Math.min(1, Math.max(-1, a / (2 * r)))); } }
package controller; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import model.Project; import model.RatingQuestion; import model.access.IRatingQuestionIdLoader; import model.access.IRatingQuestionListLoader; import model.access.IRatingQuestionMinCountLoader; import model.access.MySQLRatingQuestionIdLoader; import model.access.MySQLRatingQuestionListLoader; import model.access.MySQLRatingQuestionMinCountLoader; public class RatingQuestionLoader { public List<RatingQuestion> load() throws Exception { IRatingQuestionListLoader loader = new MySQLRatingQuestionListLoader(); List<Integer> questionIds = chooseIdsOfLowestCountVoted(); List<RatingQuestion> questions = loader.loadByIds(questionIds); return questions; } private List<Integer> chooseIdsOfLowestCountVoted() throws Exception { Project project = MainController.getDataController().getProject(); String gender = MainController.getDataController().getParticipant().getGender(); Integer neededCount = project.getQuestionCount(); //Load the minimum count of answers for pairing gender and project IRatingQuestionMinCountLoader cntLoader = new MySQLRatingQuestionMinCountLoader(); int lowestCountVoted = cntLoader.loadByGender(gender, project); List<Integer> newQuestionIds = new ArrayList<Integer>(); while(newQuestionIds.size() < neededCount) { //Load IDs with minimum count of answers IRatingQuestionIdLoader idLoader = new MySQLRatingQuestionIdLoader(); List<Integer> loadedIds = idLoader.loadByGenderCountVoted(project, gender, lowestCountVoted); //If exact amount is found if(loadedIds.size() == neededCount) { //TODO Logger newQuestionIds.addAll(loadedIds); break; } //If more questions are available chose random ones if(loadedIds.size() > neededCount) { //TODO Logger List<Integer> randomIds = getRandomQuestionIds(neededCount, loadedIds); newQuestionIds.addAll(randomIds); break; } //If not enough questions are available if(loadedIds.size() < neededCount) { lowestCountVoted = cntLoader.loadByGenderAndAbove(gender, lowestCountVoted, project); newQuestionIds.addAll(loadedIds); } } return newQuestionIds; } /** * Method chooses randomly a given number of IDs out of the given list of more IDs * @param neededCount how many IDs do you need? * @param questionIds List of IDs from which should be chosen * @return List of chosen random IDs */ private List<Integer> getRandomQuestionIds(int neededCount, List<Integer> questionIds) { Collections.shuffle(questionIds); List<Integer> newQuestionIds = new ArrayList<Integer>(); Iterator<Integer> questionIdsIterator = questionIds.iterator(); while(neededCount > 0) { Integer randomQuestion = questionIdsIterator.next(); newQuestionIds.add(randomQuestion); neededCount--; } return newQuestionIds; } }
package message; import org.jbox2d.callbacks.ContactImpulse; import org.jbox2d.callbacks.ContactListener; import org.jbox2d.collision.Manifold; import org.jbox2d.dynamics.contacts.Contact; import component.CColidable; public class ContactListenerSlick implements ContactListener { @Override public void beginContact(Contact contact) { // Pass one colidable module to the other ((CColidable) contact.getFixtureA().getBody().getUserData()).colide(((CColidable)contact.getFixtureB().getBody().getUserData())); ((CColidable) contact.getFixtureB().getBody().getUserData()).colide(((CColidable)contact.getFixtureA().getBody().getUserData())); } @Override public void endContact(Contact contact) { } @Override public void postSolve(Contact arg0, ContactImpulse arg1) { // TODO Auto-generated method stub } @Override public void preSolve(Contact arg0, Manifold arg1) { // TODO Auto-generated method stub } }
package net.oesterholt.taskgnome; import java.awt.Component; import java.awt.Dimension; import java.awt.Image; import java.awt.Point; import java.awt.SystemTray; import java.awt.Toolkit; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.net.URL; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JToolBar; import javax.swing.UIManager; import javax.swing.filechooser.FileNameExtensionFilter; import org.apache.log4j.Logger; import net.miginfocom.swing.MigLayout; import net.oesterholt.jndbm.NDbm2; import net.oesterholt.jndbm2.exceptions.NDbmException; import net.oesterholt.taskgnome.data.CdCategories; import net.oesterholt.taskgnome.data.DataFactory; import net.oesterholt.taskgnome.ui.JStatusBar; import net.oesterholt.taskgnome.utils.Config; import net.oesterholt.taskgnome.utils.Swing; import net.oesterholt.taskgnome.utils.TgLogger; public class TaskWindow implements Runnable, ActionListener { static Logger logger=TgLogger.getLogger(TaskWindow.class); class MySep extends JSeparator { public MySep() { super(JSeparator.VERTICAL); Dimension size = new Dimension( super.getPreferredSize().width, super.getMaximumSize().height ); super.setMaximumSize(size); } } private JFrame _frame; private JMenuBar _menu; private JButton _finished; private JButton _active; private JStatusBar _status; private DataFactory _factory; private TasksController _controller; private TasksView _view; private void einde() { _controller.endSyncs(new Runnable() { public void run() { _factory = null; TaskGnome.setWindowPosition(_frame.getLocation(),_frame.getSize()); _frame.setVisible(false); System.exit(0); } }); } private void hideshow() { if (_frame.isVisible()) { _frame.setVisible(false);; } else { _frame.setVisible(true); } } public void actionPerformed(ActionEvent e) { String cmd=e.getActionCommand(); if ("quit".equals(cmd)) { einde(); } else if ("addtask".equals(cmd)) { _controller.addTask(_frame); } else if ("changetask".equals(cmd)) { _controller.editSelectedTask(_frame); } else if ("deletetask".equals(cmd)) { _controller.deleteSelectedTask(_frame); } else if ("checktask".equals(cmd)) { _controller.checkSelectedTask(_frame); } else if ("changekind".equals(cmd)) { _controller.changeKind(_frame); _finished.setVisible(false); _active.setVisible(true);; } else if ("changekind1".equals(cmd)) { _controller.changeKind(_frame); _active.setVisible(false);; _finished.setVisible(true); } else if ("sync".equals(cmd)) { _controller.sync(_frame); } else if ("prefs".equals(cmd)) { _controller.prefs(_frame); } } public TaskWindow(String dataDirectory) throws Exception { _factory = new DataFactory(new File(dataDirectory)); CdCategories cats = _factory.categories(); try { if (!cats.containsKey("-")) { cats.put(_factory.newCategoryForceId("-", "-")); } if (!cats.containsKey("Inbox_id")) { cats.put(_factory.newCategoryForceId("Inbox", "Inbox_id")); } if (!cats.containsKey("Personal_id")) { cats.put(_factory.newCategoryForceId("Personal", "Personal_id")); } if (!cats.containsKey("Work_id")) { cats.put(_factory.newCategoryForceId("Work", "Work_id")); } } catch (Exception e) { e.printStackTrace(); } } public void message(String m) { _status.setMessage(m);; } public void errorMessage(String m) { _status.setError(m); } @SuppressWarnings("serial") public void run() { // Look and feel try { //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); Swing.scaleToScreen(UIManager.getSystemLookAndFeelClassName()); //UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); //UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch(Exception e) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e1) { // ignore exception } } // menu { _menu=new JMenuBar(); JMenu tasks=new JMenu("Tasks"); tasks.add(TaskGnome.menu("addtask", "Add Task", this)); tasks.add(TaskGnome.menu("changetask", "Change Task", this)); tasks.add(TaskGnome.menu("checktask", "Toggle Task", this)); tasks.add(new JSeparator()); tasks.add(TaskGnome.menu("deletetask", "Delete Task", this)); tasks.add(new JSeparator()); tasks.add(TaskGnome.menu("quit","Quit", this)); } _frame=new JFrame("Task Gnome - " + Config.Copyright()); _controller = new TasksController(_frame, _factory, this); _view = new TasksView(_controller); // tools JToolBar bar=new JToolBar(); { bar.add(TaskGnome.toolBarAction("quit",this)); bar.add(new MySep()); bar.add(TaskGnome.toolBarAction("addtask", this)); bar.add(TaskGnome.toolBarAction("changetask", this)); bar.add(new MySep()); JButton deleted = TaskGnome.toolBarAction("deletetask", this); bar.add(deleted); bar.add(new MySep()); bar.add(TaskGnome.toolBarAction("checktask", this)); bar.add(new MySep()); bar.add(TaskGnome.toolBarAction("prefs", this)); bar.add(Box.createHorizontalGlue()); _finished = TaskGnome.toolBarAction("changekind", this); _active = TaskGnome.toolBarAction("changekind1", this); _active.setVisible(false); bar.add(_finished);bar.add(_active); //bar.add(TaskGnome.toolBarAction("sync", this)); bar.setFloatable(false); bar.setFocusable(false); bar.setBorder(BorderFactory.createEtchedBorder()); } // Status bar _status = new JStatusBar(); // System tray if (!SystemTray.isSupported()) { logger.warn("System tray is not supported on this system"); } else { URL url=TaskGnome.class.getResource( String.format("/net/oesterholt/taskgnome/resources/%s.png","icon") ); final TrayIcon icon = new TrayIcon(new ImageIcon(url).getImage()); icon.setImageAutoSize(true); final SystemTray tray = SystemTray.getSystemTray(); try { tray.add(icon);; icon.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (_frame.isVisible()) { _frame.setVisible(false); } else { _frame.setVisible(true); } } }); icon.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { if (_frame.isVisible()) { _frame.setVisible(false); } else { _frame.setVisible(true); } } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }); } catch (Exception e) { logger.error(e); } } _frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); _frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { hideshow(); } }); TaskGnome.setIconImage(_frame); _frame.setJMenuBar(_menu); { JPanel p=new JPanel(new MigLayout("fill"));; p.add(bar,"dock north, growx, wrap"); p.add(_view,"growx, growy"); p.add(_status, "dock south, growx, wrap"); _frame.add(p); } Point loc=TaskGnome.getPrevWindowLocation(); Dimension size=TaskGnome.getPrevWindowSize(); Dimension ssize = Toolkit.getDefaultToolkit().getScreenSize(); if (size!=null) { _frame.setPreferredSize(size); } _frame.pack(); if (loc!=null) { if (loc.x > ssize.width - 50) { loc.x = 100; } if (loc.y > ssize.height - 50) { loc.y = 100; } _frame.setLocation(loc); } _frame.setVisible(true); } }
package org.mkcl.apps; import java.util.Locale; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * Handles requests for the application home page. */ @Controller public class HomeController { @RequestMapping(value = "/message", method = RequestMethod.GET) public @ResponseBody ResponseEntity<String> home(Locale locale, Model model) { ResponseEntity<String> responseEntity = new ResponseEntity<String>( "Hello World", HttpStatus.OK); return responseEntity; } }
package moobie.dao; import java.sql.Date; import java.util.List; import java.util.ArrayList; import java.util.Random; import moobie.entidade.Pessoa; public class PessoaDAO { /*classe simulando conexao de dados*/ //Pessoa 1 e 2 possuem propriedade de veiculos private Pessoa p1 = new Pessoa(1, "Maria", Date.valueOf("1987-12-01"), "985321475", "96523478555", "123456789"); private Pessoa p2 = new Pessoa(2, "Jo„o", Date.valueOf("1990-03-23"), "655423368", "12548963258", "987654321"); //Pessoa 3, 4 e 5 sao locadores private Pessoa p3 = new Pessoa(3, "Pedro", Date.valueOf("1972-10-05"), "100258544", "99985632447", "32165498"); private Pessoa p4 = new Pessoa(4, "Josť", Date.valueOf("1999-08-25"), "96582348", "66892514756", "232326556"); private Pessoa p5 = new Pessoa(5, "Joana", Date.valueOf("1992-07-30"), "235478111", "63254187425", "98986565656"); public List<Pessoa> listarPessoas() throws Exception { List<Pessoa> lista = new ArrayList<>(); lista.add(p1); lista.add(p2); lista.add(p3); return lista; } public int addPessoa(Pessoa pessoa) throws Exception{ int idGerado = 0; Random gerador = new Random(); System.out.println("Inserindo pessoa: " + pessoa.getNome() + " Data Nascto: " + pessoa.getData_nscto() + " RG: " + pessoa.getRg() + " CPF: " + pessoa.getCpf() + " CNH: " + pessoa.getNro_cnh()); //gera int randomico para simular id inserido. idGerado = gerador.nextInt(); return idGerado; } public void editPessoa(Pessoa pessoa) throws Exception{ System.out.println("Editando pessoa: " + pessoa.getNome() + " Data Nascto: " + pessoa.getData_nscto() + " RG: " + pessoa.getRg() + " CPF: " + pessoa.getCpf() + " CNH: " + pessoa.getNro_cnh()); } public void deletePessoa(Pessoa pessoa) throws Exception{ System.out.println("Deletando carro: " + pessoa.getNome() + " Data Nascto: " + pessoa.getData_nscto() + " RG: " + pessoa.getRg() + " CPF: " + pessoa.getCpf() + " CNH: " + pessoa.getNro_cnh()); } public Pessoa getP1() { return p1; } public void setP1(Pessoa p1) { this.p1 = p1; } public Pessoa getP2() { return p2; } public void setP2(Pessoa p2) { this.p2 = p2; } public Pessoa getP3() { return p3; } public void setP3(Pessoa p3) { this.p3 = p3; } public Pessoa getP4() { return p4; } public void setP4(Pessoa p4) { this.p4 = p4; } public Pessoa getP5() { return p5; } public void setP5(Pessoa p5) { this.p5 = p5; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package se.kth.kthfsdashboard.user; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; /** * * @author Jim Dowling<jdowling@sics.se> */ //@SessionScoped @ManagedBean @RequestScoped public class UserMB { private Username user; @EJB private UserFacade userFacade; public Username getUser() { if (user == null) { ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); String userEmail = context.getUserPrincipal().getName(); user = userFacade.findByEmail(userEmail); } return user; } public String getName() { return (getUser() != null) ? user.getName() : "null"; } public boolean isUserAdmin() { return getRequest().isUserInRole("ADMIN"); } public String logOut() { getRequest().getSession().invalidate(); return "logout"; } private HttpServletRequest getRequest() { return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); } }
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class reversequeue { public static void main(String[] args) { Queue<Integer> q=new LinkedList<>(); Scanner sc =new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt();int arr[]=new int[k]; for(int i=0;i<n;i++) { q.add(sc.nextInt()); } for(int i=k-1;i>=0;i--) { arr[i]=q.poll(); } for(int i=0;i<k;i++) { System.out.print(arr[i]+" "); } for(int j=0;j<n-k;j++) { System.out.print(q.poll()+" "); } } }
package online.lahloba.www.lahloba.utils; import android.content.Context; import android.graphics.Bitmap; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.text.format.DateUtils; import android.util.TypedValue; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import online.lahloba.www.lahloba.ui.products.ProductsActivity; public class Utils { private static final int SECOND_MILLIS = 1000; private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; private static final int DAY_MILLIS = 24 * HOUR_MILLIS; public static boolean checkValidEmail(String email){ Pattern pattern = Pattern.compile("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"); Matcher mat = pattern.matcher(email); if(mat.matches()){ return true; }else{ return false; } } public static int getCostByDistance(double distance){ if (distance <= 5){ return 10; }else if (distance >5 && distance <= 10){ return 15; }else if (distance >10 && distance <= 15){ return 20; }else if (distance >15 && distance <= 20){ return 25; }else if (distance > 20){ return 30; } return 0; } public static String getBannerActivityName(String type){ if (type.equals(Constants.BANNER_TYPE_PRODUCTS_CATEGORY)){ return ".ui.products.ProductsActivity"; }else if (type.equals(Constants.BANNER_TYPE_NEW_NEWS)){ return ".ui.news.NewsActivity"; }else { return ""; } } public static String getRelationTime(Date past) { if (past == null) return ""; long now = System.currentTimeMillis(); long difference = now - past.getTime(); if (difference > 0 && difference < DateUtils.MINUTE_IN_MILLIS){ return (String) DateUtils.getRelativeTimeSpanString(past.getTime(), now, DateUtils.SECOND_IN_MILLIS); }else if (difference >= DateUtils.MINUTE_IN_MILLIS && difference < DateUtils.HOUR_IN_MILLIS){ return (String) DateUtils.getRelativeTimeSpanString(past.getTime(), now, DateUtils.MINUTE_IN_MILLIS); }else if (difference >= DateUtils.HOUR_IN_MILLIS && difference < DateUtils.DAY_IN_MILLIS){ return (String) DateUtils.getRelativeTimeSpanString(past.getTime(), now, DateUtils.HOUR_IN_MILLIS); }else if ( difference >= DateUtils.DAY_IN_MILLIS){ return (String) DateUtils.getRelativeTimeSpanString(past.getTime(), now, DateUtils.DAY_IN_MILLIS); }else { return (String) android.text.format.DateFormat.format("hh:mm:ss a", past); } } public static Bitmap getResizedBitmap(Bitmap image, int maxSize) { int width = image.getWidth(); int height = image.getHeight(); float bitmapRatio = (float)width / (float) height; if (bitmapRatio > 1) { width = maxSize; height = (int) (width / bitmapRatio); } else { height = maxSize; width = (int) (height * bitmapRatio); } return Bitmap.createScaledBitmap(image, width, height, true); } public static int dpToPx(float dp, Context context) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); } }
package menu; import java.awt.Graphics; import java.awt.Point; import java.util.ArrayList; import java.awt.Cursor; import main_app.Handler; public abstract class Menu { ArrayList<Button> buttons; Handler handler; public Menu(Handler handler) { this.handler = handler; this.buttons = new ArrayList<Button>(); } public abstract void execute(int id); public void draw(Graphics g) { for (int i = 0; i < buttons.size(); i++) { buttons.get(i).draw(g); } } public void mouseClicked(Point p) { for (int i = 0; i < buttons.size(); i++) { buttons.get(i).mouseClicked(p); } } public boolean mouseMoved(Point p) { boolean overButton = false; for (int i = 0; i < buttons.size(); i++) { if (buttons.get(i).mouseMoved(p)) { overButton = true; } } if (!overButton) { handler.getPanel().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } return overButton; } }
package dsl.socialparser; import java.io.File; import java.io.FileInputStream; import dsl.socialparser.parser.CrawledPostParser; import dsl.socialparser.types.CrawledComment; import dsl.socialparser.types.CrawledPost; public class ParserTest { final static String EC_COMMENTS="{\"ec_comments\":"; public static void main(String args[]) throws Exception { File f = new File("/home/cclien/SocialParser/input/1512216135_00000848_2011-02-11T03_135544726479188_201165019899154.json"); FileInputStream fs = new FileInputStream(f); int b; StringBuilder sb=new StringBuilder(); while( (b=fs.read()) != -1) { sb.append((char)b); } String json = sb.toString(); CrawledPostParser p = new CrawledPostParser(); CrawledPost post = p.parse(json); System.out.println(post.getPost().getMessage()); System.out.println("Likes:"+post.getLikes().size()); System.out.println("Comments:"+post.getComments().size()); for(CrawledComment c:post.getComments()) { System.out.println(c.getComment().getMessage()); System.out.println(" Likes:"+c.getLikes().size()); } } }
package com.nematjon.edd_client_season_two; import android.Manifest; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.os.Handler; import android.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.nematjon.edd_client_season_two.receivers.EMAAlarmRcvr; import com.nematjon.edd_client_season_two.services.MainService; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import java.util.Objects; import inha.nsl.easytrack.ETServiceGrpc; import inha.nsl.easytrack.EtService; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; import static com.nematjon.edd_client_season_two.EMAActivity.EMA_NOTIF_HOURS; public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); //region UI variables private Button btnEMA; private TextView tvServiceStatus; private TextView tvInternetStatus; public TextView tvFileCount; public TextView tvDayNum; public TextView tvEmaNum; public TextView tvHBPhone; public TextView tvDataLoadedPhone; private RelativeLayout loadingPanel; private TextView ema_tv_1; private TextView ema_tv_2; private TextView ema_tv_3; private TextView ema_tv_4; private TextView tvRewards; //endregion private Intent customSensorsService; private SharedPreferences loginPrefs; SharedPreferences configPrefs; private AlertDialog dialog; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setActionBar((Toolbar) findViewById(R.id.my_toolbar)); if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { // only for gingerbread and newer versions Tools.PERMISSIONS = new String[]{ Manifest.permission.ACTIVITY_RECOGNITION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.PROCESS_OUTGOING_CALLS, Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }; } init(); final SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh); pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { initUI(); updateUI(); Tools.sendHeartbeat(getApplicationContext()); pullToRefresh.setRefreshing(false); } }); } public void init() { //region Init UI variables btnEMA = findViewById(R.id.btn_late_ema); tvServiceStatus = findViewById(R.id.tvStatus); tvInternetStatus = findViewById(R.id.connectivityStatus); tvFileCount = findViewById(R.id.filesCountTextView); loadingPanel = findViewById(R.id.loadingPanel); tvDayNum = findViewById(R.id.txt_day_num); tvEmaNum = findViewById(R.id.ema_responses_phone); tvHBPhone = findViewById(R.id.heartbeat_phone); tvDataLoadedPhone = findViewById(R.id.data_loaded_phone); ema_tv_1 = findViewById(R.id.ema_tv_1); ema_tv_2 = findViewById(R.id.ema_tv_2); ema_tv_3 = findViewById(R.id.ema_tv_3); ema_tv_4 = findViewById(R.id.ema_tv_4); tvRewards = findViewById(R.id.reward_points); //endregion DbMgr.init(getApplicationContext()); AppUseDb.init(getApplicationContext()); loginPrefs = getSharedPreferences("UserLogin", MODE_PRIVATE); configPrefs = getSharedPreferences("Configurations", Context.MODE_PRIVATE); setAlarams(); } @Override protected void onResume() { super.onResume(); if (!Tools.hasPermissions(this, Tools.PERMISSIONS)) { dialog = Tools.requestPermissions(MainActivity.this); } Tools.sendHeartbeat(getApplicationContext()); customSensorsService = new Intent(this, MainService.class); if (Tools.isNetworkAvailable()) { loadCampaign(); } else if (configPrefs.getBoolean("campaignLoaded", false)) { try { setUpCampaignConfigurations( configPrefs.getString("name", null), configPrefs.getString("notes", null), configPrefs.getString("creatorEmail", null), Objects.requireNonNull(configPrefs.getString("configJson", null)), configPrefs.getLong("startTimestamp", -1), configPrefs.getLong("endTimestamp", -1), configPrefs.getInt("participantCount", -1) ); restartService(null); } catch (JSONException e) { e.printStackTrace(); finish(); return; } } else { Toast.makeText(this, "Please connect to the Internet for the first launch!", Toast.LENGTH_SHORT).show(); finish(); return; } initUI(); updateUI(); } public void initUI() { tvServiceStatus.setTextColor(ContextCompat.getColor(this, R.color.red)); tvServiceStatus.setText(getString(R.string.service_stopped)); tvInternetStatus.setTextColor(ContextCompat.getColor(this, R.color.red)); tvInternetStatus.setText(getString(R.string.internet_off)); tvDayNum.setText("Duration:"); btnEMA.setVisibility(View.GONE); tvHBPhone.setText("Last active:"); tvEmaNum.setText("EMA responses:"); tvDataLoadedPhone.setText("Data loaded:"); ema_tv_1.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.unchecked_box, 0, 0); ema_tv_2.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.unchecked_box, 0, 0); ema_tv_3.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.unchecked_box, 0, 0); ema_tv_4.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.unchecked_box, 0, 0); tvRewards.setText(getString(R.string.earned_points, 0)); } public void updateUI() { int ema_order = Tools.getEMAOrderFromRangeAfterEMA(Calendar.getInstance()); if (ema_order == 0) { btnEMA.setVisibility(View.GONE); } else { boolean ema_btn_make_visible = loginPrefs.getBoolean("ema_btn_make_visible", true); if (!ema_btn_make_visible) { btnEMA.setVisibility(View.GONE); } else { btnEMA.setVisibility(View.VISIBLE); } } if (Tools.isNetworkAvailable()) { tvInternetStatus.setTextColor(ContextCompat.getColor(this, R.color.colorAccent)); tvInternetStatus.setText(getString(R.string.internet_on)); setMainStats(); setEMAAndRewardsStats(); } (new Handler()).postDelayed(new Runnable() { @Override public void run() { tvServiceStatus.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.colorAccent)); tvServiceStatus.setText(getString(R.string.service_runnig)); } }, 500); } public void setMainStats() { new Thread(new Runnable() { @Override public void run() { ManagedChannel channel = ManagedChannelBuilder.forAddress(getString(R.string.grpc_host), Integer.parseInt(getString(R.string.grpc_port))).usePlaintext().build(); ETServiceGrpc.ETServiceBlockingStub stub = ETServiceGrpc.newBlockingStub(channel); // region Retrieve main stats EtService.RetrieveParticipantStatisticsRequestMessage retrieveParticipantStatisticsRequestMessage = EtService.RetrieveParticipantStatisticsRequestMessage.newBuilder() .setUserId(loginPrefs.getInt(AuthActivity.user_id, -1)) .setEmail(loginPrefs.getString(AuthActivity.usrEmail, null)) .setTargetEmail(loginPrefs.getString(AuthActivity.usrEmail, null)) .setTargetCampaignId(Integer.parseInt(getString(R.string.campaign_id))) .build(); try { EtService.RetrieveParticipantStatisticsResponseMessage responseMessage = stub.retrieveParticipantStatistics(retrieveParticipantStatisticsRequestMessage); if (responseMessage.getDoneSuccessfully()) { final long join_timestamp = responseMessage.getCampaignJoinTimestamp(); final long hb_phone = responseMessage.getLastHeartbeatTimestamp(); final int samples_amount = responseMessage.getAmountOfSubmittedDataSamples(); runOnUiThread(new Runnable() { @Override public void run() { long nowTime = System.currentTimeMillis(); float joinTimeDif = nowTime - join_timestamp; int dayNum = (int) Math.ceil(joinTimeDif / 1000 / 3600 / 24); // in days float hbTimeDif = nowTime - hb_phone; int heart_beat = (int) Math.ceil(hbTimeDif / 1000 / 60); // in minutes if (heart_beat > 30) tvHBPhone.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.red)); else tvHBPhone.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.colorAccent)); tvDayNum.setText(getString(R.string.day_num, dayNum)); tvDataLoadedPhone.setText(getString(R.string.data_loaded, String.valueOf(samples_amount))); String last_active_text = hb_phone == 0 ? "just now" : Tools.formatMinutes(heart_beat) + " ago"; tvHBPhone.setText(getString(R.string.last_active, last_active_text)); } }); } } catch (StatusRuntimeException e) { Log.e("Tools", "DataCollectorService.setUpHeartbeatSubmissionThread() exception: " + e.getMessage()); e.printStackTrace(); } finally { channel.shutdown(); } //endregion } }).start(); } public void setEMAAndRewardsStats() { new Thread(new Runnable() { @Override public void run() { ManagedChannel channel = ManagedChannelBuilder.forAddress(getString(R.string.grpc_host), Integer.parseInt(getString(R.string.grpc_port))).usePlaintext().build(); ETServiceGrpc.ETServiceBlockingStub stub = ETServiceGrpc.newBlockingStub(channel); Calendar tillCal = Calendar.getInstance(); tillCal.set(Calendar.HOUR_OF_DAY, 23); tillCal.set(Calendar.MINUTE, 59); tillCal.set(Calendar.SECOND, 59); EtService.RetrieveFilteredDataRecordsRequestMessage retrieveFilteredEMARecordsRequestMessage = EtService.RetrieveFilteredDataRecordsRequestMessage.newBuilder() .setUserId(loginPrefs.getInt(AuthActivity.user_id, -1)) .setEmail(loginPrefs.getString(AuthActivity.usrEmail, null)) .setTargetEmail(loginPrefs.getString(AuthActivity.usrEmail, null)) .setTargetCampaignId(Integer.parseInt(getString(R.string.campaign_id))) .setTargetDataSourceId(configPrefs.getInt("SURVEY_EMA", -1)) .setFromTimestamp(0) .setTillTimestamp(tillCal.getTimeInMillis()) .build(); try { final EtService.RetrieveFilteredDataRecordsResponseMessage responseMessage = stub.retrieveFilteredDataRecords(retrieveFilteredEMARecordsRequestMessage); if (responseMessage.getDoneSuccessfully()) { runOnUiThread(new Runnable() { @Override public void run() { tvRewards.setText(""); ema_tv_1.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.unchecked_box, 0, 0); ema_tv_2.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.unchecked_box, 0, 0); ema_tv_3.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.unchecked_box, 0, 0); ema_tv_4.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.unchecked_box, 0, 0); if (responseMessage.getValueList() != null) { Calendar fromCal = Calendar.getInstance(); fromCal.set(Calendar.HOUR_OF_DAY, 0); fromCal.set(Calendar.MINUTE, 0); fromCal.set(Calendar.SECOND, 0); fromCal.set(Calendar.MILLISECOND, 0); Calendar tillCal = (Calendar) fromCal.clone(); tillCal.set(Calendar.HOUR_OF_DAY, 23); tillCal.set(Calendar.MINUTE, 59); tillCal.set(Calendar.SECOND, 59); //check for duplicates and get only unique ones List<String> uniqueValues = new ArrayList<>(); for (String item : responseMessage.getValueList()) if (!uniqueValues.contains(item)) uniqueValues.add(item); int rewardPoints = uniqueValues.size() * 250; tvRewards.setText(getString(R.string.earned_points, rewardPoints)); int ema_answered_count = 0; for (String val : uniqueValues) { if (Tools.inRange(Long.parseLong(val.split(Tools.DATA_SOURCE_SEPARATOR)[0]), fromCal.getTimeInMillis(), tillCal.getTimeInMillis())) { ema_answered_count++; switch (Integer.parseInt(val.split(Tools.DATA_SOURCE_SEPARATOR)[1])) { case 1: ema_tv_1.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.checked_box, 0, 0); break; case 2: ema_tv_2.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.checked_box, 0, 0); break; case 3: ema_tv_3.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.checked_box, 0, 0); break; case 4: ema_tv_4.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.checked_box, 0, 0); break; default: break; } } } tvEmaNum.setText(getString(R.string.ema_responses_rate, ema_answered_count)); } } }); } } catch (StatusRuntimeException e) { Log.e("Tools", "DataCollectorService.setUpHeartbeatSubmissionThread() exception: " + e.getMessage()); e.printStackTrace(); } finally { channel.shutdown(); } } }).start(); } public void lateEMAClick(View view) { int ema_order = Tools.getEMAOrderFromRangeAfterEMA(Calendar.getInstance()); if (ema_order != 0) { Intent intent = new Intent(this, EMAActivity.class); intent.putExtra("ema_order", ema_order); startActivity(intent); } } public void restartService(MenuItem item) { customSensorsService = new Intent(this, MainService.class); if (item != null) { //when the function is called by clicking the button stopService(customSensorsService); if (!Tools.hasPermissions(this, Tools.PERMISSIONS)) { runOnUiThread(new Runnable() { @Override public void run() { dialog = Tools.requestPermissions(MainActivity.this); } }); } else { Log.e(TAG, "restartServiceClick: 3"); if (configPrefs.getLong("startTimestamp", 0) <= System.currentTimeMillis()) { Log.e(TAG, "RESTART SERVICE"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(customSensorsService); } else { startService(customSensorsService); } } } } else { //when the function is called without clicking the button if (!Tools.isMainServiceRunning(getApplicationContext())) { customSensorsService = new Intent(this, MainService.class); stopService(customSensorsService); if (!Tools.hasPermissions(this, Tools.PERMISSIONS)) { runOnUiThread(new Runnable() { @Override public void run() { dialog = Tools.requestPermissions(MainActivity.this); } }); } else { if (configPrefs.getLong("startTimestamp", 0) <= System.currentTimeMillis()) { Log.e(TAG, "RESTART SERVICE"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(customSensorsService); } else { startService(customSensorsService); } } } } } } public void setLocationsClick(MenuItem item) { startActivity(new Intent(MainActivity.this, LocationSetActivity.class)); } public void setAlarams() { AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Intent intent1 = new Intent(MainActivity.this, EMAAlarmRcvr.class); intent1.putExtra("ema_order", 1); Intent intent2 = new Intent(MainActivity.this, EMAAlarmRcvr.class); intent2.putExtra("ema_order", 2); Intent intent3 = new Intent(MainActivity.this, EMAAlarmRcvr.class); intent3.putExtra("ema_order", 3); Intent intent4 = new Intent(MainActivity.this, EMAAlarmRcvr.class); intent4.putExtra("ema_order", 4); PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, 1, intent1, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent pendingIntent2 = PendingIntent.getBroadcast(MainActivity.this, 2, intent2, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent pendingIntent3 = PendingIntent.getBroadcast(MainActivity.this, 3, intent3, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent pendingIntent4 = PendingIntent.getBroadcast(MainActivity.this, 4, intent4, PendingIntent.FLAG_UPDATE_CURRENT); if (alarmManager == null) return; Calendar currentCal = Calendar.getInstance(); long currentTime = currentCal.getTimeInMillis(); Calendar firingCal1 = Calendar.getInstance(); firingCal1.set(Calendar.HOUR_OF_DAY, EMA_NOTIF_HOURS[0]); // at 10am firingCal1.set(Calendar.MINUTE, 0); // Particular minute firingCal1.set(Calendar.SECOND, 0); // particular second firingCal1.set(Calendar.MILLISECOND, 0); // particular second Calendar firingCal2 = Calendar.getInstance(); firingCal2.set(Calendar.HOUR_OF_DAY, EMA_NOTIF_HOURS[1]); // at 2pm firingCal2.set(Calendar.MINUTE, 0); // Particular minute firingCal2.set(Calendar.SECOND, 0); // particular second firingCal2.set(Calendar.MILLISECOND, 0); // particular second Calendar firingCal3 = Calendar.getInstance(); firingCal3.set(Calendar.HOUR_OF_DAY, EMA_NOTIF_HOURS[2]); // at 6pm firingCal3.set(Calendar.MINUTE, 0); // Particular minute firingCal3.set(Calendar.SECOND, 0); // particular second firingCal3.set(Calendar.MILLISECOND, 0); // particular second Calendar firingCal4 = Calendar.getInstance(); firingCal4.set(Calendar.HOUR_OF_DAY, EMA_NOTIF_HOURS[3]); // at 10pm firingCal4.set(Calendar.MINUTE, 0); // Particular minute firingCal4.set(Calendar.SECOND, 0); // particular second firingCal4.set(Calendar.MILLISECOND, 0); // particular second if (firingCal1.getTimeInMillis() > currentTime) alarmManager.setWindow(AlarmManager.RTC_WAKEUP, firingCal1.getTimeInMillis(), 30000, pendingIntent1); //set from today else if (firingCal2.getTimeInMillis() > currentTime) alarmManager.setWindow(AlarmManager.RTC_WAKEUP, firingCal2.getTimeInMillis(), 30000, pendingIntent2); //set from today else if (firingCal3.getTimeInMillis() > currentTime) alarmManager.setWindow(AlarmManager.RTC_WAKEUP, firingCal3.getTimeInMillis(), 30000, pendingIntent3); //set from today else if (firingCal4.getTimeInMillis() > currentTime) alarmManager.setWindow(AlarmManager.RTC_WAKEUP, firingCal4.getTimeInMillis(), 30000, pendingIntent4); //set from today else if (currentTime > firingCal4.getTimeInMillis()) { firingCal1.add(Calendar.DAY_OF_MONTH, 1); alarmManager.setWindow(AlarmManager.RTC_WAKEUP, firingCal1.getTimeInMillis(), 30000, pendingIntent1); //set from today } } public void logoutClick(MenuItem item) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setMessage(getString(R.string.log_out_confirmation)); alertDialog.setPositiveButton( getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Tools.perform_logout(getApplicationContext()); stopService(customSensorsService); finish(); } }); alertDialog.setNegativeButton( getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } private void loadCampaign() { new Thread(new Runnable() { @Override public void run() { ManagedChannel channel = ManagedChannelBuilder.forAddress(getString(R.string.grpc_host), Integer.parseInt(getString(R.string.grpc_port))).usePlaintext().build(); try { ETServiceGrpc.ETServiceBlockingStub stub = ETServiceGrpc.newBlockingStub(channel); EtService.RetrieveCampaignRequestMessage retrieveCampaignRequestMessage = EtService.RetrieveCampaignRequestMessage.newBuilder() .setUserId(loginPrefs.getInt(AuthActivity.user_id, -1)) .setEmail(loginPrefs.getString(AuthActivity.usrEmail, null)) .setCampaignId(Integer.parseInt(getString(R.string.campaign_id))) .build(); EtService.RetrieveCampaignResponseMessage retrieveCampaignResponseMessage = stub.retrieveCampaign(retrieveCampaignRequestMessage); if (retrieveCampaignResponseMessage.getDoneSuccessfully()) { setUpCampaignConfigurations( retrieveCampaignResponseMessage.getName(), retrieveCampaignResponseMessage.getNotes(), retrieveCampaignResponseMessage.getCreatorEmail(), retrieveCampaignResponseMessage.getConfigJson(), retrieveCampaignResponseMessage.getStartTimestamp(), retrieveCampaignResponseMessage.getEndTimestamp(), retrieveCampaignResponseMessage.getParticipantCount() ); SharedPreferences.Editor editor = configPrefs.edit(); editor.putString("name", retrieveCampaignResponseMessage.getName()); editor.putString("notes", retrieveCampaignResponseMessage.getNotes()); editor.putString("creatorEmail", retrieveCampaignResponseMessage.getCreatorEmail()); editor.putString("configJson", retrieveCampaignResponseMessage.getConfigJson()); editor.putLong("startTimestamp", retrieveCampaignResponseMessage.getStartTimestamp()); editor.putLong("endTimestamp", retrieveCampaignResponseMessage.getEndTimestamp()); editor.putInt("participantCount", retrieveCampaignResponseMessage.getParticipantCount()); editor.putBoolean("campaignLoaded", true); editor.apply(); restartService(null); } } catch (StatusRuntimeException | JSONException e) { e.printStackTrace(); } finally { channel.shutdown(); } } }).start(); } private void setUpCampaignConfigurations(String name, String notes, String creatorEmail, String configJson, long startTimestamp, long endTimestamp, int participantCount) throws JSONException { String oldConfigJson = configPrefs.getString(String.format(Locale.getDefault(), "%s_configJson", name), null); if (configJson.equals(oldConfigJson)) return; SharedPreferences.Editor editor = configPrefs.edit(); editor.putString(String.format(Locale.getDefault(), "%s_configJson", name), configJson); JSONArray dataSourceConfigurations = new JSONArray(configJson); StringBuilder sb = new StringBuilder(); for (int n = 0; n < dataSourceConfigurations.length(); n++) { JSONObject dataSourceConfig = dataSourceConfigurations.getJSONObject(n); String _name = dataSourceConfig.getString("name"); int _dataSourceId = dataSourceConfig.getInt("data_source_id"); editor.putInt(_name, _dataSourceId); String _json = dataSourceConfig.getString("config_json"); editor.putString(String.format(Locale.getDefault(), "config_json_%s", _name), _json); sb.append(_name).append(','); } if (sb.length() > 0) sb.replace(sb.length() - 1, sb.length(), ""); editor.putString("dataSourceNames", sb.toString()); editor.apply(); } @Override protected void onStop() { super.onStop(); loadingPanel.setVisibility(View.GONE); } @Override protected void onPause() { super.onPause(); if (dialog != null) { dialog.dismiss(); dialog = null; } } @Override protected void onDestroy() { super.onDestroy(); loadingPanel.setVisibility(View.GONE); if (dialog != null) { dialog.dismiss(); dialog = null; } } }
package controller.gerente; import controller.TelaPrincipalController; import entity.Funcionario; import entity.Login; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; public class TelaConsultarFuncionarioController implements Initializable { @FXML private AnchorPane telaConsultarFuncionario; @FXML private Button menuPrincipal; @FXML private Button sairBtn; @FXML private TextField telefoneTxt; @FXML private TextField nomeTxt; @FXML private TextField enderecoTxt; private TelaPrincipalController telaPrincipalController; @FXML private ComboBox<String> boxCPF; @FXML private TextField usuarioTxt; @FXML private TextField senhaTxt; @FXML private Button salvarBtn; Funcionario funcionario; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { preencherBoxCPFFuncionario(); } @FXML private void irMenu(ActionEvent event) { } @FXML private void sair(ActionEvent event) { telaPrincipalController.retornar(); } private void preencherBoxCPFFuncionario() { List<String> funcionarios = new ArrayList<>(); for (Object pessoa : Login.usuario.values()) { if (pessoa instanceof Funcionario) { funcionarios.add(((Funcionario) pessoa).getCPF()); } } ObservableList<String> opcoes = FXCollections.observableArrayList(funcionarios); boxCPF.setItems(opcoes); } public void setTelaPrincipalController(TelaPrincipalController telaPrincipalController) { this.telaPrincipalController = telaPrincipalController; } @FXML private void irSalvar() { if (funcionario != null) { try { String endereco = enderecoTxt.getText().trim(); String nome = nomeTxt.getText().trim(); int telefone = Integer.parseInt(telefoneTxt.getText().trim()); String senha = senhaTxt.getText().trim(); if (!nome.isEmpty()) { funcionario.setNome(nome); } if (!endereco.isEmpty()) { funcionario.setEndereco(endereco); } funcionario.setTelefone(telefone); if (!senha.isEmpty()) { funcionario.setSenha(senha); } Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("OK"); alert.setHeaderText(null); alert.setContentText("Informações alteradas com sucesso!"); alert.showAndWait(); } catch (Exception ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Erro"); alert.setHeaderText(null); alert.setContentText("Não foi possível alterar suas informações!\nCertifique as informações estejam corretas."); alert.showAndWait(); } } else { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Erro"); alert.setHeaderText(null); alert.setContentText("Erro"); alert.showAndWait(); } } @FXML private void irCPFFuncionario() { if (!boxCPF.getSelectionModel().isEmpty()) { String cpf = boxCPF.getSelectionModel().getSelectedItem().trim(); Funcionario funcionario = null; for (Object c : Login.usuario.values()) { if (c instanceof Funcionario) {//se for um cliente if (cpf.equals(((Funcionario) c).getCPF())) { //se o cpf é igual funcionario = (Funcionario) c; } } } if (funcionario != null) { atualizar(funcionario); } } } private void atualizar(Funcionario funcionario) { this.funcionario = funcionario; String nome = funcionario.getNome(); int telefone = funcionario.getTelefone(); String endereco = funcionario.getEndereco(); String usuario = funcionario.getLogin(); String senha = funcionario.getSenha(); if (endereco.isEmpty()) { endereco = "Nenhum endereço cadastrado."; } usuarioTxt.setText(usuario); senhaTxt.setText(senha); nomeTxt.setText(nome); enderecoTxt.setText(endereco); telefoneTxt.setText(Integer.toString(telefone)); } }
/* * * SWT-Praktikum TU Dresden 2015 * Gruppe 32 - Computech * * Stephan Fischer * Anna Gromykina * Kevin Horst * Philipp Oehme * */ package computech.model; import org.salespointframework.catalog.Catalog; /** * * Contains every all-in-one computer in the shop. * */ public interface ComputerCatalog extends Catalog <Article> { Iterable<Article> findByType(Article.ArticleType type); }
package com.lenovohit.mnis.base.manager; public interface ICommonRedisSequenceManager { /** * 根据键值取编码 * @param key * @return */ String get(String key); }
package exo_abstraites; public class Tigre extends Felin{ public Tigre(int poids, String couleur) { super(poids, couleur); // TODO Auto-generated constructor stub } @Override void crier() { System.out.println("Je feule"); } }
package com.programapprentice.app; import com.programapprentice.util.TreeNode; import java.util.Stack; /** * User: program-apprentice * Date: 10/7/15 * Time: 9:01 PM */ public class KthSmallestElementInABST_230 { public int kthSmallest(TreeNode root, int k) { Stack<TreeNode> stack = new Stack<TreeNode>(); int counter = 0; push(root, stack); while(!stack.isEmpty()) { TreeNode p = stack.pop(); counter++; if(counter == k) { return p.val; } push(p.right, stack); } return -1; } public void push(TreeNode root, Stack<TreeNode> stack) { TreeNode p = root; while(p != null) { stack.push(p); p = p.left; } } }
package mbd.student.gurukustudent.activity.teacher; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; import mbd.student.gurukustudent.R; import mbd.student.gurukustudent.activity.LoginActivity; import mbd.student.gurukustudent.model.APIErrorModel; import mbd.student.gurukustudent.model.student.Student; import mbd.student.gurukustudent.model.teacher.Teacher; import mbd.student.gurukustudent.model.transaction.Data; import mbd.student.gurukustudent.model.transaction.Transaction; import mbd.student.gurukustudent.services.RetrofitServices; import mbd.student.gurukustudent.utils.APIErrorUtils; import mbd.student.gurukustudent.utils.SharedPreferencesUtils; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class BookingTeacherActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.swipeRefreshLayout) SwipeRefreshLayout swipeRefreshLayout; @BindView(R.id.tvNama) TextView tvNama; @BindView(R.id.tvKeahlian) TextView tvKeahlian; @BindView(R.id.tvPrice) TextView tvPrice; @BindView(R.id.rgDuration) RadioGroup rgDuration; @BindView(R.id.rbOneHour) RadioButton rbOneHour; @BindView(R.id.rbTwoHour) RadioButton rbTwoHour; @BindView(R.id.rbThreeHour) RadioButton rbThreeHour; @BindView(R.id.tvDate) TextView tvDate; @BindView(R.id.tvTime) TextView tvTime; @BindView(R.id.tvLocation) TextView tvLocation; @BindView(R.id.etNote) EditText etNote; @BindView(R.id.tvNote) TextView tvNote; @BindView(R.id.lytNotConfirm) LinearLayout lytNotConfirm; @BindView(R.id.lytConfirmed) LinearLayout lytConfirmed; @BindView(R.id.lytPaymentSuccess) LinearLayout lytPaymentSuccess; @BindView(R.id.tvConfirm) TextView tvConfirm; @BindView(R.id.rgPaymentMethod) RadioGroup rgPaymentMethod; @BindView(R.id.rbWallet) RadioButton rbWallet; @BindView(R.id.rbCash) RadioButton rbCash; @BindView(R.id.lytWallet) LinearLayout lytWallet; @BindView(R.id.lytCash) LinearLayout lytCash; @BindView(R.id.tvPaymentSuccess) TextView tvPaymentSuccess; @BindView(R.id.tvNoTlp) TextView tvNoTlp; @BindView(R.id.tvNoWa) TextView tvNoWA; @BindView(R.id.tvLineAccount) TextView tvLineAccount; /*@BindView(R.id.tvSaldo) TextView tvSaldo;*/ @BindView(R.id.btnBookNow) Button btnBookNow; @BindView(R.id.btnPay) Button btnPay; @BindView(R.id.btnFinish) Button btnFinish; private Intent dataIntent; private ProgressDialog bookLoading; private SharedPreferencesUtils sharedPreferencesUtils; private int studentID, teacherID; private int duration = 0; private int bookID = 0; private int status, statusTrx; private int transactionID; private int total_price; private String noTlp; private String noWA; private String lineAccount; private String bookData, date, time, location, note; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_booking_teacher); ButterKnife.bind(this); bookLoading = new ProgressDialog(this); bookLoading.setMessage("Loading . . ."); bookLoading.setCancelable(false); swipeRefreshLayout.setOnRefreshListener(this); setSupportActionBar(toolbar); getSupportActionBar().setTitle(R.string.activity_title_booking_teacher); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); sharedPreferencesUtils = new SharedPreferencesUtils(this, "DataMember"); if (sharedPreferencesUtils.checkIfDataExists("profile")) { Student student = sharedPreferencesUtils.getObjectData("profile", Student.class); studentID = student.getStudentID(); } dataIntent = getIntent(); Locale localeID = new Locale("in", "ID"); final NumberFormat numberFormatCurrency = NumberFormat.getCurrencyInstance(localeID); numberFormatCurrency.setMaximumFractionDigits(0); String from = dataIntent.getStringExtra("from"); Data data; Teacher teacher = null; Transaction transaction; if (from.equals("DetailTeacher")) { bookData = dataIntent.getStringExtra("bookData"); teacher = new Gson().fromJson(dataIntent.getStringExtra("dataTeacher"), Teacher.class); total_price = teacher.getPrice(); noTlp = teacher.getNoTlp(); noWA = teacher.getNoWA(); lineAccount = teacher.getLineAccount(); try { JSONObject jsonBookData = new JSONObject(bookData); duration = jsonBookData.getInt("duration"); date = jsonBookData.getString("date"); time = jsonBookData.getString("time"); location = jsonBookData.getString("location"); } catch (JSONException e) { e.printStackTrace(); } swipeRefreshLayout.setEnabled(false); switch (duration) { case 1 : rbOneHour.setChecked(true); break; case 2 : rbTwoHour.setChecked(true); break; case 3 : rbThreeHour.setChecked(true); } total_price = total_price * duration; rbOneHour.setEnabled(false); rbTwoHour.setEnabled(false); rbThreeHour.setEnabled(false); } else if (from.equals("Trx")) { data = new Gson().fromJson(dataIntent.getStringExtra("bookData"), Data.class); teacher = data.getTeacher(); transaction = data.getTransaction(); noTlp = teacher.getNoTlp(); noWA = teacher.getNoWA(); lineAccount = teacher.getLineAccount(); bookID = data.getBookID(); status = data.getStatus(); duration = data.getDuration(); location = data.getLocation(); date = data.getDate(); time = data.getTime(); note = data.getNote(); transactionID = transaction.getTransactionID(); statusTrx = transaction.getStatus(); total_price = transaction.getTotalPrice(); switch (duration) { case 1 : rbOneHour.setChecked(true); break; case 2 : rbTwoHour.setChecked(true); break; case 3 : rbThreeHour.setChecked(true); } lytNotConfirm.setVisibility(View.GONE); btnBookNow.setVisibility(View.GONE); etNote.setVisibility(View.GONE); tvNote.setVisibility(View.VISIBLE); tvNote.setText(note); if (statusTrx == 1) { btnPay.setVisibility(View.GONE); lytConfirmed.setVisibility(View.GONE); lytPaymentSuccess.setVisibility(View.VISIBLE); btnFinish.setVisibility(View.VISIBLE); } else { btnPay.setVisibility(View.VISIBLE); lytConfirmed.setVisibility(View.VISIBLE); } rbOneHour.setEnabled(false); rbTwoHour.setEnabled(false); rbThreeHour.setEnabled(false); } teacherID = teacher.getTeacherID(); String nama = teacher.getFirstName() + " " + teacher.getLastName(); String keahlian = teacher.getCategories().get(0).getCategoryName(); tvNama.setText(nama); tvKeahlian.setText(keahlian); tvDate.setText(date); tvTime.setText(time); tvLocation.setText(location); tvPrice.setText(numberFormatCurrency.format(total_price)); tvNoTlp.setText(noTlp); tvNoWA.setText(noWA); tvLineAccount.setText(lineAccount); rgDuration.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int id) { if (id == R.id.rbOneHour) { tvPrice.setText(numberFormatCurrency.format(total_price)); } else if (id == R.id.rbTwoHour) { tvPrice.setText(numberFormatCurrency.format(total_price * 2)); } else if (id == R.id.rbThreeHour) { tvPrice.setText(numberFormatCurrency.format(total_price * 3)); } } }); if (rbWallet.isChecked()) { btnPay.setEnabled(false); } else { btnPay.setEnabled(true); } rgPaymentMethod.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int id) { if (id == R.id.rbWallet) { lytWallet.setVisibility(View.VISIBLE); lytCash.setVisibility(View.GONE); btnPay.setEnabled(false); } else if (id == R.id.rbCash) { lytWallet.setVisibility(View.GONE); lytCash.setVisibility(View.VISIBLE); btnPay.setEnabled(true); } } }); //tvSaldo.setText(numberFormatCurrency.format(50000)); btnBookNow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (rbOneHour.isChecked()) { duration = 1; } else if (rbTwoHour.isChecked()) { duration = 2; } else if (rbThreeHour.isChecked()) { duration = 3; } note = etNote.getText().toString(); if (TextUtils.isEmpty(note)) { note = "-"; } try { JSONObject param = new JSONObject(); param.put("teacherID", teacherID); param.put("studentID", studentID); param.put("duration", duration); param.put("location", location); param.put("date", date); param.put("time", time); param.put("note", note); bookTeacher(param); } catch (JSONException e) { e.printStackTrace(); } } }); btnPay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final JSONObject param = new JSONObject(); try { param.put("transactionID", transactionID); param.put("status", 1); param.put("paymentMethod", "CASH"); paymentCash(param); } catch (JSONException e) { e.printStackTrace(); } } }); btnFinish.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final JSONObject param = new JSONObject(); try { param.put("bookID", bookID); param.put("studentID", studentID); param.put("teacherID", teacherID); param.put("finish", 1); } catch (JSONException e) { e.printStackTrace(); } new AlertDialog.Builder(BookingTeacherActivity.this) .setTitle("Pesan") .setMessage("Apakah anda yakin akan menyelesaikan pembelajaran ini? Jika " + "anda sudah melaksanakan kegiatan pembelajaran silahkan klik tombol " + "\"Ya\", jika belum silahkan klik tombol \"Batal\".") .setPositiveButton("Ya", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(param); } }) .setNegativeButton("Batal", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }) .show(); } }); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; } return super.onOptionsItemSelected(item); } private void bookTeacher(JSONObject param) { bookLoading.show(); Call<String> call = RetrofitServices.sendStudentRequest().APIBookTeacher(param); if (call != null) { call.enqueue(new Callback<String>() { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { bookLoading.dismiss(); if (response.isSuccessful()) { try { JSONObject result = new JSONObject(response.body()); bookID = result.getInt("bookID"); tvConfirm.setText(result.getString("message")); rbOneHour.setEnabled(false); rbTwoHour.setEnabled(false); rbThreeHour.setEnabled(false); etNote.setVisibility(View.GONE); tvNote.setVisibility(View.VISIBLE); tvNote.setText(note); btnBookNow.setVisibility(View.GONE); btnPay.setVisibility(View.VISIBLE); btnPay.setEnabled(false); swipeRefreshLayout.setEnabled(true); } catch (Exception e) { e.printStackTrace(); } } } @Override public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { bookLoading.dismiss(); Log.e("error", t.getMessage()); } }); } } private void getBookingStatus(int bookID) { swipeRefreshLayout.setRefreshing(true); Call<String> call = RetrofitServices.sendStudentRequest().APIGetBookingStatus(bookID); if (call != null) { call.enqueue(new Callback<String>() { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { swipeRefreshLayout.setRefreshing(false); if (response.isSuccessful()) { try { JSONObject result = new JSONObject(response.body()); int status = result.getInt("statusBook"); int statusTrx = result.getInt("statusTransaction"); transactionID = result.getInt("transactionID"); if (status == 1) { lytConfirmed.setVisibility(View.VISIBLE); lytNotConfirm.setVisibility(View.GONE); if (rbWallet.isChecked()) { btnPay.setEnabled(false); } else { btnPay.setEnabled(true); } if (statusTrx == 1) { lytPaymentSuccess.setVisibility(View.VISIBLE); lytConfirmed.setVisibility(View.GONE); btnPay.setVisibility(View.GONE); } } } catch (JSONException e) { e.printStackTrace(); } } else { APIErrorModel error = APIErrorUtils.parserError(response); String message = error.getMessage(); new AlertDialog.Builder(BookingTeacherActivity.this) .setTitle("Pesan") .setMessage(message) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }) .show(); } } @Override public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { swipeRefreshLayout.setRefreshing(false); Log.e("error", t.getMessage()); } }); } } private void paymentCash(JSONObject param) { bookLoading.show(); Call<String> call = RetrofitServices.sendStudentRequest().APIPaymentCash(param); if (call != null) { call.enqueue(new Callback<String>() { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { bookLoading.dismiss(); if (response.isSuccessful()) { try { JSONObject result = new JSONObject(response.body()); String message = result.getString("message"); tvPaymentSuccess.setText(message); lytPaymentSuccess.setVisibility(View.VISIBLE); lytConfirmed.setVisibility(View.GONE); btnPay.setVisibility(View.GONE); btnFinish.setVisibility(View.VISIBLE); } catch (JSONException e) { e.printStackTrace(); } } } @Override public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { bookLoading.dismiss(); Log.e("error", t.getMessage()); } }); } } private void finish(JSONObject param) { bookLoading.show(); Call<String> call = RetrofitServices.sendStudentRequest().APIFinish(param); if (call != null) { call.enqueue(new Callback<String>() { @Override public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { bookLoading.dismiss(); btnFinish.setVisibility(View.GONE); if (response.isSuccessful()) { try { JSONObject result = new JSONObject(response.body()); String message = result.getString("message"); Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } } else { Toast.makeText(getApplicationContext(), "Terjadi Kesalahan", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { bookLoading.dismiss(); Log.e("error", t.getMessage()); } }); } } @Override public void onRefresh() { if (bookID != 0) { getBookingStatus(bookID); } } }
package com.data.main.dataSource; import java.util.List; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.alibaba.druid.pool.DruidDataSource; @Configuration @EnableTransactionManagement @ConfigurationProperties(prefix = "classpath:/config/data_source_application.properties") public class dataConfiguration implements EnvironmentAware { private RelaxedPropertyResolver propertyResolver; private static Logger log = LoggerFactory.getLogger(dataConfiguration.class); @Override public void setEnvironment(Environment environment) { this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource."); } /*** * 主数据源 加上@Primary 标签就代表该数据源是默认数据源。 */ @Bean(name = "MasterDataSource", destroyMethod = "close", initMethod = "init") @Primary public DataSource MasterDataSource() { log.info("获取数据源。。。。。。。。"); DruidDataSource druidDataSource = new DruidDataSource(); log.info(propertyResolver.getProperty("driverClassName")); log.info(propertyResolver.getProperty("url")); log.info(propertyResolver.getProperty("username")); log.info(propertyResolver.getProperty("password")); druidDataSource.setDriverClassName(propertyResolver.getProperty("driverClassName")); druidDataSource.setUrl(propertyResolver.getProperty("url")); druidDataSource.setUsername(propertyResolver.getProperty("username")); druidDataSource.setPassword(propertyResolver.getProperty("password")); System.out.println("123"); return druidDataSource; } /*** * 数据源一 * * @return @Bean(name = "", destroyMethod = "close", initMethod = "init") public DataSource DataSource_one() { return null; } */ /*** * 数据源二 * * @return @Bean(name = "", destroyMethod = "close", initMethod = "init") public DataSource DataSource_two() { return null; } */ /*** * 添加数据源到list集合中。 * * @return */ public List<DataSource> listDataSource() { return null; } }
/* * Copyright 2011 Upic * * This file is part of MailService. * * MailService is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * MailService 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 Lesser General Public License along with MailService. If not, see <http://www.gnu.org/licenses/>. */ package com.progress.codeshare.esbservice.mail; import java.util.Iterator; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import com.sonicsw.xq.XQConstants; import com.sonicsw.xq.XQEnvelope; import com.sonicsw.xq.XQHeader; import com.sonicsw.xq.XQInitContext; import com.sonicsw.xq.XQMessage; import com.sonicsw.xq.XQParameters; import com.sonicsw.xq.XQPart; import com.sonicsw.xq.XQServiceContext; import com.sonicsw.xq.XQServiceEx; import com.sonicsw.xq.XQServiceException; public final class MailService implements XQServiceEx { private static final String PARAM_BCC = "bcc"; private static final String PARAM_CC = "cc"; private static final String PARAM_FROM = "from"; private static final String PARAM_HOST = "host"; private static final String PARAM_PORT = "port"; private static final String PARAM_REPLY_TO = "replyTo"; private static final String PARAM_SUBJECT = "subject"; private static final String PARAM_TO = "to"; private static final Pattern PATTERN_HEADER = Pattern .compile("com\\.progress\\.codeshare\\.esbservice\\.mail\\.(.*)"); private static final String PROP_HOST = "mail.host"; private static final String PROP_PORT = "mail.port"; private final Properties CONF = new Properties(); public void destroy() { } public void init(final XQInitContext ctx) { final XQParameters params = ctx.getParameters(); CONF.put(PROP_HOST, params.getParameter(PARAM_HOST, XQConstants.PARAM_STRING)); final String port = params.getParameter(PARAM_PORT, XQConstants.PARAM_STRING); if (port != null) CONF.put(PROP_PORT, port); } public void service(final XQServiceContext ctx) throws XQServiceException { try { final Session session = Session.getDefaultInstance(CONF); final XQParameters params = ctx.getParameters(); final String bcc = params.getParameter(PARAM_BCC, XQConstants.PARAM_STRING); final String cc = params.getParameter(PARAM_CC, XQConstants.PARAM_STRING); final String from = params.getParameter(PARAM_FROM, XQConstants.PARAM_STRING); final String replyTo = params.getParameter(PARAM_REPLY_TO, XQConstants.PARAM_STRING); final String subject = params.getParameter(PARAM_SUBJECT, XQConstants.PARAM_STRING); final String to = params.getParameter(PARAM_TO, XQConstants.PARAM_STRING); while (ctx.hasNextIncoming()) { final XQEnvelope env = ctx.getNextIncoming(); final XQMessage msg = env.getMessage(); /* Copy all headers of the message to the mail message */ final Iterator headerIterator = msg.getHeaderNames(); final Message mail = new MimeMessage(session); while (headerIterator.hasNext()) { final String name = (String) headerIterator.next(); final Matcher matcher = PATTERN_HEADER.matcher(name); if (matcher.find()) mail.setHeader(matcher.group(1), (String) msg .getHeaderValue(matcher.group())); } /* Set/Override the bcc: header */ if (bcc != null) mail.setRecipient(RecipientType.BCC, new InternetAddress( bcc)); /* Set/Override the cc: header */ if (cc != null) mail .setRecipient(RecipientType.CC, new InternetAddress(cc)); /* Set/Override the From: header */ if (from != null) mail.setFrom(new InternetAddress(from)); /* Set/Override the Reply-To: header */ if (replyTo != null) mail .setReplyTo(new Address[] { new InternetAddress( replyTo) }); /* Set/Override the Subject: header */ if (subject != null) mail.setSubject(subject); /* Set/Override the To: header */ if (to != null) mail .setRecipient(RecipientType.TO, new InternetAddress(to)); final Multipart multipart = new MimeMultipart(); /* Map all parts of the message to the mail message */ for (int i = 0; i < msg.getPartCount(); i++) { final XQPart msgPart = msg.getPart(i); final XQHeader header = msgPart.getHeader(); final Iterator keyIterator = header.getKeys(); final BodyPart bodyPart = new MimeBodyPart(); while (keyIterator.hasNext()) { final String key = (String) keyIterator.next(); final Matcher matcher = PATTERN_HEADER.matcher(key); if (matcher.find()) bodyPart.addHeader(matcher.group(1), bodyPart .getHeader(matcher.group())[0]); } bodyPart.setContent(msgPart.getContent(), msgPart .getContentType()); multipart.addBodyPart(bodyPart); } mail.setContent(multipart); Transport.send(mail); final Iterator addressIterator = env.getAddresses(); if (addressIterator.hasNext()) ctx.addOutgoing(env); } } catch (final Exception e) { throw new XQServiceException(e); } } public void start() { } public void stop() { } }
package com.dromedicas.dao; // Generated 28/03/2017 05:43:09 PM by Hibernate Tools 5.1.2.Final import java.util.List; import javax.naming.InitialContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Example; import com.dromedicas.dto.Sucursales; /** * Home object for domain model class Sucursales. * @see com.dromedicas.dto.Sucursales * @author Hibernate Tools */ public class SucursalesHome extends BaseHibernateDAO { private static final Log log = LogFactory.getLog(SucursalesHome.class); private final Session sessionFactory = super.getSession(); protected Session getSessionFactory() { try { return this.sessionFactory; } catch (Exception e) { log.error("Could not locate SessionFactory in JNDI", e); throw new IllegalStateException( "Could not locate SessionFactory in JNDI"); } } public void persist(Sucursales transientInstance) { log.debug("persisting Sucursales instance"); try { this.getSessionFactory().persist(transientInstance); log.debug("persist successful"); } catch (RuntimeException re) { log.error("persist failed", re); throw re; } } public void attachDirty(Sucursales instance) { log.debug("attaching dirty Sucursales instance"); try { this.getSessionFactory().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Sucursales instance) { log.debug("attaching clean Sucursales instance"); try { this.getSessionFactory().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void delete(Sucursales persistentInstance) { log.debug("deleting Sucursales instance"); try { this.getSessionFactory().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Sucursales merge(Sucursales detachedInstance) { log.debug("merging Sucursales instance"); try { Sucursales result = (Sucursales) this.getSessionFactory().merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public Sucursales findById(java.lang.Integer id) { log.debug("getting Sucursales instance with id: " + id); try { Sucursales instance = (Sucursales) this.getSessionFactory().get("com.dromedicas.dto.Sucursales", id); if (instance == null) { log.debug("get successful, no instance found"); } else { log.debug("get successful, instance found"); } return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Sucursales instance) { log.debug("finding Sucursales instance by example"); try { List results = this.getSessionFactory().createCriteria("com.dromedicas.dto.Sucursales") .add(Example.create(instance)).list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findAll() { log.debug("finding all Sucursales instances"); try { String queryString = "from Sucursales s where s.esdrogueria = 'CHECKED' and " + "s.activa = 'CHECKED' order by s.codigo asc"; Query queryObject = this.sessionFactory.createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } }
/* Copyright 2015 Sébastien Vrillaud 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.kochka.android.weightlogger.fragments; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceGroup; import android.text.InputType; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import org.kochka.android.weightlogger.R; import org.kochka.android.weightlogger.data.Database; import org.kochka.android.weightlogger.data.Measurement; import org.kochka.android.weightlogger.tools.Export; import org.kochka.android.weightlogger.tools.StorageNotMountedException; import java.io.File; import java.io.FilenameFilter; import java.util.Calendar; import java.util.Locale; public class PreferencesFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener, SharedPreferences.OnSharedPreferenceChangeListener { private Callback mCallback; @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof Callback) { mCallback = (Callback) activity; } else { throw new IllegalStateException("URLCallback interface not implement"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); this.initSummaries(this.getPreferenceScreen()); // Limit age preference to numbers ((EditTextPreference) findPreference("age")).getEditText().setInputType(InputType.TYPE_CLASS_NUMBER); findPreference("optional_fields").setOnPreferenceClickListener(this); findPreference("db_backup").setOnPreferenceClickListener(this); findPreference("db_restore").setOnPreferenceClickListener(this); findPreference("db_purge").setOnPreferenceClickListener(this); findPreference("db_loadtest").setOnPreferenceClickListener(this); findPreference("about").setOnPreferenceClickListener(this); } @Override public void onResume() { super.onResume(); getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); super.onPause(); } @Override public boolean onPreferenceClick(Preference preference) { if (preference.getKey().equals("optional_fields")) mCallback.onNestedPreferenceSelected(NestedPreferenceFragment.NESTED_SCREEN_FIELDS); else if (preference.getKey().equals("db_backup")) dbBackup(); else if (preference.getKey().equals("db_restore")) dbRestore(); else if (preference.getKey().equals("db_purge")) dbPurge(); else if (preference.getKey().equals("db_loadtest")) dbLoadTest(); else if (preference.getKey().equals("about")) showAbout(); return false; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Preference pref = findPreference(key); this.setSummary(pref); } /* Set the summaries of all preferences */ private void initSummaries(PreferenceGroup pg) { for (int i = 0; i < pg.getPreferenceCount(); ++i) { Preference p = pg.getPreference(i); if (p instanceof PreferenceGroup) this.initSummaries((PreferenceGroup) p); // recursion else this.setSummary(p); } } /* Set the summaries of the given preference */ private void setSummary(Preference pref) { if (pref instanceof ListPreference) { ListPreference sPref = (ListPreference) pref; pref.setSummary(sPref.getEntry()); } else if (pref instanceof EditTextPreference) { EditTextPreference sPref = (EditTextPreference) pref; if (sPref.getText() != null) { if (sPref.getText().length() == 0) { sPref.setText(null); pref.setSummary(""); } else { if (sPref.getKey().indexOf("password") != -1) { String masked_pwd = ""; for (int i = 0; i < sPref.getText().length(); i++) masked_pwd += "*"; pref.setSummary(masked_pwd); } else pref.setSummary(sPref.getText()); } } } } /* Backup database */ private void dbBackup() { try { String filename = Export.database(getActivity()); Toast.makeText(getActivity(), String.format(getString(R.string.pref_backup_database_ok), filename), Toast.LENGTH_SHORT).show(); } catch (StorageNotMountedException e) { Toast.makeText(getActivity(), R.string.storage_not_mounted, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(getActivity(), R.string.pref_backup_database_failed, Toast.LENGTH_SHORT).show(); } } /* Restore database */ private void dbRestore() { File dir = new File(Export.path(getActivity())); FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".bkp"); } }; final String[] bkpList = dir.list(filter); if (bkpList != null && bkpList.length > 0) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.pref_restore_database); builder.setItems(bkpList, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, final int item) { new AlertDialog.Builder(getActivity()) .setTitle(R.string.pref_restore_database) .setMessage(String.format(getString(R.string.pref_restore_database_confirm), bkpList[item])) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { Database.getRawInstance(getActivity()).importDatabase(Export.path(getActivity()) + "/" + bkpList[item]); Toast.makeText(getActivity(), R.string.pref_restore_database_ok, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(getActivity(), R.string.pref_restore_database_failed, Toast.LENGTH_SHORT).show(); } }}) .setNegativeButton(android.R.string.no, null).show(); } }); AlertDialog alert = builder.create(); alert.show(); } else { Toast.makeText(getActivity(), R.string.pref_restore_database_nofiles, Toast.LENGTH_SHORT).show(); } } /* Purge database */ private void dbPurge() { new AlertDialog.Builder(getActivity()) .setTitle(R.string.pref_purge_database) .setMessage(R.string.pref_purge_database_confirm) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Measurement.purge(getActivity()); Toast.makeText(getActivity(), R.string.pref_database_purged, Toast.LENGTH_SHORT).show(); }}) .setNegativeButton(android.R.string.no, null).show(); } /* Load test data */ private void dbLoadTest() { ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.progress_spinner); progressBar.setVisibility(View.VISIBLE); new Thread(new Runnable() { public void run() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -40); for (int i=0; i<40; i++){ new Measurement(getActivity(), (70 + (int)(Math.random() * 110)/10.0f), (15 + (int)(Math.random() * 70)/10.0f), (50 + (int)(Math.random() * 210)/10.0f), (50 + (int)(Math.random() * 210)/10.0f), (short)(1500 + (int)(Math.random() * 20000)/10), (short)(1 + (int)(Math.random() * 90)/10), (short)(1 + (int)(Math.random() * 200)/10), (2 + (int)(Math.random() * 50)/10.0f), (short)(20 + (int)(Math.random() * 410)/10), cal.getTimeInMillis(), false).save(); cal.add(Calendar.DATE, 1); } getActivity().runOnUiThread(new Runnable() { public void run() { Toast.makeText(getActivity(), R.string.pref_test_data_loaded, Toast.LENGTH_SHORT).show(); ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.progress_spinner); progressBar.setVisibility(View.GONE); } }); } }).start(); } /* Display "About" dialog */ private void showAbout() { String message = "v" + getString(R.string.app_version); message += "\nSébastien Vrillaud © 2021"; if (!getString(R.string.translator).equals("")) { message += "\n\n" + Locale.getDefault().getDisplayLanguage().substring(0,1).toUpperCase() + Locale.getDefault().getDisplayLanguage().substring(1); message += "\n" + getString(R.string.translator); } AlertDialog.Builder b = new AlertDialog.Builder(getActivity()); b.setIcon(android.R.drawable.ic_menu_help); b.setTitle(R.string.app_name); b.setMessage(message); b.setPositiveButton(R.string.ok, null); b.show(); } public interface Callback { public void onNestedPreferenceSelected(int key); } }
package com.ardoise; import com.ardoise.vue.Fenetre; /** * <b>La classe Main permet de lancer l'ardoise magique via sa méthode main</b> * * @author Oltenos * @version 1 */ public class Main { /** * Permet de lancer l'application * @param args */ public static void main(String[] args) { @SuppressWarnings("unused") Fenetre fen = new Fenetre(); } }
import java.util.Arrays; class ArraySortSpecificPart { public static void main(String[] args) { int ar[]={3,6,1,7,2,9,4,6}; //Converting array to toString String s = Arrays.toString(ar); System.out.println("Given Array element is: "+s); //Sorting specific part of given array Arrays.sort(ar,2,6); String p = Arrays.toString(ar); System.out.println("Specific part sorted of given array is: "+p); //Sorting GivenArray Arrays.sort(ar); String t = Arrays.toString(ar); System.out.println("Sorted Array is: "+t); } }
package com.brainacademy.gui.app.ui; import com.brainacademy.gui.app.ui.forms.BaseForm; import com.brainacademy.gui.app.ui.forms.RoutesForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JToolBar; import javax.swing.WindowConstants; @Component public class MainFrame extends JFrame { @Autowired private RoutesForm routesForm; private JToolBar toolBar; private JButton showRoutesButton; private JButton showAirlinesButton; private JButton showAirportButton; private JScrollPane controlPanel; private BaseForm activeForm; private JToolBar childToolBar; public MainFrame() { this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setMinimumSize(new Dimension(500, 600)); this.setLocationRelativeTo(null); this.setLayout(new BorderLayout()); initComponents(); } public void showForm() { this.setVisible(true); } private void initComponents() { controlPanel = new JScrollPane(); showRoutesButton = new JButton("Routes"); showRoutesButton.addActionListener(this::showRoutesAction); showAirlinesButton = new JButton("Airlines"); showAirlinesButton.addActionListener(this::showAirlinesAction); showAirportButton = new JButton("Airports"); showAirportButton.addActionListener(this::showAirportAction); childToolBar = new JToolBar(); childToolBar.setVisible(false); toolBar = new JToolBar(); toolBar.setFloatable(false); toolBar.add(showRoutesButton); toolBar.add(showAirlinesButton); toolBar.add(showAirportButton); toolBar.addSeparator(); toolBar.add(childToolBar); this.add(toolBar, BorderLayout.PAGE_START); this.add(controlPanel); } private void showAirlinesAction(ActionEvent actionEvent) { } private void showAirportAction(ActionEvent actionEvent) { } private void showRoutesAction(ActionEvent actionEvent) { updateUi(routesForm); } private void updateUi(RoutesForm form) { if (!form.equals(activeForm)) { childToolBar.removeAll(); activeForm = form; } else { return; } activeForm.getActions().forEach(childToolBar::add); childToolBar.setVisible(childToolBar.getComponentCount() > 0); controlPanel.setViewportView(activeForm); activeForm.updateData(); } }