text
stringlengths
10
2.72M
/** * Created by Гамзат on 01.06.2017. */ public class Fry { private int year; private int month; private int day; public Fry() { this(0,0,0); } public Fry(int y){ this(y, 0, 0); } public Fry(int y, int m){ this(y, m, 0); } public Fry(int y, int m, int d) { setDate(y, m, d); } public void setDate(int y, int m, int d){ setYear(y); setMonth(m); setDay(d); } public void setYear(int y) { year = ((y >= 1900 && y <= 2017) ? y:2017); } public void setMonth(int m) { month = ((m>=1 && m <=31)? m:1); } public void setDay(int d) { day = ((d>=1 && d<=31)?d:1); } public int getYear(){ return year; } public int getMonth(){ return month; } public int getDay(){ return day; } public String toDisplay() { return String.format("%04d-%02d-%02d", getYear(), getMonth(), getDay()); } }
package cmc.vn.ejbca.RA.dto.request; public class RequestOfPKCS10CertificationDto { String keySpec; String keyalgorithmRsa; String signatureAlgorithm; String dn; public RequestOfPKCS10CertificationDto(String keySpec, String keyalgorithmRsa, String signatureAlgorithm, String dn) { this.keySpec = keySpec; this.keyalgorithmRsa = keyalgorithmRsa; this.signatureAlgorithm = signatureAlgorithm; this.dn = dn; } public String getKeySpec() { return keySpec; } public String getKeyalgorithmRsa() { return keyalgorithmRsa; } public String getSignatureAlgorithm() { return signatureAlgorithm; } public String getDn() { return dn; } }
package com.dalmirdasilva.androidmessagingprotocol.device.message; public class PingMessage extends Message { public PingMessage() { super(TYPE_PING); } }
package com.bnebit.sms.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.bnebit.sms.util.page.GridPageSet; import com.google.gson.Gson; @Controller @RequestMapping("/admin/message") public class AdminMessageController { @RequestMapping(value = "/messageList", method = RequestMethod.GET) public ModelAndView messageList(GridPageSet gridPageSet) { ModelAndView mav = new ModelAndView(); Gson gson = new Gson(); String jsonPageSet = gson.toJson(gridPageSet); mav.addObject("jsonPage", jsonPageSet); mav.setViewName("admin/adminMessageList"); return mav; } @RequestMapping(value = "/popup/messageForm", method = RequestMethod.GET) public ModelAndView messageForm() { ModelAndView mav = new ModelAndView(); mav.setViewName("admin/popup/adminMessageForm"); return mav; } }
package com.design.factory.AbstractFactory; public class XVeggiesOfRedPepper implements XVeggies { public String toString() { return "Red Pepper"; } }
package com.flowedu.util; public class FloweduUtils { public static String convertLectureDay(String engDay) { if (!"".equals(engDay)) return null; String korDay = null; switch (engDay) { case "MON" : korDay = "월요일"; break; case "TUE" : korDay = "월요일"; break; case "WEN" : korDay = "월요일"; break; case "THU" : korDay = "월요일"; break; case "FRI" : korDay = "월요일"; break; case "SAT" : korDay = "월요일"; break; case "SUN" : korDay = "일요일"; break; } return korDay; } }
package barryalan.ediary70; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Toast; public class login extends AppCompatActivity { //Define a user object to access user info user User1 = new user(); //Login page buttons declaration Button btn_Lsignin; Button btn_LforgotLogin; EditText et_Lusername; EditText et_Lpassword; CheckBox cb_LpasswordVisibility; //Defines the number of times a user fails to provide a valid login int numberOfTries = 0; //Everything that happens in login page runs from here @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //Create and link buttons and text boxes to the ones on the display btn_Lsignin = (Button) findViewById(R.id.btn_Lsignin); btn_LforgotLogin = (Button) findViewById(R.id.btn_LforgotLogin); et_Lusername = (EditText) findViewById(R.id.et_Lusername); et_Lpassword = (EditText) findViewById(R.id.et_Lpassword); cb_LpasswordVisibility = (CheckBox) findViewById(R.id.cb_LshowPassword); //If the button linked to btn_Lsignin is clicked on btn_Lsignin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Check if the user inputted a username and password if (!(isEmpty(et_Lusername)) & !(isEmpty(et_Lpassword))) { if (isValid(et_Lusername, et_Lpassword)) { //Are the provided credentials valid? //Are the valid login credentials those of an admin? if(et_Lusername.getText().toString().compareTo("Admin123") == 0 && et_Lpassword.getText().toString().compareTo("coco123") == 0){ gotoAdminActivity(v); } else { User1.setCurrentUserName(et_Lusername.getText().toString()); gotoHealthCareMenuActivity(v); } } } } }); //Allows the use of the show password feature in the login page cb_LpasswordVisibility.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //Checkbox status is changed from unchecked to checked if (!isChecked) { // SHOW PASSWORD et_Lpassword.setTransformationMethod(PasswordTransformationMethod.getInstance()); } else { // MASK PASSWORD et_Lpassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); } } }); } //Checks if the text box is empty or not public boolean isEmpty(EditText edittext) { String message; String hint = edittext.getHint().toString(); switch (hint) { case "Name": message = "Enter a name"; break; case "Password": message = "Enter a password"; break; default: message = "Enter a value"; break; } //Variables for the message Context context = getApplicationContext(); CharSequence text = "Please Enter all values"; int duration = Toast.LENGTH_SHORT; //Creates message Toast toast = Toast.makeText(context, text, duration); String value = edittext.getText().toString(); if (value.isEmpty()) { edittext.setError(message);//Message is chosen on switch statement above toast.show(); //Displays message return true; } else { return false; } } //Checks if username and password are in the database and match each other public boolean isValid(EditText usernametext, EditText passwordtext) { //Creating a new instance of the database in order to access it databaseHelper lbh = new databaseHelper(this); //Creating the login successful message Context context = getApplicationContext(); CharSequence text = "Login Successful!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); //Creating the login failed message Context context1 = getApplicationContext(); CharSequence text1 = "Login Failed!" + numberOfTries; int duration1 = Toast.LENGTH_SHORT; Toast toast1 = Toast.makeText(context1, text1, duration1); //Get the inputted text from the text boxes String userName = usernametext.getText().toString(); String password = passwordtext.getText().toString(); // Fetch the password from the database from the respective username String storedPassword = lbh.getUserPassword(userName); //Gives you three tries until the system allows for a forgot login if (numberOfTries > 1) { btn_LforgotLogin.setVisibility(View.VISIBLE); } //Validate the password with the one on the database if (password.equals(storedPassword)) { toast.show(); return true; } else { toast1.show(); numberOfTries++; return false; } } //LINK THE LOGIN PAGE TO THE REGISTRATION PAGE THROUGH THE BUTTON------------------------------- public void gotoRegistrationActivity(View view) { Intent name = new Intent(this, registration.class); startActivity(name); } //LINK THE LOGIN PAGE TO THE FORGOT LOGIN PAGE-------------------------------------------------- public void gotoForgotLoginActivity(View view) { Intent name = new Intent(this, forgotLogin.class); startActivity(name); } //LINK TO THE HEALTH MENU PAGE THROUGH THE BUTTON------------------------------- public void gotoHealthCareMenuActivity(View view) { Intent name = new Intent(this, healthCareMenu.class); startActivity(name); } //LINK THE LOGIN PAGE TO THE ADMIN PAGE--------------------------------------------------------- public void gotoAdminActivity(View view) { Intent name = new Intent(this, Admin.class); startActivity(name); } }
package sist.com.array; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; public class CalendarTest { Scanner sc = new Scanner(System.in); int year, Month; int[][] calendar = new int[6][7]; int[] lastDay = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // 각 달의 마지막 날 String[] Week = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" }; public void calendar(int[][] calendar, int month, int start) { // 캘린더에 날짜채우기 int day = 1; // 1일부터 시작 for (int i = 0; i < 6; i++) { if (i == 0) { // 첫주일때 for (int j = start; j <= 6; j++) { // 첫날은 start(firstOfDay에서 받아온 요일값)에서 채우기 시작 calendar[i][j] = day; day++; } } else { // 나머지 주일때 for (int j = 0; j <= 6; j++) { if (day > lastDay[month - 1]) // day가 마지막날보다 클때 반복문 빠져나가기 break; calendar[i][j] = day; day++; } } } } public void disp_cal() { // 캘린더 출력 for (int i = 0; i < calendar.length; i++) { for (int j = 0; j < calendar[i].length; j++) { if (calendar[i][j] == 0) { System.out.print(" "); // 배열에 채워진 값이 0이면 공백출력하고 컨티뉴 continue; } if (calendar[i][j] > lastDay[Month - 1]) // 마지막날짜보다 크면 반복빠져나가기 break; System.out.printf("%5d", calendar[i][j]); } System.out.println(); } } public void disp() { System.out.println(Arrays.toString(Week)); } public boolean leapYear(int year) { return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; } //2020.06.1 public int getCount() { int cnt = (year - 1) * 365; for (int i = 1; i < year; i++) { if (leapYear(i)) // 윤년이면 하루 많기때문에 cnt++ cnt++; } // 현재년도, 월 전까지의 총 cnt 합계. // 2019*365+leapyear if (leapYear(year)) lastDay[1] += 1; for (int i = 1; i < Month; i++) { cnt += lastDay[i - 1]; } cnt++; // 입력한 달의 첫날 return cnt; } //cnt%7 public int firstdayOfMonth() { int week = (getCount() % 7); switch (week) { case 0: return 0; case 1: return 1; case 2: return 2; case 3: return 3; case 4: return 4; case 5: return 5; default: return 6; } } public void injectWeek() { System.out.print("Year:"); year = sc.nextInt(); System.out.print("Month:"); Month = sc.nextInt(); calendar(calendar, Month, firstdayOfMonth()); disp(); disp_cal(); } public static void main(String[] args) { CalendarTest ct = new CalendarTest(); ct.injectWeek(); } }
package cn.vaf714.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import cn.vaf714.entity.AdminUser; import cn.vaf714.util.DBUtil; public class AdminUserDao { /** * 查找管理员用户 * * @param username * @return */ public AdminUser getUser(String username) { PreparedStatement preparedStatement = null; ResultSet rs = null; AdminUser user = null; // 1.获取数据库连接 Connection connection = DBUtil.getInstance().getConnection(); String sql; // 2.准备 sql 语句 sql = "select * from admin where name=?"; try { // 3.执行 sql 语句 preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, username); rs = preparedStatement.executeQuery(); // 4.处理结果 while (rs.next()) { user = new AdminUser(rs.getString("name"), rs.getString("password")); } } catch (Exception e) { e.printStackTrace(); } finally { // 4.关闭连接 DBUtil.getInstance().release(null, preparedStatement, connection); } return user; } }
package com.example.android.tourguide; import androidx.annotation.NonNull; public class LocationInfo { private String mName , mAddress,mInfo,mArtistName ; private int imageId,mPlayIcon,mStopIcon; private int NO_AUDIO_PROVIDED = -1; private int mRaw = NO_AUDIO_PROVIDED; //Displaying Location public LocationInfo(String name,String address, int imageResource){ // setting this in wrong way made the items on the list invisible mName = name; mAddress = address; imageId = imageResource; } //Displaying Song public LocationInfo(int stopIcon ,int playIcon ,String name,String artist,int raw){ mName = name; mArtistName = artist; mPlayIcon = playIcon; mStopIcon = stopIcon; mRaw = raw; } public String getmName() { return mName; } public String getmAddress() { return mAddress; } public int getImageId() { return imageId; } public String getmArtistName() { return mArtistName; } public int getmRaw() { return mRaw; } public int getmPlayIcon() { return mPlayIcon; } public int getmStopIcon() { return mStopIcon; } public boolean hasAudio (){ return mRaw != NO_AUDIO_PROVIDED; } @NonNull @Override public String toString() { return super.toString(); } }
package edu.cricket.api.cricketscores.async; import edu.cricket.api.cricketscores.utils.BbbServiceUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.Date; import java.util.Map; @Component @Scope("prototype") public class RefreshAllLiveEventBallsTask implements Runnable { private static final Logger logger = LoggerFactory.getLogger(RefreshAllLiveEventBallsTask.class); @Autowired Map<Long, Long> liveGames; @Autowired BbbServiceUtil bbbServiceUtil; @Override public void run() { liveGames.keySet().forEach(gameId -> { bbbServiceUtil.persistAllBallsForGame(gameId); }); logger.info("completed live event balls refresh job at {}", new Date()); } }
package com.openfarmanager.android.fragments; import android.annotation.TargetApi; import android.app.Dialog; import android.content.Intent; import android.content.res.Configuration; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.text.Layout; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.openfarmanager.android.App; import com.openfarmanager.android.R; import com.openfarmanager.android.adapters.LinesAdapter; import com.openfarmanager.android.filesystem.actions.RootTask; import com.openfarmanager.android.model.ViewerBigFileTextViewer; import com.openfarmanager.android.model.ViewerTextBuffer; import com.openfarmanager.android.model.exeptions.SdcardPermissionException; import com.openfarmanager.android.utils.FileUtilsExt; import com.openfarmanager.android.utils.ReversedIterator; import com.openfarmanager.android.dialogs.QuickPopupDialog; import com.openfarmanager.android.dialogs.SelectEncodingDialog; import com.openfarmanager.android.utils.StorageUtils; import com.openfarmanager.android.utils.SystemUtils; import com.openfarmanager.android.view.ToastNotification; import org.apache.commons.io.IOCase; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.ObservableOnSubscribe; import io.reactivex.Observer; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import static com.openfarmanager.android.controllers.EditViewController.MSG_BIG_FILE; import static com.openfarmanager.android.controllers.EditViewController.MSG_TEXT_CHANGED; import static com.openfarmanager.android.utils.Extensions.getThreadPool; import static com.openfarmanager.android.utils.StorageUtils.checkForPermissionAndGetBaseUri; import static com.openfarmanager.android.utils.StorageUtils.checkUseStorageApi; /** * File viewer */ public class Viewer extends Fragment { private static final String TAG = "::: Viewer :::"; private static final int MB = 1048576; public static final int MAX_FILE_SIZE = 3 * MB; public static final int LINES_COUNT_FRAGMENT = 2000; private File mFile; private ListView mList; private LinesAdapter mAdapter; private ProgressBar mProgress; private Handler mHandler; private ViewerTextBuffer mText; private ViewerBigFileTextViewer mBigText; private boolean mStopLoading; private boolean mBigFile; private LoadFileTask mLoadFileTask; private LoadTextFragmentTask mLoadTextFragmentTask; private Charset mSelectedCharset = Charset.forName("UTF-8"); private Dialog mCharsetSelectDialog; protected QuickPopupDialog mSearchResultsPopup; private int mCalculatedRowHeight = -1; // private CompositeDisposable mCompositeDisposable; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.viewer, container); mList = (ListView) view.findViewById(android.R.id.list); mProgress = (ProgressBar) view.findViewById(android.R.id.progress); mText = new ViewerTextBuffer(); mBigText = new ViewerBigFileTextViewer(); view.findViewById(R.id.root_view).setBackgroundColor(App.sInstance.getSettings().getViewerColor()); mSearchResultsPopup = new QuickPopupDialog(getActivity(), view, R.layout.search_results_popup); mSearchResultsPopup.setPosition(Gravity.RIGHT | Gravity.TOP, (int) (50 * getResources().getDisplayMetrics().density)); // mCompositeDisposable = new CompositeDisposable(); return view; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (mCharsetSelectDialog != null && mCharsetSelectDialog.isShowing()) { adjustDialogSize(mCharsetSelectDialog); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BaseFileSystemPanel.REQUEST_CODE_REQUEST_PERMISSION && Build.VERSION.SDK_INT >= 21 && data != null) { getActivity().getContentResolver().takePersistableUriPermission(data.getData(), Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } } @Override public void onDestroy() { if (mLoadFileTask != null) { mStopLoading = true; mLoadFileTask.cancel(true); mLoadFileTask = null; } // mCompositeDisposable.clear(); mSearchResultsPopup.dismiss(); super.onDestroy(); } public void changeMode() { mAdapter.setMode(mAdapter.getMode() == LinesAdapter.MODE_VIEW ? LinesAdapter.MODE_EDIT : LinesAdapter.MODE_VIEW); updateAdapter(); } public int getMode() { return mAdapter.getMode(); } public void setHandler(Handler handler) { mHandler = handler; } public void setEncoding(Charset charset) { mSelectedCharset = charset; openSelectedFile(); } public void gotoLine(final int lineNumber, int type) { int totalLinesNumber = mAdapter.getCount(); int position = type == EditViewGotoDialog.GOTO_LINE_POSITION ? lineNumber : (int) (totalLinesNumber / 100.0 * lineNumber); if (position > totalLinesNumber) { position = totalLinesNumber; } mList.setSelection(position); } public void openFile(final File file) { mFile = file; String charset = App.sInstance.getSettings().getDefaultCharset(); if (charset == null) { setEncoding(Charset.defaultCharset()); showSelectEncodingDialog(); } else { setEncoding(Charset.forName(charset)); } } public boolean isFileTooBig() { return mFile.length() > MAX_FILE_SIZE; } private void openSelectedFile() { mProgress.setVisibility(View.VISIBLE); if (isFileTooBig()) { mBigFile = true; mHandler.sendMessage(Message.obtain(mHandler, MSG_BIG_FILE)); Log.d(TAG, "file to large to be opened in edit mode"); ToastNotification.makeText(Viewer.this.getActivity(), App.sInstance.getString(R.string.error_file_is_too_big), Toast.LENGTH_SHORT).show(); mList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (i == mAdapter.getCount() - 1 && mBigText.hasBottomFragment()) { loadBifFileFragment(mBigText.nextFragment()); } else if (i == 0 && mBigText.hasUpperFragment()) { loadBifFileFragment(mBigText.previousFragment()); } } }); } mAdapter = new LinesAdapter(mBigFile ? mBigText : mText); mList.setAdapter(mAdapter); mStopLoading = false; mLoadFileTask = new LoadFileTask(); //noinspection unchecked mLoadFileTask.execute(); } private void loadBifFileFragment(int fragmentNumber) { if (mLoadTextFragmentTask != null) { mLoadTextFragmentTask.cancel(true); } mLoadTextFragmentTask = new LoadTextFragmentTask(fragmentNumber); //noinspection unchecked mLoadTextFragmentTask.execute(); } public void search(String pattern, boolean caseSensitive, boolean wholeWords, boolean regularExpression) { mAdapter.search(pattern, caseSensitive, wholeWords, regularExpression); doSearch(pattern, caseSensitive, wholeWords, regularExpression); } public void doSearch(final String pattern, final boolean caseSensitive, final boolean wholeWords, final boolean regularExpression) { if (!mSearchResultsPopup.isShowing()) { mSearchResultsPopup.show(); } final List<Integer> searchLines = Collections.synchronizedList(new ArrayList<Integer>()); final Map<Integer, int[]> wordsOnLine = Collections.synchronizedMap(new HashMap<Integer, int[]>()); View view = mSearchResultsPopup.getContentView(); final View progress = view.findViewById(R.id.search_progress); final TextView matches = (TextView) view.findViewById(R.id.search_found); final View next = view.findViewById(R.id.search_next); final View prev = view.findViewById(R.id.search_prev); final View close = view.findViewById(R.id.search_close); progress.setVisibility(View.VISIBLE); prev.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = mList.getFirstVisiblePosition(); for (Integer pos : new ReversedIterator<>(searchLines)) { TextView textView = (TextView) getChildView(pos); if (pos < position) { gotoLine(pos - 1, EditViewGotoDialog.GOTO_LINE_POSITION); return; } else if (textView != null && textView.getLineCount() > 1 && wordsOnLine.get(pos).length > 1) { Layout layout = textView.getLayout(); calculateRowHeight(textView, layout); int firstVisibleRow = calculateFirstVisibleRow(textView); if (layout.getLineCount() < firstVisibleRow) { continue; } int firstSearchIndex = layout.getLineEnd(firstVisibleRow - 1); int prevPosition = wordsOnLine.get(pos)[0]; for (int wordPosition : wordsOnLine.get(pos)) { if (wordPosition > firstSearchIndex) { for (int j = firstVisibleRow; j >= 0; j--) { if (isSearchWordOnLine(layout, prevPosition, j)) { // no need to scroll to the same line - let's find next occurrence if (firstVisibleRow == j) { break; } scrollToLine(textView, firstVisibleRow, j); return; } } } else { prevPosition = wordPosition; } } } } } }); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = mList.getFirstVisiblePosition() + 2; for (Integer pos : searchLines) { TextView textView = (TextView) getChildView(pos); if (pos > position) { gotoLine(pos - 1, EditViewGotoDialog.GOTO_LINE_POSITION); return; } else if (textView != null && textView.getLineCount() > 1 && wordsOnLine.get(pos).length > 1) { Layout layout = textView.getLayout(); calculateRowHeight(textView, layout); int firstVisibleRow = calculateFirstVisibleRow(textView); int firstSearchIndex = layout.getLineEnd(firstVisibleRow); for (int wordPosition : wordsOnLine.get(pos)) { if (wordPosition > firstSearchIndex) { for (int j = firstVisibleRow + 1; j < layout.getLineCount(); j++) { if (isSearchWordOnLine(layout, wordPosition, j)) { // no need to scroll to the same line - let's find next occurrence if (firstVisibleRow == j) { break; } scrollToLine(textView, firstVisibleRow, j); return; } } } } } } } }); matches.setText("0"); // final Subscription subscription = Observable.create( CompositeDisposable compositeDisposable = new CompositeDisposable(); Observable.create((ObservableOnSubscribe<SearchResult>) e -> { ArrayList<String> lines = mAdapter.getText(); SearchResult searchResult = new SearchResult(); for (int i = 0; i < lines.size(); i++) { if (e.isDisposed()) { break; } searchResult.reset(); String line = lines.get(i); doSearchInText(line, pattern, caseSensitive, wholeWords, regularExpression, searchResult); if (searchResult.count > 0) { searchResult.lineNumber = i; e.onNext(searchResult); } } e.onComplete(); }).subscribeOn(Schedulers.from(getThreadPool())).subscribe(new Observer<SearchResult>() { private int mTotalOccurrence; @Override public void onSubscribe(Disposable d) { compositeDisposable.add(d); } @Override public void onNext(SearchResult searchResult) { mTotalOccurrence += searchResult.count; searchLines.add(searchResult.lineNumber); int[] wordPositions = new int[searchResult.positions.size()]; int i = 0; for (Integer position : searchResult.positions) { wordPositions[i++] = position; } wordsOnLine.put(searchResult.lineNumber, wordPositions); updateUi(mUpdateOccurrences); } @Override public void onError(Throwable t) { } @Override public void onComplete() { updateUi(() -> progress.setVisibility(View.GONE)); } private Runnable mUpdateOccurrences = new Runnable() { @Override public void run() { matches.setText(String.valueOf(mTotalOccurrence)); } }; }); close.setOnClickListener(v -> { compositeDisposable.clear(); mAdapter.stopSearch(); mSearchResultsPopup.dismiss(); }); } private int calculateFirstVisibleRow(TextView textView) { return Math.abs(Math.round(textView.getY() / mCalculatedRowHeight)); } private boolean isSearchWordOnLine(Layout layout, int wordPosition, int j) { return wordPosition >= layout.getLineStart(j) && wordPosition <= layout.getLineEnd(j); } private void scrollToLine(TextView textView, int firstVisibleRow, int requiredRow) { int scrollBy = mCalculatedRowHeight * (requiredRow - firstVisibleRow); mList.smoothScrollBy(scrollBy + (int) (textView.getY() + firstVisibleRow * mCalculatedRowHeight), 0); } private void calculateRowHeight(TextView textView, Layout layout) { if (mCalculatedRowHeight == -1) { mCalculatedRowHeight = layout.getHeight() / textView.getLineCount(); } } private View getChildView(int pos) { int firstPosition = mList.getFirstVisiblePosition() - mList.getHeaderViewsCount(); int wantedChild = pos - firstPosition; return mList.getChildAt(wantedChild); } private void doSearchInText(String string, String pattern, boolean caseSensitive, boolean wholeWords, boolean regularExpression, SearchResult result) { Pattern patternMatch = FileUtilsExt.createWordSearchPattern(pattern, wholeWords, caseSensitive ? IOCase.SENSITIVE : IOCase.INSENSITIVE); Matcher matcher = patternMatch.matcher(string); while (matcher.find()) { result.positions.add(matcher.start()); result.count++; } } private class SearchResult { int lineNumber; int count; LinkedList<Integer> positions = new LinkedList<>(); public void reset() { count = 0; positions.clear(); } } public void save() { mAdapter.saveCurrentEditLine(getActivity().getCurrentFocus()); mSaveObservable.subscribe(() -> { mHandler.sendMessage(Message.obtain(mHandler, MSG_TEXT_CHANGED, mText.isTextChanged())); }, throwable -> { throwable.printStackTrace(); if (throwable instanceof SdcardPermissionException && Build.VERSION.SDK_INT >= 21) { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); startActivityForResult(intent, BaseFileSystemPanel.REQUEST_CODE_REQUEST_PERMISSION); } }); } public void replace(final String pattern, final String replaceTo, final boolean caseSensitive, final boolean wholeWords, final boolean regularExpression) { Completable.create(e -> { mText.replace(pattern, replaceTo, caseSensitive ? IOCase.SENSITIVE : IOCase.INSENSITIVE, wholeWords, regularExpression); e.onComplete(); }).subscribeOn(Schedulers.from(getThreadPool())).subscribe(() -> { updateUi(() -> { updateAdapter(); mSearchResultsPopup.dismiss(); mHandler.sendMessage(Message.obtain(mHandler, MSG_TEXT_CHANGED, mText.isTextChanged())); }); }, Throwable::printStackTrace); } // TODO: we need to avoid this говнокод!!! private class LoadTextFragmentTask extends AsyncTask<Void, Void, ArrayList<String>> { private int mFragment; private int mStartPosition; private LoadTextFragmentTask(int fragment) { mFragment = fragment; mStartPosition = fragment * LINES_COUNT_FRAGMENT; } @Override protected void onPreExecute() { super.onPreExecute(); mProgress.setVisibility(View.VISIBLE); } @Override protected ArrayList<String> doInBackground(Void... voids) { BufferedReader is = null; ArrayList<String> lines = new ArrayList<String>(); try { is = new BufferedReader(new InputStreamReader(new FileInputStream(mFile), mSelectedCharset.name())); String line; int count = 0; while (count < mStartPosition && (is.readLine()) != null) { count++; } count = 0; while (count < LINES_COUNT_FRAGMENT && (line = is.readLine()) != null) { lines.add(line); count++; } } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return lines; } @Override protected void onPostExecute(ArrayList<String> result) { super.onPostExecute(result); mBigText.setLines(result); mProgress.setVisibility(View.GONE); mList.post(new Runnable() { public void run() { mList.setSelection(0); mList.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { mAdapter.notifyDataSetChanged(); mList.getViewTreeObserver().removeOnScrollChangedListener(this); } }); } }); } } private class LoadFileTask extends AsyncTask<Void, Void, Void> { private ArrayList<String> mLines; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... voids) { mLines = new ArrayList<String>(); if (mBigFile) { loadFragmentsFileStrings(); } else { loadFileStrings(); } return null; } private void loadFragmentsFileStrings() { BufferedReader is = null; try { is = new BufferedReader(new InputStreamReader(new FileInputStream(mFile), mSelectedCharset.name())); String line; int count = 0; while (!mStopLoading && count < LINES_COUNT_FRAGMENT && (line = is.readLine()) != null) { mLines.add(line); count++; } } catch (Exception e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void loadFileStrings() { BufferedReader is = null; try { if(mFile.canRead()){ is = new BufferedReader(new InputStreamReader(new FileInputStream(mFile), mSelectedCharset.name())); }else{ is = new BufferedReader(RootTask.readFile(mFile)); } if (App.sInstance.getSettings().isReplaceDelimeters()) { loadLinesReplaceSpecialCh(is); } else { loadLines(is); } } catch (IOException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void loadLines(BufferedReader is) throws IOException { String line; while (!mStopLoading && (line = is.readLine()) != null) { mLines.add(line); } } private void loadLinesReplaceSpecialCh(BufferedReader is) throws IOException { String line; while (!mStopLoading && (line = is.readLine()) != null) { for (int i = 1; i <= 31; i++) { line = line.replace(Character.toString((char) i), "0x" + Integer.toString(i, 16)); } mLines.add(line); } } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); mProgress.setVisibility(View.GONE); mAdapter.swapData(mLines); } } private void updateAdapter() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } public void showSelectEncodingDialog() { mCharsetSelectDialog = new SelectEncodingDialog(getActivity(), mHandler, mFile); mCharsetSelectDialog.show(); mCharsetSelectDialog.setCancelable(true); adjustDialogSize(mCharsetSelectDialog); } /** * Adjust dialog size. Actuall for old android version only (due to absence of Holo themes). * * @param dialog dialog whose size should be adjusted. */ private void adjustDialogSize(Dialog dialog) { DisplayMetrics metrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); WindowManager.LayoutParams params = new WindowManager.LayoutParams(); params.copyFrom(dialog.getWindow().getAttributes()); params.width = (int) (metrics.widthPixels * 0.65); params.height = (int) (metrics.heightPixels * 0.55); dialog.getWindow().setAttributes(params); } private void updateUi(Runnable runnable) { getActivity().runOnUiThread(runnable); } private Completable mSaveObservable = Completable.create(emitter -> { try { String sdCardPath = SystemUtils.getExternalStorage(mFile.getAbsolutePath()); if (checkUseStorageApi(sdCardPath)) { checkForPermissionAndGetBaseUri(); OutputStream stream = StorageUtils.getStorageOutputFileStream(mFile, sdCardPath); mText.save(stream); } else { mText.save(mFile); } } catch (Exception e) { emitter.onError(e); } emitter.onComplete(); }).subscribeOn(Schedulers.from(getThreadPool()));; }
package com.example.user.e_kpiv3; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; 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.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.Hashtable; import java.util.Map; public class LoginActivity extends AppCompatActivity { EditText EmailEt, PasswordEt; String email, password; String staffID = ""; private int isLecturer = 1; private SharedPreferences preferences; static final String PREF_NAME = "PrefKey"; public static final String KEY_STAFFID = "staffID"; private String roleType = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); EmailEt = (EditText)findViewById(R.id.etEmail); PasswordEt = (EditText) findViewById(R.id.etPassword); preferences = getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE); } public void OnLogin(View view){ email = EmailEt.getText().toString(); password = PasswordEt.getText().toString(); String type = "login"; BackgroundWorker backgroundWorker = new BackgroundWorker(this); backgroundWorker.execute(type, email, password); } public void OnRegister(View view) { startActivity(new Intent(this, RegisterActivity.class)); } public class BackgroundWorker extends AsyncTask<String, Void, String> { Context context; AlertDialog alertDialog; BackgroundWorker(Context ctx) { context = ctx; } @Override protected String doInBackground(String... params) { String type = params[0]; String result = ""; String login_url = "http://192.168.173.1/e-KPI/php/Login.php"; if (type.equals("login")) { try { String email = params[1]; String password = params[2]; URL url = new URL(login_url); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); OutputStream outputStream = httpURLConnection.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); String post_data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); bufferedWriter.write(post_data); bufferedWriter.flush(); bufferedWriter.close(); outputStream.close(); InputStream inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1")); //String result=""; String line; while ((line = bufferedReader.readLine()) != null) { result += line; } bufferedReader.close(); inputStream.close(); httpURLConnection.disconnect(); return result; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return result; } @Override protected void onPreExecute() { //alertDialog = new AlertDialog.Builder(context).create(); //alertDialog.setTitle("Login Status"); super.onPreExecute(); } @Override protected void onPostExecute(String result) { //alertDialog.setMessage(result); //alertDialog.show(); if (result.equals("")) { result = "Login unsuccessful."; } else { staffID = result; getSecondaryPosition(); SharedPreferences.Editor editor = preferences.edit(); editor.putString("staffid", result); editor.commit(); Intent intent = new Intent(LoginActivity.this, HomepageActivity.class); intent.putExtra("result", result); LoginActivity.this.startActivity(intent); } Toast.makeText(context, result, Toast.LENGTH_LONG).show(); } private void getSecondaryPosition() { // Instantiate the RequestQueue. String secondaryPosition_url = "http://192.168.173.1/e-KPI/php/GetSecondaryPosition.php"; StringRequest stringRequest = new StringRequest(Request.Method.POST, secondaryPosition_url, new Response.Listener<String>() { @Override public void onResponse(String s) { if (s.contains("Dean") || s.equals("Administrator")) { isLecturer = 0; roleType = "Faculty"; } else if (s.equals("Head of Department")){ isLecturer = 0; roleType = "Departmental"; //Toast.makeText(LoginActivity.this, s, Toast.LENGTH_LONG).show(); } else { isLecturer = 1; roleType = "Individual"; } SharedPreferences.Editor editor = preferences.edit(); editor.putString("secondaryPosition", s); editor.putInt("isLecturer", isLecturer); editor.putString("roleType", roleType); editor.commit(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { //Toast.makeText(LoginActivity.this, s , Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { //Creating parameters Map<String, String> params = new Hashtable<String, String>(); //Adding parameters params.put(KEY_STAFFID, staffID); //returning parameters return params; } }; //Creating a Request Queue RequestQueue requestQueue = Volley.newRequestQueue(context); //Adding request to the queue requestQueue.add(stringRequest); } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); } } }
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /// CHECK-START: char Main.$noinline$inlineMonomorphic(java.lang.CharSequence) inliner (before) /// CHECK: InvokeInterface method_name:java.lang.CharSequence.charAt /// CHECK-START: char Main.$noinline$inlineMonomorphic(java.lang.CharSequence) inliner (after) /// CHECK: Deoptimize /// CHECK: InvokeVirtual method_name:java.lang.String.charAt intrinsic:StringCharAt /// CHECK-START: char Main.$noinline$inlineMonomorphic(java.lang.CharSequence) instruction_simplifier$after_inlining (after) /// CHECK: Deoptimize /// CHECK-NOT: InvokeInterface /// CHECK-NOT: InvokeVirtual public static char $noinline$inlineMonomorphic(CharSequence cs) { return cs.charAt(0); } /// CHECK-START: char Main.$noinline$knownReceiverType() inliner (before) /// CHECK: InvokeInterface method_name:java.lang.CharSequence.charAt /// CHECK-START: char Main.$noinline$knownReceiverType() inliner (after) /// CHECK: InvokeVirtual method_name:java.lang.String.charAt intrinsic:StringCharAt /// CHECK-START: char Main.$noinline$knownReceiverType() instruction_simplifier$after_inlining (after) /// CHECK-NOT: InvokeInterface /// CHECK-NOT: InvokeVirtual public static char $noinline$knownReceiverType() { CharSequence cs = "abc"; return cs.charAt(1); } /// CHECK-START: boolean Main.$noinline$stringEquals(java.lang.Object) inliner (before) /// CHECK: InvokeVirtual method_name:java.lang.Object.equals intrinsic:None /// CHECK-START: boolean Main.$noinline$stringEquals(java.lang.Object) inliner (after) /// CHECK: Deoptimize /// CHECK: InvokeVirtual method_name:java.lang.String.equals intrinsic:StringEquals /// CHECK-START: boolean Main.$noinline$stringEquals(java.lang.Object) instruction_simplifier$after_inlining (after) /// CHECK: Deoptimize /// CHECK: InvokeVirtual method_name:java.lang.String.equals intrinsic:StringEquals public static boolean $noinline$stringEquals(Object obj) { return obj.equals("def"); } public static void test() { // Warm up inline cache. for (int i = 0; i < 600000; i++) { $noinline$inlineMonomorphic(str); } for (int i = 0; i < 600000; i++) { $noinline$stringEquals(str); } ensureJitCompiled(Main.class, "$noinline$stringEquals"); ensureJitCompiled(Main.class, "$noinline$inlineMonomorphic"); ensureJitCompiled(Main.class, "$noinline$knownReceiverType"); if ($noinline$inlineMonomorphic(str) != 'x') { throw new Error("Expected x"); } if ($noinline$knownReceiverType() != 'b') { throw new Error("Expected b"); } if ($noinline$stringEquals("abc")) { throw new Error("Expected false"); } } public static void main(String[] args) { System.loadLibrary(args[0]); test(); } static String str = "xyz"; private static native void ensureJitCompiled(Class<?> itf, String method_name); }
package com.beike.dao.impl.merchant; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.stereotype.Repository; import com.beike.dao.GenericDaoImpl; import com.beike.dao.merchant.BranchProfileDao; import com.beike.entity.merchant.BranchProfile; /** * project:beiker Title: Description: Copyright:Copyright (c) 2011 * Company:Sinobo * * @author qiaowb * @date Mar 15, 2012 2:22:15 PM * @version 1.0 */ @Repository("branchProfileDao") public class BranchProfileDaoImpl extends GenericDaoImpl<BranchProfile, Long> implements BranchProfileDao { /* * (non-Javadoc) * * @see * com.beike.dao.merchant.BranchProfileDao#getBranchProfileById(java.lang * .String) */ @Override public List<BranchProfile> getBranchProfileById(String ids) { StringBuilder selSql = new StringBuilder( "select merchantid,branchid,well_count,satisfy_count,poor_count ") .append("from beiker_branch_profile where branchid in (") .append(ids).append(")"); List<BranchProfile> lstBranch = null; lstBranch = this.getSimpleJdbcTemplate().query(selSql.toString(), new RowMapperImpl()); return lstBranch; } protected class RowMapperImpl implements ParameterizedRowMapper<BranchProfile> { @Override public BranchProfile mapRow(ResultSet rs, int rowNum) throws SQLException { BranchProfile profile = new BranchProfile(); profile.setMerchantId(rs.getLong("merchantid")); profile.setBranchId(rs.getLong("branchid")); profile.setWellCount(rs.getLong("well_count")); profile.setSatisfyCount(rs.getLong("satisfy_count")); profile.setPoorCount(rs.getLong("poor_count")); return profile; } } @Override public BranchProfile getBranchProfileById(Long branchid) { StringBuilder selSql = new StringBuilder( "select merchantid,branchid,well_count,satisfy_count,poor_count ") .append("from beiker_branch_profile where branchid=?"); BranchProfile lstBranch = (BranchProfile) getJdbcTemplate().queryForObject(selSql.toString(), new Object[]{branchid}, new RowMapperImpl()); return lstBranch; } }
package de.omikron.server; import de.omikron.client.Frontend; public class Backend { private ServerConnection server; public Backend() { server = new ServerConnection(3000); } protected void init() { server.init(); } }
package com.pelephone_mobile.mypelephone.ui.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.androidquery.AQuery; import com.pelephone_mobile.R; import com.pelephone_mobile.mypelephone.network.rest.pojos.BannerItem; import java.util.ArrayList; import java.util.List; /** * Created by gali.issachar on 10/12/13. */ public class MainViewFlowAdapter extends BaseAdapter { private Context context; private List<BannerItem> list = new ArrayList<BannerItem>(); public MainViewFlowAdapter(Context context, List<BannerItem> list){ this.context = context; this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null){ convertView = LayoutInflater.from(context).inflate(R.layout.main_view_flow_item,null,false); } // ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView); String url = list.get(position).imageURL.replace('\\', '/'); url = url.replace("https","http"); AQuery aQuery = new AQuery(convertView); aQuery.id(R.id.imageView).progress(R.id.progressBar).image(url); return convertView; } }
package backup; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.http.FileContent; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.io.IOException; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) class BackedFile { @JsonProperty private String name; @JsonProperty private String id; @JsonProperty private long when; public void setName(String n) { this.name = n; } public void setId(String i) { this.id = i; } public void setWhen(long w) { this.when = w; } public String getName() { return this.name; } public String getId() { return this.id; } public long getWhen() { return this.when; } } public class GDriveBackup { private static final String APPLICATION_NAME = "Password Manager"; private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static final String TOKENS_DIRECTORY_PATH = "tokens"; // "View and manage Google Drive files and folders that you have opened or created with this app" private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE_FILE); private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; private static final String BACKEDUP_FILE_PATH = "src/main/resources/backup.json"; /** * Creates an authorized Credential object. * @param HTTP_TRANSPORT The network HTTP Transport. * @return An authorized Credential object. * @throws IOException If the credentials.json file cannot be found. */ private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { // Load client secrets. InputStream in = GDriveBackup.class.getResourceAsStream(CREDENTIALS_FILE_PATH); if (in == null) { throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH); } GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); // Build flow and trigger user authorization request. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) .setAccessType("offline") .build(); LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); } private String removePathPart(String path) throws UnsupportedEncodingException { byte[] rawPath = path.getBytes("UTF-8"); int pos = rawPath.length - 1; while (rawPath[pos] != (byte)'/' && pos > 1) --pos; ++pos; byte[] rawName = new byte[rawPath.length - pos]; System.arraycopy(rawPath, pos, rawName, 0, rawPath.length - pos); return new String(rawName); } /** * Use the Drive.Files.Create class * to create a new file on drive. */ public void doFileBackup(String path) throws IOException, GeneralSecurityException { final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME) .build(); com.google.api.services.drive.model.File fMeta = new com.google.api.services.drive.model.File(); java.io.File fObj = new java.io.File(path); FileContent content = new FileContent("application/octet-stream", fObj); String name = null; final ObjectMapper mapper = new ObjectMapper(); java.io.File fileBackup = new java.io.File(BACKEDUP_FILE_PATH); BackedFile bFile = null; String gFileId = null; if (fileBackup.exists()) { byte[] data = Files.readAllBytes(Paths.get(BACKEDUP_FILE_PATH)); bFile = mapper.readValue(data, BackedFile.class); gFileId = bFile.getId(); } else { bFile = new BackedFile(); } try { name = removePathPart(path); name += "_passwordfile_backup_" + System.currentTimeMillis(); } catch (UnsupportedEncodingException e) { System.err.println("UnsupportedCodingException while getting name part of path"); e.printStackTrace(); } fMeta.setName(name); //fMeta.setOwnedByMe(true); // << This was causing a 403 Forbidden error (field not writeable) /* * If we already have a backup, use the files.update method. */ if (null != gFileId) { service .files() .update(gFileId, fMeta, content) .execute(); System.out.println("Updated backup file on GDrive with ID " + gFileId); bFile.setWhen(System.currentTimeMillis()); } else { com.google.api.services.drive.model.File gFile = service .files() .create(fMeta, content) .execute(); System.out.println( "Created new file on GDrive with ID " + gFile.getId()); bFile.setName(name); bFile.setId(gFile.getId()); bFile.setWhen(System.currentTimeMillis()); } mapper.writeValue(new java.io.File(BACKEDUP_FILE_PATH), bFile); return; } public int doDownloadBackup(String path) throws IOException, GeneralSecurityException { final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME) .build(); ObjectMapper mapper = new ObjectMapper(); java.io.File fileBackup = new java.io.File(BACKEDUP_FILE_PATH); BackedFile bFile = null; OutputStream out = new ByteArrayOutputStream(); if (!fileBackup.exists()) return -1; byte[] data = Files.readAllBytes(Paths.get(BACKEDUP_FILE_PATH)); bFile = mapper.readValue(data, BackedFile.class); service .files() .get(bFile.getId()) .executeMediaAndDownloadTo(out); ((ByteArrayOutputStream)out).writeTo(new FileOutputStream(new java.io.File(path))); return 0; } }
package kxg.searchaf.url.hollisterco; import java.sql.*; import java.util.List; import kxg.searchaf.db.mysql.MysqlDao; import kxg.searchaf.util.ProxyUtli; public class HollistercoMysqlDao extends MysqlDao { public void save(HollistercoProduct product) { if (product == null || product.productid == 0) return; if (product.inventoryList == null || product.inventoryList.size() == 0) { return; } try { getConnection(); conn.setAutoCommit(false); String sql = "INSERT INTO hollistercoproduct(productid, name, listprice, collection)" + " VALUES (?,?,?,?)"; // 插入数据的sql语句 PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, product.productid); ps.setString(2, product.name); ps.setFloat(3, product.listprice); ps.setString(4, product.data_collection); ps.executeUpdate(); // insert inventory if (product.inventoryList != null && product.inventoryList.size() > 0) { for (int i = 0; i < product.inventoryList.size(); i++) { Inventory inventory = product.inventoryList.get(i); sql = "INSERT INTO hollistercoproduct_inventory(name, seq,listprice,imgPrefix,longSku, itemSize,itemSeq,sku,cat,productid)" + " VALUES (?,?,?,?,?,?,?,?,?,?)"; // 插入数据的sql语句 ps = conn.prepareStatement(sql); ps.setString(1, inventory.name); ps.setString(2, inventory.seq); ps.setString(3, inventory.listprice); ps.setString(4, inventory.imgPrefix); ps.setString(5, inventory.longSku); ps.setString(6, inventory.itemSize); ps.setString(7, inventory.itemSeq); ps.setString(8, inventory.sku); ps.setString(9, inventory.cat); ps.setInt(10, product.productid); ps.executeUpdate(); } } conn.commit(); System.out.println("插入数据"); ps.close(); conn.close(); // 关闭数据库连接 } catch (SQLException e) { System.out.println("插入数据失败" + e.getMessage()); try { conn.rollback(); } catch (Exception e1) { } } } public void update(HollistercoProduct product) { try { getConnection(); conn.setAutoCommit(false); boolean prodindb = false; String sql = "select * hollistercoproduct where productid=?"; // 插入数据的sql语句 PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if (rs.next()) { prodindb = true; } rs.close(); if (prodindb) { save(product); return; } sql = "update hollistercoproduct(productid, name, listprice, collection)" + " VALUES (?,?,?,?)"; // 插入数据的sql语句 ps = conn.prepareStatement(sql); ps.setInt(1, product.productid); ps.setString(2, product.name); ps.setFloat(3, product.listprice); ps.setString(4, product.data_collection); ps.executeUpdate(); // insert inventory if (product.inventoryList != null && product.inventoryList.size() > 0) { for (int i = 0; i < product.inventoryList.size(); i++) { Inventory inventory = product.inventoryList.get(i); sql = "INSERT INTO hollistercoproduct_inventory(name, seq,listprice,imgPrefix,longSku, itemSize,itemSeq,sku,cat,productid)" + " VALUES (?,?,?,?,?,?,?,?,?,?)"; // 插入数据的sql语句 ps = conn.prepareStatement(sql); ps.setString(1, inventory.name); ps.setString(2, inventory.seq); ps.setString(3, inventory.listprice); ps.setString(4, inventory.imgPrefix); ps.setString(5, inventory.longSku); ps.setString(6, inventory.itemSize); ps.setString(7, inventory.itemSeq); ps.setString(8, inventory.sku); ps.setString(9, inventory.cat); ps.setInt(10, product.productid); ps.executeUpdate(); // System.out.println("插入数据"); } } conn.commit(); ps.close(); conn.close(); // 关闭数据库连接 } catch (SQLException e) { System.out.println("插入数据失败" + e.getMessage()); try { conn.rollback(); } catch (Exception e1) { } } } public void delete(HollistercoProduct product) { getConnection(); } public HollistercoProduct find(HollistercoProduct product) { try { getConnection(); String sql = "select * hollistercoproduct where productid=?"; // 插入数据的sql语句 PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if (rs.next()) { return null; } // insert inventory if (product.inventoryList != null && product.inventoryList.size() > 0) { for (int i = 0; i < product.inventoryList.size(); i++) { Inventory inventory = product.inventoryList.get(i); sql = "INSERT INTO hollistercoproduct_inventory(name, seq,listprice,imgPrefix,longSku, itemSize,itemSeq,sku,cat,productid)" + " VALUES (?,?,?,?,?,?,?,?,?,?)"; // 插入数据的sql语句 ps = conn.prepareStatement(sql); ps.setString(1, inventory.name); ps.setString(2, inventory.seq); ps.setString(3, inventory.listprice); ps.setString(4, inventory.imgPrefix); ps.setString(5, inventory.longSku); ps.setString(6, inventory.itemSize); ps.setString(7, inventory.itemSeq); ps.setString(8, inventory.sku); ps.setString(9, inventory.cat); ps.setInt(10, product.productid); ps.executeUpdate(); // System.out.println("插入数据"); } } conn.commit(); ps.close(); conn.close(); // 关闭数据库连接 } catch (SQLException e) { System.out.println("插入数据失败" + e.getMessage()); try { conn.rollback(); } catch (Exception e1) { } } return null; } public boolean existIndb(int productid) { boolean returnkey = false; try { getConnection(); String sql = "select * from hollistercoproduct where productid=?"; // 插入数据的sql语句 PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, productid); ResultSet rs = ps.executeQuery(); if (rs.next()) { returnkey = true; } ps.close(); conn.close(); // 关闭数据库连接 } catch (SQLException e) { System.out.println("插入数据失败" + e.getMessage()); try { conn.rollback(); } catch (Exception e1) { } } return returnkey; } public static void main(String[] args) throws Exception { ProxyUtli.setProxy(true); // HollistercoMysqlDao dao = new HollistercoMysqlDao(); // SearchHollistercoJSP hollisterco = new SearchHollistercoJSP(); // List<HollistercoProduct> list = hollisterco // .getcustomerdiscountproductforJsp( // "http://www.hollisterco.com/webapp/wcs/stores/servlet/CategoryDisplay?parentCategoryId=13050&catalogId=10901&categoryId=78566&langId=-1&storeId=10051&topCategoryId=12202", // "1", "", ""); // for (int i = 0; i < list.size(); i++) { // HollistercoProduct product = list.get(i); // ParserHollistercoProduct ParserHollistercoProduct = new // ParserHollistercoProduct(product); // ParserHollistercoProduct.checkColorItemInventory(false); // dao.save(product); // } // HollistercoProduct product = dao.find(1048129); System.out.println(dao.existIndb(11226461)); } }
package xtrus.nhvan.mgr.nhmca.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.esum.appetizer.controller.AbstractController; import com.esum.appetizer.exception.ErrorCode; import com.esum.appetizer.vo.RestResult; import xtrus.nhvan.mgr.nhmca.service.NhIfInfoService; import xtrus.nhvan.mgr.nhmca.vo.NhIfInfo; @RestController public class NhIfInfoRestController extends AbstractController { @Autowired private NhIfInfoService baseService; /** * IF 문서 관리 - 중복검사 */ @RequestMapping(value = "/rest/c/nhvan/nhmca/nhIfInfoExist") public RestResult nhIfInfoExist(HttpServletRequest request) throws Exception { try { String ifId = request.getParameter("ifId"); boolean exist = baseService.exist(ifId); return new RestResult(ErrorCode.SUCCESS, exist); } catch (Exception e) { return new RestResult(e); } } /** * IF 문서 관리 - 등록 */ @RequestMapping(value = "/rest/c/nhvan/nhmca/nhIfInfoInsert") public RestResult nhIfInfoInsert(HttpServletRequest request) throws Exception { try { String ifId = request.getParameter("ifId"); String ifType = request.getParameter("ifType"); String useFlag = request.getParameter("useFlag"); String ioType = request.getParameter("ioType"); String ifClass = request.getParameter("ifClass"); String ifHandlerClass = request.getParameter("ifHandlerClass"); String ifDesc = request.getParameter("ifDesc"); NhIfInfo vo = new NhIfInfo(); vo.setIfId(ifId); vo.setIfType(ifType); vo.setUseFlag(useFlag); vo.setIoType(ioType); vo.setIfClass(ifClass); vo.setIfHandlerClass(ifHandlerClass); vo.setIfDesc(ifDesc); baseService.insert(vo); baseService.reload(ifId); // reload return new RestResult(ErrorCode.SUCCESS); } catch (Exception e) { return new RestResult(e); } } /** * IF 문서 관리 - 수정 */ @RequestMapping(value = "/rest/c/nhvan/nhmca/nhIfInfoUpdate") public RestResult nhIfInfoUpdate(HttpServletRequest request) throws Exception { try { String ifId = request.getParameter("ifId"); String ifType = request.getParameter("ifType"); String useFlag = request.getParameter("useFlag"); String ioType = request.getParameter("ioType"); String ifClass = request.getParameter("ifClass"); String ifHandlerClass = request.getParameter("ifHandlerClass"); String ifDesc = request.getParameter("ifDesc"); NhIfInfo vo = new NhIfInfo(); vo.setIfId(ifId); vo.setIfType(ifType); vo.setUseFlag(useFlag); vo.setIoType(ioType); vo.setIfClass(ifClass); vo.setIfHandlerClass(ifHandlerClass); vo.setIfDesc(ifDesc); baseService.update(vo); baseService.reload(ifId); // reload return new RestResult(ErrorCode.SUCCESS); } catch (Exception e) { return new RestResult(e); } } /** * IF 문서 관리 - 삭제 */ @RequestMapping(value = "/rest/c/nhvan/nhmca/nhIfInfoDelete") public RestResult nhIfInfoDelete(HttpServletRequest request) throws Exception { try { String ifId = request.getParameter("ifId"); baseService.delete(ifId); baseService.reload(ifId); // reload return new RestResult(ErrorCode.SUCCESS); } catch (Exception e) { return new RestResult(e); } } /** * IF 문서 관리 - 리로드 */ @RequestMapping(value = "/rest/c/nhvan/nhmca/nhIfInfoReload") public RestResult nhIfInfoReload(HttpServletRequest request) throws Exception { try { baseService.reload(null); // reload return new RestResult(ErrorCode.SUCCESS); } catch (Exception e) { return new RestResult(e); } } }
package componentes; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; public class TamanhoFixoJTextField extends PlainDocument { private int tamMax; private String permitir,padrao = "[^"; public TamanhoFixoJTextField(int tamMax, String permitir) { super(); this.tamMax = tamMax; this.permitir = permitir; } public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { if (str == null) { return; } //Define a condição para aceitar qualquer número de caracteres if (tamMax <= 0) { super.insertString(offset, str.toUpperCase().replaceAll(permitir, ""), attr); return; } int tam = (getLength() + str.length()); //Se o tamanho final for menor, chama insertString() aceitando a String if (tam <= tamMax) { super.insertString(offset, str.toUpperCase().replaceAll(permitir, ""), attr); } } }
package com.test.billing.dao; import com.test.billing.dao.mapper.AccountMapper; import com.test.billing.dao.model.Account; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.BindBean; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; /** * Created by denis.medvedev on 09.08.2016. */ @RegisterMapper(AccountMapper.class) public interface AccountDAO { @SqlUpdate("create table account (account_id bigint primary key, first_name character varying(128), second_name character varying(128), last_name character varying(128), cre_date timestamp without time zone)") void createAccountTable(); @SqlUpdate("drop table account") void dropAccountTable(); @SqlQuery("select count(*) from pg_catalog.pg_tables where tablename='account'") int checkAccountTable(); @SqlQuery("select * from account where account_id = :account_id") Account getAccountById(@Bind("account_id") Long account_id); @SqlUpdate("insert into account (account_id, first_name, second_name, last_name, cre_date) values (:accountId, :firstName, :secondName, :lastName, :creDate)") void insert(@BindBean Account account); @SqlUpdate("update account set account_id=:accountId, first_name=:firstName, second_name=:secondName, last_name=:lastName, cre_date=:creDate where account_id=:accountId") void update(@BindBean Account account); }
package com.atomix.sidrapulse; import com.atomix.customview.SidraTextView; import com.atomix.sidrainfo.SidraPulseApp; import android.os.Bundle; import android.text.util.Linkify; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.app.Activity; import android.content.Intent; import android.graphics.Color; public class AnnouncementDetailsActivity extends Activity implements OnClickListener { private Button btnBack; private Button btnMenu; private SidraTextView txtViewTitle; private SidraTextView txtViewType; private SidraTextView txtViewDateTime; private SidraTextView txtViewDescription; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_announcement_details); initViews(); setListener(); loadData(); } private void loadData() { if(getIntent().getExtras() != null) { int position = getIntent().getExtras().getInt("click_position"); txtViewTitle.setText(SidraPulseApp.getInstance().getAnnouncementsInfoList().get(position).getTitle().toString().trim()); Linkify.addLinks(txtViewTitle, Linkify.ALL); txtViewType.setText("Type: "+SidraPulseApp.getInstance().getAnnouncementsInfoList().get(position).getType().toString().trim()); if("OAM".equals(SidraPulseApp.getInstance().getAnnouncementsInfoList().get(position).getType())) { txtViewType.setTextColor(Color.parseColor("#2367B2")); } else if("CEMC".equals(SidraPulseApp.getInstance().getAnnouncementsInfoList().get(position).getType())) { txtViewType.setTextColor(Color.parseColor("#0C8943")); } else if("FLASH".equals(SidraPulseApp.getInstance().getAnnouncementsInfoList().get(position).getType())) { txtViewType.setTextColor(Color.parseColor("#C82828")); } txtViewDescription.setText(SidraPulseApp.getInstance().getAnnouncementsInfoList().get(position).getDescription().toString().trim()); Linkify.addLinks(txtViewDescription, Linkify.ALL); String dateAndTime = SidraPulseApp.getInstance().getAnnouncementsInfoList().get(position).getDayAndDate().toString().trim() +", "+SidraPulseApp.getInstance().getAnnouncementsInfoList().get(position).getTime().toString().trim(); txtViewDateTime.setText(dateAndTime); } } private void initViews() { btnBack = (Button) findViewById(R.id.btn_back); btnMenu = (Button) findViewById(R.id.btn_menu); txtViewTitle = (SidraTextView) findViewById(R.id.txt_view_title); txtViewType = (SidraTextView) findViewById(R.id.txt_view_type); txtViewDateTime = (SidraTextView) findViewById(R.id.txt_view_date_time); txtViewDescription = (SidraTextView) findViewById(R.id.txt_view_description); } private void setListener() { btnBack.setOnClickListener(this); btnMenu.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_back: onBackPressed(); break; case R.id.btn_menu: startActivity(new Intent(AnnouncementDetailsActivity.this, MainMenuActivity.class)); finish(); break; default: break; } } }
package gov.nih.mipav.model.scripting.actions; import gov.nih.mipav.model.scripting.*; import gov.nih.mipav.model.scripting.parameters.*; import gov.nih.mipav.model.structures.*; import gov.nih.mipav.view.*; import java.awt.*; /** * An action which extracts the imageB from a frame and puts it into a new image frame. */ public class ActionExtractImageB extends ActionImageProcessorBase { //~ Constructors --------------------------------------------------------------------------------------------------- /** * Constructor for the dynamic instantiation and execution of the script action. */ public ActionExtractImageB() { super(); } /** * Constructor used to record the script action line. * * @param input The image which was processed. * @param result The result image generated. */ public ActionExtractImageB(ModelImage input, ModelImage result) { super(input, result); } //~ Methods -------------------------------------------------------------------------------------------------------- /** * {@inheritDoc} */ public void insertScriptLine() { ParameterTable parameters = new ParameterTable(); try { parameters.put(createInputImageParameter(isScript)); storeImageInRecorder(recordingResultImage, isScript); } catch (ParserException pe) { MipavUtil.displayError("Error encountered creating input image parameter while recording " + getActionName() + " script action:\n" + pe); return; } ScriptRecorder.getReference().addLine(getActionName(), parameters); } /** * {@inheritDoc} */ public void scriptRun(ParameterTable parameters) { ModelImage clonedImage = null; ViewJFrameImage frame = parameters.getImage(INPUT_IMAGE_LABEL).getParentFrame(); try { clonedImage = (ModelImage) frame.getImageB().clone(); ModelLUT lutClone = null; lutClone = (ModelLUT) frame.getLUTb().clone(); new ViewJFrameImage(clonedImage, lutClone, new Dimension(610, 200), frame.getImageB().getLogMagDisplay()); System.gc(); ScriptRunner.getReference().getImageTable().storeImageName(clonedImage.getImageName()); } catch (OutOfMemoryError error) { if (clonedImage != null) { clonedImage.disposeLocal(); } clonedImage = null; System.gc(); MipavUtil.displayError("Out of memory: unable to open new frame"); return; } } }
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; public class Compressor { HashMap<String, Integer> table = new HashMap<>(); String sourceFile; String destinationFile; int nextVal = 0; /** * Constructor for the compressor class. * * @param originalFile * : Name of the file to be compressed * @param compressedFile * : Name of the zipped file */ public Compressor(String originalFile, String compressedFile) { this.sourceFile = originalFile; this.destinationFile = compressedFile; // Enter all symbols in the table for (char ch = 0; ch <= 255; ch++) { table.put(ch + "", nextVal); // System.out.println((ch + "") + nextVal); nextVal++; } } /** * Initiate compression * * @throws IOException */ public void startCompressing() throws IOException { char c; String s = null; int value; DataInputStream in = null; DataOutputStream out = null; Buffer12BitWriterClass bwc = null; try { in = new DataInputStream(new BufferedInputStream( new FileInputStream(sourceFile))); out = new DataOutputStream(new BufferedOutputStream( new FileOutputStream(destinationFile))); bwc = new Buffer12BitWriterClass(out); // s = ((char) (in.readByte() & 0x00FF) + ""); // This one below will also work byte b1 = in.readByte(); /* System.out.println(Integer.toHexString(b1 & 0x00FF) + " " + Integer.toBinaryString(b1 & 0x00FF));*/ int temp = (char) b1; s = ((char) (temp & 0x00FF)) + ""; while (true) { byte b2 = in.readByte(); /*System.out.println(Integer.toHexString(b2 & 0x00FF) + " " + Integer.toBinaryString(b2 & 0x00FF));*/ c = (char) (b2 & 0x00FF); // c = (char) (in.readByte() & 0x00FF); if (table.containsKey(s + c)) { s = s + c; } else { value = table.get(s); bwc.writeData(value); insertIntoTable(s + c, nextVal); s = c + ""; } } } catch (Exception e) { in.close(); } value = table.get(s); bwc.writeData(value); bwc.flush(); out.flush(); out.close(); } /** * Table insertion is not done in this as it is normally done. * * * @param key * @param value */ public void insertIntoTable(String key, int value) { if (value >= 4096) { // Array is full table = new HashMap<>(); nextVal = 0; for (char ch = 0; ch <= 255; ch++) { table.put(ch + "", nextVal); nextVal++; } } table.put(key, nextVal); nextVal++; } public static void main(String[] args) throws Exception { Compressor comp = new Compressor("access_log_Jul95.txt", "zippedlog.txt"); comp.startCompressing(); DeCompressor deComp = new DeCompressor("zippedlog.txt", "unzippedlog.txt"); deComp.startDecompressing(); /* * Compressor comp = new Compressor("words.html", "zippedWords.html"); * comp.startCompressing(); * * DeCompressor deComp = new DeCompressor("zippedWords.html", * "unzippedWords.html"); deComp.startDecompressing(); */ /*Compressor comp = new Compressor("shortwords.txt", "zippedShortWords.txt"); comp.startCompressing(); DeCompressor deComp = new DeCompressor("zippedShortWords.txt", "unzippedShortWords.txt"); deComp.startDecompressing();*/ /* * Compressor comp = new Compressor("CrimeLatLonXY1990.csv", * "zippedwords.csv"); comp.startCompressing(); DeCompressor deComp = * new DeCompressor("zippedwords.csv", "unzippedwords.csv"); * deComp.startDecompressing(); */ } }
package de.doctorintro.superjump; import org.bukkit.Bukkit; import org.bukkit.Location; public class LocationUtile { public String locationToString(Location loc){ return loc.getWorld().getName()+"*"+loc.getBlockX()+"*"+loc.getBlockY()+"*"+loc.getBlockZ()+"*"+loc.getPitch()+"*"+loc.getYaw(); } public Location stringToLocation(String loc, boolean direction){ String[] args = loc.split("\\*"); String world = args[0]; double x = Double.parseDouble(args[1]); double y = Double.parseDouble(args[2]); double z = Double.parseDouble(args[3]); float pitch = Float.parseFloat(args[4]); float yaw = Float.parseFloat(args[5]); Location loca = new Location(Bukkit.getWorld(world), x, y, z); if(direction){ loca.setPitch(pitch); loca.setYaw(yaw); } return loca; } }
package com.github.vitorm3lo.jbossplugin.forms; import com.github.vitorm3lo.jbossplugin.model.Instance; import com.intellij.ui.components.JBList; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.List; import java.util.stream.Collectors; public class EditServerDialog extends JDialog { private JPanel contentPane; private JButton buttonOK; private JList<String> serverList; private JButton editButton; private DefaultListModel<String> listModel; private Instance selectedInstance; public EditServerDialog(List<Instance> instances) { super.setMinimumSize(new Dimension(500, 300)); setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonOK); List<String> names = instances.stream().map(Instance::getServerName).collect(Collectors.toList()); listModel.addAll(names); editButton.addActionListener(e -> { for (Instance instance : instances) { if (instance.getServerName().equals(listModel.get(serverList.getSelectedIndex()))) { selectedInstance = instance; break; } } if (selectedInstance != null) { AddServerDialog dialog = new AddServerDialog(names, selectedInstance); Instance modifiedInstance = dialog.showDialog(); if (!selectedInstance.equals(modifiedInstance)) { selectedInstance.setServerName(modifiedInstance.getServerName()); selectedInstance.setDebugPort(modifiedInstance.getDebugPort()); selectedInstance.setServerPath(modifiedInstance.getServerPath()); selectedInstance.setDeployablePath(modifiedInstance.getDeployablePath()); List<String> newNames = instances.stream().map(Instance::getServerName).collect(Collectors.toList()); listModel.removeAllElements(); listModel.addAll(newNames); } } }); buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onOK(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } public void showDialog() { pack(); setLocationRelativeTo(null); setVisible(true); } private void onOK() { // add your code here if necessary dispose(); } private void createUIComponents() { listModel = new DefaultListModel<>(); serverList = new JBList<>(listModel); serverList.setDragEnabled(false); serverList.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION); } }
package com.haobi.okhttpdemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * 采用OkHttp框架,通过访问聚合API查询手机归属地 */ public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button sync_get; private Button async_get; private Button sync_post; private Button async_post; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sync_get = (Button)findViewById(R.id.sync_get); async_get = (Button)findViewById(R.id.async_get); sync_post = (Button)findViewById(R.id.sync_post); async_post = (Button)findViewById(R.id.async_post); textView = (TextView)findViewById(R.id.tv); sync_get.setOnClickListener(this); async_get.setOnClickListener(this); sync_post.setOnClickListener(this); async_post.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.sync_get: Sync_Get(); break; case R.id.sync_post: Sync_Post(); break; case R.id.async_get: Async_Get(); break; case R.id.async_post: Async_Post(); break; default: break; } } //同步请求-GET private void Sync_Get(){ //开启新线程来发起网络请求 new Thread(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://apis.juhe.cn/mobile/get?phone=13429667914&key=fef8795fcfa0a1977582d8c31b529112") .build(); Response response = null;//初始化 try { response = client.newCall(request).execute(); String responseData = response.body().string(); showResponse(responseData); } catch (IOException e) { e.printStackTrace(); } } }).start(); } //异步请求-GET private void Async_Get(){ new Thread(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://apis.juhe.cn/mobile/get?phone=13956676914&key=fef8795fcfa0a1977582d8c31b529112") .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Toast.makeText(MainActivity.this, "异步网络请求(GET)失败!", Toast.LENGTH_SHORT).show(); } @Override public void onResponse(Call call, Response response) throws IOException { String responseData = response.body().string(); showResponse(responseData); } }); } }).start(); } //同步请求-Post private void Sync_Post(){ new Thread(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder() .add("phone", "13852676914") .add("key", "fef8795fcfa0a1977582d8c31b529112") .build(); Request request = new Request.Builder() .url("http://apis.juhe.cn/mobile/get?") .post(requestBody) .build(); Response response = null;//初始化 try { response = client.newCall(request).execute(); String responseData = response.body().string(); showResponse(responseData); } catch (IOException e) { e.printStackTrace(); } } }).start(); } //异步请求-Post private void Async_Post(){ new Thread(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder() .add("phone", "13159476914") .add("key", "fef8795fcfa0a1977582d8c31b529112") .build(); Request request = new Request.Builder() .url("http://apis.juhe.cn/mobile/get?") .post(requestBody) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Toast.makeText(MainActivity.this, "异步网络请求(Post)失败!", Toast.LENGTH_SHORT).show(); } @Override public void onResponse(Call call, Response response) throws IOException { String responseData = response.body().string(); showResponse(responseData); } }); } }).start(); } private void showResponse(final String response){ //Android不允许在子线程中进行UI操作 //通过该方法可以将线程切换到主线程,然后再更新UI元素 runOnUiThread(new Runnable() { @Override public void run() { textView.setText(response); } }); } }
package dfs_ch05; import java.util.*; public class Ch05_04 { public static void main(String[] args) { recursive_function(1); } public static void recursive_function(int i) { if(i==100) { System.out.println(i+"번째 재귀함수에서"+(i+1)+"번째 재귀함수를 호출합니다."); recursive_function(i+1); System.out.println(i+"번 째 재귀함수를 종료합니다."); } } }
package fr.unice.polytech.isa.polyevent.cli.framework; import java.io.PrintStream; import java.util.Scanner; public class Context { public final Scanner scanner; public final PrintStream out; public final boolean echo; public Context(Scanner scanner, PrintStream out, boolean echo) { this.scanner = scanner; this.out = out; this.echo = echo; } }
package gradedGroupProject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ProfileImpl implements ProfileImplInterface{ private String name; private String address; private Date birthDate; public ProfileInterface createBankClientProfile() { System.out.println("Create Bank Client Profile"); try { provideClientInformation(); } catch(Exception e) { printErrorMessage(); } if(checkClientInformation()) { ProfileInterface newProfile = executeCreateBankClientProfileTransaction(); return newProfile; } else printErrorMessage(); return null; } public Profile executeCreateBankClientProfileTransaction() { return new Profile(name, address, birthDate); } public void provideClientInformation() throws ParseException { KeyInput KeyInput = new KeyInput(); name = KeyInput.read("full Name: "); address = KeyInput.read("full Address: "); birthDate = new SimpleDateFormat("dd/MM/yyyy").parse(KeyInput.read("Date of Birth in the format dd/MM/yyyy: ")); } public boolean checkClientInformation() { if(name == null || address == null || birthDate == null) return false; else return true; } public void printErrorMessage() { System.out.println(invalidInformation()); } public String invalidInformation() { return "Invalid Information Provided!"; } }
package common.amazon.jax; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class ItemLookupRequest { protected String condition; protected String deliveryMethod; protected String futureLaunchDate; protected String idType; protected String ispuPostalCode; protected String merchantId; protected BigInteger offerPage; protected List<String> itemId; protected List<String> responseGroup; protected BigInteger reviewPage; protected String reviewSort; protected String searchIndex; protected String searchInsideKeywords; protected BigInteger tagPage; protected BigInteger tagsPerPage; protected String tagSort; protected String variationPage; protected String relatedItemPage; protected List<String> relationshipType; /** * Gets the value of the condition property. * * @return * possible object is * {@link String } * */ public String getCondition() { return condition; } /** * Sets the value of the condition property. * * @param value * allowed object is * {@link String } * */ public void setCondition(String value) { this.condition = value; } /** * Gets the value of the deliveryMethod property. * * @return * possible object is * {@link String } * */ public String getDeliveryMethod() { return deliveryMethod; } /** * Sets the value of the deliveryMethod property. * * @param value * allowed object is * {@link String } * */ public void setDeliveryMethod(String value) { this.deliveryMethod = value; } /** * Gets the value of the futureLaunchDate property. * * @return * possible object is * {@link String } * */ public String getFutureLaunchDate() { return futureLaunchDate; } /** * Sets the value of the futureLaunchDate property. * * @param value * allowed object is * {@link String } * */ public void setFutureLaunchDate(String value) { this.futureLaunchDate = value; } /** * Gets the value of the idType property. * * @return * possible object is * {@link String } * */ public String getIdType() { return idType; } /** * Sets the value of the idType property. * * @param value * allowed object is * {@link String } * */ public void setIdType(String value) { this.idType = value; } /** * Gets the value of the ispuPostalCode property. * * @return * possible object is * {@link String } * */ public String getISPUPostalCode() { return ispuPostalCode; } /** * Sets the value of the ispuPostalCode property. * * @param value * allowed object is * {@link String } * */ public void setISPUPostalCode(String value) { this.ispuPostalCode = value; } /** * Gets the value of the merchantId property. * * @return * possible object is * {@link String } * */ public String getMerchantId() { return merchantId; } /** * Sets the value of the merchantId property. * * @param value * allowed object is * {@link String } * */ public void setMerchantId(String value) { this.merchantId = value; } /** * Gets the value of the offerPage property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getOfferPage() { return offerPage; } /** * Sets the value of the offerPage property. * * @param value * allowed object is * {@link BigInteger } * */ public void setOfferPage(BigInteger value) { this.offerPage = value; } /** * Gets the value of the itemId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the itemId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getItemId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getItemId() { if (itemId == null) { itemId = new ArrayList<String>(); } return this.itemId; } /** * Gets the value of the responseGroup property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the responseGroup property. * * <p> * For example, to add a new item, do as follows: * <pre> * getResponseGroup().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getResponseGroup() { if (responseGroup == null) { responseGroup = new ArrayList<String>(); } return this.responseGroup; } /** * Gets the value of the reviewPage property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getReviewPage() { return reviewPage; } /** * Sets the value of the reviewPage property. * * @param value * allowed object is * {@link BigInteger } * */ public void setReviewPage(BigInteger value) { this.reviewPage = value; } /** * Gets the value of the reviewSort property. * * @return * possible object is * {@link String } * */ public String getReviewSort() { return reviewSort; } /** * Sets the value of the reviewSort property. * * @param value * allowed object is * {@link String } * */ public void setReviewSort(String value) { this.reviewSort = value; } /** * Gets the value of the searchIndex property. * * @return * possible object is * {@link String } * */ public String getSearchIndex() { return searchIndex; } /** * Sets the value of the searchIndex property. * * @param value * allowed object is * {@link String } * */ public void setSearchIndex(String value) { this.searchIndex = value; } /** * Gets the value of the searchInsideKeywords property. * * @return * possible object is * {@link String } * */ public String getSearchInsideKeywords() { return searchInsideKeywords; } /** * Sets the value of the searchInsideKeywords property. * * @param value * allowed object is * {@link String } * */ public void setSearchInsideKeywords(String value) { this.searchInsideKeywords = value; } /** * Gets the value of the tagPage property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getTagPage() { return tagPage; } /** * Sets the value of the tagPage property. * * @param value * allowed object is * {@link BigInteger } * */ public void setTagPage(BigInteger value) { this.tagPage = value; } /** * Gets the value of the tagsPerPage property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getTagsPerPage() { return tagsPerPage; } /** * Sets the value of the tagsPerPage property. * * @param value * allowed object is * {@link BigInteger } * */ public void setTagsPerPage(BigInteger value) { this.tagsPerPage = value; } /** * Gets the value of the tagSort property. * * @return * possible object is * {@link String } * */ public String getTagSort() { return tagSort; } /** * Sets the value of the tagSort property. * * @param value * allowed object is * {@link String } * */ public void setTagSort(String value) { this.tagSort = value; } /** * Gets the value of the variationPage property. * * @return * possible object is * {@link String } * */ public String getVariationPage() { return variationPage; } /** * Sets the value of the variationPage property. * * @param value * allowed object is * {@link String } * */ public void setVariationPage(String value) { this.variationPage = value; } /** * Gets the value of the relatedItemPage property. * * @return * possible object is * {@link String } * */ public String getRelatedItemPage() { return relatedItemPage; } /** * Sets the value of the relatedItemPage property. * * @param value * allowed object is * {@link String } * */ public void setRelatedItemPage(String value) { this.relatedItemPage = value; } /** * Gets the value of the relationshipType property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the relationshipType property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRelationshipType().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getRelationshipType() { if (relationshipType == null) { relationshipType = new ArrayList<String>(); } return this.relationshipType; } }
package 数据结构.线性结构.队列; /** * Created by Yingjie.Lu on 2018/8/30. */ /** * @Title: 链式存储_队列 * @Date: 2018/8/30 14:12 */ public class MyLinkedQueue { private Node front;//指向队头节点 private Node rear;//指向队尾节点 private int size=0; /** * @Title: 定义一个元素 * @Date: 2018/8/30 15:44 */ private class Node{ Object data;//数据 Node next;//下一个元素的地址 Node(Object o){ this.data=o; } } /** * @Title: 入队 * @Date: 2018/8/30 15:55 */ public void offer(Object o){ Node node=new Node(o); if(size==0){ front=node; rear=node; }else { rear.next=node; rear=node; } size++; } /** * @Title: 出队 * @Date: 2018/8/30 15:55 */ public Object poll(){ if(size==0){ return null; } Node node=front.next;//保存下一个节点的地址 Node needReturn=front;//保存要出队的元素 front.next=null;//将队头的节点删除(即吧队头的next设为null) front=node;//front指向保存的下一个节点 size--; return needReturn.data; } /** * @Title: 判断队列是否为空 * @Date: 2018/8/30 15:56 */ public boolean isEmpty(){ if(size==0){ return true; }else { return false; } } public static void main(String[] args) { MyLinkedQueue myLinkedQueue=new MyLinkedQueue(); //入队10个元素 for(int i=0;i<10;i++){ myLinkedQueue.offer(i); } //出队5个元素 for(int i=0;i<5;i++){ myLinkedQueue.poll(); // System.out.println(myArrayQueue.poll()); } //再入队5个元素 for(int i=20;i<25;i++){ myLinkedQueue.offer(i); } //再全部出队 while(!myLinkedQueue.isEmpty()){ System.out.println(myLinkedQueue.poll()); } } }
package ch08; public class DataSet { private double sum; private Object maximum; private int count; private IMeasurer measurer; public DataSet(IMeasurer m) { sum = 0; count = 0; maximum = null; measurer = m; } public void add(Object o) { sum += measurer.measure(o); if(count == 0 || measurer.measure(maximum) < measurer.measure(o)){ maximum = o; } count ++; } public double getAverage() { if (count == 0) { return 0; } else { return sum / count; } } public Object getMaximum() { return maximum; } }
public class Range { private double lowerBound; private double upperBound; public Range(double lower, double upper) { lowerBound = lower; upperBound = upper; } public Range() {} public boolean inRange(double x) { if (x >= lowerBound && x < upperBound) { return true; } return false; } public double getLowerBound() { return lowerBound; } public void setLowerBound(double lowerBound) { this.lowerBound = lowerBound; } public double getUpperBound() { return upperBound; } public void setUpperBound(double upperBound) { this.upperBound = upperBound; } }
package com.project; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; //scan the project's packages for specific components @SpringBootApplication @EntityScan("com.project.entities") @EnableMongoRepositories("com.project.repos") @ComponentScan(basePackages = { "com" }) public class SeProjectApplication { public static void main(String[] args) { SpringApplication.run(SeProjectApplication.class, args); } }
package com.programapprentice.app; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * User: program-apprentice * Date: 8/17/15 * Time: 10:12 PM * Finished Time: 11:00 PM */ /** Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will be positive integers. Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). The solution set must not contain duplicate combinations. For example, given candidate set 2,3,6,7 and target 7, A solution set is: [7] [2, 2, 3] * */ public class CombinationSum_39 { public List<List<Integer>> combinationStep(int[] candidates, int target, int minimum) { List<List<Integer>> output = new ArrayList<List<Integer>>(); if(target < 0) { return output; } for(int i = 0; i < candidates.length; i++) { if(candidates[i] < minimum) { // avoid 2 3 2 for 7 continue; } if(i > 0 && candidates[i] == candidates[i-1]) { continue; } if(target == candidates[i]) { List<Integer> elem = new ArrayList<Integer>(); elem.add(candidates[i]); output.add(elem); break; } else if (target > candidates[i]) { List<List<Integer>> items = combinationStep(candidates, target - candidates[i], candidates[i]); if(!items.isEmpty()) { for (List<Integer> l : items) { List<Integer> lc = new ArrayList<Integer>(l); lc.add(0, candidates[i]); output.add(lc); } } } else { break; } } return output; } public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); return combinationStep(candidates, target, 0); } }
package com.nowcoder.community.service; import com.nowcoder.community.dao.LoginTicketMapper; import com.nowcoder.community.entity.LoginTicket; import com.nowcoder.community.entity.User; import com.nowcoder.community.dao.UserMapper; import com.nowcoder.community.util.CommunityConstant; import com.nowcoder.community.util.CommunityUtil; import com.nowcoder.community.util.MailClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Random; @Service public class UserService extends CommunityUtil { @Autowired private UserMapper userMapper; @Autowired private MailClient mailClient; @Autowired private TemplateEngine templateEngine; @Autowired private LoginTicketMapper loginTicketMapper; @Value("${community.path.domain}") private String domain; @Value("${server.servlet.context-path}") private String contextPath; public User findUserById(int id){ return userMapper.selectById(id); } public User findUserByName(String name){ return userMapper.selectByName(name); } public User selectByEmail(String email){ return userMapper.selectByEmail(email); } /** * * @param user * @return */ public Map<String,Object> register(User user){ Map<String,Object> map = new HashMap<>(); //空值处理 //邮箱被注册: if(user == null) throw new IllegalArgumentException("参数不能为空!"); if(StringUtils.isEmpty(user.getUsername())) { map.put("usernameMsg","账号不能为空"); return map; } if(StringUtils.isEmpty(user.getPassword())) { map.put("passwordMsg","账号密码不能为空"); return map; } if(StringUtils.isEmpty(user.getEmail())) { map.put("usernameMsg","账号邮箱不能为空"); return map; } //观察注册信息是否重复 User u = userMapper.selectByName(user.getUsername()); if(u!=null){ map.put("registerMsg","账号已经注册"); return map; } user.setType(0); user.setSalt(CommunityUtil.generateUUID().substring(0,3)); user.setPassword(CommunityUtil.md5(user.getPassword()+user.getSalt())); //设置用户头象 //http://images.nowcoder.com/head/%dt.png user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000))); user.setStatus(0); user.setActivationCode(CommunityUtil.generateUUID()); //注册用户: userMapper.insertUser(user); //更新插入user user = userMapper.selectByEmail(user.getEmail()); Context context = new Context(); System.err.println(domain); String url = domain+contextPath+"/activation/"+user.getId()+"/"+CommunityUtil.generateUUID(); context.setVariable("name",user.getEmail()); context.setVariable("url",url); String html = templateEngine.process("mail/activation",context); mailClient.sendEmail(user.getEmail(),"激活账户",html); return map; } /** * 判断激活是否成功 * @param userId * @param code * @return */ public int activation(int userId,String code){ User user = userMapper.selectById(userId); if(user.getStatus()==1) return CommunityConstant.ACTIVATION_REPEAT; else if(user.getActivationCode()==code){ //1代表有效 userMapper.updateUserStatus(1,userId); return CommunityConstant.ACTIVATION_SUCCESS; }else{ return CommunityConstant.ACTIVATION_FAILURE; } } /** * 登陆功能只需要账号和密码和过期时间 * @param username * @param password * @param expiredSeconds * @return */ //service 主要生成每次业务结果,controller每次根据service生成页面 public Map<String,Object> login(String username,String password,int expiredSeconds){ Map<String,Object> map = new HashMap<>(); //判断username是否是空值 if(StringUtils.isEmpty(username)){ map.put("usernameMsg","账号不能为空"); return map; } //判断password是否是空值。 if(StringUtils.isEmpty(password)){ map.put("passwordMsg","账号密码不能为空"); return map; } //验证账号: User user = userMapper.selectByName(username); if (user == null){ map.put("usernameMsg","账号不存在"); return map; } //验证状态 if(user.getStatus()==0){ map.put("usernameMsg","该账号未激活"); return map; } //验证密码 password = CommunityUtil.md5(password+user.getSalt()); if (!user.getPassword().equals(password)){ map.put("usernameMsg","该账号密码错误"); return map; } //登录,生称登陆的ticket,返回给浏览器, // 下面浏览器每次访问服务器都会携带包含ticket cookie //服务器会从服务器里去查,你的时间没有过期,我就默认你是登陆的 LoginTicket loginTicket = new LoginTicket(); loginTicket.setUserId(user.getId()); loginTicket.setTicket(CommunityUtil.generateUUID()); loginTicket.setStatus(0); //0为有效 loginTicket.setExpired(new Date(System.currentTimeMillis()+expiredSeconds*1000)); loginTicketMapper.insertLoginTicket(loginTicket); map.put("ticket",loginTicket.getTicket()); return map; } /** * 登出 * @param ticket */ public void logout(String ticket){ loginTicketMapper.updateStatus(ticket,1); } /** * 获取t票 * @param ticket * @return */ public LoginTicket getLoginTicketByTicket(String ticket){ return loginTicketMapper.selectByTicket(ticket); } /** * 修改头像路径 * @param userId * @param headerUrl */ public void updateHeaderUrl(int userId,String headerUrl){ userMapper.updateUserHead(headerUrl,userId); } public void updatePassword(int userId,String password){ userMapper.updateUserPassword(password,userId); } }
package com.cloudinte.modules.upload.web; import java.util.List; import com.cloudinte.modules.upload.web.ChunkUploadService.UploadStatus; import com.google.common.collect.Lists; public class ResultVo { /** 文件上传状态 */ private UploadStatus uploadStatus; /** 未上传的片段 */ private List<Integer> missChunks = Lists.newArrayList(); public ResultVo(UploadStatus uploadStatus) { this.uploadStatus = uploadStatus; } public ResultVo(UploadStatus uploadStatus, List<Integer> missChunks) { this(uploadStatus); this.missChunks = missChunks; } public List<Integer> getMissChunks() { return missChunks; } public void setMissChunks(List<Integer> missChunks) { this.missChunks = missChunks; } public UploadStatus getUploadStatus() { return uploadStatus; } public void setUploadStatus(UploadStatus uploadStatus) { this.uploadStatus = uploadStatus; } }
package com.myvodafone.android.front.helpers; import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; /** * Created by p.koutsias on 2/3/2016. */ public class ExpandAnimation extends Animation { private int baseHeight; private int delta; private View view; public ExpandAnimation(View v, int startHeight, int endHeight) { baseHeight = startHeight; delta = endHeight - startHeight; view = v; view.getLayoutParams().height = startHeight; view.requestLayout(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); if (interpolatedTime < 1.0f) { int val = baseHeight + (int) (delta * interpolatedTime); view.getLayoutParams().height = val; view.requestLayout(); } else { int val = baseHeight + delta; view.getLayoutParams().height = val; view.requestLayout(); } } }
package expansion.neto.com.mx.jefeapp.cameraApi2; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.Toast; import expansion.neto.com.mx.jefeapp.R; public class Lienzo extends View { public static boolean bandera_logo; private static Path drawPath; // trazo del que vamos pintando private static Paint drawPaint, canvasPaint; // es como el pincel, private static int paintColor = 0xFFFA7E0A; //color inicial private static Canvas drawCanvas; //lienzo, fondo private static Bitmap canvasBitmap; //tipo de archivo par apoder guardarlo float touchX; float touchY; private float iniciotouchX ; private float iniciotouchY ; int anchoNuevo, altoNuevo; //marquesina Bitmap marco; float xMarco; int xMArcoInt; Bitmap marco2; public Lienzo(Context context, AttributeSet attrs) { super(context, attrs); setUpDrawing(); marco = BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.marquesina2_foreground); marco = Bitmap.createScaledBitmap(marco, 600, 150, true); } private static void setUpDrawing() { drawPath = new Path(); drawPaint = new Paint(); drawPaint.setColor(paintColor); drawPaint.setAntiAlias(true); drawPaint.setStrokeWidth(7); drawPaint.setStyle(Paint.Style.STROKE); //pintar solo bordes, trazos drawPaint.setStrokeJoin(Paint.Join.ROUND); //pintura sera redondeada drawPaint.setStrokeCap(Paint.Cap.ROUND); canvasPaint = new Paint(Paint.DITHER_FLAG); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { //cambioTamanio(canvasBitmap, w,h,0.9f); //super.onSizeChanged(anchoNuevo, altoNuevo, anchoNuevo, altoNuevo); //Toast.makeText(getContext(), "w: "+w +" h:"+ h, Toast.LENGTH_SHORT).show(); super.onSizeChanged(w, h, oldw, oldh); //canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); //drawCanvas = new Canvas(canvasBitmap); //Toast.makeText(getContext(), "ancho: "+ canvasBitmap.getWidth()+ " alto:"+canvasBitmap.getHeight(), Toast.LENGTH_SHORT).show(); if (FragmentEditPhoto.width <= 400 && FragmentEditPhoto.height <= 400){ canvasBitmap = Bitmap.createScaledBitmap(canvasBitmap, 240, 240, true); }else if (FragmentEditPhoto.width <= 500){ canvasBitmap = Bitmap.createScaledBitmap(canvasBitmap, 450, 450, true); }else{ canvasBitmap = Bitmap.createScaledBitmap(canvasBitmap, 1100, 1100, true); } Bitmap mutableBitmap = canvasBitmap.copy(Bitmap.Config.ARGB_8888, true); drawCanvas = new Canvas(mutableBitmap); drawCanvas.setBitmap(mutableBitmap); } public void cambioTamanio(Bitmap b, int w, int h, float porcentajeABajar){ float w2, h2; anchoNuevo = w; altoNuevo = h; if(b.getWidth() > w || b.getHeight() > h){ w2 = b.getWidth() * porcentajeABajar; h2 = b.getHeight() * porcentajeABajar; if(w2 > w || h2 > h){ cambioTamanio(b, w, h, (porcentajeABajar - 0.1f)); }else{ anchoNuevo = Math.round(w2); altoNuevo = Math.round(h2); } }else{ anchoNuevo = w; altoNuevo = h; } } @Override public boolean onTouchEvent(MotionEvent event) { touchX = event.getX(); touchY = event.getY(); bandera_logo = true; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: drawPath.moveTo(touchX, touchY); iniciotouchX = touchX; iniciotouchY = touchY; break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: xMarco = touchX - iniciotouchX ; xMArcoInt = Math.round(xMarco); break; default: return false; } invalidate(); return true; } @Override protected void onDraw(Canvas canvas) { canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint); canvas.drawPath(drawPath, drawPaint); canvas.drawRect(iniciotouchX, iniciotouchY, touchX, touchY,drawPaint); System.out.println( "tamaños: " + iniciotouchX + " "+ touchX +" "+ iniciotouchY +" "+ touchY ); if ((touchX - iniciotouchX) <= 200 /*|| (touchY - iniciotouchY) <= 100 */){ bandera_logo = false; } xMArcoInt = xMArcoInt <1 ? 1: xMArcoInt; marco2 = Bitmap.createScaledBitmap(marco, xMArcoInt, 150, true); canvas.drawBitmap(marco2, iniciotouchX, iniciotouchY, drawPaint); } //actualiza color public void setColor(String newColor) { invalidate(); paintColor = Color.parseColor(newColor); drawPaint.setColor(paintColor); } public static void setBitmap( Bitmap bitmap){ canvasBitmap = bitmap; setUpDrawing(); } }
package heapAreaAnay; /** * Created by Administrator on 2018-7-15 0015. */ public class BigObjectEnterOldGen { private static final int _1MB = 1024 * 1024; /** * * -verbose:gc -Xms20M -Mmx20M -Xmn10M -XX:+printGCDetails -XX:SurvivorRatio=8 -XX:PretenureSizeThreshold=3145728 * 总共堆大小20M * 新生代10M,老年代10M * 在新生代的10M中有,edan:8M,两个suv各1M,也就是新生代可用空间可用的共有9M, * 因为新生代采用的复制算法,所以总会有一部分空间是不可用的,那一部分就是suv的空间1M * * 在分配大对象时,新生代中连续空间不足的可能性更大,更容易发生gc,同时发生gc后,对象在edan和suvisor中来回复制消耗性能。 * 为了防止这些情况发生,通过设置参数PretenureSizeThreshold,可以将大小大于PretenureSizeThreshold的对象直接放到老年代中,(所谓直接的意思就是进入老年代的条件不同了,不用等到新生代装不下了才会放进老年代,只要对象大小的条件满足了,就放进去了) * 避免了新生代的上述问题, * 但是,如果这个大对象,是朝生夕灭的话,那么他在老年代真的很浪费空间,因为老年代中的对象不会轻易被gc掉,只有老年代不足的时候,才会发生老年代的gc。 * * @param args */ public static void main(String[] args){ byte[] allocation1; allocation1 = new byte[4 * _1MB]; //因为这个对象大于指定的3M,所以这个对象会直接放到老年代中,不会发生gc。 } }
package iit.android.swarachakra; import android.content.Context; import android.content.res.AssetManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.util.Log; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Properties; import java.util.Set; public class KeyLogger { private static long uploadFreq = 7 * 24 * 60; // every 6 days private static long uploadtimestamp = 0; private static String stringUrl; private static String map; private static String language; public final String TAG = "logger"; private HashMap<String, Integer> ht; public String extractedText; private SoftKeyboard mSoftKeyboard; private Context mContext; String draft_msg = ""; public KeyLogger(Context context) { mContext = context; map = mContext.getString(R.string.logger_map); language = mContext.getString(R.string.logger_language); if (BuildConfig.DEBUG) { stringUrl = context.getString(R.string.logger_url_beta); } else { AssetManager assetManager = context.getAssets(); try { InputStream inputStream = assetManager.open("prod.properties"); Properties properties = new Properties(); properties.load(inputStream); stringUrl = properties.getProperty("loggingUrl"); Log.d(TAG, "loggingUrl : " + stringUrl); } catch (IOException e) { throw new IllegalStateException("prod.properties file not found in assets"); } stringUrl = context.getString(R.string.logger_url_production); } } public void setSoftKeyboard(SoftKeyboard softKeyboard) { mSoftKeyboard = softKeyboard; } public void writeToLocalStorage() { String str = extractedText; readMap(map); Log.d(TAG, "Map read into file done"); // break text into words String[] words; try { if (str.isEmpty() || str.length() <= 0) { Log.d(TAG, "Nothing to save"); return; } words = str.split(" "); } catch (Exception ex) { Log.d(TAG, ex.getCause().toString()); return; } // trim space, punctuation marks or perhaps let the server do it // str.replaceAll(".", ""); // str.trim(); // Insert-update into db / write to storage // Log.d(TAG,"About to read map"); for (int i = 0; i < words.length; i++) { // Log.d(TAG,"word: "+words[i]); addToMap(words[i]); } Log.d(TAG, "Done adding map"); writeMapToFile(); Log.d(TAG, "Done writing map"); // uploadFile(); long tmpTS = System.currentTimeMillis(); Log.d(TAG, "uploadTS" + uploadtimestamp + ", current TS " + tmpTS); if (uploadtimestamp == 0) { uploadtimestamp = tmpTS; Log.d(TAG, "No upload"); } else if ((tmpTS - uploadtimestamp) / (60 * 1000) >= uploadFreq) { // uploadtimestamp=tmpTS; //uploadToServer(); } else { Log.d(TAG, "No upload"); } // set the dirty flag } @SuppressWarnings("unchecked") public void readMap(String filename) { /* * File file = new File(map); * * if(file.exists()==false){ //create a new hash map * Log.d(TAG,"--hash map empty. create new"); ht=new HashMap(); * * } */ // else // { // Load from file into ht Log.d(TAG, "Load from file."); try { /* * ht = new Hashtable<Integer, ArrayList<Deck>>(); FileInputStream * myIn = context.openFileInput(FLASHCARDS_FILENAME); * ObjectInputStream IS = new ObjectInputStream(myIn); * Toast.makeText(context, "here", Toast.LENGTH_SHORT).show(); */ ht = new HashMap<String, Integer>(); // File file = new File(getExternalFilesDir(null), map); FileInputStream myIn = mSoftKeyboard.openFileInput(filename); ObjectInputStream IS = new ObjectInputStream(myIn); try { // temp = (Hashtable<Integer, ArrayList<Deck>>)IS.readObject(); // IS. HashMap<String, Integer> readObject = (HashMap<String, Integer>) IS .readObject(); ht = readObject; Set<String> tmpSet = ht.keySet(); Object[] tmpArray = (Object[]) tmpSet.toArray(); // Log.d(TAG,"map length:"+tmpArray.length); for (int i = 0; i < tmpArray.length; i++) { Log.d(TAG, i + "-key:" + (String) tmpArray[i] + ", value: " + ht.get(tmpArray[i])); } IS.close(); myIn.close(); // Log.d(TAG,"Map ready for use"); } catch (Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); Log.d(TAG, "Some exception trying to read map"); Log.d(TAG, e.getMessage()); } // IS.close(); // testing purposes /* * for (int i = 0; i < temp.size(); i++) { for (int p = 0; p < * temp.get(i).size(); p++) { for (int q = 0; q < * temp.get(i).get(p).getDeck().size(); q++) { * Toast.makeText(context, * temp.get(i).get(p).getDeck().get(q).getQuestion(), * Toast.LENGTH_LONG).show(); } } } */ } catch (IOException e) { // e.printStackTrace(); Log.d(TAG, e.getMessage()); // Toast.makeText(context, "here", Toast.LENGTH_SHORT).show(); } // } //else // } } public void addToMap(String key) { boolean setUUIDValues = false; // if map empty just add the entry // chk if the value exists try { if (ht.isEmpty() == true) { // put in the unique install identifier we generated, hardware // serial no. SERIAL and the 64-bit ANDROID_ID value setUUIDValues = true; } if ((ht.isEmpty() == false && ht.containsKey(key) == true)) { // if it does, increment its count Integer c = ht.get(key); // Log.d(TAG,"Map not empty and "+key+ "found wid freq "+c); ht.put(key, c + 1); // Log.d(TAG,key+ " frequency now "+ht.get(key)); } else { // list must be empty or key not found, insert the key // Log.d(TAG,"Map empty or key found"); ht.put(key, 1); } if (setUUIDValues == true) { // Unique identifiers ht.put(Installation.id(mSoftKeyboard.getApplicationContext()).toString(), -1); ht.put(android.os.Build.SERIAL, -2); ht.put(android.provider.Settings.Secure.ANDROID_ID, -3); ht.put(language, -4); } } catch (Exception ex) { Log.d(TAG, ex.getCause().toString()); } // Log.d(TAG,"Map length after adding 1 more key "+ht.size()); // else, add it to the map with count 1 // ht.put(key, value); } @SuppressWarnings("finally") public String uploadFile() { /* * try{ * * }catch(Exception e){ Log.d(TAG,e.getMessage()); } */ HttpURLConnection connection = null; DataOutputStream outputStream = null; String pathToOurFile = map; String urlServer = stringUrl; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String serverResponseMessage = "Upload failed"; try { FileInputStream fileInputStream = new FileInputStream( mSoftKeyboard.getBaseContext().getFileStreamPath(pathToOurFile)); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // Enable POST method connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream .writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); serverResponseMessage = connection.getResponseMessage(); fileInputStream.close(); outputStream.flush(); outputStream.close(); Log.d(TAG, "resp code: " + serverResponseCode + " , resp string: " + serverResponseMessage); if (serverResponseCode == 200 || serverResponseMessage.contains("ok")) { Log.d(TAG, "Delete the file " + map); long tmpTS = System.currentTimeMillis(); uploadtimestamp = tmpTS; deleteNamedFile(map); } } catch (Exception ex) { // Exception handling Log.d(TAG, ex.getMessage()); } finally { return serverResponseMessage; } } @SuppressWarnings("unused") public boolean hasExternalStoragePrivateFile(String fName) { // Get path for the file on external storage. If external // storage is not currently mounted this will fail. File file = new File(mSoftKeyboard.getExternalFilesDir(null), fName); if (file != null) { return file.exists(); } return false; } public void writeMapToFile() { try { FileOutputStream fos = mSoftKeyboard.openFileOutput(map, Context.MODE_PRIVATE); ObjectOutputStream osw = new ObjectOutputStream(fos); osw.writeObject(ht); osw.flush(); fos.close(); osw.close(); } catch (FileNotFoundException e) { Log.d(TAG, e.getMessage()); } catch (IOException e) { Log.d(TAG, e.getMessage()); } } // deleteFile public void deleteNamedFile(String filename) { try { File file = mSoftKeyboard.getBaseContext().getFileStreamPath(filename); boolean status = file.delete(); if (status) Log.d(TAG, "Deleted " + filename); else Log.d(TAG, "Couldnt delete " + filename); } catch (Exception e) { Log.d(TAG, e.getMessage()); } } // when connection available, upload to the server public void uploadToServer() { Log.d(TAG, "Connecting to " + stringUrl); try { ConnectivityManager connMgr = (ConnectivityManager) mSoftKeyboard.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { Log.d(TAG, networkInfo.getTypeName()); Log.d(TAG, networkInfo.getSubtypeName()); Log.d(TAG, networkInfo.toString()); Log.d(TAG, "Apparently nw is available"); new SendStatsTask().execute(stringUrl); } else { Log.d(TAG, "No network connection available."); connMgr.setNetworkPreference(ConnectivityManager.TYPE_MOBILE); if (connMgr.getActiveNetworkInfo().isConnected()) { Log.d(TAG, "Using mobile data"); new SendStatsTask().execute(stringUrl); } Log.d(TAG, "No go for mobile data either"); } } catch (Exception e) { Log.d(TAG, e.getMessage()); } // if successful delete local data } // Given a URL, establishes an HttpUrlConnection and retrieves // the web page content as a InputStream, which it returns as // a string. // Uses AsyncTask to create a task away from the main UI thread. This task // takes a // URL string and uses it to create an HttpUrlConnection. Once the // connection // has been established, the AsyncTask downloads the contents of the webpage // as // an InputStream. Finally, the InputStream is converted into a string, // which is // displayed in the UI by the AsyncTask's onPostExecute method. public class SendStatsTask extends AsyncTask<String, Void, String> { // @Override protected String doInBackground(String... urls) { Log.d(TAG, "In thread..trying to connect..sending-"); return uploadFile(); } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { Log.d(TAG, "Result returned"); if (result.isEmpty()) { Log.d(TAG, "Result string empty"); return; } if (result.contains("ok:200")) { Log.d(TAG, "Delete log file"); deleteNamedFile(map); } } } }
package be.openclinic.util; import java.util.Comparator; public class ClusterDataSortByGravity implements Comparator{ public int compare(Object arg0, Object arg1) { // TODO Auto-generated method stub return new Double(((ClusterData)arg1).getGravity()-((ClusterData)arg0).getGravity()).intValue(); } }
package com.abt.middle.global; /** * @描述: @全局常量 * @作者: @黄卫旗 * @创建时间: @2018-03-10 */ public class GlobalConstant { public static final String FILE_PROVIDER = ".fileProvider"; public static final String MEDIA_INFO = "mediaInfo"; public static final String MEDIA = "media"; public static final String TYPE = "type"; public static final int REQUEST_CODE_LIVE = 1; public static final int REQUEST_CODE_GALLERY = 2; public static final String SETTING_ACTION = "android.settings.APPLICATION_DETAILS_SETTINGS"; public static final String PACKAGE = "package"; }
/* ==================================================================== * * Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved. * * ==================================================================== * */ package com.aof.component.domain.party; import java.io.Serializable; /** * @author xxp * @version 2003-6-24 * */ public class RoleType implements Serializable { private String roleTypeId; private String description; /** * @return */ public String getDescription() { return description; } /** * @return */ public String getRoleTypeId() { return roleTypeId; } /** * @param string */ public void setDescription(String string) { description = string; } /** * @param string */ public void setRoleTypeId(String string) { roleTypeId = string; } }
package vista; import controlador.MiFuncion; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import modelo.Curso; /** * * @author Jonathan Pacheco R. * @version 0.1 * */ public class AgregarCurso extends javax.swing.JFrame { Curso cur = new Curso(); public AgregarCurso() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); txtf_nombre_curso = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); spn_creditos = new javax.swing.JSpinner(); btn_agregar = new javax.swing.JButton(); btn_cancelar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Myriad Pro", 0, 24)); // NOI18N jLabel1.setText("Agregar curso"); jLabel2.setFont(new java.awt.Font("Myriad Pro", 0, 13)); // NOI18N jLabel2.setText("Nombre del curso::"); txtf_nombre_curso.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N txtf_nombre_curso.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtf_nombre_cursoActionPerformed(evt); } }); jLabel8.setFont(new java.awt.Font("Myriad Pro", 0, 13)); // NOI18N jLabel8.setText("Créditos:"); spn_creditos.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N spn_creditos.setModel(new javax.swing.SpinnerNumberModel(0, 0, 20, 1)); btn_agregar.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N btn_agregar.setText("AGREGAR"); btn_agregar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 204, 102))); btn_agregar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_agregarActionPerformed(evt); } }); btn_cancelar.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N btn_cancelar.setText("CANCELAR"); btn_cancelar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 0, 0))); btn_cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_cancelarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel8) .addComponent(jLabel1) .addComponent(spn_creditos, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btn_agregar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btn_cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtf_nombre_curso, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(29, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtf_nombre_curso, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(spn_creditos, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(44, 44, 44) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_agregar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(25, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtf_nombre_cursoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtf_nombre_cursoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtf_nombre_cursoActionPerformed private void btn_agregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_agregarActionPerformed if (!cur.cursoExiste(txtf_nombre_curso.getText())) { String etiqueta = txtf_nombre_curso.getText(); int creditos = Integer.valueOf(spn_creditos.getValue().toString()); cur.inUpDelCurso('i', null, etiqueta, creditos); FormularioPrincipal.lbl_cant_cur.setText("Cantidad de cursos: "+Integer.toString(MiFuncion.contarData("curso"))); GestionarCurso.tbl_cursos.setModel(new DefaultTableModel(null, new Object[]{"Identificador","Nombre","Créditos"})); cur.llenarJTCurso(GestionarCurso.tbl_cursos); } else { JOptionPane.showMessageDialog(null, "Ya existe el curso"); } }//GEN-LAST:event_btn_agregarActionPerformed private void btn_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cancelarActionPerformed this.dispose(); // if (txtf_id_est.getText().equals("")) { // JOptionPane.showMessageDialog(null, "Selecciona a un estudiante primero"); // } else { // int id = Integer.valueOf(txtf_id_est.getText()); // est.inUpDelEstudiante('b', id, null, null, null, null, null, null); // est.llenarJTEstudiante(tbl_estudiantes, ""); // tbl_estudiantes.setModel(new DefaultTableModel(null, new Object[]{"Identificador", "Nombre(s)", "Apellido(s)", "Sexo", "Fecha nac.", "Teléfono", "Dirección"})); // est.llenarJTEstudiante(tbl_estudiantes, txtf_buscar.getText()); // FormularioPrincipal.lbl_cant_est.setText("Cantidad de estudiantes: "+Integer.toString(MiFuncion.contarData("estudiante"))); // // txtf_id_est.setText(""); // txtf_nombre.setText(""); // txtf_apellido.setText(""); // txtf_telefono.setText(""); // txta_direccion.setText(""); // rbtn_fem.setSelected(false); // rbtn_mas.setSelected(false); // dch_nacimiento.setDate(null); // // } }//GEN-LAST:event_btn_cancelarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AgregarCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AgregarCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AgregarCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AgregarCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AgregarCurso().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_agregar; private javax.swing.JButton btn_cancelar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JSpinner spn_creditos; private javax.swing.JTextField txtf_nombre_curso; // End of variables declaration//GEN-END:variables }
package com.ece671.urar_server; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBAdapter { public static final String KEY_ROWID = "_id"; public static final String KEY_PORT = "Victim_id"; public static final String KEY_Location = "Location"; public static final String KEY_FLAG = "Flag"; //static final String TAG = "DBAdapter"; public static final String DATABASE_NAME = "Victim_DB"; public static final String DATABASE_TABLE = "Victim_TB"; static final int DATABASE_VERSION = 1; private DBHelper Victimhelper; private final Context Victimcontext; private SQLiteDatabase VictimDatabase; private static class DBHelper extends SQLiteOpenHelper{ public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE " + DATABASE_TABLE + "(" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT , " + KEY_PORT + " TEXT NOT NULL , " + KEY_Location + " TEXT NOT NULL , " + KEY_FLAG + " TEXT NOT NULL );" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE ); onCreate(db); } } public DBAdapter (Context c) { Victimcontext = c; } //open database public DBAdapter open() throws SQLException { Victimhelper = new DBHelper(Victimcontext); VictimDatabase = Victimhelper.getWritableDatabase(); return this; } //close database public void close(){ Victimhelper.close(); } //add info to database public long createntry(String Victim_id, String location) { // TODO Auto-generated method stub ContentValues VictimValues = new ContentValues(); VictimValues.put(KEY_PORT, Victim_id); VictimValues.put(KEY_Location, location); return VictimDatabase.insert(DATABASE_TABLE, null, VictimValues); } //get all data from database public String getalldata() { // TODO Auto-generated method stub String [] VI = new String[]{KEY_ROWID,KEY_PORT,KEY_Location}; String result = ""; Cursor c = VictimDatabase.query(DATABASE_TABLE, VI, null, null, null, null, null); int iRow = c.getColumnIndex(KEY_ROWID); int iVictim_id = c.getColumnIndex(KEY_PORT); int iLocation = c.getColumnIndex(KEY_Location); for(c.moveToFirst();!c.moveToLast();c.moveToNext()) { result = result + c.getString(iRow) + ", " + c.getString(iVictim_id) + ", " + c.getString(iLocation) + "\n"; } return result; } // get a pointed data from database public String getpoineddata(String Victim_id){ String [] VI = new String[]{KEY_ROWID,KEY_PORT,KEY_Location}; String result = ""; Cursor userport = VictimDatabase.query(DATABASE_TABLE, VI,null, null, null, null, null); int iRow = userport.getColumnIndex(KEY_ROWID); int iVictim_id = userport.getColumnIndex(KEY_PORT); int iLocation = userport.getColumnIndex(KEY_Location); for(userport.moveToFirst();!userport.moveToLast();userport.moveToNext()) { if(userport.getString(iVictim_id).equals(Victim_id)) { result = result + userport.getString(iRow) + ", " + userport.getString(iVictim_id) + ", " + userport.getString(iLocation); } } return result; } //Edit info public void updateInfo(String Victim_id, String location) { ContentValues newVictimValues = new ContentValues(); newVictimValues.put(KEY_PORT,Victim_id); newVictimValues.put(KEY_Location, location); VictimDatabase.update(DATABASE_TABLE, newVictimValues,KEY_PORT + "=" + Victim_id, null); } }
package com.framgia.fsalon.data.source; import com.framgia.fsalon.data.model.Stylist; import java.util.List; import io.reactivex.Observable; /** * Created by THM on 7/20/2017. */ public class StylistRepository implements StylistDataSource { private StylistDataSource mStylistRemoteDataSource; public StylistRepository(StylistDataSource stylistDataSource) { mStylistRemoteDataSource = stylistDataSource; } @Override public Observable<List<Stylist>> getAllStylists(int id) { return mStylistRemoteDataSource.getAllStylists(id); } }
/* * Licensed to DuraSpace under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. * * DuraSpace 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.fcrepo.client; import static org.fcrepo.client.FedoraHeaderConstants.CACHE_CONTROL; import static org.fcrepo.client.FedoraHeaderConstants.WANT_DIGEST; import static org.fcrepo.client.HeaderHelpers.UTC_RFC_1123_FORMATTER; import static org.fcrepo.client.FedoraHeaderConstants.ACCEPT_DATETIME; import java.net.URI; import java.time.Instant; import org.apache.http.client.config.RequestConfig; /** * Abstract builder for requests to retrieve information from the server * * @author bbpennel */ public abstract class RetrieveRequestBuilder extends RequestBuilder { protected RetrieveRequestBuilder(final URI uri, final FcrepoClient client) { super(uri, client); } /** * Disable following redirects. * * @return this builder */ public RetrieveRequestBuilder disableRedirects() { request.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build()); return this; } /** * Provide a Want-Digest header for this request * * @param value header value, following the syntax defined in: https://tools.ietf.org/html/rfc3230#section-4.3.1 * @return this builder */ public RetrieveRequestBuilder wantDigest(final String value) { if (value != null) { request.setHeader(WANT_DIGEST, value); } return this; } /** * Provide a Cache-Control header with value "no-cache" * * @return this builder */ public RetrieveRequestBuilder noCache() { request.setHeader(CACHE_CONTROL, "no-cache"); return this; } /** * Provide an Accept-Datetime header in RFC1123 format from the given instant for memento datetime negotiation. * * @param acceptInstant the accept datetime represented as an Instant. * @return this builder */ public RetrieveRequestBuilder acceptDatetime(final Instant acceptInstant) { if (acceptInstant != null) { final String rfc1123Datetime = UTC_RFC_1123_FORMATTER.format(acceptInstant); request.setHeader(ACCEPT_DATETIME, rfc1123Datetime); } return this; } /** * Provide an Accept-Datetime from the given RFC1123 formatted string. * * @param acceptDatetime the accept datetime as a string, must be in RFC1123 format. * @return this builder */ public RetrieveRequestBuilder acceptDatetime(final String acceptDatetime) { if (acceptDatetime != null) { // Parse the datetime to ensure that it is in RFC1123 format UTC_RFC_1123_FORMATTER.parse(acceptDatetime); request.setHeader(ACCEPT_DATETIME, acceptDatetime); } return this; } }
package com.example.balaji.myweatherapp; import android.content.DialogInterface; import android.content.Intent; import android.provider.ContactsContract; import android.provider.Settings; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.ContentLoadingProgressBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ProgressBar; import com.example.balaji.myweatherapp.listeners.DataPassListener; import com.example.balaji.myweatherapp.models.Forecastday; import com.example.balaji.myweatherapp.weatherDetails.WeatherDetailsFragment; import com.example.balaji.myweatherapp.weatherSearch.WeatherFragment; public class MainActivity extends AppCompatActivity implements DataPassListener { private WeatherFragment weatherFragment; private FragmentManager fragmentManager; private FragmentTransaction fragmentTransaction; private ContentLoadingProgressBar mProgressDialog; private WeatherDetailsFragment weatherDetailsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mProgressDialog = findViewById(R.id.progressBar); initializeWeatherFragment(); } public void showDialog() { if (mProgressDialog != null) mProgressDialog.show(); } public void hideDialog() { if (mProgressDialog != null) mProgressDialog.hide(); } public void showInfoDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("TURN INTERNET ON"); builder.setMessage("You have no internet connection, kindly please turn on the Internet"); builder.setPositiveButton("TURN ON", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS); startActivity(i); } }); builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(false); dialog.show(); } void initializeWeatherFragment() { weatherFragment = WeatherFragment.newInstance(MainActivity.this); fragmentManager = getSupportFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction = fragmentTransaction.replace(R.id.theContainerView, weatherFragment, weatherFragment.getClass().getSimpleName()); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).show(weatherFragment); fragmentTransaction.commit(); } @Override public void passDataBetweenFragments(Forecastday forecastday) { weatherDetailsFragment = WeatherDetailsFragment.newInstance(forecastday); fragmentManager = getSupportFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction = fragmentTransaction.add(R.id.theContainerView, weatherDetailsFragment, weatherFragment.getClass().getSimpleName()); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).show(weatherDetailsFragment); fragmentTransaction.addToBackStack(weatherFragment.getClass().getSimpleName()); fragmentTransaction.commit(); } }
package com.ecjcoach.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import com.google.gson.annotations.Expose; @Entity public class Cust_exp_dtls { @Id private String tx_id; private String cust_id; private String org_name; private String cust_desg; private String wrk_frm; private String wrk_to; private String cust_sal; private String cust_role; private String cust_industry; private String cust_fun_area; private Date created_dt; //datetime, @Expose private Date modified_dt; //datetime, @Column(length=500) @Expose private String usr_chng; //varchar(500) not null, @Expose private char pst_flg; //varchar(1) not null, @Column(length=15) @Expose private int nmbr_chng; //numeric(15) not null, @Expose private char use_flg; //varchar(1) , check (use_flg in('Y','N','X','P')), @ManyToOne @JoinColumn(name="cust_id", insertable=false, nullable=false, updatable=false) private Cust_prsnl_dtls cust_prsnl_dtls; public String getTx_id() { return tx_id; } public void setTx_id(String tx_id) { this.tx_id = tx_id; } public String getCust_id() { return cust_id; } public void setCust_id(String cust_id) { this.cust_id = cust_id; } public String getOrg_name() { return org_name; } public void setOrg_name(String org_name) { this.org_name = org_name; } public String getCust_desg() { return cust_desg; } public void setCust_desg(String cust_desg) { this.cust_desg = cust_desg; } public String getWrk_frm() { return wrk_frm; } public void setWrk_frm(String wrk_frm) { this.wrk_frm = wrk_frm; } public String getWrk_to() { return wrk_to; } public void setWrk_to(String wrk_to) { this.wrk_to = wrk_to; } public String getCust_sal() { return cust_sal; } public void setCust_sal(String cust_sal) { this.cust_sal = cust_sal; } public String getCust_role() { return cust_role; } public void setCust_role(String cust_role) { this.cust_role = cust_role; } public String getCust_industry() { return cust_industry; } public void setCust_industry(String cust_industry) { this.cust_industry = cust_industry; } public String getCust_fun_area() { return cust_fun_area; } public void setCust_fun_area(String cust_fun_area) { this.cust_fun_area = cust_fun_area; } public Date getCreated_dt() { return created_dt; } public void setCreated_dt(Date created_dt) { this.created_dt = created_dt; } public Date getModified_dt() { return modified_dt; } public void setModified_dt(Date modified_dt) { this.modified_dt = modified_dt; } public String getUsr_chng() { return usr_chng; } public void setUsr_chng(String usr_chng) { this.usr_chng = usr_chng; } public char getPst_flg() { return pst_flg; } public void setPst_flg(char pst_flg) { this.pst_flg = pst_flg; } public int getNmbr_chng() { return nmbr_chng; } public void setNmbr_chng(int nmbr_chng) { this.nmbr_chng = nmbr_chng; } public char getUse_flg() { return use_flg; } public void setUse_flg(char use_flg) { this.use_flg = use_flg; } public Cust_prsnl_dtls getCust_prsnl_dtls() { return cust_prsnl_dtls; } public void setCust_prsnl_dtls(Cust_prsnl_dtls cust_prsnl_dtls) { this.cust_prsnl_dtls = cust_prsnl_dtls; } }
/* * 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 ArrayMetodo1; /** * * @author mati */ public class Ejecutable { public static void main(String[] args) { int [] vector={4,7,1,5,67,6}; Array_Metodo.mostrarArrayPantalla2(vector); Array_Metodo.obtenerArrayComoString(vector); Array_Metodo.completarArray3(vector); Array_Metodo.obtenerSumaArray(vector); } }
public class Solution2 { public boolean inRange(int a,int b) { if((a>=10&&a<=20) || (b>=10&&b<=20)) return true; return false; } }
package com.lxd.controller; import org.apache.log4j.Logger; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/hello") public class TestController { private Logger logger = Logger.getLogger(TestController.class); @RequestMapping("/hello") public @ResponseBody String HelloWorld(){ for(int i=0;i<10;i++){ System.out.println(10/0); logger.debug("debug"); logger.info("info"); } return "Hello World!"; } }
package pl.edu.agh.mwo; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * @author Kamil Rojek */ public class TripManagerTest { TripManager tripManager; Trip trip; @BeforeMethod public void setUp() { tripManager = new TripManager(); trip = new Trip("nazwa", "opis"); } @Test public void testAdd() throws TripAlreadyExistsException { assertEquals(0, tripManager.getTrips().size()); tripManager.add(trip); assertEquals(1, tripManager.getTrips().size()); } @Test(expectedExceptions = TripAlreadyExistsException.class) public void testAddTripTwice() throws TripAlreadyExistsException { assertEquals(0, tripManager.getTrips().size()); tripManager.add(trip); assertEquals(1, tripManager.getTrips().size()); tripManager.add(trip); } @Test public void testRemoveTrip() throws Exception { tripManager.add(trip); assertEquals(1, tripManager.getTrips().size()); tripManager.remove(trip.getName()); assertEquals(0, tripManager.getTrips().size()); } @Test public void testFindTrip_whenKeyIsPartOfTripName_returnTrip() throws TripAlreadyExistsException { //Arrange Trip tripPoland = new Trip("Polska", "Polska jest spoko"); Trip tripJapan = new Trip("Japonia", "Japonia też jest spoko"); //Act tripManager.add(tripPoland); tripManager.add(tripJapan); Trip result = tripManager.findTrip("Japonia"); //Assert assertEquals(result.getName(), "Japonia"); } @Test public void testFindTrip_whenKeyIsPartOfTripDesc_returnTrip() throws TripAlreadyExistsException { //Arrange Trip tripPoland = new Trip("Polska", "Stolicą Polski jest Warszawa"); Trip tripJapan = new Trip("Japonia", "Stolicą Japoni jest Tokio"); //Act tripManager.add(tripPoland); tripManager.add(tripJapan); Trip result = tripManager.findTrip("Tokio"); //Assert assertEquals(result.getName(), "Japonia"); } @Test public void testFindTrip_whenKeyIsPartOfPhotoComment_returnTrip() throws TripAlreadyExistsException { //Arrange Photo firstPhoto = new Photo.Builder().addComment("Zdjęcie nad polskim jeziorem.").takePhoto(); Photo secondPhoto = new Photo.Builder().addComment("Widoki na mazury.").takePhoto(); Photo photoFromJapan = new Photo.Builder().addComment("W japoni jest pyszny Ramen.").takePhoto(); Trip tripPoland = new Trip("Polska", "Stolicą Polski jest Warszawa"); Trip tripJapan = new Trip("Japonia", "Stolicą Japoni jest Tokio"); //Act tripPoland.addPhotoToTripAlbum(firstPhoto); tripPoland.addPhotoToTripAlbum(secondPhoto); tripJapan.addPhotoToTripAlbum(photoFromJapan); tripManager.add(tripPoland); tripManager.add(tripJapan); Trip result = tripManager.findTrip("mazury"); //Assert assertEquals(result.getName(), "Polska"); } @Test public void testFindTrip_whenKeyCannotBeFound_returnNull() throws TripAlreadyExistsException { //Arrange Trip tripPoland = new Trip("Polska", "Stolicą Polski jest Warszawa"); Trip tripJapan = new Trip("Japonia", "Stolicą Japoni jest Tokio"); //Act tripManager.add(tripPoland); tripManager.add(tripJapan); Trip result = tripManager.findTrip("mazury"); //Assert assertNull(result); } @Test public void testFindTrip_whenKeyIsNull_returnNull() throws TripAlreadyExistsException { //Arrange Trip tripPoland = new Trip("Polska", "Stolicą Polski jest Warszawa"); Trip tripJapan = new Trip("Japonia", "Stolicą Japoni jest Tokio"); //Act tripManager.add(tripPoland); tripManager.add(tripJapan); Trip result = tripManager.findTrip(null); //Assert assertNull(result); } @Test public void testFindTrip_whenKeyIsEmpty_returnNull() throws TripAlreadyExistsException { //Arrange Trip tripPoland = new Trip("Polska", "Stolicą Polski jest Warszawa"); Trip tripJapan = new Trip("Japonia", "Stolicą Japoni jest Tokio"); //Act tripManager.add(tripPoland); tripManager.add(tripJapan); Trip result = tripManager.findTrip(""); //Assert assertNull(result); } }
package com.gymteam.tom.gymteam; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; public class MyTabsPagerAdapter extends FragmentStatePagerAdapter { int mNumOfTabs; public BrowseFragment tabBrowse; public MyInvitesFragment tabMyInvites; public MyTabsPagerAdapter(FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } @Override public Fragment getItem(int position) { switch (position) { case 0: tabMyInvites = new MyInvitesFragment(); return tabMyInvites; case 1: tabBrowse = new BrowseFragment(); return tabBrowse; default: return null; } } @Override public int getCount() { return mNumOfTabs; } }
package com.resjob.common.persistence; import com.resjob.common.utils.IdGen; /** * 应用Entity类 * @author ThinkGem * @version 2014-05-16 */ public abstract class AppEntity<T> extends BaseEntity<T> { private static final long serialVersionUID = 1L; public AppEntity() { super(); } public AppEntity(String id) { super(id); } /** * 插入之前执行方法,需要手动调用 */ @Override public void preInsert(){ // 不限制ID为UUID,调用setIsNewRecord()使用自定义ID if (!this.isNewRecord){ setId(IdGen.uuid()); } } /** * 更新之前执行方法,需要手动调用 */ @Override public void preUpdate(){ } }
package com.example.bryannaphan.pickupgen; import android.content.Context; import android.content.SharedPreferences; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; public class MainActivity extends AppCompatActivity { public static String[] DEFAULTS = { "Do you have a Band-Aid? Because I just scraped my knee falling for you.", "If you were a vegetable youd be a cute-cumber.", "Do you have a sunburn, or are you always this hot?", "Are you Australian? Because you meet all of my koala-fications.", "Are you a banana? Because I find you a-peeling!" }; FragmentManager fm = getSupportFragmentManager(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.example.bryannaphan.pickupgen.R.layout.activity_main); final ArrayList<String> pickupLines = new ArrayList<String>(Arrays.asList(DEFAULTS)); final Button textButton = (Button) findViewById(com.example.bryannaphan.pickupgen.R.id.textButton); textButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); int count = sharedPref.getInt("count",0); for(int i = 0; i < count; i++) { String current = sharedPref.getString("custom" + i, "");; if(!current.equals("") && !pickupLines.contains(current)) { pickupLines.add(current); } } final Random rand = new Random(); final TextView helloText = (TextView) findViewById(com.example.bryannaphan.pickupgen.R.id.helloText); int randNum = rand.nextInt(pickupLines.size()); helloText.setText(pickupLines.get(randNum)); } }); final FloatingActionButton addButton = (FloatingActionButton) findViewById(R.id.addButton); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AddLineFragment addFrag = new AddLineFragment(); addFrag.show(fm, "dialog fragment"); } }); } }
package br.com.douglastuiuiu.biometricengine.integration.creddefense.dto.response.viewdocuments; import br.com.douglastuiuiu.biometricengine.integration.creddefense.dto.response.ResponseDTO; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; /** * @author douglas * @since 20/03/2017 */ @JsonIgnoreProperties(ignoreUnknown = true) public class ViewDocumentsResponseDTO extends ResponseDTO implements Serializable { private static final long serialVersionUID = -8771257576759855802L; private ViewDocumentsCreditResponseDTO creditrequest; public ViewDocumentsCreditResponseDTO getCreditrequest() { return creditrequest; } public void setCreditrequest(ViewDocumentsCreditResponseDTO creditrequest) { this.creditrequest = creditrequest; } }
package cqut.lexicalAnalyzer.impl; import cqut.lexicalAnalyzer.Recog; import cqut.util.EncodeTable; import cqut.util.Symbol; import cqut.util.Token; import cqut.util.entity.Source; import cqut.util.entity.SymbolMeta; import cqut.util.entity.TokenMeta; /** * * @author Allen 字符串分析 */ public class StringAnalysis implements Recog { Recog r = new DigitAnalysis(); static StringAnalysis SA; static StringBuffer temp = new StringBuffer();// 字符缓存 static int state = 1;// 1表示是关键字 2表示是标识符 0表示程序出错 private StringAnalysis() { } public static StringAnalysis getStringAnalysis() { if (SA == null) { SA = new StringAnalysis(); } return SA; } @Override public void recog(Character ch) { if (ch == '_') state = 2; switch (state) { case 0: { error("error:第" + (Source.getInstance().getRow() + 1) + "行 第" + (Source.getInstance().getColspan() + 1) + "列"); break; } case 1: { isKeyword(ch); break; } case 2: { isIdentifier(ch); break; } } Source.getInstance().sort(); } public void error(String message) { System.out.println(message); } private void isIdentifier(Character ch) {// 包含下划线,不可能是关键字 // if (ch != ' ' && ch != ';' && ch != '+' && ch != '-' && ch != '*' // && ch != '/' && ch != '=' && ch != '(' && ch != ')' // && ch != '[' && ch != ']') { if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_' || ch >= '0' && ch <= '9') { temp.append(ch); if (Source.getInstance().isLastCharacter()) { addIdentifier(temp.toString()); insertSymbol(temp.toString()); state = 1; temp = new StringBuffer();// 清空字符缓存 return; } isIdentifier(Source.getInstance().getNextCharacter()); } // else { // error("error:第" + Source.getInstance().getRow() + "行 第" // + Source.getInstance().getColspan() + "列" + " :" + ch); // } // } else { addIdentifier(temp.toString()); insertSymbol(temp.toString()); state = 1;// 还原状态,方便下次调用 temp = new StringBuffer();// 清空字符缓存 } } private void isKeyword(Character ch) {// 纯字母组成,有可能是关键字 // if (ch != ' ' && ch != ';' && ch != '+' && ch != '-' && ch != '*' // && ch != '/' && ch != '=' && ch != '(' && ch != ')' // && ch != '[' && ch != ']') { if (ch != '_' && (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z')) { temp.append(ch); if (Source.getInstance().isLastCharacter()) { if (EncodeTable.search(temp.toString()) != 0) { addKeyword(temp.toString()); state = 1; temp = new StringBuffer();// 清空字符缓存 } else { addIdentifier(temp.toString()); insertSymbol(temp.toString()); state = 1; temp = new StringBuffer();// 清空字符缓存 } return; } else isKeyword(Source.getInstance().getNextCharacter()); } else if (ch == '_' || ch >= '0' && ch <= '9') { state = 2; isIdentifier(Source.getInstance().getNextCharacter()); } // else { // temp = new StringBuffer(); // error("error:第" + (Source.getInstance().getRow() + 1) + "行 第" // + (Source.getInstance().getColspan() + 1) + "列" + " :" // + ch); // } // } else { if (EncodeTable.search(temp.toString()) != 0) { addKeyword(temp.toString()); state = 1; temp = new StringBuffer();// 清空字符缓存 } else { addIdentifier(temp.toString()); insertSymbol(temp.toString()); state = 1; temp = new StringBuffer();// 清空字符缓存 } } } private void insertSymbol(String Str_temp) { // Symbol.getInstance().getSymbol() SymbolMeta Cur = new SymbolMeta(); Cur.setMeta(Str_temp); Cur.setPointer(35); Cur.setKind(Symbol.KIND_VAR); Symbol.getInstance().getSymbol().add(Cur); } private void addIdentifier(String Str_temp) { // TokenMeta Cur = new TokenMeta(); // Cur.setLine(Source.getInstance().getRow()); // Cur.setMeta(Str_temp); // Cur.setPointer(35); Token.getInstance().insert(Str_temp, 35); } private void addKeyword(String Str_temp) { int Cur_pointer = EncodeTable.search(Str_temp); // TokenMeta Cur = new TokenMeta(); // Cur.setLine(Source.getInstance().getRow()); // Cur.setMeta(Str_temp); // Cur.setPointer(Cur_pointer); Token.getInstance().insert(Str_temp, Cur_pointer); } }
package com.citibank.ods.modules.client.relationeg.action; import com.citibank.ods.common.action.BaseODSDetailAction; import com.citibank.ods.common.functionality.BaseFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.modules.client.relationeg.functionality.RelationEgDetailFnc; import com.citibank.ods.modules.client.relationeg.functionality.valueobject.RelationEgDetailFncVO; /** * @author leonardo.nakada * */ public class RelationEgDetailAction extends BaseODSDetailAction { private static final String C_DELETE_DOMAIN = "DeleteDomain"; private static final String C_INSERT_DOMAIN = "InsertDomain"; /* * Parte do nome do módulo ou ação */ private static final String C_SCREEN_NAME = "RelationEg.RelationEgDetail"; /** * @see com.citibank.ods.commom.action.BaseAction#getFncVOPublishName() */ public String getFncVOPublishName() { return RelationEgDetailFncVO.class.getName(); } /* * (non-Javadoc) * @see com.citibank.ods.common.action.BaseODSAction#getODSFuncionality() */ protected BaseFnc getFuncionality() { return new RelationEgDetailFnc(); } /* * (non-Javadoc) * @see com.citibank.ods.common.action.BaseODSAction#getScreenName() */ protected String getScreenName() { return C_SCREEN_NAME; } /** * Actions Extras */ protected String extraActions( BaseFncVO fncVO_, String invokePath_ ) { String[] splittedInvokePath = invokePath_.split( "\\." ); RelationEgDetailFnc detailFnc = ( RelationEgDetailFnc ) getFuncionality(); String forwardKey = ""; if ( ( splittedInvokePath[ 2 ].equals( C_MODE_INSERT ) || splittedInvokePath[ 2 ].equals( C_MODE_UPDATE ) ) && ( splittedInvokePath[ 3 ].equals( C_INSERT_DOMAIN ) ) ) { detailFnc.insertDomain( fncVO_ ); if ( !fncVO_.hasErrors() ) { forwardKey = getScreenName() + C_SPLITTER_CHAR + C_ACTION_BACK; } else { forwardKey = getScreenName() + C_SPLITTER_CHAR + splittedInvokePath[ 2 ]; } } else if ( ( splittedInvokePath[ 2 ].equals( C_MODE_INSERT ) || splittedInvokePath[ 2 ].equals( C_MODE_UPDATE ) ) && ( splittedInvokePath[ 3 ].equals( C_DELETE_DOMAIN ) ) ) { detailFnc.deleteDomain( fncVO_ ); if ( !fncVO_.hasErrors() ) { forwardKey = getScreenName() + C_SPLITTER_CHAR + C_ACTION_BACK; } else { forwardKey = getScreenName() + C_SPLITTER_CHAR + splittedInvokePath[ 2 ]; } } return forwardKey; } /** * Realiza a pesquisa por ReltnNbr */ protected String searchActions( BaseFncVO fncVO_, String invokePath_ ) { RelationEgDetailFncVO fncVO = ( RelationEgDetailFncVO ) fncVO_; fncVO.setFromSearch( true ); String[] splittedInvokePath = invokePath_.split( "\\." ); String nextPage = splittedInvokePath[ 3 ] + C_SPLITTER_CHAR + splittedInvokePath[ 4 ]; fncVO.setClickedSearch( nextPage ); return getScreenName(); } }
package ru.yandex.artists.model; import android.os.Parcel; import android.os.Parcelable; /** * Created by druger on 27.03.2016. */ public class Artist implements Parcelable { private String name; private String genres; private int tracks; private int albums; private String description; private String coverSmall; private String coverBig; public Artist() { } public Artist(String name, String genres, int tracks, int albums) { this.name = name; this.genres = genres; this.tracks = tracks; this.albums = albums; } protected Artist(Parcel in) { name = in.readString(); genres = in.readString(); tracks = in.readInt(); albums = in.readInt(); description = in.readString(); coverSmall = in.readString(); coverBig = in.readString(); } public static final Creator<Artist> CREATOR = new Creator<Artist>() { @Override public Artist createFromParcel(Parcel in) { return new Artist(in); } @Override public Artist[] newArray(int size) { return new Artist[size]; } }; public String getName() { return name; } public String getGenres() { return genres; } public int getTracks() { return tracks; } public int getAlbums() { return albums; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCoverSmall() { return coverSmall; } public void setCoverSmall(String coverSmall) { this.coverSmall = coverSmall; } public String getCoverBig() { return coverBig; } public void setCoverBig(String coverBig) { this.coverBig = coverBig; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeString(genres); dest.writeInt(tracks); dest.writeInt(albums); dest.writeString(description); dest.writeString(coverSmall); dest.writeString(coverBig); } }
package com.javawebtutor.Controllers; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; import javafx.stage.StageStyle; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class PopUpController implements Initializable { @FXML private Button btn; public static String content; public PopUpController() { } public void close(){ Stage stage = (Stage) btn.getScene().getWindow(); stage.close(); } public void popUp() throws IOException { Parent nn = FXMLLoader.load(Controller.class.getResource("/PopUpScene.fxml")); Scene scene = new Scene(nn); Stage window = new Stage(); window.initStyle(StageStyle.UNDECORATED); window.setScene(scene); window.show(); window.setTitle(""); } @Override public void initialize(URL location, ResourceBundle resources) { btn.setStyle("-fx-alignment: center;-fx-hgap: 10; -fx-vgap: 10;"); btn.setText(content); } }
package com.crypto.document; import java.math.BigDecimal; public class LatestPrice { BigDecimal price; BigDecimal volume; BigDecimal marketCap; public LatestPrice(BigDecimal price, BigDecimal volume, BigDecimal marketCap) { super(); this.price = price; this.volume = volume; this.marketCap = marketCap; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getVolume() { return volume; } public void setVolume(BigDecimal volume) { this.volume = volume; } public BigDecimal getMarketCap() { return marketCap; } public void setMarketCap(BigDecimal marketCap) { this.marketCap = marketCap; } }
package views; import com.cloudgarden.resource.SWTResourceManager; import common.Utilities; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import service.SellGoodsService; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class SellGoodsConfirm extends org.eclipse.swt.widgets.Dialog { private Shell dialogShell; private Composite sellGoodsConfirmComponent; private Label sellGoodsConfirmSellPriceTotalLabel; private Label sellGoodsConfirmCustomerBillLabel; private Button sellGoodsConfirmConfirmButton; private Label sellGoodsConfirmChangeTitleLabel; private Composite sellGoodsConfirmChangeAreaComponent; private Text sellGoodsConfirmChangeText; private Button sellGoodsConfirmCancelButton; private Text sellGoodsConfirmInfoText; private Label sellGoodsConfirmWonLabel; private Text sellGoodsConfirmCustomerBillValueText; private Label sellGoodConfirmSellPriceWonLabel; private Text sellGoodsConfirmSellPriceValueText; private int result = SWT.NO; Utilities util = new Utilities(); /** * Auto-generated main method to display this * org.eclipse.swt.widgets.Dialog inside a new Shell. */ // public static void main(String[] args) { // try { // Display display = Display.getDefault(); // Shell shell = new Shell(display); // SellGoodsConfirm inst = new SellGoodsConfirm(shell, SWT.NULL); // inst.open(); // } catch (Exception e) { // e.printStackTrace(); // } // } public SellGoodsConfirm(Shell parent, int style) { super(parent, style); } public int open(SellGoodsService sellGoodsService) { try { Shell parent = getParent(); dialogShell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); { //Register as a resource user - SWTResourceManager will //handle the obtaining and disposing of resources SWTResourceManager.registerResourceUser(dialogShell); } dialogShell.setLayout(new FormLayout()); dialogShell.layout(); dialogShell.pack(); dialogShell.setSize(496, 241); dialogShell.setText("손님 지불 금액 입력"); { sellGoodsConfirmComponent = new Composite(dialogShell, SWT.NONE); FormData sellGoodsConfirmComponentLData = new FormData(); sellGoodsConfirmComponentLData.left = new FormAttachment(0, 1000, 0); sellGoodsConfirmComponentLData.top = new FormAttachment(0, 1000, 0); sellGoodsConfirmComponentLData.width = 496; sellGoodsConfirmComponentLData.height = 225; sellGoodsConfirmComponent.setLayoutData(sellGoodsConfirmComponentLData); sellGoodsConfirmComponent.setLayout(null); { sellGoodsConfirmSellPriceTotalLabel = new Label(sellGoodsConfirmComponent, SWT.RIGHT); sellGoodsConfirmSellPriceTotalLabel.setText("\ud310\ub9e4\uac00\uaca9 \ud569\uacc4 :"); sellGoodsConfirmSellPriceTotalLabel.setBounds(29, 24, 143, 28); sellGoodsConfirmSellPriceTotalLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 14, 0, false, false)); } { sellGoodsConfirmSellPriceValueText = new Text(sellGoodsConfirmComponent, SWT.RIGHT); sellGoodsConfirmSellPriceValueText.setBounds(184, 24, 196, 20); sellGoodsConfirmSellPriceValueText.setEditable(false); sellGoodsConfirmSellPriceValueText.setBackground(dialogShell.getBackground()); sellGoodsConfirmSellPriceValueText.setText(String.valueOf(sellGoodsService.getTotalPrice())); sellGoodsConfirmSellPriceValueText.setFont(SWTResourceManager.getFont("Lucida Grande", 14, 0, false, false)); } { sellGoodConfirmSellPriceWonLabel = new Label(sellGoodsConfirmComponent, SWT.NONE); sellGoodConfirmSellPriceWonLabel.setText("\uc6d0"); sellGoodConfirmSellPriceWonLabel.setBounds(392, 24, 49, 25); sellGoodConfirmSellPriceWonLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 14, 0, false, false)); } { sellGoodsConfirmCustomerBillLabel = new Label(sellGoodsConfirmComponent, SWT.RIGHT); sellGoodsConfirmCustomerBillLabel.setText("\uc190\ub2d8 \uc9c0\ubd88 \uae08\uc561 :"); sellGoodsConfirmCustomerBillLabel.setBounds(12, 57, 160, 30); sellGoodsConfirmCustomerBillLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 14, 0, false, false)); } { sellGoodsConfirmCustomerBillValueText = new Text(sellGoodsConfirmComponent, SWT.RIGHT); sellGoodsConfirmCustomerBillValueText.setBounds(184, 57, 196, 23); sellGoodsConfirmCustomerBillValueText.setFont(SWTResourceManager.getFont("Lucida Grande", 14, 0, false, false)); sellGoodsConfirmCustomerBillValueText.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent evt) { sellGoodsConfirmCustomerBillValueTextKeyReleased(evt); } }); sellGoodsConfirmCustomerBillValueText.setFocus(); sellGoodsConfirmCustomerBillValueText.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent evt) { // 숫자만 입력 가능 evt.doit = evt.text.matches("[0-9]*"); } }); } { sellGoodsConfirmWonLabel = new Label(sellGoodsConfirmComponent, SWT.NONE); sellGoodsConfirmWonLabel.setText("\uc6d0"); sellGoodsConfirmWonLabel.setBounds(392, 57, 60, 30); sellGoodsConfirmWonLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 14, 0, false, false)); } { sellGoodsConfirmInfoText = new Text(sellGoodsConfirmComponent, SWT.SINGLE | SWT.LEFT); sellGoodsConfirmInfoText.setBounds(20, 95, 458, 24); sellGoodsConfirmInfoText.setEditable(false); sellGoodsConfirmInfoText.setBackground(dialogShell.getBackground()); sellGoodsConfirmInfoText.setText("잔액 계산을 하시려면 손님 지불 금액을 입력해주십시오."); } { sellGoodsConfirmCancelButton = new Button(sellGoodsConfirmComponent, SWT.PUSH | SWT.CENTER); sellGoodsConfirmCancelButton.setText("\ucde8 \uc18c"); sellGoodsConfirmCancelButton.setBounds(17, 173, 86, 35); sellGoodsConfirmCancelButton.addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent evt) { dialogShell.dispose(); } }); } { sellGoodsConfirmConfirmButton = new Button(sellGoodsConfirmComponent, SWT.PUSH | SWT.CENTER); sellGoodsConfirmConfirmButton.setText("\ud310\ub9e4\uc644\ub8cc"); sellGoodsConfirmConfirmButton.setBounds(342, 173, 142, 35); sellGoodsConfirmConfirmButton.addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent evt) { sellGoodsConfirmConfirmButtonMouseUp(evt); } }); } { sellGoodsConfirmChangeAreaComponent = new Composite(sellGoodsConfirmComponent, SWT.BORDER); sellGoodsConfirmChangeAreaComponent.setLayout(null); sellGoodsConfirmChangeAreaComponent.setBounds(19, 124, 459, 34); sellGoodsConfirmChangeAreaComponent.setBackground(SWTResourceManager.getColor(238, 232, 183)); } { sellGoodsConfirmChangeText = new Text(sellGoodsConfirmChangeAreaComponent, SWT.RIGHT); sellGoodsConfirmChangeText.setText(""); sellGoodsConfirmChangeText.setBackground(sellGoodsConfirmChangeAreaComponent.getBackground()); sellGoodsConfirmChangeText.setBounds(165, 5, 185, 24); sellGoodsConfirmChangeText.setFont(SWTResourceManager.getFont("Lucida Grande", 14, 0, false, false)); sellGoodsConfirmChangeText.setEditable(false); } { sellGoodsConfirmChangeTitleLabel = new Label(sellGoodsConfirmChangeAreaComponent, SWT.LEFT); sellGoodsConfirmChangeTitleLabel.setText("\uc794 \uc561"); sellGoodsConfirmChangeTitleLabel.setBounds(45, 5, 89, 24); sellGoodsConfirmChangeTitleLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 14, 0, false, false)); sellGoodsConfirmChangeTitleLabel.setBackground(sellGoodsConfirmChangeAreaComponent.getBackground()); } } dialogShell.setLocation(getParent().toDisplay(250, 150)); dialogShell.open(); Display display = dialogShell.getDisplay(); while (!dialogShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } } catch (Exception e) { e.printStackTrace(); } return this.result; } private void sellGoodsConfirmCustomerBillValueTextKeyReleased(KeyEvent evt) { if (util.isEmpty(sellGoodsConfirmSellPriceValueText.getText()) || util.isEmpty(sellGoodsConfirmCustomerBillValueText.getText())) { sellGoodsConfirmInfoText.setBackground(dialogShell.getBackground()); sellGoodsConfirmInfoText.setText("잔액 계산을 하시려면 손님 지불 금액을 입력해주십시오."); sellGoodsConfirmChangeText.setText(""); return; } Long sellPriceTotal = Long.valueOf(sellGoodsConfirmSellPriceValueText.getText()); Long customerBill = null; try { customerBill = Long.valueOf(sellGoodsConfirmCustomerBillValueText.getText()); } catch (NumberFormatException e) { util.showMsg(dialogShell, "손님 지불 금액의 숫자가 올바르지 않습니다."); sellGoodsConfirmCustomerBillValueText.setText(""); sellGoodsConfirmCustomerBillValueText.setFocus(); return; } if (sellPriceTotal > customerBill) { sellGoodsConfirmInfoText.setBackground(SWTResourceManager.getColor(227, 178, 167)); sellGoodsConfirmInfoText.setText("손님 지불 금액이 상품 금액보다 적습니다."); sellGoodsConfirmChangeText.setText(util.addCommaForPrice(customerBill - sellPriceTotal)); } else if (sellPriceTotal == customerBill) { sellGoodsConfirmInfoText.setText(""); sellGoodsConfirmInfoText.setBackground(dialogShell.getBackground()); sellGoodsConfirmChangeText.setText(util.addCommaForPrice(0l)); } else { long charge = customerBill - sellPriceTotal; sellGoodsConfirmInfoText.setText(""); sellGoodsConfirmInfoText.setBackground(dialogShell.getBackground()); sellGoodsConfirmChangeText.setText(util.addCommaForPrice(charge)); } } private void sellGoodsConfirmConfirmButtonMouseUp(MouseEvent evt) { this.result = SWT.YES; dialogShell.dispose(); } }
package irix.measurement.structure; import irix.measurement.service.MeasurementsImp; public class Measurements extends DoseRate implements MeasurementsImp /*implements Comparable<Measurements>*/ { private Measurement measurement; public Measurements() { } public Measurements(Measurement measurement) { this.measurement = measurement; } public Measurement getMeasurement() { return measurement; } public void setMeasurement(Measurement measurement) { this.measurement = measurement; } @Override public int hashCode() { final int prime = 67; int hash = 7; hash = prime * hash + ((measurement == null) ? 0 : measurement.hashCode()); return hash; } public boolean equals(Object obj) { if (!(obj instanceof Measurements)) return false; return this.measurement == ((Measurements)obj).getMeasurement(); } @Override public String toString() { return "measurement=" + measurement; } public int compareTo(Measurements o) { return measurement.compareTo(o.getMeasurement()); } }
package com.reagan.graphingcalc; public class CartesianPoint { public double x, y; public CartesianPoint(double x, double y) { this.x = x; this.y = y; } }
package com.Hellel.PSoloid.ColorsShape.Shape; import com.Hellel.PSoloid.ColorsShape.Colour.Colour; import com.Hellel.PSoloid.ColorsShape.Shape.Shape; /** * Created by otk_prog on 20.07.2015. */ public class Triangle extends Shape { private double h; private double b; public double getH() { return h; } public void setH(double h) { this.h = h; } public double getB() { return b; } public void setB(double b) { this.b = b; } public Triangle(String nameShape, Colour colour, double h, double b) { super(nameShape, colour); this.h = h; this.b = b; } @Override public double getSquare() { return h*b/2; } }
package com.dromedicas.test; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.dromedicas.dao.ExistenciasHome; import com.dromedicas.dao.SucursalesHome; import com.dromedicas.dao.VentadiariaglobalHome; import com.dromedicas.dto.Existencias; import com.dromedicas.dto.Sucursales; import com.dromedicas.dto.Ventadiariaglobal; public class TestCRUD { private static final Log log = LogFactory.getLog(SucursalesHome.class); public static void main(String[] args) { String dateStart = "10/04/2017 09:55:58"; String dateStop = "10/04/2017 10:03:48"; //HH converts hour in 24 hours format (0-23), day calculation SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.parse(dateStart); d2 = format.parse(dateStop); //in milliseconds long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); System.out.print(diffDays + " days, "); System.out.print(diffHours + " hours, "); System.out.print(diffMinutes + " minutes, "); System.out.print(diffSeconds + " seconds."); } catch (Exception e) { e.printStackTrace(); } } }
package com.ipincloud.iotbj.srv.domain; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Time; import java.sql.Date; import java.sql.Timestamp; import com.alibaba.fastjson.annotation.JSONField; //(Person) //generate by redcloud,2020-07-24 19:59:20 public class Person implements Serializable { private static final long serialVersionUID = 39L; // 自增ID private Long id ; // 姓名: private String name ; // 岗位: private String post ; // 选择部门: @JSONField(name = "org_id") private Long orgId ; // 身份证号: private String idnumber ; // 工号: private String jobno ; // 手机号: private String phone ; // 性别: private String gender ; // 照片 private String image ; // 卡片数量: private Integer cardnum ; // 最后修改时间: private Long uptime ; public Long getId() { return id ; } public void setId(Long id) { this.id = id; } public String getName() { return name ; } public void setName(String name) { this.name = name; } public String getPost() { return post ; } public void setPost(String post) { this.post = post; } public Long getOrgId() { return orgId ; } public void setOrgId(Long orgId) { this.orgId = orgId; } public String getIdnumber() { return idnumber ; } public void setIdnumber(String idnumber) { this.idnumber = idnumber; } public String getJobno() { return jobno ; } public void setJobno(String jobno) { this.jobno = jobno; } public String getPhone() { return phone ; } public void setPhone(String phone) { this.phone = phone; } public String getGender() { return gender ; } public void setGender(String gender) { this.gender = gender; } public String getImage() { return image ; } public void setImage(String image) { this.image = image; } public Integer getCardnum() { return cardnum ; } public void setCardnum(Integer cardnum) { this.cardnum = cardnum; } public Long getUptime() { return uptime ; } public void setUptime(Long uptime) { this.uptime = uptime; } }
package ru.sgu.csit.csc.graphs; import java.util.*; public class AdjacencyListsGraph extends BaseGraph { private final List<List<Integer>> adjacencyLists; public AdjacencyListsGraph(int vertexCount, Type type) { super(vertexCount, type); adjacencyLists = new ArrayList<List<Integer>>(vertexCount); for (int i = 0; i < vertexCount; ++i) { adjacencyLists.add(new ArrayList<Integer>()); } } @Override public boolean addEdge(int from, int to) { handleAddEdge(from, to); adjacencyLists.get(from).add(to); if (getType() == Type.UNDIRECTED) { adjacencyLists.get(to).add(from); } return true; } @Override public Iterable<Integer> getNeighbors(int vertex) { return Collections.unmodifiableList(adjacencyLists.get(vertex)); } }
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public class Candidate { public static void main(String[] args) { String[] votesString= new String[]{"meghana","mugdha","upas","meghana","anjali","upas","upas"}; Candidate candidate=new Candidate(); candidate.electionWinner(votesString); } static String electionWinner(String[] votesString) { HashMap<String, Integer> map = new HashMap<>(); int maximum = 1; for(String candidateName: votesString){ if(map.containsKey(candidateName)){ int votes = map.get(candidateName) + 1; map.put(candidateName, votes); if (votes > maximum){ maximum = votes; } } else { map.put(candidateName, 1); } } int max=0; List<String> candidates = new ArrayList<>(); for (String candidateName :map.keySet()){ if (map.get(candidateName) == maximum){ candidates.add(candidateName); } } Collections.sort(candidates); System.out.println(candidates.get(candidates.size() -1 )); return candidates.get(candidates.size() -1 ); } }
package lesson1.hw; /** * Алгоритмы_и_структуры_данных_на_Java.БазовыйКурс. 24.09.2019 Webinar. * Teacher: Фанзиль Кусяпкулов * Урок 1. Общие сведения об алгоритмах и структурах данных * Домашняя работа. * @author Litvinenko Yuriy * Задачи на http://acmp.ru * Тема. Двумерные массивы. * DONE ЗАДАЧА №265. Шахматная доска (Время: 1 сек. Память: 16 Мб Сложность: 26%) * Из шахматной доски по границам клеток выпилили связную (не распадающуюся на части) * фигуру без дыр. Требуется определить ее периметр. * Входные данные: * Во входном файле INPUT.TXT сначала записано число N (1 ≤ N ≤ 64) – количество выпиленных клеток. * В следующих N строках указаны координаты выпиленных клеток, разделенные пробелом * (номер строки и столбца – числа от 1 до 8). Каждая выпиленная клетка указывается один раз. * Выходные данные: * В выходной файл OUTPUT.TXT выведите одно число – периметр выпиленной фигуры (сторона клетки равна единице). * Примеры: * 3 * 1 1 * 1 2 * 2 1 >> 8 * 1 * 8 8 >> 4 * Формализованная задача. * Суммируем стороны ячейки, если это крайняя сторона или нет соседа. */ import java.io.PrintWriter; import java.util.Scanner; public class Acmp0265 { public static void main(String[] args){ Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); //инициируем переменную периметра int perimeter = 0;//минимальный размер периметра из одной клетки int cellSize = 1; //принимаем количество выпеленных ячеек int num = in.nextInt(); //инициируем массив для координат ячеек int[][] holes = new int[num][2]; //принимаем в цикле координаты ячеек и заполняем массив for (int i = 0; i < holes.length; i++) { for (int j = 0; j < holes[0].length; j++) { holes[i][j] = in.nextInt(); } } //вычисляем длину максимально возможного периода perimeter = num * cellSize * 4; //листаем массив сравниваем текущий элемент for (int i = 0; i < holes.length; i++) { //листаем массив сравниваем с остальными элементами for (int j = 0; j < holes.length; j++) { //проверяем не своя ли ячейка if(i != j){ //и есть ли сосед сверху(колонки равны, if(holes[i][1] == holes[j][1]) { //а строка меньше на 1) if (holes[i][0] - holes[j][0] == 1) { //если нет соседа, увеличиваем периметр на величину стороны perimeter -= cellSize; } //проверяем есть ли сосед снизу(колонки равны, а строка больше на 1) if(holes[j][0] - holes[i][0] == 1){ //если нет соседа, увеличиваем периметр на величину стороны perimeter -= cellSize; } } //и есть ли сосед слева(строки равны, if(holes[i][0] == holes[j][0]) { //а колонка меньше на 1) if (holes[i][1] - holes[j][1] == 1) { //если нет соседа, увеличиваем периметр на величину стороны perimeter -= cellSize; } //проверяем есть ли сосед справа(строки равны, а колонка больше на 1) if(holes[j][1] - holes[i][1] == 1){ //если нет соседа, увеличиваем периметр на величину стороны perimeter -= cellSize; } } } } } out.println(perimeter); out.flush(); } } //TODO временно //out.println("holes.length: " + holes.length); //out.println("holes[0].length: " + holes[0].length); //TODO временно /*for (int[] h : holes) { for (int c: h) { out.print(c + " "); } out.println(); }*/
package com.qa.test; import com.qa.core.Base; import java.util.Set; import org.testng.annotations.Test; public class HandleWindows extends Base { @Test public void verifyHomePageTitle() throws InterruptedException { browserSetup(); driver.manage().deleteAllCookies(); // Delete all the cookies driver.manage().window().maximize(); // Maximize the window System.out.println("Test Execution Started!!!"); driver.get("https://www.naukri.com"); String parent = driver.getWindowHandle(); System.out.println("Parent window id is "+parent); Set<String> totalwindow = driver.getWindowHandles(); int size =totalwindow.size(); for(String child:totalwindow) { System.out.println("window id is "+child); if(!parent.equalsIgnoreCase(child)) { String secondwindow = child; driver.switchTo().window(secondwindow); driver.close(); } Thread.sleep(3000); }}}
package com.example.NFEspring.repository; import com.example.NFEspring.entity.Ticket; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.Repository; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.Date; import java.util.Optional; import java.util.Set; @org.springframework.stereotype.Repository public interface ITicketRepository extends Repository<Ticket, Integer> { // @Transactional(readOnly = true) @Transactional(propagation = Propagation.REQUIRES_NEW) @Query("select ticket from Ticket ticket where ticket.id = :ticketId and ticket.deleted = false") Optional<Ticket> findById(@Param("ticketId") Integer ticketId); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.region is not null and ticket.deleted = false") Collection<Ticket> findByRegion(); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.region.id in :regionIds and ticket.deleted = false") Collection<Ticket> findByRegionIds(@Param("regionIds") Set<Integer> regionIds); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.tracker is not null and ticket.deleted = false") Collection<Ticket> findByTracker(); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.tracker.id in :trackerIds and ticket.deleted = false") Collection<Ticket> findByTrackerIds(@Param("trackerIds") Set<Integer> trackerIds); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.priority is not null and ticket.deleted = false") Collection<Ticket> findByPriority(); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.priority.id in :priorityIds and ticket.deleted = false") Collection<Ticket> findByPriorityIds(@Param("priorityIds") Set<Integer> priorityIds); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.status is not null and ticket.deleted = false") Collection<Ticket> findByStatus(); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.status.id in :statusIds and ticket.deleted = false") Collection<Ticket> findByStatusIds(@Param("statusIds") Set<Integer> statusIds); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.reporter is not null and ticket.deleted = false") Collection<Ticket> findByReporter(); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.reporter.id in :reporterIds and ticket.deleted = false") Collection<Ticket> findByReporterIds(@Param("reporterIds") Set<Integer> reporterIds); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket join Assignee assignee on assignee.ticket.id = ticket.id where ticket.deleted = false group by ticket.id") Collection<Ticket> findByAssignee(); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket join Assignee assignee on assignee.ticket.id = ticket.id and assignee.user.id in :assigneeIds where ticket.deleted = false") Collection<Ticket> findByAssigneeIds(@Param("assigneeIds") Set<Integer> assigneeIds); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.deleted = false") Collection<Ticket> findAll(); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.created >= :startDate and ticket.created <= :endDate") Collection<Ticket> findAllWithPeriode(@Param("startDate") Date startDate, @Param("endDate") Date endDate); @Transactional(readOnly = true) @Query("select ticket from Ticket ticket where ticket.id in :ticketIds and ticket.deleted = false") Collection<Ticket> findAllIds(@Param("ticketIds") Set<Integer> ticketIds); Ticket save(Ticket ticket); @Transactional @Modifying @Query("update Ticket ticket set ticket.deleted = true where ticket.id = :ticketId and ticket.archived = false") void eraseById(@Param("ticketId") int ticketId); }
package com.example.hp.cold_chain_logistic.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.hp.cold_chain_logistic.R; import com.example.hp.cold_chain_logistic.beans.GridViewItem; import java.util.List; /** * @author liz * @version V1.0 * @date 2018/4/8 */ public class GridViewAdapter extends BaseAdapter { private Context context; private List<GridViewItem> list; LayoutInflater layoutInflater; private ImageView mImageView; private TextView mTextView; public GridViewAdapter(Context context, List<GridViewItem> list) { this.context = context; this.list = list; layoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = layoutInflater.inflate(R.layout.item_gridview_fg_two, null); mImageView = (ImageView) convertView.findViewById(R.id.iv_gridview); mTextView=convertView.findViewById(R.id.tv_gridview); mImageView.setBackgroundResource(list.get(position).getImgId()); mTextView.setText(list.get(position).getIMSI()); return convertView; } }
package com.itheima.ssh01.dao; import com.itheima.ssh01.domain.User; /** * ClassName:UserDAO <br/> * Function: <br/> * Date: 2018年3月9日 上午9:04:21 <br/> */ public interface UserDAO { User findUserById(Integer id); }
package by.epam.kooks.action.get; import by.epam.kooks.action.constants.Constants; import by.epam.kooks.action.manager.Action; import by.epam.kooks.action.manager.ActionResult; import by.epam.kooks.service.BookService; import by.epam.kooks.service.exception.ServiceException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Action class, provide data for register new book customer * * @author Eugene Kooks */ public class PageBookRegisterAction implements Action { private static final Logger log = LogManager.getLogger(PageBookRegisterAction.class); @Override public ActionResult execute(HttpServletRequest request, HttpServletResponse response) { BookService bookService = new BookService(); try { request.setAttribute(Constants.GENRE_LIST, bookService.getAllGenre()); log.debug("Transfer book registration information"); } catch (ServiceException e) { log.warn("Can't transfer book registration information", e); } return new ActionResult(Constants.REGISTER_BOOK); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hw1.q02; /** * * @author yribbens */ public class Animal{ private String animal_type; private String animal_sound; public Animal(String type, String sound){ animal_type = type; animal_sound = sound; } public String getSound(){ return animal_sound; } public String getType(){ return animal_type; } }
// // Decompiled by Procyon v0.5.36 // package com.davivienda.multifuncional.tablas.edccargue.session; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import java.util.Collection; import java.util.Date; import javax.annotation.PostConstruct; import com.davivienda.multifuncional.tablas.edccargue.servicio.EdcMultifuncionalServicio; import javax.persistence.PersistenceContext; import javax.persistence.EntityManager; import javax.ejb.Stateless; import com.davivienda.sara.entitys.Edcarguemultifuncional; import com.davivienda.sara.base.BaseAdministracionTablas; @Stateless public class EdcMultifuncionalSessionBean extends BaseAdministracionTablas<Edcarguemultifuncional> implements EDCCargueMultifuncionalLocal { @PersistenceContext private EntityManager em; private EdcMultifuncionalServicio EdcCargueServicio; @PostConstruct public void postConstructor() { this.EdcCargueServicio = new EdcMultifuncionalServicio(this.em); super.servicio = this.EdcCargueServicio; } @Override public Collection<Edcarguemultifuncional> getEDCCargueXFecha(final Date fechaInicial, final Date fechaFinal) throws EntityServicioExcepcion { return this.EdcCargueServicio.getEDCCargueXFecha(fechaInicial, fechaFinal); } }
package com.csair.datatrs.common.processor; import com.csair.datatrs.common.Processor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Created by cloudoo on 2015/7/17. */ public class File2VectorProcessor implements Processor<List<double[]>> { protected static final Logger log = LoggerFactory.getLogger(File2VectorProcessor.class); public static String SPLIT_TEXT=" "; private String fileName; private List<double[]> vectors; public File2VectorProcessor(String fileName,List<double[]> vectors){ this.fileName = fileName; this.vectors = vectors; } public List<double[]> doit() { if(vectors==null){ log.error("未传入listֹ"); return null; } try { String line=""; BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); while ((line=br.readLine())!=null) { String[] temp = line.split(File2VectorProcessor.SPLIT_TEXT); double[] tempDouble = new double[temp.length]; for(int i=0;i<temp.length;i++){ tempDouble[i]= Double.parseDouble(temp[i]); } vectors.add(tempDouble); } } catch (FileNotFoundException e) { log.error("文件" + fileName + "没有找到", e); } catch (IOException e) { log.error("文件读取io错误",e); } return vectors; } public static void main(String[] args){ String fileName = "D:\\03_工作文件\\02_研究院\\01_项目\\05_大数据平台\\00_项目文档\\09_数据\\02_MIDT\\demo_,_div.txt"; List<double[]> vectors = new ArrayList<double[]>(); File2VectorProcessor file2VectorProcessor = new File2VectorProcessor(fileName,vectors); file2VectorProcessor.doit(); NormalizeProcessor normalizeProcessor = new NormalizeProcessor(vectors); normalizeProcessor.doit(); } }
/* * Copyright 2017 Rundeck, Inc. (http://rundeck.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rundeck.client.tool.options; import lombok.Getter; import lombok.Setter; import picocli.CommandLine; /** * @author greg * @since 3/2/17 */ @Getter @Setter public class PagingResultOptions { @CommandLine.Option(names = {"-m", "--max"}, description = "Maximum number of results to retrieve at once.") private Integer max; public boolean isMax() { return max != null && max > 0; } @CommandLine.Option(names = {"-o", "--offset"}, description = "First result offset to receive.") private Integer offset; public boolean isOffset() { return offset != null && offset > 0; } }
package com.project.info; import java.util.ArrayList; import com.segments.build.Segment; public class CPObject { public String value1; public String value2; public int Frequency; public Double Accuracy; public boolean isCorrectMapping; public boolean isCleaned;// save if we applied filter or not on this relation public CPObject(String value1, String value2) { this.value1 = value1; this.value2 = value2; this.Frequency = 1; this.isCleaned = false; this.Accuracy = 0.0; this.isCorrectMapping = false; } // for class instance public CPObject() { } public int isFound(ArrayList<CPObject> listOfCPObject) { int foundIndex = -1; for (int i = 0; i < listOfCPObject.size(); i++) { CPObject cpObject = listOfCPObject.get(i); if ((cpObject.value1.equals(this.value1) && cpObject.value2.equals(this.value2)) || (cpObject.value1.equals(this.value2) && cpObject.value2.equals(this.value1))) { foundIndex = i; break; } } return foundIndex; } public int isFoundUnique(ArrayList<CPObject> listOfCPObject) { int foundIndex = -1; for (int i = 0; i < listOfCPObject.size(); i++) { CPObject cpObject = listOfCPObject.get(i); if ((cpObject.value1.equals(this.value1) && cpObject.value2.equals(this.value2))) { foundIndex = i; break; } } return foundIndex; } public static ArrayList<CPObject> sort(ArrayList<CPObject> listOfFilterLibraries) { for (int i = 0; i < listOfFilterLibraries.size(); i++) { CPObject cPObject = listOfFilterLibraries.get(i); for (int j = 0; j < listOfFilterLibraries.size(); j++) { if (cPObject.Frequency > listOfFilterLibraries.get(j).Frequency) { listOfFilterLibraries.remove(i); listOfFilterLibraries.add(i, listOfFilterLibraries.get(j)); listOfFilterLibraries.remove(j); listOfFilterLibraries.add(j, cPObject); } } } return listOfFilterLibraries; } public ArrayList<Segment> objectToSegment(ArrayList<CPObject> listOfCP, double thresholdValue) { ArrayList<Segment> listOfSolvedFragments = new ArrayList<Segment>(); // ArrayList<CPObject> listOfCPCopy=listOfCP; double oldFilterValue = 0.0; // group output according to filter value ArrayList<String> addedCode = new ArrayList<String>(); ArrayList<String> removedCode = new ArrayList<String>(); for (CPObject cpObject : listOfCP) { if (cpObject.Accuracy >= thresholdValue) { // group same filter value under one fragments if (oldFilterValue != cpObject.Frequency) { if (addedCode.size() > 0 && removedCode.size() > 0) { Segment segment = new Segment(new ArrayList<String>(), addedCode, removedCode); listOfSolvedFragments.add(segment); } addedCode = new ArrayList<String>(); removedCode = new ArrayList<String>(); oldFilterValue = cpObject.Frequency; } addedCode.add(cpObject.value2); removedCode.add(cpObject.value1); } // end if } // end loop // add last element to group if (addedCode.size() > 0 && removedCode.size() > 0) { Segment segment = new Segment(new ArrayList<String>(), addedCode, removedCode); listOfSolvedFragments.add(segment); } return listOfSolvedFragments; } }
package io.zentity.model; import org.junit.Test; public class MatcherTest { public final static String VALID_OBJECT = "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}}}"; //// "matchers" ////////////////////////////////////////////////////////////////////////////////////////////////// @Test public void testValid() throws Exception { new Matcher("matcher_name", VALID_OBJECT); new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":0.5}"); } @Test(expected = ValidationException.class) public void testInvalidUnexpectedField() throws Exception { new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"foo\":\"bar\"}"); } //// "matchers".MATCHER_NAME ///////////////////////////////////////////////////////////////////////////////////// @Test(expected = ValidationException.class) public void testInvalidNameEmpty() throws Exception { new Matcher(" ", VALID_OBJECT); } //// "matchers".MATCHER_NAME."clause" //////////////////////////////////////////////////////////////////////////// @Test(expected = ValidationException.class) public void testInvalidClauseEmpty() throws Exception { new Matcher("matcher_name", "{\"clause\":{}}"); } @Test(expected = ValidationException.class) public void testInvalidClauseTypeArray() throws Exception { new Matcher("matcher_name", "{\"clause\":[]}"); } @Test(expected = ValidationException.class) public void testInvalidClauseTypeBoolean() throws Exception { new Matcher("matcher_name", "{\"clause\":true}"); } @Test(expected = ValidationException.class) public void testInvalidClauseTypeFloat() throws Exception { new Matcher("matcher_name", "{\"clause\":1.0}"); } @Test(expected = ValidationException.class) public void testInvalidClauseTypeInteger() throws Exception { new Matcher("matcher_name", "{\"clause\":1}"); } @Test(expected = ValidationException.class) public void testInvalidClauseTypeNull() throws Exception { new Matcher("matcher_name", "{\"clause\":null}"); } @Test(expected = ValidationException.class) public void testInvalidClauseTypeString() throws Exception { new Matcher("matcher_name", "{\"clause\":\"foobar\"}"); } //// "matchers".MATCHER_NAME."quality" /////////////////////////////////////////////////////////////////////////// @Test public void testValidQualityValue() throws Exception { new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":0.0}"); new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":0.5}"); new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":1.0}"); new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":null}"); } @Test(expected = ValidationException.class) public void testInvalidQualityTypeArray() throws Exception { new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":[]}"); } @Test(expected = ValidationException.class) public void testInvalidQualityTypeBoolean() throws Exception { new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":true}"); } @Test(expected = ValidationException.class) public void testInvalidQualityTypeInteger() throws Exception { new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":1}"); } @Test(expected = ValidationException.class) public void testInvalidQualityTypeFloatNegative() throws Exception { new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":-1.0}"); } @Test(expected = ValidationException.class) public void testInvalidQualityTypeObject() throws Exception { new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":{}}"); } @Test(expected = ValidationException.class) public void testInvalidQualityValueTooHigh() throws Exception { new Matcher("matcher_name", "{\"clause\":{\"match\":{\"{{ field }}\":\"{{ value }}\"}},\"quality\":100.0}"); } }
package com.fanfte.spring.jdbc; import java.util.List; /** * Created by tianen on 2019/3/25 * * @author fanfte * @date 2019/3/25 **/ public interface UserService { void save(User user); List<User> getUsers(); }
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.jspf.terms; import org.apache.james.jspf.core.MacroExpand; import org.apache.james.jspf.core.MacroExpandEnabled; import org.apache.james.jspf.core.SPFSession; import org.apache.james.jspf.core.exceptions.PermErrorException; /** * This abstract class represent a gerneric mechanism * */ public abstract class GenericMechanism implements Mechanism, ConfigurationEnabled, MacroExpandEnabled { /** * ABNF: ip4-cidr-length = "/" 1*DIGIT */ protected static final String IP4_CIDR_LENGTH_REGEX = "/(\\d+)"; /** * ABNF: ip6-cidr-length = "/" 1*DIGIT */ protected static final String IP6_CIDR_LENGTH_REGEX = "/(\\d+)"; /** * ABNF: dual-cidr-length = [ ip4-cidr-length ] [ "/" ip6-cidr-length ] */ protected static final String DUAL_CIDR_LENGTH_REGEX = "(?:" + IP4_CIDR_LENGTH_REGEX + ")?" + "(?:/" + IP6_CIDR_LENGTH_REGEX + ")?"; private String domain; protected MacroExpand macroExpand; /** * Expand the hostname * * @param spfData The SPF1Data to use * @throws PermErrorException get Thrown if invalid macros are used */ protected String expandHost(SPFSession spfData) throws PermErrorException { String host = getDomain(); if (host == null) { host = spfData.getCurrentDomain(); } else { // throws a PermErrorException that we cat pass through host = macroExpand.expand(host, spfData, MacroExpand.DOMAIN); } return host; } /** * @see org.apache.james.jspf.terms.ConfigurationEnabled#config(Configuration) */ public synchronized void config(Configuration params) throws PermErrorException { if (params.groupCount() >= 1 && params.group(1) != null) { domain = params.group(1); } else { domain = null; } } /** * @return Returns the domain. */ protected synchronized String getDomain() { return domain; } /** * @see org.apache.james.jspf.core.MacroExpandEnabled#enableMacroExpand(org.apache.james.jspf.core.MacroExpand) */ public void enableMacroExpand(MacroExpand macroExpand) { this.macroExpand = macroExpand; } }
package com.wkrzywiec.spring.library.entity; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @EqualsAndHashCode @ToString @NoArgsConstructor @Entity @Table(name="user_password_token") public class UserPasswordToken { public static final int EXPIRATION = 60 * 24; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private int id; @Column(name="token") private String token; @OneToOne (fetch=FetchType.EAGER) @JoinColumn(name="user_id") private User user; @Column(name="due_date") private Timestamp dueDate; }
package com.cc.faas.dbmanager.rest; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.cc.faas.dbmanager.rest.constants.ExceptionConstants; import com.cc.faas.dbmanager.rest.pojo.Function; import com.cc.faas.dbmanager.rest.service.FunctionServiceImpl; import com.cc.faas.dbmanager.rest.util.Helper; import com.cc.faas.dbmanager.rest.util.Message; @Path("/functions") public class FunctionHandler { private FunctionServiceImpl functionService = new FunctionServiceImpl(); @GET @Path("/{id}") public Response getFunctionById(@PathParam("id") String id) { Function requestedFunction=null; try { requestedFunction=functionService.getFunctionById(id); } catch (Exception e) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(Helper.convertToJsonString(new Message(e.getMessage()))).build(); } if(requestedFunction==null){ return Response.status(Status.NOT_FOUND).entity(Helper.convertToJsonString(new Message(ExceptionConstants.ID_NOT_EXIST))).build(); }else{ return Response.status(Status.OK).entity(Helper.convertToJsonString(requestedFunction)).build(); } } @GET public Response getAllFunctions() { List<Function> functions; try { functions=functionService.getFunctions(); } catch (Exception e) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(Helper.convertToJsonString(new Message(e.getMessage()))).build(); } return Response.status(Status.OK).entity(Helper.convertToJsonString(functions)).build(); } @GET @Path("/{username}/{functioname}") public Response getFunctionByUserNameAndFunctionName(@PathParam("username") String username,@PathParam("functioname") String functioname) { Function requestedFunction=null; try { requestedFunction=functionService.getFunctionByUserNameAndFunctionName(username, functioname); } catch (Exception e) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(Helper.convertToJsonString(new Message(e.getMessage()))).build(); } if(requestedFunction==null){ return Response.status(Status.NOT_FOUND).entity(Helper.convertToJsonString(new Message(ExceptionConstants.NAME_NOT_EXIST))).build(); }else{ return Response.status(Status.OK).entity(Helper.convertToJsonString(requestedFunction)).build(); } } @POST @Consumes(MediaType.APPLICATION_JSON) public Response createFunction(Function function) { if(function==null||function.getFunctionName()==null||function.getFunctionName().isEmpty()||function.getFunctionContent()==null||function.getFunctionContent().isEmpty()||function.getCreator()==null||function.getCreator().getUserId()==null||function.getCreator().getUserId().isEmpty()){ return Response.status(Status.BAD_REQUEST).entity(Helper.convertToJsonString(new Message(ExceptionConstants.NULL_EMPTY_INPUT))).build(); } try{ Function createdFunction=functionService.createFunction(function); return Response.status(Status.CREATED).entity(Helper.convertToJsonString(createdFunction)).build(); }catch(Exception ex){ if(Helper.checkBadRequest(ex)){ return Response.status(Status.BAD_REQUEST).entity(Helper.convertToJsonString(new Message(ex.getMessage()))).build(); } return Response.status(Status.INTERNAL_SERVER_ERROR).entity(Helper.convertToJsonString(new Message(ex.getMessage()))).build(); } } @PUT @Consumes(MediaType.APPLICATION_JSON) public Response updateFunction(Function function) { if(function==null||function.getFunctionId()==null||function.getFunctionId().isEmpty()||function.getFunctionName()==null||function.getFunctionName().isEmpty()||function.getFunctionContent()==null||function.getFunctionContent().isEmpty()||function.getCreator()==null||function.getCreator().getUserId()==null||function.getCreator().getUserId().isEmpty()){ return Response.status(Status.BAD_REQUEST).entity(Helper.convertToJsonString(new Message(ExceptionConstants.NULL_EMPTY_INPUT))).build(); } try{ Function updatedFunction=functionService.updateFunction(function); return Response.status(Status.OK).entity(Helper.convertToJsonString(updatedFunction)).build(); }catch(Exception ex){ if(Helper.checkBadRequest(ex)){ return Response.status(Status.BAD_REQUEST).entity(Helper.convertToJsonString(new Message(ex.getMessage()))).build(); } return Response.status(Status.INTERNAL_SERVER_ERROR).entity(Helper.convertToJsonString(new Message(ex.getMessage()))).build(); } } @DELETE @Path("/{functionId}") public Response deleteFunction(@PathParam("functionId") String id) { try{ functionService.deleteFunction(id); return Response.status(Status.NO_CONTENT).build(); }catch(Exception ex){ return Response.status(Status.INTERNAL_SERVER_ERROR).entity(Helper.convertToJsonString(new Message(ex.getMessage()))).build(); } } }
package br.agroamigos.controller; import br.agroamigos.exception.ResourceNotFoundException; import br.agroamigos.model.Cotacao; import br.agroamigos.repository.CotacaoRepository; import br.agroamigos.repository.IndicadorRepository; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @Api(value = "Cotação", description = "Cotação dos indicadores") public class CotacaoController { @Autowired private CotacaoRepository cotacaoRepository; @Autowired private IndicadorRepository indicadorRepository; @GetMapping("/indicadores/{indicadorId}/cotacoes") public Page<Cotacao> getAllCotacoesByIndicadorId(@PathVariable(value = "indicadorId") Integer indicadorId, Pageable pageable) { return cotacaoRepository.findByIndicador(indicadorId, pageable); } // @PostMapping("/indicadores/{indicadorId}/cotacoes") // public Cotacao postCotacao(@PathVariable (value = "indicadorId") Integer indicadorId, // @Valid @RequestBody Cotacao cotacao) { // return indicadorRepository.findById(indicadorId).map(indicador -> { // cotacao.setIndicador(indicador); // return cotacaoRepository.save(cotacao); // }).orElseThrow(()-> new ResourceNotFoundException("Indicador", "não encontrado", indicadorId)); // } }
public class Question6 { public static void main(String[] x) { int n=33; boolean flag=false; for(int i=2;i<=n/2;++i) { if(n%i==0) { flag=true; break; } } if(!flag) System.out.println(n + "number is prime"); else System.out.println(n + "number is not prime"); } }
package Pack_2; public class Jugador { //Variables// private String nombre; private String apellido1; private String apellido2; private int edad; private int id; private int puntos; public Jugador() { System.out.println("JUGADOR"); } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido1() { return apellido1; } public void setApellido1(String apellido1) { this.apellido1 = apellido1; } public String getApellido2() { return apellido2; } public void setApellido2(String apellido2) { this.apellido2 = apellido2; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPuntos() { return puntos; } public void setPuntos(int puntos) { this.puntos = puntos; } //Integer para Edad// public boolean isNumeric(String cadena){ try{ Integer.parseInt(cadena); return true; } catch (NumberFormatException nfe){ return false; } } //Espacios en Blanco// public boolean espaciosBlanco(String blanco) { for(int i = 0; i<blanco.length(); i++) if(blanco.charAt(i) != ' ') return false; return true; } public String toString(){ return this.nombre+ " " +this.apellido1+ " " +this.apellido2+ " " +this.edad+ " aņos" +this.id+ " " +this.puntos; } }
package com.zs.ui.home.present; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.View; import com.google.gson.Gson; import com.huaiye.sdk.HYClient; import com.huaiye.sdk.core.SdkCallback; import com.huaiye.sdk.core.SdkCaller; import com.huaiye.sdk.core.SdkNotifyCallback; import com.huaiye.sdk.logger.Logger; import com.huaiye.sdk.sdkabi._api.ApiSocial; import com.huaiye.sdk.sdkabi._api.ApiTalk; import com.huaiye.sdk.sdkabi._params.SdkParamsCenter; import com.huaiye.sdk.sdpmsgs.face.CServerNotifyAlarmInfo; import com.huaiye.sdk.sdpmsgs.meet.CStartMeetingReq; import com.huaiye.sdk.sdpmsgs.social.CNotifyUserStatus; import com.huaiye.sdk.sdpmsgs.social.SendUserBean; import com.huaiye.sdk.sdpmsgs.talk.trunkchannel.CGetTrunkChannelInfoRsp; import com.huaiye.sdk.sdpmsgs.talk.trunkchannel.CQueryTrunkChannelListRsp; import com.huaiye.sdk.sdpmsgs.talk.trunkchannel.TrunkChannelBean; import com.huaiye.sdk.sdpmsgs.talk.trunkchannel.TrunkChannelUserBean; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.zs.R; import com.zs.bus.CreateMeet; import com.zs.bus.CreateTalkAndVideo; import com.zs.common.AppUtils; import com.zs.common.dialog.DeviceListPopupWindow; import com.zs.common.dialog.GroupListPopupWindow; import com.zs.common.dialog.LogicDialog; import com.zs.common.dialog.UserListPopupWindow; import com.zs.common.recycle.LiteBaseAdapter; import com.zs.common.rx.RxUtils; import com.zs.dao.AppDatas; import com.zs.dao.msgs.ChangeUserBean; import com.zs.dao.msgs.ChatUtil; import com.zs.dao.msgs.VssMessageListBean; import com.zs.dao.msgs.VssMessageListMessages; import com.zs.models.ModelCallback; import com.zs.models.contacts.ContactsApi; import com.zs.models.contacts.bean.PersonBean; import com.zs.models.contacts.bean.PersonModelBean; import com.zs.models.device.DeviceApi; import com.zs.models.device.bean.DeviceListBean; import com.zs.models.device.bean.DevicePlayerBean; import com.zs.ui.channel.ChannelDetailActivity; import com.zs.ui.chat.ChatActivity; import com.zs.ui.device.DevicePlayRealActivity; import com.zs.ui.device.holder.DeviceHolder; import com.zs.ui.device.holder.GroupHolder; import com.zs.ui.device.holder.PersonHolder; import com.zs.ui.home.view.IContactsView; import ttyy.com.jinnetwork.core.work.HTTPResponse; /** * author: admin * date: 2018/05/07 * version: 0 * mail: secret * desc: DeviceListPresent */ public class ContactsPresent { private final int PERSON = 0; private final int GROUP = 1; private final int DEVICE = 2; IContactsView iView; ArrayList<PersonModelBean> personList = new ArrayList<>(); LiteBaseAdapter<PersonModelBean> personAdapter; Map<String, PersonModelBean> selectedAll = new HashMap<>(); // int total_person; // int rel_person; int person_order = 0; boolean isOnline = true; ArrayList<TrunkChannelBean> groupList = new ArrayList<>(); LiteBaseAdapter<TrunkChannelBean> groupAdapter; TrunkChannelBean currentGroup; int total_group; int group_order = 0; ArrayList<DevicePlayerBean> deviceList = new ArrayList<>(); LiteBaseAdapter<DevicePlayerBean> deviceAdapter; int total_device; int device_order = 0; UserListPopupWindow userListPopupWindow; DeviceListPopupWindow deviceListPopupWindow; GroupListPopupWindow groupListPopupWindow; int index = PERSON; boolean isLoad; int size = 999; // int pagePerson = 1; // int pageGroup = 1; // int pageDevice = 1; SdkCaller observeUserStatus; SdkNotifyCallback<CServerNotifyAlarmInfo> deviceStatusListener; public ContactsPresent(final IContactsView iView) { this.iView = iView; userListPopupWindow = new UserListPopupWindow(iView.getContext()); userListPopupWindow.setConfirmClickListener(new UserListPopupWindow.ConfirmClickListener() { @Override public void onClickXingShiShengXu(boolean choose) { person_order = 0; loadPerson(true); } @Override public void onClickXingShiJiangXu(boolean choose) { person_order = 1; loadPerson(true); } @Override public void onClickOnLine(boolean choose) { isOnline = choose; loadPerson(true); } }); deviceListPopupWindow = new DeviceListPopupWindow(iView.getContext()); deviceListPopupWindow.setConfirmClickListener(new DeviceListPopupWindow.ConfirmClickListener() { @Override public void onClickXingShiShengXu(boolean choose) { device_order = 0; com.huaiye.sdk.logger.Logger.debug("loadDevice from deviceListPopupWindow onClickXingShiShengXu" ); loadDevice(true); } @Override public void onClickXingShiJiangXu(boolean choose) { device_order = 1; com.huaiye.sdk.logger.Logger.debug("loadDevice from deviceListPopupWindow onClickXingShiJiangXu" ); loadDevice(true); } }); groupListPopupWindow = new GroupListPopupWindow(iView.getContext()); groupListPopupWindow.setConfirmClickListener(new GroupListPopupWindow.ConfirmClickListener() { @Override public void onClickXingShiShengXu(boolean choose) { group_order = 0; loadGroup(true); } @Override public void onClickXingShiJiangXu(boolean choose) { group_order = 1; loadGroup(true); } }); personAdapter = new LiteBaseAdapter<>(iView.getContext(), personList, PersonHolder.class, R.layout.item_person_holder, new View.OnClickListener() { @Override public void onClick(View v) { if (!PersonHolder.selected_mode) { // ((ContactsActivity) iView.getContext()).iv_right_choose.performClick(); PersonHolder.selected_mode = !PersonHolder.selected_mode; refAdapter(PersonHolder.selected_mode); } if (!PersonHolder.selected_mode) { return; } PersonModelBean bean = (PersonModelBean) v.getTag(); if (selectedAll.containsKey(bean.strUserID)) { selectedAll.remove(bean.strUserID); if (selectedAll.isEmpty()) { // ((ContactsActivity) iView.getContext()).iv_right_choose.performClick(); PersonHolder.selected_mode = !PersonHolder.selected_mode; refAdapter(PersonHolder.selected_mode); } } else { selectedAll.put(bean.strUserID, bean); } changeMenu(); personAdapter.notifyDataSetChanged(); } }, selectedAll); // personAdapter.setLoadListener(new LiteBaseAdapter.LoadListener() { // @Override // public boolean isLoadOver() { // return !isLoad; // } // // @Override // public boolean isEnd() { // return rel_person >= total_person; // } // // @Override // public void lazyLoad() { // loadPerson(false); // } // }); // 监听 用户状态 observeUserStatus = HYClient.getModule(ApiSocial.class).observeUserStatus(new SdkNotifyCallback<CNotifyUserStatus>() { @Override public void onEvent(final CNotifyUserStatus data) { Logger.debug("ContactsPresent observeUserStatus " + data.toString()); boolean hasThis = false; for (PersonModelBean temp : personList) { if (temp.strUserID.equals(data.strUserID)) { hasThis = true; if (data.isOnline()) { temp.nStatus = PersonModelBean.STATUS_ONLINE_IDLE; if (data.isCapturing()) { temp.nStatus = PersonModelBean.STATUS_ONLINE_CAPTURING; } if (data.isTalking()) { temp.nStatus = PersonModelBean.STATUS_ONLINE_TALKING; } if (data.isMeeting()) { temp.nStatus = PersonModelBean.STATUS_ONLINE_MEETING; } if (data.isTrunkSpeaking()){ temp.nStatus = PersonModelBean.STATUS_ONLINE_TRUNK_SPEAKING; } } else { temp.nStatus = PersonModelBean.STATUS_OFFLINE; } if (data.nOnline == -1) { personList.remove(temp); } break; } } if (!hasThis) { loadPerson(true); } else { personAdapter.notifyDataSetChanged(); } } }); // 监听 设备状态 deviceStatusListener = new SdkNotifyCallback<CServerNotifyAlarmInfo>() { @Override public void onEvent(final CServerNotifyAlarmInfo data) { boolean hasThis = false; // DevicePlayerBean offlineDevice = null; //设置最新状态,更新adapter for (DevicePlayerBean temp : deviceList) { if (temp.strDeviceCode.equals(data.strDeviceCode)) { hasThis = true; if (data.nAlarmType == DeviceApi.NOTIFY_TYPE_DEIVCE_OFFLINE) { temp.nOnlineState = 2; }else { temp.nOnlineState = 1; } deviceAdapter.notifyDataSetChanged(); break; } } // if (offlineDevice != null){ // deviceList.remove(offlineDevice); // deviceAdapter.notifyDataSetChanged(); // } if (!hasThis) { loadDevice(true); } } }; DeviceApi.get().addAlarmListener(deviceStatusListener); groupAdapter = new LiteBaseAdapter<>(iView.getContext(), groupList, GroupHolder.class, R.layout.item_group_holder, new View.OnClickListener() { @Override public void onClick(View v) { TrunkChannelBean bean = (TrunkChannelBean) v.getTag(); if (currentGroup == null) { for (TrunkChannelBean temp : groupList) { if (temp == bean) { temp.extr = true; currentGroup = bean; } else { temp.extr = false; } } } else { if (currentGroup == bean) { currentGroup.extr = false; currentGroup = null; } else { for (TrunkChannelBean temp : groupList) { if (temp == bean) { temp.extr = true; currentGroup = bean; } else { temp.extr = false; } } } } changeMenu(); groupAdapter.notifyDataSetChanged(); } }, ""); // groupAdapter.setLoadListener(new LiteBaseAdapter.LoadListener() { // @Override // public boolean isLoadOver() { // return !isLoad; // } // // @Override // public boolean isEnd() { // return groupList.size() >= total_group; // } // // @Override // public void lazyLoad() { // loadGroup(false); // } // }); deviceAdapter = new LiteBaseAdapter<>(iView.getContext(), deviceList, DeviceHolder.class, R.layout.item_device_holder, new View.OnClickListener() { @Override public void onClick(View v) { com.huaiye.sdk.logger.Logger.debug("ContactsPresent onClick start"); DevicePlayerBean bean = (DevicePlayerBean) v.getTag(); if (bean == null){ com.huaiye.sdk.logger.Logger.debug("ContactsPresent onClick bean null"); }else { com.huaiye.sdk.logger.Logger.debug("ContactsPresent onClick bean " + bean.toString()); } Intent intent = new Intent(iView.getContext(), DevicePlayRealActivity.class); intent.putExtra("data", bean); iView.getContext().startActivity(intent); } }, ""); // deviceAdapter.setLoadListener(new LiteBaseAdapter.LoadListener() { // @Override // public boolean isLoadOver() { // com.huaiye.sdk.logger.Logger.debug("deviceAdapter isLoadOver " + isLoad); // return !isLoad; // } // // @Override // public boolean isEnd() { // com.huaiye.sdk.logger.Logger.debug("deviceAdapter isEnd " + deviceList.size() + " total " + total_device ); // return deviceList.size() >= total_device; // } // // @Override // public void lazyLoad() { // com.huaiye.sdk.logger.Logger.debug("loadDevice from deviceAdapter lazyLoad" ); // loadDevice(false); // } // }); } public void loadPerson(final boolean isRef) { // if (isRef) // pagePerson = 1; // else // pagePerson++; isLoad = true; ContactsApi.get().getPerson(1, size, 0, person_order, new ModelCallback<PersonBean>() { @Override public void onSuccess(PersonBean personBean) { // total_person = personBean.nTotalSize; loadFinish(); if (isRef) { // rel_person = 0; personList.clear(); } if (personBean.userList != null) { // rel_person += personBean.userList.size(); for (PersonModelBean bean : personBean.userList) { if (!bean.strUserID.equals(AppDatas.Auth().getUserID() + "")) { if (bean.nStatus > PersonModelBean.STATUS_OFFLINE && bean.nSpeaking == 2){ bean.nStatus = PersonModelBean.STATUS_ONLINE_TRUNK_SPEAKING; } if (isOnline) { if (bean.nStatus > PersonModelBean.STATUS_OFFLINE) { personList.add(bean); } } else { personList.add(bean); } } } } if (index == PERSON) { changeViewShow(personList.isEmpty()); } personAdapter.notifyDataSetChanged(); } @Override public void onFailure(HTTPResponse httpResponse) { super.onFailure(httpResponse); loadFinish(); iView.getContext().showToast(AppUtils.getString(R.string.get_person_false)); } }); } public void loadGroup(final boolean isRef) { // if (isRef) // pageGroup = 1; // else // pageGroup++; isLoad = true; HYClient.getModule(ApiTalk.class) .queryTrunkChannel(SdkParamsCenter.Talk.QueryTrunkChannel() .setnReverse(group_order) .setnTrunkChannelType(TrunkChannelBean.CHANNLE_TYPE_DEFAULT|TrunkChannelBean.CHANNLE_TYPE_STATIC|TrunkChannelBean.CHANNLE_TYPE_TMP_ING) .setnSize(size), new SdkCallback<CQueryTrunkChannelListRsp>() { @Override public void onSuccess(CQueryTrunkChannelListRsp resp) { total_group = resp.nTotalSize; loadFinish(); groupList.clear(); ArrayList<TrunkChannelBean> trunkChannelBeans = resp.lstTrunkChannelInfo; if (trunkChannelBeans != null){ for (TrunkChannelBean bean : trunkChannelBeans){ if (bean.nTrunkChannelType != TrunkChannelBean.CHANNLE_TYPE_TMP_FINISH){ groupList.add(bean); } } } if (currentGroup != null) { for (TrunkChannelBean temp : groupList) { if (temp.nTrunkChannelID == currentGroup.nTrunkChannelID) { temp.extr = currentGroup.extr; break; } } } if (index == GROUP) { changeViewShow(groupList.isEmpty()); } groupAdapter.notifyDataSetChanged(); } @Override public void onError(ErrorInfo error) { loadFinish(); } }); } /** * 加载设备 */ public void loadDevice(final boolean isRef) { com.huaiye.sdk.logger.Logger.debug("loadDevice start " + isRef); isLoad = true; DeviceApi.get().getDomainDeviceList(1, 999, device_order, new ModelCallback<DeviceListBean>() { @Override public void onSuccess(DeviceListBean deviceListBean) { Gson gson = new Gson(); String strDeviceList = gson.toJson(deviceListBean); com.huaiye.sdk.logger.Logger.debug("loadDevice ret = " + strDeviceList); total_device = deviceListBean.nTotalSize; loadFinish(); if (isRef) deviceList.clear(); if (deviceListBean.deviceList != null && !deviceListBean.deviceList.isEmpty()) { for (DeviceListBean.DeviceBean temp : deviceListBean.deviceList) { for (DeviceListBean.ChannelBean channelBean : temp.channelList) { DevicePlayerBean bean = new DevicePlayerBean(); bean.strChannelName = channelBean.strChannelName; bean.strChannelCode = channelBean.strChannelCode; bean.strDeviceCode = temp.strDeviceCode; bean.strDomainCode = temp.strDomainCode; bean.nOnlineState = temp.nOnlineState; if (channelBean.streamList.isEmpty()){ continue; } bean.strStreamCode = channelBean.streamList.get(0).strStreamCode; if (channelBean.streamList.size()> 1){ bean.strSubStreamCode = channelBean.streamList.get(1).strStreamCode; } // if (channelBean.streamList == null || channelBean.streamList.size() == 0) { // com.huaiye.sdk.logger.Logger.debug("device " + channelBean.strChannelName +" stream is empty " ); // }else { // bean.strStreamCode = channelBean.streamList.get(0).strStreamCode; // if (channelBean.streamList.size()> 1){ // bean.strSubStreamCode = channelBean.streamList.get(1).strStreamCode; // } // } deviceList.add(bean); } } } if (index == DEVICE) { changeViewShow(deviceList.isEmpty()); } com.huaiye.sdk.logger.Logger.debug("device list size = " + deviceList.size()); deviceAdapter.notifyDataSetChanged(); } @Override public void onFailure(HTTPResponse httpResponse) { super.onFailure(httpResponse); com.huaiye.sdk.logger.Logger.debug("device list failure " +httpResponse.getErrorMessage()); loadFinish(); iView.getContext().showToast(AppUtils.getString(R.string.get_device_false)); } }); } /** * 语音 */ public void phoneClick() { switch (index) { case PERSON: String domain = null; String userId = null; String userName = null; for (Map.Entry<String, PersonModelBean> entry : selectedAll.entrySet()) { PersonModelBean value = entry.getValue(); domain = value.strDomainCode; userId = value.strUserID; userName = value.strUserName; } iView.getContext().finish(); final String finalDomain = domain; final String finalUserId = userId; final String finalUserName = userName; RxUtils rxUtils = new RxUtils(); rxUtils.doDelayOn(1000, new RxUtils.IMainDelay() { @Override public void onMainDelay() { EventBus.getDefault().post(new CreateTalkAndVideo(false, finalDomain, finalUserId, finalUserName, null, "ContactsPresent 481")); } }); break; case GROUP: break; } } /** * 指令 */ public void zhiHuiClick() { List<VssMessageListBean> allBean = VssMessageListMessages.get().getMessages(); switch (index) { case PERSON: ArrayList<SendUserBean> sessionUserList = new ArrayList<>(); //先添加选中的 for (Map.Entry<String, PersonModelBean> entry : selectedAll.entrySet()) { PersonModelBean value = entry.getValue(); sessionUserList.add(new SendUserBean(value.strUserID, value.strDomainCode, value.strUserName)); } //再添加自己,这里创建人肯定是自己 sessionUserList.add(new SendUserBean(AppDatas.Auth().getUserID() + "", AppDatas.Auth().getDomainCode(), AppDatas.Auth().getUserName())); //一对一对话有没有重复创建 VssMessageListBean oldBean = null; if (sessionUserList.size() == 2) { //allbean是本地已经存在的会话列表 for (VssMessageListBean bean : allBean) { //本地存在的一个会话中人数为2 // 并且两个人与这次即将新建的人id相同 if (bean.sessionUserList.size() == 2 && (bean.sessionUserList.get(0).strUserID.equals(sessionUserList.get(0).strUserID) || bean.sessionUserList.get(0).strUserID.equals(sessionUserList.get(1).strUserID) && (bean.sessionUserList.get(1).strUserID.equals(sessionUserList.get(0).strUserID) || bean.sessionUserList.get(1).strUserID.equals(sessionUserList.get(1).strUserID)))) { oldBean = bean; break; } } } //如果有的话就填充listBean Intent intent = new Intent(iView.getContext(), ChatActivity.class); if (oldBean != null) { intent.putExtra("listBean", oldBean); } else { intent.putExtra("sessionUserList", sessionUserList); } iView.getContext().startActivity(intent); break; case GROUP: if (currentGroup != null) { VssMessageListBean oldGroup = null; for (VssMessageListBean bean : allBean) { if (bean.sessionID.equals(currentGroup.nTrunkChannelID + "")) { oldGroup = bean; break; } } Intent intent1 = new Intent(iView.getContext(), ChatActivity.class); if (oldGroup != null) { intent1.putExtra("listBean", oldGroup); } intent1.putExtra("channelName", currentGroup.strTrunkChannelName); intent1.putExtra("channelId", currentGroup.nTrunkChannelID + ""); intent1.putExtra("sessionDomainCode", currentGroup.strTrunkChannelDomainCode + ""); intent1.putExtra("isGroup", true); iView.getContext().startActivity(intent1); } break; } } /** * 观察 */ public void watchClick() { String domain = null; String userId = null; String userName = null; for (Map.Entry<String, PersonModelBean> entry : selectedAll.entrySet()) { PersonModelBean value = entry.getValue(); domain = value.strDomainCode; userId = value.strUserID; userName = value.strUserName; } ChatUtil.get().reqGuanMo(userId, domain, userName); } /** * 会议 */ public void meetClick() { switch (index) { case PERSON: final ArrayList<CStartMeetingReq.UserInfo> allUser = new ArrayList<>(); for (Map.Entry<String, PersonModelBean> entry : selectedAll.entrySet()) { PersonModelBean value = entry.getValue(); CStartMeetingReq.UserInfo bean = new CStartMeetingReq.UserInfo(); bean.setDevTypeUser(); bean.strUserDomainCode = value.strDomainCode; bean.strUserID = value.strUserID; bean.strUserName = value.strUserName; allUser.add(bean); } if (allUser.size() > 10) { final LogicDialog dialog = iView.getContext().getLogicDialog() .setMessageText(AppUtils.getString(R.string.user_more)); dialog.setConfirmText(AppUtils.getString(R.string.cancel)); dialog.setCancelText(AppUtils.getString(R.string.makesure)); dialog.setConfirmClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBus.getDefault().post(new CreateMeet(allUser)); iView.getContext().finish(); } }).setCancelClickListener(new View.OnClickListener() { @Override public void onClick(View v) { allUser.clear(); } }).show(); } else { EventBus.getDefault().post(new CreateMeet(allUser)); iView.getContext().finish(); } break; case GROUP: getGroupUser(true); break; } } /** * 频道点击详情 */ public void channelClick() { if (currentGroup != null) { Intent intent = new Intent(iView.getContext(), ChannelDetailActivity.class); intent.putExtra("trunkChannelBean", currentGroup); iView.getContext().startActivity(intent); } } /** * 视频 */ public void videoClick() { switch (index) { case PERSON: String domain = null; String userId = null; String userName = null; for (Map.Entry<String, PersonModelBean> entry : selectedAll.entrySet()) { PersonModelBean value = entry.getValue(); domain = value.strDomainCode; userId = value.strUserID; userName = value.strUserName; } final String finalDomain = domain; final String finalUserId = userId; final String finalUserName = userName; new RxUtils<>().doDelayOn(1000, new RxUtils.IMainDelay() { @Override public void onMainDelay() { EventBus.getDefault().post(new CreateTalkAndVideo(true, finalDomain, finalUserId, finalUserName, null, "ContactsPresent 641")); } }); break; case GROUP: break; } } private void getGroupUser(final boolean isMeet) { if (currentGroup != null) { HYClient.getModule(ApiTalk.class) .getTrunkChannelInfo(SdkParamsCenter.Talk.GetTrunkChannelInfo() .setnTrunkChannelID(currentGroup.nTrunkChannelID) .setStrTrunkChannelDomainCode(currentGroup.strTrunkChannelDomainCode), new SdkCallback<CGetTrunkChannelInfoRsp>() { @Override public void onSuccess(final CGetTrunkChannelInfoRsp cGetTrunkChannelInfoRsp) { if (cGetTrunkChannelInfoRsp.lstTrunkChannelUser.size() > 10) { final LogicDialog dialog = iView.getContext().getLogicDialog() .setMessageText(AppUtils.getString(R.string.user_more)); dialog.setConfirmText(AppUtils.getString(R.string.cancel)); dialog.setCancelText(AppUtils.getString(R.string.makesure)); dialog.setConfirmClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fromGroupCreateMeet(cGetTrunkChannelInfoRsp, isMeet); } }).show(); } else { fromGroupCreateMeet(cGetTrunkChannelInfoRsp, isMeet); } } @Override public void onError(ErrorInfo errorInfo) { } }); } } /** * 群组创建会议 * * @param cGetTrunkChannelInfoRsp * @param isMeet */ private void fromGroupCreateMeet(CGetTrunkChannelInfoRsp cGetTrunkChannelInfoRsp, boolean isMeet) { ArrayList<TrunkChannelUserBean> lstTrunkChannelUser; if (cGetTrunkChannelInfoRsp == null) { iView.getContext().showToast(AppUtils.getString(R.string.get_group_false)); return; } if (cGetTrunkChannelInfoRsp.lstTrunkChannelUser == null) { iView.getContext().showToast(AppUtils.getString(R.string.get_group_false)); return; } if (cGetTrunkChannelInfoRsp.lstTrunkChannelUser.size() == 0) { iView.getContext().showToast(AppUtils.getString(R.string.get_group_empty)); return; } if (isMeet) { ArrayList<CStartMeetingReq.UserInfo> allUser = new ArrayList<>(); for (TrunkChannelUserBean temp : cGetTrunkChannelInfoRsp.lstTrunkChannelUser) { CStartMeetingReq.UserInfo bean = new CStartMeetingReq.UserInfo(); bean.setDevTypeUser(); bean.strUserDomainCode = temp.strTcUserDomainCode; bean.strUserID = temp.strTcUserID; bean.strUserName = temp.strTcUserName; allUser.add(bean); } EventBus.getDefault().post(new CreateMeet(allUser)); iView.getContext().finish(); } else { ArrayList<SendUserBean> sessionUserList = new ArrayList<>(); for (TrunkChannelUserBean temp : cGetTrunkChannelInfoRsp.lstTrunkChannelUser) { sessionUserList.add(new SendUserBean(temp.strTcUserID, temp.strTcUserDomainCode, temp.strTcUserName)); } sessionUserList.add(new SendUserBean(AppDatas.Auth().getUserID() + "", AppDatas.Auth().getDomainCode(), AppDatas.Auth().getUserName())); Intent intent = new Intent(iView.getContext(), ChatActivity.class); intent.putExtra("sessionUserList", sessionUserList); intent.putExtra("channelName", currentGroup.strTrunkChannelName); intent.putExtra("sessionID", currentGroup.nTrunkChannelID + ""); intent.putExtra("sessionDomainCode", currentGroup.strTrunkChannelDomainCode + ""); intent.putExtra("isGroup", true); iView.getContext().startActivity(intent); } } private void loadFinish() { isLoad = false; iView.getRefView().setRefreshing(false); } public LiteBaseAdapter getDeviceAdapter() { index = DEVICE; isLoad = false; changeMenu(); return deviceAdapter; } public RecyclerView.Adapter getPersonAdapter() { index = PERSON; isLoad = false; changeMenu(); return personAdapter; } public RecyclerView.Adapter getGroupAdapter() { index = GROUP; isLoad = false; changeMenu(); return groupAdapter; } /** * 改变可点击的view */ public void changeMenu() { switch (index) { case PERSON: if (selectedAll.size() == 1) { PersonModelBean value = null; for (Map.Entry<String, PersonModelBean> entry : selectedAll.entrySet()) { value = entry.getValue(); break; } iView.personSingle(value.nPriority); } else if (selectedAll.size() > 1) { iView.personMulite(); } else { iView.personNull(); } break; case GROUP: if (currentGroup == null) { iView.personNull(); } else { if (currentGroup.extr == null) { iView.personNull(); } else { if ((boolean) currentGroup.extr) { iView.groupSingle(); } else { iView.personNull(); } } } break; case DEVICE: break; } } public ArrayList<PersonModelBean> getPersonList() { return personList; } public ArrayList<TrunkChannelBean> getGroupList() { return groupList; } public ArrayList<DevicePlayerBean> getDeviceList() { return deviceList; } public void changeViewShow(boolean isEmpty) { if (isEmpty) { iView.getEmptyView().setVisibility(View.VISIBLE); iView.getListView().setVisibility(View.GONE); } else { iView.getEmptyView().setVisibility(View.GONE); iView.getListView().setVisibility(View.VISIBLE); } } public void showPopu(View v) { switch (index) { case PERSON: userListPopupWindow.showView(v); break; case GROUP: groupListPopupWindow.showView(v); break; case DEVICE: deviceListPopupWindow.showView(v); break; } } public void refAdapter(boolean selected) { if (!selected) { selectedAll.clear(); changeMenu(); } personAdapter.notifyDataSetChanged(); } /** * 改变数据 * * @param bean */ public void refBean(ChangeUserBean bean) { for (PersonModelBean temp : personList) { if (temp.strUserID.equals(bean.strModifyUserID) && temp.strDomainCode.equals(bean.strModifyUserDomainCode)) { temp.strUserName = bean.strModifyUserName; temp.nPriority = bean.nPriority; break; } } personAdapter.notifyDataSetChanged(); for (Map.Entry<String, PersonModelBean> entry : selectedAll.entrySet()) { if (entry.getValue().strUserID.equals(bean.strModifyUserID) && entry.getValue().strDomainCode.equals(bean.strModifyUserDomainCode)) { entry.getValue().strUserName = bean.strModifyUserName; entry.getValue().nPriority = bean.nPriority; changeMenu(); break; } } } public void destory(){ if (observeUserStatus != null){ observeUserStatus.cancel(); } if (deviceStatusListener != null){ DeviceApi.get().removeAlarmListener(deviceStatusListener); deviceStatusListener = null; } } }
package com.example.firstprogram.SOS; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.model.LatLng; import com.example.Class.GetAllParams; import com.example.Class.Person; import com.example.evaluate.EvaluateMainActivity; import com.example.firstprogram.R; import com.example.firstprogram.TopBar; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class SosIngActivity extends Activity { private TextView textview; private TopBar topbar; private String url; private int event_id; private Person person; private GetAllParams c; private JSONObject answer; //private JSONObject obj; //地图显示相关 private BaiduMap mBaiduMap; private MapView mMapView; //帮客们的坐标 private List<LatLng> support_latlng_list = new ArrayList<>(); //绘制帮客的坐标 private DrawIcon drawIcon; //定位相关 boolean isFirstLoc = true; private LocationClient mLocClient; //定时更新相关 Handler handler=new Handler(); Runnable runnable=new Runnable() { @Override public void run() { //要做的事情 //Toast.makeText(SosIngActivity.this, "refresh", Toast.LENGTH_SHORT).show(); refresh_support_location(); handler.postDelayed(this, 5000); } }; private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.sos_ing_activity); intent = getIntent(); //初始化 url = "http://120.24.208.130:1503/event/modify"; person = (Person) getApplication(); Intent intent = getIntent(); //获取上一个activity的intent里的事件ID“event_id" event_id = intent.getIntExtra("event_id",-1); init(); topbar_setting(); //地图初始化 mMapView = (MapView) findViewById(R.id.bmapView); mBaiduMap = mMapView.getMap(); //定位相关 mBaiduMap.setMyLocationEnabled(true); // 定位初始化 mLocClient = new LocationClient(this); mLocClient.registerLocationListener(new MyLocationListenner()); LocationClientOption option = new LocationClientOption(); option.setOpenGps(true);// 打开gps option.setCoorType("bd09ll"); // 设置坐标类型 option.setScanSpan(1000);//发起定位请求的间隔时间 mLocClient.setLocOption(option); mLocClient.start(); //模拟着一组帮客坐标 //support_latlng_list = getSupportLalngList(); drawIcon = new DrawIcon(this, support_latlng_list, mBaiduMap); //启动计时器 handler.postDelayed(runnable, 5000); } private void init() { textview = (TextView) findViewById(R.id.textview1); c = new GetAllParams(this); } private void refresh_support_location(){ JSONObject param = new JSONObject(); try { param.put("event_id",intent.getIntExtra("event_id",0)); param.put("id", person.getId()); } catch (JSONException e) { e.printStackTrace(); } c.getList("http://120.24.208.130:1503/event/get_supporter", param, new GetAllParams.VolleyJsonCallback() { @Override public void onSuccess(JSONObject result) { try { if (result.getInt("status") == 200) { JSONArray array = result.getJSONArray("user_account"); List<LatLng> temp1 = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { JSONObject temp = (JSONObject) array.get(i); LatLng l = new LatLng(temp.getDouble("latitude"), temp.getDouble("longitude")); temp1.add(l); } drawIcon.resetOverlay(temp1); textview.setText("已有" + temp1.size() + "人赶来救助"); } } catch (JSONException e) { e.printStackTrace(); } } }); } /** * 定位SDK监听函数 */ public class MyLocationListenner implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { // map view 销毁后不在处理新接收的位置 if (location == null || mMapView == null) return; MyLocationData locData = new MyLocationData.Builder() .accuracy(location.getRadius()) // 此处设置开发者获取到的方向信息,顺时针0-360 .direction(100).latitude(location.getLatitude()) .longitude(location.getLongitude()).build(); mBaiduMap.setMyLocationData(locData); if (isFirstLoc) { isFirstLoc = false; LatLng ll = new LatLng(location.getLatitude(), location.getLongitude()); MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll); mBaiduMap.animateMapStatus(u); } } public void onReceivePoi(BDLocation poiLocation) { } } /*对topbar的设置*/ private void topbar_setting(){ //setOnTopbarClickListener topbar = (TopBar) findViewById(R.id.topbar_in_sosing); topbar.setOnTopbarClickListener(new TopBar.topbarClickListener() { @Override public void leftClick() {//点击中止求救 AlertDialog.Builder dialog = new AlertDialog.Builder(SosIngActivity.this); dialog.setMessage("确认中止求救吗?您将会被扣除1个积分!"); dialog.setTitle("提示"); dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ///////////////////////////////////////////////// //向后台发送 中止求救 请求,把事件状态改为 “1”--结束状态 JSONObject map = new JSONObject(); c = new GetAllParams(SosIngActivity.this); JSONObject temp = new JSONObject(); try { map.put("id", person.getId());//用户的id map.put("event_id",event_id);//事件的id map.put("state",1);//事件的状态,0是进行中,1是结束状态 map.put("type",0);//操作类型,0是中止求救,1是完成求救 //下面是向后台发送请求 temp = c.getList(url, map, new GetAllParams.VolleyJsonCallback() { @Override public void onSuccess(JSONObject result) { //answer = result; Toast.makeText(SosIngActivity.this, "求救已中止", Toast.LENGTH_SHORT).show(); SosIngActivity.this.finish();//结束”求救中“页面 } }); } catch (JSONException e) { e.printStackTrace(); } } }); dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.create().show(); } @Override public void rightClick() throws UnsupportedEncodingException { Toast.makeText(SosIngActivity.this, " next UI", Toast.LENGTH_SHORT).show(); AlertDialog.Builder dialog = new AlertDialog.Builder(SosIngActivity.this); dialog.setMessage("确认完成求救吗?"); dialog.setTitle("提示"); dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); /////////////////////////////////////////////////////////////////////// // 向后台发送 完成求救 请求,把事件状态改为 “1”--结束状态 //跟上面差不多 JSONObject map = new JSONObject(); c = new GetAllParams(SosIngActivity.this); JSONObject temp = new JSONObject(); answer = new JSONObject(); try { map.put("id", person.getId()); map.put("event_id",event_id); map.put("state",1); map.put("type",1); temp = c.getList(url, map, new GetAllParams.VolleyJsonCallback() { @Override public void onSuccess(JSONObject result) { answer = result; Toast.makeText(SosIngActivity.this, "求救已完成", Toast.LENGTH_SHORT).show(); //SosIngActivity.this.finish();//结束”求救中“页面 Intent intent = new Intent(SosIngActivity.this, EvaluateMainActivity.class); intent.putExtra("event_id", event_id); startActivity(intent);//跳转到下一页 finish(); } }); } catch (JSONException e) { e.printStackTrace(); } } }); dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.create().show(); } }); } @Override protected void onDestroy() { super.onDestroy(); mMapView.onDestroy(); handler.removeCallbacks(runnable); } @Override protected void onResume() { super.onResume(); mMapView.onResume(); } @Override protected void onPause() { super.onPause(); mMapView.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK ) { Toast.makeText(SosIngActivity.this, "请选择“中止求救”或“完成求救”", Toast.LENGTH_SHORT).show(); } return false; } }
import javax.swing.*; import java.awt.*; import java.lang.reflect.Field; import java.util.*; /** * MainFrame class of the GUI */ public class MainFrame extends JFrame { private Dimension mainSize = new Dimension(400, 400); private ImageIcon deckIcon; private static JLabel stackLabel; private static JPanel bottomPanel; static JPanel topPanel; static JPanel mainPanel; private JTextArea _protocol; public JPanel outputPanel; static Controller controller; /** * Standard Konstruktor des MainFrame * Baut die GUI auf und verbindet sie mit dem Controller * * @param controller Controller Objekt, der zur Steuerung verwendet werden soll */ public MainFrame(Controller controller) { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // setLayout(new GridLayout(2,1,10,10)); setLayout(new BorderLayout(10, 10)); mainPanel = new JPanel(new GridLayout(2, 1, 10, 10)); add(mainPanel, BorderLayout.CENTER); setTitle("Uno"); setPreferredSize(mainSize); topPanel = new JPanel(); topPanel.setLayout(new GridLayout(1, 3, 10, 10)); bottomPanel = new JPanel(); // bottomPanel.setBackground(Color.DARK_GRAY); mainPanel.add(topPanel); mainPanel.add(bottomPanel); outputPanel = new JPanel(); outputPanel.setBackground(Color.BLUE); // JPanel stackPanel = new JPanel(); stackLabel = new JLabel("leer"); this.controller = controller; /** * Wird deckButton gedrückt, wird eine Karte gezogen */ //final JButton deckButton = new JButton(); DrawButton deckButton = new DrawButton(); deckIcon = new ImageIcon(getClass().getResource("images/Back1.png")); Image img = deckIcon.getImage(); Image newimg = img.getScaledInstance(175, 350, java.awt.Image.SCALE_SMOOTH); deckIcon = new ImageIcon(newimg); deckButton.setIcon(deckIcon); deckButton.addMouseListener(controller); // stackPanel.add(stackButton); // stackPanel.setBackground(Color.GREEN); // JPanel deckPanel = new JPanel(); // deckPanel.setBackground(Color.YELLOW); topPanel.add(outputPanel); // topPanel.add(stackPanel); topPanel.add(stackLabel); _protocol = new JTextArea("Protokoll:"); _protocol.setBackground(this.getContentPane().getBackground()); _protocol.setEditable(false); topPanel.add(_protocol); topPanel.add(deckButton); // pack(); // get the screen size as a java dimension Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // get 2/3 of the height, and 2/3 of the width int height = screenSize.height * 2 / 3; int width = screenSize.width * 1 / 2; // set the jframe height and width this.setMinimumSize(new Dimension(width, height)); setVisible(true); } /** * Updated den Kartenstack und gibt an welche Karte oben liegt * * @param topCard Liegende oberste Karte */ public void refreshStack(UnoCard topCard) { stackLabel.setText(topCard.get_color() + ", " + topCard.get_number()); setColorOfUpperCard(topCard); setVisible(true); } /** * Repaints the GUI area where that represents the players hand / cards * * @param playerCards ArrayList of Cards the player is holding on his hand */ public void repaintPlayerCards(ArrayList<UnoCard> playerCards) { bottomPanel.removeAll(); bottomPanel.setLayout(new GridLayout(1, playerCards.size())); for (UnoCard c : playerCards) { PlayerCardButton playerCard = new PlayerCardButton(c); playerCard.addMouseListener(controller); playerCard.setFont(new Font("Arial", Font.BOLD, 40)); playerCard.setText(String.valueOf(c.get_number())); Color cardColor; try { Field field = Class.forName("java.awt.Color").getField(c.get_color()); cardColor = (Color)field.get(null); } catch (Exception e) { cardColor = null; // Not defined } playerCard.setBackground(cardColor); bottomPanel.add(playerCard); } bottomPanel.repaint(); } public void Message(String message) { this.stackLabel.setText(message); } /** * Schreibt einen String in das Protokoll feld in der Oberfläche * sollte immer mittels SwingUtilities.invokeLater aufgerufen werden * * @param text Zeichenkette, die dem Protokoll hinzugefügt werden soll */ public void writeToProtocol(String text) { if (_protocol.getLineCount() > 16) { _protocol.setText("Protokoll: "); } _protocol.append("\n" + text); _protocol.setCaretPosition(_protocol.getDocument().getLength()); } /** * Passt die Farbe des Feldes in der Oberfläche der Farbe der liegenden Karte an. * * @param unoCard Karte an deren Farbe das Feld in der Oberfläche angepasst werden soll */ private void setColorOfUpperCard(UnoCard unoCard) { Color color; try { Field field = Class.forName("java.awt.Color").getField(unoCard.get_color()); color = (Color) field.get(null); } catch (Exception e) { color = null; // Not defined e.printStackTrace(); } outputPanel.setBackground(color); outputPanel.repaint(); outputPanel.setVisible(true); } }
//our catch default throw && our catch our throw package exception_handling; import java.lang.*; import java.util.Scanner; public class ExceptionHandling1 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("enter the balance :"); int balance=sc.nextInt(); System.out.println("enter the withdrawl:"); int withdrawl=sc.nextInt(); System.out.print("balance amount is :"+balance); System.out.println(); System.out.print("withdrawl amount is: "+withdrawl); System.out.println(); try { if(withdrawl>balance) throw new ArithmeticException("insufficient balance:"); System.out.println("you can withdrawl:"); balance-=withdrawl; System.out.println("new balance is "+balance); } catch(ArithmeticException e) { System.out.println("oh! sorry: "+e.getMessage()); } finally { System.out.println("visited again:"); System.out.println("thankyou :"); } } }
package com.demo.aws.json; import java.util.Collection; public class ResponseList<T> { private Integer total; private Collection<T> items; public ResponseList(Integer total, Collection<T> items) { this.total = total; this.items = items; } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public Collection<T> getItems() { return items; } public void setItems(Collection<T> items) { this.items = items; } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.engine; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.Collection; import org.junit.Test; import pl.edu.icm.unity.stdext.attr.StringAttribute; import pl.edu.icm.unity.stdext.attr.StringAttributeSyntax; import pl.edu.icm.unity.stdext.identity.X500Identity; import pl.edu.icm.unity.types.EntityState; import pl.edu.icm.unity.types.I18nString; import pl.edu.icm.unity.types.basic.AttributeExt; import pl.edu.icm.unity.types.basic.AttributeStatement2; import pl.edu.icm.unity.types.basic.AttributeStatement2.ConflictResolution; import pl.edu.icm.unity.types.basic.AttributeType; import pl.edu.icm.unity.types.basic.AttributeVisibility; import pl.edu.icm.unity.types.basic.EntityParam; import pl.edu.icm.unity.types.basic.Group; import pl.edu.icm.unity.types.basic.Identity; import pl.edu.icm.unity.types.basic.IdentityParam; public class TestAttributeStatements2 extends DBIntegrationTestBase { private EntityParam entity; private Group groupA; private Group groupAB; private AttributeType at2; @Test public void onlyOneEntityGetsAttributeCopiedFromSubgroupIfAssignedWithStatementInSubgroup() throws Exception { setupStateForConditions(); Identity id2 = idsMan.addEntity(new IdentityParam(X500Identity.ID, "cn=golbi2"), "crMock", EntityState.disabled, false); EntityParam entity2 = new EntityParam(id2); groupsMan.addMemberFromParent("/A", entity2); AttributeStatement2 statement1 = AttributeStatement2.getFixedEverybodyStatement( new StringAttribute("a2", "/A/B", AttributeVisibility.local, "VV")); groupAB.setAttributeStatements(new AttributeStatement2[] {statement1}); groupsMan.updateGroup("/A/B", groupAB); AttributeStatement2 statement2 = new AttributeStatement2("eattrs contains 'a2'", "/A/B", ConflictResolution.skip, new StringAttribute("a2", "/A", AttributeVisibility.local, "NEW")); groupA.setAttributeStatements(new AttributeStatement2[] {statement2}); groupsMan.updateGroup("/A", groupA); Collection<AttributeExt<?>> aRet = attrsMan.getAllAttributes(entity2, true, "/A", "a2", false); assertThat(aRet.isEmpty(), is(true)); Collection<AttributeExt<?>> aRet2 = attrsMan.getAllAttributes(entity, true, "/A", "a2", false); assertThat(aRet2.size(), is(1)); } private void setupStateForConditions() throws Exception { setupMockAuthn(); at2 = createSimpleAT("a2"); at2.setMaxElements(Integer.MAX_VALUE); attrsMan.addAttributeType(at2); groupA = new Group("/A"); groupsMan.addGroup(groupA); groupAB = new Group("/A/B"); groupsMan.addGroup(groupAB); Identity id = idsMan.addEntity(new IdentityParam(X500Identity.ID, "cn=golbi"), "crMock", EntityState.disabled, false); entity = new EntityParam(id); groupsMan.addMemberFromParent("/A", entity); groupsMan.addMemberFromParent("/A/B", entity); } private AttributeType createSimpleAT(String name) { AttributeType at = new AttributeType(); at.setValueType(new StringAttributeSyntax()); at.setDescription(new I18nString("desc")); at.setFlags(0); at.setMaxElements(5); at.setMinElements(1); at.setName(name); at.setSelfModificable(true); at.setVisibility(AttributeVisibility.local); return at; } }
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import model.Item; import model.Post; public class PostDao { public List<Item> getSalesReport(Post post) { /* * The students code to fetch data from the database will be written here * Each record is required to be encapsulated as a "Item" class object and added to the "items" List * Query to get sales report for a particular month must be implemented * post, which has details about the month and year for which the sales report is to be generated, is given as method parameter * The month and year are in the format "month-year", e.g. "10-2018" and stored in the expireDate attribute of post object * The month and year can be accessed by getter method, i.e., post.getExpireDate() */ List<Item> items = new ArrayList<Item>(); /*Sample data begins*/ // for (int i = 0; i < 10; i++) { // Item item = new Item(); // item.setName("Sample item"); // item.setSoldPrice(100); // items.add(item); // } /*Sample data ends*/ try { Class.forName("com.mysql.cj.jdbc.Driver"); // String dbPass = System.getenv("DB_PASSWORD"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/quickbid", "root", "password"); Statement s = con.createStatement(); String[] date = post.getExpireDate().split("-"); ResultSet query_results = s.executeQuery("select * from auctions " + "inner join item " + "on item.item_id = auctions.item_id " + "inner join bid " + "on bid.auction_id = auctions.auction_id " + "where auctions.is_closed = 1 and" + " MONTH(bid_time) = " + date[0] + " and YEAR(bid_time) = " + date[1] + " and auctions.current_high_bid = bid.bid_price"); while(query_results.next()) { Item item = new Item(); item.setItemID(query_results.getInt("item_id")); item.setName(query_results.getString("name")); item.setType(query_results.getString("type")); item.setNumCopies(query_results.getInt("num_copies")); item.setDescription(query_results.getString("description")); item.setSoldPrice(query_results.getInt("current_high_bid")); item.setYearManufactured(query_results.getInt("year_manufactured")); items.add(item); } } catch(Exception e) { System.out.println(e); } return items; } }
package com.eliffuruncu.sqliteproject; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { TextView txt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt=(TextView)findViewById(R.id.sqlTxt); try { SQLiteDatabase database=this.openOrCreateDatabase("Musicians",MODE_PRIVATE,null); database.execSQL("CREATE TABLE IF NOT EXISTS musicians(id INTEGER PRIMARY KEY,name VARCHAR,age INT)"); //veri kaydetme // database.execSQL("INSERT INTO musicians (name,age) VALUES ('James',50)"); // database.execSQL("INSERT INTO musicians (name,age) VALUES ('Lars',60)"); //database.execSQL("INSERT INTO musicians (name,age) VALUES ('Kirk',55)"); //Güncelleme //database.execSQL("UPDATE musicians SET age = 61 where name = 'Lars'"); //Silme // database.execSQL("DELETE FROM musicians WHERE id = 2"); //Filtreleme //Cursor cursor = database.rawQuery("SELECT * FROM musicians where age >52",null); //like // Cursor cursor=database.rawQuery("SELECT * FROM musicians WHERE name like 'K%'",null); //Tüm kayıtlı verileri getirir. Cursor cursor = database.rawQuery("SELECT * FROM musicians",null); int nameIx = cursor.getColumnIndex("name"); int ageIx = cursor.getColumnIndex("age"); int idx= cursor.getColumnIndex("id"); ArrayList<Integer> ids=new ArrayList<>(); ArrayList<String> names=new ArrayList<>(); ArrayList<Integer> ages=new ArrayList<>(); while(cursor.moveToNext()) { System.out.println("Name: "+ cursor.getString(nameIx)); System.out.println("Age: "+ cursor.getString(ageIx)); System.out.println("Id: "+ cursor.getInt(idx)); ids.add(cursor.getInt(idx)); names.add(cursor.getString(nameIx)); ages.add(cursor.getInt(idx)); } cursor.close(); String RegisteredDatas=""; for(int i=0;i<names.size();i++) { RegisteredDatas+=" Id: "+ids.get(i)+" - Name: "+names.get(i)+" - Age: "+ages.get(i); } txt.setText(RegisteredDatas); }catch (Exception e) { e.printStackTrace(); } } }