blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
c01e36ee0147c1b7e7841acd9718c14cf6277320
d9bebdbe54272d6f9628513c15774426aebb96e6
/conway-structured-streaming/src/test/java/com/mkwhitacre/conway/spark/streaming/ConwayStructuredStreamingToolTest.java
4b3c430df50945689cdb2f6fde421c05f6084c47
[]
no_license
mkwhitacre/conway-life-processing
bf40af56ca970c95cc4188b8a487c8bc6e9d2377
92d2c9ab9d9ac3e05f83c2c49f86bf0a4694d6f2
refs/heads/master
2021-01-20T01:35:42.369316
2017-06-08T02:34:39
2017-06-08T02:34:39
89,303,634
1
1
null
null
null
null
UTF-8
Java
false
false
262
java
package com.mkwhitacre.conway.spark.streaming; import org.junit.Test; public class ConwayStructuredStreamingToolTest { @Test public void test() throws Exception { String[] args = {}; ConwayStructuredStreamingTool.main(args); } }
0916496b9f58c1c8c323f446c6b44bace38615b2
0a6fc16101eb23523a98188fd5f9f36cd4a4904e
/src/main/java/com/onlinepay/manage/web/util/HttpRequestUtil.java
ddacac47de2251199dc6a481621be17b4099521a
[]
no_license
soloicesky/OLPmanage
4c7559638d56bd53950626f6730f63b49d6782b0
0309b442baffb5308383827c0dcf498bfbdfb1a7
refs/heads/master
2020-04-13T14:17:43.372657
2018-12-09T14:16:48
2018-12-09T14:16:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
711
java
package com.onlinepay.manage.web.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; /** * TODO: * Created by tom on 17/7/4. */ public class HttpRequestUtil { private static final Logger log = LoggerFactory.getLogger(HttpRequestUtil.class); public static String getContentPath(HttpServletRequest request){ String requestUrl = request.getRequestURL().toString(); String requestUri = request.getRequestURI(); int endIndex = requestUrl.indexOf(requestUri); String path = requestUrl.substring(0,endIndex); log.info("Path = {}",request.getContextPath()); return request.getContextPath(); } }
310725154f84cfd001c7880511bdd92ffdb1d135
42e0ea86f91783cb6462eff9acae29f1cec955ca
/projectJava/firstProject/src/ada/lesson/mosh/ExWhile.java
30099ea58d9516d839c032f9f83a91f1978a6d9b
[]
no_license
Ada-Kiekhaefer/otherProjects
376ff45611f091b8edc100ebcb0df287f356acad
9ea16387aa799ac4bd2a068ca2e5dd40abc5beab
refs/heads/master
2022-09-20T07:49:50.550381
2020-06-04T15:06:26
2020-06-04T15:06:26
269,390,488
0
0
null
null
null
null
UTF-8
Java
false
false
881
java
package ada.lesson.mosh; import java.util.Scanner; public class ExWhile { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("---- Ex 1 ------"); Scanner scanner = new Scanner(System.in); String input = ""; // while (!input.equals("quit")) { while(true) { // make sure to have break statement with while(true) System.out.println("Input (quit to exit): "); input = scanner.next().toLowerCase(); if (input.equals("pass")) continue; if (input.equals("quit")) break; System.out.println(input); } System.out.println("---- Ex 2 ------"); //do while loop, check condition later //use while loop most of the time do { System.out.println("Input (quit to exit): "); input = scanner.next().toLowerCase(); System.out.println(input); } while (!input.equals("quit")); } }
8e07214d819f35b8bafa2698f969b60db645c485
863e9120918b0d3ed9ceb5e5563dc29fc9cd82ff
/FlagsAndPatterns/src/PatternDrawer.java
568a9d0f3f972fc87c77a6365226489dec06184d
[]
no_license
onecl800/Bootcamp_Projects
f7a9c025a243bee01b0e4c396bacede6368c65d1
5317a03e47ad9eec93c2346430cb6bffa9007703
refs/heads/master
2020-05-27T11:05:15.633409
2017-02-20T10:30:49
2017-02-20T10:30:49
82,544,006
0
0
null
null
null
null
UTF-8
Java
false
false
5,123
java
// This program is copyright VUW. // You are granted permission to use it to construct your answer to a SWEN131 assignment. // You may not distribute it in any other way without permission. /* Code for SWEN131 * Name: * Usercode: * ID: */ import java.awt.Color; import ecs100.*; public class PatternDrawer{ public static final double boardLeft = 50; // Top left corner of the board public static final double boardTop = 50; public static final double boardSize = 300; // The size of the board on the window /** Draw a square grid board with white squares. * Asks the user for the number of squares on each side * * CORE */ public void drawGridBoard(){ UI.clearGraphics(); int num = UI.askInt("How many rows:"); int squares = num; double widthOfSquare = boardSize/num; for (num = 1; num < squares; num++) { double x = boardLeft + (widthOfSquare * num); UI.drawRect(x, boardTop, widthOfSquare, boardSize); UI.println("I loop" + "X = " + x + " Y = " + boardTop); } for (num = 0; num < squares; num++) { double y = boardTop + (widthOfSquare * num); UI.drawRect(boardLeft, y, boardSize, widthOfSquare); UI.println("J loop" + "X = " + boardLeft + " Y = " + y); } } /** Illusion * a pattern that makes dark circles appear in the intersections * when you look at it. **/ public void drawIllusion(){ UI.clearGraphics(); int num = UI.askInt("How many rows:"); int square = num; double widthOfSquare = boardSize / num; // draw black square UI.setColor(Color.black); UI.fillRect(boardLeft, boardTop, boardSize, boardSize); for (square = 1; square < num; square++) { //draw white horizontal lines double rx1 = boardLeft; double ry1 = boardTop + (widthOfSquare * square); double rx2 = boardLeft + boardSize; double ry2 = boardTop + (widthOfSquare * square); UI.setLineWidth(10); UI.setColor(Color.white); UI.drawLine(rx1, ry1, rx2, ry2); UI.println("RX1 = " + rx1 + " RY1 = " + ry1 + " RX2 = " + rx2 + " RY2 = " + ry2); //draw white vertical lines double cx1 = boardLeft + (widthOfSquare * square); double cy1 = boardTop; double cx2 = boardLeft + (widthOfSquare * square); double cy2 = boardTop + boardSize; UI.setLineWidth(10); UI.setColor(Color.white); UI.drawLine(cx1, cy1, cx2, cy2); UI.println("CX1 = " + cx1 + " Cy1 = " + cy1 + " CX2 = " + cx2 + " CY2 = " + cy2); } } /** Draw a checkered board with alternating black and white squares * Asks the user for the number of squares on each side * * COMPLETION */ public void drawCheckersBoard(){ UI.clearGraphics(); int num = UI.askInt("How many rows:"); double widthOfSquare = boardSize/num; Color evenSquare = Color.gray; Color oddSquare = Color.black; int row = 0; int column = 0; for (row = 0; row < num; row++) { for (column = 0; column < num; column++) { double x = boardLeft + ((boardSize/num) * row); double y = boardTop + ((boardSize/num) * column); if ((row+column)%2 == 0) { UI.setColor(evenSquare); UI.fillRect(x, y, widthOfSquare, widthOfSquare); } else { UI.setColor(oddSquare); UI.fillRect(x, y, widthOfSquare, widthOfSquare); } } } } /** Draw a board made of concentric circles, 2 pixel apart * Asks the user for the number of squares on each side */ public void drawConcentricBoard(){ UI.clearGraphics(); int num = UI.askInt("How many rows: "); double widthOfCircle = boardSize/num; double row; double column; double circle; double numInnerCircles = ((boardSize/num) / 4); for (row = 0; row < num; row++) { for (column = 0; column < num; column++) { double x = boardLeft + ((boardSize/num) * row); double y = boardTop + ((boardSize/num) * column); UI.drawOval(x, y, widthOfCircle, widthOfCircle); //UI.println("x: " + x + " y: " + " width: " + widthOfCircle); for (circle = 0; circle < numInnerCircles; circle++) { double innerX = x + (2 * circle); double innerY = y + (2 * circle); double innerWidthOfCircle = widthOfCircle - (4 * circle); UI.drawOval(innerX, innerY, innerWidthOfCircle, innerWidthOfCircle); //UI.println("number of inner circles: " + numInnerCircles); //UI.println("innerX: " + innerX + " innerY: " + innerY + " inner Width: " + innerWidthOfCircle); } } } } }
8576978a197853ad626f88ea1cf060c3c912cab9
8c13057a9aef75e68ace14dabdb6cfc243546ba0
/src/main/java/com/project/projectjeju/daos/ArticleDao.java
c028795811570154687ccd980bffc5bdbbebf8c9
[]
no_license
Xepy-source/projectjeju
61ac004e2ee6d64fda3fa9ac9917b8ca5d4cffbb
356f4f6df26e33374efd7d4821858764baa48923
refs/heads/master
2023-02-06T00:47:42.067490
2020-12-30T05:57:24
2020-12-30T05:57:24
325,467,609
0
0
null
null
null
null
UTF-8
Java
false
false
7,347
java
package com.project.projectjeju.daos; import com.project.projectjeju.enums.ArticleResult; import com.project.projectjeju.vos.InsertArticleVo; import com.project.projectjeju.vos.ModifyArticleVo; import org.springframework.stereotype.Repository; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @Repository public class ArticleDao { public int getArticleCount(Connection connection) throws SQLException { int count = -1; String query = "SELECT COUNT(`article_index`) AS `count` FROM `project_jeju`.`articles`"; try (PreparedStatement preparedStatement = connection.prepareStatement(query)) { try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { count = resultSet.getInt("count"); } } } return count; } public int getUserCount(Connection connection) throws SQLException { int count = -1; String query = "SELECT COUNT(`user_index`) AS `count` FROM `project_jeju`.`users`"; try (PreparedStatement preparedStatement = connection.prepareStatement(query)) { try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { count = resultSet.getInt("count"); } } } return count; } public ArticleResult insertArticle(Connection connection, InsertArticleVo insertArticleVo) throws SQLException { String query = "insert into `project_jeju`.`articles` " + "(`user_index`, `article_title`, `article_image`, `board_classification`, `article_location`, `article_content`, `article_hashtag`) " + "values (?, ?, ?, ?, ?, ? ,?)"; try (PreparedStatement preparedStatement = connection.prepareStatement(query)) { preparedStatement.setInt(1, insertArticleVo.getWriterIndex()); preparedStatement.setString(2, insertArticleVo.getTitle()); preparedStatement.setString(3, insertArticleVo.getImage()); preparedStatement.setString(4, insertArticleVo.getClassification()); preparedStatement.setString(5, insertArticleVo.getLocation()); preparedStatement.setString(6, insertArticleVo.getContent()); preparedStatement.setString(7, insertArticleVo.getHashtags()); if (preparedStatement.executeUpdate() == 1) { return ArticleResult.SUCCESS; } else { return ArticleResult.FAILURE; } } } public ArticleResult deleteArticle(Connection connection, int articleIndex) throws SQLException { String query = "DELETE FROM `project_jeju`.`articles` WHERE `article_index` = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(query)) { preparedStatement.setInt(1, articleIndex); if (preparedStatement.executeUpdate() == 1) { return ArticleResult.SUCCESS; } else { return ArticleResult.FAILURE; } } } public ArticleResult modifyArticleAndImage(Connection connection, ModifyArticleVo modifyArticleVo) throws SQLException { String query = "UPDATE `project_jeju`.`articles` " + "SET `article_title`=?, `article_image`=?, `article_location`=?, " + "`article_content`=?, `article_hashtag`=?, `board_classification`=? " + "WHERE `article_index`=?"; try (PreparedStatement preparedStatement = connection.prepareStatement(query)) { preparedStatement.setString(1, modifyArticleVo.getTitle()); preparedStatement.setString(2, modifyArticleVo.getImage()); preparedStatement.setString(3, modifyArticleVo.getLocation()); preparedStatement.setString(4, modifyArticleVo.getContent()); preparedStatement.setString(5, modifyArticleVo.getHashtags()); preparedStatement.setString(6, modifyArticleVo.getClassification()); preparedStatement.setInt(7, modifyArticleVo.getArticleIndex()); if (preparedStatement.executeUpdate() == 1) { return ArticleResult.SUCCESS; } else { return ArticleResult.FAILURE; } } } public ArticleResult modifyArticleNoneImage(Connection connection, ModifyArticleVo modifyArticleVo) throws SQLException { String query = "UPDATE `project_jeju`.`articles` " + "SET `article_title`=?, `article_location`=?, " + "`article_content`=?, `article_hashtag`=?, `board_classification`=? " + "WHERE `article_index`=?"; try (PreparedStatement preparedStatement = connection.prepareStatement(query)) { preparedStatement.setString(1, modifyArticleVo.getTitle()); preparedStatement.setString(2, modifyArticleVo.getLocation()); preparedStatement.setString(3, modifyArticleVo.getContent()); preparedStatement.setString(4, modifyArticleVo.getHashtags()); preparedStatement.setString(5, modifyArticleVo.getClassification()); preparedStatement.setInt(6, modifyArticleVo.getArticleIndex()); if (preparedStatement.executeUpdate() == 1) { return ArticleResult.SUCCESS; } else { return ArticleResult.FAILURE; } } } public ModifyArticleVo modifyGetArticle(Connection connection, int index) throws SQLException { ModifyArticleVo modifyArticleVo = null; String query = "SELECT `article_index` AS `articleIndex`, " + "`article_title` AS `title`, " + "`user_nickname` AS `nickname`, " + "`board_classification` AS `classification`, " + "`article_location` AS `location`, " + "`article_content` AS `content`, " + "`article_hashtag` AS `hashtags` " + "FROM `project_jeju`.`articles` " + "INNER JOIN `project_jeju`.`users` " + "WHERE `users`.`user_index` = `articles`.`user_index` " + "AND `article_index`=?"; try (PreparedStatement preparedStatement = connection.prepareStatement(query)) { preparedStatement.setInt(1, index); try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { modifyArticleVo = new ModifyArticleVo( resultSet.getInt("articleIndex"), resultSet.getString("writer"), resultSet.getString("title"), null, resultSet.getString("classification"), resultSet.getString("location"), resultSet.getString("content"), resultSet.getString("hashtags") ); } } } return modifyArticleVo; } }
2ee5ad9d9383c6d22bb636b0a15f5528d910418b
c091b85c24b44b92ce863ad8c94da42ca5b97604
/PayUMoneySDK/src/main/java/com/payUMoney/sdk/fragment/Debit.java
8fc86dc220aec066dadbe41cb6336fd9c7496822
[]
no_license
teamOSC/dhodu-android
9c1b50e04a9266bce76c16c829f1c5271fb6669a
74acea1dd8572058f17d0dfb642554378f8dc21b
refs/heads/master
2021-01-10T02:51:44.311729
2015-11-07T20:37:15
2015-11-07T20:37:15
55,851,613
2
0
null
null
null
null
UTF-8
Java
false
false
17,179
java
package com.payUMoney.sdk.fragment; import android.app.Activity; import android.app.DatePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import com.payUMoney.sdk.Constants; import com.payUMoney.sdk.HomeActivity; import com.payUMoney.sdk.Luhn; import com.payUMoney.sdk.R; import com.payUMoney.sdk.SetupCardDetails; import com.payUMoney.sdk.dialog.CustomDatePicker; import com.payUMoney.sdk.entity.Card; import com.payUMoney.sdk.interfaces.FragmentLifecycle; import org.json.JSONException; import java.util.Calendar; import java.util.HashMap; import java.util.zip.Inflater; /** * Created by sagar on 20/5/15. */ public class Debit extends Fragment implements FragmentLifecycle { MakePaymentListener mCallback; @Override public void onResumeFragment(HomeActivity activity) { EditText expiryDatePickerEditText = (EditText)activity.findViewById(R.id.expiryDatePickerEditText); String expiryDatePickerEditTextString = expiryDatePickerEditText.getText().toString(); String delims = "[/]"; String[] tokens = null; if(expiryDatePickerEditTextString != null) tokens = expiryDatePickerEditTextString.split(delims); if (tokens != null && tokens.length > 0 && isCvvValid && isCardNumberValid && isExpired) { int mnths = Integer.parseInt(tokens[0]); int yrs = Integer.parseInt(tokens[1]); checkExpiry(expiryDatePickerEditText, yrs, mnths, 0); valid(expiryDatePickerEditText, calenderDrawable); } } // Container Activity must implement this interface public interface MakePaymentListener { public void goToPayment(String mode, HashMap<String, Object> data) throws JSONException; } private int expiryMonth = 7; private int expiryYear = 2025; private String cardNumber = ""; private String cvv = ""; DatePickerDialog.OnDateSetListener mDateSetListener; int mYear; int mMonth; int mDay; Boolean isCardNumberValid = false; Boolean isExpired = true; Boolean isCvvValid = false; Boolean card_store_check = true; Drawable cardNumberDrawable; Drawable calenderDrawable; Drawable cvvDrawable; private CheckBox mCardStore; private EditText mCardLabel; View debitCardDetails; CustomDatePicker mDatePicker; public Debit() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d("Sagar", "DebitCardFragment" + "onCreateView"); // Inflate the layout for this fragment debitCardDetails = inflater.inflate(R.layout.fragment_card_details, container, false); mYear = Calendar.getInstance().get(Calendar.YEAR); mMonth = Calendar.getInstance().get(Calendar.MONTH); mDay = Calendar.getInstance().get(Calendar.DATE); mCardLabel = (EditText) debitCardDetails.findViewById(R.id.label); mCardStore = (CheckBox) debitCardDetails.findViewById(R.id.store_card); super.onActivityCreated(savedInstanceState); cardNumberDrawable = getResources().getDrawable(R.drawable.card); calenderDrawable = getResources().getDrawable(R.drawable.calendar); cvvDrawable = getResources().getDrawable(R.drawable.lock); cardNumberDrawable.setAlpha(100); calenderDrawable.setAlpha(100); cvvDrawable.setAlpha(100); ((TextView) debitCardDetails.findViewById(R.id.enterCardDetailsTextView)).setText(getString(R.string.enter_debit_card_details)); ((EditText) debitCardDetails.findViewById(R.id.cardNumberEditText)).setCompoundDrawablesWithIntrinsicBounds(null, null, cardNumberDrawable, null); ((EditText) debitCardDetails.findViewById(R.id.expiryDatePickerEditText)).setCompoundDrawablesWithIntrinsicBounds(null, null, calenderDrawable, null); ((EditText) debitCardDetails.findViewById(R.id.cvvEditText)).setCompoundDrawablesWithIntrinsicBounds(null, null, cvvDrawable, null); ((EditText) debitCardDetails.findViewById(R.id.cardNumberEditText)).addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { cardNumber = ((EditText) debitCardDetails.findViewById(R.id.cardNumberEditText)).getText().toString(); if (cardNumber.startsWith("34") || cardNumber.startsWith("37")) ((EditText) debitCardDetails.findViewById(R.id.cvvEditText)).setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)}); else ((EditText) debitCardDetails.findViewById(R.id.cvvEditText)).setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)}); if (SetupCardDetails.findIssuer(cardNumber, "DC") == "MAES") { // disable cvv and expiry if (cardNumber.length() > 11 && Luhn.validate(cardNumber)) { isCardNumberValid = true; valid(((EditText) debitCardDetails.findViewById(R.id.cardNumberEditText)), SetupCardDetails.getCardDrawable(getResources(), cardNumber)); } else { isCardNumberValid = false; invalid(((EditText) debitCardDetails.findViewById(R.id.cardNumberEditText)), cardNumberDrawable); cardNumberDrawable.setAlpha(100); resetHeader(); } } else { // enable cvv and expiry debitCardDetails.findViewById(R.id.expiryCvvLinearLayout).setVisibility(View.VISIBLE); if (cardNumber.length() > 11 && Luhn.validate(cardNumber)) { isCardNumberValid = true; valid(((EditText) debitCardDetails.findViewById(R.id.cardNumberEditText)), SetupCardDetails.getCardDrawable(getResources(), cardNumber)); } else { isCardNumberValid = false; invalid(((EditText) debitCardDetails.findViewById(R.id.cardNumberEditText)), cardNumberDrawable); cardNumberDrawable.setAlpha(100); resetHeader(); } } } @Override public void afterTextChanged(Editable editable) { } }); ((EditText) debitCardDetails.findViewById(R.id.cvvEditText)).addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { cvv = ((EditText) debitCardDetails.findViewById(R.id.cvvEditText)).getText().toString(); if (cardNumber.startsWith("34") || cardNumber.startsWith("37")) { if (cvv.length() == 4) { //valid isCvvValid = true; valid(((EditText) debitCardDetails.findViewById(R.id.cvvEditText)), cvvDrawable); } else { //invalid isCvvValid = false; invalid(((EditText) debitCardDetails.findViewById(R.id.cvvEditText)), cvvDrawable); } } else { if (cvv.length() == 3) { //valid isCvvValid = true; valid(((EditText) debitCardDetails.findViewById(R.id.cvvEditText)), cvvDrawable); } else { //invalid isCvvValid = false; invalid(((EditText) debitCardDetails.findViewById(R.id.cvvEditText)), cvvDrawable); } } } @Override public void afterTextChanged(Editable editable) { } }); debitCardDetails.findViewById(R.id.cardNumberEditText).setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (b) { makeInvalid(); } } }); debitCardDetails.findViewById(R.id.cvvEditText).setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (b) { makeInvalid(); } } }); debitCardDetails.findViewById(R.id.expiryDatePickerEditText).setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (b) { makeInvalid(); } } }); mCardStore.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (mCardStore.isChecked()) { card_store_check = true; mCardLabel.setVisibility(View.VISIBLE); } else { card_store_check = false; mCardLabel.setVisibility(View.GONE); } } }); mDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int i, int i2, int i3) { checkExpiry((EditText)debitCardDetails.findViewById(R.id.expiryDatePickerEditText),i,i2,i3); } }; debitCardDetails.findViewById(R.id.expiryDatePickerEditText).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_UP) { mDatePicker = new CustomDatePicker(getActivity()); mDatePicker.build(mMonth, mYear, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //positive button checkExpiry((EditText)debitCardDetails.findViewById(R.id.expiryDatePickerEditText),mDatePicker.getSelectedYear(),mDatePicker.getSelectedMonth(),0); } }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //negative button mDatePicker.dismissDialog(); } }); mDatePicker.show(); } return false; } }); debitCardDetails.findViewById(R.id.makePayment).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String cardNumber = ((TextView) debitCardDetails.findViewById(R.id.cardNumberEditText)).getText().toString(); final HashMap<String, Object> data = new HashMap<String, Object>(); try { if (cvv.equals("") || cvv == null) data.put(Constants.CVV, "123"); else data.put(Constants.CVV, cvv); data.put(Constants.EXPIRY_MONTH, expiryMonth); data.put(Constants.EXPIRY_YEAR, expiryYear); data.put(Constants.NUMBER, cardNumber); data.put("key", ((HomeActivity) getActivity()).getBankObject().getJSONObject("paymentOption").getString("publicKey").replaceAll("\\r", "")); if (Card.isAmex(cardNumber)) { data.put("bankcode", Constants.AMEX); } else { data.put("bankcode", SetupCardDetails.findIssuer(cardNumber, "DC")); // data.put("bankcode", Card.getType(cardNumber)); } if (card_store_check == true) { if (mCardLabel.getText().toString().trim().length() == 0) { data.put(Constants.LABEL, "PayUmoney Debit Card"); data.put(Constants.STORE, "1"); } else { data.put(Constants.LABEL, "DC - "+ mCardLabel.getText().toString().toUpperCase()); data.put(Constants.STORE, "1"); } } mCallback.goToPayment("DC", data); } catch (Exception e) { e.printStackTrace(); } } }); return debitCardDetails; } private void checkExpiry(EditText expiryDatePickerEditText, int i, int i2, int i3){ expiryDatePickerEditText.setText("" + (i2 + 1) + " / " + i); expiryMonth = i2 + 1; expiryYear = i; if (expiryYear > Calendar.getInstance().get(Calendar.YEAR)) { isExpired = false; valid(expiryDatePickerEditText, calenderDrawable); } else if (expiryYear == Calendar.getInstance().get(Calendar.YEAR) && expiryMonth - 1 >= Calendar.getInstance().get(Calendar.MONTH)) { isExpired = false; valid(expiryDatePickerEditText, calenderDrawable); } else { isExpired = true; invalid(expiryDatePickerEditText, calenderDrawable); } } private void valid(EditText editText, Drawable drawable) { drawable.setAlpha(255); editText.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null); if (debitCardDetails.findViewById(R.id.expiryCvvLinearLayout).getVisibility() == View.GONE) { isExpired = false; isCvvValid = true; } if (isCardNumberValid && !isExpired && isCvvValid) { debitCardDetails.findViewById(R.id.makePayment).setEnabled(true); // debitCardDetails.findViewById(R.id.makePayment).setBackgroundResource(R.drawable.button_enabled); } else { debitCardDetails.findViewById(R.id.makePayment).setEnabled(false); // debitCardDetails.findViewById(R.id.makePayment).setBackgroundResource(R.drawable.button); } } private void invalid(EditText editText, Drawable drawable) { drawable.setAlpha(100); editText.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null); debitCardDetails.findViewById(R.id.makePayment).setEnabled(false); debitCardDetails.findViewById(R.id.makePayment).setBackgroundResource(R.drawable.button); } private void makeInvalid() { if (!isCardNumberValid && cardNumber.length() > 0 && !debitCardDetails.findViewById(R.id.cardNumberEditText).isFocused()) ((EditText) debitCardDetails.findViewById(R.id.cardNumberEditText)).setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.error_icon), null); if (!isCvvValid && cvv.length() > 0 && !debitCardDetails.findViewById(R.id.cvvEditText).isFocused()) ((EditText) debitCardDetails.findViewById(R.id.cvvEditText)).setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.error_icon), null); } private void resetHeader() { } @Override public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (MakePaymentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } @Override public void onDestroy() { Log.e("ACT", "onDestroy called"); debitCardDetails = null; super.onDestroy(); } }
50191edab5e11884324e834bd851425ff714eab8
ae0ea6891f5df83ed5f2980083d84d64d0433093
/XMSSSignerTest.java
daf9204d5a153e926b3534857e52637437ea0c2e
[]
no_license
disparate1/post-quantum
f0dcf80180b23f789f8871d3ca4d28507dc14df9
2980e7768492e1c7c215a491f70f69c70ec5dd42
refs/heads/master
2020-03-20T23:04:13.592715
2018-06-19T02:07:04
2018-06-19T02:07:04
137,827,671
4
0
null
null
null
null
UTF-8
Java
false
false
15,510
java
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.PrintWriter; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.Security; import java.text.ParseException; import java.util.Arrays; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.digests.SHAKEDigest; //import org.bouncycastle.pqc.crypto.xmss.NullPRNG; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.prng.FixedSecureRandom; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.pqc.crypto.xmss.XMSS; import org.bouncycastle.pqc.crypto.xmss.XMSSKeyGenerationParameters; import org.bouncycastle.pqc.crypto.xmss.XMSSKeyPairGenerator; import org.bouncycastle.pqc.crypto.xmss.XMSSParameters; import org.bouncycastle.pqc.crypto.xmss.XMSSSigner; import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; public class XMSSSignerTest { public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException { Security.addProvider(new BouncyCastleProvider()); xmssTest(); } public static void xmssTest() throws NoSuchAlgorithmException, NoSuchProviderException{ try { /* //XMSSParameters xmssParams = new XMSSParameters(10, new SHAKEDigest(128)); //XMSSKeyPairGenerator xmss = new XMSSKeyPairGenerator(); // FixedSecureRandom fs = new FixedSecureRandom(new byte[99]); // xmss.init(new XMSSKeyGenerationParameters(xmssParams, new SecureRandom())); // AsymmetricCipherKeyPair kp = xmss.generateKeyPair(); XMSSSigner signer = new XMSSSigner(); // AsymmetricKeyParameter privateKey = kp.getPrivate(); byte[] message = "hi".getBytes(); signer.init(true, privateKey); byte[] signature = signer.generateSignature(message); privateKey = signer.getUpdatedPrivateKey(); signer.init(false, kp.getPublic()); boolean valid=false; valid= signer.verifySignature(message, signature); System.out.println("message: "+new String(message)); System.out.println("signature: "+new String(signature)); System.out.println("signature size: "+signature.length); System.out.println("valid: "+valid); // */ //keys for (10, new SHAKEDigest(128)) // byte[] publicKey = new byte[]{-43, -64, -86, 2, 11, 100, 66, -14, 103, -38, 110, -126, -102, 7, 81, 98, 77, -103, -14, -47, -119, 91, 59, -36, 95, 99, -53, 44, 119, -62, 36, -124, 50, -67, -41, -24, -128, -70, 105, 44, -80, 16, 123, 69, -121, 72, -33, 33, 111, -59, 57, 101, 44, -78, 1, 60, -41, -15, 78, -112, -110, -19, -61, 13}; //byte[] privateKey = new byte[]{0, 0, 0, 0, -118, 88, 26, 9, 82, -85, -111, 36, 71, 38, -122, -40, -93, 6, -15, 127, 35, -51, -42, 69, 103, 85, 89, 50, 123, 109, 58, 49, 18, -104, 48, 64, -121, 90, 37, -19, -25, -34, 12, -75, 86, 51, -14, 27, 94, 122, 109, 58, 64, -128, 6, 24, -107, 16, -108, -33, 74, 93, -8, -89, -4, -34, -49, -51, 50, -67, -41, -24, -128, -70, 105, 44, -80, 16, 123, 69, -121, 72, -33, 33, 111, -59, 57, 101, 44, -78, 1, 60, -41, -15, 78, -112, -110, -19, -61, 13, -43, -64, -86, 2, 11, 100, 66, -14, 103, -38, 110, -126, -102, 7, 81, 98, 77, -103, -14, -47, -119, 91, 59, -36, 95, 99, -53, 44, 119, -62, 36, -124, -84, -19, 0, 5, 115, 114, 0, 36, 111, 114, 103, 46, 98, 111, 117, 110, 99, 121, 99, 97, 115, 116, 108, 101, 46, 112, 113, 99, 46, 99, 114, 121, 112, 116, 111, 46, 120, 109, 115, 115, 46, 66, 68, 83, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 10, 73, 0, 5, 105, 110, 100, 101, 120, 73, 0, 1, 107, 73, 0, 10, 116, 114, 101, 101, 72, 101, 105, 103, 104, 116, 90, 0, 4, 117, 115, 101, 100, 76, 0, 18, 97, 117, 116, 104, 101, 110, 116, 105, 99, 97, 116, 105, 111, 110, 80, 97, 116, 104, 116, 0, 16, 76, 106, 97, 118, 97, 47, 117, 116, 105, 108, 47, 76, 105, 115, 116, 59, 76, 0, 4, 107, 101, 101, 112, 116, 0, 15, 76, 106, 97, 118, 97, 47, 117, 116, 105, 108, 47, 77, 97, 112, 59, 76, 0, 6, 114, 101, 116, 97, 105, 110, 113, 0, 126, 0, 2, 76, 0, 4, 114, 111, 111, 116, 116, 0, 43, 76, 111, 114, 103, 47, 98, 111, 117, 110, 99, 121, 99, 97, 115, 116, 108, 101, 47, 112, 113, 99, 47, 99, 114, 121, 112, 116, 111, 47, 120, 109, 115, 115, 47, 88, 77, 83, 83, 78, 111, 100, 101, 59, 76, 0, 5, 115, 116, 97, 99, 107, 116, 0, 17, 76, 106, 97, 118, 97, 47, 117, 116, 105, 108, 47, 83, 116, 97, 99, 107, 59, 76, 0, 17, 116, 114, 101, 101, 72, 97, 115, 104, 73, 110, 115, 116, 97, 110, 99, 101, 115, 113, 0, 126, 0, 1, 120, 112, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 10, 0, 115, 114, 0, 19, 106, 97, 118, 97, 46, 117, 116, 105, 108, 46, 65, 114, 114, 97, 121, 76, 105, 115, 116, 120, -127, -46, 29, -103, -57, 97, -99, 3, 0, 1, 73, 0, 4, 115, 105, 122, 101, 120, 112, 0, 0, 0, 10, 119, 4, 0, 0, 0, 10, 115, 114, 0, 41, 111, 114, 103, 46, 98, 111, 117, 110, 99, 121, 99, 97, 115, 116, 108, 101, 46, 112, 113, 99, 46, 99, 114, 121, 112, 116, 111, 46, 120, 109, 115, 115, 46, 88, 77, 83, 83, 78, 111, 100, 101, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 73, 0, 6, 104, 101, 105, 103, 104, 116, 91, 0, 5, 118, 97, 108, 117, 101, 116, 0, 2, 91, 66, 120, 112, 0, 0, 0, 0, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8, 84, -32, 2, 0, 0, 120, 112, 0, 0, 0, 32, 0, -128, -23, -128, -83, -28, -87, -39, -3, -66, 50, 53, -20, -112, -29, -19, -28, -30, -3, -99, -64, 54, -23, 103, -69, 26, 55, -65, 73, -115, -122, -20, 115, 113, 0, 126, 0, 8, 0, 0, 0, 1, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 49, 109, -79, 119, -116, -94, 123, 38, 6, -96, 90, 9, -1, -52, -83, -58, -82, 73, -115, -126, 37, -12, -31, -16, 57, 120, 121, 100, 80, 111, 127, 60, 115, 113, 0, 126, 0, 8, 0, 0, 0, 2, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, -15, -4, -85, 23, -16, 64, 82, 82, -100, 78, -71, 18, 20, -87, 3, -30, 70, -95, 81, -82, 61, -27, -87, 71, 125, 123, -53, 95, -5, -87, 94, 120, 115, 113, 0, 126, 0, 8, 0, 0, 0, 3, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, -59, -29, 94, 96, 62, 21, 14, 31, 5, 40, -14, -12, -63, 126, 22, 33, 20, 43, 91, 86, -37, -87, 122, -95, -83, -81, -73, -25, -1, 74, -81, -63, 115, 113, 0, 126, 0, 8, 0, 0, 0, 4, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 36, 52, -74, -125, 57, 116, -115, -128, 34, 64, -18, -6, -121, -7, -63, 13, 43, 54, 67, -29, 22, -123, 22, 118, -93, 36, -77, -21, 97, 68, -105, -82, 115, 113, 0, 126, 0, 8, 0, 0, 0, 5, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 116, -86, -110, -82, 37, 10, 78, -104, 77, 31, -98, 70, 34, 49, 27, -89, -6, 9, -60, -48, 41, 40, 119, -111, 57, -85, -120, 88, 64, 115, 15, 28, 115, 113, 0, 126, 0, 8, 0, 0, 0, 6, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 96, -51, -4, -50, 17, 75, 15, -53, -59, 104, 94, -53, -54, -25, -4, 28, 94, 120, -82, -72, 3, 4, -37, -87, 37, 71, -3, -69, -80, 12, 10, -3, 115, 113, 0, 126, 0, 8, 0, 0, 0, 7, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 122, 108, 112, -7, -73, -127, -61, -61, -42, -107, -1, -44, -37, 64, -46, -54, 99, 27, 30, -69, 12, 74, -113, -24, 59, 33, -97, 30, 127, 52, 53, 68, 115, 113, 0, 126, 0, 8, 0, 0, 0, 8, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 9, 80, -112, 29, 74, 46, -52, -87, 102, -49, -68, 103, -115, 18, -39, -24, 119, -97, -94, -67, 79, -2, 85, -16, 36, 51, -92, -40, 110, -52, -99, 92, 115, 113, 0, 126, 0, 8, 0, 0, 0, 9, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 66, 85, -34, -28, 11, -85, 13, -109, 36, 41, 87, 68, -113, -101, 48, -109, 19, 107, 79, 16, -48, 116, 110, -37, 127, 33, -113, 71, 80, 40, 29, 117, 120, 115, 114, 0, 17, 106, 97, 118, 97, 46, 117, 116, 105, 108, 46, 84, 114, 101, 101, 77, 97, 112, 12, -63, -10, 62, 45, 37, 106, -26, 3, 0, 1, 76, 0, 10, 99, 111, 109, 112, 97, 114, 97, 116, 111, 114, 116, 0, 22, 76, 106, 97, 118, 97, 47, 117, 116, 105, 108, 47, 67, 111, 109, 112, 97, 114, 97, 116, 111, 114, 59, 120, 112, 112, 119, 4, 0, 0, 0, 0, 120, 115, 113, 0, 126, 0, 31, 112, 119, 4, 0, 0, 0, 1, 115, 114, 0, 17, 106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 73, 110, 116, 101, 103, 101, 114, 18, -30, -96, -92, -9, -127, -121, 56, 2, 0, 1, 73, 0, 5, 118, 97, 108, 117, 101, 120, 114, 0, 16, 106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 78, 117, 109, 98, 101, 114, -122, -84, -107, 29, 11, -108, -32, -117, 2, 0, 0, 120, 112, 0, 0, 0, 8, 115, 114, 0, 20, 106, 97, 118, 97, 46, 117, 116, 105, 108, 46, 76, 105, 110, 107, 101, 100, 76, 105, 115, 116, 12, 41, 83, 93, 74, 96, -120, 34, 3, 0, 0, 120, 112, 119, 4, 0, 0, 0, 1, 115, 113, 0, 126, 0, 8, 0, 0, 0, 8, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, -91, -54, -22, -91, 73, 76, 14, 9, -76, -128, -14, -112, 78, -122, -65, 16, -13, 83, -7, -74, 34, -111, 66, 92, -66, 63, -37, -43, 20, -36, 124, 20, 120, 120, 115, 113, 0, 126, 0, 8, 0, 0, 0, 10, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, -43, -64, -86, 2, 11, 100, 66, -14, 103, -38, 110, -126, -102, 7, 81, 98, 77, -103, -14, -47, -119, 91, 59, -36, 95, 99, -53, 44, 119, -62, 36, -124, 115, 114, 0, 15, 106, 97, 118, 97, 46, 117, 116, 105, 108, 46, 83, 116, 97, 99, 107, 16, -2, 42, -62, -69, 9, -122, 29, 2, 0, 0, 120, 114, 0, 16, 106, 97, 118, 97, 46, 117, 116, 105, 108, 46, 86, 101, 99, 116, 111, 114, -39, -105, 125, 91, -128, 59, -81, 1, 3, 0, 3, 73, 0, 17, 99, 97, 112, 97, 99, 105, 116, 121, 73, 110, 99, 114, 101, 109, 101, 110, 116, 73, 0, 12, 101, 108, 101, 109, 101, 110, 116, 67, 111, 117, 110, 116, 91, 0, 11, 101, 108, 101, 109, 101, 110, 116, 68, 97, 116, 97, 116, 0, 19, 91, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 59, 120, 112, 0, 0, 0, 0, 0, 0, 0, 0, 117, 114, 0, 19, 91, 76, 106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 79, 98, 106, 101, 99, 116, 59, -112, -50, 88, -97, 16, 115, 41, 108, 2, 0, 0, 120, 112, 0, 0, 0, 10, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 120, 115, 113, 0, 126, 0, 6, 0, 0, 0, 8, 119, 4, 0, 0, 0, 8, 115, 114, 0, 44, 111, 114, 103, 46, 98, 111, 117, 110, 99, 121, 99, 97, 115, 116, 108, 101, 46, 112, 113, 99, 46, 99, 114, 121, 112, 116, 111, 46, 120, 109, 115, 115, 46, 66, 68, 83, 84, 114, 101, 101, 72, 97, 115, 104, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 6, 90, 0, 8, 102, 105, 110, 105, 115, 104, 101, 100, 73, 0, 6, 104, 101, 105, 103, 104, 116, 73, 0, 13, 105, 110, 105, 116, 105, 97, 108, 72, 101, 105, 103, 104, 116, 90, 0, 11, 105, 110, 105, 116, 105, 97, 108, 105, 122, 101, 100, 73, 0, 9, 110, 101, 120, 116, 73, 110, 100, 101, 120, 76, 0, 8, 116, 97, 105, 108, 78, 111, 100, 101, 113, 0, 126, 0, 3, 120, 112, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 115, 113, 0, 126, 0, 8, 0, 0, 0, 0, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 35, -77, -94, 96, 83, 93, 92, -2, 116, -40, -86, 85, 125, 78, 26, -48, 46, -121, 76, 40, -98, -78, 52, -5, -6, -86, 110, 59, 115, -11, -115, -120, 115, 113, 0, 126, 0, 51, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 115, 113, 0, 126, 0, 8, 0, 0, 0, 1, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 64, 116, -13, 120, -20, 46, -112, -78, -80, -12, -60, 48, -6, 11, -103, -73, 85, 101, -107, 31, -116, -104, 81, 41, 89, -28, 45, -56, 68, 34, 17, -94, 115, 113, 0, 126, 0, 51, 1, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 115, 113, 0, 126, 0, 8, 0, 0, 0, 2, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 68, 71, -79, -4, -3, 24, -69, 36, 73, -15, 3, 102, 17, -124, -68, 63, 60, -28, 9, -114, -104, 96, 34, -61, 66, 107, -117, -65, -22, 95, 96, 24, 115, 113, 0, 126, 0, 51, 1, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 0, 0, 115, 113, 0, 126, 0, 8, 0, 0, 0, 3, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, -103, -17, -31, -111, 12, 37, 7, 33, 67, 74, -125, 15, -53, 97, 14, 89, 61, -16, -75, 21, -34, -71, 121, 60, -81, 70, 9, -30, 99, -100, 47, 36, 115, 113, 0, 126, 0, 51, 1, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 115, 113, 0, 126, 0, 8, 0, 0, 0, 4, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 54, -65, -81, -122, 30, 115, -37, 46, 13, -69, -30, 27, 45, 62, -34, 119, 36, 64, -35, 89, -119, -85, -15, -6, -121, 46, -10, 3, -66, -26, 63, -90, 115, 113, 0, 126, 0, 51, 1, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 0, 0, 0, 115, 113, 0, 126, 0, 8, 0, 0, 0, 5, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, 9, 56, 113, 7, 24, -37, 75, -70, 53, -39, -95, 54, 14, 97, -55, 83, -17, -35, -98, -53, -23, -107, -38, -17, -40, -124, 41, 80, -47, -73, 82, 53, 115, 113, 0, 126, 0, 51, 1, 0, 0, 0, 6, 0, 0, 0, 6, 0, 0, 0, 0, 0, 115, 113, 0, 126, 0, 8, 0, 0, 0, 6, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, -91, -122, -108, 33, -89, -18, -86, -116, -18, 89, -61, -93, -96, -74, -50, 105, -54, -92, 23, -35, 4, 74, -120, -59, -87, -102, -42, -111, -42, 64, -111, -54, 115, 113, 0, 126, 0, 51, 1, 0, 0, 0, 7, 0, 0, 0, 7, 0, 0, 0, 0, 0, 115, 113, 0, 126, 0, 8, 0, 0, 0, 7, 117, 113, 0, 126, 0, 11, 0, 0, 0, 32, -82, -122, -44, -93, 96, 10, 104, 78, -50, 126, -59, 14, -9, 24, 35, 76, 31, 126, -41, -117, -77, 119, 82, -126, 117, -15, 23, 26, 69, 58, 85, 104, 120}; // byte[] publicKey = getByte("E:\\public.txt"); // byte[] privateKey = getByte("E:\\private.txt"); // XMSSParameters xmssParams = new XMSSParameters(10, new SHA256Digest()); XMSSParameters xmssParams = new XMSSParameters(10, new SHA512Digest()); // XMSSParameters xmssParams = new XMSSParameters(10, new SHAKEDigest(128)); XMSS xmss = new XMSS(xmssParams, new SecureRandom()); long start3 = System.currentTimeMillis(); //xmss.importState(privateKey, publicKey); xmss.generateKeys(); //get elapsed time for keygen long elapsed3 = System.currentTimeMillis() - start3; System.out.println("elapsed key gen: "+elapsed3); byte[] privateKey = xmss.exportPrivateKey(); byte[] publicKey = xmss.exportPublicKey(); /* FileOutputStream fos1 = new FileOutputStream("E:\\public.txt"); fos1.write(publicKey); fos1.close(); FileOutputStream fos2 = new FileOutputStream("E:\\private.txt"); fos2.write(privateKey); fos2.close();*/ /* PrintWriter out = new PrintWriter("publicKeyx.txt"); out.println(Arrays.toString(publicKey)); out.close(); PrintWriter out2 = new PrintWriter("privateKeyx.txt"); out2.println(Arrays.toString(privateKey)); out2.close();*/ System.out.println("pub key size: "+publicKey.length); System.out.println("pub key : "+Arrays.toString(publicKey)); System.out.println("priv key size: "+privateKey.length); System.out.println("riv key : "+Arrays.toString(privateKey)); byte[] message = "hi".getBytes(); byte[] signature = xmss.sign(message); boolean valid=false; valid= xmss.verifySignature(message, signature, publicKey); System.out.println("message: "+new String(message)); System.out.println("signature: "+new String(signature)); System.out.println("signature size: "+signature.length); System.out.println("valid: "+valid); } catch (Exception e) { e.printStackTrace(); } } public static byte[] getByte(String path) { byte[] getBytes = {}; try { File file = new File(path); getBytes = new byte[(int) file.length()]; InputStream is = new FileInputStream(file); is.read(getBytes); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return getBytes; } }
9a73177d34c67ae29b19c2c1907da7a926a618ff
21e16c35caac040b51d77c22823f51616da5fcc4
/app/src/androidTest/java/com/example/brainbeats/basicbb/MusicServiceTest.java
13cdebcf7eb3bcc11a159e39f94a61eed5b626da
[]
no_license
BrainBeats/BasicBB
16c45846a3cc2d9a4e46d88e3e7a67165186c817
13130db944adbf0b402b56a40f4ae8c1ed420a9c
refs/heads/master
2021-01-09T20:26:43.239906
2016-06-16T07:57:37
2016-06-16T07:57:37
60,679,491
0
0
null
2016-06-09T08:12:05
2016-06-08T07:55:01
Java
UTF-8
Java
false
false
1,437
java
package com.example.brainbeats.basicbb; import android.test.AndroidTestCase; import java.util.ArrayList; import java.util.List; public class MusicServiceTest extends AndroidTestCase{ public void testFilter() { MusicService musicService = new MusicService(); List<Song> songList = new ArrayList<>(); songList.add(new Song(1, "1",null,null)); songList.add(new Song(2, "2",null,null)); songList.add(new Song(3, "3",null,null)); songList.add(new Song(4, "4",null,null)); songList.add(new Song(5, "5",null,null)); final int wantedA = 3; final int wantedB = 1; final Integer integer = musicService.filterPositionsByIds( new long[]{wantedA,wantedB}, songList ); assertTrue(songList.get(integer).getID() == wantedA || songList.get(integer).getID() == wantedB ); } public void testFilterWithNoIDs() { MusicService musicService = new MusicService(); List<Song> songList = new ArrayList<>(); songList.add(new Song(1, "1",null,null)); songList.add(new Song(2, "2",null,null)); songList.add(new Song(3, "3",null,null)); songList.add(new Song(4, "4",null,null)); songList.add(new Song(5, "5",null,null)); final Integer integer = musicService.filterPositionsByIds( new long[]{}, songList ); assertTrue(integer == -1); } }
be7110f79092d8586066c4328bc4a6eec18ae624
b6a49c1c8eaf6a8ff7808381505e94ce70a9ab3a
/src/main/java/services/CustomerService.java
bbe28c94c82ec491c771f5cac2cc211891f9100f
[]
no_license
thaophamhetxat/CRUD-JBDC
0a63e54068f7b7c37a60bd42d6d34d809f2248f1
a1bf4e11fea2ad651e5a0e98c5024b220fc8f649
refs/heads/master
2023-07-03T18:56:34.211283
2021-08-01T03:54:31
2021-08-01T03:54:31
391,518,831
0
0
null
null
null
null
UTF-8
Java
false
false
1,231
java
package services; import dao.ManagerCustomer; import models.Customer; import java.sql.SQLException; import java.util.ArrayList; public class CustomerService { public ArrayList<Customer> list = new ArrayList<>(); public CustomerService() { try { list = (ArrayList<Customer>) ManagerCustomer.select(); } catch (SQLException | ClassNotFoundException throwables) { throwables.printStackTrace(); } } public void save(Customer customer) throws SQLException { ManagerCustomer.create(customer); list.add(customer); } public void edit(Customer customer,int index) throws SQLException { ManagerCustomer.edit(customer); list.set(index,customer); } public void delete(int index) throws SQLException { ManagerCustomer.delete(list.get(index).getId()); list.remove(index); } // public Customer findById(int id){ // for (Customer c:list) { // if (c.getId() == id){ // return c; // } // } // return null; // } public ArrayList<Customer>findByName(String name) throws SQLException { return ManagerCustomer.findByName(name); } }
a2ef6f91b536d481fbff898a4491a2d5919fe1c8
63d319fbd88e49701d8dcc2919c8f3a6013e90d0
/CoCoNut/org.reuseware.coconut.compositionprogram.diagram/src-gen/org/reuseware/coconut/compositionprogram/diagram/navigator/CompositionprogramDomainNavigatorContentProvider.java
a4a3b960bb9bce07bcc38565d291cd764b046bc3
[]
no_license
DevBoost/Reuseware
2e6b3626c0d434bb435fcf688e3a3c570714d980
4c2f0170df52f110c77ee8cffd2705af69b66506
refs/heads/master
2021-01-19T21:28:13.184309
2019-06-09T20:39:41
2019-06-09T20:48:34
5,324,741
1
1
null
null
null
null
UTF-8
Java
false
false
6,586
java
/******************************************************************************* * Copyright (c) 2006-2012 * Software Technology Group, Dresden University of Technology * DevBoost GmbH, Berlin, Amtsgericht Charlottenburg, HRB 140026 * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany; * DevBoost GmbH - Berlin, Germany * - initial API and implementation ******************************************************************************/ package org.reuseware.coconut.compositionprogram.diagram.navigator; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import org.eclipse.core.resources.IFile; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain; import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider; import org.eclipse.emf.transaction.TransactionalEditingDomain; import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; import org.eclipse.gmf.runtime.emf.core.GMFEditingDomainFactory; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IMemento; import org.eclipse.ui.navigator.ICommonContentExtensionSite; import org.eclipse.ui.navigator.ICommonContentProvider; import org.reuseware.coconut.compositionprogram.diagram.part.CompositionprogramDiagramEditorPlugin; /** * @generated */ public class CompositionprogramDomainNavigatorContentProvider implements ICommonContentProvider { /** * @generated */ private AdapterFactoryContentProvider myAdapterFactoryContentProvier; /** * @generated */ private static final Object[] EMPTY_ARRAY = new Object[0]; /** * @generated */ private Viewer myViewer; /** * @generated */ private AdapterFactoryEditingDomain myEditingDomain; /** * @generated */ private WorkspaceSynchronizer myWorkspaceSynchronizer; /** * @generated */ private Runnable myViewerRefreshRunnable; /** * @generated */ public CompositionprogramDomainNavigatorContentProvider() { myAdapterFactoryContentProvier = new AdapterFactoryContentProvider( CompositionprogramDiagramEditorPlugin.getInstance() .getItemProvidersAdapterFactory()); TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE .createEditingDomain(); myEditingDomain = (AdapterFactoryEditingDomain) editingDomain; myEditingDomain.setResourceToReadOnlyMap(new HashMap() { public Object get(Object key) { if (!containsKey(key)) { put(key, Boolean.TRUE); } return super.get(key); } }); myViewerRefreshRunnable = new Runnable() { public void run() { if (myViewer != null) { myViewer.refresh(); } } }; myWorkspaceSynchronizer = new WorkspaceSynchronizer(editingDomain, new WorkspaceSynchronizer.Delegate() { public void dispose() { } public boolean handleResourceChanged(final Resource resource) { unloadAllResources(); asyncRefresh(); return true; } public boolean handleResourceDeleted(Resource resource) { unloadAllResources(); asyncRefresh(); return true; } public boolean handleResourceMoved(Resource resource, final URI newURI) { unloadAllResources(); asyncRefresh(); return true; } }); } /** * @generated */ public void dispose() { myWorkspaceSynchronizer.dispose(); myWorkspaceSynchronizer = null; myViewerRefreshRunnable = null; myViewer = null; unloadAllResources(); ((TransactionalEditingDomain) myEditingDomain).dispose(); myEditingDomain = null; } /** * @generated */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { myViewer = viewer; } /** * @generated */ void unloadAllResources() { for (Resource nextResource : myEditingDomain.getResourceSet() .getResources()) { nextResource.unload(); } } /** * @generated */ void asyncRefresh() { if (myViewer != null && !myViewer.getControl().isDisposed()) { myViewer.getControl().getDisplay() .asyncExec(myViewerRefreshRunnable); } } /** * @generated */ public Object[] getElements(Object inputElement) { return getChildren(inputElement); } /** * @generated */ public void restoreState(IMemento aMemento) { } /** * @generated */ public void saveState(IMemento aMemento) { } /** * @generated */ public void init(ICommonContentExtensionSite aConfig) { } /** * @generated */ public Object[] getChildren(Object parentElement) { if (parentElement instanceof IFile) { IFile file = (IFile) parentElement; URI fileURI = URI.createPlatformResourceURI(file.getFullPath() .toString(), true); Resource resource = myEditingDomain.getResourceSet().getResource( fileURI, true); return wrapEObjects( myAdapterFactoryContentProvier.getChildren(resource), parentElement); } if (parentElement instanceof CompositionprogramDomainNavigatorItem) { return wrapEObjects( myAdapterFactoryContentProvier.getChildren(((CompositionprogramDomainNavigatorItem) parentElement) .getEObject()), parentElement); } return EMPTY_ARRAY; } /** * @generated */ public Object[] wrapEObjects(Object[] objects, Object parentElement) { Collection result = new ArrayList(); for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof EObject) { result.add(new CompositionprogramDomainNavigatorItem( (EObject) objects[i], parentElement, myAdapterFactoryContentProvier)); } } return result.toArray(); } /** * @generated */ public Object getParent(Object element) { if (element instanceof CompositionprogramAbstractNavigatorItem) { CompositionprogramAbstractNavigatorItem abstractNavigatorItem = (CompositionprogramAbstractNavigatorItem) element; return abstractNavigatorItem.getParent(); } return null; } /** * @generated */ public boolean hasChildren(Object element) { return element instanceof IFile || getChildren(element).length > 0; } }
189e32ec805d62855f90ef011c9115acf04c28c5
f4941098a46fdb60f2bc8f98b257e475806308a8
/src/main/java/be/realshoping/shop/repositories/ProductImageRepository.java
71b190e327d8188d824336d0f25baa33cc8f3f2b
[]
no_license
tjulhakyan/shop
0e0478fc19ae47bab96e7bd3b0f2346a10836259
e0052c3d170de71448fa1054081783e0a0aaafa8
refs/heads/master
2023-02-21T01:31:20.181042
2021-01-21T22:09:01
2021-01-21T22:09:01
326,491,031
0
0
null
null
null
null
UTF-8
Java
false
false
240
java
package be.realshoping.shop.repositories; import be.realshoping.shop.data.ProductImage; import org.springframework.data.jpa.repository.JpaRepository; public interface ProductImageRepository extends JpaRepository<ProductImage,Integer> { }
393359c0479df35776c5bb4b9c3fec7026c9cf61
a63134ab87564c2b203356468fe0b1260d5d44d6
/src/com/itvdn/homework/javastart/lesson9/ReversedArray.java
75884dc824e509b5a72c3f72eab17808e4ab794c
[]
no_license
apshow/ITVDNHomeWork
87dbe7d5d8745bc9972abeb3849a432beea21e10
12fbf2ad7327bac0354daa5dbb32a5598703c9d6
refs/heads/master
2023-06-10T19:10:48.145093
2021-06-23T16:12:22
2021-06-23T16:12:22
368,498,099
0
0
null
null
null
null
UTF-8
Java
false
false
2,042
java
package com.itvdn.homework.javastart.lesson9; import java.util.Arrays; public class ReversedArray { static int[] myReverse(int[] array) { int[] newArray = new int[array.length]; for (int i = 0; i < array.length; i++) { newArray[i] = array[array.length - 1 - i]; } return newArray; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; System.out.println(Arrays.toString(myReverse(arr))); } } // Задание 3 // Используя IntelliJ IDEA, создайте класс ReversedArray. // Требуется: // 1) Создать метод myReverse(int [] array), который принимает в качестве аргумента массив // целочисленных элементов и возвращает инвертированный массив (элементы массива в обратном порядке). // // 2) Создайте метод int [] subArray(int [] array, int index, int count). Метод возвращает часть // полученного в качестве аргумента массива, начиная с позиции указанной в аргументе index, размерностью, которая соответствует значению аргумента count. // Если аргумент count содержит значение больше чем количество элементов, которые входят в // выбираемую часть исходного массива (от указанного индекса index, до индекса последнего элемента), // то при формировании нового массива размерностью в count, заполните единицами те элементы, // которые не были скопированы из исходного массива.
faac550160216d97c0a57b3fb758b40169ab2914
6e84a473499304f59f38936ef48dcf3352dfbb18
/app/src/main/java/com/vxiaoxue/weiketang/domain/RecordInfo.java
3fc14efdf652552477a99912d2dcecfca9d92809
[]
no_license
HeChengR/MyApplication
6b12977427cdca6a9674a4fb0cacf68fbd828607
efe5d1180ce61b8b2ba14aa7c0d9bdfe83a86ae4
refs/heads/master
2021-01-10T17:47:58.874603
2015-11-30T10:07:48
2015-11-30T10:07:48
47,105,430
0
0
null
null
null
null
UTF-8
Java
false
false
456
java
package com.vxiaoxue.weiketang.domain; /** * Created by Administrator on 2015/8/21. */ public class RecordInfo { private String reward;//奖励微币 private String date; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getReward() { return reward; } public void setReward(String reward) { this.reward = reward; } }
bf0c838a6749a69cc71ccbd9a5f403d5e54a67b8
42fb13627b25b97b075ac436301ec0bf3cd96aed
/ProximitySenseSDK/lib/src/main/java/com/bluesensenetworks/proximitysense/le/BleNotAvailableException.java
ca3c48ca190c6dd43da5aa1de4beebfa13f9ed21
[ "Apache-2.0" ]
permissive
blueSense/Android
2c7dd492ff60aaa3d640786bb6f31ee7a32cf2b3
955dbab7b16b8b6c384d0a85c60f02cf3c9900d9
refs/heads/master
2020-12-28T00:03:29.014047
2015-06-29T22:56:44
2015-06-29T22:56:44
16,595,956
1
0
null
null
null
null
UTF-8
Java
false
false
272
java
package com.bluesensenetworks.proximitysense.le; public class BleNotAvailableException extends RuntimeException { private static final long serialVersionUID = -8532603161001803466L; public BleNotAvailableException(String message) { super(message); } }
4686e14c2fd583233fd9fa7591ae0eadfaca37dc
8619e30b017c84cc2de142251ab541d23e440c09
/app/src/androidTest/java/ie/careersportal/alan/pointscalculator2017plus/ApplicationTest.java
80286424f930dd2948e54d24faae743c4f277c5d
[]
no_license
vuxtaposition/pointscalculatorPlus
e899ae39d3501b1a4abc4ff256410e7c397398a7
f1097bbd8ff7ac3c0d4c801ce193c51f9e145700
refs/heads/master
2021-01-22T11:37:30.139523
2015-09-17T09:43:14
2015-09-17T09:43:14
42,647,175
0
0
null
null
null
null
UTF-8
Java
false
false
389
java
package ie.careersportal.alan.pointscalculator2017plus; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
a2aa8c83d5c91cd786bf62bb3701f633e9a39371
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/13/13_2273ff0f2e471ad75bf3929946a3ecf50bdc0fef/DateTypeConverterTest/13_2273ff0f2e471ad75bf3929946a3ecf50bdc0fef_DateTypeConverterTest_t.java
d3344af261b0e86cf3c6ae34f63371815ca8c0c3
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
7,745
java
package net.sourceforge.stripes.validation; import org.testng.annotations.Test; import org.testng.Assert; import java.util.Locale; import java.util.Collection; import java.util.ArrayList; import java.util.Date; import java.util.Calendar; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * Tests that ensure that the DateTypeConverter does the right thing given * an appropriate input locale. * * @author Tim Fennell */ public class DateTypeConverterTest { // Used to format back to dates for equality checking :) private DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.US); private DateTypeConverter getConverter(Locale locale) { DateTypeConverter converter = new DateTypeConverter(); converter.setLocale(locale); return converter; } @Test(groups="fast") public void testBasicUsLocaleDates() { Collection<ValidationError> errors = new ArrayList<ValidationError>(); DateTypeConverter converter = getConverter(Locale.US); Date date = converter.convert("1/31/07", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "01/31/2007"); date = converter.convert("Feb 28, 2006", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "02/28/2006"); date = converter.convert("March 1, 2007", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "03/01/2007"); } @Test(groups="fast") public void testVariantUsLocaleDates() { Collection<ValidationError> errors = new ArrayList<ValidationError>(); DateTypeConverter converter = getConverter(Locale.US); Date date = converter.convert("01/31/2007", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "01/31/2007"); date = converter.convert("28 Feb 06", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "02/28/2006"); date = converter.convert("1 March 07", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "03/01/2007"); } @Test(groups="fast") public void testAlternateSeparatorsDates() { Collection<ValidationError> errors = new ArrayList<ValidationError>(); DateTypeConverter converter = getConverter(Locale.US); Date date = converter.convert("01 31 2007", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "01/31/2007"); date = converter.convert("28-Feb-06", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "02/28/2006"); date = converter.convert("01-March-07", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "03/01/2007"); } @Test(groups="fast") public void testUkLocaleDates() { Collection<ValidationError> errors = new ArrayList<ValidationError>(); DateTypeConverter converter = getConverter(Locale.UK); Date date = converter.convert("31 01 2007", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "01/31/2007"); date = converter.convert("28/02/2006", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "02/28/2006"); date = converter.convert("01 March 2007", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "03/01/2007"); } @Test(groups="fast") public void testWhackySeparators() { Collection<ValidationError> errors = new ArrayList<ValidationError>(); DateTypeConverter converter = getConverter(Locale.US); Date date = converter.convert("01, 31, 2007", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "01/31/2007"); date = converter.convert("02--28.2006", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "02/28/2006"); date = converter.convert("01//March,./ 2007", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "03/01/2007"); } @Test(groups="fast") public void testNonStandardFormats() { Collection<ValidationError> errors = new ArrayList<ValidationError>(); DateTypeConverter converter = getConverter(Locale.US); Date date = converter.convert("Jan 31 2007", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "01/31/2007"); date = converter.convert("February 28 2006", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "02/28/2006"); date = converter.convert("2007-03-01", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "03/01/2007"); } @Test(groups="fast") public void testPartialInputFormats() { Collection<ValidationError> errors = new ArrayList<ValidationError>(); DateTypeConverter converter = getConverter(Locale.US); Date date = converter.convert("Jan 31", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "01/31/" + Calendar.getInstance().get( Calendar.YEAR )); date = converter.convert("February 28", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "02/28/" + Calendar.getInstance().get( Calendar.YEAR )); date = converter.convert("03/01", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), "03/01/" + Calendar.getInstance().get( Calendar.YEAR )); } @Test(groups="fast") public void testDateToStringFormat() { Collection<ValidationError> errors = new ArrayList<ValidationError>(); DateTypeConverter converter = getConverter(Locale.US); Date now = new Date(); Date date = converter.convert(now.toString(), Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Assert.assertEquals(format.format(date), format.format(now)); } }
81177b6f85399ed0cbcaead13327c09e7094d58b
ac4c00ee6eea58394a3494e295246f2c4589b31e
/swap.java
053a811c169ab88794398d614edf55a77133e0d2
[]
no_license
EShi538/USACO-Silver
679ed9a45caa5b44b2a49b6ee8bedf96f6796211
31684fe2a9a734080acfb14b77f5164f7db4444b
refs/heads/master
2023-07-23T06:30:28.015943
2021-09-04T18:00:51
2021-09-04T18:00:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,645
java
import java.io.*; import java.util.*; public class swap { static int n, m, k; static int[] a; static List<ArrayList<Integer>> adjList = new ArrayList<>(), cycles = new ArrayList<>(); static boolean done = false; static boolean[] visited; static void findCycle(int node, int ind) { cycles.get(ind).add(node); visited[node] = true; List<Integer> adj = adjList.get(node); for(int i: adj){ if(!visited[i]){ findCycle(i, ind); if(done){ return; } } else{ done = true; return; } } } public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new FileReader("swap.in")); PrintWriter out = new PrintWriter(new File("swap.out")); StringTokenizer st = new StringTokenizer(in.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); k = Integer.parseInt(st.nextToken()); a = new int[n]; for(int i = 1; i <= n; i++){ a[i - 1] = i; } for(int i = 0; i < m; i++){ st = new StringTokenizer(in.readLine()); int l = Integer.parseInt(st.nextToken()), r = Integer.parseInt(st.nextToken()); rev(l - 1, r - 1); } in.close(); visited = new boolean[n + 1]; for(int i = 0; i <= n; i++){ adjList.add(new ArrayList<>()); } for(int i = 0; i < n; i++){ adjList.get(a[i]).add(i + 1); } for(int i = 1; i <= n; i++){ if(!visited[i]){ cycles.add(new ArrayList<>()); findCycle(i, cycles.size() - 1); } } int[] cycleInd = new int[n + 1], posInCycle = new int[n + 1]; for(int i = 0; i < cycles.size(); i++){ for(int j = 0; j < cycles.get(i).size(); j++){ cycleInd[cycles.get(i).get(j)] = i; posInCycle[cycles.get(i).get(j)] = j; } } int[] ans = new int[n]; for(int i = 1; i <= n; i++){ int index = (posInCycle[i] + k) % cycles.get(cycleInd[i]).size(); ans[cycles.get(cycleInd[i]).get(index) - 1] = i; } for(int i: ans){ out.println(i); } out.close(); } static void rev(int l, int r){ for(int i = l; i <= (l + r)/2; i++){ int tmp = a[i]; a[i] = a[r - i + l]; a[r - i + l] = tmp; } } }
e320e8ba819c57c440f396932a4aca4a9b8f4669
a3c22b9da96258be2a352b1f51b65a383e872005
/Web/RecognizerLib/src/test/java/pl/sudokusolver/recognizerlib/filters/FixedWidthResizeFilterTest.java
22d7b0f8188edd43bfe2dd31d35013f465b8a121
[ "Apache-2.0" ]
permissive
lukmccall/SudokuSolver
f8ee6b9a9b0f56dda98204459454480f3a4d0713
2d76ea7289e1a59179dde20071dcf63f874b9175
refs/heads/master
2022-12-23T17:26:32.269391
2020-07-03T09:13:06
2020-07-03T09:13:06
173,821,083
1
0
Apache-2.0
2022-12-16T15:23:39
2019-03-04T21:03:58
Java
UTF-8
Java
false
false
1,730
java
package pl.sudokusolver.recognizerlib.filters; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.opencv.core.CvException; import org.opencv.core.Mat; import org.opencv.core.Size; import pl.sudokusolver.recognizerlib._INIT_; import static org.junit.jupiter.api.Assertions.*; import static org.opencv.core.CvType.*; @ExtendWith({_INIT_.class}) class FixedWidthResizeFilterTest { @Test void applyTest() { Mat matrix = Mat.zeros(new Size(600,300), CV_8UC1); new FixedWidthResizeFilter(300).apply(matrix); Assert.assertEquals(new Size(300,150),matrix.size()); matrix = Mat.zeros(new Size(100,300), CV_8UC1); new FixedWidthResizeFilter(500).apply(matrix); Assert.assertEquals(new Size(500,1500),matrix.size()); matrix = Mat.zeros(new Size(100,100), CV_8UC1); new FixedWidthResizeFilter(390).apply(matrix); Assert.assertEquals(new Size(390,390),matrix.size()); matrix = Mat.zeros(new Size(100,500), CV_8UC1); new FixedWidthResizeFilter(200).apply(matrix); Assert.assertEquals(new Size(200,1000),matrix.size()); } @Test void applyCvExceptionTest(){ Mat matrix = Mat.zeros(new Size(600,300), CV_8UC1); assertThrows(CvException.class, () -> { new FixedWidthResizeFilter(-1).apply(matrix); }, "The argument given for the constructor must be greater than 0"); Mat matrix2 = Mat.zeros(new Size(600,300), CV_8UC2); assertThrows(CvException.class, () -> { new FixedWidthResizeFilter(-1).apply(matrix2); }, "Wrong type of matrix - only support mat with on channel"); } }
4d1131cd8616fb43779edc54b43ec534076f1b68
a103c215912b20603d924036668e0029bb58639f
/appbar/src/main/java/com/example/igormoraes/appbar/produto/AdapterProdutoAvaliacao.java
8622c2cae4fa7976a1b303b0585e3f04d8765285
[]
no_license
running-android-dev01/AppTcc
77b19abd81b647a55ea7c1531b7a1244b077425c
3601c518c3c08d4d0631ba550de00b6e1f484476
refs/heads/master
2021-05-23T05:49:58.590598
2018-04-11T20:03:51
2018-04-11T20:03:51
94,934,164
0
0
null
null
null
null
UTF-8
Java
false
false
1,810
java
package com.example.igormoraes.appbar.produto; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.example.igormoraes.appbar.R; import com.example.igormoraes.appbar.model.ProdutoAvaliacao; import com.example.igormoraes.appbar.utils.DateUtils; import java.util.List; /** * Created by igormoraes on 17/03/18. */ class AdapterProdutoAvaliacao extends RecyclerView.Adapter<ViewHolderProdutoAvaliacao> { private List<ProdutoAvaliacao> mProdutoAvaliacao; private final Context context; public AdapterProdutoAvaliacao(Context context){ this.context = context; } public void atualizarLista(List<ProdutoAvaliacao> produtoAvaliacaos){ mProdutoAvaliacao = produtoAvaliacaos; notifyDataSetChanged(); } @Override public ViewHolderProdutoAvaliacao onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolderProdutoAvaliacao(LayoutInflater.from(parent.getContext()) .inflate(R.layout.content_info_produto_avaliacao, parent, false)); } @Override public void onBindViewHolder(ViewHolderProdutoAvaliacao holder, int position) { final ProdutoAvaliacao produtoAvaliacao = mProdutoAvaliacao.get(position); holder.txtNomeProdutoAvaliacao.setText(produtoAvaliacao.nome); holder.txtDataProdutoAvaliacao.setText(DateUtils.ConvertToString(produtoAvaliacao.data, context)); holder.txtNotaProdutoAvaliacao.setText(String.format("%d", produtoAvaliacao.avaliacao)); holder.txtDescricaoProdutoAvaliacao.setText(produtoAvaliacao.descricao); } @Override public int getItemCount() { return mProdutoAvaliacao != null ? mProdutoAvaliacao.size() : 0; } }
f547ecd1f325d7b7410819f10b855facf1e5621c
b9a0fbc1f0e3fdc82e5065a655754ef63354c816
/src/com/bjp/util/OverIsMergeablePlugin.java
4e00133e2f0f90d5730d434ee3bdd1ce1b034125
[]
no_license
learn2j-code/xupu-zongciweb
3e752fe489ab5553d75dab3bce4fa27019ba3018
5c17285997369f9b267c99c68d2fe8e947f43ae3
refs/heads/master
2022-12-29T23:42:29.298437
2020-10-20T15:37:15
2020-10-20T15:37:15
305,749,559
0
0
null
null
null
null
UTF-8
Java
false
false
807
java
package com.bjp.util; import org.mybatis.generator.api.GeneratedXmlFile; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.PluginAdapter; import java.lang.reflect.Field; import java.util.List; public class OverIsMergeablePlugin extends PluginAdapter { @Override public boolean validate(List<String> warnings) { return true; } @Override public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) { try { Field field = sqlMap.getClass().getDeclaredField("isMergeable"); field.setAccessible(true); field.setBoolean(sqlMap, false); } catch (Exception e) { e.printStackTrace(); } return true; } }
[ "Administrator@iZbdzc7ijwfizsZ" ]
Administrator@iZbdzc7ijwfizsZ
62f1a7660be35f75a3e33a96d612bcb6ac9c9f2e
fa7874cedd053e06a01425f2e9a5b6f0b141f372
/src/main/java/com/jfastnet/ISimpleProcessable.java
2586e149880e6e3be273c50da271d47436b19951
[ "Apache-2.0" ]
permissive
haiderny/jfastnet
dd76248a4e540e583d17c6a1d7a5919528534780
3e4b34a04d059da95df727320fa0fde070f5e058
refs/heads/master
2021-05-12T09:24:35.735703
2017-09-12T14:33:37
2017-09-12T14:33:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
906
java
/******************************************************************************* * Copyright 2015 Klaus Pfeiffer <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jfastnet; /** @author Klaus Pfeiffer - [email protected] */ public interface ISimpleProcessable { void process(); }
ea760151e2eda9c18eda67885cf40984103c9bb5
da5ce7545d453663373487bdf6d4d983dcffb3b4
/springboot/core-bean/src/main/java/core/bean/Myconfig2.java
c3858b8eb5865cf5cd15d5eeec70a8b18bd3ebc0
[]
no_license
jorfeng/springboot-demos
738a707c08fa8c392a534db20638b3aea08542ea
84d7e45250f92ba6c81f3c626dd009dce9be3f42
refs/heads/master
2020-03-23T21:30:09.950893
2018-05-29T10:22:49
2018-05-29T10:22:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
241
java
package core.bean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class Myconfig2 { @Bean public Dog dog(){ return new Dog(); } }
16082d99daaa12051197d3732a19dc479c368ff9
fbbd05e72d121dbeeef69ad100092ab17b920671
/src/main/java/com/simplify/sample/security/adapter/CustomWebSecurityConfigurerAdapter.java
6449bf81c30a5cd8995fcdcbcb48647623bcaa8e
[]
no_license
Simplify-study/SpringBootSample
4a9906b8e2160260fe3ff225fa3763dcda0b55b0
f54839bf60d04a39c794f6c82c19e04132eab191
refs/heads/master
2022-06-13T03:12:42.278881
2022-05-24T00:19:09
2022-05-24T00:19:09
151,514,871
3
7
null
2022-05-24T00:19:50
2018-10-04T03:43:11
Java
UTF-8
Java
false
false
2,250
java
package com.simplify.sample.security.adapter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import com.simplify.sample.handlers.CustomLoginFailureHandler; import com.simplify.sample.handlers.CustomLoginSuccessHandler; import com.simplify.sample.security.service.CustomUserDetailsService; @EnableWebSecurity public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Autowired CustomUserDetailsService customUserDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuthenticationSuccessHandler successHandler() { return new CustomLoginSuccessHandler("/"); } @Bean public AuthenticationFailureHandler failureHandler() { return new CustomLoginFailureHandler(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers("/openapi/**", "/resources/**"); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().formLogin() .successHandler(successHandler()).failureHandler(failureHandler()); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder()); } }
e5c242653f87883d50f99b422bcdadcb345e12f2
3a7fc488f72daa37123ef49ff5180138fde3187f
/src/com/lineage/server/datatables/sql/LogChatTable.java
9fcfef067c79854623240c30e6ea3ec07c7c4048
[]
no_license
WeiFangChou/lineage_363
52c3dc712e19853829c3d1802973cf307ca52143
dc2d3b3adc026d4b2933ec3573c44ce99ac8f6ea
refs/heads/master
2022-09-12T15:37:48.729753
2020-05-25T14:32:55
2020-05-25T14:32:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,870
java
package com.lineage.server.datatables.sql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.lineage.DatabaseFactory; import com.lineage.server.datatables.storage.LogChatStorage; import com.lineage.server.model.Instance.L1PcInstance; import com.lineage.server.utils.SQLUtil; /** * 对话纪录 * * @author dexc * */ public class LogChatTable implements LogChatStorage { private static final Log _log = LogFactory.getLog(LogChatTable.class); /** * 具有传送对象 * * @param pc * @param target * @param content * @param type */ @Override public void isTarget(final L1PcInstance pc, final L1PcInstance target, final String content, final int type) { if (target == null) { return; } Connection con = null; PreparedStatement pstm = null; try { final String account_name = pc.getAccountName(); final int char_id = pc.getId(); final String name = pc.isGm() ? "******" : pc.getName(); final int clan_id = pc.getClanid(); final String clan_name = pc.getClanname(); final int locx = pc.getX(); final int locy = pc.getY(); final short mapid = pc.getMapId(); final String target_account_name = target.getAccountName(); final int target_id = target.getId(); final String target_name = target.getName(); final int target_clan_id = target.getClanid(); final String target_clan_name = target.getClanname(); final int target_locx = target.getX(); final int target_locy = target.getY(); final short target_mapid = target.getMapId(); con = DatabaseFactory.get().getConnection(); pstm = con .prepareStatement("INSERT INTO other_chat (account_name, char_id, name, clan_id, clan_name, locx, locy, mapid, type, target_account_name, target_id, target_name, target_clan_id, target_clan_name, target_locx, target_locy, target_mapid, content, datetime) VALUE (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, SYSDATE())"); pstm.setString(1, account_name); pstm.setInt(2, char_id); pstm.setString(3, name); pstm.setInt(4, clan_id); pstm.setString(5, clan_name); pstm.setInt(6, locx); pstm.setInt(7, locy); pstm.setInt(8, mapid); pstm.setInt(9, type); pstm.setString(10, target_account_name); pstm.setInt(11, target_id); pstm.setString(12, target_name); pstm.setInt(13, target_clan_id); pstm.setString(14, target_clan_name); pstm.setInt(15, target_locx); pstm.setInt(16, target_locy); pstm.setInt(17, target_mapid); pstm.setString(18, content); pstm.execute(); } catch (final SQLException e) { _log.error(e.getLocalizedMessage(), e); } finally { SQLUtil.close(pstm); SQLUtil.close(con); } } /** * 无传送对象 * * @param pc * @param content * @param type */ @Override public void noTarget(final L1PcInstance pc, final String content, final int type) { Connection con = null; PreparedStatement pstm = null; try { final String account_name = pc.getAccountName(); final int char_id = pc.getId(); final String name = pc.isGm() ? "******" : pc.getName(); final int clan_id = pc.getClanid(); final String clan_name = pc.getClanname(); final int locx = pc.getX(); final int locy = pc.getY(); final short mapid = pc.getMapId(); con = DatabaseFactory.get().getConnection(); pstm = con .prepareStatement("INSERT INTO other_chat (account_name, char_id, name, clan_id, clan_name, locx, locy, mapid, type, content, datetime) VALUE (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, SYSDATE())"); pstm.setString(1, account_name); pstm.setInt(2, char_id); pstm.setString(3, name); pstm.setInt(4, clan_id); pstm.setString(5, clan_name); pstm.setInt(6, locx); pstm.setInt(7, locy); pstm.setInt(8, mapid); pstm.setInt(9, type); pstm.setString(10, content); pstm.execute(); } catch (final SQLException e) { _log.error(e.getLocalizedMessage(), e); } finally { SQLUtil.close(pstm); SQLUtil.close(con); } } }
de492a958c8b7b201ba633e437923e02bc3b27f6
23a23288eace02a1365b62d364122a22d54b663f
/RISHABH_SRIVASTAVA_LABBOOK/LAB_2/src/config/MyFactory.java
0c65e284acec9793527d22cc9697897095681596
[]
no_license
RishabhSrivastava27/Capgemini
7e83f4833074412f5653064643134d60944f0107
54b8abe207a6600ae94aadc9da5051c6be7dd0cc
refs/heads/master
2023-05-03T05:15:37.957252
2020-04-30T11:57:45
2020-04-30T11:57:45
242,647,818
0
0
null
2023-04-17T19:40:03
2020-02-24T04:39:21
Java
UTF-8
Java
false
false
424
java
package config; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class MyFactory { private static EntityManagerFactory emf; static { emf= Persistence.createEntityManagerFactory("ABES"); } public static EntityManager getEntityManager() { return emf.createEntityManager(); } }
3e7d7bba055a14b1a1663b31763ebde505707493
4558084438688284524ccdbfeafc770e4a838e61
/travelservices/src/de/hybris/platform/travelservices/dao/TravelConsignmentDao.java
68b62651b568db9795d58f32d1858bafd4499bf2
[]
no_license
rchhabra/ext-travel
d86696ef94842a5e00276756f7a42f09e4ffe076
4a3484ba318304aec717977f695c8082cb94ca9d
refs/heads/master
2021-05-12T01:53:42.256739
2018-01-15T16:10:18
2018-01-15T16:10:18
117,567,472
0
0
null
null
null
null
UTF-8
Java
false
false
1,089
java
/* * [y] hybris Platform * * Copyright (c) 2000-2017 SAP SE or an SAP affiliate company. * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with SAP Hybris. * */ package de.hybris.platform.travelservices.dao; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.ordersplitting.model.ConsignmentModel; import de.hybris.platform.ordersplitting.model.WarehouseModel; import de.hybris.platform.travelservices.model.user.TravellerModel; /** * The interface Travel consignment dao. */ public interface TravelConsignmentDao { /** * Gets consignment. * * @param warehouseModel * the warehouse model * @param order * the order * @param traveller * the traveller * @return the consignment */ ConsignmentModel getConsignment(WarehouseModel warehouseModel, OrderModel order, TravellerModel traveller); }
8037f0189231a5e71433aaafc61ca2f8d08f7d96
580a2f5e0d92687787a93e2dbbc9c20b1f1e4c7e
/proman-api/target/generated-sources/com/upgrad/proman/api/model/PermissionsType.java
a92ac68b6e2bdcf2b5072c72e11c6b4cd1bf3a0e
[]
no_license
guptapraveen89/Proman_Quora
fb773e1805a4c892e94581a4a1027254a2b7f16c
6873221519ae61cc87e14f58df8b5bc008341015
refs/heads/master
2022-09-27T09:33:33.554009
2020-01-20T17:07:51
2020-01-20T17:07:51
235,151,306
0
0
null
2022-09-08T01:06:03
2020-01-20T16:55:42
Java
UTF-8
Java
false
false
2,422
java
package com.upgrad.proman.api.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * PermissionsType */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-08-13T18:51:44.461+05:30") public class PermissionsType { @JsonProperty("id") private Integer id = null; @JsonProperty("name") private String name = null; public PermissionsType id(Integer id) { this.id = id; return this; } /** * Permission id of the user * @return id **/ @ApiModelProperty(required = true, value = "Permission id of the user") @NotNull public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public PermissionsType name(String name) { this.name = name; return this; } /** * Permission name of the user * @return name **/ @ApiModelProperty(required = true, value = "Permission name of the user") @NotNull public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PermissionsType permissionsType = (PermissionsType) o; return Objects.equals(this.id, permissionsType.id) && Objects.equals(this.name, permissionsType.name); } @Override public int hashCode() { return Objects.hash(id, name); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PermissionsType {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
93c33cc839c29e7d8102aad6664e7fd772c80245
c218e5f8838ffe92cb0301e54edb647a86396498
/qcb/qcb-common/src/main/java/com/xionger/qcb/common/util/json/JsonUtil.java
eaa636e96f2db171a6e6e511fd3a3da254830465
[]
no_license
fristflaytwo/qcb
52eec7475901302285707138972d26ed48f7db0a
eef6597c9b78cb2755d7700d5dcb9e7f3b966a8c
refs/heads/master
2021-01-11T03:20:16.425050
2017-09-22T10:06:34
2017-09-22T10:06:34
71,048,145
0
0
null
null
null
null
UTF-8
Java
false
false
3,421
java
package com.xionger.qcb.common.util.json; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; /** * @Project: trust-common * @Author zy * @Company: * @Create Time: 2016年7月26日 下午1:02:25 */ public class JsonUtil { private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class); private JsonUtil() { } private static Gson gson = new Gson(); public static String objectToJson(Object ts) { String jsonStr = null; if (gson != null) { jsonStr = gson.toJson(ts); } return jsonStr; } public static String objectToJsonDateSerializer(Object ts, final String dateformat) { String jsonStr = null; gson = new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new JsonSerializer<Date>() { public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { SimpleDateFormat format = new SimpleDateFormat(dateformat); return new JsonPrimitive(format.format(src)); } }).setDateFormat(dateformat).create(); if (gson != null) { jsonStr = gson.toJson(ts); } return jsonStr; } public static List<?> jsonToList(String jsonStr) { List<?> objList = null; if (gson != null) { java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<?>>() { }.getType(); objList = gson.fromJson(jsonStr, type); } return objList; } public static Map<?, ?> jsonToMap(String jsonStr) { Map<?, ?> objMap = null; if (gson != null) { java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<?, ?>>() { }.getType(); objMap = gson.fromJson(jsonStr, type); } return objMap; } public static Object jsonToBean(String jsonStr, Class<?> cl) { Object obj = null; if (gson != null) { obj = gson.fromJson(jsonStr, cl); } return obj; } @SuppressWarnings("unchecked") public static <T> T jsonToBeanDateSerializer(String jsonStr, Class<T> cl, final String pattern) { Object obj = null; gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { SimpleDateFormat format = new SimpleDateFormat(pattern); String dateStr = json.getAsString(); try { return format.parse(dateStr); } catch (ParseException e) { LOGGER.error(dateStr + "json转为对象失败", e); } return null; } }).setDateFormat(pattern).create(); if (gson != null) { obj = gson.fromJson(jsonStr, cl); } return (T) obj; } public static Object getJsonValue(String jsonStr, String key) { Object rulsObj = null; Map<?, ?> rulsMap = jsonToMap(jsonStr); if (rulsMap != null && rulsMap.size() > 0) { rulsObj = rulsMap.get(key); } return rulsObj; } }
7f821da0419b82b9fc5e2216fe9bdf0f6d0ece8e
5bb4a4b0364ec05ffb422d8b2e76374e81c8c979
/sdk/resources/mgmt/src/main/java/com/azure/resourcemanager/resources/fluent/inner/TemplateHashResultInner.java
8ffe982b0b32eecb3914e83b558912f164540cc7
[ "MIT", "LicenseRef-scancode-generic-cla", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-or-later", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
FabianMeiswinkel/azure-sdk-for-java
bd14579af2f7bc63e5c27c319e2653db990056f1
41d99a9945a527b6d3cc7e1366e1d9696941dbe3
refs/heads/main
2023-08-04T20:38:27.012783
2020-07-15T21:56:57
2020-07-15T21:56:57
251,590,939
3
1
MIT
2023-09-02T00:50:23
2020-03-31T12:05:12
Java
UTF-8
Java
false
false
2,164
java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.resources.fluent.inner; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** The TemplateHashResult model. */ @Fluent public final class TemplateHashResultInner { @JsonIgnore private final ClientLogger logger = new ClientLogger(TemplateHashResultInner.class); /* * The minified template string. */ @JsonProperty(value = "minifiedTemplate") private String minifiedTemplate; /* * The template hash. */ @JsonProperty(value = "templateHash") private String templateHash; /** * Get the minifiedTemplate property: The minified template string. * * @return the minifiedTemplate value. */ public String minifiedTemplate() { return this.minifiedTemplate; } /** * Set the minifiedTemplate property: The minified template string. * * @param minifiedTemplate the minifiedTemplate value to set. * @return the TemplateHashResultInner object itself. */ public TemplateHashResultInner withMinifiedTemplate(String minifiedTemplate) { this.minifiedTemplate = minifiedTemplate; return this; } /** * Get the templateHash property: The template hash. * * @return the templateHash value. */ public String templateHash() { return this.templateHash; } /** * Set the templateHash property: The template hash. * * @param templateHash the templateHash value to set. * @return the TemplateHashResultInner object itself. */ public TemplateHashResultInner withTemplateHash(String templateHash) { this.templateHash = templateHash; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
b69e532fd44f15081bf8b66f1a8d76773101d155
71f2a247385149bd3fa6376a2e9b49d62b241e6f
/app/src/main/java/com/example/fitnessplanner/adapters/MealsAdapter.java
6b880cd9c3e57671809a6ed47b7d740de4ceecce
[]
no_license
ap16at/FitnessPlanner
54b76312eabb6e690ec0961e344984c9c7f23e22
270b870aed1ceb94df63a39a6c9747b06b5547a7
refs/heads/master
2023-06-25T03:10:03.412404
2021-07-27T08:00:56
2021-07-27T08:00:56
378,291,782
0
0
null
null
null
null
UTF-8
Java
false
false
2,700
java
package com.example.fitnessplanner.adapters; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.RecyclerView; import com.example.fitnessplanner.R; import com.example.fitnessplanner.models.Meal; import java.util.ArrayList; import java.util.Arrays; public class MealsAdapter extends RecyclerView.Adapter<MealsAdapter.ViewHolder>{ Context context; private ArrayList<Meal> mealItems; public MealsAdapter(Context context, ArrayList<Meal> mealItems){ this.context = context; this.mealItems = mealItems; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.meal_items, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { String des = mealItems.get(position).getDescription(); holder.meal_name.setText(des); int cal = mealItems.get(position).getTotalCalories(); String calories = cal + "calories"; holder.total_cal.setText(calories); int pro = mealItems.get(position).getProtein(); String protein = "Protein: " + pro + "g"; holder.protein.setText(protein); int car = mealItems.get(position).getCarbs(); String carbs = "Carbs: " + car + "g"; holder.carb.setText(carbs); int fat = mealItems.get(position).getFat(); String fats = "Fats: " + fat + "g"; holder.fat.setText(fats); System.out.println("des: " + des + "cal: " + cal); } @Override public int getItemCount() { return mealItems.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ TextView meal_name; TextView total_cal; TextView protein; TextView carb; TextView fat; ConstraintLayout item; public ViewHolder(@NonNull View itemView) { super(itemView); meal_name = itemView.findViewById(R.id.meal_name); total_cal = itemView.findViewById(R.id.total_cal); protein = itemView.findViewById(R.id.protein); carb = itemView.findViewById(R.id.carb); fat = itemView.findViewById(R.id.fat); item = itemView.findViewById(R.id.meal_item); } } }
612037adac39a1b3c37596f19c71c2e5649f0ab1
347e5bff5320b08b32d5e2e492fdd971d56281f6
/app/src/main/java/com/hbln/myadvertisingtest/FrameWork/DividerItemDecoration.java
e105e5a3824babdbec5ce542892864f66aa7bc25
[]
no_license
freedream520/MyAdvertisingTest
75b91866b2b834476cda6ebeed400e8064fe1ecc
5c69206ac2d04244838dff4c52295f9165bb9b50
refs/heads/master
2021-01-20T18:33:13.895117
2016-03-15T10:15:29
2016-03-15T10:15:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,356
java
package com.hbln.myadvertisingtest.FrameWork; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Created by Administrator on 2015/10/21. */ public class DividerItemDecoration extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[]{ android.R.attr.listDivider }; public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; private Drawable mDivider; private int mOrientation; public DividerItemDecoration(Context context, int orientation) { final TypedArray a = context.obtainStyledAttributes(ATTRS); mDivider = a.getDrawable(0); a.recycle(); setOrientation(orientation); } public void setOrientation(int orientation) { if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { throw new IllegalArgumentException("invalid orientation"); } mOrientation = orientation; } @Override public void onDraw(Canvas c, RecyclerView parent) { if (mOrientation == VERTICAL_LIST) { drawVertical(c, parent); } else { drawHorizontal(c, parent); } } public void drawVertical(Canvas c, RecyclerView parent) { final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext()); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } public void drawHorizontal(Canvas c, RecyclerView parent) { final int top = parent.getPaddingTop(); final int bottom = parent.getHeight() - parent.getPaddingBottom(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int left = child.getRight() + params.rightMargin; final int right = left + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { if (mOrientation == VERTICAL_LIST) { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); } } }
284bc90ddcd300eb06d502920c5d83f11c9f6c6e
57cf0448c6e372147a265f9a657f999e02f9b282
/src/net/atomique/ksar/Solaris/squeueSar.java
661f9a4d64e314d7947c668367e1a18d0737aac6
[ "BSD-3-Clause" ]
permissive
czerwonk/ksar-fork
ee9cbbc270d0c26257fc67b7365974f10fd9f827
d7757711ca69c95d193db2c8ae78a2d3c713c275
refs/heads/master
2023-08-31T16:30:35.196807
2010-01-31T15:46:00
2010-01-31T15:46:00
477,967
2
1
null
null
null
null
UTF-8
Java
false
false
3,505
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.atomique.ksar.Solaris; import javax.swing.tree.DefaultMutableTreeNode; import net.atomique.ksar.AllGraph; import net.atomique.ksar.GraphDescription; import net.atomique.ksar.kSar; import net.atomique.ksar.kSarConfig; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CombinedDomainXYPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.data.time.Second; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; /** * * @author alex */ public class squeueSar extends AllGraph { public squeueSar(final kSar hissar) { super(hissar); Title = "Swap queue"; t_swpqsz = new TimeSeries("swpq-sz", org.jfree.data.time.Second.class); mysar.dispo.put("Swap queue size", t_swpqsz); t_swpqocc = new TimeSeries("swpqocc", org.jfree.data.time.Second.class); mysar.dispo.put("Swap queuue occupied", t_swpqocc); // Collection collectionswpq1 = new TimeSeriesCollection(); collectionswpq1.addSeries(this.t_swpqsz); collectionswpq2 = new TimeSeriesCollection(); collectionswpq2.addSeries(this.t_swpqocc); } public void add(final Second now,final Float val1Init,final Float val2Init) { this.t_swpqsz.add(now, val1Init, do_notify()); this.t_swpqocc.add(now, val2Init, do_notify()); number_of_sample++; } public void addtotree(final DefaultMutableTreeNode myroot) { mynode = new DefaultMutableTreeNode(new GraphDescription(this, "SOLARISSQUEUE", this.Title, null)); mysar.add2tree(myroot,mynode); } public JFreeChart makegraph(final Second g_start, final Second g_end) { // swap XYItemRenderer minichart1 = new StandardXYItemRenderer(); minichart1.setBaseStroke(kSarConfig.DEFAULT_STROKE); minichart1.setSeriesPaint(0, kSarConfig.color1); XYPlot subplot1 = new XYPlot(collectionswpq1, null, new NumberAxis(""), minichart1); // mem XYItemRenderer minichart2 = new StandardXYItemRenderer(); minichart2.setSeriesPaint(0, kSarConfig.color2); minichart2.setBaseStroke(kSarConfig.DEFAULT_STROKE); XYPlot subplot2 = new XYPlot(collectionswpq2, null, new NumberAxis("%"), minichart2); // the graph CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis("")); plot.add(subplot1, 1); plot.add(subplot2, 1); plot.setOrientation(PlotOrientation.VERTICAL); // the graph JFreeChart mychart = new JFreeChart(this.getGraphTitle(), kSarConfig.DEFAULT_FONT, plot, true); if (setbackgroundimage(mychart) == 1) { subplot1.setBackgroundPaint(null); subplot2.setBackgroundPaint(null); } if (g_start != null) { DateAxis dateaxis1 = (DateAxis) mychart.getXYPlot().getDomainAxis(); dateaxis1.setRange(g_start.getStart(), g_end.getEnd()); } return mychart; } private final TimeSeries t_swpqsz; private final TimeSeries t_swpqocc; private final TimeSeriesCollection collectionswpq1; private final TimeSeriesCollection collectionswpq2; }
9f1fb1a8c5bb4a9261e2a13191fe247a409339f4
f0373b9417f953cb2cb0e53f5a3e8edaed608b00
/ly-order/src/main/java/com/leyou/order/utils/PayHelper.java
1ce9b9c9d1580df6ec232cfb20a9283d4828a845
[]
no_license
wyh97210/leyou
d93c9d83048c8d72654c7942a61aa1ee36447b49
92c7c2c5a03ad7e5772974d1411cf904a6fc78ab
refs/heads/master
2022-12-25T09:22:55.574188
2020-06-11T05:48:20
2020-06-11T05:48:20
197,743,823
0
0
null
2022-12-16T00:44:37
2019-07-19T09:24:28
Java
UTF-8
Java
false
false
5,819
java
package com.leyou.order.utils; import com.github.wxpay.sdk.WXPay; import com.github.wxpay.sdk.WXPayConstants; import com.github.wxpay.sdk.WXPayUtil; import com.leyou.common.enums.ExceptionEnum; import com.leyou.common.exception.LyException; import com.leyou.order.config.PayConfig; import com.leyou.order.enums.OrderStatusEnum; import com.leyou.order.enums.PayState; import com.leyou.order.mapper.OrderMapper; import com.leyou.order.mapper.OrderStatusMapper; import com.leyou.order.pojo.Order; import com.leyou.order.pojo.OrderStatus; import java.util.Date; import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import static com.github.wxpay.sdk.WXPayConstants.FAIL; import static com.github.wxpay.sdk.WXPayConstants.SUCCESS; @Slf4j @Component public class PayHelper { @Autowired private WXPay wxPay; @Autowired private PayConfig payConfig; @Autowired private OrderMapper orderMapper; @Autowired private OrderStatusMapper statusMapper; public String createPayUrl(Long orderId, Long totalFee, String body) { // 准备请求参数 HashMap<String, String> data = new HashMap<>(); data.put("body", body); data.put("out_trade_no", orderId.toString()); data.put("total_fee", totalFee.toString()); data.put("spbill_create_ip", payConfig.getSpbillCreateIp()); String notifyUrl = payConfig.getNotifyUrl(); log.info("notifyUrl = {}", notifyUrl); data.put("notify_url", notifyUrl); data.put("trade_type", payConfig.getTradeType()); try { // 调用统一下单 API Map<String, String> result = wxPay.unifiedOrder(data); isSuccess(result); // 验证签名 //isSignatureValid(result); String payUrl = result.get("code_url"); return payUrl; } catch (Exception e) { log.error("【微信下单】下单失败,订单号:{}", orderId, e); throw new LyException(ExceptionEnum.WX_PAY_ORDER_FAIL); } } public void isSuccess(Map<String, String> result) { // 校验通信标示 if (FAIL.equals(result.get("return_code"))) { log.error("【微信下单】下单通信失败, 原因:{}", result.get("return_msg")); throw new LyException(ExceptionEnum.WX_PAY_ORDER_FAIL); } // 校验业务标示 if (FAIL.equals(result.get("result_code"))) { log.error("【微信下单】下单失败, 错误码:{}, 错误原因:{}", result.get("err_code"), result.get("err_code_des")); throw new LyException(ExceptionEnum.WX_PAY_ORDER_FAIL); } } public void isValidSign(Map<String, String> data) { // 重新生成签名, 和传过来的签名进行比较 try { String sign1 = WXPayUtil.generateSignature(data, payConfig.getKey(), WXPayConstants.SignType.MD5); String sign2 = WXPayUtil.generateSignature(data, payConfig.getKey(), WXPayConstants.SignType.HMACSHA256); String sign = data.get("sign"); if (!StringUtils.equals(sign, sign1) && !StringUtils.equals(sign, sign2)) { // 签名有误 throw new LyException(ExceptionEnum.INVALID_SIGN_ERROR); } } catch (Exception e) { log.error("【微信下单】签名验证出错 ", e); throw new LyException(ExceptionEnum.INVALID_SIGN_ERROR); } } public PayState queryPayState(Long orderId) { try { Map<String, String> data = new HashMap<>(); data.put("out_trade_no", orderId.toString()); Map<String, String> result = wxPay.orderQuery(data); // 校验状态 isSuccess(result); // 校验签名 isValidSign(result); // 校验金额 String totalFeeStr = result.get("total_fee"); String tradeNoStr = result.get("out_trade_no"); if (StringUtils.isBlank(tradeNoStr) || StringUtils.isBlank(totalFeeStr)) { throw new LyException(ExceptionEnum.INVALID_ORDER_PARAM); } Long totalFee = Long.valueOf(totalFeeStr); Order order = orderMapper.selectByPrimaryKey(orderId); if (order == null) { throw new LyException(ExceptionEnum.INVALID_ORDER_PARAM); } // FIXME 这里应该是不等于实际金额 if (totalFee != 1L) { // 金额不符 throw new LyException(ExceptionEnum.INVALID_ORDER_PARAM); } String state = result.get("trade_state"); if (SUCCESS.equals(state)) { // 修改订单状态 OrderStatus status = new OrderStatus(); status.setStatus(OrderStatusEnum.PAYED.getCode()); status.setOrderId(orderId); status.setPaymentTime(new Date()); int count = statusMapper.updateByPrimaryKeySelective(status); if (count != 1) { throw new LyException(ExceptionEnum.UPDATE_ORDER_STATUS_ERROR); } return PayState.SUCCESS; } else if ("NOTPAY".equals(state) || "USERPAYING".equals(state)) { return PayState.NOT_PAY; } return PayState.FAIL; } catch (Exception e) { log.error("[微信支付], 调用微信接口查询支付状态失败", e); return PayState.NOT_PAY; } } }
2b5abfbba3eec2ca0ccafcb4279ad73c1747933e
866171598378e08aff65eccda43b013b3e764a1c
/Sponsor.java
5d5586fe6e783e0b0ad1a1163964789493fe73c0
[]
no_license
Samu1991/java-ficha-7
21e9e57454281b0364cc109f1a9376f7614b53cf
669e0e50fce8eff7cb5072271f8da6de75046f16
refs/heads/master
2020-05-20T13:14:28.812346
2019-05-08T11:28:14
2019-05-08T11:28:14
185,592,363
0
0
null
null
null
null
UTF-8
Java
false
false
290
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Enum; /** * * @author samum */ public enum Sponsor { NIKE,ADIDAS,PUMA; }
86ab7ce039254bccbd444a1837e87b9a07a8e775
7e6ffeaeab0dad59d6d25a8d4ea4c2f6e5c6317b
/src/introsde/assignment/soap/ReadMeasureTypesResponse.java
c125474c437a2deac38aa977359794ead65ff5df
[]
no_license
FinalProject-ZsanettOrosz/StorageService
940e7c2ae483c67e8497c3f1c62b0c0a4fb95a3c
df29811dc18130f4b620e872d95443e676bc6307
refs/heads/master
2021-01-10T17:17:07.959600
2016-01-19T19:58:19
2016-01-19T19:58:19
49,892,147
0
0
null
null
null
null
UTF-8
Java
false
false
1,531
java
package introsde.assignment.soap; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for readMeasureTypesResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="readMeasureTypesResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="measureType" type="{http://soap.assignment.introsde/}customMeasureDefinition" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "readMeasureTypesResponse", propOrder = { "measureType" }) public class ReadMeasureTypesResponse { protected CustomMeasureDefinition measureType; /** * Gets the value of the measureType property. * * @return * possible object is * {@link CustomMeasureDefinition } * */ public CustomMeasureDefinition getMeasureType() { return measureType; } /** * Sets the value of the measureType property. * * @param value * allowed object is * {@link CustomMeasureDefinition } * */ public void setMeasureType(CustomMeasureDefinition value) { this.measureType = value; } }
afb0066fe08d211e309f77463b72118234f5114d
00dfd3d1f4eca58df2c1fb595ba94edcd6108edc
/src/main/java/com/mobimeo/citynavigation/dao/model/Stop.java
8265060e1d116489104041a683d0c729e04ea578
[ "MIT" ]
permissive
gamal-ahmed/verspaetung-navigation
e22aabc6b708aa2170813393db9274f3fcc6dafc
a6b555b96f476b1d63a99e5b0071bd650b48856c
refs/heads/master
2020-03-23T17:14:21.466915
2018-07-25T02:57:23
2018-07-25T02:57:23
141,850,067
0
0
null
null
null
null
UTF-8
Java
false
false
1,661
java
package com.mobimeo.citynavigation.dao.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.util.Objects; @Entity @Table(name = "stop") @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Stop { @Id @GeneratedValue() private Long id; private Long stopId; private int x; private int y; public Stop(Long stopId, int x, int y) { this.x = x; this.stopId = stopId; this.y = y; } public Stop(){} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getStopId() { return stopId; } public void setStopId(Long stopId) { this.stopId = stopId; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Stop stop = (Stop) o; return Objects.equals(id, stop.id) && Objects.equals(stopId, stop.stopId) && Objects.equals(x, stop.x) && Objects.equals(y, stop.y); } @Override public int hashCode() { return Objects.hash(id, stopId, x, y); } }
7a46965ea28036379e629acc92a6d61a98e0bfd5
255ff79057c0ff14d0b760fc2d6da1165f1806c8
/08Advanced/12资料-并发编程/concurrent/case_java8/src/main/java/cn/itcast/n8/Emp.java
747ffad3b1bb8eefc1c485097ada796e82877605
[]
no_license
wjphappy90/Resource
7f1f817d323db5adae06d26da17dfc09ee5f9d3a
6574c8399f3cdfb6d6b39cd64dc9507e784a2549
refs/heads/master
2022-07-30T03:33:59.869345
2020-08-10T02:31:35
2020-08-10T02:31:35
285,701,650
2
6
null
null
null
null
UTF-8
Java
false
false
941
java
package cn.itcast.n8; import java.math.BigDecimal; class Emp { private int empno; private String ename; private String job; private BigDecimal sal; public int getEmpno() { return empno; } public void setEmpno(int empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public BigDecimal getSal() { return sal; } public void setSal(BigDecimal sal) { this.sal = sal; } @Override public String toString() { return "Emp{" + "empno=" + empno + ", ename='" + ename + '\'' + ", job='" + job + '\'' + ", sal=" + sal + '}'; } }
b986930b04873e84a3125d9f91bc4512603ff558
937f30f7f8addf2c7157435909d09fe93e397bfd
/web-app/src/main/java/org/ideakat/webapp/api/contract/auth/AuthenticationStatus.java
2e152ee0258ba20569ebf4b6d65c62ecdc600011
[]
no_license
swar8080/ideaKat
4e4bf173ddc52e851fb32e66d3d67bd9e3e4b010
4c27b66b614eaf5ad03a03679022fa0067558105
refs/heads/master
2022-12-27T08:39:14.204765
2020-04-25T01:50:49
2020-04-25T01:50:49
253,299,960
1
0
null
2022-12-16T01:59:26
2020-04-05T18:07:47
TypeScript
UTF-8
Java
false
false
391
java
package org.ideakat.webapp.api.contract.auth; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Builder; import lombok.Data; import org.ideakat.domain.entities.user.User; @Data @Builder public class AuthenticationStatus { @JsonProperty("isLoggedIn") private boolean isLoggedIn; private User user; @JsonProperty("isAdmin") private boolean isAdmin; }
1d611d48cdc4cc3605011cdc2ae7d473a5db8923
b6914ccf36d274f1235107bcae315df5b296af3a
/src/com/roboxes/messaging/Message.java
706b43195f1a683d1c475c48ed754b161b4ec2c6
[]
no_license
toastedcode/IoTDebugger
4559dd1aa8039a7e604363426862c6e02098a302
8c9f066f60fd8b0c11f051ed99fbdf7377471e08
refs/heads/master
2020-06-27T06:27:39.001307
2019-03-22T19:16:27
2019-03-22T19:16:27
97,050,278
0
0
null
null
null
null
UTF-8
Java
false
false
2,430
java
package com.roboxes.messaging; import org.json.simple.JSONObject; public class Message { public Message() { json = new JSONObject(); } public Message(String messageId) { json = new JSONObject(); setMessageId(messageId); } public Message(JSONObject json) { this.json = (JSONObject)json.clone(); } public String getMessageId() { return ((String)json.get("messageId")); } @SuppressWarnings("unchecked") public void setMessageId( String messageId) { json.put("messageId", messageId); } public String getSource() { return ((String)json.get("source")); } @SuppressWarnings("unchecked") public void setSource( String id) { json.put("source", id); } public String getDestination() { return ((String)json.get("destination")); } @SuppressWarnings("unchecked") public void setDestination( String id) { json.put("destination", id); } public String getTopic() { return ((String)json.get("topic")); } @SuppressWarnings("unchecked") public void setTopic( String topic) { json.put("topic", topic); } public String getTransactionId() { return ((String)json.get("transactionId")); } @SuppressWarnings("unchecked") public void setTransactionId( String transactionId) { json.put("transactionId", transactionId); } @SuppressWarnings("unchecked") public void put(String key, Object value) { json.put(key, value); } public Object get(String key) { return (json.get(key)); } public JSONObject getJson() { return ((JSONObject)json.clone()); } public int getInt(String key) { int value = 0; try { Long longValue = (Long)json.get(key); value = longValue.intValue(); } catch (NullPointerException | ClassCastException e) { // No value existed, or was not an Integer. } return (value); } public String getString(String key) { String value = ""; try { value = (String)json.get(key); } catch (NullPointerException | ClassCastException e) { // No value existed, or was not a String. } return (value); } JSONObject json; }
2da96da1d49e0aa750faffe97029b375dec1ceac
cf9b167b6d73305eb7cb37712bc70fb8b2f60175
/minecraft/net/minecraft/src/Lagometer.java
a8be30b232c23d172e3b878f021c0186c4c92015
[]
no_license
Capsar/Rapture
b1ef74dfceb005b291e695605f83839dc25d1c9e
b73f53f22eb1caed44e39e4a026eac5cda7b41fc
refs/heads/master
2021-06-12T20:06:53.100425
2020-04-09T14:13:47
2020-04-09T14:13:47
254,388,305
5
2
null
null
null
null
UTF-8
Java
false
false
10,028
java
package net.minecraft.src; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiIngame; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.settings.GameSettings; import net.minecraft.profiler.Profiler; import org.lwjgl.opengl.GL11; public class Lagometer { private static Minecraft mc; private static GameSettings gameSettings; private static Profiler profiler; public static boolean active = false; public static Lagometer.TimerNano timerTick = new Lagometer.TimerNano(); public static Lagometer.TimerNano timerScheduledExecutables = new Lagometer.TimerNano(); public static Lagometer.TimerNano timerChunkUpload = new Lagometer.TimerNano(); public static Lagometer.TimerNano timerChunkUpdate = new Lagometer.TimerNano(); public static Lagometer.TimerNano timerVisibility = new Lagometer.TimerNano(); public static Lagometer.TimerNano timerTerrain = new Lagometer.TimerNano(); public static Lagometer.TimerNano timerServer = new Lagometer.TimerNano(); private static long[] timesFrame = new long[512]; private static long[] timesTick = new long[512]; private static long[] timesScheduledExecutables = new long[512]; private static long[] timesChunkUpload = new long[512]; private static long[] timesChunkUpdate = new long[512]; private static long[] timesVisibility = new long[512]; private static long[] timesTerrain = new long[512]; private static long[] timesServer = new long[512]; private static boolean[] gcs = new boolean[512]; private static int numRecordedFrameTimes = 0; private static long prevFrameTimeNano = -1L; private static long renderTimeNano = 0L; private static long memTimeStartMs = System.currentTimeMillis(); private static long memStart = getMemoryUsed(); private static long memTimeLast = memTimeStartMs; private static long memLast = memStart; private static long memTimeDiffMs = 1L; private static long memDiff = 0L; private static int memMbSec = 0; public static boolean updateMemoryAllocation() { long timeNowMs = System.currentTimeMillis(); long memNow = getMemoryUsed(); boolean gc = false; if (memNow < memLast) { double memDiffMb = memDiff / 1000000.0D; double timeDiffSec = memTimeDiffMs / 1000.0D; int mbSec = (int)(memDiffMb / timeDiffSec); if (mbSec > 0) { memMbSec = mbSec; } memTimeStartMs = timeNowMs; memStart = memNow; memTimeDiffMs = 0L; memDiff = 0L; gc = true; } else { memTimeDiffMs = timeNowMs - memTimeStartMs; memDiff = memNow - memStart; } memTimeLast = timeNowMs; memLast = memNow; return gc; } private static long getMemoryUsed() { Runtime r = Runtime.getRuntime(); return r.totalMemory() - r.freeMemory(); } public static void updateLagometer() { if (mc == null) { mc = Minecraft.getMinecraft(); gameSettings = mc.gameSettings; profiler = mc.mcProfiler; } if (gameSettings.showDebugInfo && gameSettings.ofLagometer) { active = true; long timeNowNano = System.nanoTime(); if (prevFrameTimeNano == -1L) { prevFrameTimeNano = timeNowNano; } else { int frameIndex = numRecordedFrameTimes & timesFrame.length - 1; ++numRecordedFrameTimes; boolean gc = updateMemoryAllocation(); timesFrame[frameIndex] = timeNowNano - prevFrameTimeNano - renderTimeNano; timesTick[frameIndex] = timerTick.timeNano; timesScheduledExecutables[frameIndex] = timerScheduledExecutables.timeNano; timesChunkUpload[frameIndex] = timerChunkUpload.timeNano; timesChunkUpdate[frameIndex] = timerChunkUpdate.timeNano; timesVisibility[frameIndex] = timerVisibility.timeNano; timesTerrain[frameIndex] = timerTerrain.timeNano; timesServer[frameIndex] = timerServer.timeNano; gcs[frameIndex] = gc; timerTick.reset(); timerScheduledExecutables.reset(); timerVisibility.reset(); timerChunkUpdate.reset(); timerChunkUpload.reset(); timerTerrain.reset(); timerServer.reset(); prevFrameTimeNano = System.nanoTime(); } } else { active = false; prevFrameTimeNano = -1L; } } public static void showLagometer(ScaledResolution scaledResolution) { if (gameSettings != null && gameSettings.ofLagometer) { long timeRenderStartNano = System.nanoTime(); GlStateManager.clear(256); GlStateManager.matrixMode(5889); GlStateManager.pushMatrix(); GlStateManager.enableColorMaterial(); GlStateManager.loadIdentity(); GlStateManager.ortho(0.0D, mc.displayWidth, mc.displayHeight, 0.0D, 1000.0D, 3000.0D); GlStateManager.matrixMode(5888); GlStateManager.pushMatrix(); GlStateManager.loadIdentity(); GlStateManager.translate(0.0F, 0.0F, -2000.0F); GL11.glLineWidth(1.0F); GlStateManager.disableTexture2D(); Tessellator tess = Tessellator.getInstance(); WorldRenderer tessellator = tess.getWorldRenderer(); tessellator.startDrawing(1); int memColR; for (int lumMem = 0; lumMem < timesFrame.length; ++lumMem) { memColR = (lumMem - numRecordedFrameTimes & timesFrame.length - 1) * 100 / timesFrame.length; memColR += 155; float memColG = mc.displayHeight; long memColB = 0L; if (gcs[lumMem]) { renderTime(lumMem, timesFrame[lumMem], memColR, memColR / 2, 0, memColG, tessellator); } else { renderTime(lumMem, timesFrame[lumMem], memColR, memColR, memColR, memColG, tessellator); memColG -= renderTime(lumMem, timesServer[lumMem], memColR / 2, memColR / 2, memColR / 2, memColG, tessellator); memColG -= renderTime(lumMem, timesTerrain[lumMem], 0, memColR, 0, memColG, tessellator); memColG -= renderTime(lumMem, timesVisibility[lumMem], memColR, memColR, 0, memColG, tessellator); memColG -= renderTime(lumMem, timesChunkUpdate[lumMem], memColR, 0, 0, memColG, tessellator); memColG -= renderTime(lumMem, timesChunkUpload[lumMem], memColR, 0, memColR, memColG, tessellator); memColG -= renderTime(lumMem, timesScheduledExecutables[lumMem], 0, 0, memColR, memColG, tessellator); float var10000 = memColG - renderTime(lumMem, timesTick[lumMem], 0, memColR, memColR, memColG, tessellator); } } tess.draw(); GlStateManager.matrixMode(5889); GlStateManager.popMatrix(); GlStateManager.matrixMode(5888); GlStateManager.popMatrix(); GlStateManager.enableTexture2D(); float var12 = 1.0F - (float)((System.currentTimeMillis() - memTimeStartMs) / 1000.0D); var12 = Config.limit(var12, 0.0F, 1.0F); memColR = (int)(170.0F + var12 * 85.0F); int var13 = (int)(100.0F + var12 * 55.0F); int var14 = (int)(10.0F + var12 * 10.0F); int colMem = memColR << 16 | var13 << 8 | var14; int posX = 512 / scaledResolution.getScaleFactor() + 2; int posY = mc.displayHeight / scaledResolution.getScaleFactor() - 8; GuiIngame var15 = mc.ingameGUI; Gui.drawRect(posX - 1, posY - 1, posX + 50, posY + 10, -1605349296); mc.fontRendererObj.drawString(" " + memMbSec + " MB/s", posX, posY, colMem); renderTimeNano = System.nanoTime() - timeRenderStartNano; } } private static long renderTime(int frameNum, long time, int r, int g, int b, float baseHeight, WorldRenderer tessellator) { long heightTime = time / 200000L; if (heightTime < 3L) { return 0L; } else { tessellator.setColorRGBA(r, g, b, 255); tessellator.addVertex(frameNum + 0.5F, baseHeight - heightTime + 0.5F, 0.0D); tessellator.addVertex(frameNum + 0.5F, baseHeight + 0.5F, 0.0D); return heightTime; } } public static boolean isActive() { return active; } public static class TimerNano { public long timeStartNano = 0L; public long timeNano = 0L; public void start() { if (Lagometer.active) { if (this.timeStartNano == 0L) { this.timeStartNano = System.nanoTime(); } } } public void end() { if (Lagometer.active) { if (this.timeStartNano != 0L) { this.timeNano += System.nanoTime() - this.timeStartNano; this.timeStartNano = 0L; } } } private void reset() { this.timeNano = 0L; this.timeStartNano = 0L; } } }
756fb8d6f542480c14f4e422fb44bf60b1dff11b
c4a033cf7cadcdf2f9dca20da6ee268f19f76369
/src/main/java/com/shell/autowiring/AutoWiringService.java
0f8065a624562d7601aa592ef59f9f3ba238c841
[]
no_license
xieyufish/springstudy
3c7bf9a559ba917851bed13d66bb07689a375edd
c0867f18a4006cbd29d8c6567f16fa05b493f869
refs/heads/master
2021-01-23T03:58:58.489896
2015-09-17T01:46:28
2015-09-17T01:46:28
42,162,100
0
0
null
null
null
null
UTF-8
Java
false
false
621
java
package com.shell.autowiring; public class AutoWiringService { private AutoWiringDAO autoWiringDAO; /** * @param autoWiringDAO the autoWiringDAO to set */ public void setAutoWiringDAO(AutoWiringDAO autoWiringDAO) { System.out.println("setter method"); this.autoWiringDAO = autoWiringDAO; } public AutoWiringService() { System.out.println("default constructor"); } public AutoWiringService(AutoWiringDAO autoWiringDAO) { System.out.println("constructor method"); this.autoWiringDAO = autoWiringDAO; } public void dao(String word) { autoWiringDAO.dao(word); } }
f59e7affee6c9b4947b2df769abdcf9360f0c6a8
5e0a4ec9a896977798051ac2c715bc48b9181e9c
/app/src/androidTest/java/com/example/admin/myquizapp/ApplicationTest.java
2b6de21eaecb34ecc94ed2eadd5a2d30c058d0fa
[]
no_license
maiti1/QuizApp
3e7a9cacb1b9cc88c2a64480a90efb87a93e12ec
9348f915a86dc05d6f53acb9cf8c6c7c7ad1fce8
refs/heads/master
2021-01-10T23:23:54.777218
2016-10-12T07:48:59
2016-10-12T07:48:59
70,588,539
0
0
null
null
null
null
UTF-8
Java
false
false
358
java
package com.example.admin.myquizapp; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
5e539c9f3d61f487cd30ce99a2b2d402e94d2f06
bf2966abae57885c29e70852243a22abc8ba8eb0
/aws-java-sdk-elasticache/src/main/java/com/amazonaws/services/elasticache/model/transform/DeleteUserGroupResultStaxUnmarshaller.java
05d9b99068bc2439d3a2207f597ec0be8e306573
[ "Apache-2.0" ]
permissive
kmbotts/aws-sdk-java
ae20b3244131d52b9687eb026b9c620da8b49935
388f6427e00fb1c2f211abda5bad3a75d29eef62
refs/heads/master
2021-12-23T14:39:26.369661
2021-07-26T20:09:07
2021-07-26T20:09:07
246,296,939
0
0
Apache-2.0
2020-03-10T12:37:34
2020-03-10T12:37:33
null
UTF-8
Java
false
false
4,369
java
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.elasticache.model.transform; import java.util.ArrayList; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.elasticache.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * DeleteUserGroupResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteUserGroupResultStaxUnmarshaller implements Unmarshaller<DeleteUserGroupResult, StaxUnmarshallerContext> { public DeleteUserGroupResult unmarshall(StaxUnmarshallerContext context) throws Exception { DeleteUserGroupResult deleteUserGroupResult = new DeleteUserGroupResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 2; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return deleteUserGroupResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("UserGroupId", targetDepth)) { deleteUserGroupResult.setUserGroupId(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("Status", targetDepth)) { deleteUserGroupResult.setStatus(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("Engine", targetDepth)) { deleteUserGroupResult.setEngine(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("UserIds", targetDepth)) { deleteUserGroupResult.withUserIds(new ArrayList<String>()); continue; } if (context.testExpression("UserIds/member", targetDepth)) { deleteUserGroupResult.withUserIds(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("PendingChanges", targetDepth)) { deleteUserGroupResult.setPendingChanges(UserGroupPendingChangesStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("ReplicationGroups", targetDepth)) { deleteUserGroupResult.withReplicationGroups(new ArrayList<String>()); continue; } if (context.testExpression("ReplicationGroups/member", targetDepth)) { deleteUserGroupResult.withReplicationGroups(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("ARN", targetDepth)) { deleteUserGroupResult.setARN(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return deleteUserGroupResult; } } } } private static DeleteUserGroupResultStaxUnmarshaller instance; public static DeleteUserGroupResultStaxUnmarshaller getInstance() { if (instance == null) instance = new DeleteUserGroupResultStaxUnmarshaller(); return instance; } }
[ "" ]
859fd9a09f3593607edad9a731f5b7feb234d51e
0f4f6c6d779fd9ba8a85a1697379dddeff31b9e0
/src/main/java/com/kish/demooauthserver/oauth/config/AuthServerOAuth2Config.java
113626eda420c3f4930602e75a1ecff0f0993db9
[]
no_license
ThejKishore/cust_authorization_server_demo
9b49e5f9dd19cf1ce3d9960b82c3159b862a71e2
596e5509a5aab0fa1d04508e5611e49364476de3
refs/heads/master
2021-04-29T18:55:37.687302
2018-02-17T20:39:58
2018-02-17T20:39:58
121,703,516
0
0
null
null
null
null
UTF-8
Java
false
false
4,605
java
package com.kish.demooauthserver.oauth.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.DatabasePopulator; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import javax.sql.DataSource; @Configuration @EnableAuthorizationServer public class AuthServerOAuth2Config extends AuthorizationServerConfigurerAdapter { @Autowired private Environment env; @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Override public void configure( AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer .tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource()) .withClient("sampleClientId") .authorizedGrantTypes("implicit") .scopes("read") .autoApprove(true) .and() .withClient("clientIdPassword") .secret("secret") .authorizedGrantTypes( "password","authorization_code", "refresh_token") .scopes("read"); } @Override public void configure( AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .tokenStore(tokenStore()) .authenticationManager(authenticationManager); // endpoints // .accessTokenConverter(accessTokenConverter()) // .authenticationManager(authenticationManager); // endpoints.authenticationManager(authenticationManager); // endpoints.userDetailsService(); } @Bean public JwtAccessTokenConverter accessTokenConverter() { return new JwtAccessTokenConverter(); } @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource()); } /// @Value("classpath:schema.sql") private Resource schemaScript; @Value("classpath:data.sql") private Resource dataScript; @Bean public DataSourceInitializer dataSourceInitializer(DataSource dataSource) { DataSourceInitializer initializer = new DataSourceInitializer(); initializer.setDataSource(dataSource); initializer.setDatabasePopulator(databasePopulator()); return initializer; } private DatabasePopulator databasePopulator() { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScripts(schemaScript,dataScript); return populator; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; } }
a8752bbfa9fa2d6c6d0f23b92e6e5cc2ee03ab1c
265eac54e500542064d321654ff478e4ed8d53c6
/masoom/src/test/java/com/masoomyf/masoom/ExampleUnitTest.java
0d5f562aebc0616e05dc6d43f09b8f24a8eb8ca9
[]
no_license
masoomyf/MasoomLibraryExample
6c6ca2d591c663d8ba35d0645807b1655d742089
8431d41185b8d73d7f0b27a639f05091ec3e12ad
refs/heads/master
2020-05-07T18:17:48.900971
2019-04-11T09:37:49
2019-04-11T09:37:49
180,760,999
0
0
null
null
null
null
UTF-8
Java
false
false
380
java
package com.masoomyf.masoom; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
1f06338674a90a40a375481bf9304b893f6bb5f8
3c59a06e4754207e8e35016359187f76c23e97db
/SFHealthScores/app/src/main/java/edu/sjsu/cs175/sfhealthscores/activities/BusinessActivity.java
4ac01457d48ac4565d59a8611db691564479e734
[ "MIT" ]
permissive
katsoohoo/SFHealthScores
f451e8279c1595f466d49eecb038c7db20d4440e
70cedcb3995863b8f7295d21d28a0014784ce69d
refs/heads/master
2021-04-30T17:07:06.816418
2017-01-27T20:03:22
2017-01-27T20:03:22
80,195,952
0
0
null
null
null
null
UTF-8
Java
false
false
6,120
java
package edu.sjsu.cs175.sfhealthscores.activities; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import java.util.HashMap; import java.util.List; import edu.sjsu.cs175.sfhealthscores.R; import edu.sjsu.cs175.sfhealthscores.adapters.InspectionCardAdapter; import edu.sjsu.cs175.sfhealthscores.helpers.Globals; import edu.sjsu.cs175.sfhealthscores.helpers.RecyclerItemClickListener; import edu.sjsu.cs175.sfhealthscores.models.InspectionHistory; import edu.sjsu.cs175.sfhealthscores.retrofit.RetrofitCallback; import edu.sjsu.cs175.sfhealthscores.retrofit.SFODQueries; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Business Activity shows business information and inspection history. */ public class BusinessActivity extends AppCompatActivity { private Context context; private LinearLayout headerLayout; private TextView scoreTextView; private TextView nameTextView; private TextView addressTextView; private TextView phoneNumberTextView; private RecyclerView recyclerView; private ProgressBar inspectionLoadingSpinner; private HashMap<String, Object> businessInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_business); if (getIntent().hasExtra("businessInfo")) { // Get data from intent businessInfo = (HashMap<String, Object>) getIntent().getSerializableExtra("businessInfo"); // Initialize views context = getBaseContext(); headerLayout = (LinearLayout) findViewById(R.id.business_header); scoreTextView = (TextView) findViewById(R.id.business_score); nameTextView = (TextView) findViewById(R.id.business_name); addressTextView = (TextView) findViewById(R.id.business_address); phoneNumberTextView = (TextView) findViewById(R.id.business_phone_number); recyclerView = (RecyclerView) findViewById(R.id.business_inspection_recycler_view); inspectionLoadingSpinner = (ProgressBar) findViewById(R.id.business_inspection_loading_spinner); // Fetch data fillBusinessInfo(); fetchInspectionHistory(); } else { Toast.makeText(context, "Failed to retrieve data", Toast.LENGTH_SHORT).show(); } } /** * Fill business info data. */ private void fillBusinessInfo() { Object score = businessInfo.get("inspectionScore"); Object name = businessInfo.get("businessName"); Object address = businessInfo.get("businessAddress"); Object city = businessInfo.get("businessCity"); Object state = businessInfo.get("businessState"); Object phoneNumber = businessInfo.get("businessPhoneNumber"); int scoreColor = Globals.getScoreColor(Integer.parseInt(score.toString())); headerLayout.setBackgroundColor(scoreColor); scoreTextView.setText((String) score); nameTextView.setText((String) name); addressTextView.setText(address + "\n" + city + ", " + state); phoneNumberTextView.setText((String) phoneNumber); } /** * Fetch inspection history from API call. */ private void fetchInspectionHistory() { showLoading(); // Call api with Retrofit Call<List<InspectionHistory>> apiCall = Globals.SFOD_SERVICE.inspectionHistory( SFODQueries.getInspectionHistory(businessInfo.get("businessId").toString())); Log.i("API", "Inspection History: " + apiCall.request()); // Receive results on asynchronous callback Callback callback = new RetrofitCallback<List<InspectionHistory>>() { @Override public void onResponse(Call<List<InspectionHistory>> call, Response<List<InspectionHistory>> response) { if (response.isSuccessful()) { setupRecyclerView(response.body()); } else { Toast.makeText(context, "API Response Failure", Toast.LENGTH_LONG).show(); } } }; apiCall.enqueue(callback); } /** * Setup recycler view with data. * * @param data */ private void setupRecyclerView(final List<InspectionHistory> data) { showInspections(); // set recycler view data recyclerView.setNestedScrollingEnabled(false); recyclerView.setHasFixedSize(true); recyclerView.setAdapter(new InspectionCardAdapter(data)); recyclerView.setLayoutManager(new LinearLayoutManager(context)); // add on item touch listener recyclerView.addOnItemTouchListener( new RecyclerItemClickListener(context, recyclerView, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { // pass selected inspection to next activity InspectionHistory selected = data.get(position); HashMap<String, Object> fieldMap = Globals.getInspectionHistoryData(selected); Intent intent = new Intent(context, InspectionActivity.class); intent.putExtra("inspectionInfo", fieldMap); startActivity(intent); } }) ); } private void showLoading() { inspectionLoadingSpinner.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.GONE); } private void showInspections() { inspectionLoadingSpinner.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); } }
d2078461be55de32910fe3a878098cb78142d332
34bf7ec972e390c7a248df3ef8c10cb12c3d5803
/src/main/java/com/seecen/springboot/aop/MyLog.java
76f398469b4925752580757c80997c2f1e137550
[]
no_license
zhangjiankun94/springboot1
8a3d25c4cd9193d0068bce8ddd42cba8a06b396f
14bdeafd613bb522d2c5f5e5d956686640dc82a8
refs/heads/master
2020-12-02T12:53:45.627184
2019-12-31T02:19:56
2019-12-31T02:19:56
231,011,339
0
0
null
null
null
null
UTF-8
Java
false
false
800
java
package com.seecen.springboot.aop; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author ZhangJiankun * @date 2019/12/13 11:37 * 描述:自定义注解 */ @Target({ElementType.METHOD}) //指定可以将注解加在什么地方 METHOD表示在方法上加注解(或类上,属性,参数,注解上。。。。) @Retention(RetentionPolicy.RUNTIME) //指定在运行时 public @interface MyLog { /* * 日志类型: 0 登录 1 新增 2 修改 3 删除 4 注销 5 推出登录 * */ String logType(); //定义方法,对应注解中的属性 /* * 操作描述:如删除用户/修改用户 * */ String connect(); //操作描述 }
fa80236cefee4c0ccc5c3f9de3c94d8e7a5d4e67
9f01a04b91e3bb987010330bb5a13a879b5d5c2f
/src/main/test/java/cn/com/codingce/MyTest.java
0bdd4483fcaf0f4eda654556c12a83831d2462d9
[ "MIT" ]
permissive
xzMhehe/bbs_codingce
031db39e9e876b639658d46e0892900db9b677d7
6d99aef35bec4fc30859a9bc2761c1c54587c3e7
refs/heads/master
2023-02-15T08:29:14.108693
2021-01-13T11:34:35
2021-01-13T11:34:35
304,346,086
0
0
null
null
null
null
UTF-8
Java
false
false
610
java
package java.cn.com.codingce; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class MyTest { @Test public void test() { // BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); // String admin = encoder.encode("admin"); // System.out.println(admin); // // System.out.println(new BCryptPasswordEncoder().encode("admin")); // System.out.println(ZeUtils.getUuid()); } }
bfd554e853c544174028ea2f936a513ad018a98f
7834f2d2f41e57255e8a25083807c9b4b52d3f55
/src/main/java/application/dao/romMapper/IngredientRowMapper.java
16a6c31c0157aa4a95f916ab0aa19b56f65d0891
[]
no_license
anastasiya28/emenu
e06dd249fab950c7620515fa09f09f4abfec4786
288d1d6146a3d211507e861f54c02cea220f658a
refs/heads/master
2021-01-20T00:41:47.741941
2017-04-23T22:11:43
2017-04-23T22:11:43
89,174,438
0
0
null
null
null
null
UTF-8
Java
false
false
1,147
java
package application.dao.romMapper; import application.model.Ingredient; import org.apache.log4j.Logger; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; import static application.dao.impls.IngredientDAOImpl.INGREDIENT_ID_COLUMN; import static application.dao.impls.IngredientDAOImpl.NAME_COLUMN; import static application.dao.impls.IngredientDAOImpl.TABLE_NAME; public class IngredientRowMapper implements RowMapper<Ingredient> { public static final Logger logger = Logger.getLogger(IngredientRowMapper.class); @Override public Ingredient mapRow(ResultSet resultSet, int rowNum) { Ingredient ingredient = new Ingredient(); try { ingredient.setId(resultSet.getInt(TABLE_NAME + "." + INGREDIENT_ID_COLUMN)); ingredient.setName(resultSet.getString(TABLE_NAME + "." + NAME_COLUMN)); } catch (SQLException e) { logger.trace("SQLException in the method: public Ingredient mapRow(ResultSet rs, int rowNum) {...} " + "of the class IngredientRowMapper", e); } return ingredient; } }
c4c92c9805d941b7fd2ef3a2260c64ce06b5b81f
614727fee510b262b41361bb30ad912fdc53b932
/app/src/main/java/org/pursuit/mealprep/MainActivity.java
f8299d3ad66714988455752a7f8c75109540a63c
[]
no_license
LolaAbudu/Lolitas_Kitchen
75374476f0dc26bf63698f3ffc48fd3327fe4889
719fbf5b0ec17f04ed39c86a722def2e261287b4
refs/heads/master
2020-05-01T12:12:20.148921
2019-04-24T17:11:41
2019-04-24T17:11:41
177,460,486
3
0
null
2019-04-24T17:11:42
2019-03-24T19:39:06
Java
UTF-8
Java
false
false
3,750
java
package org.pursuit.mealprep; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import org.pursuit.mealprep.fragments.AboutMeFragment; import org.pursuit.mealprep.fragments.DisplayAllMealsFragment; import org.pursuit.mealprep.fragments.SelectedMealFragment; import org.pursuit.mealprep.fragments.SplashFragment; import org.pursuit.mealprep.fragments.ViewPagerFragment; import org.pursuit.mealprep.model.Meal; import org.pursuit.mealprep.model.NutritionFacts; import org.pursuit.mealprep.model.Time; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements FragmentInteractionListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SplashFragment splashFragment = SplashFragment.newInstance(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.main_container, splashFragment) .commit(); } @Override public void toViewPagerFragment() { ViewPagerFragment viewPagerFragment = ViewPagerFragment.newInstance(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.main_container, viewPagerFragment) .commit(); } @Override public void toDisplayAllMealFragment(List<Meal> meals, List<String> userSelection) { DisplayAllMealsFragment displayAllMealsFragment = DisplayAllMealsFragment.newInstance(meals, userSelection); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.main_container, displayAllMealsFragment) .addToBackStack(null) .commit(); } @Override public void toSelectedMealFragment(String name, String image, String description, List<String> ingredients, List<String> direction, NutritionFacts nutritionalFacts, Time cookTime) { //TODO add to above later // ,ArrayList<NutritionFacts> nutritionalFacts, // ArrayList<Time> cookTime SelectedMealFragment selectedMealFragment = SelectedMealFragment.newInstance(name, image, description, ingredients, direction, nutritionalFacts, cookTime); //TODO add late ---, nutritionalFacts, cookTime FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.main_container, selectedMealFragment) .addToBackStack(null) .commit(); } @Override public void toAboutMe() { AboutMeFragment aboutMeFragment = AboutMeFragment.newInstance(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.main_container, aboutMeFragment) .addToBackStack(null) .commit(); } }
5ede6bc99a3850d1a79c5bd8c47b08520a0b6e84
32bb7c996e02691cea319b86c5a74bb84b7aee12
/src/main/java/com/hbhb/cw/report/web/vo/PropertyVO.java
7dc7389cd34618ff37bd5e3d07f796d0d224af0f
[]
no_license
hbhb-devloper/report-manage
a60dd6b01983e831174d7f94487426c59471fd60
6107e72c703942999040a9113f1db4801c57f635
refs/heads/master
2023-03-18T02:38:59.421663
2021-03-20T12:05:42
2021-03-20T12:05:42
349,712,531
0
0
null
null
null
null
UTF-8
Java
false
false
1,392
java
package com.hbhb.cw.report.web.vo; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @author wangxiaogang */ @Data @AllArgsConstructor @NoArgsConstructor @Builder public class PropertyVO implements Serializable { private static final long serialVersionUID = 2129738745415922422L; private Long id; @Schema(description = "报表名称id") private Long categoryId; @Schema(description = "编报范围(0-分公司、1-营业厅)") private Integer scope; @Schema(description = "编报范围(0-分公司、1-营业厅)") private String scopeName; @Schema(description = "周期(0-年、1-季、2-月、3-旬、4-日)") private Integer period; @Schema(description = "周期(0-年、1-季、2-月、3-旬、4-日)") private String periodName; @Schema(description = "流程类型id") private Long flowTypeId; @Schema(description = "流程类型名称") private String flowTypeName; @Schema(description = "流程id") private Long flowId; @Schema(description = "流程名称") private String flowName; @Schema(description = "开始时间") private String startTime; @Schema(description = "结束时间") private String endTime; }
5868f68f5827245e8d1a46c95e8ed28e0ef89ea3
bf2966abae57885c29e70852243a22abc8ba8eb0
/aws-java-sdk-appconfig/src/main/java/com/amazonaws/services/appconfig/model/transform/TagResourceRequestProtocolMarshaller.java
e0cb0b268e30a1652c981e77cfb6c0e826b3bfae
[ "Apache-2.0" ]
permissive
kmbotts/aws-sdk-java
ae20b3244131d52b9687eb026b9c620da8b49935
388f6427e00fb1c2f211abda5bad3a75d29eef62
refs/heads/master
2021-12-23T14:39:26.369661
2021-07-26T20:09:07
2021-07-26T20:09:07
246,296,939
0
0
Apache-2.0
2020-03-10T12:37:34
2020-03-10T12:37:33
null
UTF-8
Java
false
false
2,600
java
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.appconfig.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.appconfig.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * TagResourceRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class TagResourceRequestProtocolMarshaller implements Marshaller<Request<TagResourceRequest>, TagResourceRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/tags/{ResourceArn}") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).serviceName("AmazonAppConfig").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public TagResourceRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<TagResourceRequest> marshall(TagResourceRequest tagResourceRequest) { if (tagResourceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<TagResourceRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, tagResourceRequest); protocolMarshaller.startMarshalling(); TagResourceRequestMarshaller.getInstance().marshall(tagResourceRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
[ "" ]
52152dce9f25ac7b8f6513fa113fdfae90e1c1f6
d181858c94fa1487727d2acd9ec1508ca195a8c1
/app/src/main/java/com/google/zxing/client/android/Contents.java
23534d6ea2c2496a48a4fc00ef2191229d1811ab
[]
no_license
HellCat24/ZXingAndroidLib
d933501e0bba2ab12f0aa366abb20a46129568f1
7371f0d4b98cf15fda13973908d6f9f23f594859
refs/heads/master
2021-01-21T23:20:38.974665
2015-05-08T15:24:22
2015-05-08T15:24:22
35,280,015
0
0
null
null
null
null
UTF-8
Java
false
false
3,161
java
/* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.client.android; import android.provider.Contacts; /** * The set of constants to use when sending Barcode Scanner an Intent which requests a barcode * to be encoded. * * @author [email protected] (Daniel Switkin) */ public final class Contents { private Contents() { } public static final class Type { /** * Plain text. Use Intent.putExtra(DATA, string). This can be used for URLs too, but string * must include "http://" or "https://". */ public static final String TEXT = "TEXT_TYPE"; /** * An email type. Use Intent.putExtra(DATA, string) where string is the email address. */ public static final String EMAIL = "EMAIL_TYPE"; /** * Use Intent.putExtra(DATA, string) where string is the phone number to call. */ public static final String PHONE = "PHONE_TYPE"; /** * An SMS type. Use Intent.putExtra(DATA, string) where string is the number to SMS. */ public static final String SMS = "SMS_TYPE"; /** * A contact. Send a request to encode it as follows: * <p/> * import android.provider.Contacts; * <p/> * Intent intent = new Intent(Intents.Encode.ACTION); * intent.putExtra(Intents.Encode.TYPE, CONTACT); * Bundle bundle = new Bundle(); * bundle.putString(Contacts.Intents.Insert.NAME, "Jenny"); * bundle.putString(Contacts.Intents.Insert.PHONE, "8675309"); * bundle.putString(Contacts.Intents.Insert.EMAIL, "[email protected]"); * bundle.putString(Contacts.Intents.Insert.POSTAL, "123 Fake St. San Francisco, CA 94102"); * intent.putExtra(Intents.Encode.DATA, bundle); */ public static final String CONTACT = "CONTACT_TYPE"; /** * A geographic location. Use as follows: * Bundle bundle = new Bundle(); * bundle.putFloat("LAT", latitude); * bundle.putFloat("LONG", longitude); * intent.putExtra(Intents.Encode.DATA, bundle); */ public static final String LOCATION = "LOCATION_TYPE"; private Type() { } } /** * When using Type.CONTACT, these arrays provide the keys for adding or retrieving multiple * phone numbers and addresses. */ public static final String[] PHONE_KEYS = { Contacts.Intents.Insert.PHONE, Contacts.Intents.Insert.SECONDARY_PHONE, Contacts.Intents.Insert.TERTIARY_PHONE }; public static final String[] EMAIL_KEYS = { Contacts.Intents.Insert.EMAIL, Contacts.Intents.Insert.SECONDARY_EMAIL, Contacts.Intents.Insert.TERTIARY_EMAIL }; }
408d2fa325e4058e764a2df12f697ef4537857e2
1ee5701c762fc49c89d6a020cc2c41e3dad1a433
/Polymorphism/src/calculator/Main.java
bb556e406f879def36911cad93ce94ac28ccfeb3
[]
no_license
kaloyanminchev/Java-OOP
c562a250df38f0cc1f89bc5254ac246e3d8255c5
0652cf308cc465f6939a2499b6c6a079610dd1a8
refs/heads/master
2020-12-13T07:07:14.850073
2020-01-16T15:41:48
2020-01-16T15:41:48
234,342,575
0
0
null
2020-10-13T18:53:55
2020-01-16T14:50:11
Java
UTF-8
Java
false
false
607
java
package calculator; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); CalculationEngine engine = new CalculationEngine(); InputInterpreter interpreter = Extensions.buildInterpreter(engine); String[] tokens = scanner.nextLine().split("\\s+"); for (String token : tokens) { if(token.equals("end")){ break; } interpreter.interpret(token); } System.out.println(engine.getCurrentResult()); } }
39ac179fee2e376685408322deb84e6b33ba0d2e
77b40a4e7014a8e4b9385ef25a015aea89a6d637
/rpcserver/src/test/java/com/pxy/rpcserver/rpc/MainControllerTests.java
f4426fc7d4942d4515482d3106f803d3dbcf2acf
[]
no_license
buptpxy/rpcByHttp
76156398a03936f7b50f5de562a7529a1ffdbda5
33e36205a41efb4a2048e7a137733041c8257370
refs/heads/master
2022-06-25T19:37:57.692884
2020-02-29T10:19:04
2020-02-29T10:19:04
243,247,085
0
1
null
2022-06-17T02:57:26
2020-02-26T11:32:04
Java
UTF-8
Java
false
false
712
java
package com.pxy.rpcserver.rpc; import com.alibaba.fastjson.JSON; import com.pxy.rpcserver.entity.User; import com.pxy.rpcserver.service.UserServiceImpl; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class MainControllerTests { UserServiceImpl userServiceImpl = new UserServiceImpl(); @Autowired MainController mainController; @Test public void testGetResult() { } }
0aa88c735239f9420ff1e6a8ef0ef2276cf7ec0b
9ae07bb210092dc7bc371c520ebbce66831d05ff
/src/main/java/io/kamax/mxisd/config/threepid/medium/PhoneConfig.java
05d9ea6a74f586f9529315cd3d414352b2629f49
[ "AGPL-3.0-only", "Apache-2.0" ]
permissive
privatefoundation/pqvid
994e0f08fd26a78a3ae272969e351bbfbcea2f11
303eca032a99dcca9aed399b29f0df870bd33bf6
refs/heads/master
2023-06-24T09:02:47.686746
2021-07-25T06:42:35
2021-07-25T06:42:35
464,129,268
1
0
Apache-2.0
2022-02-27T12:23:54
2022-02-27T12:23:53
null
UTF-8
Java
false
false
1,160
java
/* * mxisd - Matrix Identity Server Daemon * Copyright (C) 2017 Kamax Sarl * * https://www.kamax.io/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.kamax.mxisd.config.threepid.medium; import io.kamax.mxisd.threepid.connector.phone.PhoneSmsTwilioConnector; import io.kamax.mxisd.threepid.generator.phone.SmsNotificationGenerator; public class PhoneConfig extends MediumConfig { public PhoneConfig() { setConnector(PhoneSmsTwilioConnector.ID); setGenerator(SmsNotificationGenerator.ID); } }
899e504296e98454ccf25e722c9c492c917cf542
2c5328519c9fea8897a0ce98dc6da39923bc03f2
/src/testgen/module/testsrcfilesgen/SrcFileGenerator.java
b40c68160b48ff86c1a72d4ff952c87ca77ce1b2
[]
no_license
suriyadev/testgen
fbbff2fbaef235df3645b9df79e6197e96d33cf3
f6eccd3af7e78ea42823f9ea8e76d41955f64cdd
refs/heads/master
2023-01-02T16:18:07.527966
2020-11-01T20:22:21
2020-11-01T20:22:21
309,180,571
0
0
null
null
null
null
UTF-8
Java
false
false
233
java
package testgen.module.testsrcfilesgen; import java.util.List; import testgen.module.testclasscontentgen.TestFileData; public interface SrcFileGenerator { public boolean generateTestSrcFiles(List<TestFileData> testClassData); }
e8154de067545d1052d00982f4589bd39076becd
f8786ef49ca6b6faa3e1272c4d8ff00d805fbf03
/matrix-sdk/src/main/java/org/matrix/androidsdk/rest/model/AddThreePidsParams.java
d9c54c847595616cd8f9f550418dac8893955ac8
[ "Apache-2.0" ]
permissive
telred-llc/clearkeep-android
4f81c97a202fde834aed67825535c467b8e4ca9b
2d20e94e9711b51aee89fa569efd61449cc7e9c3
refs/heads/develop
2022-03-31T19:13:53.496758
2020-01-22T07:53:11
2020-01-22T07:53:11
194,596,139
2
0
Apache-2.0
2020-01-22T07:53:12
2019-07-01T03:52:18
Java
UTF-8
Java
false
false
920
java
/* * Copyright 2019 The Matrix.org Foundation C.I.C. * * 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.matrix.androidsdk.rest.model; import org.matrix.androidsdk.rest.model.login.AuthParams; public class AddThreePidsParams { // the 3 pids sid public String sid; // a secret key public String client_secret; // current account information public AuthParams auth; }
59a524eca397abffc9e57ff2f404588b66fd3480
3d87541fb78f0369b8084eddcaa066f71fe2342b
/Week 3/Lab 3/Shape(no P)/src/Rectangle.java
dfbfc4f782ce1c64f9df1642b18975adab9e31d5
[]
no_license
LiChingCheng/JAC444
1935309aaeb68fd297c15bf463b5368954cbe3a4
3458fbfa009f5cce3154c801bfae8ef4510d2a15
refs/heads/master
2023-01-06T02:07:27.433585
2020-11-06T20:47:44
2020-11-06T20:47:44
310,694,114
0
0
null
null
null
null
UTF-8
Java
false
false
338
java
public class Rectangle extends Parallelogram { public Rectangle(double length, double width) throws IllegalArgumentException{ super(length, width); } public String toString() { return String.format("Rectangle {w=" + super.getWidth() + ", h=" + super.getWidth() + "} perimeter = " + getPerimeter()); } }
9b74773a1aa45da183f558d4b252ecb691f54ca5
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
/data_defect4j/preprossed_method_corpus/Math/45/org/apache/commons/math/fraction/BigFractionField_readResolve_78.java
a38d9cf8081f03d0a42e226b331f2aee2daa0a3f
[]
no_license
hvdthong/NetML
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
9bb103da21327912e5a29cbf9be9ff4d058731a5
refs/heads/master
2021-06-30T15:03:52.618255
2020-10-07T01:58:48
2020-10-07T01:58:48
150,383,588
1
1
null
2018-09-26T07:08:45
2018-09-26T07:08:44
null
UTF-8
Java
false
false
362
java
org apach common math fraction represent fraction number overflow field singleton fraction version big fraction field bigfractionfield field big fraction bigfract serializ handl deseri singleton singleton instanc object read resolv readresolv singleton instanc lazi holder lazyhold instanc
5a8ba6d5c0c5d350d52074f4eb59af8f5a79c841
bd2139703c556050403c10857bde66f688cd9ee6
/jmc/58/webrev.01/core/org.openjdk.jmc.flightrecorder.rules.jdk/src/main/java/org/openjdk/jmc/flightrecorder/rules/jdk/latency/MethodProfilingRule.java
1608e763d352adba7c5d30ee3435d21b0482bb8c
[]
no_license
isabella232/cr-archive
d03427e6fbc708403dd5882d36371e1b660ec1ac
8a3c9ddcfacb32d1a65d7ca084921478362ec2d1
refs/heads/master
2023-02-01T17:33:44.383410
2020-12-17T13:47:48
2020-12-17T13:47:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
25,797
java
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The contents of this file are subject to the terms of either the Universal Permissive License * v 1.0 as shown at http://oss.oracle.com/licenses/upl * * or the following license: * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openjdk.jmc.flightrecorder.rules.jdk.latency; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.RunnableFuture; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.openjdk.jmc.common.IDisplayable; import org.openjdk.jmc.common.IMCFrame; import org.openjdk.jmc.common.IMCMethod; import org.openjdk.jmc.common.IMCPackage; import org.openjdk.jmc.common.IMCStackTrace; import org.openjdk.jmc.common.item.Aggregators; import org.openjdk.jmc.common.item.Aggregators.CountConsumer; import org.openjdk.jmc.common.item.GroupingAggregator; import org.openjdk.jmc.common.item.GroupingAggregator.GroupEntry; import org.openjdk.jmc.common.item.IAggregator; import org.openjdk.jmc.common.item.IItem; import org.openjdk.jmc.common.item.IItemCollection; import org.openjdk.jmc.common.item.IItemFilter; import org.openjdk.jmc.common.item.IItemIterable; import org.openjdk.jmc.common.item.IMemberAccessor; import org.openjdk.jmc.common.item.IType; import org.openjdk.jmc.common.item.ItemFilters; import org.openjdk.jmc.common.unit.IQuantity; import org.openjdk.jmc.common.unit.IRange; import org.openjdk.jmc.common.unit.QuantityConversionException; import org.openjdk.jmc.common.unit.QuantityRange; import org.openjdk.jmc.common.unit.UnitLookup; import org.openjdk.jmc.common.util.FormatToolkit; import org.openjdk.jmc.common.util.IPreferenceValueProvider; import org.openjdk.jmc.common.util.MCStackTrace; import org.openjdk.jmc.common.util.Pair; import org.openjdk.jmc.common.util.TypedPreference; import org.openjdk.jmc.flightrecorder.JfrAttributes; import org.openjdk.jmc.flightrecorder.jdk.JdkAttributes; import org.openjdk.jmc.flightrecorder.jdk.JdkFilters; import org.openjdk.jmc.flightrecorder.jdk.JdkTypeIDs; import org.openjdk.jmc.flightrecorder.rules.IRule; import org.openjdk.jmc.flightrecorder.rules.Result; import org.openjdk.jmc.flightrecorder.rules.jdk.dataproviders.MethodProfilingDataProvider; import org.openjdk.jmc.flightrecorder.rules.jdk.messages.internal.Messages; import org.openjdk.jmc.flightrecorder.rules.util.JfrRuleTopics; import org.openjdk.jmc.flightrecorder.rules.util.RulesToolkit; import org.openjdk.jmc.flightrecorder.rules.util.RulesToolkit.EventAvailability; import org.openjdk.jmc.flightrecorder.rules.util.SlidingWindowToolkit; import org.openjdk.jmc.flightrecorder.rules.util.SlidingWindowToolkit.IUnorderedWindowVisitor; import org.owasp.encoder.Encode; /** * Rule that calculates the top method balance in a sliding window throughout the recording with a * relevance calculated by the ratio of samples to maximum samples for that period. */ public class MethodProfilingRule implements IRule { /** * Constant value of the maximum number of samples the JVM attempts per sampling period. */ private static final double SAMPLES_PER_PERIOD = 5; /** * Constant value of the maximum number of stack frames to display for the hottest path. */ private static final int MAX_STACK_DEPTH = 10; /** * A simple class for storing execution sample period settings, allowing the sliding window to * get the correct samples for each time slice. */ private static class PeriodRangeMap { private List<Pair<IQuantity, IQuantity>> settingPairs = new ArrayList<>(); void addSetting(IQuantity settingTime, IQuantity setting) { settingPairs.add(new Pair<>(settingTime, setting)); } /** * Gets the execution sample period that is in effect for the given timestamp. * * @param timestamp * the timestamp for which to find the given period setting * @return an IQuantity representing the period setting for the period given */ IQuantity getSetting(IQuantity timestamp) { for (Pair<IQuantity, IQuantity> settingPair : settingPairs) { boolean isAfterOrAtSettingTime = settingPair.left.compareTo(timestamp) <= 0; if (isAfterOrAtSettingTime) { return settingPair.right; } } return null; // before first period setting event in recording, i.e. we should ignore any profiling events that get this result } void sort() { Collections.sort(settingPairs, new Comparator<Pair<IQuantity, IQuantity>>() { @Override public int compare(Pair<IQuantity, IQuantity> p1, Pair<IQuantity, IQuantity> p2) { return p1.left.compareTo(p2.left); // sorting according to time of setting event } }); } } private static class MethodProfilingWindowResult { IMCMethod method; IMCStackTrace path; IQuantity ratioOfAllPossibleSamples; IQuantity ratioOfActualSamples; IRange<IQuantity> window; public MethodProfilingWindowResult(IMCMethod method, IMCStackTrace path, IQuantity ratio, IQuantity actualRatio, IRange<IQuantity> window) { this.method = method; this.path = path; this.ratioOfAllPossibleSamples = ratio; this.ratioOfActualSamples = actualRatio; this.window = window; } @Override public String toString() { return FormatToolkit.getHumanReadable(method, false, false, true, true, true, false) + " (" //$NON-NLS-1$ + ratioOfActualSamples.displayUsing(IDisplayable.AUTO) + " of samples) " //$NON-NLS-1$ + window.displayUsing(IDisplayable.AUTO); } } private static final String RESULT_ID = "MethodProfiling"; //$NON-NLS-1$ public static final TypedPreference<IQuantity> WINDOW_SIZE = new TypedPreference<>( "method.profiling.evaluation.window.size", //$NON-NLS-1$ Messages.getString(Messages.MethodProfilingRule_WINDOW_SIZE), Messages.getString(Messages.MethodProfilingRule_WINDOW_SIZE_DESC), UnitLookup.TIMESPAN, UnitLookup.SECOND.quantity(30)); public static final TypedPreference<String> EXCLUDED_PACKAGE_REGEXP = new TypedPreference<>( "method.profiling.evaluation.excluded.package", //$NON-NLS-1$ Messages.getString(Messages.MethodProfilingRule_EXCLUDED_PACKAGES), Messages.getString(Messages.MethodProfilingRule_EXCLUDED_PACKAGES_DESC), UnitLookup.PLAIN_TEXT.getPersister(), "java\\.(lang|util)"); //$NON-NLS-1$ private static final List<TypedPreference<?>> CONFIG_ATTRIBUTES = Arrays.<TypedPreference<?>> asList(WINDOW_SIZE, EXCLUDED_PACKAGE_REGEXP); /** * Private Callable implementation specifically used to avoid storing the FutureTask as a field. */ private class MethodProfilingCallable implements Callable<Result> { private FutureTask<Result> evaluationTask = null; private IItemCollection items; private IPreferenceValueProvider valueProvider; private MethodProfilingCallable(IItemCollection items, IPreferenceValueProvider valueProvider) { this.items = items; this.valueProvider = valueProvider; } @Override public Result call() throws Exception { return getResult(items, valueProvider, evaluationTask); } void setTask(FutureTask<Result> task) { evaluationTask = task; } } @Override public RunnableFuture<Result> evaluate(final IItemCollection items, final IPreferenceValueProvider valueProvider) { MethodProfilingCallable callable = new MethodProfilingCallable(items, valueProvider); FutureTask<Result> evaluationTask = new FutureTask<>(callable); callable.setTask(evaluationTask); return evaluationTask; } private Result getResult( IItemCollection items, IPreferenceValueProvider valueProvider, FutureTask<Result> evaluationTask) { EventAvailability eventAvailability = RulesToolkit.getEventAvailability(items, JdkTypeIDs.EXECUTION_SAMPLE, JdkTypeIDs.RECORDING_SETTING); if (eventAvailability != EventAvailability.AVAILABLE) { return RulesToolkit.getEventAvailabilityResult(this, items, eventAvailability, JdkTypeIDs.EXECUTION_SAMPLE, JdkTypeIDs.RECORDING_SETTING); } PeriodRangeMap settings = new PeriodRangeMap(); IItemFilter settingsFilter = RulesToolkit.getSettingsFilter(RulesToolkit.REC_SETTING_NAME_PERIOD, JdkTypeIDs.EXECUTION_SAMPLE); populateSettingsMap(items.apply(settingsFilter), settings); IQuantity windowSize = valueProvider.getPreferenceValue(WINDOW_SIZE); IQuantity slideSize = UnitLookup.SECOND.quantity(windowSize.ratioTo(UnitLookup.SECOND.quantity(2))); String excludedPattern = valueProvider.getPreferenceValue(EXCLUDED_PACKAGE_REGEXP); Pattern excludes; try { excludes = Pattern.compile(excludedPattern); } catch (Exception e) { // Make sure we don't blow up on an invalid pattern. excludes = Pattern.compile(""); //$NON-NLS-1$ } List<MethodProfilingWindowResult> windowResults = new ArrayList<>(); IUnorderedWindowVisitor visitor = createWindowVisitor(settings, settingsFilter, windowSize, windowResults, evaluationTask, excludes); SlidingWindowToolkit.slidingWindowUnordered(visitor, items, windowSize, slideSize); // If a window visitor over a non empty quantity of events is guaranteed to always generate at minimum one raw score, this can be removed. if (windowResults.isEmpty()) { return RulesToolkit.getNotApplicableResult(this, Messages.getString(Messages.HotMethodsRuleFactory_NOT_ENOUGH_SAMPLES)); } Pair<MethodProfilingWindowResult, Map<IMCStackTrace, MethodProfilingWindowResult>> interestingMethods = getInterestingMethods( windowResults); Map<IMCStackTrace, MethodProfilingWindowResult> percentByMethod = interestingMethods.right; MethodProfilingWindowResult mostInterestingResult = interestingMethods.left; if (mostInterestingResult == null) { // Couldn't find any interesting methods return new Result(this, 0, Messages.getString(Messages.HotMethodsRuleFactory_TEXT_OK)); } double mappedScore = performSigmoidMap( mostInterestingResult.ratioOfAllPossibleSamples.doubleValueIn(UnitLookup.PERCENT_UNITY)); Result result = null; if (mappedScore < 25) { result = new Result(this, mappedScore, Messages.getString(Messages.HotMethodsRuleFactory_TEXT_OK)); } else { String shortDescription = MessageFormat.format(Messages.getString(Messages.HotMethodsRuleFactory_TEXT_INFO), FormatToolkit.getHumanReadable(mostInterestingResult.method, false, false, true, false, true, false), mostInterestingResult.ratioOfAllPossibleSamples.displayUsing(IDisplayable.AUTO), windowSize.displayUsing(IDisplayable.AUTO), mostInterestingResult.ratioOfActualSamples.displayUsing(IDisplayable.AUTO)); String formattedPath = "<ul>" + //$NON-NLS-1$ FormatToolkit.getHumanReadable(mostInterestingResult.path, false, false, true, true, true, false, MAX_STACK_DEPTH, null, "<li>", //$NON-NLS-1$ "</li>" //$NON-NLS-1$ ) + "</ul>"; //$NON-NLS-1$ String longDescription = MessageFormat.format( Messages.getString(Messages.HotMethodsRuleFactory_TEXT_INFO_LONG), buildResultList(percentByMethod), formattedPath); result = new Result(this, mappedScore, shortDescription, shortDescription + "<p>" + longDescription); //$NON-NLS-1$ } return result; } private String buildResultList(Map<IMCStackTrace, MethodProfilingWindowResult> percentByMethod) { StringBuilder longList = new StringBuilder(); longList.append("<ul>"); //$NON-NLS-1$ for (Entry<IMCStackTrace, MethodProfilingWindowResult> entry : percentByMethod.entrySet()) { longList.append("<li>"); //$NON-NLS-1$ longList.append(Encode.forHtml(entry.getValue().toString())); longList.append("</li>"); //$NON-NLS-1$ } longList.append("</ul>"); //$NON-NLS-1$ return longList.toString(); } private Pair<MethodProfilingWindowResult, Map<IMCStackTrace, MethodProfilingWindowResult>> getInterestingMethods( List<MethodProfilingWindowResult> windowResults) { Map<IMCStackTrace, MethodProfilingWindowResult> percentByMethod = new HashMap<>(); IQuantity maxRawScore = UnitLookup.PERCENT_UNITY.quantity(0); MethodProfilingWindowResult mostInterestingResult = null; for (MethodProfilingWindowResult result : windowResults) { if (result != null) { if (result.ratioOfAllPossibleSamples.compareTo(maxRawScore) > 0) { mostInterestingResult = result; maxRawScore = result.ratioOfAllPossibleSamples; } if (result.path != null && performSigmoidMap( result.ratioOfAllPossibleSamples.doubleValueIn(UnitLookup.PERCENT_UNITY)) >= 25) { MethodProfilingWindowResult r = percentByMethod.get(result.path); if (r == null || result.ratioOfAllPossibleSamples.compareTo(r.ratioOfAllPossibleSamples) > 0) { percentByMethod.put(result.path, result); } } } } return new Pair<>(mostInterestingResult, percentByMethod); } private double performSigmoidMap(double input) { return RulesToolkit.mapSigmoid(input, 0, 100, 150, 0.03333, 7); } /** * Creates an IUnorderedWindowVisitor that is called on each slice in the recording and * generates the scores for each slice and places them in the rawScores list. The given * parameters that are also given to the slidingWindowUnordered call must be the same as in this * call. * * @param settings * the settings map with all the times the execution sample event has a change of * periodicity * @param settingsFilter * the filter used to select the recording setting for the execution sample event * @param windowSize * the size of the sliding window * @param rawScores * the list of raw scores that will be populated by this visitor * @return an IUnorderedWindowVisitor implementation that will populate the rawScores list with * raw score values */ private IUnorderedWindowVisitor createWindowVisitor( final PeriodRangeMap settings, final IItemFilter settingsFilter, final IQuantity windowSize, final List<MethodProfilingWindowResult> rawScores, final FutureTask<Result> evaluationTask, final Pattern excludes) { return new IUnorderedWindowVisitor() { @Override public void visitWindow(IItemCollection items, IQuantity startTime, IQuantity endTime) { IRange<IQuantity> windowRange = QuantityRange.createWithEnd(startTime, endTime); if (RulesToolkit.getSettingMaxPeriod(items, JdkTypeIDs.EXECUTION_SAMPLE) == null) { Pair<Pair<IQuantity, IQuantity>, IMCStackTrace> resultPair = performCalculation(items, settings.getSetting(startTime)); if (resultPair != null) { rawScores.add(new MethodProfilingWindowResult(resultPair.right.getFrames().get(0).getMethod(), resultPair.right, resultPair.left.left, resultPair.left.right, windowRange)); } } else { Set<IQuantity> settingTimes = items.apply(settingsFilter) .getAggregate(Aggregators.distinct(JfrAttributes.START_TIME)); IQuantity start = startTime; List<Pair<Pair<IQuantity, IQuantity>, IMCStackTrace>> scores = new ArrayList<>(settingTimes.size()); for (IQuantity settingTime : settingTimes) { IItemFilter window = ItemFilters.interval(JfrAttributes.END_TIME, start, true, settingTime, true); scores.add(performCalculation(items.apply(window), settings.getSetting(start))); start = settingTime; } Map<IMCStackTrace, Pair<IQuantity, IQuantity>> scoresByMethod = new HashMap<>(); for (Pair<Pair<IQuantity, IQuantity>, IMCStackTrace> score : scores) { if (score != null) { if (scoresByMethod.get(score.right) == null) { scoresByMethod.put(score.right, score.left); } else { scoresByMethod.put(score.right, new Pair<>(score.left.left.add(scoresByMethod.get(score.right).left), score.left.right.add(scoresByMethod.get(score.right).right))); } } } IQuantity sumScore = UnitLookup.PERCENT_UNITY.quantity(0); IQuantity actualScore = UnitLookup.PERCENT_UNITY.quantity(0); IMCStackTrace hottestPath = null; for (Entry<IMCStackTrace, Pair<IQuantity, IQuantity>> entry : scoresByMethod.entrySet()) { if (entry.getValue().left.compareTo(sumScore) > 0) { hottestPath = entry.getKey(); actualScore = entry.getValue().right; sumScore = sumScore.add(entry.getValue().left); } } IQuantity averageOfAllPossibleSamples = sumScore.multiply(1d / scores.size()); IMCMethod hottestMethod = (hottestPath == null ? null : hottestPath.getFrames().get(0).getMethod()); rawScores.add(new MethodProfilingWindowResult(hottestMethod, hottestPath, averageOfAllPossibleSamples, actualScore, windowRange)); } } @Override public boolean shouldContinue() { return evaluationTask != null && !evaluationTask.isCancelled(); } /** * Performs the actual calculation of the score for the given period of the recording. * * @param items * the items to base the score on * @param period * the periodicity to base the relevancy calculation on * @return a double value in the interval [0,1] with 1 being a system in completely * saturated load with only one method called */ private Pair<Pair<IQuantity, IQuantity>, IMCStackTrace> performCalculation( IItemCollection items, IQuantity period) { IItemCollection filteredItems = items.apply(JdkFilters.EXECUTION_SAMPLE); final IMCMethod[] maxMethod = new IMCMethod[1]; final IMCStackTrace[] maxPath = new IMCStackTrace[1]; // Using this GroupingAggregator because it's the only way to extract the keys from the aggregation along with values IAggregator<IQuantity, ?> aggregator = GroupingAggregator.build("", "", //$NON-NLS-1$ //$NON-NLS-2$ MethodProfilingDataProvider.PATH_ACCESSOR_FACTORY, Aggregators.count(), new GroupingAggregator.IGroupsFinisher<IQuantity, IMCStackTrace, CountConsumer>() { @Override public IType<IQuantity> getValueType() { return UnitLookup.NUMBER; } @Override public IQuantity getValue( Iterable<? extends GroupEntry<IMCStackTrace, CountConsumer>> groupEntries) { HashMap<IMCMethod, IQuantity> map = new HashMap<>(); HashMap<IMCMethod, IMCStackTrace> pathMap = new HashMap<>(); int total = 0; // When we group by stack trace we can run into situations where the top frames are otherwise the same // for our purposes (finding the hottest method), but they differ by BCI, throwing off the count. // so we should collect further on the method for the top frame. for (GroupEntry<IMCStackTrace, CountConsumer> group : groupEntries) { IMCStackTrace trace = processPath(group.getKey()); total += group.getConsumer().getCount(); if (!trace.getFrames().isEmpty()) { IMCMethod topFrameMethod = trace.getFrames().get(0).getMethod(); if (map.get(topFrameMethod) == null) { map.put(topFrameMethod, UnitLookup.NUMBER_UNITY.quantity(group.getConsumer().getCount())); pathMap.put(topFrameMethod, trace); } else { IQuantity old = map.get(topFrameMethod); map.put(topFrameMethod, old.add( UnitLookup.NUMBER_UNITY.quantity(group.getConsumer().getCount()))); } } } if (!pathMap.isEmpty() && !map.isEmpty()) { Entry<IMCMethod, IQuantity> topEntry = Collections.max(map.entrySet(), new Comparator<Entry<IMCMethod, IQuantity>>() { @Override public int compare( Entry<IMCMethod, IQuantity> arg0, Entry<IMCMethod, IQuantity> arg1) { return arg0.getValue().compareTo(arg1.getValue()); } }); maxPath[0] = pathMap.get(topEntry.getKey()); maxMethod[0] = topEntry.getKey(); return topEntry.getValue().multiply(1d / total); } return UnitLookup.NUMBER_UNITY.quantity(0); } private IMCStackTrace processPath(IMCStackTrace path) { List<IMCFrame> frames = new ArrayList<>(path.getFrames()); List<IMCFrame> framesToDrop = new ArrayList<IMCFrame>(); // Drop any frames that match the excluded pattern, thereby treating the first non-matching frame that we encounter as the hot one. for (IMCFrame frame : frames) { IMCPackage p = frame.getMethod().getType().getPackage(); // Under some circumstances p.getName() will return a raw null, we need to handle this case. Matcher m = excludes.matcher(p.getName() == null ? "" : p.getName()); //$NON-NLS-1$ if (m.matches()) { framesToDrop.add(frame); } else { break; } } frames.removeAll(framesToDrop); return new MCStackTrace(frames, path.getTruncationState()); } }); IQuantity maxRatio = filteredItems.getAggregate(aggregator); Pair<Pair<IQuantity, IQuantity>, IMCStackTrace> result = null; if (maxMethod[0] != null && maxRatio != null && period != null) { // ignoring if there are no samples or if we don't yet know the periodicity double periodsPerSecond = 1 / period.doubleValueIn(UnitLookup.SECOND); double maxSamplesPerSecond = SAMPLES_PER_PERIOD * periodsPerSecond; double samplesInPeriod = items .getAggregate(Aggregators.count(ItemFilters.type(JdkTypeIDs.EXECUTION_SAMPLE))) .doubleValueIn(UnitLookup.NUMBER_UNITY); double maxSamplesInPeriod = maxSamplesPerSecond * windowSize.doubleValueIn(UnitLookup.SECOND); double relevancy = samplesInPeriod / maxSamplesInPeriod; double highestRatioOfSamples = maxRatio.doubleValueIn(UnitLookup.NUMBER_UNITY); IQuantity percentOfActualSamples = UnitLookup.PERCENT_UNITY.quantity(highestRatioOfSamples); IQuantity percentOfAllPossibleSamples = UnitLookup.PERCENT_UNITY .quantity(highestRatioOfSamples * relevancy); result = new Pair<>(new Pair<>(percentOfAllPossibleSamples, percentOfActualSamples), maxPath[0]); } return result; } }; } /** * Populates the settings map with all the period settings for the execution sample event found * in this recording. * * @param items * the items to search for execution sample period events * @param settings * the map to populate with the events */ private void populateSettingsMap(IItemCollection items, final PeriodRangeMap settings) { Iterator<IItemIterable> itemIterableIterator = items.iterator(); while (itemIterableIterator.hasNext()) { IItemIterable itemIterable = itemIterableIterator.next(); IMemberAccessor<IQuantity, IItem> startTimeAccessor = JfrAttributes.START_TIME .getAccessor(itemIterable.getType()); IMemberAccessor<String, IItem> settingValueAccessor = JdkAttributes.REC_SETTING_VALUE .getAccessor(itemIterable.getType()); Iterator<IItem> itemIterator = itemIterable.iterator(); while (itemIterator.hasNext()) { IItem item = itemIterator.next(); settings.addSetting(startTimeAccessor.getMember(item), getValueQuantity(settingValueAccessor.getMember(item))); } } settings.sort(); } /** * Used to parse the value of a Recording Setting Period attribute * * @param settingValue * the value to parse * @return an IQuantity representation of the passed String object */ private IQuantity getValueQuantity(String settingValue) { try { if (RulesToolkit.REC_SETTING_PERIOD_EVERY_CHUNK.equals(settingValue)) { return null; } return RulesToolkit.parsePersistedJvmTimespan(settingValue); } catch (QuantityConversionException e) { throw new RuntimeException(e); } } @Override public Collection<TypedPreference<?>> getConfigurationAttributes() { return CONFIG_ATTRIBUTES; } @Override public String getId() { return RESULT_ID; } @Override public String getName() { return Messages.getString(Messages.MethodProfilingRule_RULE_NAME); } @Override public String getTopic() { return JfrRuleTopics.METHOD_PROFILING_TOPIC; } }
3f46ad4b00e2db0ff043727598b4ddba3837c1ce
bbc6319c3fd69b27fce761c4e09178ea60d700db
/app/src/main/java/com/gwaja92/android/autobiography/SettingFragment.java
b9812de4f8b73655713e568e6b29af8c32b52bb7
[]
no_license
gwaja92/autobiography
9b5ba07792b00e1bb1d7ab4db8087be724097017
9a4580718f56836f2725370224c4ce5cfa2a064a
refs/heads/master
2023-06-11T21:20:56.704230
2021-07-03T11:27:28
2021-07-03T11:27:28
378,842,749
0
0
null
null
null
null
UTF-8
Java
false
false
1,022
java
package com.gwaja92.android.autobiography; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; public class SettingFragment extends Fragment { SharedPreferences sharedPref; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); String name = sharedPref.getString("sharedName", ""); View view = inflater.inflate(R.layout.fragment_setting, container, false); TextView nameTextView = view.findViewById(R.id.myNameInSettings); nameTextView.setText(name); // Inflate the layout for this fragment return view; } }
b4560b0eeac51e75ce26ead51f3ebc8781d2be96
37cb33cedaba19573125922b6042f929446181d8
/flowable-server/src/main/java/com/github/web/response/result/ResultCodeEnum.java
3f923e361cd3611824007dc35d931d0199a55f44
[]
no_license
1178494717/flowable-work
c2c1763e09d6f757753c04d1fda01ece7b03ffb6
13117861eba13e7589c8681dc0c2d604d4243e39
refs/heads/master
2023-08-24T10:45:31.077395
2020-06-21T03:30:53
2020-06-21T03:30:53
272,145,948
0
0
null
2023-07-23T20:32:36
2020-06-14T06:27:52
Java
UTF-8
Java
false
false
449
java
package com.github.web.response.result; import lombok.Getter; /** * @date 2020/6/19 */ public enum ResultCodeEnum { // 成功 SUCCESS(200), // 失败 FAIL(400), // 未认证(签名错误) UNAUTHORIZED(401), // 接口不存在 NOT_FOUND(404), // 服务器内部错误 INTERNAL_SERVER_ERROR(500); @Getter private int code; ResultCodeEnum(int code) { this.code = code; } }
6f2c265b952ae162a95fe3bdebc20d078acec4bc
063be0d85f7f39d441b3c3ee1edeb7b727c2ee51
/src/main/java/com/hc/utils/mapper/Car.java
16780954a0d0547a5e4b905fc741a469b504f9d3
[]
no_license
whodarewin/utils
ff169de3970b088931ebdaecc752ec4313d2f030
19689d34c84d3785deda3d3db021d530807f1de6
refs/heads/master
2022-12-23T11:22:34.494548
2021-12-09T05:59:00
2021-12-09T05:59:00
160,476,309
0
0
null
2022-12-16T05:07:52
2018-12-05T07:11:58
Java
UTF-8
Java
false
false
2,073
java
package com.hc.utils.mapper; import org.modelmapper.spi.SourceGetter; import org.springframework.beans.BeanWrapperImpl; import org.springframework.util.ReflectionUtils; import java.io.FileDescriptor; import java.lang.reflect.Field; /** * @author hancongcong */ public class Car { private String make; private int numberOfSeats; private CarType type; private SourceGetter sourceGetter; public Car() { } public Car(String make, int numberOfSeats, CarType type) { this.make = make; this.numberOfSeats = numberOfSeats; this.type = type; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } public int getNumberOfSeats() { return numberOfSeats; } public void setNumberOfSeats(int numberOfSeats) { this.numberOfSeats = numberOfSeats; } public CarType getType() { return type; } public void setType(CarType type) { this.type = type; } public SourceGetter getSourceGetter() { return sourceGetter; } public void setSourceGetter(SourceGetter sourceGetter) { this.sourceGetter = sourceGetter; } @Override public String toString() { return "Car{" + "make='" + make + '\'' + ", numberOfSeats=" + numberOfSeats + ", type=" + type + ", sourceGetter=" + sourceGetter + '}'; } public static void main(String[] args){ Car car = new Car(); SourceGetter<Car> sourceGetter = Car::getMake; long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { car.getMake(); } System.out.println(System.currentTimeMillis() - start); // Car car = new Car(); // Field field = ReflectionUtils.findField(Car.class,"make"); // ReflectionUtils.makeAccessible(field); // ReflectionUtils.setField(field,car,"test"); // System.out.println(car); } }
f4750ea7dc53653e2737fcc431f1ca80b4b36f65
95890bb20285115766a69b38bd2e068ffea8203f
/examples/ex-showcase/src/main/java/com/realaicy/pg/sys/auth/entity/Auth.java
abc7ef3a7cff53f99d5107ba32fda8569a12395a
[]
no_license
cehkongfu/mypg
58a12860af214e796b1859fdee23e713349e03fa
e203b9ba594ea16d87c321553a60634a5eb114a3
refs/heads/master
2021-05-27T10:59:09.217874
2014-06-15T09:24:32
2014-06-15T09:25:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,755
java
package com.realaicy.pg.sys.auth.entity; import com.google.common.collect.Sets; import com.realaicy.pg.core.entity.BaseEntity; import com.realaicy.pg.core.repository.hibernate.type.CollectionToStringUserType; import com.realaicy.pg.core.repository.support.annotation.EnableQueryCache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import javax.persistence.*; import java.util.Set; /** * 组织机构 工作职位 用户 用户组 角色 关系表<br/> * <p/> * 1、授权的五种情况<br/> * 只给组织机构授权 (orgnizationId=? and jobId=0)<br/> * 只给工作职务授权 (orgnizationId=0 and jobId=?)<br/> * 给组织机构和工作职务都授权 (orgnizationId=? and jobId=?)<br/> * 给用户授权 (userId=?)<br/> * 给组授权 (groupId=?)<br/> * <p/> * 因此查询用户有没有权限 就是 * where (orgnizationId=? and jobId=0) or (organizationId = 0 and jobId=?) or (orgnizationId=? and jobId=?) or (userId=?) or (groupId=?) * <p/> * <p/> * 2、为了提高性能 * 放到一张表 * 此处不做关系映射(这样需要配合缓存) * <p/> * 3、如果另一方是可选的(如只选组织机构 或 只选工作职务) 那么默认0 使用0的目的是为了也让走索引 * <p/> * * @author realaicy * @version 1.1 * @email [email protected] * @qq 8042646 * @date 14-2-1 上午9:18 * @description TODO * @since 1.1 */ @TypeDef( name = "SetToStringUserType", typeClass = CollectionToStringUserType.class, parameters = { @Parameter(name = "separator", value = ","), @Parameter(name = "collectionType", value = "java.util.HashSet"), @Parameter(name = "elementType", value = "java.lang.Long") } ) @Entity @Table(name = "sys_auth") @EnableQueryCache @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Auth extends BaseEntity<Long> { /** * 组织机构 */ @Column(name = "organization_id") private Long organizationId = 0L; /** * 工作职务 */ @Column(name = "job_id") private Long jobId = 0L; /** * 用户 */ @Column(name = "user_id") private Long userId = 0L; /** * 组 */ @Column(name = "group_id") private Long groupId = 0L; @Type(type = "SetToStringUserType") @Column(name = "role_ids") private Set<Long> roleIds; @Enumerated(EnumType.STRING) private AuthType type; public Long getOrganizationId() { return organizationId; } public void setOrganizationId(Long organizationId) { this.organizationId = organizationId; } public Long getJobId() { return jobId; } public void setJobId(Long jobId) { this.jobId = jobId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Set<Long> getRoleIds() { if (roleIds == null) { roleIds = Sets.newHashSet(); } return roleIds; } public void setRoleIds(Set<Long> roleIds) { this.roleIds = roleIds; } public void addRoleId(Long roleId) { getRoleIds().add(roleId); } public void addRoleIds(Set<Long> roleIds) { getRoleIds().addAll(roleIds); } public AuthType getType() { return type; } public void setType(AuthType type) { this.type = type; } public Long getGroupId() { return groupId; } public void setGroupId(Long groupId) { this.groupId = groupId; } }
829957f16d8bf2688524d4173e04302e731f02c0
329307375d5308bed2311c178b5c245233ac6ff1
/src/com/tencent/mm/ui/widget/MMSwitchBtn$a.java
0fb82042da4b2552dfababb120aa20bafd5524a5
[]
no_license
ZoneMo/com.tencent.mm
6529ac4c31b14efa84c2877824fa3a1f72185c20
dc4f28aadc4afc27be8b099e08a7a06cee1960fe
refs/heads/master
2021-01-18T12:12:12.843406
2015-07-05T03:21:46
2015-07-05T03:21:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
268
java
package com.tencent.mm.ui.widget; public abstract interface MMSwitchBtn$a { public abstract void dr(boolean paramBoolean); } /* Location: * Qualified Name: com.tencent.mm.ui.widget.MMSwitchBtn.a * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
84db428c5f5812e287a6efeae886cebc4df46b0b
d5ab8ff243e823c051a0e652845d9cc5ce4ba2f1
/java/carsharing/Applicazione.java
ffc664f56006e4c0fa72acd829391b2aeaa01918
[]
no_license
CremaLuca/high-school-work
d8871b7e5806068e7daf5ca0883468d9a68de7ca
15452fded1bbd0fac434c37072c07c9208cba524
refs/heads/master
2022-12-17T01:50:36.901787
2020-09-17T08:41:24
2020-09-17T08:41:24
295,989,273
0
0
null
null
null
null
UTF-8
Java
false
false
717
java
import java.util.ArrayList; @SuppressWarnings("unused") public class Applicazione { GestoreDatabase gestoreDatabase = new GestoreDatabase("carsharing"); ArrayList<Socio> soci; ArrayList<Auto> auto; ArrayList<Noleggio> noleggi; public static void main(String[] args) { Applicazione app = new Applicazione(); } public Applicazione(){ ApriFinestra(); soci = gestoreDatabase.caricaAllSoci(); auto = gestoreDatabase.caricaAllAuto(); noleggi = gestoreDatabase.caricaAllNoleggi(); } /** * Fai partire la finestra. */ private void ApriFinestra(){ try { ApplicazioneGrafica window = new ApplicazioneGrafica(); window.open(); } catch (Exception e) { e.printStackTrace(); } } }
137b34fcf17d80afc8d6c839042d520e3c6493e3
4ddc42b1ce2640e3c13b638dd2e85b9e4571b5a2
/src/com/sogistudio/online/couchdb/model/NotificationMessage.java
ed5c23ba5ea873f5fe1010171f640f9d11f9fcc9
[]
no_license
likegreen/AndroidChat
09bf5fa9ef4c0eaeabf81148cdeac369ceea574e
512d86247c6d010d81a6f2739adf1176bc77a19a
refs/heads/master
2020-12-25T02:00:52.845275
2014-10-13T13:19:13
2014-10-13T13:19:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,018
java
/* * The MIT License (MIT) * * Copyright � 2013 Clover Studio Ltd. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.sogistudio.online.couchdb.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * NotificationMessage * * Model class for recent activity notification messages. */ public class NotificationMessage { public NotificationMessage(String fromUserId, String message, String userImageUrl) { super(); this.mFromUserId = fromUserId; this.mMessage = message; this.mUserImageUrl = userImageUrl; } @SerializedName("from_user_id") @Expose private String mFromUserId; @SerializedName("message") @Expose private String mMessage; @SerializedName("user_image_url") @Expose private String mUserImageUrl; @SerializedName("avatar_thumb_file_id") @Expose private String mUserAvatarFileId; private String mTargetId; private int mCount; public NotificationMessage() { } public String getFromUserId() { return mFromUserId; } public void setFromUserId(String fromUserId) { this.mFromUserId = fromUserId; } public String getMessage() { return mMessage; } public void setMessage(String message) { this.mMessage = message; } @Override public String toString() { return "NotificationMessage [_fromUserId=" + mFromUserId + ", _message=" + mMessage + "]"; } public String getTargetId() { return mTargetId; } public void setTargetId(String targetId) { this.mTargetId = targetId; } public int getCount() { return mCount; } public void setCount(int count) { this.mCount = count; } public String getUserImageUrl() { return mUserImageUrl; } public void setUserImageUrl(String userImageUrl) { this.mUserImageUrl = userImageUrl; } public String getUserAvatarFileId() { return mUserAvatarFileId; } public void setUserAvatarFileId(String mUserAvatarFileId) { this.mUserAvatarFileId = mUserAvatarFileId; } }
3d0af5c93856da6dca5f360f8c6ac0ebb6d4e7d9
e4f925f0d85dffb70ff7d9362622429364cf42a7
/SistemGestiuneInscrieri/Main.java
fac9cd3a1d354059c437730a2e99e3a484366c15
[]
no_license
theodorparfene/Java-Junior
fe73c726255b113d779bdb6735f483dbc852750f
9ac7ce46d1102a55bc830398042893bce47bb2ba
refs/heads/main
2023-04-20T01:00:43.653909
2021-05-08T01:02:03
2021-05-08T01:02:03
330,460,859
0
0
null
null
null
null
UTF-8
Java
false
false
6,012
java
package SistemGestiuneInscrieri; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); startApp(sc); sc.close(); } public static void startApp(Scanner sc) { System.out.println("Bun venit! Introduceti numarul de locuri disponibile:"); int availSeats = 0; while (availSeats <= 0) { try { // prevents non-integer inputs availSeats = sc.nextInt(); } catch(Exception e) { System.out.println("Trebuie sa introduceti un numar!"); sc.nextLine(); continue; } if (availSeats <= 0) { System.out.println("Numarul de locuri disponibile trebuie sa fie mai mare decat 0!"); } } GuestsList list = new GuestsList(availSeats); while (true) { System.out.println("Asteapta comanda: (help - Afiseaza lista de comenzi)"); switch (sc.next()) { case "help" -> help(); case "add" -> add(sc, list); case "check" -> check(sc, list); case "remove" -> remove(sc, list); case "update" -> update(sc, list); case "guests" -> list.allParticipatingGuests(); case "waitlist" -> list.allWaitingGuests(); case "available" -> System.out.println("Numar de locuri disponibile: " + list.remainingSeats()); case "guests_no" -> System.out.println("Numarul de persoane care participa la eveniment: " + list.occupiedSeats()); case "waitlist_no" -> System.out.println("Numarul de persoane din lista de asteptare: " + list.waitingSeats()); case "subscribe_no" -> System.out.println("Numarul de persoane inscrise: " + list.getList().size()); case "search" -> list.partialSearch(sc.next()); case "quit" -> { System.out.println("Aplicatia se inchide.."); return; } default -> System.out.println("Comanda invalida"); } } } public static void help() { System.out.println( "help - Afiseaza aceasta lista de comenzi\n" + "add - Adauga o noua persoana (inscriere)\n" + "check - Verifica daca o persoana este inscrisa la eveniment\n" + "remove - Sterge o persoana existenta din lista\n" + "update - Actualizeaza detaliile unei persoane\n" + "guests - Lista de persoane care participa la eveniment\n" + "waitlist - Persoanele din lista de asteptare\n" + "available - Numarul de locuri libere\n" + "guests_no - Numarul de persoane care participa la eveniment\n" + "waitlist_no - Numarul de persoane din lista de asteptare\n" + "subscribe_no - Numarul total de persoane inscrise\n" + "search - Cauta toti invitatii conform sirului de caractere introdus\n" + "quit - Inchide aplicatia"); } public static void add(Scanner sc, GuestsList list) { System.out.println("Se adauga o noua persoana…"); System.out.println("Introduceti prenumele:"); String firstName = sc.next(); System.out.println("Introduceti numele de familie:"); String lastName = sc.next(); System.out.println("Introduceti email:"); String email = sc.next(); System.out.println("Introduceti numar de telefon (format „+40733386463“):"); String phoneNumber = sc.next(); list.addGuest(firstName, lastName, email, phoneNumber); } public static void check(Scanner sc, GuestsList list) { System.out.println("Se cauta o persoana.."); System.out.println("Cautati prin a introduce: prenume si nume SAU email SAU numar de telefon: "); sc.nextLine(); if (list.searchGuest(sc.nextLine()) != null) { System.out.println("Persoana cautata se afla in lista."); } else { System.out.println("Persoana cautata nu se afla in lista"); } } public static void remove(Scanner sc, GuestsList list) { System.out.println("Se sterge o persoana existenta in lista.."); System.out.println("Cautati prin a introduce: prenume si nume SAU email SAU numar de telefon: "); sc.nextLine(); list.removeGuest(sc.nextLine()); } public static void update(Scanner sc, GuestsList list) { System.out.println("Se actualizeaza detaliile unei persoane.."); System.out.println("Cautati prin a introduce: prenume si nume SAU email SAU numar de telefon: "); sc.nextLine(); Guest guest = list.searchGuest(sc.nextLine()); if (guest == null) { System.out.println("Persoana introdusa nu exista.."); } else { System.out.println("Alege campul de actualizat, tastand:\n" + "\"1\" - Prenume\n" + "\"2\" - Nume\n" + "\"3\" - Email\n" + "\"4\" - Numar de telefon (format \"+40733386463\")"); int ans; while (true) { try { // prevents all non-integer inputs ans = sc.nextInt(); sc.nextLine(); break; } catch(Exception e) { System.out.println("Trebuie sa introduceti un numar!"); sc.nextLine(); } } System.out.println("Introduceti datele: "); String st2 = sc.nextLine(); list.setGuestFields(guest, st2, ans); } } }
88159cbe6211f103d9592a09b9eed2b835f576b1
5a61acf9a32ad1d3fb00ab99f0df0a2df1c7f3ec
/android/app/src/main/java/com/shophub/MainApplication.java
6370870306809f0a03b62ad47a8d9b70afea98c0
[]
no_license
Aweuk/ShopHubFront
260e46b4a1a3aa170d004b0593291b819ace23df
acb71bd41b17cd9044e56b73d88be28f4ed82979
refs/heads/master
2023-01-11T15:48:06.940190
2019-06-07T16:52:22
2019-06-07T16:52:22
190,765,848
0
0
null
null
null
null
UTF-8
Java
false
false
1,153
java
package com.shophub; import android.app.Application; import com.facebook.react.ReactApplication; import com.swmansion.gesturehandler.react.RNGestureHandlerPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new RNGestureHandlerPackage() ); } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
259dcd39367651e7223fbb9ea4c09ffea1412dbd
40455b8221e3e9c9318e600bd68fd28893b94a8b
/android-ngn-stack/src/main/java/org/doubango/ngn/datatype/mo/Float.java
4416abd930f6f41427c24f08d3f0b03d6749768b
[]
no_license
jonirazabal/BomberosTFG
d64615a9c4240525051f503794bb0020eaa4f415
622f10adbd5f61fa658b7d3caf4bc51ea8d499f5
refs/heads/master
2021-05-17T12:59:07.197671
2020-03-28T12:15:47
2020-03-28T12:15:47
250,788,142
1
0
null
null
null
null
UTF-8
Java
false
false
1,077
java
/* * * Copyright (C) 2018, University of the Basque Country (UPV/EHU) * * Contact for licensing options: <licensing-mcpttclient(at)mcopenplatform(dot)com> * * This file is part of MCOP MCPTT Client * * This is free software: you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.doubango.ngn.datatype.mo; import org.simpleframework.xml.Root; /** * */ @Root(strict=false, name = "float") public class Float { }
48e9a35f69e2211e85b7c02ebe4c414296b09ae6
56c6131e8b1bf8fb097a9161d0be6d85802b99bb
/src/packageRPG/entities/statics/yellowFlower.java
348a2e6a5a3e1d93378a1054ccfabdf4bfb5e290
[]
no_license
rzfortes/Curse-of-Westerrose
330d23c7d38e5546527df8d231253ad112241a00
b8d208676de6810df18a2c61fdf5605432d68338
refs/heads/master
2021-01-11T05:43:55.500937
2019-06-26T17:10:50
2019-06-26T17:10:50
71,336,375
0
0
null
null
null
null
UTF-8
Java
false
false
930
java
package packageRPG.entities.statics; import java.awt.Graphics; import packageRPG.Handler; import packageRPG.entities.statics.StaticEntity; import packageRPG.gfx.Assets; import packageRPG.tiles.Tile; public class yellowFlower extends StaticEntity{ public yellowFlower(Handler handler, float x, float y, int i) { super(handler, x, y, Tile.TILEWIDTH + i,Tile.TILEHEIGHT + i, 1000); // TODO Auto-generated constructor stub bounds.x = 10; bounds.y = (int)(height / 1.5f); bounds.width = width - 20; bounds.height = (int)(height - height / 1.5f); } @Override public void update() { // TODO Auto-generated method stub } @Override public void render(Graphics g) { g.drawImage(Assets.yellowFlower, (int)(x -handler.getGameCamera().getxOffset()), (int)(y - handler.getGameCamera().getyOffset()), width, height, null); } @Override public void dead() { // TODO Auto-generated method stub } }
30d8b1b96cc30fb9377831aa223ee39729c36cd5
460db6d94ccb7a3946ea5587d0cf1f593f6c0c19
/JANE_Simulation/de/uni_trier/jane/simulation/gui/ConsoleFrame.java
4946808696bd9905097e42bfce1af90061eceea4
[]
no_license
tobiaskalmes/MobileComputingJANE
60d7cba55097ea9ba918039192c8ecde713bbc63
54cb6b6fc14a37b6822efaf856f7812870ddec5e
refs/heads/master
2021-01-20T11:40:55.461841
2013-08-10T20:14:12
2013-08-10T20:14:12
11,000,185
1
1
null
null
null
null
ISO-8859-2
Java
false
false
2,163
java
/* * Created on 18.02.2005 * * To change this generated comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ package de.uni_trier.jane.simulation.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; import de.uni_trier.jane.console.*; /** * @author Daniel Görgen * * To change this generated comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class ConsoleFrame extends JFrame implements JANEConsoleFrame { private JTextAreaConsole console; /** * */ public ConsoleFrame() { super("Console"); setSize(600, 200); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); JTextArea textArea = new JTextArea(4, 80); textArea.setEditable(false); console = new JTextAreaConsole(textArea); JScrollPane scrollPane = new JScrollPane(textArea); contentPane.add(scrollPane, BorderLayout.CENTER); setVisible(false); // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see de.uni_trier.jane.simulation.gui.JANEFrame#addFrameListener(de.uni_trier.jane.simulation.gui.JANEFrameListener) */ public void addFrameListener(final JANEFrameListener frameListener) { addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent e) { // TODO Auto-generated method stub } public void componentMoved(ComponentEvent e) { // TODO Auto-generated method stub } public void componentShown(ComponentEvent e) { // TODO Auto-generated method stub } public void componentHidden(ComponentEvent e) { frameListener.frameHidden(); } }); } /* (non-Javadoc) * @see de.uni_trier.jane.console.Console#println(java.lang.String) */ public void println(String text) { console.println(text); } /* (non-Javadoc) * @see de.uni_trier.jane.console.Console#print(java.lang.String) */ public void print(String text) { console.print(text); } /* (non-Javadoc) * @see de.uni_trier.jane.console.Console#println() */ public void println() { console.println(); } }
d5d19beb2d1f55e3e489c833c410ff2b495f983d
3851a7b297a221635a95acb0f6d903b6c636bcbb
/HibernateTest/src/main/java/org/huihui/app/domain/News.java
58cda88a466f4c13e0bf681ddfe2b669603f0bed
[]
no_license
liuchunhui/JavaProject
137525e4ad6683122b95745b84ee062eff31ae51
ac92cf32fedd5abb519539d26b31ad9ca022b5f0
refs/heads/master
2016-09-06T01:29:15.348074
2014-11-21T07:47:19
2014-11-21T07:47:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,104
java
package org.huihui.app.domain; import org.hibernate.annotations.Formula; import org.hibernate.annotations.Generated; import org.hibernate.annotations.GenerationTime; import javax.persistence.*; /** * Created by huihui on 14-10-31. */ @Entity @Table(name = "news_inf") public class News { // 消息类的标识属性 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; // 消息标题 @Column(name = "new_title",length = 50) private String title; // 消息内容 // concent不会映射到数据列 @Transient private String content; // EnumType.STRING 保存列举值的名称 //@Enumerated(EnumType.STRING) // EnumType.STRING 保存列举值的序号 @Enumerated(EnumType.ORDINAL) @Column(name = "happen_season") private Season happenSeanson; // 消息全部内容,由系统根据公式生成 不在数据库中生成 //@Formula("(select concat(nt.title,nt.content)" + "from news_inf nt where nt.id= id)") // 指定@Generated的value为ALWAYS,表明该属性的值由数据库生成 // HIbernate会在每次执行insert,update时执行select语句来查询获取该属性的值 //@Generated(GenerationTime.ALWAYS) //private String fullContent; public News() { } // set,get方法 public Season getHappenSeanson() { return happenSeanson; } public void setHappenSeanson(Season happenSeanson) { this.happenSeanson = happenSeanson; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } // public String getFullContent() { // return fullContent; // } // // public void setFullContent(String fullContent) { // this.fullContent = fullContent; // } }
6259552169f296f5001d9b44f6eacbab3e7971a7
2b98f6a16554ac50871467fb6769aa323a0f779f
/src/MyServer.java
d6c787e22d79f4fae26845a37ccfcbf087876233
[]
no_license
jesstracy/Assignment14-ConsoleChatRoom
57d75e510dcb7f1cc2c3abea99f2c6b8ca012270
18fbe8b7d21b7d855e76bfa54a88c1bd6949e03a
refs/heads/master
2021-06-04T06:07:20.254236
2016-08-25T18:27:12
2016-08-25T18:27:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
988
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; /** * Created by jessicatracy on 8/25/16. */ public class MyServer { public void startServer() { try { ServerSocket serverListener = new ServerSocket(8080); System.out.println("Waiting for a connection..."); while (true) { Socket clientSocket = serverListener.accept(); System.out.println("Connection found!"); //start Thread on this connection ConnectionHandler myHandler = new ConnectionHandler(clientSocket); // handleIncomingConnection(clientSocket); Thread newHandlingThread = new Thread(myHandler); newHandlingThread.start(); } } catch (IOException exception) { exception.printStackTrace(); } } }
fce7305d7c569e0bce087f44e1f18c46df4858f9
571c0edd8b8f32db258e30adb0c9dc5200594571
/MIU-SWA/LAB06/LAB06_EX01/order-service/src/main/java/shop/order/service/dto/ShoppingCartDTO.java
f2571d53897131e0c502fa5bb2ae13472c6b489f
[]
no_license
bpuje/MIU-SWA
0d076a67cc8e51ec0cce08d4cecc7e2346bb7394
5cec1814688cc66fed883a51ab53d1c0a8361996
refs/heads/master
2022-12-18T00:16:52.295300
2020-09-20T05:37:59
2020-09-20T05:37:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,424
java
package shop.order.service.dto; import shop.order.service.dto.CartLineDTO; import java.util.ArrayList; public class ShoppingCartDTO { private String cartid; private double totalPrice; private ArrayList<CartLineDTO> cartlineList = new ArrayList<CartLineDTO>(); public void print() { System.out.println("Content of the shoppingcart:"); for (CartLineDTO cline : cartlineList) { System.out.println(cline.getQuantity() + " " + cline.getProduct().getProductnumber() + " " + cline.getProduct().getDescription() + " " + cline.getProduct().getPrice()); } System.out.println("Total price = "+totalPrice); } public String getCartid() { return cartid; } public void setCartid(String cartid) { this.cartid = cartid; } public ArrayList<CartLineDTO> getCartlineList() { return cartlineList; } public void setCartlineList(ArrayList<CartLineDTO> cartlineList) { this.cartlineList = cartlineList; } public void addCartLine(CartLineDTO cartLine) { cartlineList.add(cartLine); } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } public double getTotalPrice() { return totalPrice; } @Override public String toString() { return "ShoppingCartDTO{" + "cartid='" + cartid + '\'' + ", totalPrice=" + totalPrice + ", cartlineList=" + cartlineList + '}'; } }
bd32e98df1f361adbf174c5eddadd0ab33ff0992
df1bb3e7d221242076ff0f1244cff29ba449df0a
/eclipse/imsdb/src/imsdb/Admin_SupplierAdd.java
ecaae1af035633e9958301e7970d60e2b10abb16
[]
no_license
sskimssheridan/imsdb
fde728ae0b64abb5d765afe3fe8505af6a32eab2
f91fc3425450e01a49efeae229aeb2b0180f30d7
refs/heads/master
2021-01-19T09:23:55.812989
2014-03-17T22:54:15
2014-03-17T22:54:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
580
java
package imsdb; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Admin_SupplierAdd extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.getRequestDispatcher("/jsp/task/Supplier/AddSupplier.jsp").forward(request, response); } }
31e5cc9d3622f606a286d66c1b87c8c4b1bb02b5
0f3048e71e16283a72f2aa4649c78f734b788a87
/src/main/java/security/PBKDF2Encoder.java
220da5cdf1af8b946abb19a21e734fc112ef9e35
[]
no_license
JuuanC/demo-quarkus
af0b0daa93e66039e25412b37e51acee8f3af407
1ef6bebba6e6a6f3e4d89f8bd3b8bec259a94eb2
refs/heads/master
2023-01-22T12:44:22.763013
2020-10-07T14:22:38
2020-10-07T14:22:38
299,399,310
0
0
null
null
null
null
UTF-8
Java
false
false
1,688
java
package security; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.Base64; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.enterprise.context.RequestScoped; import org.eclipse.microprofile.config.inject.ConfigProperty; @RequestScoped /** * Encargado de proveer de servicios de codificacion de contraseñas al sistema. Utilizando propiedades del sistema * para generar y configurar la encriptacion de cadenas de texto. Su principal uso se encuentra en la decodificación de las * contraseñas de los nuevos usuarios registrados del sistema. * * @author José Alberto Espinoza */ public class PBKDF2Encoder { @ConfigProperty(name = "demo-crum.quarkusjwt.password.secret") private String secret; @ConfigProperty(name = "demo-crum.quarkusjwt.password.iteration") private Integer iteration; @ConfigProperty(name = "demo-crum.quarkusjwt.password.keylength") private Integer keylength; /** * More info <a href="https://www.owasp.org/index.php/Hashing_Java">(https://www.owasp.org/index.php/Hashing_Java)</a> * @param cs un string con la contraseña sin codificar * @return contraseña codificada * @author José Alberto Espinoza */ public String encode(CharSequence cs) { try { byte[] result = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512") .generateSecret(new PBEKeySpec(cs.toString().toCharArray(), secret.getBytes(), iteration, keylength)) .getEncoded(); return Base64.getEncoder().encodeToString(result); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { throw new RuntimeException(ex); } } }
4d3fe84a5c0b8688af24c1eb9fd7b8769df9d8ac
768350f4762299a465882df0166953265f8f9e1f
/dolphin/src/main/java/com/yusj/dolphin/decorator/package-info.java
aefc5607543a4e5c26e7fdd58a00ef03a97ab3de
[]
no_license
kakalgy/ocean
b4457d66ba424c259578e37ec301f0645112d068
ccdfaf6cb8ab3b291364d5400246ff6386bdace9
refs/heads/master
2020-03-31T15:46:59.402048
2019-01-14T08:13:31
2019-01-14T08:13:31
152,351,352
0
0
null
null
null
null
UTF-8
Java
false
false
131
java
/** * @apiNote 装饰者模式 * @author gyli * @version 1.0 * date: 2018-10-11 21:01 */ package com.yusj.dolphin.decorator;
4fb7acc4bd402b4f81346f0668e40dcf416e51dd
6fbf457d85ac67cc6d7dcdcb57feadadbf1e3477
/bbdevice-example/src/main/java/com/bbpos/bbdevice/util/LogT.java
3dbc0d40729f62fc78f08832d77ccc682296d161
[]
no_license
haohz1987/BBPos_demo-master
392aab8d56fc9a0b6a05f304249dc097e935b20f
4c1fbc292683f0d1a3754ac44c880e87b9522948
refs/heads/master
2021-04-15T11:20:39.768852
2017-12-19T02:50:17
2017-12-19T02:50:17
126,466,634
0
0
null
null
null
null
UTF-8
Java
false
false
4,407
java
package com.bbpos.bbdevice.util; import android.text.TextUtils; import android.util.Log; public class LogT { private static final String TAG = "bbM"; /** * 日志输出等级 */ private static int LOG_LEVEL = Log.VERBOSE; /** * 是否显示日志 */ private static boolean isShowLog = true; private static final String DOUBLE_DIVIDER = "--->>>"; public static void init(boolean isShowLog) { LogT.isShowLog = isShowLog; } public static void init(boolean isShowLog, int logLevel) { LogT.isShowLog = isShowLog; LogT.LOG_LEVEL = logLevel; } public static int v(Object msg) { return v(TAG, msg); } public static int v(String tag, Object msg) { return v(tag, msg, null); } public static int v(String tag, Object msg, Throwable tr) { return printLog(Log.VERBOSE, tag, msg, tr); } public static int d(Object msg) { return d(TAG, msg); } public static int d(String tag, Object msg) { return d(tag, msg, null); } public static int d(String tag, Object msg, Throwable tr) { return printLog(Log.DEBUG, tag, msg, tr); } public static int i(Object msg) { return i(TAG, msg); } public static int i(String tag, Object msg) { return i(tag, msg, null); } public static int i(String tag, Object msg, Throwable tr) { return printLog(Log.INFO, tag, msg, tr); } public static int w(Object msg) { return w(TAG, msg); } public static int w(String tag, Object msg) { return w(tag, msg, null); } public static int w(String tag, Object msg, Throwable tr) { return printLog(Log.WARN, tag, msg, tr); } public static int e(Object msg) { return e(TAG, msg); } public static int e(String tag, Object msg) { return e(tag, msg, null); } public static int e(String tag, Object msg, Throwable tr) { return printLog(Log.ERROR, tag, msg, tr); } private static int printLog(int type, String tag, Object msgObj, Throwable tr) { if (!isShowLog) { return 0; } String msg; // StringBuilder builder = new StringBuilder(DOUBLE_DIVIDER); StringBuilder builder = new StringBuilder(getFunctionName()+DOUBLE_DIVIDER); if (msgObj == null) { msg = ""; } else { msg = msgObj.toString(); } if (!TextUtils.isEmpty(msg)) { builder.append(msg); } if (tr != null) { builder.append('\n').append(Log.getStackTraceString(tr)); } // builder.append('\n'); switch (type) { case Log.VERBOSE: if (LOG_LEVEL <= Log.VERBOSE) { return Log.v(tag, builder.toString()); } break; case Log.DEBUG: if (LOG_LEVEL <= Log.DEBUG) { return Log.v(tag, builder.toString()); } break; case Log.INFO: if (LOG_LEVEL <= Log.INFO) { return Log.i(tag, builder.toString()); } break; case Log.WARN: if (LOG_LEVEL <= Log.WARN) { return Log.w(tag, builder.toString()); } break; case Log.ERROR: if (LOG_LEVEL <= Log.ERROR) { return Log.e(tag, builder.toString()); } break; } return 0; } private static String getFunctionName() { StackTraceElement[] elements = Thread.currentThread().getStackTrace(); if (elements == null) { return ""; } for (StackTraceElement ste : elements) { if (ste.isNativeMethod()) { continue; } if (ste.getClassName().equals(Thread.class.getName())) { continue; } if (ste.getClassName().equals(LogT.class.getName())) { continue; } return " " + ste.getFileName().substring(0, ste.getFileName().indexOf(".")) + "." + ste.getMethodName() + " (" + ste.getFileName() + ":" + ste.getLineNumber() + ")"; } return ""; } }
04080932b30b0fda5a10ef9ceee5a1db95203723
4387629e9e13db4ee616a0c98b88082db209ccbd
/Automatisering/src/test/java/stepDefinitions/StepDefinitions.java
9bd09c8df7429178e1bc8fe46cc62e4f8a71a075
[]
no_license
staffanaberg/Automatisering-3
41eac1fe292340f1af7231eff23a4b26c4560c33
c1efca007c044bf83e2105fb5ad1dab7c565abc4
refs/heads/master
2023-04-02T02:05:31.613058
2021-04-09T17:16:30
2021-04-09T17:16:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,630
java
package stepDefinitions; import static org.junit.Assert.assertEquals; import java.util.Random; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import io.cucumber.java.After; import io.cucumber.java.Before; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; public class StepDefinitions { private WebDriver driver; Random randomGenerator = new Random(); int randomInt = randomGenerator.nextInt(10000); String longusername = "JaghetererJaghetererJaghetererJaghetererJaghetererJaghetererJaghetererJaghetererJaghetererJaghetereri"; @Before public void openBrowser() { System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Selenium\\chromedriver.exe"); driver = new ChromeDriver(); driver.get("https://login.mailchimp.com/signup/"); driver.manage().window().maximize(); click(driver, By.cssSelector("button[id=onetrust-accept-btn-handler]")); } private void click(WebDriver driver, By by) { (new WebDriverWait(driver,10)).until(ExpectedConditions.elementToBeClickable(by)); driver.findElement(by).click(); } private void sendKeys(WebDriver driver, By by, String keys) { (new WebDriverWait(driver,10)).until(ExpectedConditions.presenceOfElementLocated(by)); driver.findElement(by).sendKeys(keys); } @Given("I have entered {string} into the e-mail text field") public void i_have_entered_into_the_e_mail_text_field(String mail) { if(mail.equals("email")) { sendKeys(driver, By.name("email"), mail + randomInt + "@gmail.com"); }else if(mail.equals("")) { } } @Given("I have also entered {string} into the username text field") public void i_have_also_entered_into_the_username_text_field(String usern) { if(usern.equals("username")) { sendKeys(driver, By.name("username"), usern); }else if(usern.equals("longusername")) { sendKeys(driver, By.name("username"), longusername); } else if(usern.equals("workingusername")) { sendKeys(driver, By.name("username"), usern + randomInt); } } @Given("I have also entered {string} into the password text field") public void i_have_also_entered_into_the_password_text_field(String passw) { sendKeys(driver, By.name("password"), passw); } @When("I press sign up") public void i_press_sign_up() throws InterruptedException { click(driver, By.id("create-account")); Thread.sleep(3000); } @Then("I continue to {string} for verification") public void i_continue_to_for_verification(String veri) { if (veri.equals("Check your email")) { assertEquals(veri, driver.findElement(By.cssSelector(".\\!margin-bottom--lv3")).getText()); }else if(veri.equals("Enter a value less than 100 characters long")) { assertEquals(veri, driver.findElement(By.className("invalid-error")).getText()); }else if(veri.equals("Another user with this username already exists. Maybe it's your evil twin. Spooky.")) { assertEquals(veri, driver.findElement(By.className("invalid-error")).getText()); }else if(veri.equals("Please enter a value")) { assertEquals(veri, driver.findElement(By.className("invalid-error")).getText()); } } @After public void teardown() { driver.quit(); } }
875218b0adf11f36d409d6c960395407bab602d8
bf05ebe1eb9d58a8603981757a4c822a16aade9a
/Java/FP/src/utiles/Museos.java
f1d8eaefc54cdd424e9c13bf059a1eae78e49156
[]
no_license
pfa1990/Task
4ba6b0d3cf8534c4f2a815ff7e7145b0d6ee7790
b3ffe8891f3d5032b739468333ddab616e3a1347
refs/heads/master
2021-01-10T05:33:33.467365
2016-02-18T17:37:02
2016-02-18T17:37:02
51,999,140
0
0
null
null
null
null
UTF-8
Java
false
false
1,701
java
package utiles; import java.util.HashSet; import java.util.Set; import persona.Persona; public class Museos { public static Set<Persona> repiten(Set<Persona> anterior, Set<Persona> actual) { Set<Persona> interseccion = new HashSet<Persona>(anterior); interseccion.retainAll(actual); return interseccion; } public static Set<Persona> todos(Set<Persona> anterior, Set<Persona> actual) { Set<Persona> union = new HashSet<Persona>(anterior); union.addAll(actual); return union; } public static Set<Persona> nuevos(Set<Persona> anterior, Set<Persona> actual) { Set<Persona> resta = new HashSet<Persona>(actual); resta.addAll(anterior); return resta; } public static Set<Persona> espanolYOtro(Set<Persona> espanol, Set<Persona> ingles, Set<Persona> frances) { Set<Persona> espIng = new HashSet<Persona>(espanol); espIng.retainAll(ingles); Set<Persona> espFra = new HashSet<Persona>(espanol); espFra.retainAll(frances); espFra.addAll(espIng); return espFra; } public static Set<Persona> alMenosDos(Set<Persona> espanol, Set<Persona> ingles, Set<Persona> frances) { Set<Persona> ingFra = new HashSet<Persona>(ingles); ingFra.retainAll(frances); ingFra.addAll(espanolYOtro(espanol, ingles, frances)); return ingFra; } public static Set<Persona> soloUno(Set<Persona> espanol, Set<Persona> ingles, Set<Persona> frances) { Set<Persona> uno = new HashSet<Persona>(espanol); uno.addAll(frances); uno.addAll(ingles); uno.remove(alMenosDos(espanol, ingles, frances)); return uno; } }
53023b10470ad4e4251a1313b3f66150f2d59dd3
905123b2a2df72d89c8713cc7fc8fee94bf7284b
/examples/org.eclipse.gmf.sketch.transformer/src/org/eclipse/gmf/internal/sketch/transformer/reconcile/SketchReconcilerConfig.java
7d7bf32e7c0e9ec7e202d8a41c3ef809b0dfc5ee
[]
no_license
isabella232/gmf-tooling
8fde6904f5a843fec900ebb05e66846a4851bf77
14ed41c5e22a4e8e3906a6b9fcc07612c6f66f0b
refs/heads/master
2023-03-19T18:03:05.757525
2015-12-10T16:11:38
2015-12-10T16:50:12
349,976,026
0
0
null
2021-03-21T11:26:41
2021-03-21T11:19:38
null
UTF-8
Java
false
false
8,631
java
/* * Copyright (c) 2007 Borland Software Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Dmitry Stadnik (Borland) - initial API and implementation */ package org.eclipse.gmf.internal.sketch.transformer.reconcile; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.gmf.codegen.gmfgen.GMFGenPackage; import org.eclipse.gmf.internal.codegen.util.VisualIDMatcher; import org.eclipse.gmf.internal.common.reconcile.Copier; import org.eclipse.gmf.internal.common.reconcile.Decision; import org.eclipse.gmf.internal.common.reconcile.DefaultDecision; import org.eclipse.gmf.internal.common.reconcile.ReconcilerConfigBase; /** * @author dstadnik */ public class SketchReconcilerConfig extends ReconcilerConfigBase { private final GMFGenPackage GMFGEN = GMFGenPackage.eINSTANCE; public SketchReconcilerConfig() { setMatcher(GMFGEN.getGenEditorGenerator(), ALWAYS_MATCH); preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_CopyrightText()); preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_PackageNamePrefix()); preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_DomainFileExtension()); preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_DiagramFileExtension()); preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_SameFileForDiagramAndModel()); preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_ModelID()); preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_DynamicTemplates()); preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_TemplateDirectory()); addDecision(GMFGEN.getGenEditorGenerator(), new Decision.ALWAYS_OLD(GMFGEN.getGenEditorGenerator_Plugin())); addDecision(GMFGEN.getGenEditorGenerator(), new Decision.ALWAYS_OLD(GMFGEN.getGenEditorGenerator_Editor())); addDecision(GMFGEN.getGenEditorGenerator(), new Decision.ALWAYS_OLD(GMFGEN.getGenEditorGenerator_DiagramUpdater())); addDecision(GMFGEN.getGenEditorGenerator(), new Decision.ALWAYS_OLD(GMFGEN.getGenEditorGenerator_PropertySheet())); addDecision(GMFGEN.getGenEditorGenerator(), new Decision.ALWAYS_OLD(GMFGEN.getGenEditorGenerator_Audits())); addDecision(GMFGEN.getGenEditorGenerator(), new Decision.ALWAYS_OLD(GMFGEN.getGenEditorGenerator_ExpressionProviders())); addDecision(GMFGEN.getGenEditorGenerator(), new Decision.ALWAYS_OLD(GMFGEN.getGenEditorGenerator_Application())); // Diagram setMatcher(GMFGEN.getGenDiagram(), ALWAYS_MATCH); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getGenDiagram_Synchronized()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getShortcuts_ContainsShortcutsTo()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getShortcuts_ShortcutsProvidedFor()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getProviderClassNames_IconProviderPriority()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getEditorCandies_CreationWizardIconPath()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getEditorCandies_CreationWizardCategoryID()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationEnabled()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_LiveValidationUIFeedback()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationDecorators()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationDecoratorProviderClassName()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationDecoratorProviderPriority()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationProviderClassName()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationProviderPriority()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_MetricProviderPriority()); preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_MetricProviderClassName()); addDecision(GMFGEN.getGenDiagram(), new Decision.ALWAYS_OLD(GMFGEN.getGenDiagram_Preferences())); addDecision(GMFGEN.getGenDiagram(), new Decision.ALWAYS_OLD(GMFGEN.getGenDiagram_PreferencePages())); addDecision(GMFGEN.getGenDiagram(), new ViewmapDecision()); for (EClass node : new EClass[] { GMFGEN.getGenTopLevelNode(), GMFGEN.getGenChildNode(), GMFGEN.getGenChildLabelNode(), GMFGEN.getGenChildSideAffixedNode() }) { setMatcher(node, new VisualIDMatcher()); addDecision(node, new ModelFacetDecision()); addDecision(node, new ViewmapDecision()); preserveIfSet(node, GMFGEN.getGenNode_PrimaryDragEditPolicyQualifiedClassName()); } addDecision(GMFGEN.getGenChildLabelNode(), new LabelModelFacetDecision()); preserveIfSet(GMFGEN.getGenChildSideAffixedNode(), GMFGEN.getGenChildSideAffixedNode_PreferredSideName()); setMatcher(GMFGEN.getGenCompartment(), new VisualIDMatcher()); preserveIfSet(GMFGEN.getGenCompartment(), GMFGEN.getGenCompartment_Title()); preserveIfSet(GMFGEN.getGenCompartment(), GMFGEN.getGenCompartment_ListLayout()); preserveIfSet(GMFGEN.getGenCompartment(), GMFGEN.getGenCompartment_CanCollapse()); preserveIfSet(GMFGEN.getGenCompartment(), GMFGEN.getGenCompartment_HideIfEmpty()); preserveIfSet(GMFGEN.getGenCompartment(), GMFGEN.getGenCompartment_NeedsTitle()); addDecision(GMFGEN.getGenCompartment(), new ViewmapDecision()); setMatcher(GMFGEN.getGenLink(), new VisualIDMatcher()); preserveIfSet(GMFGEN.getGenLink(), GMFGEN.getGenLink_IncomingCreationAllowed()); preserveIfSet(GMFGEN.getGenLink(), GMFGEN.getGenLink_OutgoingCreationAllowed()); preserveIfSet(GMFGEN.getGenLink(), GMFGEN.getGenLink_ViewDirectionAlignedWithModel()); addDecision(GMFGEN.getGenLink(), new ModelFacetDecision()); addDecision(GMFGEN.getGenLink(), new ViewmapDecision()); addDecision(GMFGEN.getGenLink(), new Decision.ALWAYS_OLD(GMFGEN.getGenLink_CreationConstraints())); for (EClass label : new EClass[] { GMFGEN.getGenLinkLabel(), GMFGEN.getGenNodeLabel(), GMFGEN.getGenExternalNodeLabel() }) { setMatcher(label, new VisualIDMatcher()); addDecision(label, new LabelModelFacetDecision()); addDecision(label, new ViewmapDecision()); preserveIfSet(label, GMFGEN.getGenLabel_ElementIcon()); preserveIfSet(label, GMFGEN.getGenLabel_ReadOnly()); } preserveIfSet(GMFGEN.getGenLinkLabel(), GMFGEN.getGenLinkLabel_Alignment()); setMatcher(GMFGEN.getCustomBehaviour(), ALWAYS_MATCH); setCopier(GMFGEN.getCustomBehaviour(), Copier.COMPLETE_COPY); setMatcher(GMFGEN.getOpenDiagramBehaviour(), ALWAYS_MATCH); setCopier(GMFGEN.getOpenDiagramBehaviour(), Copier.COMPLETE_COPY); setMatcher(GMFGEN.getMetamodelType(), ALWAYS_MATCH); preserveIfSet(GMFGEN.getMetamodelType(), GMFGEN.getElementType_DisplayName()); preserveIfSet(GMFGEN.getMetamodelType(), GMFGEN.getElementType_DefinedExternally()); setMatcher(GMFGEN.getSpecializationType(), ALWAYS_MATCH); preserveIfSet(GMFGEN.getSpecializationType(), GMFGEN.getElementType_DisplayName()); preserveIfSet(GMFGEN.getSpecializationType(), GMFGEN.getElementType_DefinedExternally()); // Palette setMatcher(GMFGEN.getPalette(), ALWAYS_MATCH); preserveIfSet(GMFGEN.getPalette(), GMFGEN.getPalette_Flyout()); preserveIfSet(GMFGEN.getPalette(), GMFGEN.getPalette_PackageName()); preserveIfSet(GMFGEN.getPalette(), GMFGEN.getPalette_FactoryClassName()); for (EClass entry : new EClass[] { GMFGEN.getToolGroup(), GMFGEN.getToolEntry(), GMFGEN.getStandardEntry() }) { setMatcher(entry, new PropertyMatcher(GMFGEN.getEntryBase_Title())); preserveIfSet(entry, GMFGEN.getEntryBase_Description()); preserveIfSet(entry, GMFGEN.getEntryBase_CreateMethodName()); preserveIfSet(entry, GMFGEN.getEntryBase_LargeIconPath()); preserveIfSet(entry, GMFGEN.getEntryBase_SmallIconPath()); } for (EClass entry : new EClass[] { GMFGEN.getToolEntry(), GMFGEN.getStandardEntry() }) { preserveIfSet(entry, GMFGEN.getAbstractToolEntry_Default()); preserveIfSet(entry, GMFGEN.getAbstractToolEntry_QualifiedToolName()); } preserveIfSet(GMFGEN.getToolGroup(), GMFGEN.getToolGroup_Collapse()); preserveIfSet(GMFGEN.getToolGroup(), GMFGEN.getToolGroup_Stack()); preserveIfSet(GMFGEN.getStandardEntry(), GMFGEN.getStandardEntry_Kind()); } private void preserveIfSet(EClass eClass, EAttribute feature) { addDecision(eClass, new DefaultDecision(feature)); } }
[ "dstadnik" ]
dstadnik
f1f88720bb9812e1138514f124c9cb8ba9f9198f
bd02936120bcfdd81d0fbbbc752e89bf49b1cf03
/org/spongepowered/asm/mixin/gen/AccessorGeneratorField.java
2e9f8c0c2ce071520b8f25263ed9381c8006847b
[]
no_license
Tuzakci/ICEHack-0.5-Source
f336f2b4e8f0b5ea3462f3f37da14fba7c0a554a
fc347479ce8dddb606d14b4c19dac2e7d446ca20
refs/heads/main
2023-01-09T08:33:56.273435
2020-11-13T21:37:18
2020-11-13T21:37:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
622
java
package org.spongepowered.asm.mixin.gen; import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.FieldNode; public abstract class AccessorGeneratorField extends AccessorGenerator { protected final FieldNode targetField; protected final Type targetType; protected final boolean isInstanceField; public AccessorGeneratorField(AccessorInfo paramAccessorInfo) { super(paramAccessorInfo); this.targetField = paramAccessorInfo.getTargetField(); this.targetType = paramAccessorInfo.getTargetFieldType(); this.isInstanceField = ((this.targetField.access & 0x8) == 0); } }
91da4fbba0a59ffbc704ff0db828f6c643f0d9db
4dfcd7b83b122885068780de37a2f1c6e3c68c87
/src/main/java/com/Hotelreservation/HotelReservation.java
3d8277f6d9e096b2d3e4597b207adbddb2fdc704
[]
no_license
stutisaurya/Hotel-Reservation
dae141aa9bd5dadcf91c2b266e822573da7b2021
606c2c2c870fb4aa52d4547d9392727f045d2972
refs/heads/main
2023-06-23T10:36:30.410666
2021-07-19T10:42:04
2021-07-19T10:42:04
386,147,711
0
0
null
null
null
null
UTF-8
Java
false
false
810
java
package com.Hotelreservation; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class HotelReservation { public static List<Hotel> hotels = new ArrayList<Hotel>(); public void addHotel(Hotel hotel) { hotels.add(hotel); } public Hotel getCheapestHotel(LocalDate startDate, LocalDate lastDate) { long daysBetween = ChronoUnit.DAYS.between(startDate, lastDate); int cheapRate; Hotel cheapest = Collections.min(hotels, Comparator.comparing(hotel -> hotel.regularWeekDayRate)); cheapRate = (int) ((daysBetween + 1) * cheapest.regularWeekDayRate); System.out.println("Cheapest Hotel Name: " + cheapest.name + "\nTotal Rate: " + cheapRate); return cheapest; } }
a763b1578a75cca447a4a094d700197d925e89d0
8d41727c520e783943f4c07ef46efd83c32020b8
/Practical_notesb/src/week6/LIstDemo4.java
abafd466dd0589fe644b98837bbbc91ddb038678
[]
no_license
Mgunadi/APS
d1c42a50395b6df43877d4d1fb6cb91ade7e33c1
195273de5d24951f6bb83c8423c0a9342653edd7
refs/heads/master
2020-04-30T21:17:53.660395
2019-06-28T06:54:11
2019-06-28T06:54:11
175,555,861
0
0
null
null
null
null
UTF-8
Java
false
false
1,528
java
package week6; import java.util.*; class ListDemo4 { public static void main(String[] args) { Account accArray[] ={ new Account("s123", "Mercy Brown" , 5000), new Account("g234", "David Brown" , 3000), new Account("x001", "Mary Brown" , 2000)}; List accounts = Arrays.asList(accArray); Collections.sort(accounts); for (Object acc : accounts){ System.out.println("Name: " + ((Account)acc).getName()); System.out.println("Balance: " + ((Account)acc).getBalance()); } } } class Account implements Comparable{ private String name; private double balance; private String accID; public double getBalance() { return balance;} public String getID() { return accID; } public String getName() { return name; } public Account(String accID, String accountName, double amount) { this.accID = accID; name = accountName; if (amount < 0) balance = 0; else balance = Math.round(amount); } public Account(String accID, String accountName) { } public Account(String accID) { } public void deposit(double amount) { } public int compareTo(Object o){ //override the interface method, compareTo, for the object, Account. if (getBalance() < ((Account) o ).getBalance()) return -1; if (getBalance() > ((Account) o ).getBalance()) return 1; return 0; } }
5c38a56d4ffdb54e65129c2a270d5844bcaf96b0
984167a4c294b637278992b86af7489289fc9450
/RTextLang/src/main/java/org/fife/rsta/ac/xml/tree/XmlOutlineTree.java
4747bf4e5ba965f0fffdfeb88fdf9cb3a4651be1
[]
no_license
Averroes/RText4SikuliX
2a947e0e8b15d5613a4caa7f986f6839baf10111
dc185b3040b8eb9ce66d36725993b9ba8ad8b50d
refs/heads/master
2021-01-21T00:17:45.508436
2014-02-17T09:01:57
2014-02-17T09:01:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,578
java
/* * 04/07/2012 * * Copyright (C) 2012 Robert Futrell * robert_futrell at users.sourceforge.net * http://fifesoft.com/rsyntaxtextarea * * This library is distributed under a modified BSD license. See the included * RSTALanguageSupport.License.txt file for details. */ package org.fife.rsta.ac.xml.tree; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.BorderFactory; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import org.fife.rsta.ac.AbstractSourceTree; import org.fife.rsta.ac.LanguageSupport; import org.fife.rsta.ac.LanguageSupportFactory; import org.fife.rsta.ac.xml.XmlLanguageSupport; import org.fife.rsta.ac.xml.XmlParser; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; /** * A tree view showing the outline of XML, similar to the "Outline" view in * Eclipse. It also uses Eclipse's icons, just like the rest of this code * completion library.<p> * * You can get this tree automatically updating in response to edits in an * <code>RSyntaxTextArea</code> with {@link XmlLanguageSupport} installed by * calling {@link #listenTo(RSyntaxTextArea)}. Note that an instance of this * class can only listen to a single editor at a time, so if your application * contains multiple instances of RSyntaxTextArea, you'll either need a separate * <code>XmlOutlineTree</code> for each one, or call <code>uninstall()</code> * and <code>listenTo(RSyntaxTextArea)</code> each time a new RSTA receives * focus. * * @author Robert Futrell * @version 1.0 */ public class XmlOutlineTree extends AbstractSourceTree { private XmlParser parser; private XmlEditorListener listener; private DefaultTreeModel model; private XmlTreeCellRenderer xmlTreeCellRenderer; /** * Constructor. The tree created will not have its elements sorted * alphabetically. */ public XmlOutlineTree() { this(false); } /** * Constructor. * * @param sorted Whether the tree should sort its elements alphabetically. * Note that outline trees will likely group nodes by type before * sorting (i.e. methods will be sorted in one group, fields in * another group, etc.). */ public XmlOutlineTree(boolean sorted) { setSorted(sorted); setBorder(BorderFactory.createEmptyBorder(0,8,0,8)); setRootVisible(false); xmlTreeCellRenderer = new XmlTreeCellRenderer(); setCellRenderer(xmlTreeCellRenderer); model = new DefaultTreeModel(new XmlTreeNode("Nothing")); setModel(model); listener = new XmlEditorListener(); addTreeSelectionListener(listener); } /** * Refreshes listeners on the text area when its syntax style changes. */ private void checkForXmlParsing() { // Remove possible listener on old Java parser (in case they're just // changing syntax style AWAY from Java) if (parser!=null) { parser.removePropertyChangeListener(XmlParser.PROPERTY_AST, listener); parser = null; } // Get the Java language support (shared by all RSTA instances editing // Java that were registered with the LanguageSupportFactory). LanguageSupportFactory lsf = LanguageSupportFactory.get(); LanguageSupport support = lsf.getSupportFor(SyntaxConstants. SYNTAX_STYLE_XML); XmlLanguageSupport xls = (XmlLanguageSupport)support; // Listen for re-parsing of the editor, and update the tree accordingly parser = xls.getParser(textArea); if (parser!=null) { // Should always be true parser.addPropertyChangeListener(XmlParser.PROPERTY_AST, listener); // Populate with any already-existing AST. XmlTreeNode root = parser.getAst(); update(root); } else { update((XmlTreeNode)null); // Clear the tree } } //static int expandCount; /** * {@inheritDoc} */ @Override public void expandInitialNodes() { //long start = System.currentTimeMillis(); //expandCount = 0; fastExpandAll(new TreePath(getModel().getRoot()), true); //long end2 = System.currentTimeMillis(); //System.out.println("Expand all all: " + ((end2-start)/1000f) + " seconds (" + expandCount + ")"); //System.out.println("--- " + getRowCount()); } private void gotoElementAtPath(TreePath path) { Object node = path.getLastPathComponent(); if (node instanceof XmlTreeNode) { XmlTreeNode xtn = (XmlTreeNode)node; textArea.select(xtn.getStartOffset(), xtn.getEndOffset()); } } /** * {@inheritDoc} */ @Override public boolean gotoSelectedElement() { TreePath path = getLeadSelectionPath();//e.getNewLeadSelectionPath(); if (path != null) { gotoElementAtPath(path); return true; } return false; } /** * {@inheritDoc} */ @Override public void listenTo(RSyntaxTextArea textArea) { if (this.textArea!=null) { uninstall(); } // Nothing new to listen to if (textArea==null) { return; } // Listen for future language changes in the text editor this.textArea = textArea; textArea.addPropertyChangeListener( RSyntaxTextArea.SYNTAX_STYLE_PROPERTY, listener); checkForXmlParsing(); } /** * {@inheritDoc} */ @Override public void uninstall() { if (parser!=null) { parser.removePropertyChangeListener(XmlParser.PROPERTY_AST, listener); parser = null; } if (textArea!=null) { textArea.removePropertyChangeListener( RSyntaxTextArea.SYNTAX_STYLE_PROPERTY, listener); textArea = null; } } private void update(XmlTreeNode root) { if (root!=null) { root = (XmlTreeNode)root.cloneWithChildren(); } model.setRoot(root); if (root!=null) { root.setSorted(isSorted()); } refresh(); } /** * Overridden to update the cell renderer */ @Override public void updateUI() { super.updateUI(); xmlTreeCellRenderer = new XmlTreeCellRenderer(); setCellRenderer(xmlTreeCellRenderer); // So it picks up new LAF's properties } /** * Listens for events this tree is interested in (events in the associated * editor, for example), as well as events in this tree. */ private class XmlEditorListener implements PropertyChangeListener, TreeSelectionListener { /** * Called whenever the text area's syntax style changes, as well as * when it is re-parsed. */ public void propertyChange(PropertyChangeEvent e) { String name = e.getPropertyName(); // If the text area is changing the syntax style it is editing if (RSyntaxTextArea.SYNTAX_STYLE_PROPERTY.equals(name)) { checkForXmlParsing(); } else if (XmlParser.PROPERTY_AST.equals(name)) { XmlTreeNode root = (XmlTreeNode)e.getNewValue(); update(root); } } /** * Selects the corresponding element in the text editor when a user * clicks on a node in this tree. */ public void valueChanged(TreeSelectionEvent e) { if (getGotoSelectedElementOnClick()) { //gotoSelectedElement(); TreePath newPath = e.getNewLeadSelectionPath(); if (newPath!=null) { gotoElementAtPath(newPath); } } } } /** * Whenever the caret moves in the listened-to RSyntaxTextArea, this * class ensures that the XML element containing the caret position is * focused in the tree view after a small delay. */ /* * TODO: Make me work for any LanguageSupport (don't synchronize if waiting on * a pending parse) and pull me out and make me available for all languages. private class Synchronizer implements CaretListener, ActionListener { private Timer timer; private int dot; public Synchronizer() { timer = new Timer(650, this); timer.setRepeats(false); } public void actionPerformed(ActionEvent e) { recursivelyCheck(root); //System.out.println("Here"); } public void caretUpdate(CaretEvent e) { this.dot = e.getDot(); timer.restart(); } private boolean recursivelyCheck(XmlTreeNode node) { if (node.containsOffset(dot)) { for (int i=0; i<node.getChildCount(); i++) { XmlTreeNode child = (XmlTreeNode)node.getChildAt(i); if (recursivelyCheck(child)) { return true; } } // None of the children contain the offset, must this guy node.selectInTree(); return true; } return false; } } */ }
68b3ed003cdc00df5e58418728dfffe49cdc4278
001fa28efc1cfda612f1e9d5b4113622284b5bf8
/tests_no_procyon/hanoi/test_0_orig_no_procyon/Main.java
c3dda88752aeed68ea4246bba41bc97e53ead75b
[]
no_license
cragkhit/es_exp
eaa72b6bde3656977ea9454593ebd12a85a5023c
dc9f29045d0bcdba79cdf5cb48bababb8aa9adba
refs/heads/master
2016-08-11T15:19:18.709889
2016-03-27T02:15:01
2016-03-27T02:15:01
51,704,609
0
0
null
null
null
null
UTF-8
Java
false
false
5,277
java
import java.io.Reader; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Stack; // // Decompiled by Procyon v0.5.29 // class Main { static int movecount; public static Stack A; public static Stack B; public static Stack C; static int countA; static int countB; static int countC; public static void Solve2DiscsTOH(final Stack stack, final Stack stack2, final Stack stack3) { stack2.push(stack.pop()); ++Main.movecount; PrintStacks(); stack3.push(stack.pop()); ++Main.movecount; PrintStacks(); stack3.push(stack2.pop()); ++Main.movecount; PrintStacks(); } public static int SolveTOH(int n, final Stack stack, final Stack stack2, final Stack stack3) { if (n <= 4) { if (n % 2 == 0) { Solve2DiscsTOH(stack, stack2, stack3); if (--n == 1) { return 1; } stack2.push(stack.pop()); ++Main.movecount; PrintStacks(); Solve2DiscsTOH(stack3, stack, stack2); stack3.push(stack.pop()); ++Main.movecount; PrintStacks(); SolveTOH(n, stack2, stack, stack3); } else { if (n == 1) { return -1; } Solve2DiscsTOH(stack, stack3, stack2); --n; stack3.push(stack.pop()); ++Main.movecount; PrintStacks(); Solve2DiscsTOH(stack2, stack, stack3); } return 1; } if (n >= 5) { SolveTOH(n - 2, stack, stack2, stack3); stack2.push(stack.pop()); ++Main.movecount; PrintStacks(); SolveTOH(n - 2, stack3, stack, stack2); stack3.push(stack.pop()); ++Main.movecount; PrintStacks(); SolveTOH(n - 1, stack2, stack, stack3); } return 1; } public static void PrintStacks() { if (Main.countA != Main.A.size() || Main.countB != Main.B.size() || Main.countC != Main.C.size()) { final int n = Main.A.size() - Main.countA; final int n2 = Main.B.size() - Main.countB; final int n3 = Main.C.size() - Main.countC; if (n == 1) { if (n2 == -1) { System.out.print("Move Disc " + Main.A.peek() + " From B To A"); } else { System.out.print("Move Disc " + Main.A.peek() + " From C To A"); } } else if (n2 == 1) { if (n == -1) { System.out.print("Move Disc " + Main.B.peek() + " From A To B"); } else { System.out.print("Move Disc " + Main.B.peek() + " From C To B"); } } else if (n == -1) { System.out.print("Move Disc " + Main.C.peek() + " From A To C"); } else { System.out.print("Move Disc " + Main.C.peek() + " From B To C"); } Main.countA = Main.A.size(); Main.countB = Main.B.size(); Main.countC = Main.C.size(); System.out.println(); } PrintStack(Main.A); System.out.print(" , "); PrintStack(Main.B); System.out.print(" , "); PrintStack(Main.C); System.out.print(" , "); } public static void PrintStack(final Stack stack) { System.out.print(stack.toString()); } public static void main(final String[] array) { try { while (true) { System.out.print("\nEnter the number of discs (-1 to exit): "); final String line = new BufferedReader(new InputStreamReader(System.in)).readLine(); Main.movecount = 0; final int int1 = Integer.parseInt(line); if (int1 == -1) { break; } if (int1 <= 1 || int1 >= 10) { System.out.println("Enter between 2 - 9"); } else { for (int i = int1; i >= 1; --i) { Main.A.push(i); } Main.countA = Main.A.size(); Main.countB = Main.B.size(); Main.countC = Main.C.size(); PrintStacks(); SolveTOH(int1, Main.A, Main.B, Main.C); System.out.println("Total Moves = " + Main.movecount); while (Main.C.size() > 0) { Main.C.pop(); } } } System.out.println("Good Bye!"); } catch (Exception ex) { ex.printStackTrace(); } } static { Main.movecount = 0; Main.A = new Stack(); Main.B = new Stack(); Main.C = new Stack(); Main.countA = 0; Main.countB = 0; Main.countC = 0; } }
05800ca86f76e7db35279a5578679c1554d180a1
3e3904e6990bb078bece18d5deec130f9076d1fd
/study/Cryptography/trunk/src/com/unit7/study/cryptography/labs/lab2/CoderInfo.java
9c654dd56b20e1d05d6e976cc6d8ce628df94f98
[]
no_license
unit7-0/com-unit7
6f5d27484531522940d8a8ffac3546f9b33f1e63
6dbcb8536988362774adddee5083ddb65fedbe25
refs/heads/master
2020-04-05T22:46:31.309842
2014-03-26T02:23:03
2014-03-26T02:23:03
32,127,343
0
0
null
null
null
null
UTF-8
Java
false
false
246
java
package com.unit7.study.cryptography.labs.lab2; public interface CoderInfo { Object getEncoded(int m); int getDecoded(Object coded); public String getAlgorithm(); public Object clone() throws CloneNotSupportedException; }
[ "vialurt@8dae9c98-9cfa-19cd-7016-99b4da0f52a5" ]
vialurt@8dae9c98-9cfa-19cd-7016-99b4da0f52a5
74017bc657fa7adfb9a20f1ffb262f5b700eef8b
313897d533e984053c2cc52b482b2cb70ca43c92
/src/com/zengbobobase/demo/TWWebChromeClient.java
b8131df037d3bd6f34fe3a75f11bf61a9365cbd6
[]
no_license
zengbobo0805/zengbobobaseDemo
0d34de7f9eea8f80ca69e8ec1d12e3de9cf1ec92
4a787a9cdb8f29956bd847af503504a35b49f4d5
refs/heads/master
2021-01-17T00:26:11.236125
2016-11-16T10:13:15
2016-11-16T10:13:15
17,888,852
0
0
null
null
null
null
UTF-8
Java
false
false
6,175
java
package com.zengbobobase.demo; import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.os.Message; import android.view.View; import android.webkit.ConsoleMessage; import android.webkit.GeolocationPermissions.Callback; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebStorage.QuotaUpdater; import android.webkit.WebView; public class TWWebChromeClient extends WebChromeClient { private void p(String str){ S.p("webview TWWebChromeClient"+str); } @Override public void onProgressChanged(WebView view, int newProgress) { p(" onProgressChanged newProgress:"+newProgress); // TODO Auto-generated method stub super.onProgressChanged(view, newProgress); } @Override public void onReceivedTitle(WebView view, String title) { p(" onReceivedTitle title:"+title); // TODO Auto-generated method stub super.onReceivedTitle(view, title); } @Override public void onReceivedIcon(WebView view, Bitmap icon) { p(" onReceivedIcon "); // TODO Auto-generated method stub super.onReceivedIcon(view, icon); } @Override public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { p(" onReceivedTouchIconUrl url:"+url); // TODO Auto-generated method stub super.onReceivedTouchIconUrl(view, url, precomposed); } @Override public void onShowCustomView(View view, CustomViewCallback callback) { // TODO Auto-generated method stub p(" onShowCustomView :"); super.onShowCustomView(view, callback); } @SuppressLint("NewApi") @Override @Deprecated public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { p(" onShowCustomView -@Deprecated--:"); // TODO Auto-generated method stub super.onShowCustomView(view, requestedOrientation, callback); } @Override public void onHideCustomView() { p(" onHideCustomView :"); // TODO Auto-generated method stub super.onHideCustomView(); } @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { p(" onCreateWindow :"); // TODO Auto-generated method stub return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } @Override public void onRequestFocus(WebView view) { p(" onRequestFocus :"); // TODO Auto-generated method stub super.onRequestFocus(view); } @Override public void onCloseWindow(WebView window) { p(" onCloseWindow :"); // TODO Auto-generated method stub super.onCloseWindow(window); } @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { p(" onJsAlert url:"+url+",message:"+message); // TODO Auto-generated method stub return super.onJsAlert(view, url, message, result); } @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { // TODO Auto-generated method stub p(" onJsConfirm url:"+url+",message:"+message); return super.onJsConfirm(view, url, message, result); } @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { // TODO Auto-generated method stub p(" onJsPrompt url:"+url+",message:"+message+",defaultValue:"+defaultValue); return super.onJsPrompt(view, url, message, defaultValue, result); } @Override public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) { // TODO Auto-generated method stub p(" onJsBeforeUnload url:"+url+",message:"+message); return super.onJsBeforeUnload(view, url, message, result); } @Override public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { // TODO Auto-generated method stub p(" onGeolocationPermissionsShowPrompt origin:"+origin); super.onGeolocationPermissionsShowPrompt(origin, callback); } @Override public void onGeolocationPermissionsHidePrompt() { // TODO Auto-generated method stub p(" onGeolocationPermissionsHidePrompt :"); super.onGeolocationPermissionsHidePrompt(); } @Override public boolean onJsTimeout() { // TODO Auto-generated method stub p(" onJsTimeout :"); return super.onJsTimeout(); } @Override @Deprecated public void onConsoleMessage(String message, int lineNumber, String sourceID) { // TODO Auto-generated method stub p(" onConsoleMessage message:"+message+",lineNumber:"+lineNumber+",sourceID:"+sourceID); super.onConsoleMessage(message, lineNumber, sourceID); } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { // TODO Auto-generated method stub p(" onConsoleMessage :"); return super.onConsoleMessage(consoleMessage); } @Override public Bitmap getDefaultVideoPoster() { // TODO Auto-generated method stub p(" getDefaultVideoPoster :"); return super.getDefaultVideoPoster(); } @Override public View getVideoLoadingProgressView() { // TODO Auto-generated method stub p(" getVideoLoadingProgressView :"); return super.getVideoLoadingProgressView(); } @Override public void getVisitedHistory(ValueCallback<String[]> callback) { // TODO Auto-generated method stub p(" getVisitedHistory :"); super.getVisitedHistory(callback); } @Override @Deprecated public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) { // TODO Auto-generated method stub p(" onExceededDatabaseQuota :"); super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); } @Override @Deprecated public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) { // TODO Auto-generated method stub p(" onReachedMaxAppCacheSize :"); super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); } }
c849615cf2f64daa910870d63569eba855471026
3a76a7fd19e2f95328a3bfed09ef8498e27dfc35
/springboot_인프런 백기선/springboot04/src/test/java/com/example/springboot04/BookControllerTest.java
2d27d260b06ef8a95426bbef6dd81b784dee4faf
[]
no_license
kys4548/2020_Simple_Web_Project
204dcd19a09c3c72be3de7819b56093ebcda6638
8e068af2c1ad0893e0fa8f7a2b6cbfedf218f9f1
refs/heads/master
2022-12-24T02:24:47.402963
2020-11-17T15:16:22
2020-11-17T15:16:22
245,647,907
0
0
null
2022-12-16T01:03:00
2020-03-07T14:31:52
Java
UTF-8
Java
false
false
602
java
package com.example.springboot04; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.junit.jupiter.api.Assertions.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @WebMvcTest class BookControllerTest { @Autowired MockMvc mockMvck; }
9399a8b0981eb3998bccfa99532d75c3a86801d3
072216667ef59e11cf4994220ea1594538db10a0
/googleplay/com/google/android/finsky/billing/InstrumentFlow.java
c07bcf2348ff7543821179b92391dd0f0892791f
[]
no_license
jackTang11/REMIUI
896037b74e90f64e6f7d8ddfda6f3731a8db6a74
48d65600a1b04931a510e1f036e58356af1531c0
refs/heads/master
2021-01-18T05:43:37.754113
2015-07-03T04:01:06
2015-07-03T04:01:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
829
java
package com.google.android.finsky.billing; import android.os.Bundle; import com.google.android.finsky.protos.BuyInstruments.UpdateInstrumentResponse; public abstract class InstrumentFlow extends BillingFlow { public InstrumentFlow(BillingFlowContext billingFlowContext, BillingFlowListener listener, Bundle parameters) { super(billingFlowContext, listener, parameters); } protected void finishWithUpdateInstrumentResponse(UpdateInstrumentResponse response) { Bundle result = new Bundle(); if (response.hasInstrumentId) { result.putString("instrument_id", response.instrumentId); } if (response.redeemedOffer != null) { result.putString("redeemed_offer_message_html", response.redeemedOffer.descriptionHtml); } finish(result); } }
ac829955a951e2d6b7f7c5c3e0f17cc9cf5b5d44
73721ac441b25d17bfcec5ffe368089050114020
/mps-dates/languages/dates/source_gen/jetbrains/mps/baseLanguage/dates/behavior/DateTimePlusPeriodOperation_BehaviorDescriptor.java
2846c40931b6608ccea22230a5fcb85d199fd070
[]
no_license
JetBrains/MPS-Contrib
c7fa7ce6892f79f36b74cc3157ff992129c1a10a
6bb663e130842c3649bc03fecfb1436db95b9ddb
refs/heads/master
2023-05-29T09:43:05.356423
2023-03-06T12:52:56
2023-03-06T12:52:56
10,595,762
3
5
null
null
null
null
UTF-8
Java
false
false
454
java
package jetbrains.mps.baseLanguage.dates.behavior; /*Generated by MPS */ import jetbrains.mps.baseLanguage.behavior.Expression_BehaviorDescriptor; public class DateTimePlusPeriodOperation_BehaviorDescriptor extends Expression_BehaviorDescriptor { public DateTimePlusPeriodOperation_BehaviorDescriptor() { } @Override public String getConceptFqName() { return "jetbrains.mps.baseLanguage.dates.structure.DateTimePlusPeriodOperation"; } }
11a630bc627f10ac8140022f36acda7f66fac16f
c39ed5a05ba4c0e94147e4c319f846c43b8f494f
/src/com/bean/Bill.java
809e6c36678bfa1ca7c39aeb4774b61007702123
[]
no_license
hui1209/shop
802a5cef93a0056d5dc6c3ac269f832fb7d77359
11599c9908736d704cb877aef4f61e411d391121
refs/heads/main
2023-06-12T19:59:36.006723
2021-07-09T02:31:41
2021-07-09T02:31:41
384,289,851
0
0
null
2021-07-09T02:35:12
2021-07-09T01:34:04
Java
UTF-8
Java
false
false
2,789
java
package com.bean; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * �˵�ʵ���� * @author asuna * */ public class Bill implements Serializable { private Integer id; private Integer money; private String unti; private Integer number; private String name; private String detail; private String supplier; private Integer payment; private Date time; /* * 无参构造 * */ public Bill() { } /* * 主键构造 * */ public Bill(Integer id) { this.id = id; } /* * 有参构造 * */ public Bill(Integer id, Integer money, String unti, Integer number, String name, String detail, String supplier, Integer payment, String time) { this.id = id; this.money = money; this.unti = unti; this.number = number; this.name = name; this.detail = detail; this.supplier = supplier; this.payment = payment; setTime(time); } public Bill(Integer id, Integer money, String unti, Integer number, String name, String detail, String supplier, Integer payment, Date time) { this.id = id; this.money = money; this.unti = unti; this.number = number; this.name = name; this.detail = detail; this.supplier = supplier; this.payment = payment; this.time = time; } @Override public String toString() { return "Bill [id=" + id + ", money=" + money + ", unti=" + unti + ", number=" + number + ", name=" + name + ", detail=" + detail + ", supplier=" + supplier + ", payment=" + payment + ", time=" + time + "]"; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getMoney() { return money; } public void setMoney(Integer money) { this.money = money; } public String getUnti() { return unti; } public void setUnti(String unti) { this.unti = unti; } public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public String getSupplier() { return supplier; } public void setSupplier(String supplier) { this.supplier = supplier; } public Integer getPayment() { return payment; } public void setPayment(Integer payment) { this.payment = payment; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public void setTime(String time) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { this.time = format.parse(time); } catch (ParseException e) { this.time = new Date(); } } }
78a2bf009d4f5ef058ca8bd588d63e5c759dc025
a8350a7f2e9c9fb358ae5d042173b097f90770ed
/picture_library/src/main/java/com/yuanfei/picture_lib/widget/longimage/SubsamplingScaleImageView.java
b33dd37dffb985a7698351a4f1b15597a1137156
[]
no_license
flyMountain/SelectPicture
0bd96befa5aac6efd4e3daf9e652ca013d2f8e4d
e9f916ed36be08535891f01c01c918f735d4859d
refs/heads/master
2021-04-06T07:32:37.679285
2018-03-12T02:34:20
2018-03-12T02:34:20
124,819,817
0
0
null
null
null
null
UTF-8
Java
false
false
130,052
java
/* Copyright 2013-2015 David Morrissey Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.yuanfei.picture_lib.widget.longimage; import android.content.ContentResolver; import android.content.Context; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.media.ExifInterface; import android.net.Uri; import android.os.AsyncTask; import android.os.Build.VERSION; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.support.annotation.AnyThread; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.util.TypedValue; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.ViewParent; import com.yuanfei.picture_lib.R; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.Executor; /** * Displays an image subsampled as necessary to avoid loading too much image data into memory. After a pinch to zoom in, * a set of image tiles subsampled at higher resolution are loaded and displayed over the base layer. During pinch and * zoom, tiles off screen or higher/lower resolution than required are discarded from memory. * * Tiles are no larger than the max supported bitmap size, so with large images tiling may be used even when zoomed out. * * v prefixes - coordinates, translations and distances measured in screen (view) pixels * s prefixes - coordinates, translations and distances measured in source image pixels (scaled) */ @SuppressWarnings("unused") public class SubsamplingScaleImageView extends View { private static final String TAG = SubsamplingScaleImageView.class.getSimpleName(); /** Attempt to use EXIF information on the image to rotate it. Works for external files only. */ public static final int ORIENTATION_USE_EXIF = -1; /** Display the image file in its native orientation. */ public static final int ORIENTATION_0 = 0; /** Rotate the image 90 degrees clockwise. */ public static final int ORIENTATION_90 = 90; /** Rotate the image 180 degrees. */ public static final int ORIENTATION_180 = 180; /** Rotate the image 270 degrees clockwise. */ public static final int ORIENTATION_270 = 270; private static final List<Integer> VALID_ORIENTATIONS = Arrays.asList(ORIENTATION_0, ORIENTATION_90, ORIENTATION_180, ORIENTATION_270, ORIENTATION_USE_EXIF); /** During zoom animation, keep the point of the image that was tapped in the same place, and scale the image around it. */ public static final int ZOOM_FOCUS_FIXED = 1; /** During zoom animation, move the point of the image that was tapped to the center of the screen. */ public static final int ZOOM_FOCUS_CENTER = 2; /** Zoom in to and center the tapped point immediately without animating. */ public static final int ZOOM_FOCUS_CENTER_IMMEDIATE = 3; private static final List<Integer> VALID_ZOOM_STYLES = Arrays.asList(ZOOM_FOCUS_FIXED, ZOOM_FOCUS_CENTER, ZOOM_FOCUS_CENTER_IMMEDIATE); /** Quadratic ease out. Not recommended for scale animation, but good for panning. */ public static final int EASE_OUT_QUAD = 1; /** Quadratic ease in and out. */ public static final int EASE_IN_OUT_QUAD = 2; private static final List<Integer> VALID_EASING_STYLES = Arrays.asList(EASE_IN_OUT_QUAD, EASE_OUT_QUAD); /** Don't allow the image to be panned off screen. As much of the image as possible is always displayed, centered in the view when it is smaller. This is the best option for galleries. */ public static final int PAN_LIMIT_INSIDE = 1; /** Allows the image to be panned until it is just off screen, but no further. The edge of the image will stop when it is flush with the screen edge. */ public static final int PAN_LIMIT_OUTSIDE = 2; /** Allows the image to be panned until a corner reaches the center of the screen but no further. Useful when you want to pan any spot on the image to the exact center of the screen. */ public static final int PAN_LIMIT_CENTER = 3; private static final List<Integer> VALID_PAN_LIMITS = Arrays.asList(PAN_LIMIT_INSIDE, PAN_LIMIT_OUTSIDE, PAN_LIMIT_CENTER); /** Scale the image so that both dimensions of the image will be equal to or less than the corresponding dimension of the view. The image is then centered in the view. This is the default behaviour and best for galleries. */ public static final int SCALE_TYPE_CENTER_INSIDE = 1; /** Scale the image uniformly so that both dimensions of the image will be equal to or larger than the corresponding dimension of the view. The image is then centered in the view. */ public static final int SCALE_TYPE_CENTER_CROP = 2; /** Scale the image so that both dimensions of the image will be equal to or less than the maxScale and equal to or larger than minScale. The image is then centered in the view. */ public static final int SCALE_TYPE_CUSTOM = 3; private static final List<Integer> VALID_SCALE_TYPES = Arrays.asList(SCALE_TYPE_CENTER_CROP, SCALE_TYPE_CENTER_INSIDE, SCALE_TYPE_CUSTOM); /** State change originated from animation. */ public static final int ORIGIN_ANIM = 1; /** State change originated from touch gesture. */ public static final int ORIGIN_TOUCH = 2; /** State change originated from a fling momentum anim. */ public static final int ORIGIN_FLING = 3; /** State change originated from a double tap zoom anim. */ public static final int ORIGIN_DOUBLE_TAP_ZOOM = 4; // Bitmap (preview or full image) private Bitmap bitmap; // Whether the bitmap is a preview image private boolean bitmapIsPreview; // Specifies if a cache handler is also referencing the bitmap. Do not recycle if so. private boolean bitmapIsCached; // Uri of full size image private Uri uri; // Sample size used to display the whole image when fully zoomed out private int fullImageSampleSize; // Map of zoom level to tile grid private Map<Integer, List<Tile>> tileMap; // Overlay tile boundaries and other info private boolean debug; // Image orientation setting private int orientation = ORIENTATION_0; // Max scale allowed (prevent infinite zoom) private float maxScale = 2F; // Min scale allowed (prevent infinite zoom) private float minScale = minScale(); // Density to reach before loading higher resolution tiles private int minimumTileDpi = -1; // Pan limiting style private int panLimit = PAN_LIMIT_INSIDE; // Minimum scale type private int minimumScaleType = SCALE_TYPE_CENTER_INSIDE; // overrides for the dimensions of the generated tiles public static int TILE_SIZE_AUTO = Integer.MAX_VALUE; private int maxTileWidth = TILE_SIZE_AUTO; private int maxTileHeight = TILE_SIZE_AUTO; // Whether to use the thread pool executor to load tiles private boolean parallelLoadingEnabled; // Gesture detection settings private boolean panEnabled = true; private boolean zoomEnabled = true; private boolean quickScaleEnabled = true; // Double tap zoom behaviour private float doubleTapZoomScale = 1F; private int doubleTapZoomStyle = ZOOM_FOCUS_FIXED; private int doubleTapZoomDuration = 500; // Current scale and scale at start of zoom private float scale; private float scaleStart; // Screen coordinate of top-left corner of source image private PointF vTranslate; private PointF vTranslateStart; private PointF vTranslateBefore; // Source coordinate to center on, used when new position is set externally before view is ready private Float pendingScale; private PointF sPendingCenter; private PointF sRequestedCenter; // Source image dimensions and orientation - dimensions relate to the unrotated image private int sWidth; private int sHeight; private int sOrientation; private Rect sRegion; private Rect pRegion; // Is two-finger zooming in progress private boolean isZooming; // Is one-finger panning in progress private boolean isPanning; // Is quick-scale gesture in progress private boolean isQuickScaling; // Max touches used in current gesture private int maxTouchCount; // Fling detector private GestureDetector detector; // Tile and image decoding private ImageRegionDecoder decoder; private final Object decoderLock = new Object(); private DecoderFactory<? extends ImageDecoder> bitmapDecoderFactory = new CompatDecoderFactory<ImageDecoder>(SkiaImageDecoder.class); private DecoderFactory<? extends ImageRegionDecoder> regionDecoderFactory = new CompatDecoderFactory<ImageRegionDecoder>(SkiaImageRegionDecoder.class); // Debug values private PointF vCenterStart; private float vDistStart; // Current quickscale state private final float quickScaleThreshold; private float quickScaleLastDistance; private boolean quickScaleMoved; private PointF quickScaleVLastPoint; private PointF quickScaleSCenter; private PointF quickScaleVStart; // Scale and center animation tracking private Anim anim; // Whether a ready notification has been sent to subclasses private boolean readySent; // Whether a base layer loaded notification has been sent to subclasses private boolean imageLoadedSent; // Event listener private OnImageEventListener onImageEventListener; // Scale and center listener private OnStateChangedListener onStateChangedListener; // Long click listener private OnLongClickListener onLongClickListener; // Long click handler private Handler handler; private static final int MESSAGE_LONG_CLICK = 1; // Paint objects created once and reused for efficiency private Paint bitmapPaint; private Paint debugPaint; private Paint tileBgPaint; // Volatile fields used to reduce object creation private ScaleAndTranslate satTemp; private Matrix matrix; private RectF sRect; private float[] srcArray = new float[8]; private float[] dstArray = new float[8]; //The logical density of the display private float density; public SubsamplingScaleImageView(Context context, AttributeSet attr) { super(context, attr); density = getResources().getDisplayMetrics().density; setMinimumDpi(160); setDoubleTapZoomDpi(160); setGestureDetector(context); this.handler = new Handler(new Handler.Callback() { public boolean handleMessage(Message message) { if (message.what == MESSAGE_LONG_CLICK && onLongClickListener != null) { maxTouchCount = 0; SubsamplingScaleImageView.super.setOnLongClickListener(onLongClickListener); performLongClick(); SubsamplingScaleImageView.super.setOnLongClickListener(null); } return true; } }); // Handle XML attributes if (attr != null) { TypedArray typedAttr = getContext().obtainStyledAttributes(attr, R.styleable.SubsamplingScaleImageView); if (typedAttr.hasValue(R.styleable.SubsamplingScaleImageView_assetName)) { String assetName = typedAttr.getString(R.styleable.SubsamplingScaleImageView_assetName); if (assetName != null && assetName.length() > 0) { setImage(ImageSource.asset(assetName).tilingEnabled()); } } if (typedAttr.hasValue(R.styleable.SubsamplingScaleImageView_src)) { int resId = typedAttr.getResourceId(R.styleable.SubsamplingScaleImageView_src, 0); if (resId > 0) { setImage(ImageSource.resource(resId).tilingEnabled()); } } if (typedAttr.hasValue(R.styleable.SubsamplingScaleImageView_panEnabled)) { setPanEnabled(typedAttr.getBoolean(R.styleable.SubsamplingScaleImageView_panEnabled, true)); } if (typedAttr.hasValue(R.styleable.SubsamplingScaleImageView_zoomEnabled)) { setZoomEnabled(typedAttr.getBoolean(R.styleable.SubsamplingScaleImageView_zoomEnabled, true)); } if (typedAttr.hasValue(R.styleable.SubsamplingScaleImageView_quickScaleEnabled)) { setQuickScaleEnabled(typedAttr.getBoolean(R.styleable.SubsamplingScaleImageView_quickScaleEnabled, true)); } if (typedAttr.hasValue(R.styleable.SubsamplingScaleImageView_tileBackgroundColor)) { setTileBackgroundColor(typedAttr.getColor(R.styleable.SubsamplingScaleImageView_tileBackgroundColor, Color.argb(0, 0, 0, 0))); } typedAttr.recycle(); } quickScaleThreshold = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, context.getResources().getDisplayMetrics()); } public SubsamplingScaleImageView(Context context) { this(context, null); } /** * Sets the image orientation. It's best to call this before setting the image file or asset, because it may waste * loading of tiles. However, this can be freely called at any time. */ public final void setOrientation(int orientation) { if (!VALID_ORIENTATIONS.contains(orientation)) { throw new IllegalArgumentException("Invalid orientation: " + orientation); } this.orientation = orientation; reset(false); invalidate(); requestLayout(); } /** * Set the image source from a bitmap, resource, asset, file or other URI. * @param imageSource Image source. */ public final void setImage(ImageSource imageSource) { setImage(imageSource, null, null); } /** * Set the image source from a bitmap, resource, asset, file or other URI, starting with a given orientation * setting, scale and center. This is the best method to use when you want scale and center to be restored * after screen orientation change; it avoids any redundant loading of tiles in the wrong orientation. * @param imageSource Image source. * @param state State to be restored. Nullable. */ public final void setImage(ImageSource imageSource, ImageViewState state) { setImage(imageSource, null, state); } /** * Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be * displayed until the full size image is loaded. * * You must declare the dimensions of the full size image by calling {@link ImageSource#dimensions(int, int)} * on the imageSource object. The preview source will be ignored if you don't provide dimensions, * and if you provide a bitmap for the full size image. * @param imageSource Image source. Dimensions must be declared. * @param previewSource Optional source for a preview image to be displayed and allow interaction while the full size image loads. */ public final void setImage(ImageSource imageSource, ImageSource previewSource) { setImage(imageSource, previewSource, null); } /** * Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be * displayed until the full size image is loaded, starting with a given orientation setting, scale and center. * This is the best method to use when you want scale and center to be restored after screen orientation change; * it avoids any redundant loading of tiles in the wrong orientation. * * You must declare the dimensions of the full size image by calling {@link ImageSource#dimensions(int, int)} * on the imageSource object. The preview source will be ignored if you don't provide dimensions, * and if you provide a bitmap for the full size image. * @param imageSource Image source. Dimensions must be declared. * @param previewSource Optional source for a preview image to be displayed and allow interaction while the full size image loads. * @param state State to be restored. Nullable. */ public final void setImage(ImageSource imageSource, ImageSource previewSource, ImageViewState state) { if (imageSource == null) { throw new NullPointerException("imageSource must not be null"); } reset(true); if (state != null) { restoreState(state); } if (previewSource != null) { if (imageSource.getBitmap() != null) { throw new IllegalArgumentException("Preview image cannot be used when a bitmap is provided for the main image"); } if (imageSource.getSWidth() <= 0 || imageSource.getSHeight() <= 0) { throw new IllegalArgumentException("Preview image cannot be used unless dimensions are provided for the main image"); } this.sWidth = imageSource.getSWidth(); this.sHeight = imageSource.getSHeight(); this.pRegion = previewSource.getSRegion(); if (previewSource.getBitmap() != null) { this.bitmapIsCached = previewSource.isCached(); onPreviewLoaded(previewSource.getBitmap()); } else { Uri uri = previewSource.getUri(); if (uri == null && previewSource.getResource() != null) { uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getContext().getPackageName() + "/" + previewSource.getResource()); } BitmapLoadTask task = new BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, true); execute(task); } } if (imageSource.getBitmap() != null && imageSource.getSRegion() != null) { onImageLoaded(Bitmap.createBitmap(imageSource.getBitmap(), imageSource.getSRegion().left, imageSource.getSRegion().top, imageSource.getSRegion().width(), imageSource.getSRegion().height()), ORIENTATION_0, false); } else if (imageSource.getBitmap() != null) { onImageLoaded(imageSource.getBitmap(), ORIENTATION_0, imageSource.isCached()); } else { sRegion = imageSource.getSRegion(); uri = imageSource.getUri(); if (uri == null && imageSource.getResource() != null) { uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getContext().getPackageName() + "/" + imageSource.getResource()); } if (imageSource.getTile() || sRegion != null) { // Load the bitmap using tile decoding. TilesInitTask task = new TilesInitTask(this, getContext(), regionDecoderFactory, uri); execute(task); } else { // Load the bitmap as a single image. BitmapLoadTask task = new BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, false); execute(task); } } } /** * Reset all state before setting/changing image or setting new rotation. */ private void reset(boolean newImage) { debug("reset newImage=" + newImage); scale = 0f; scaleStart = 0f; vTranslate = null; vTranslateStart = null; vTranslateBefore = null; pendingScale = 0f; sPendingCenter = null; sRequestedCenter = null; isZooming = false; isPanning = false; isQuickScaling = false; maxTouchCount = 0; fullImageSampleSize = 0; vCenterStart = null; vDistStart = 0; quickScaleLastDistance = 0f; quickScaleMoved = false; quickScaleSCenter = null; quickScaleVLastPoint = null; quickScaleVStart = null; anim = null; satTemp = null; matrix = null; sRect = null; if (newImage) { uri = null; if (decoder != null) { synchronized (decoderLock) { decoder.recycle(); decoder = null; } } if (bitmap != null && !bitmapIsCached) { bitmap.recycle(); } if (bitmap != null && bitmapIsCached && onImageEventListener != null) { onImageEventListener.onPreviewReleased(); } sWidth = 0; sHeight = 0; sOrientation = 0; sRegion = null; pRegion = null; readySent = false; imageLoadedSent = false; bitmap = null; bitmapIsPreview = false; bitmapIsCached = false; } if (tileMap != null) { for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { for (Tile tile : tileMapEntry.getValue()) { tile.visible = false; if (tile.bitmap != null) { tile.bitmap.recycle(); tile.bitmap = null; } } } tileMap = null; } setGestureDetector(getContext()); } private void setGestureDetector(final Context context) { this.detector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (panEnabled && readySent && vTranslate != null && e1 != null && e2 != null && (Math.abs(e1.getX() - e2.getX()) > 50 || Math.abs(e1.getY() - e2.getY()) > 50) && (Math.abs(velocityX) > 500 || Math.abs(velocityY) > 500) && !isZooming) { PointF vTranslateEnd = new PointF(vTranslate.x + (velocityX * 0.25f), vTranslate.y + (velocityY * 0.25f)); float sCenterXEnd = ((getWidth()/2) - vTranslateEnd.x)/scale; float sCenterYEnd = ((getHeight()/2) - vTranslateEnd.y)/scale; new AnimationBuilder(new PointF(sCenterXEnd, sCenterYEnd)).withEasing(EASE_OUT_QUAD).withPanLimited(false).withOrigin(ORIGIN_FLING).start(); return true; } return super.onFling(e1, e2, velocityX, velocityY); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { performClick(); return true; } @Override public boolean onDoubleTap(MotionEvent e) { if (zoomEnabled && readySent && vTranslate != null) { // Hacky solution for #15 - after a double tap the GestureDetector gets in a state // where the next fling is ignored, so here we replace it with a new one. setGestureDetector(context); if (quickScaleEnabled) { // Store quick scale params. This will become either a double tap zoom or a // quick scale depending on whether the user swipes. vCenterStart = new PointF(e.getX(), e.getY()); vTranslateStart = new PointF(vTranslate.x, vTranslate.y); scaleStart = scale; isQuickScaling = true; isZooming = true; quickScaleLastDistance = -1F; quickScaleSCenter = viewToSourceCoord(vCenterStart); quickScaleVStart = new PointF(e.getX(), e.getY()); quickScaleVLastPoint = new PointF(quickScaleSCenter.x, quickScaleSCenter.y); quickScaleMoved = false; // We need to get events in onTouchEvent after this. return false; } else { // Start double tap zoom animation. doubleTapZoom(viewToSourceCoord(new PointF(e.getX(), e.getY())), new PointF(e.getX(), e.getY())); return true; } } return super.onDoubleTapEvent(e); } }); } /** * On resize, preserve center and scale. Various behaviours are possible, override this method to use another. */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { debug("onSizeChanged %dx%d -> %dx%d", oldw, oldh, w, h); PointF sCenter = getCenter(); if (readySent && sCenter != null) { this.anim = null; this.pendingScale = scale; this.sPendingCenter = sCenter; } } /** * Measures the width and height of the view, preserving the aspect ratio of the image displayed if wrap_content is * used. The image will scale within this box, not resizing the view as it is zoomed. */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int parentWidth = MeasureSpec.getSize(widthMeasureSpec); int parentHeight = MeasureSpec.getSize(heightMeasureSpec); boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY; boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY; int width = parentWidth; int height = parentHeight; if (sWidth > 0 && sHeight > 0) { if (resizeWidth && resizeHeight) { width = sWidth(); height = sHeight(); } else if (resizeHeight) { height = (int)((((double)sHeight()/(double)sWidth()) * width)); } else if (resizeWidth) { width = (int)((((double)sWidth()/(double)sHeight()) * height)); } } width = Math.max(width, getSuggestedMinimumWidth()); height = Math.max(height, getSuggestedMinimumHeight()); setMeasuredDimension(width, height); } /** * Handle touch events. One finger pans, and two finger pinch and zoom plus panning. */ @Override public boolean onTouchEvent(@NonNull MotionEvent event) { // During non-interruptible anims, ignore all touch events if (anim != null && !anim.interruptible) { requestDisallowInterceptTouchEvent(true); return true; } else { if (anim != null && anim.listener != null) { try { anim.listener.onInterruptedByUser(); } catch (Exception e) { Log.w(TAG, "Error thrown by animation listener", e); } } anim = null; } // Abort if not ready if (vTranslate == null) { return true; } // Detect flings, taps and double taps if (!isQuickScaling && (detector == null || detector.onTouchEvent(event))) { isZooming = false; isPanning = false; maxTouchCount = 0; return true; } if (vTranslateStart == null) { vTranslateStart = new PointF(0, 0); } if (vTranslateBefore == null) { vTranslateBefore = new PointF(0, 0); } if (vCenterStart == null) { vCenterStart = new PointF(0, 0); } // Store current values so we can send an event if they change float scaleBefore = scale; vTranslateBefore.set(vTranslate); boolean handled = onTouchEventInternal(event); sendStateChanged(scaleBefore, vTranslateBefore, ORIGIN_TOUCH); return handled || super.onTouchEvent(event); } @SuppressWarnings("deprecation") private boolean onTouchEventInternal(@NonNull MotionEvent event) { int touchCount = event.getPointerCount(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_1_DOWN: case MotionEvent.ACTION_POINTER_2_DOWN: anim = null; requestDisallowInterceptTouchEvent(true); maxTouchCount = Math.max(maxTouchCount, touchCount); if (touchCount >= 2) { if (zoomEnabled) { // Start pinch to zoom. Calculate distance between touch points and center point of the pinch. float distance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); scaleStart = scale; vDistStart = distance; vTranslateStart.set(vTranslate.x, vTranslate.y); vCenterStart.set((event.getX(0) + event.getX(1))/2, (event.getY(0) + event.getY(1))/2); } else { // Abort all gestures on second touch maxTouchCount = 0; } // Cancel long click timer handler.removeMessages(MESSAGE_LONG_CLICK); } else if (!isQuickScaling) { // Start one-finger pan vTranslateStart.set(vTranslate.x, vTranslate.y); vCenterStart.set(event.getX(), event.getY()); // Start long click timer handler.sendEmptyMessageDelayed(MESSAGE_LONG_CLICK, 600); } return true; case MotionEvent.ACTION_MOVE: boolean consumed = false; if (maxTouchCount > 0) { if (touchCount >= 2) { // Calculate new distance between touch points, to scale and pan relative to start values. float vDistEnd = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); float vCenterEndX = (event.getX(0) + event.getX(1))/2; float vCenterEndY = (event.getY(0) + event.getY(1))/2; if (zoomEnabled && (distance(vCenterStart.x, vCenterEndX, vCenterStart.y, vCenterEndY) > 5 || Math.abs(vDistEnd - vDistStart) > 5 || isPanning)) { isZooming = true; isPanning = true; consumed = true; double previousScale = scale; scale = Math.min(maxScale, (vDistEnd / vDistStart) * scaleStart); if (scale <= minScale()) { // Minimum scale reached so don't pan. Adjust start settings so any expand will zoom in. vDistStart = vDistEnd; scaleStart = minScale(); vCenterStart.set(vCenterEndX, vCenterEndY); vTranslateStart.set(vTranslate); } else if (panEnabled) { // Translate to place the source image coordinate that was at the center of the pinch at the start // at the center of the pinch now, to give simultaneous pan + zoom. float vLeftStart = vCenterStart.x - vTranslateStart.x; float vTopStart = vCenterStart.y - vTranslateStart.y; float vLeftNow = vLeftStart * (scale/scaleStart); float vTopNow = vTopStart * (scale/scaleStart); vTranslate.x = vCenterEndX - vLeftNow; vTranslate.y = vCenterEndY - vTopNow; if ((previousScale * sHeight() < getHeight() && scale * sHeight() >= getHeight()) || (previousScale * sWidth() < getWidth() && scale * sWidth() >= getWidth())) { fitToBounds(true); vCenterStart.set(vCenterEndX, vCenterEndY); vTranslateStart.set(vTranslate); scaleStart = scale; vDistStart = vDistEnd; } } else if (sRequestedCenter != null) { // With a center specified from code, zoom around that point. vTranslate.x = (getWidth()/2) - (scale * sRequestedCenter.x); vTranslate.y = (getHeight()/2) - (scale * sRequestedCenter.y); } else { // With no requested center, scale around the image center. vTranslate.x = (getWidth()/2) - (scale * (sWidth()/2)); vTranslate.y = (getHeight()/2) - (scale * (sHeight()/2)); } fitToBounds(true); refreshRequiredTiles(false); } } else if (isQuickScaling) { // One finger zoom // Stole Google's Magical Formula™ to make sure it feels the exact same float dist = Math.abs(quickScaleVStart.y - event.getY()) * 2 + quickScaleThreshold; if (quickScaleLastDistance == -1f) { quickScaleLastDistance = dist; } boolean isUpwards = event.getY() > quickScaleVLastPoint.y; quickScaleVLastPoint.set(0, event.getY()); float spanDiff = Math.abs(1 - (dist / quickScaleLastDistance)) * 0.5f; if (spanDiff > 0.03f || quickScaleMoved) { quickScaleMoved = true; float multiplier = 1; if (quickScaleLastDistance > 0) { multiplier = isUpwards ? (1 + spanDiff) : (1 - spanDiff); } double previousScale = scale; scale = Math.max(minScale(), Math.min(maxScale, scale * multiplier)); if (panEnabled) { float vLeftStart = vCenterStart.x - vTranslateStart.x; float vTopStart = vCenterStart.y - vTranslateStart.y; float vLeftNow = vLeftStart * (scale/scaleStart); float vTopNow = vTopStart * (scale/scaleStart); vTranslate.x = vCenterStart.x - vLeftNow; vTranslate.y = vCenterStart.y - vTopNow; if ((previousScale * sHeight() < getHeight() && scale * sHeight() >= getHeight()) || (previousScale * sWidth() < getWidth() && scale * sWidth() >= getWidth())) { fitToBounds(true); vCenterStart.set(sourceToViewCoord(quickScaleSCenter)); vTranslateStart.set(vTranslate); scaleStart = scale; dist = 0; } } else if (sRequestedCenter != null) { // With a center specified from code, zoom around that point. vTranslate.x = (getWidth()/2) - (scale * sRequestedCenter.x); vTranslate.y = (getHeight()/2) - (scale * sRequestedCenter.y); } else { // With no requested center, scale around the image center. vTranslate.x = (getWidth()/2) - (scale * (sWidth()/2)); vTranslate.y = (getHeight()/2) - (scale * (sHeight()/2)); } } quickScaleLastDistance = dist; fitToBounds(true); refreshRequiredTiles(false); consumed = true; } else if (!isZooming) { // One finger pan - translate the image. We do this calculation even with pan disabled so click // and long click behaviour is preserved. float dx = Math.abs(event.getX() - vCenterStart.x); float dy = Math.abs(event.getY() - vCenterStart.y); //On the Samsung S6 long click event does not work, because the dx > 5 usually true float offset = density * 5; if (dx > offset || dy > offset || isPanning) { consumed = true; vTranslate.x = vTranslateStart.x + (event.getX() - vCenterStart.x); vTranslate.y = vTranslateStart.y + (event.getY() - vCenterStart.y); float lastX = vTranslate.x; float lastY = vTranslate.y; fitToBounds(true); boolean atXEdge = lastX != vTranslate.x; boolean atYEdge = lastY != vTranslate.y; boolean edgeXSwipe = atXEdge && dx > dy && !isPanning; boolean edgeYSwipe = atYEdge && dy > dx && !isPanning; boolean yPan = lastY == vTranslate.y && dy > offset * 3; if (!edgeXSwipe && !edgeYSwipe && (!atXEdge || !atYEdge || yPan || isPanning)) { isPanning = true; } else if (dx > offset || dy > offset) { // Haven't panned the image, and we're at the left or right edge. Switch to page swipe. maxTouchCount = 0; handler.removeMessages(MESSAGE_LONG_CLICK); requestDisallowInterceptTouchEvent(false); } if (!panEnabled) { vTranslate.x = vTranslateStart.x; vTranslate.y = vTranslateStart.y; requestDisallowInterceptTouchEvent(false); } refreshRequiredTiles(false); } } } if (consumed) { handler.removeMessages(MESSAGE_LONG_CLICK); invalidate(); return true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_POINTER_2_UP: handler.removeMessages(MESSAGE_LONG_CLICK); if (isQuickScaling) { isQuickScaling = false; if (!quickScaleMoved) { doubleTapZoom(quickScaleSCenter, vCenterStart); } } if (maxTouchCount > 0 && (isZooming || isPanning)) { if (isZooming && touchCount == 2) { // Convert from zoom to pan with remaining touch isPanning = true; vTranslateStart.set(vTranslate.x, vTranslate.y); if (event.getActionIndex() == 1) { vCenterStart.set(event.getX(0), event.getY(0)); } else { vCenterStart.set(event.getX(1), event.getY(1)); } } if (touchCount < 3) { // End zooming when only one touch point isZooming = false; } if (touchCount < 2) { // End panning when no touch points isPanning = false; maxTouchCount = 0; } // Trigger load of tiles now required refreshRequiredTiles(true); return true; } if (touchCount == 1) { isZooming = false; isPanning = false; maxTouchCount = 0; } return true; } return false; } private void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(disallowIntercept); } } /** * Double tap zoom handler triggered from gesture detector or on touch, depending on whether * quick scale is enabled. */ private void doubleTapZoom(PointF sCenter, PointF vFocus) { if (!panEnabled) { if (sRequestedCenter != null) { // With a center specified from code, zoom around that point. sCenter.x = sRequestedCenter.x; sCenter.y = sRequestedCenter.y; } else { // With no requested center, scale around the image center. sCenter.x = sWidth()/2; sCenter.y = sHeight()/2; } } float doubleTapZoomScale = Math.min(maxScale, SubsamplingScaleImageView.this.doubleTapZoomScale); boolean zoomIn = scale <= doubleTapZoomScale * 0.9; float targetScale = zoomIn ? doubleTapZoomScale : minScale(); if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER_IMMEDIATE) { setScaleAndCenter(targetScale, sCenter); } else if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER || !zoomIn || !panEnabled) { new AnimationBuilder(targetScale, sCenter).withInterruptible(false).withDuration(doubleTapZoomDuration).withOrigin(ORIGIN_DOUBLE_TAP_ZOOM).start(); } else if (doubleTapZoomStyle == ZOOM_FOCUS_FIXED) { new AnimationBuilder(targetScale, sCenter, vFocus).withInterruptible(false).withDuration(doubleTapZoomDuration).withOrigin(ORIGIN_DOUBLE_TAP_ZOOM).start(); } invalidate(); } /** * Draw method should not be called until the view has dimensions so the first calls are used as triggers to calculate * the scaling and tiling required. Once the view is setup, tiles are displayed as they are loaded. */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); createPaints(); // If image or view dimensions are not known yet, abort. if (sWidth == 0 || sHeight == 0 || getWidth() == 0 || getHeight() == 0) { return; } // When using tiles, on first render with no tile map ready, initialise it and kick off async base image loading. if (tileMap == null && decoder != null) { initialiseBaseLayer(getMaxBitmapDimensions(canvas)); } // If image has been loaded or supplied as a bitmap, onDraw may be the first time the view has // dimensions and therefore the first opportunity to set scale and translate. If this call returns // false there is nothing to be drawn so return immediately. if (!checkReady()) { return; } // Set scale and translate before draw. preDraw(); // If animating scale, calculate current scale and center with easing equations if (anim != null) { // Store current values so we can send an event if they change float scaleBefore = scale; if (vTranslateBefore == null) { vTranslateBefore = new PointF(0, 0); } vTranslateBefore.set(vTranslate); long scaleElapsed = System.currentTimeMillis() - anim.time; boolean finished = scaleElapsed > anim.duration; scaleElapsed = Math.min(scaleElapsed, anim.duration); scale = ease(anim.easing, scaleElapsed, anim.scaleStart, anim.scaleEnd - anim.scaleStart, anim.duration); // Apply required animation to the focal point float vFocusNowX = ease(anim.easing, scaleElapsed, anim.vFocusStart.x, anim.vFocusEnd.x - anim.vFocusStart.x, anim.duration); float vFocusNowY = ease(anim.easing, scaleElapsed, anim.vFocusStart.y, anim.vFocusEnd.y - anim.vFocusStart.y, anim.duration); // Find out where the focal point is at this scale and adjust its position to follow the animation path vTranslate.x -= sourceToViewX(anim.sCenterEnd.x) - vFocusNowX; vTranslate.y -= sourceToViewY(anim.sCenterEnd.y) - vFocusNowY; // For translate anims, showing the image non-centered is never allowed, for scaling anims it is during the animation. fitToBounds(finished || (anim.scaleStart == anim.scaleEnd)); sendStateChanged(scaleBefore, vTranslateBefore, anim.origin); refreshRequiredTiles(finished); if (finished) { if (anim.listener != null) { try { anim.listener.onComplete(); } catch (Exception e) { Log.w(TAG, "Error thrown by animation listener", e); } } anim = null; } invalidate(); } if (tileMap != null && isBaseLayerReady()) { // Optimum sample size for current scale int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize(scale)); // First check for missing tiles - if there are any we need the base layer underneath to avoid gaps boolean hasMissingTiles = false; for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { if (tileMapEntry.getKey() == sampleSize) { for (Tile tile : tileMapEntry.getValue()) { if (tile.visible && (tile.loading || tile.bitmap == null)) { hasMissingTiles = true; } } } } // Render all loaded tiles. LinkedHashMap used for bottom up rendering - lower res tiles underneath. for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { if (tileMapEntry.getKey() == sampleSize || hasMissingTiles) { for (Tile tile : tileMapEntry.getValue()) { sourceToViewRect(tile.sRect, tile.vRect); if (!tile.loading && tile.bitmap != null) { if (tileBgPaint != null) { canvas.drawRect(tile.vRect, tileBgPaint); } if (matrix == null) { matrix = new Matrix(); } matrix.reset(); setMatrixArray(srcArray, 0, 0, tile.bitmap.getWidth(), 0, tile.bitmap.getWidth(), tile.bitmap.getHeight(), 0, tile.bitmap.getHeight()); if (getRequiredRotation() == ORIENTATION_0) { setMatrixArray(dstArray, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom); } else if (getRequiredRotation() == ORIENTATION_90) { setMatrixArray(dstArray, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top); } else if (getRequiredRotation() == ORIENTATION_180) { setMatrixArray(dstArray, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top); } else if (getRequiredRotation() == ORIENTATION_270) { setMatrixArray(dstArray, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom); } matrix.setPolyToPoly(srcArray, 0, dstArray, 0, 4); canvas.drawBitmap(tile.bitmap, matrix, bitmapPaint); if (debug) { canvas.drawRect(tile.vRect, debugPaint); } } else if (tile.loading && debug) { canvas.drawText("LOADING", tile.vRect.left + 5, tile.vRect.top + 35, debugPaint); } if (tile.visible && debug) { canvas.drawText("ISS " + tile.sampleSize + " RECT " + tile.sRect.top + "," + tile.sRect.left + "," + tile.sRect.bottom + "," + tile.sRect.right, tile.vRect.left + 5, tile.vRect.top + 15, debugPaint); } } } } } else if (bitmap != null) { float xScale = scale, yScale = scale; if (bitmapIsPreview) { xScale = scale * ((float)sWidth/bitmap.getWidth()); yScale = scale * ((float)sHeight/bitmap.getHeight()); } if (matrix == null) { matrix = new Matrix(); } matrix.reset(); matrix.postScale(xScale, yScale); matrix.postRotate(getRequiredRotation()); matrix.postTranslate(vTranslate.x, vTranslate.y); if (getRequiredRotation() == ORIENTATION_180) { matrix.postTranslate(scale * sWidth, scale * sHeight); } else if (getRequiredRotation() == ORIENTATION_90) { matrix.postTranslate(scale * sHeight, 0); } else if (getRequiredRotation() == ORIENTATION_270) { matrix.postTranslate(0, scale * sWidth); } if (tileBgPaint != null) { if (sRect == null) { sRect = new RectF(); } sRect.set(0f, 0f, bitmapIsPreview ? bitmap.getWidth() : sWidth, bitmapIsPreview ? bitmap.getHeight() : sHeight); matrix.mapRect(sRect); canvas.drawRect(sRect, tileBgPaint); } canvas.drawBitmap(bitmap, matrix, bitmapPaint); } if (debug) { canvas.drawText("Scale: " + String.format(Locale.ENGLISH, "%.2f", scale), 5, 15, debugPaint); canvas.drawText("Translate: " + String.format(Locale.ENGLISH, "%.2f", vTranslate.x) + ":" + String.format(Locale.ENGLISH, "%.2f", vTranslate.y), 5, 35, debugPaint); PointF center = getCenter(); canvas.drawText("Source center: " + String.format(Locale.ENGLISH, "%.2f", center.x) + ":" + String.format(Locale.ENGLISH, "%.2f", center.y), 5, 55, debugPaint); debugPaint.setStrokeWidth(2f); if (anim != null) { PointF vCenterStart = sourceToViewCoord(anim.sCenterStart); PointF vCenterEndRequested = sourceToViewCoord(anim.sCenterEndRequested); PointF vCenterEnd = sourceToViewCoord(anim.sCenterEnd); canvas.drawCircle(vCenterStart.x, vCenterStart.y, 10, debugPaint); debugPaint.setColor(Color.RED); canvas.drawCircle(vCenterEndRequested.x, vCenterEndRequested.y, 20, debugPaint); debugPaint.setColor(Color.BLUE); canvas.drawCircle(vCenterEnd.x, vCenterEnd.y, 25, debugPaint); debugPaint.setColor(Color.CYAN); canvas.drawCircle(getWidth() / 2, getHeight() / 2, 30, debugPaint); } if (vCenterStart != null) { debugPaint.setColor(Color.RED); canvas.drawCircle(vCenterStart.x, vCenterStart.y, 20, debugPaint); } if (quickScaleSCenter != null) { debugPaint.setColor(Color.BLUE); canvas.drawCircle(sourceToViewX(quickScaleSCenter.x), sourceToViewY(quickScaleSCenter.y), 35, debugPaint); } if (quickScaleVStart != null) { debugPaint.setColor(Color.CYAN); canvas.drawCircle(quickScaleVStart.x, quickScaleVStart.y, 30, debugPaint); } debugPaint.setColor(Color.MAGENTA); debugPaint.setStrokeWidth(1f); } } /** * Helper method for setting the values of a tile matrix array. */ private void setMatrixArray(float[] array, float f0, float f1, float f2, float f3, float f4, float f5, float f6, float f7) { array[0] = f0; array[1] = f1; array[2] = f2; array[3] = f3; array[4] = f4; array[5] = f5; array[6] = f6; array[7] = f7; } /** * Checks whether the base layer of tiles or full size bitmap is ready. */ private boolean isBaseLayerReady() { if (bitmap != null && !bitmapIsPreview) { return true; } else if (tileMap != null) { boolean baseLayerReady = true; for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { if (tileMapEntry.getKey() == fullImageSampleSize) { for (Tile tile : tileMapEntry.getValue()) { if (tile.loading || tile.bitmap == null) { baseLayerReady = false; } } } } return baseLayerReady; } return false; } /** * Check whether view and image dimensions are known and either a preview, full size image or * base layer tiles are loaded. First time, send ready event to listener. The next draw will * display an image. */ private boolean checkReady() { boolean ready = getWidth() > 0 && getHeight() > 0 && sWidth > 0 && sHeight > 0 && (bitmap != null || isBaseLayerReady()); if (!readySent && ready) { preDraw(); readySent = true; onReady(); if (onImageEventListener != null) { onImageEventListener.onReady(); } } return ready; } /** * Check whether either the full size bitmap or base layer tiles are loaded. First time, send image * loaded event to listener. */ private boolean checkImageLoaded() { boolean imageLoaded = isBaseLayerReady(); if (!imageLoadedSent && imageLoaded) { preDraw(); imageLoadedSent = true; onImageLoaded(); if (onImageEventListener != null) { onImageEventListener.onImageLoaded(); } } return imageLoaded; } /** * Creates Paint objects once when first needed. */ private void createPaints() { if (bitmapPaint == null) { bitmapPaint = new Paint(); bitmapPaint.setAntiAlias(true); bitmapPaint.setFilterBitmap(true); bitmapPaint.setDither(true); } if (debugPaint == null && debug) { debugPaint = new Paint(); debugPaint.setTextSize(18); debugPaint.setColor(Color.MAGENTA); debugPaint.setStyle(Style.STROKE); } } /** * Called on first draw when the view has dimensions. Calculates the initial sample size and starts async loading of * the base layer image - the whole source subsampled as necessary. */ private synchronized void initialiseBaseLayer(Point maxTileDimensions) { debug("initialiseBaseLayer maxTileDimensions=%dx%d", maxTileDimensions.x, maxTileDimensions.y); satTemp = new ScaleAndTranslate(0f, new PointF(0, 0)); fitToBounds(true, satTemp); // Load double resolution - next level will be split into four tiles and at the center all four are required, // so don't bother with tiling until the next level 16 tiles are needed. fullImageSampleSize = calculateInSampleSize(satTemp.scale); if (fullImageSampleSize > 1) { fullImageSampleSize /= 2; } if (fullImageSampleSize == 1 && sRegion == null && sWidth() < maxTileDimensions.x && sHeight() < maxTileDimensions.y) { // Whole image is required at native resolution, and is smaller than the canvas max bitmap size. // Use BitmapDecoder for better image support. decoder.recycle(); decoder = null; BitmapLoadTask task = new BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, false); execute(task); } else { initialiseTileMap(maxTileDimensions); List<Tile> baseGrid = tileMap.get(fullImageSampleSize); for (Tile baseTile : baseGrid) { TileLoadTask task = new TileLoadTask(this, decoder, baseTile); execute(task); } refreshRequiredTiles(true); } } /** * Loads the optimum tiles for display at the current scale and translate, so the screen can be filled with tiles * that are at least as high resolution as the screen. Frees up bitmaps that are now off the screen. * @param load Whether to load the new tiles needed. Use false while scrolling/panning for performance. */ private void refreshRequiredTiles(boolean load) { if (decoder == null || tileMap == null) { return; } int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize(scale)); // Load tiles of the correct sample size that are on screen. Discard tiles off screen, and those that are higher // resolution than required, or lower res than required but not the base layer, so the base layer is always present. for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { for (Tile tile : tileMapEntry.getValue()) { if (tile.sampleSize < sampleSize || (tile.sampleSize > sampleSize && tile.sampleSize != fullImageSampleSize)) { tile.visible = false; if (tile.bitmap != null) { tile.bitmap.recycle(); tile.bitmap = null; } } if (tile.sampleSize == sampleSize) { if (tileVisible(tile)) { tile.visible = true; if (!tile.loading && tile.bitmap == null && load) { TileLoadTask task = new TileLoadTask(this, decoder, tile); execute(task); } } else if (tile.sampleSize != fullImageSampleSize) { tile.visible = false; if (tile.bitmap != null) { tile.bitmap.recycle(); tile.bitmap = null; } } } else if (tile.sampleSize == fullImageSampleSize) { tile.visible = true; } } } } /** * Determine whether tile is visible. */ private boolean tileVisible(Tile tile) { float sVisLeft = viewToSourceX(0), sVisRight = viewToSourceX(getWidth()), sVisTop = viewToSourceY(0), sVisBottom = viewToSourceY(getHeight()); return !(sVisLeft > tile.sRect.right || tile.sRect.left > sVisRight || sVisTop > tile.sRect.bottom || tile.sRect.top > sVisBottom); } /** * Sets scale and translate ready for the next draw. */ private void preDraw() { if (getWidth() == 0 || getHeight() == 0 || sWidth <= 0 || sHeight <= 0) { return; } // If waiting to translate to new center position, set translate now if (sPendingCenter != null && pendingScale != null) { scale = pendingScale; if (vTranslate == null) { vTranslate = new PointF(); } vTranslate.x = (getWidth()/2) - (scale * sPendingCenter.x); vTranslate.y = (getHeight()/2) - (scale * sPendingCenter.y); sPendingCenter = null; pendingScale = null; fitToBounds(true); refreshRequiredTiles(true); } // On first display of base image set up position, and in other cases make sure scale is correct. fitToBounds(false); } /** * Calculates sample size to fit the source image in given bounds. */ private int calculateInSampleSize(float scale) { if (minimumTileDpi > 0) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float averageDpi = (metrics.xdpi + metrics.ydpi)/2; scale = (minimumTileDpi/averageDpi) * scale; } int reqWidth = (int)(sWidth() * scale); int reqHeight = (int)(sHeight() * scale); // Raw height and width of image int inSampleSize = 1; if (reqWidth == 0 || reqHeight == 0) { return 32; } if (sHeight() > reqHeight || sWidth() > reqWidth) { // Calculate ratios of height and width to requested height and width final int heightRatio = Math.round((float) sHeight() / (float) reqHeight); final int widthRatio = Math.round((float) sWidth() / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will guarantee // a final image with both dimensions larger than or equal to the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } // We want the actual sample size that will be used, so round down to nearest power of 2. int power = 1; while (power * 2 < inSampleSize) { power = power * 2; } return power; } /** * Adjusts hypothetical future scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale * is set so one dimension fills the view and the image is centered on the other dimension. Used to calculate what the target of an * animation should be. * @param center Whether the image should be centered in the dimension it's too small to fill. While animating this can be false to avoid changes in direction as bounds are reached. * @param sat The scale we want and the translation we're aiming for. The values are adjusted to be valid. */ private void fitToBounds(boolean center, ScaleAndTranslate sat) { if (panLimit == PAN_LIMIT_OUTSIDE && isReady()) { center = false; } PointF vTranslate = sat.vTranslate; float scale = limitedScale(sat.scale); float scaleWidth = scale * sWidth(); float scaleHeight = scale * sHeight(); if (panLimit == PAN_LIMIT_CENTER && isReady()) { vTranslate.x = Math.max(vTranslate.x, getWidth()/2 - scaleWidth); vTranslate.y = Math.max(vTranslate.y, getHeight()/2 - scaleHeight); } else if (center) { vTranslate.x = Math.max(vTranslate.x, getWidth() - scaleWidth); vTranslate.y = Math.max(vTranslate.y, getHeight() - scaleHeight); } else { vTranslate.x = Math.max(vTranslate.x, -scaleWidth); vTranslate.y = Math.max(vTranslate.y, -scaleHeight); } // Asymmetric padding adjustments float xPaddingRatio = getPaddingLeft() > 0 || getPaddingRight() > 0 ? getPaddingLeft()/(float)(getPaddingLeft() + getPaddingRight()) : 0.5f; float yPaddingRatio = getPaddingTop() > 0 || getPaddingBottom() > 0 ? getPaddingTop()/(float)(getPaddingTop() + getPaddingBottom()) : 0.5f; float maxTx; float maxTy; if (panLimit == PAN_LIMIT_CENTER && isReady()) { maxTx = Math.max(0, getWidth()/2); maxTy = Math.max(0, getHeight()/2); } else if (center) { maxTx = Math.max(0, (getWidth() - scaleWidth) * xPaddingRatio); maxTy = Math.max(0, (getHeight() - scaleHeight) * yPaddingRatio); } else { maxTx = Math.max(0, getWidth()); maxTy = Math.max(0, getHeight()); } vTranslate.x = Math.min(vTranslate.x, maxTx); vTranslate.y = Math.min(vTranslate.y, maxTy); sat.scale = scale; } /** * Adjusts current scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale * is set so one dimension fills the view and the image is centered on the other dimension. * @param center Whether the image should be centered in the dimension it's too small to fill. While animating this can be false to avoid changes in direction as bounds are reached. */ private void fitToBounds(boolean center) { boolean init = false; if (vTranslate == null) { init = true; vTranslate = new PointF(0, 0); } if (satTemp == null) { satTemp = new ScaleAndTranslate(0, new PointF(0, 0)); } satTemp.scale = scale; satTemp.vTranslate.set(vTranslate); fitToBounds(center, satTemp); scale = satTemp.scale; vTranslate.set(satTemp.vTranslate); if (init) { vTranslate.set(vTranslateForSCenter(sWidth()/2, sHeight()/2, scale)); } } /** * Once source image and view dimensions are known, creates a map of sample size to tile grid. */ private void initialiseTileMap(Point maxTileDimensions) { debug("initialiseTileMap maxTileDimensions=%dx%d", maxTileDimensions.x, maxTileDimensions.y); this.tileMap = new LinkedHashMap<>(); int sampleSize = fullImageSampleSize; int xTiles = 1; int yTiles = 1; while (true) { int sTileWidth = sWidth()/xTiles; int sTileHeight = sHeight()/yTiles; int subTileWidth = sTileWidth/sampleSize; int subTileHeight = sTileHeight/sampleSize; while (subTileWidth + xTiles + 1 > maxTileDimensions.x || (subTileWidth > getWidth() * 1.25 && sampleSize < fullImageSampleSize)) { xTiles += 1; sTileWidth = sWidth()/xTiles; subTileWidth = sTileWidth/sampleSize; } while (subTileHeight + yTiles + 1 > maxTileDimensions.y || (subTileHeight > getHeight() * 1.25 && sampleSize < fullImageSampleSize)) { yTiles += 1; sTileHeight = sHeight()/yTiles; subTileHeight = sTileHeight/sampleSize; } List<Tile> tileGrid = new ArrayList<>(xTiles * yTiles); for (int x = 0; x < xTiles; x++) { for (int y = 0; y < yTiles; y++) { Tile tile = new Tile(); tile.sampleSize = sampleSize; tile.visible = sampleSize == fullImageSampleSize; tile.sRect = new Rect( x * sTileWidth, y * sTileHeight, x == xTiles - 1 ? sWidth() : (x + 1) * sTileWidth, y == yTiles - 1 ? sHeight() : (y + 1) * sTileHeight ); tile.vRect = new Rect(0, 0, 0, 0); tile.fileSRect = new Rect(tile.sRect); tileGrid.add(tile); } } tileMap.put(sampleSize, tileGrid); if (sampleSize == 1) { break; } else { sampleSize /= 2; } } } /** * Async task used to get image details without blocking the UI thread. */ private static class TilesInitTask extends AsyncTask<Void, Void, int[]> { private final WeakReference<SubsamplingScaleImageView> viewRef; private final WeakReference<Context> contextRef; private final WeakReference<DecoderFactory<? extends ImageRegionDecoder>> decoderFactoryRef; private final Uri source; private ImageRegionDecoder decoder; private Exception exception; TilesInitTask(SubsamplingScaleImageView view, Context context, DecoderFactory<? extends ImageRegionDecoder> decoderFactory, Uri source) { this.viewRef = new WeakReference<>(view); this.contextRef = new WeakReference<>(context); this.decoderFactoryRef = new WeakReference<DecoderFactory<? extends ImageRegionDecoder>>(decoderFactory); this.source = source; } @Override protected int[] doInBackground(Void... params) { try { String sourceUri = source.toString(); Context context = contextRef.get(); DecoderFactory<? extends ImageRegionDecoder> decoderFactory = decoderFactoryRef.get(); SubsamplingScaleImageView view = viewRef.get(); if (context != null && decoderFactory != null && view != null) { view.debug("TilesInitTask.doInBackground"); decoder = decoderFactory.make(); Point dimensions = decoder.init(context, source); int sWidth = dimensions.x; int sHeight = dimensions.y; int exifOrientation = view.getExifOrientation(context, sourceUri); if (view.sRegion != null) { sWidth = view.sRegion.width(); sHeight = view.sRegion.height(); } return new int[] { sWidth, sHeight, exifOrientation }; } } catch (Exception e) { Log.e(TAG, "Failed to initialise bitmap decoder", e); this.exception = e; } return null; } @Override protected void onPostExecute(int[] xyo) { final SubsamplingScaleImageView view = viewRef.get(); if (view != null) { if (decoder != null && xyo != null && xyo.length == 3) { view.onTilesInited(decoder, xyo[0], xyo[1], xyo[2]); } else if (exception != null && view.onImageEventListener != null) { view.onImageEventListener.onImageLoadError(exception); } } } } /** * Called by worker task when decoder is ready and image size and EXIF orientation is known. */ private synchronized void onTilesInited(ImageRegionDecoder decoder, int sWidth, int sHeight, int sOrientation) { debug("onTilesInited sWidth=%d, sHeight=%d, sOrientation=%d", sWidth, sHeight, orientation); // If actual dimensions don't match the declared size, reset everything. if (this.sWidth > 0 && this.sHeight > 0 && (this.sWidth != sWidth || this.sHeight != sHeight)) { reset(false); if (bitmap != null) { if (!bitmapIsCached) { bitmap.recycle(); } bitmap = null; if (onImageEventListener != null && bitmapIsCached) { onImageEventListener.onPreviewReleased(); } bitmapIsPreview = false; bitmapIsCached = false; } } this.decoder = decoder; this.sWidth = sWidth; this.sHeight = sHeight; this.sOrientation = sOrientation; checkReady(); if (!checkImageLoaded() && maxTileWidth > 0 && maxTileWidth != TILE_SIZE_AUTO && maxTileHeight > 0 && maxTileHeight != TILE_SIZE_AUTO && getWidth() > 0 && getHeight() > 0) { initialiseBaseLayer(new Point(maxTileWidth, maxTileHeight)); } invalidate(); requestLayout(); } /** * Async task used to load images without blocking the UI thread. */ private static class TileLoadTask extends AsyncTask<Void, Void, Bitmap> { private final WeakReference<SubsamplingScaleImageView> viewRef; private final WeakReference<ImageRegionDecoder> decoderRef; private final WeakReference<Tile> tileRef; private Exception exception; TileLoadTask(SubsamplingScaleImageView view, ImageRegionDecoder decoder, Tile tile) { this.viewRef = new WeakReference<>(view); this.decoderRef = new WeakReference<>(decoder); this.tileRef = new WeakReference<>(tile); tile.loading = true; } @Override protected Bitmap doInBackground(Void... params) { try { SubsamplingScaleImageView view = viewRef.get(); ImageRegionDecoder decoder = decoderRef.get(); Tile tile = tileRef.get(); if (decoder != null && tile != null && view != null && decoder.isReady() && tile.visible) { view.debug("TileLoadTask.doInBackground, tile.sRect=%s, tile.sampleSize=%d", tile.sRect, tile.sampleSize); synchronized (view.decoderLock) { // Update tile's file sRect according to rotation view.fileSRect(tile.sRect, tile.fileSRect); if (view.sRegion != null) { tile.fileSRect.offset(view.sRegion.left, view.sRegion.top); } return decoder.decodeRegion(tile.fileSRect, tile.sampleSize); } } else if (tile != null) { tile.loading = false; } } catch (Exception e) { Log.e(TAG, "Failed to decode tile", e); this.exception = e; } catch (OutOfMemoryError e) { Log.e(TAG, "Failed to decode tile - OutOfMemoryError", e); this.exception = new RuntimeException(e); } return null; } @Override protected void onPostExecute(Bitmap bitmap) { final SubsamplingScaleImageView subsamplingScaleImageView = viewRef.get(); final Tile tile = tileRef.get(); if (subsamplingScaleImageView != null && tile != null) { if (bitmap != null) { tile.bitmap = bitmap; tile.loading = false; subsamplingScaleImageView.onTileLoaded(); } else if (exception != null && subsamplingScaleImageView.onImageEventListener != null) { subsamplingScaleImageView.onImageEventListener.onTileLoadError(exception); } } } } /** * Called by worker task when a tile has loaded. Redraws the view. */ private synchronized void onTileLoaded() { debug("onTileLoaded"); checkReady(); checkImageLoaded(); if (isBaseLayerReady() && bitmap != null) { if (!bitmapIsCached) { bitmap.recycle(); } bitmap = null; if (onImageEventListener != null && bitmapIsCached) { onImageEventListener.onPreviewReleased(); } bitmapIsPreview = false; bitmapIsCached = false; } invalidate(); } /** * Async task used to load bitmap without blocking the UI thread. */ private static class BitmapLoadTask extends AsyncTask<Void, Void, Integer> { private final WeakReference<SubsamplingScaleImageView> viewRef; private final WeakReference<Context> contextRef; private final WeakReference<DecoderFactory<? extends ImageDecoder>> decoderFactoryRef; private final Uri source; private final boolean preview; private Bitmap bitmap; private Exception exception; BitmapLoadTask(SubsamplingScaleImageView view, Context context, DecoderFactory<? extends ImageDecoder> decoderFactory, Uri source, boolean preview) { this.viewRef = new WeakReference<>(view); this.contextRef = new WeakReference<>(context); this.decoderFactoryRef = new WeakReference<DecoderFactory<? extends ImageDecoder>>(decoderFactory); this.source = source; this.preview = preview; } @Override protected Integer doInBackground(Void... params) { try { String sourceUri = source.toString(); Context context = contextRef.get(); DecoderFactory<? extends ImageDecoder> decoderFactory = decoderFactoryRef.get(); SubsamplingScaleImageView view = viewRef.get(); if (context != null && decoderFactory != null && view != null) { view.debug("BitmapLoadTask.doInBackground"); bitmap = decoderFactory.make().decode(context, source); return view.getExifOrientation(context, sourceUri); } } catch (Exception e) { Log.e(TAG, "Failed to load bitmap", e); this.exception = e; } catch (OutOfMemoryError e) { Log.e(TAG, "Failed to load bitmap - OutOfMemoryError", e); this.exception = new RuntimeException(e); } return null; } @Override protected void onPostExecute(Integer orientation) { SubsamplingScaleImageView subsamplingScaleImageView = viewRef.get(); if (subsamplingScaleImageView != null) { if (bitmap != null && orientation != null) { if (preview) { subsamplingScaleImageView.onPreviewLoaded(bitmap); } else { subsamplingScaleImageView.onImageLoaded(bitmap, orientation, false); } } else if (exception != null && subsamplingScaleImageView.onImageEventListener != null) { if (preview) { subsamplingScaleImageView.onImageEventListener.onPreviewLoadError(exception); } else { subsamplingScaleImageView.onImageEventListener.onImageLoadError(exception); } } } } } /** * Called by worker task when preview image is loaded. */ private synchronized void onPreviewLoaded(Bitmap previewBitmap) { debug("onPreviewLoaded"); if (bitmap != null || imageLoadedSent) { previewBitmap.recycle(); return; } if (pRegion != null) { bitmap = Bitmap.createBitmap(previewBitmap, pRegion.left, pRegion.top, pRegion.width(), pRegion.height()); } else { bitmap = previewBitmap; } bitmapIsPreview = true; if (checkReady()) { invalidate(); requestLayout(); } } /** * Called by worker task when full size image bitmap is ready (tiling is disabled). */ private synchronized void onImageLoaded(Bitmap bitmap, int sOrientation, boolean bitmapIsCached) { debug("onImageLoaded"); // If actual dimensions don't match the declared size, reset everything. if (this.sWidth > 0 && this.sHeight > 0 && (this.sWidth != bitmap.getWidth() || this.sHeight != bitmap.getHeight())) { reset(false); } if (this.bitmap != null && !this.bitmapIsCached) { this.bitmap.recycle(); } if (this.bitmap != null && this.bitmapIsCached && onImageEventListener!=null) { onImageEventListener.onPreviewReleased(); } this.bitmapIsPreview = false; this.bitmapIsCached = bitmapIsCached; this.bitmap = bitmap; this.sWidth = bitmap.getWidth(); this.sHeight = bitmap.getHeight(); this.sOrientation = sOrientation; boolean ready = checkReady(); boolean imageLoaded = checkImageLoaded(); if (ready || imageLoaded) { invalidate(); requestLayout(); } } /** * Helper method for load tasks. Examines the EXIF info on the image file to determine the orientation. * This will only work for external files, not assets, resources or other URIs. */ @AnyThread private int getExifOrientation(Context context, String sourceUri) { int exifOrientation = ORIENTATION_0; if (sourceUri.startsWith(ContentResolver.SCHEME_CONTENT)) { Cursor cursor = null; try { String[] columns = { MediaStore.Images.Media.ORIENTATION }; cursor = context.getContentResolver().query(Uri.parse(sourceUri), columns, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int orientation = cursor.getInt(0); if (VALID_ORIENTATIONS.contains(orientation) && orientation != ORIENTATION_USE_EXIF) { exifOrientation = orientation; } else { Log.w(TAG, "Unsupported orientation: " + orientation); } } } } catch (Exception e) { Log.w(TAG, "Could not get orientation of image from media store"); } finally { if (cursor != null) { cursor.close(); } } } else if (sourceUri.startsWith(ImageSource.FILE_SCHEME) && !sourceUri.startsWith(ImageSource.ASSET_SCHEME)) { try { ExifInterface exifInterface = new ExifInterface(sourceUri.substring(ImageSource.FILE_SCHEME.length() - 1)); int orientationAttr = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); if (orientationAttr == ExifInterface.ORIENTATION_NORMAL || orientationAttr == ExifInterface.ORIENTATION_UNDEFINED) { exifOrientation = ORIENTATION_0; } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_90) { exifOrientation = ORIENTATION_90; } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_180) { exifOrientation = ORIENTATION_180; } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_270) { exifOrientation = ORIENTATION_270; } else { Log.w(TAG, "Unsupported EXIF orientation: " + orientationAttr); } } catch (Exception e) { Log.w(TAG, "Could not get EXIF orientation of image"); } } return exifOrientation; } private void execute(AsyncTask<Void, Void, ?> asyncTask) { if (parallelLoadingEnabled && VERSION.SDK_INT >= 11) { try { Field executorField = AsyncTask.class.getField("THREAD_POOL_EXECUTOR"); Executor executor = (Executor)executorField.get(null); Method executeMethod = AsyncTask.class.getMethod("executeOnExecutor", Executor.class, Object[].class); executeMethod.invoke(asyncTask, executor, null); return; } catch (Exception e) { Log.i(TAG, "Failed to execute AsyncTask on thread pool executor, falling back to single threaded executor", e); } } asyncTask.execute(); } private static class Tile { private Rect sRect; private int sampleSize; private Bitmap bitmap; private boolean loading; private boolean visible; // Volatile fields instantiated once then updated before use to reduce GC. private Rect vRect; private Rect fileSRect; } private static class Anim { private float scaleStart; // Scale at start of anim private float scaleEnd; // Scale at end of anim (target) private PointF sCenterStart; // Source center point at start private PointF sCenterEnd; // Source center point at end, adjusted for pan limits private PointF sCenterEndRequested; // Source center point that was requested, without adjustment private PointF vFocusStart; // View point that was double tapped private PointF vFocusEnd; // Where the view focal point should be moved to during the anim private long duration = 500; // How long the anim takes private boolean interruptible = true; // Whether the anim can be interrupted by a touch private int easing = EASE_IN_OUT_QUAD; // Easing style private int origin = ORIGIN_ANIM; // Animation origin (API, double tap or fling) private long time = System.currentTimeMillis(); // Start time private OnAnimationEventListener listener; // Event listener } private static class ScaleAndTranslate { private ScaleAndTranslate(float scale, PointF vTranslate) { this.scale = scale; this.vTranslate = vTranslate; } private float scale; private PointF vTranslate; } /** * Set scale, center and orientation from saved state. */ private void restoreState(ImageViewState state) { if (state != null && state.getCenter() != null && VALID_ORIENTATIONS.contains(state.getOrientation())) { this.orientation = state.getOrientation(); this.pendingScale = state.getScale(); this.sPendingCenter = state.getCenter(); invalidate(); } } /** * By default the View automatically calculates the optimal tile size. Set this to override this, and force an upper limit to the dimensions of the generated tiles. Passing {@link #TILE_SIZE_AUTO} will re-enable the default behaviour. * * @param maxPixels Maximum tile size X and Y in pixels. */ public void setMaxTileSize(int maxPixels) { this.maxTileWidth = maxPixels; this.maxTileHeight = maxPixels; } /** * By default the View automatically calculates the optimal tile size. Set this to override this, and force an upper limit to the dimensions of the generated tiles. Passing {@link #TILE_SIZE_AUTO} will re-enable the default behaviour. * * @param maxPixelsX Maximum tile width. * @param maxPixelsY Maximum tile height. */ public void setMaxTileSize(int maxPixelsX, int maxPixelsY) { this.maxTileWidth = maxPixelsX; this.maxTileHeight = maxPixelsY; } /** * In SDK 14 and above, use canvas max bitmap width and height instead of the default 2048, to avoid redundant tiling. */ private Point getMaxBitmapDimensions(Canvas canvas) { int maxWidth = 2048; int maxHeight = 2048; if (VERSION.SDK_INT >= 14) { try { maxWidth = (Integer)Canvas.class.getMethod("getMaximumBitmapWidth").invoke(canvas); maxHeight = (Integer)Canvas.class.getMethod("getMaximumBitmapHeight").invoke(canvas); } catch (Exception e) { // Return default } } return new Point(Math.min(maxWidth, maxTileWidth), Math.min(maxHeight, maxTileHeight)); } /** * Get source width taking rotation into account. */ @SuppressWarnings("SuspiciousNameCombination") private int sWidth() { int rotation = getRequiredRotation(); if (rotation == 90 || rotation == 270) { return sHeight; } else { return sWidth; } } /** * Get source height taking rotation into account. */ @SuppressWarnings("SuspiciousNameCombination") private int sHeight() { int rotation = getRequiredRotation(); if (rotation == 90 || rotation == 270) { return sWidth; } else { return sHeight; } } /** * Converts source rectangle from tile, which treats the image file as if it were in the correct orientation already, * to the rectangle of the image that needs to be loaded. */ @SuppressWarnings("SuspiciousNameCombination") @AnyThread private void fileSRect(Rect sRect, Rect target) { if (getRequiredRotation() == 0) { target.set(sRect); } else if (getRequiredRotation() == 90) { target.set(sRect.top, sHeight - sRect.right, sRect.bottom, sHeight - sRect.left); } else if (getRequiredRotation() == 180) { target.set(sWidth - sRect.right, sHeight - sRect.bottom, sWidth - sRect.left, sHeight - sRect.top); } else { target.set(sWidth - sRect.bottom, sRect.left, sWidth - sRect.top, sRect.right); } } /** * Determines the rotation to be applied to tiles, based on EXIF orientation or chosen setting. */ @AnyThread private int getRequiredRotation() { if (orientation == ORIENTATION_USE_EXIF) { return sOrientation; } else { return orientation; } } /** * Pythagoras distance between two points. */ private float distance(float x0, float x1, float y0, float y1) { float x = x0 - x1; float y = y0 - y1; return (float) Math.sqrt(x * x + y * y); } /** * Releases all resources the view is using and resets the state, nulling any fields that use significant memory. * After you have called this method, the view can be re-used by setting a new image. Settings are remembered * but state (scale and center) is forgotten. You can restore these yourself if required. */ public void recycle() { reset(true); bitmapPaint = null; debugPaint = null; tileBgPaint = null; } /** * Convert screen to source x coordinate. */ private float viewToSourceX(float vx) { if (vTranslate == null) { return Float.NaN; } return (vx - vTranslate.x)/scale; } /** * Convert screen to source y coordinate. */ private float viewToSourceY(float vy) { if (vTranslate == null) { return Float.NaN; } return (vy - vTranslate.y)/scale; } /** * Convert screen coordinate to source coordinate. */ public final PointF viewToSourceCoord(PointF vxy) { return viewToSourceCoord(vxy.x, vxy.y, new PointF()); } /** * Convert screen coordinate to source coordinate. */ public final PointF viewToSourceCoord(float vx, float vy) { return viewToSourceCoord(vx, vy, new PointF()); } /** * Convert screen coordinate to source coordinate. */ public final PointF viewToSourceCoord(PointF vxy, PointF sTarget) { return viewToSourceCoord(vxy.x, vxy.y, sTarget); } /** * Convert screen coordinate to source coordinate. */ public final PointF viewToSourceCoord(float vx, float vy, PointF sTarget) { if (vTranslate == null) { return null; } sTarget.set(viewToSourceX(vx), viewToSourceY(vy)); return sTarget; } /** * Convert source to screen x coordinate. */ private float sourceToViewX(float sx) { if (vTranslate == null) { return Float.NaN; } return (sx * scale) + vTranslate.x; } /** * Convert source to screen y coordinate. */ private float sourceToViewY(float sy) { if (vTranslate == null) { return Float.NaN; } return (sy * scale) + vTranslate.y; } /** * Convert source coordinate to screen coordinate. */ public final PointF sourceToViewCoord(PointF sxy) { return sourceToViewCoord(sxy.x, sxy.y, new PointF()); } /** * Convert source coordinate to screen coordinate. */ public final PointF sourceToViewCoord(float sx, float sy) { return sourceToViewCoord(sx, sy, new PointF()); } /** * Convert source coordinate to screen coordinate. */ public final PointF sourceToViewCoord(PointF sxy, PointF vTarget) { return sourceToViewCoord(sxy.x, sxy.y, vTarget); } /** * Convert source coordinate to screen coordinate. */ public final PointF sourceToViewCoord(float sx, float sy, PointF vTarget) { if (vTranslate == null) { return null; } vTarget.set(sourceToViewX(sx), sourceToViewY(sy)); return vTarget; } /** * Convert source rect to screen rect, integer values. */ private Rect sourceToViewRect(Rect sRect, Rect vTarget) { vTarget.set( (int)sourceToViewX(sRect.left), (int)sourceToViewY(sRect.top), (int)sourceToViewX(sRect.right), (int)sourceToViewY(sRect.bottom) ); return vTarget; } /** * Get the translation required to place a given source coordinate at the center of the screen, with the center * adjusted for asymmetric padding. Accepts the desired scale as an argument, so this is independent of current * translate and scale. The result is fitted to bounds, putting the image point as near to the screen center as permitted. */ private PointF vTranslateForSCenter(float sCenterX, float sCenterY, float scale) { int vxCenter = getPaddingLeft() + (getWidth() - getPaddingRight() - getPaddingLeft())/2; int vyCenter = getPaddingTop() + (getHeight() - getPaddingBottom() - getPaddingTop())/2; if (satTemp == null) { satTemp = new ScaleAndTranslate(0, new PointF(0, 0)); } satTemp.scale = scale; satTemp.vTranslate.set(vxCenter - (sCenterX * scale), vyCenter - (sCenterY * scale)); fitToBounds(true, satTemp); return satTemp.vTranslate; } /** * Given a requested source center and scale, calculate what the actual center will have to be to keep the image in * pan limits, keeping the requested center as near to the middle of the screen as allowed. */ private PointF limitedSCenter(float sCenterX, float sCenterY, float scale, PointF sTarget) { PointF vTranslate = vTranslateForSCenter(sCenterX, sCenterY, scale); int vxCenter = getPaddingLeft() + (getWidth() - getPaddingRight() - getPaddingLeft())/2; int vyCenter = getPaddingTop() + (getHeight() - getPaddingBottom() - getPaddingTop())/2; float sx = (vxCenter - vTranslate.x)/scale; float sy = (vyCenter - vTranslate.y)/scale; sTarget.set(sx, sy); return sTarget; } /** * Returns the minimum allowed scale. */ private float minScale() { int vPadding = getPaddingBottom() + getPaddingTop(); int hPadding = getPaddingLeft() + getPaddingRight(); if (minimumScaleType == SCALE_TYPE_CENTER_CROP) { return Math.max((getWidth() - hPadding) / (float) sWidth(), (getHeight() - vPadding) / (float) sHeight()); } else if (minimumScaleType == SCALE_TYPE_CUSTOM && minScale > 0) { return minScale; } else { return Math.min((getWidth() - hPadding) / (float) sWidth(), (getHeight() - vPadding) / (float) sHeight()); } } /** * Adjust a requested scale to be within the allowed limits. */ private float limitedScale(float targetScale) { targetScale = Math.max(minScale(), targetScale); targetScale = Math.min(maxScale, targetScale); return targetScale; } /** * Apply a selected type of easing. * @param type Easing type, from static fields * @param time Elapsed time * @param from Start value * @param change Target value * @param duration Anm duration * @return Current value */ private float ease(int type, long time, float from, float change, long duration) { switch (type) { case EASE_IN_OUT_QUAD: return easeInOutQuad(time, from, change, duration); case EASE_OUT_QUAD: return easeOutQuad(time, from, change, duration); default: throw new IllegalStateException("Unexpected easing type: " + type); } } /** * Quadratic easing for fling. With thanks to Robert Penner - http://gizma.com/easing/ * @param time Elapsed time * @param from Start value * @param change Target value * @param duration Anm duration * @return Current value */ private float easeOutQuad(long time, float from, float change, long duration) { float progress = (float)time/(float)duration; return -change * progress*(progress-2) + from; } /** * Quadratic easing for scale and center animations. With thanks to Robert Penner - http://gizma.com/easing/ * @param time Elapsed time * @param from Start value * @param change Target value * @param duration Anm duration * @return Current value */ private float easeInOutQuad(long time, float from, float change, long duration) { float timeF = time/(duration/2f); if (timeF < 1) { return (change/2f * timeF * timeF) + from; } else { timeF--; return (-change/2f) * (timeF * (timeF - 2) - 1) + from; } } /** * Debug logger */ @AnyThread private void debug(String message, Object... args) { if (debug) { Log.d(TAG, String.format(message, args)); } } /** * * Swap the default region decoder implementation for one of your own. You must do this before setting the image file or * asset, and you cannot use a custom decoder when using layout XML to set an asset name. Your class must have a * public default constructor. * @param regionDecoderClass The {@link ImageRegionDecoder} implementation to use. */ public final void setRegionDecoderClass(Class<? extends ImageRegionDecoder> regionDecoderClass) { if (regionDecoderClass == null) { throw new IllegalArgumentException("Decoder class cannot be set to null"); } this.regionDecoderFactory = new CompatDecoderFactory<>(regionDecoderClass); } /** * Swap the default region decoder implementation for one of your own. You must do this before setting the image file or * asset, and you cannot use a custom decoder when using layout XML to set an asset name. * @param regionDecoderFactory The {@link DecoderFactory} implementation that produces {@link ImageRegionDecoder} * instances. */ public final void setRegionDecoderFactory(DecoderFactory<? extends ImageRegionDecoder> regionDecoderFactory) { if (regionDecoderFactory == null) { throw new IllegalArgumentException("Decoder factory cannot be set to null"); } this.regionDecoderFactory = regionDecoderFactory; } /** * Swap the default bitmap decoder implementation for one of your own. You must do this before setting the image file or * asset, and you cannot use a custom decoder when using layout XML to set an asset name. Your class must have a * public default constructor. * @param bitmapDecoderClass The {@link ImageDecoder} implementation to use. */ public final void setBitmapDecoderClass(Class<? extends ImageDecoder> bitmapDecoderClass) { if (bitmapDecoderClass == null) { throw new IllegalArgumentException("Decoder class cannot be set to null"); } this.bitmapDecoderFactory = new CompatDecoderFactory<>(bitmapDecoderClass); } /** * Swap the default bitmap decoder implementation for one of your own. You must do this before setting the image file or * asset, and you cannot use a custom decoder when using layout XML to set an asset name. * @param bitmapDecoderFactory The {@link DecoderFactory} implementation that produces {@link ImageDecoder} instances. */ public final void setBitmapDecoderFactory(DecoderFactory<? extends ImageDecoder> bitmapDecoderFactory) { if (bitmapDecoderFactory == null) { throw new IllegalArgumentException("Decoder factory cannot be set to null"); } this.bitmapDecoderFactory = bitmapDecoderFactory; } /** * Set the pan limiting style. See static fields. Normally {@link #PAN_LIMIT_INSIDE} is best, for image galleries. */ public final void setPanLimit(int panLimit) { if (!VALID_PAN_LIMITS.contains(panLimit)) { throw new IllegalArgumentException("Invalid pan limit: " + panLimit); } this.panLimit = panLimit; if (isReady()) { fitToBounds(true); invalidate(); } } /** * Set the minimum scale type. See static fields. Normally {@link #SCALE_TYPE_CENTER_INSIDE} is best, for image galleries. */ public final void setMinimumScaleType(int scaleType) { if (!VALID_SCALE_TYPES.contains(scaleType)) { throw new IllegalArgumentException("Invalid scale type: " + scaleType); } this.minimumScaleType = scaleType; if (isReady()) { fitToBounds(true); invalidate(); } } /** * Set the maximum scale allowed. A value of 1 means 1:1 pixels at maximum scale. You may wish to set this according * to screen density - on a retina screen, 1:1 may still be too small. Consider using {@link #setMinimumDpi(int)}, * which is density aware. */ public final void setMaxScale(float maxScale) { this.maxScale = maxScale; } /** * Set the minimum scale allowed. A value of 1 means 1:1 pixels at minimum scale. You may wish to set this according * to screen density. Consider using {@link #setMaximumDpi(int)}, which is density aware. */ public final void setMinScale(float minScale) { this.minScale = minScale; } /** * This is a screen density aware alternative to {@link #setMaxScale(float)}; it allows you to express the maximum * allowed scale in terms of the minimum pixel density. This avoids the problem of 1:1 scale still being * too small on a high density screen. A sensible starting point is 160 - the default used by this view. * @param dpi Source image pixel density at maximum zoom. */ public final void setMinimumDpi(int dpi) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float averageDpi = (metrics.xdpi + metrics.ydpi)/2; setMaxScale(averageDpi/dpi); } /** * This is a screen density aware alternative to {@link #setMinScale(float)}; it allows you to express the minimum * allowed scale in terms of the maximum pixel density. * @param dpi Source image pixel density at minimum zoom. */ public final void setMaximumDpi(int dpi) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float averageDpi = (metrics.xdpi + metrics.ydpi)/2; setMinScale(averageDpi / dpi); } /** * Returns the maximum allowed scale. */ public float getMaxScale() { return maxScale; } /** * Returns the minimum allowed scale. */ public final float getMinScale() { return minScale(); } /** * By default, image tiles are at least as high resolution as the screen. For a retina screen this may not be * necessary, and may increase the likelihood of an OutOfMemoryError. This method sets a DPI at which higher * resolution tiles should be loaded. Using a lower number will on average use less memory but result in a lower * quality image. 160-240dpi will usually be enough. This should be called before setting the image source, * because it affects which tiles get loaded. When using an untiled source image this method has no effect. * @param minimumTileDpi Tile loading threshold. */ public void setMinimumTileDpi(int minimumTileDpi) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float averageDpi = (metrics.xdpi + metrics.ydpi)/2; this.minimumTileDpi = (int)Math.min(averageDpi, minimumTileDpi); if (isReady()) { reset(false); invalidate(); } } /** * Returns the source point at the center of the view. */ public final PointF getCenter() { int mX = getWidth()/2; int mY = getHeight()/2; return viewToSourceCoord(mX, mY); } /** * Returns the current scale value. */ public final float getScale() { return scale; } /** * Externally change the scale and translation of the source image. This may be used with getCenter() and getScale() * to restore the scale and zoom after a screen rotate. * @param scale New scale to set. * @param sCenter New source image coordinate to center on the screen, subject to boundaries. */ public final void setScaleAndCenter(float scale, PointF sCenter) { this.anim = null; this.pendingScale = scale; this.sPendingCenter = sCenter; this.sRequestedCenter = sCenter; invalidate(); } /** * Fully zoom out and return the image to the middle of the screen. This might be useful if you have a view pager * and want images to be reset when the user has moved to another page. */ public final void resetScaleAndCenter() { this.anim = null; this.pendingScale = limitedScale(0); if (isReady()) { this.sPendingCenter = new PointF(sWidth()/2, sHeight()/2); } else { this.sPendingCenter = new PointF(0, 0); } invalidate(); } /** * Call to find whether the view is initialised, has dimensions, and will display an image on * the next draw. If a preview has been provided, it may be the preview that will be displayed * and the full size image may still be loading. If no preview was provided, this is called once * the base layer tiles of the full size image are loaded. */ public final boolean isReady() { return readySent; } /** * Called once when the view is initialised, has dimensions, and will display an image on the * next draw. This is triggered at the same time as {@link OnImageEventListener#onReady()} but * allows a subclass to receive this event without using a listener. */ protected void onReady() { } /** * Call to find whether the main image (base layer tiles where relevant) have been loaded. Before * this event the view is blank unless a preview was provided. */ public final boolean isImageLoaded() { return imageLoadedSent; } /** * Called once when the full size image or its base layer tiles have been loaded. */ protected void onImageLoaded() { } /** * Get source width, ignoring orientation. If {@link #getOrientation()} returns 90 or 270, you can use {@link #getSHeight()} * for the apparent width. */ public final int getSWidth() { return sWidth; } /** * Get source height, ignoring orientation. If {@link #getOrientation()} returns 90 or 270, you can use {@link #getSWidth()} * for the apparent height. */ public final int getSHeight() { return sHeight; } /** * Returns the orientation setting. This can return {@link #ORIENTATION_USE_EXIF}, in which case it doesn't tell you * the applied orientation of the image. For that, use {@link #getAppliedOrientation()}. */ public final int getOrientation() { return orientation; } /** * Returns the actual orientation of the image relative to the source file. This will be based on the source file's * EXIF orientation if you're using ORIENTATION_USE_EXIF. Values are 0, 90, 180, 270. */ public final int getAppliedOrientation() { return getRequiredRotation(); } /** * Get the current state of the view (scale, center, orientation) for restoration after rotate. Will return null if * the view is not ready. */ public final ImageViewState getState() { if (vTranslate != null && sWidth > 0 && sHeight > 0) { return new ImageViewState(getScale(), getCenter(), getOrientation()); } return null; } /** * Returns true if zoom gesture detection is enabled. */ public final boolean isZoomEnabled() { return zoomEnabled; } /** * Enable or disable zoom gesture detection. Disabling zoom locks the the current scale. */ public final void setZoomEnabled(boolean zoomEnabled) { this.zoomEnabled = zoomEnabled; } /** * Returns true if double tap &amp; swipe to zoom is enabled. */ public final boolean isQuickScaleEnabled() { return quickScaleEnabled; } /** * Enable or disable double tap &amp; swipe to zoom. */ public final void setQuickScaleEnabled(boolean quickScaleEnabled) { this.quickScaleEnabled = quickScaleEnabled; } /** * Returns true if pan gesture detection is enabled. */ public final boolean isPanEnabled() { return panEnabled; } /** * Enable or disable pan gesture detection. Disabling pan causes the image to be centered. */ public final void setPanEnabled(boolean panEnabled) { this.panEnabled = panEnabled; if (!panEnabled && vTranslate != null) { vTranslate.x = (getWidth()/2) - (scale * (sWidth()/2)); vTranslate.y = (getHeight()/2) - (scale * (sHeight()/2)); if (isReady()) { refreshRequiredTiles(true); invalidate(); } } } /** * Set a solid color to render behind tiles, useful for displaying transparent PNGs. * @param tileBgColor Background color for tiles. */ public final void setTileBackgroundColor(int tileBgColor) { if (Color.alpha(tileBgColor) == 0) { tileBgPaint = null; } else { tileBgPaint = new Paint(); tileBgPaint.setStyle(Style.FILL); tileBgPaint.setColor(tileBgColor); } invalidate(); } /** * Set the scale the image will zoom in to when double tapped. This also the scale point where a double tap is interpreted * as a zoom out gesture - if the scale is greater than 90% of this value, a double tap zooms out. Avoid using values * greater than the max zoom. * @param doubleTapZoomScale New value for double tap gesture zoom scale. */ public final void setDoubleTapZoomScale(float doubleTapZoomScale) { this.doubleTapZoomScale = doubleTapZoomScale; } /** * A density aware alternative to {@link #setDoubleTapZoomScale(float)}; this allows you to express the scale the * image will zoom in to when double tapped in terms of the image pixel density. Values lower than the max scale will * be ignored. A sensible starting point is 160 - the default used by this view. * @param dpi New value for double tap gesture zoom scale. */ public final void setDoubleTapZoomDpi(int dpi) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float averageDpi = (metrics.xdpi + metrics.ydpi)/2; setDoubleTapZoomScale(averageDpi/dpi); } /** * Set the type of zoom animation to be used for double taps. See static fields. * @param doubleTapZoomStyle New value for zoom style. */ public final void setDoubleTapZoomStyle(int doubleTapZoomStyle) { if (!VALID_ZOOM_STYLES.contains(doubleTapZoomStyle)) { throw new IllegalArgumentException("Invalid zoom style: " + doubleTapZoomStyle); } this.doubleTapZoomStyle = doubleTapZoomStyle; } /** * Set the duration of the double tap zoom animation. * @param durationMs Duration in milliseconds. */ public final void setDoubleTapZoomDuration(int durationMs) { this.doubleTapZoomDuration = Math.max(0, durationMs); } /** * Toggle parallel loading. When enabled, tiles are loaded using the thread pool executor available * in SDK 11+. In older versions this has no effect. Parallel loading may use more memory and there * is a possibility that it will make the tile loading unreliable, but it reduces the chances of * an app's background processes blocking loading. * @param parallelLoadingEnabled Whether to run AsyncTasks using a thread pool executor. */ public void setParallelLoadingEnabled(boolean parallelLoadingEnabled) { this.parallelLoadingEnabled = parallelLoadingEnabled; } /** * Enables visual debugging, showing tile boundaries and sizes. */ public final void setDebug(boolean debug) { this.debug = debug; } /** * Check if an image has been set. The image may not have been loaded and displayed yet. * @return If an image is currently set. */ public boolean hasImage() { return uri != null || bitmap != null; } /** * {@inheritDoc} */ @Override public void setOnLongClickListener(OnLongClickListener onLongClickListener) { this.onLongClickListener = onLongClickListener; } /** * Add a listener allowing notification of load and error events. */ public void setOnImageEventListener(OnImageEventListener onImageEventListener) { this.onImageEventListener = onImageEventListener; } /** * Add a listener for pan and zoom events. */ public void setOnStateChangedListener(OnStateChangedListener onStateChangedListener) { this.onStateChangedListener = onStateChangedListener; } private void sendStateChanged(float oldScale, PointF oldVTranslate, int origin) { if (onStateChangedListener != null) { if (scale != oldScale) { onStateChangedListener.onScaleChanged(scale, origin); } if (!vTranslate.equals(oldVTranslate)) { onStateChangedListener.onCenterChanged(getCenter(), origin); } } } /** * Creates a panning animation builder, that when started will animate the image to place the given coordinates of * the image in the center of the screen. If doing this would move the image beyond the edges of the screen, the * image is instead animated to move the center point as near to the center of the screen as is allowed - it's * guaranteed to be on screen. * @param sCenter Target center point * @return {@link AnimationBuilder} instance. Call {@link AnimationBuilder#start()} to start the anim. */ public AnimationBuilder animateCenter(PointF sCenter) { if (!isReady()) { return null; } return new AnimationBuilder(sCenter); } /** * Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image * beyond the panning limits, the image is automatically panned during the animation. * @param scale Target scale. * @return {@link AnimationBuilder} instance. Call {@link AnimationBuilder#start()} to start the anim. */ public AnimationBuilder animateScale(float scale) { if (!isReady()) { return null; } return new AnimationBuilder(scale); } /** * Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image * beyond the panning limits, the image is automatically panned during the animation. * @param scale Target scale. * @return {@link AnimationBuilder} instance. Call {@link AnimationBuilder#start()} to start the anim. */ public AnimationBuilder animateScaleAndCenter(float scale, PointF sCenter) { if (!isReady()) { return null; } return new AnimationBuilder(scale, sCenter); } /** * Builder class used to set additional options for a scale animation. Create an instance using {@link #animateScale(float)}, * then set your options and call {@link #start()}. */ public final class AnimationBuilder { private final float targetScale; private final PointF targetSCenter; private final PointF vFocus; private long duration = 500; private int easing = EASE_IN_OUT_QUAD; private int origin = ORIGIN_ANIM; private boolean interruptible = true; private boolean panLimited = true; private OnAnimationEventListener listener; private AnimationBuilder(PointF sCenter) { this.targetScale = scale; this.targetSCenter = sCenter; this.vFocus = null; } private AnimationBuilder(float scale) { this.targetScale = scale; this.targetSCenter = getCenter(); this.vFocus = null; } private AnimationBuilder(float scale, PointF sCenter) { this.targetScale = scale; this.targetSCenter = sCenter; this.vFocus = null; } private AnimationBuilder(float scale, PointF sCenter, PointF vFocus) { this.targetScale = scale; this.targetSCenter = sCenter; this.vFocus = vFocus; } /** * Desired duration of the anim in milliseconds. Default is 500. * @param duration duration in milliseconds. * @return this builder for method chaining. */ public AnimationBuilder withDuration(long duration) { this.duration = duration; return this; } /** * Whether the animation can be interrupted with a touch. Default is true. * @param interruptible interruptible flag. * @return this builder for method chaining. */ public AnimationBuilder withInterruptible(boolean interruptible) { this.interruptible = interruptible; return this; } /** * Set the easing style. See static fields. {@link #EASE_IN_OUT_QUAD} is recommended, and the default. * @param easing easing style. * @return this builder for method chaining. */ public AnimationBuilder withEasing(int easing) { if (!VALID_EASING_STYLES.contains(easing)) { throw new IllegalArgumentException("Unknown easing type: " + easing); } this.easing = easing; return this; } /** * Add an animation event listener. * @param listener The listener. * @return this builder for method chaining. */ public AnimationBuilder withOnAnimationEventListener(OnAnimationEventListener listener) { this.listener = listener; return this; } /** * Only for internal use. When set to true, the animation proceeds towards the actual end point - the nearest * point to the center allowed by pan limits. When false, animation is in the direction of the requested end * point and is stopped when the limit for each axis is reached. The latter behaviour is used for flings but * nothing else. */ private AnimationBuilder withPanLimited(boolean panLimited) { this.panLimited = panLimited; return this; } /** * Only for internal use. Indicates what caused the animation. */ private AnimationBuilder withOrigin(int origin) { this.origin = origin; return this; } /** * Starts the animation. */ public void start() { if (anim != null && anim.listener != null) { try { anim.listener.onInterruptedByNewAnim(); } catch (Exception e) { Log.w(TAG, "Error thrown by animation listener", e); } } int vxCenter = getPaddingLeft() + (getWidth() - getPaddingRight() - getPaddingLeft())/2; int vyCenter = getPaddingTop() + (getHeight() - getPaddingBottom() - getPaddingTop())/2; float targetScale = limitedScale(this.targetScale); PointF targetSCenter = panLimited ? limitedSCenter(this.targetSCenter.x, this.targetSCenter.y, targetScale, new PointF()) : this.targetSCenter; anim = new Anim(); anim.scaleStart = scale; anim.scaleEnd = targetScale; anim.time = System.currentTimeMillis(); anim.sCenterEndRequested = targetSCenter; anim.sCenterStart = getCenter(); anim.sCenterEnd = targetSCenter; anim.vFocusStart = sourceToViewCoord(targetSCenter); anim.vFocusEnd = new PointF( vxCenter, vyCenter ); anim.duration = duration; anim.interruptible = interruptible; anim.easing = easing; anim.origin = origin; anim.time = System.currentTimeMillis(); anim.listener = listener; if (vFocus != null) { // Calculate where translation will be at the end of the anim float vTranslateXEnd = vFocus.x - (targetScale * anim.sCenterStart.x); float vTranslateYEnd = vFocus.y - (targetScale * anim.sCenterStart.y); ScaleAndTranslate satEnd = new ScaleAndTranslate(targetScale, new PointF(vTranslateXEnd, vTranslateYEnd)); // Fit the end translation into bounds fitToBounds(true, satEnd); // Adjust the position of the focus point at end so image will be in bounds anim.vFocusEnd = new PointF( vFocus.x + (satEnd.vTranslate.x - vTranslateXEnd), vFocus.y + (satEnd.vTranslate.y - vTranslateYEnd) ); } invalidate(); } } /** * An event listener for animations, allows events to be triggered when an animation completes, * is aborted by another animation starting, or is aborted by a touch event. Note that none of * these events are triggered if the activity is paused, the image is swapped, or in other cases * where the view's internal state gets wiped or draw events stop. */ public interface OnAnimationEventListener { /** * The animation has completed, having reached its endpoint. */ void onComplete(); /** * The animation has been aborted before reaching its endpoint because the user touched the screen. */ void onInterruptedByUser(); /** * The animation has been aborted before reaching its endpoint because a new animation has been started. */ void onInterruptedByNewAnim(); } /** * Default implementation of {@link OnAnimationEventListener} for extension. This does nothing in any method. */ public static class DefaultOnAnimationEventListener implements OnAnimationEventListener { @Override public void onComplete() { } @Override public void onInterruptedByUser() { } @Override public void onInterruptedByNewAnim() { } } /** * An event listener, allowing subclasses and activities to be notified of significant events. */ public interface OnImageEventListener { /** * Called when the dimensions of the image and view are known, and either a preview image, * the full size image, or base layer tiles are loaded. This indicates the scale and translate * are known and the next draw will display an image. This event can be used to hide a loading * graphic, or inform a subclass that it is safe to draw overlays. */ void onReady(); /** * Called when the full size image is ready. When using tiling, this means the lowest resolution * base layer of tiles are loaded, and when tiling is disabled, the image bitmap is loaded. * This event could be used as a trigger to enable gestures if you wanted interaction disabled * while only a preview is displayed, otherwise for most cases {@link #onReady()} is the best * event to listen to. */ void onImageLoaded(); /** * Called when a preview image could not be loaded. This method cannot be relied upon; certain * encoding types of supported image formats can result in corrupt or blank images being loaded * and displayed with no detectable error. The view will continue to load the full size image. * @param e The exception thrown. This error is logged by the view. */ void onPreviewLoadError(Exception e); /** * Indicates an error initiliasing the decoder when using a tiling, or when loading the full * size bitmap when tiling is disabled. This method cannot be relied upon; certain encoding * types of supported image formats can result in corrupt or blank images being loaded and * displayed with no detectable error. * @param e The exception thrown. This error is also logged by the view. */ void onImageLoadError(Exception e); /** * Called when an image tile could not be loaded. This method cannot be relied upon; certain * encoding types of supported image formats can result in corrupt or blank images being loaded * and displayed with no detectable error. Most cases where an unsupported file is used will * result in an error caught by {@link #onImageLoadError(Exception)}. * @param e The exception thrown. This error is logged by the view. */ void onTileLoadError(Exception e); /** * Called when a bitmap set using ImageSource.cachedBitmap is no longer being used by the View. * This is useful if you wish to manage the bitmap after the preview is shown */ void onPreviewReleased(); } /** * Default implementation of {@link OnImageEventListener} for extension. This does nothing in any method. */ public static class DefaultOnImageEventListener implements OnImageEventListener { @Override public void onReady() { } @Override public void onImageLoaded() { } @Override public void onPreviewLoadError(Exception e) { } @Override public void onImageLoadError(Exception e) { } @Override public void onTileLoadError(Exception e) { } @Override public void onPreviewReleased() { } } /** * An event listener, allowing activities to be notified of pan and zoom events. Initialisation * and calls made by your code do not trigger events; touch events and animations do. Methods in * this listener will be called on the UI thread and may be called very frequently - your * implementation should return quickly. */ public interface OnStateChangedListener { /** * The scale has changed. Use with {@link #getMaxScale()} and {@link #getMinScale()} to determine * whether the image is fully zoomed in or out. * @param newScale The new scale. * @param origin Where the event originated from - one of {@link #ORIGIN_ANIM}, {@link #ORIGIN_TOUCH}. */ void onScaleChanged(float newScale, int origin); /** * The source center has been changed. This can be a result of panning or zooming. * @param newCenter The new source center point. * @param origin Where the event originated from - one of {@link #ORIGIN_ANIM}, {@link #ORIGIN_TOUCH}. */ void onCenterChanged(PointF newCenter, int origin); } /** * Default implementation of {@link OnStateChangedListener}. This does nothing in any method. */ public static class DefaultOnStateChangedListener implements OnStateChangedListener { @Override public void onCenterChanged(PointF newCenter, int origin) { } @Override public void onScaleChanged(float newScale, int origin) { } } }
00c5b5ea16880170f068ea323dc3050b82f10432
511d5b6fbd5b831ed81b1a7505db9208d0840d83
/Java2DGame/src/game/gui/Gui.java
45a3a895397a3ae74f8c3d2fc2a5d6704058c870
[]
no_license
BinSin/Java2DGame
7cc585731194ff5cc1eda3fff597b9b5a0ef616f
2ed77d2c2abe6b2e97337dff889c4cb228f7f616
refs/heads/master
2021-05-27T00:48:31.777500
2013-09-11T08:33:22
2013-09-11T08:33:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,333
java
package game.gui; import game.Game; import game.InputHandler; import game.InputHandler.GameActionListener; import game.InputHandler.InputEvent; import game.InputHandler.InputEventType; import game.gfx.Colors; import game.gfx.SpriteSheet; public abstract class Gui implements GameActionListener { private static int DEFAULT_BKG_COLOR = 0x555555; private double red; private double green; private double blue; protected Gui parentGui; protected Game game; public InputHandler input; public SpriteSheet font; public int[] pixels; public int[] bkgPixels; public int width; public int height; protected boolean pauseGame; protected boolean closeOnEscape = true; public Gui(Game game, int width, int height) { this.game = game; this.input = game.input; this.font = new SpriteSheet("/sprite_sheet.png"); this.width = width; this.height = height; this.pixels = new int[width * height]; this.setTint(0.3D, 0.3D, 0.3D); if (game.getWorld() != null && game.screen.pixels.length == pixels.length) { bkgPixels = game.pixels.clone(); } } public abstract void render(); public abstract void tick(int ticks); public abstract void guiActionPerformed(int elementId, int action); public void setParentGui(Gui gui) { this.parentGui = gui; } public boolean pausesGame() { return pauseGame; } public void drawDefaultBackground() { if (bkgPixels != null) { for (int i = 0; i < bkgPixels.length; i++) { pixels[i] = Colors.tint(bkgPixels[i], red, green, blue); } } else { for (int i = 0; i < pixels.length; i++) { pixels[i] = DEFAULT_BKG_COLOR; } } } public void drawRect(int xPos, int yPos, int width, int height, int color) { if (xPos > this.width) xPos = this.width - 1; if (yPos > this.height) yPos = this.height - 1; if (xPos + width > this.width) width = this.width - xPos; if (yPos + height > this.height) height = this.height - yPos; width -= 1; height -= 1; for (int x = xPos; x < xPos + width; x++) { pixels[x + yPos * this.width] = color; } for (int y = yPos; y < yPos + height; y++) { pixels[xPos + y * this.width] = color; } for (int x = xPos; x < xPos + width; x++) { pixels[x + (yPos + height) * this.width] = color; } for (int y = yPos; y < yPos + height; y++) { pixels[(xPos + width) + y * this.width] = color; } } public void fillRect(int xPos, int yPos, int width, int height, int color) { if (xPos > this.width) xPos = this.width; if (yPos > this.height) yPos = this.height; if (xPos + width > this.width) width = this.width - xPos; if (yPos + height > this.height) height = this.height - yPos; for (int y = yPos; y < yPos + height; y++) { for (int x = xPos; x < xPos + width; x++) { pixels[x + y * this.width] = color; } } } @Override public void actionPerformed(InputEvent event) { if (event.key.id == input.esc.id && event.type == InputEventType.PRESSED && closeOnEscape) { last(); } } public void setTint(double r, double g, double b) { red = r; green = g; blue = b; } public Gui setParent(Gui gui) { this.parentGui = gui; return this; } public void last() { game.hideGui(this); } public void close() { this.parentGui = null; game.hideGui(this); } public Gui getParentGui() { return parentGui; } }
4be6e2b9f357fca146d8fe17514c13390f459e0d
d14b9df4ff14c6e869d29b67409dc6d7d4fca67f
/src/com/learning/String/StringMethods.java
3eac3fd7bc5071527dbbe62efe040d8fa0387d2e
[]
no_license
IsmithI/Learning
6a4cf4ed9e762b0ce1afd9c1f1f0544ae5e4f3c2
eafa8c55e1f9d9e2036c7ba540e392dac0ec8aac
refs/heads/master
2021-01-11T23:14:21.310084
2017-01-10T19:09:24
2017-01-10T19:09:24
70,183,217
0
0
null
null
null
null
UTF-8
Java
false
false
356
java
package com.learning.String; /** * Created by smith on 07.12.16. */ public class StringMethods { public static void main(String[] args) { String a = "Bacon"; String b = "monster"; System.out.println(a.replace('B', 'F')); System.out.println(a); a = a.replace('B', 'F'); System.out.println(a); } }
70abb9ffd8eafde7d76511597d51c214d677d325
35fe14303829bbf595c0ad262af34504102b2a66
/app/src/main/java/com/example/cinescarlos/SharedPreference/SharedPrefManager.java
660870ce2ff450f0e29912ef3d0db6f326322e7f
[]
no_license
carlosmc91/CinesCarlos
c3d5804eb13088f89c8058126531ed9f1ad05500
3bc10ef954ffa22f20102311e81d2e7de5294933
refs/heads/master
2020-12-01T10:41:44.595064
2020-02-18T17:42:59
2020-02-18T17:42:59
230,610,056
0
0
null
null
null
null
UTF-8
Java
false
false
3,754
java
package com.example.cinescarlos.SharedPreference; import android.content.Context; import android.content.SharedPreferences; import com.example.cinescarlos.Beans.Peliculas; import com.example.cinescarlos.Beans.Usuarios; public class SharedPrefManager { private static final String SHARED_PREFERENCES = "SHARED_PREFERENCES"; private static final String SHARED_PREFERENCES_NOMBRE = "SHARED_PREFERENCES_NOMBRE"; private static final String SHARED_PREFERENCES_APELLIDO = "SHARED_PREFERENCES_APELLIDO"; private static final String SHARED_PREFERENCES_CORREO = "SHARED_PREFERENCES_CORREO"; private static final String SHARED_PREFERENCES_TELEFONO = "SHARED_PREFERENCES_TELEFONO"; private static final String SHARED_PREFERENCES_TARJETA = "SHARED_PREFERENCES_TARJETA"; private static final String SHARED_PREFERENCES_ID = "SHARED_PREFERENCES_ID"; private static final String SHARED_PREFERENCES_IDPELICULA = "SHARED_PREFERENCES_IDPELICULA"; private static final String SHARED_PREFERENCES_NOMBREPELICULA = "SHARED_PREFERENCES_NOMBREPELICULA"; private static SharedPrefManager instance; private Context context; private SharedPreferences sharedPreferences; private SharedPrefManager(Context context){ this.context = context; sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE); //Modo privado para que no accedan de terceros } public static synchronized SharedPrefManager getInstance(Context context){ if(instance== null){ instance = new SharedPrefManager(context); } return instance; } public void saveUsuario(Usuarios usuario){ SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putLong(SHARED_PREFERENCES_ID, usuario.getId()); editor.putString(SHARED_PREFERENCES_NOMBRE, usuario.getNombre()); editor.putString(SHARED_PREFERENCES_APELLIDO, usuario.getApellido()); editor.putString(SHARED_PREFERENCES_CORREO, usuario.getCorreo()); editor.putString(SHARED_PREFERENCES_TARJETA, usuario.getTarjeta()); editor.putLong(SHARED_PREFERENCES_TELEFONO, usuario.getTelefono()); editor.apply(); } public void savePelicula(Peliculas pelicula){ SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putLong(SHARED_PREFERENCES_IDPELICULA, pelicula.getId()); editor.putString(SHARED_PREFERENCES_NOMBREPELICULA, pelicula.getNombre()); editor.apply(); } public boolean isLoggedIn(){ if(sharedPreferences.getLong(SHARED_PREFERENCES_ID, -1)!= -1){ return true; } return false; } public Usuarios getUsuario(){ Usuarios usuario = new Usuarios( sharedPreferences.getString(SHARED_PREFERENCES_APELLIDO, null), sharedPreferences.getString(SHARED_PREFERENCES_CORREO, null), sharedPreferences.getString(SHARED_PREFERENCES_NOMBRE, null), sharedPreferences.getString(SHARED_PREFERENCES_TARJETA, null), sharedPreferences.getLong(SHARED_PREFERENCES_TELEFONO, -1), sharedPreferences.getLong(SHARED_PREFERENCES_ID, -1) ); return usuario; } public Peliculas getPelicula(){ Peliculas pelicula = new Peliculas( sharedPreferences.getLong(SHARED_PREFERENCES_IDPELICULA, -1), sharedPreferences.getString(SHARED_PREFERENCES_NOMBREPELICULA, null) ); return pelicula; } public void logOut(){ //Método para salir del Login de Usuario SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.apply(); } }
0c11f0d7148fca03d3c067c232abbda3f6c9d4fb
a3bc0bb2c8c70b0b6bb4bbd83f900dd46091d2bd
/app/src/main/java/io/github/xudaojie/androiddemo/Main2Activity.java
e9424881d05dbf3499718ef56d946be6fd074612
[]
no_license
XuDaojie/AndroidDemo
5049e99680f979153f923c5c159d8a8ee3be5db6
995b8cbf4b7c65284240e7ded5ebd6e0556999a9
refs/heads/master
2020-04-16T02:14:23.767928
2017-02-10T08:21:55
2017-02-10T08:21:55
59,456,062
3
0
null
null
null
null
UTF-8
Java
false
false
3,514
java
package io.github.xudaojie.androiddemo; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
c0aba9d2458294fac88050442ac6abf05c352028
8e1c5673074b941483a03e0e3d2964c245f92887
/app/src/androidTest/java/com/example/android/braintrainer/ExampleInstrumentedTest.java
51650cae6016bef5fb908dff6347e51b04afd10f
[]
no_license
SrishtyC13/BrainTrainer
ecddef70e2cd8be85f62a95dc1115e39746b2843
b7cd915277c00bbd6d88d6e8bcf032e25c512476
refs/heads/master
2020-05-19T04:06:50.137267
2019-05-04T15:21:53
2019-05-04T15:21:53
184,817,200
1
0
null
null
null
null
UTF-8
Java
false
false
748
java
package com.example.android.braintrainer; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.android.braintrainer", appContext.getPackageName()); } }