blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
8050cc8b15f5b8fba7a8d0ec85bdcef9f1709d1f
Java
empinator/JDiffPatch
/src/test/java/de/polstelle/diffpatch/model/Address.java
UTF-8
248
2.078125
2
[]
no_license
package de.polstelle.diffpatch.model; public class Address { private String postfach; public String getPostfach() { return postfach; } public void setPostfach(String postfach) { this.postfach = postfach; } }
true
4b0fcb2d82c2151269422e4e4f0390e9f72d659c
Java
gaotong6434/opencode-platform
/src/main/java/cn/meteor/opencode/platform/entity/Branch.java
UTF-8
570
1.945313
2
[]
no_license
package cn.meteor.opencode.platform.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @Data @TableName("branch") //@TableName("User") public class Branch { @TableField("branch_id") //分支id private String branchId; @TableField("repo_id") //仓库id private String repoId; @TableField("branch_status") //分支状态 可用:1 (真)删除:0 private Integer branchStatus; //判断是否为主支 private Integer master; }
true
a1c517d98d416766f380b7d556efc9c89ab2776a
Java
membermanagesystem/MemberManageSystem
/src/main/java/com/zs/controller/TestController.java
UTF-8
465
1.671875
2
[]
no_license
package com.zs.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @Controller /*@RequestMapping("/test")*/ public class TestController { @RequestMapping("/hello") /* @ResponseBody*/ public ModelAndView Hello() { return new ModelAndView("top"); } }
true
31cc9bd6dba58dbc131b021d834a2538773c1ca4
Java
Tomatinho13/TP05-smarttraining
/smarttraining-core/src/br/cefetmg/inf/model/adapter/ManterMusculoAdapter.java
UTF-8
1,458
2.515625
3
[]
no_license
package br.cefetmg.inf.model.adapter; import br.cefetmg.inf.model.domain.Musculo; import br.cefetmg.inf.model.services.IManterMusculo; import br.cefetmg.inf.model.services.impl.ManterMusculo; import java.rmi.RemoteException; import java.sql.SQLException; import java.util.ArrayList; public class ManterMusculoAdapter implements IManterMusculo { private final IManterMusculo manterMusculo; public ManterMusculoAdapter() throws RemoteException { this.manterMusculo = new ManterMusculo(); } @Override public Musculo pesquisarPorCodigo(int codMusculo) throws SQLException, RemoteException { Musculo resultado = manterMusculo.pesquisarPorCodigo(codMusculo); return resultado; } @Override public ArrayList<Musculo> pesquisarTodos() throws SQLException, RemoteException { return manterMusculo.pesquisarTodos(); } @Override public boolean cadastrar(Musculo musculo) throws SQLException, RemoteException { boolean resultado = manterMusculo.cadastrar(musculo); return resultado; } @Override public boolean alterar(Musculo musculo) throws SQLException, RemoteException { boolean resultado = manterMusculo.alterar(musculo); return resultado; } @Override public boolean excluir(int codMusculo) throws SQLException, RemoteException { boolean resultado = manterMusculo.excluir(codMusculo); return resultado; } }
true
201d53f19202e7522845847cf0e357ceedcc6516
Java
techquest/autopay-sdk-java
/autopay-sdk-beneficiary-upload/src/main/java/com/interswitchng/techquest/autopay/sdk/beneficiary/upload/utils/BeneficiaryUploadSecurityUtils.java
UTF-8
3,441
2.3125
2
[]
no_license
package com.interswitchng.techquest.autopay.sdk.beneficiary.upload.utils; import java.security.SecureRandom; import java.util.ArrayList; import org.bouncycastle.util.encoders.Hex; import com.interswitchng.techquest.autopay.sdk.beneficiary.upload.dto.BeneficiaryRequest; import com.interswitchng.techquest.autopay.sdk.beneficiary.upload.dto.UploadBeneficiaryRequest; import com.interswitchng.techquest.autopay.sdk.lib.utils.SecurityUtils; public class BeneficiaryUploadSecurityUtils extends SecurityUtils{ public String getBeneficiaryUploadTransactionParameters(UploadBeneficiaryRequest uploadBeneficiaryRequest) { String beneficiaryRequestTransactionParameters = ""; ArrayList<String> parameterList = getTransactionParametersList(uploadBeneficiaryRequest); for(String str : parameterList) if(!SecurityUtils.isNullorEmpty(str)) beneficiaryRequestTransactionParameters += "&" + str; return beneficiaryRequestTransactionParameters; } private ArrayList<String> getTransactionParametersList(UploadBeneficiaryRequest uploadBeneficiaryRequest) { BeneficiaryRequest beneficiaryRequestArr[] = uploadBeneficiaryRequest.getBeneficiarys(); ArrayList<String> parameterList = new ArrayList<String>(); parameterList.add(SecurityUtils.isNullorEmpty(uploadBeneficiaryRequest.getTerminalId()) ? "" : uploadBeneficiaryRequest.getTerminalId()); parameterList.add(SecurityUtils.isNullorEmpty(uploadBeneficiaryRequest.getBatchName()) ? "" : uploadBeneficiaryRequest.getBatchName()); parameterList.add(SecurityUtils.isNullorEmpty(uploadBeneficiaryRequest.getSourceAccount()) ? "" : uploadBeneficiaryRequest.getSourceAccount()); parameterList.add(getAccountNumbersTransactionParameter(beneficiaryRequestArr)); parameterList.add(getBeneficiaryNamesTransactionParameter(beneficiaryRequestArr)); parameterList.add(getBeneficiaryCodesTransactionParameter(beneficiaryRequestArr)); parameterList.add(getMaxPayableAmountsTransactionParameter(beneficiaryRequestArr)); return parameterList; } private String getAccountNumbersTransactionParameter(BeneficiaryRequest[] beneficiaryRequestArr) { String node = ""; for(BeneficiaryRequest beneficiaryRequest: beneficiaryRequestArr) node += SecurityUtils.isNullorEmpty(beneficiaryRequest.getAccountNumber()) ? "" : beneficiaryRequest.getAccountNumber(); return node; } private String getBeneficiaryNamesTransactionParameter(BeneficiaryRequest[] beneficiaryRequestArr) { String node = ""; for(BeneficiaryRequest beneficiaryRequest: beneficiaryRequestArr) node += SecurityUtils.isNullorEmpty(beneficiaryRequest.getBeneficiaryName()) ? "" : beneficiaryRequest.getBeneficiaryName(); return node; } private String getBeneficiaryCodesTransactionParameter(BeneficiaryRequest[] beneficiaryRequestArr) { String node = ""; for(BeneficiaryRequest beneficiaryRequest: beneficiaryRequestArr) node += SecurityUtils.isNullorEmpty(beneficiaryRequest.getBeneficiaryCode()) ? "" : beneficiaryRequest.getBeneficiaryCode(); return node; } private String getMaxPayableAmountsTransactionParameter(BeneficiaryRequest[] beneficiaryRequestArr) { String node = ""; for(BeneficiaryRequest beneficiaryRequest: beneficiaryRequestArr) node += SecurityUtils.isNullorEmpty(beneficiaryRequest.getMaxPayableAmount()) ? "" : beneficiaryRequest.getMaxPayableAmount(); return node; } }
true
c7e1b42e66c3fa95b8e143245b246cdfdca035e0
Java
EdFrota/overwatchapi
/src/main/java/com/overwatch/api/repository/HeroRepository.java
UTF-8
438
2.328125
2
[]
no_license
package com.overwatch.api.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.overwatch.api.model.Hero; /** * Repository to deal with {@link Hero} * * @author edmundofrota */ public interface HeroRepository extends JpaRepository<Hero, Integer> { /** * Find {@link Hero} by name. * * @param name hero name. * @return {@link Hero} filtered by name. */ Hero findByName(String name); }
true
4e91ce318ed0518a1b272edeb9039aa4aa76fef0
Java
vytjan/buggyCommits
/src/versioningSystem/bean/BlameBean.java
UTF-8
1,875
2.15625
2
[]
no_license
package versioningSystem.bean; import java.util.Date; import java.util.Vector; public class BlameBean { private String bugCommitId; private String preBugCommitId; private String authorName; private String fileName; private Vector<String> addedLines; private Vector<String> removedLines; private String addedNumber; private String removedNumber; private Date fixCommitDate; private Date bugCommitDate; public String getName() { return fileName; } public void setName(String fileName) { this.fileName = fileName; } public String getAuthor() { return authorName; } public void setAuthor(String author) { this.authorName = author; } public Vector<String> getAddedLines() { return addedLines; } public void setAddedLines(Vector<String> addedLines) { this.addedLines = addedLines; } public Vector<String> getRemovedLines() { return removedLines; } public void setRemovedLines(Vector<String> removedLines) { this.removedLines = removedLines; } public String getBugCommitId() { return bugCommitId; } public void setCommitId(String bugCommitId) { this.bugCommitId = bugCommitId; } public String getPreBugCommitId() { return preBugCommitId; } public void setPreBugCommitId(String preBugCommitId) { this.preBugCommitId = preBugCommitId; } public String getAddedNumber() { return addedNumber; } public void setAddedNumber(String addedNumber) { this.addedNumber = addedNumber; } public String getRemovedNumber() { return removedNumber; } public void setRemovedNumber(String removedNumber) { this.removedNumber = removedNumber; } public Date getFixDate() { return fixCommitDate; } public void setFixDate(Date fixDate) { this.fixCommitDate = fixDate; } public Date getBugDate() { return bugCommitDate; } public void setBugDate(Date bugDate) { this.bugCommitDate = bugDate; } }
true
f74b2cc5d6148fef1e6f391f72e66cf56b09e779
Java
darwink/Themis
/dealer/src/test/java/com/jdc/themis/dealer/data/hibernate/type/TestPersistentTimestamp.java
UTF-8
3,072
2.25
2
[]
no_license
package com.jdc.themis.dealer.data.hibernate.type; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Calendar; import java.util.GregorianCalendar; import javax.time.calendar.LocalDateTime; import javax.time.calendar.TimeZone; import junit.framework.Assert; import org.hibernate.HibernateException; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class TestPersistentTimestamp { private PersistentTimestamp timestamp; @Mock private ResultSet rs; @Mock private PreparedStatement ps; @Before public void setup() { MockitoAnnotations.initMocks(this); rs = mock(ResultSet.class); ps = mock(PreparedStatement.class); timestamp = new PersistentTimestamp(); } @Test public void checkSqlTypes() { Assert.assertEquals(Types.TIMESTAMP, timestamp.sqlTypes()[0]); } @Test public void checkEquals() { Assert.assertTrue(timestamp.equals(LocalDateTime.of(2013, 8, 1, 11, 23) .atZone(TimeZone.UTC).toInstant(), LocalDateTime.of(2013, 8, 1, 11, 23).atZone(TimeZone.UTC) .toInstant())); Assert.assertFalse(timestamp.equals(LocalDateTime .of(2013, 8, 1, 11, 23).atZone(TimeZone.UTC).toInstant(), LocalDateTime.of(2013, 9, 1, 11, 23).atZone(TimeZone.UTC) .toInstant())); Assert.assertFalse(timestamp.equals(null, LocalDateTime.of(2013, 9, 1, 11, 23).atZone(TimeZone.UTC) .toInstant())); } @Test public void safeGet() throws HibernateException, SQLException { final Date date = new Date(new java.util.Date().getTime()); when(rs.getTimestamp("timestamp")).thenReturn( new java.sql.Timestamp(date.getTime())); final Calendar c = new GregorianCalendar(); c.setTime(date); final Object result = timestamp.nullSafeGet(rs, new String[] { "timestamp" }, null); Assert.assertNotNull(result); } @Test public void safeGetNull() throws HibernateException, SQLException { when(rs.getTimestamp("timestamp")).thenReturn(null); final Object result = timestamp.nullSafeGet(rs, new String[] { "timestamp" }, null); Assert.assertEquals(null, result); } @Test public void safeGetWasNull() throws HibernateException, SQLException { when(rs.wasNull()).thenReturn(true); final Object result = timestamp.nullSafeGet(rs, new String[] { "timestamp" }, null); Assert.assertEquals(null, result); } @Test public void safeSet() throws HibernateException, SQLException { timestamp.nullSafeSet(ps, LocalDateTime.of(2013, 8, 1, 11, 23).atZone(TimeZone.UTC) .toInstant(), 1); verify(ps).setTimestamp(eq(1), any(java.sql.Timestamp.class)); } @Test public void safeSetNull() throws HibernateException, SQLException { timestamp.nullSafeSet(ps, null, 1); verify(ps).setNull(1, Types.TIMESTAMP); } }
true
2797663544de3ee558a4fec11a07429b917de869
Java
harisraza999/primeflix
/app/src/main/java/com/rcloud/netflix/MyWalletActivity.java
UTF-8
53,458
1.507813
2
[]
no_license
package com.rcloud.netflix; import android.app.Activity; import android.app.ProgressDialog; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.json.JSONException; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.AsyncTask; import androidx.appcompat.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.braintreepayments.api.dropin.DropInActivity; import com.braintreepayments.api.dropin.DropInRequest; import com.braintreepayments.api.dropin.DropInResult; import com.braintreepayments.api.interfaces.HttpResponseCallback; import com.braintreepayments.api.internal.HttpClient; import com.braintreepayments.api.models.PaymentMethodNonce; import com.classes.purchaselogic.JSONParser; import com.example.config.config; import com.example.util.Constant; import com.example.util.PrefManager; import com.google.android.material.textfield.TextInputEditText; import com.paytm.pgsdk.PaytmOrder; import com.paytm.pgsdk.PaytmPGService; import com.paytm.pgsdk.PaytmPaymentTransactionCallback; import com.razorpay.Checkout; import com.razorpay.PaymentResultListener; import com.rilixtech.CountryCodePicker; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Random; import instamojo.library.InstamojoPay; import instamojo.library.InstapayListener; import static com.example.util.Constant.PLANDAYS; import static com.example.util.Constant.PLANID; import static com.example.util.Constant.PLANNAME; import static com.example.util.Constant.PLANPRICE; public class MyWalletActivity extends AppCompatActivity implements PaytmPaymentTransactionCallback, PaymentResultListener { // Progress Dialog private ProgressDialog pDialog; // Creating JSON Parser object private final JSONParser jsonParser = new JSONParser(); private final JSONParserString jsonParserString = new JSONParserString(); // url to get all products list private static final String url = config.mainurl + "payment.php"; private static final String urlpaytmchecksum = config.paytmchecksum + "generateChecksum.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; //instamojo private static final String TAG_INSTA_ORDERID = "instaorderid"; private static final String TAG_INSTA_TXNID = "instatxnid"; private static final String TAG_INSTA_PAYMENTID = "instapaymentid"; private static final String TAG_INSTA_TOKEN = "instatoken"; private String balance; private String email; private String number; private TextView walletBalance; //Prefrance private static PrefManager prf; //paytm private String paytmemail; private String paytmphone; private String paytmamount; private String paytmpurpose; private String paytmbuyername; private String paytmorder_id; private String paytmchecksumhash; //instamojo InstapayListener listener; InstamojoPay instamojoPay; private String addamount; private String instaorderid; private String instatoken; private String instapaymentid; private String instatxnid; private int success; //Paypal final int REQUEST_CODE = 1; final String get_token = config.mainurl + "paypal/main.php"; final String send_payment_details = config.mainurl + "paypal/checkout.php"; String token, paypalamount; HashMap<String, String> paramHash; public String stringNonce; //GooglePay private String googleamount; public String GOOGLE_PAY_PACKAGE_NAME = "com.google.android.apps.nbu.paisa.user"; public int GOOGLE_PAY_REQUEST_CODE = 123; private CountryCodePicker ccp; private TextInputEditText phoneed; private String planid; private String planname; private String planprice; private String plandays; Toolbar toolbar; public LinearLayout paytmln, googleln, paypalln, instamojoln, razorpayln, paykunln, traknpayln; public RadioButton paytm, google, paypal, instamojo, razorpay, paykun, traknpay; public void PaytmAddMoney(String email, String phone, String amount, String purpose, String buyername) { paytmemail = email; paytmphone = phone; paytmamount = amount; paytmpurpose = purpose; paytmbuyername = buyername; final int min = 1000; final int max = 10000; final int random = new Random().nextInt((max - min) + 1) + min; paytmorder_id = prf.getString(Constant.USER_ID) +random; // Join Player in Match in Background Thread new GetChecksum().execute(); } public void GooglePayAddMoney(String email, String number, String amount, String add_money_to_wallet, String name) { googleamount = amount; Uri uri = new Uri.Builder() .scheme("upi") .authority("pay") .appendQueryParameter("pa", config.UPI) .appendQueryParameter("pn", config.MERCHANTNAME) // .appendQueryParameter("mc", "your-merchant-code") // .appendQueryParameter("tr", "your-transaction-ref-id") .appendQueryParameter("tn", add_money_to_wallet) .appendQueryParameter("am", amount) .appendQueryParameter("cu", "INR") // .appendQueryParameter("url", "your-transaction-url") .build(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(uri); intent.setPackage(GOOGLE_PAY_PACKAGE_NAME); startActivityForResult(intent, GOOGLE_PAY_REQUEST_CODE); } // private void PaykunAddMoney(String email, String number, String amount, String add_money_to_wallet, String name) { // // JSONObject object = new JSONObject(); // try { // object.put("merchant_id",config.merchantIdLive); // object.put("access_token",config.accessTokenLive); // object.put("customer_name",name); // object.put("customer_email",email); // object.put("customer_phone",number); // object.put("product_name",planname); // object.put("order_no",System.currentTimeMillis()); // order no. should have 10 to 30 character in numeric format // object.put("amount",amount); // minimum amount should be 10 // object.put("isLive",false); // need to send false if you are in sandbox mode // } catch (JSONException e) { // e.printStackTrace(); // } // new PaykunApiCall.Builder(MyWalletActivity.this).sendJsonObject(object); // Paykun api to initialize your payment and send info. // } // private void TraknpayAddMoney(String email, String phone, String amount, String purpose, String buyername) { // // addamount = amount; // // Random rnd = new Random(); // int n = 100000 + rnd.nextInt(900000); // // PaymentParams pgPaymentParams = new PaymentParams(); // pgPaymentParams.setAPiKey(config.PG_API_KEY); // pgPaymentParams.setAmount(amount); // pgPaymentParams.setEmail(email); // pgPaymentParams.setName(buyername); // pgPaymentParams.setPhone(phone); // pgPaymentParams.setOrderId(Integer.toString(n)); // pgPaymentParams.setCurrency("INR"); // pgPaymentParams.setDescription(purpose); // pgPaymentParams.setCity("RAJSTHAN"); // pgPaymentParams.setState("RAJSTHAN"); // pgPaymentParams.setAddressLine1("RAJSTHAN"); // pgPaymentParams.setAddressLine2("RAJSTHAN"); // pgPaymentParams.setZipCode("400001"); // pgPaymentParams.setCountry("IND"); // pgPaymentParams.setReturnUrl("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); // pgPaymentParams.setMode("LIVE"); // pgPaymentParams.setUdf1(""); // pgPaymentParams.setUdf2(""); // pgPaymentParams.setUdf3(""); // pgPaymentParams.setUdf4(""); // pgPaymentParams.setUdf5(""); // pgPaymentParams.setEnableAutoRefund("n"); // pgPaymentParams.setOfferCode("testcoupon"); // //pgPaymentParams.setSplitInfo("{\"vendors\":[{\"vendor_code\":\"24VEN985\",\"split_amount_percentage\":\"20\"}]}"); // // PaymentGatewayPaymentInitializer pgPaymentInitialzer = new PaymentGatewayPaymentInitializer(pgPaymentParams,MyWalletActivity.this); // pgPaymentInitialzer.initiatePaymentProcess(); // } class GetChecksum extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MyWalletActivity.this); pDialog.setMessage("Loading Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url * */ protected String doInBackground(String... args) { // Building Parameters Map<String, String> params = new HashMap<>(); params.put( "MID" , config.MID); params.put( "ORDER_ID" , paytmorder_id); params.put( "CUST_ID" , prf.getString(Constant.USER_ID)); // params.put( "MOBILE_NO" , paytmphone); params.put( "EMAIL" , prf.getString(Constant.USER_EMAIL)); params.put( "CHANNEL_ID" , "WAP"); params.put( "TXN_AMOUNT" , paytmamount); params.put( "WEBSITE" , config.WEBSITE); params.put( "INDUSTRY_TYPE_ID" , config.INDUSTRY_TYPE_ID); params.put( "CALLBACK_URL", config.CALLBACK_URL + paytmorder_id); // getting JSON string from URL JSONObject json = jsonParser.makeHttpRequest(urlpaytmchecksum, "POST", params); // Check your log cat for JSON reponse if(json != null){ try { paytmchecksumhash=json.has("CHECKSUMHASH")?json.getString("CHECKSUMHASH"):""; } catch (JSONException e) { e.printStackTrace(); } } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /* Updating parsed JSON data into ListView */ try { Map<String, String> paramMap = new HashMap<>(); paramMap.put( "MID" , config.MID); // Key in your staging and production MID available in your dashboard paramMap.put( "ORDER_ID" , paytmorder_id); paramMap.put( "CUST_ID" , prf.getString(Constant.USER_ID)); // paramMap.put( "MOBILE_NO" , paytmphone); paramMap.put( "EMAIL" , prf.getString(Constant.USER_EMAIL)); paramMap.put( "CHANNEL_ID" , "WAP"); paramMap.put( "TXN_AMOUNT" , paytmamount); paramMap.put( "WEBSITE" , config.WEBSITE); paramMap.put( "INDUSTRY_TYPE_ID" , config.INDUSTRY_TYPE_ID); paramMap.put( "CALLBACK_URL", config.CALLBACK_URL + paytmorder_id); paramMap.put( "CHECKSUMHASH" , paytmchecksumhash); PaytmOrder Order = new PaytmOrder((HashMap<String, String>) paramMap); // For Staging environment: // PaytmPGService Service = PaytmPGService.getStagingService(); // For Production environment: PaytmPGService Service = PaytmPGService.getProductionService(); Service.initialize(Order, null); Service.startPaymentTransaction(MyWalletActivity.this, true, true, MyWalletActivity.this); } catch (Exception e) { System.out.println("Rjn_paytm"+e.toString()); e.printStackTrace(); } } }); } } @Override public void someUIErrorOccurred(String inErrorMessage) { Toast.makeText(getApplicationContext(), "UI Error " + inErrorMessage, Toast.LENGTH_LONG).show(); } @Override public void onTransactionResponse(Bundle inResponse) { // getting JSON string from URL JSONObject json = null; try { String resstatus=inResponse.getString("STATUS"); if(resstatus.equalsIgnoreCase("TXN_SUCCESS")) { instaorderid = inResponse.getString("ORDERID"); instatxnid = inResponse.getString("TXNID"); addamount = inResponse.getString("TXNAMOUNT"); instapaymentid = inResponse.getString("CHECKSUMHASH"); instatoken = inResponse.getString("MID"); // Loading jsonarray in Background Thread new OneLoadAllProducts().execute(); } } catch (Exception e) { e.printStackTrace(); } // Toast.makeText(getApplicationContext(), "Payment Transaction response " + inResponse.toString(), Toast.LENGTH_LONG).show(); } @Override public void networkNotAvailable() { Toast.makeText(getApplicationContext(), "Network connection error: Check your internet connectivity", Toast.LENGTH_LONG).show(); } @Override public void clientAuthenticationFailed(String inErrorMessage) { Toast.makeText(getApplicationContext(), "Authentication failed: Server error" + inErrorMessage, Toast.LENGTH_LONG).show(); } @Override public void onErrorLoadingWebPage(int iniErrorCode, String inErrorMessage, String inFailingUrl) { Toast.makeText(getApplicationContext(), "Unable to load webpage " + inErrorMessage, Toast.LENGTH_LONG).show(); } @Override public void onBackPressedCancelTransaction() { Toast.makeText(getApplicationContext(), "Transaction cancelled", Toast.LENGTH_LONG).show(); } @Override public void onTransactionCancel(String inErrorMessage, Bundle inResponse) { Toast.makeText(getApplicationContext(), "Transaction Cancelled" + inResponse.toString(), Toast.LENGTH_LONG).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_wallet); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle(getString(R.string.payment)); getSupportActionBar().setTitle(getResources().getString(R.string.payment)); // Call the function callInstamojo to start payment here prf = new PrefManager(MyWalletActivity.this); planid = getIntent().getStringExtra(PLANID); planname = getIntent().getStringExtra(PLANNAME); planprice = getIntent().getStringExtra(PLANPRICE); plandays = getIntent().getStringExtra(PLANDAYS); paytmln = (LinearLayout) findViewById(R.id.paytmln); paypalln = (LinearLayout) findViewById(R.id.paypalln); instamojoln = (LinearLayout) findViewById(R.id.instamojoln); razorpayln = (LinearLayout) findViewById(R.id.razorpayln); googleln = (LinearLayout) findViewById(R.id.googleln); paykunln = (LinearLayout) findViewById(R.id.paykunln); traknpayln = (LinearLayout) findViewById(R.id.traknpayln); ccp = (CountryCodePicker) findViewById(R.id.ccp); phoneed = (TextInputEditText) this.findViewById(R.id.numbered); // ccp.registerPhoneNumberTextView(phoneed); // ccp.setOnCountryChangeListener(new CountryCodePicker.OnCountryChangeListener() { // @Override // public void onCountrySelected(Country selectedCountry) { // countrycode = selectedCountry.getPhoneCode(); // Toast.makeText(MobileVerifyActivity.this, "Updated " + selectedCountry.getPhoneCode(), Toast.LENGTH_SHORT).show(); // } // }); if(!config.paytm) { paytmln.setVisibility(View.GONE); } if(!config.paypal) { paypalln.setVisibility(View.GONE); } if(!config.instamojo) { instamojoln.setVisibility(View.GONE); } if(!config.razorpay) { razorpayln.setVisibility(View.GONE); } if(!config.google) { googleln.setVisibility(View.GONE); } if(!config.paykun) { paykunln.setVisibility(View.GONE); } if(!config.traknpay) { traknpayln.setVisibility(View.GONE); } paytm = (RadioButton) findViewById(R.id.radio0); paypal = (RadioButton) findViewById(R.id.radio01); instamojo = (RadioButton) findViewById(R.id.radio02); razorpay = (RadioButton) findViewById(R.id.radio03); google = (RadioButton) findViewById(R.id.radio5); paykun = (RadioButton) findViewById(R.id.radio7); traknpay = (RadioButton) findViewById(R.id.radio11); walletBalance = (TextView) findViewById(R.id.walletBalance); walletBalance.setText(config.currency + " "+planprice); Button pay = (Button) findViewById(R.id.pay); pay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!phoneed.getText().toString().trim().isEmpty() && phoneed.getText().toString().trim().length() >= 5) { String phone = ccp.getSelectedCountryCode()+phoneed.getText().toString().trim(); String phn = phoneed.getText().toString().trim(); if (paytm.isChecked()) { PaytmAddMoney(prf.getString(Constant.USER_EMAIL), phn, planprice, "Add Money to Wallet", prf.getString(Constant.USER_NAME)); } else if (paypal.isChecked()){ onBraintreeSubmit(email, phn, planprice, "Add Money to Wallet", prf.getString(Constant.USER_NAME)); } else if (instamojo.isChecked()){ callInstamojoPay(prf.getString(Constant.USER_EMAIL), phn, planprice, "Add Money to Wallet", prf.getString(Constant.USER_NAME)); } if (razorpay.isChecked()) { startPayment(prf.getString(Constant.USER_EMAIL), phn, planprice, "Add Money to Wallet", prf.getString(Constant.USER_NAME)); } else if (google.isChecked()) { GooglePayAddMoney(prf.getString(Constant.USER_EMAIL), phn, planprice, "Add Money to Wallet", prf.getString(Constant.USER_NAME)); } // else if (paykun.isChecked()) { // PaykunAddMoney(prf.getString(Constant.USER_EMAIL), phn, planprice, "Add Money to Wallet", prf.getString(Constant.USER_NAME)); // } if (traknpay.isChecked()) { // TraknpayAddMoney(prf.getString(Constant.USER_EMAIL), phn, planprice, "Add Money to Wallet", prf.getString(Constant.USER_NAME)); // } else { ((TextView) findViewById(R.id.errorMessage)).setText("Select Payment Mode"); ((TextView) findViewById(R.id.errorMessage)).setVisibility(View.VISIBLE); // Toast.makeText(MyWalletActivity.this, "Select Payment Mode", Toast.LENGTH_SHORT).show(); } } else { phoneed.setError("Please enter valid mobile number"); } } }); paytm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { paytm.setChecked(true); paypal.setChecked(false); instamojo.setChecked(false); razorpay.setChecked(false); google.setChecked(false); paykun.setChecked(false); traknpay.setChecked(false); } }); paypal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { paytm.setChecked(false); paypal.setChecked(true); instamojo.setChecked(false); razorpay.setChecked(false); google.setChecked(false); paykun.setChecked(false); traknpay.setChecked(false); } }); instamojo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { paytm.setChecked(false); paypal.setChecked(false); instamojo.setChecked(true); razorpay.setChecked(false); google.setChecked(false); paykun.setChecked(false); traknpay.setChecked(false); } }); razorpay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { paytm.setChecked(false); paypal.setChecked(false); instamojo.setChecked(false); razorpay.setChecked(true); google.setChecked(false); paykun.setChecked(false); traknpay.setChecked(false); } }); google.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { paytm.setChecked(false); paypal.setChecked(false); instamojo.setChecked(false); razorpay.setChecked(false); google.setChecked(true); paykun.setChecked(false); traknpay.setChecked(false); } }); paykun.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { paytm.setChecked(false); paypal.setChecked(false); instamojo.setChecked(false); razorpay.setChecked(false); google.setChecked(false); paykun.setChecked(true); traknpay.setChecked(false); } }); traknpay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { paytm.setChecked(false); paypal.setChecked(false); instamojo.setChecked(false); razorpay.setChecked(false); google.setChecked(false); paykun.setChecked(false); traknpay.setChecked(true); } }); //Paypal if(config.paypal) { new HttpRequest().execute(); } //Razorpay if(config.razorpay) { /* To ensure faster loading of the Checkout form, call this method as early as possible in your checkout flow. */ Checkout.preload(getApplicationContext()); } } public void callInstamojoPay(String email, String phone, String amount, String purpose, String buyername) { final Activity activity = MyWalletActivity.this; instamojoPay = new InstamojoPay(); IntentFilter filter = new IntentFilter("ai.devsupport.instamojo"); registerReceiver(instamojoPay, filter); JSONObject pay = new JSONObject(); try { pay.put("email", email); pay.put("phone", phone); pay.put("purpose", purpose); addamount=amount; pay.put("amount", amount); pay.put("name", buyername); pay.put("send_sms", true); pay.put("send_email", true); } catch (JSONException e) { e.printStackTrace(); System.out.println("Rjn_instamojo_error"+e.getMessage()); } initListener(); instamojoPay.start(activity, pay, listener); } private void initListener() { listener = new InstapayListener() { @Override public void onSuccess(String response) { System.out.println("Rjn_payment"+response); String[] str = response.split(":"); String[] split = str[1].split("="); instaorderid = split[1]; split = str[2].split("="); instatxnid = split[1]; split = str[3].split("="); instapaymentid = split[1]; str = str[4].split("="); instatoken = str[1]; // Loading jsonarray in Background Thread new OneLoadAllProducts().execute(); } @Override public void onFailure(int code, String reason) { System.out.println("Rjn_payment_error"+"code:"+code+"reason:"+reason); Toast.makeText(getApplicationContext(), "Failed: " + reason, Toast.LENGTH_LONG) .show(); } }; } class OneLoadAllProducts extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MyWalletActivity.this); pDialog.setMessage("Loading Please wait..."); pDialog.setIndeterminate(true); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url * */ protected String doInBackground(String... args) { // Building Parameters Map<String, String> params = new HashMap<>(); params.put(Constant.USER_ID, prf.getString(Constant.USER_ID)); params.put(Constant.USER_NAME, prf.getString(Constant.USER_NAME)); params.put(PLANID, planid); params.put("addamount", planprice); params.put(PLANDAYS, plandays); params.put(TAG_INSTA_ORDERID, instaorderid); params.put(TAG_INSTA_TXNID, instatxnid); params.put(TAG_INSTA_PAYMENTID, instapaymentid); params.put(TAG_INSTA_TOKEN, instatoken); params.put("status", "Add Money Success"); // getting JSON string from URL JSONObject json = jsonParser.makeHttpRequest(url, "POST", params); // Check your log cat for JSON reponse // Log.d("All jsonarray: ", json.toString()); try { // Checking for SUCCESS TAG success = json.getInt(TAG_SUCCESS); try { prf.setString(Constant.TAG_PLANID, json.getString(Constant.TAG_PLANID)); prf.setString(Constant.TAG_PLANACTIVE, json.getString(Constant.TAG_PLANACTIVE)); prf.setString(Constant.TAG_PLANDAYS, json.getString(Constant.TAG_PLANDAYS)); prf.setString(Constant.TAG_PLANSTART, json.getString(Constant.TAG_PLANSTART)); prf.setString(Constant.TAG_PLANEND, json.getString(Constant.TAG_PLANEND)); } catch (Exception e) { e.printStackTrace(); } } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /* Updating parsed JSON data into ListView */ if (success == 1) { // // jsonarray found // // Getting Array of jsonarray // // prf.setString(Constant.TAG_PLANID, planid); // prf.setString(Constant.TAG_PLANACTIVE, "Y"); // prf.setString(Constant.TAG_PLANDAYS, plandays); // // Date cur = Calendar.getInstance().getTime(); // // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // String formattedDate = df.format(cur); // String output = null; // // if (prf.getString(Constant.TAG_PLANEND).compareTo(formattedDate) > 0) { // System.out.println("Rajan_app_Date is after Date1_Plan is Active"); // // //add days // // plandays = String.valueOf(Integer.parseInt(prf.getString(Constant.TAG_PLANDAYS)) + Integer.parseInt(plandays)); // String dt = prf.getString(Constant.TAG_PLANEND); // Start date current date // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Calendar c = Calendar.getInstance(); // try { // c.setTime(sdf.parse(dt)); // } catch (ParseException e) { // e.printStackTrace(); // } // c.add(Calendar.DATE, Integer.parseInt(plandays)); // number of days to add, can also use Calendar.DAY_OF_MONTH in place of Calendar.DATE // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // output = sdf1.format(c.getTime()); // // } else { // System.out.println("app_Date is equal to Date1_No Premium Plan is Active"); // // //add days // // String dt = formattedDate; // Start date current date // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Calendar c = Calendar.getInstance(); // try { // c.setTime(sdf.parse(dt)); // } catch (ParseException e) { // e.printStackTrace(); // } // c.add(Calendar.DATE, Integer.parseInt(plandays)); // number of days to add, can also use Calendar.DAY_OF_MONTH in place of Calendar.DATE // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // output = sdf1.format(c.getTime()); // } // // System.out.println("Rajan_Current time => " + formattedDate); // System.out.println("Rajan_Current time_planend => " + output); // // prf.setString(Constant.TAG_PLANSTART, formattedDate); // prf.setString(Constant.TAG_PLANEND, output); Intent intent = new Intent(MyWalletActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); Toast.makeText(MyWalletActivity.this,"Payment done. Enjoy !",Toast.LENGTH_LONG).show(); } else { Toast.makeText(MyWalletActivity.this,"Something went wrong. Try again!",Toast.LENGTH_LONG).show(); } } }); } } //PayPal class OneLoadAllProductsPayPal extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog */ @Override protected void onPreExecute() { super.onPreExecute(); if (pDialog != null && pDialog.isShowing()) { pDialog = new ProgressDialog(MyWalletActivity.this); pDialog.setMessage("Loading Please wait..."); pDialog.setIndeterminate(true); pDialog.setCancelable(false); pDialog.show(); } } /** * getting All products from url */ protected String doInBackground(String... args) { // Building Parameters Map<String, String> params = new HashMap<>(); params.put(Constant.USER_ID, prf.getString(Constant.USER_ID)); params.put(Constant.USER_NAME, prf.getString(Constant.USER_NAME)); params.put(PLANID, planid); params.put("addamount", planprice); params.put(PLANDAYS, plandays); params.put("addamount", addamount); params.put(TAG_INSTA_ORDERID, stringNonce); params.put(TAG_INSTA_TXNID, "111"); params.put(TAG_INSTA_PAYMENTID, stringNonce); params.put(TAG_INSTA_TOKEN, "PayPal"); params.put("status", "Add Money Success"); // getting JSON string from URL JSONObject json = jsonParser.makeHttpRequest(url, "POST", params); // Check your log cat for JSON reponse // Log.d("All jsonarray: ", json.toString()); try { // Checking for SUCCESS TAG success = json.getInt(TAG_SUCCESS); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /* Updating parsed JSON data into ListView */ if (success == 1) { // jsonarray found // Getting Array of jsonarray prf.setString(Constant.TAG_PLANID, planid); prf.setString(Constant.TAG_PLANACTIVE, "Y"); prf.setString(Constant.TAG_PLANDAYS, plandays); Date cur = Calendar.getInstance().getTime(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = df.format(cur); //add days String dt = formattedDate; // Start date current date SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar c = Calendar.getInstance(); try { c.setTime(sdf.parse(dt)); } catch (ParseException e) { e.printStackTrace(); } c.add(Calendar.DATE, Integer.parseInt(plandays)); // number of days to add, can also use Calendar.DAY_OF_MONTH in place of Calendar.DATE SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String output = sdf1.format(c.getTime()); System.out.println("Rajan_Current time => " + formattedDate); System.out.println("Rajan_Current time_planend => " + output); prf.setString(Constant.TAG_PLANSTART, formattedDate); prf.setString(Constant.TAG_PLANEND, output); Intent intent = new Intent(MyWalletActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); Toast.makeText(MyWalletActivity.this,"Payment done. Enjoy !",Toast.LENGTH_LONG).show(); } else { Toast.makeText(MyWalletActivity.this,"Something went wrong. Try again!",Toast.LENGTH_LONG).show(); } } }); } } //Paypal @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { DropInResult result = data.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT); PaymentMethodNonce nonce = result.getPaymentMethodNonce(); stringNonce = nonce.getNonce(); System.out.println("Rajan_mylog_Result: " + stringNonce); // Send payment price with the nonce // use the result to update your UI and send the payment method nonce to your server if (!paypalamount.toString().isEmpty()) { // amount = paypalamount.toString(); paramHash = new HashMap<>(); paramHash.put("amount", paypalamount); paramHash.put("nonce", stringNonce); // sendPaymentDetails(); // Loading jsonarray in Background Thread new OneLoadAllProductsPayPalSendNonceDetails().execute(); } else Toast.makeText(MyWalletActivity.this, "Please enter a valid amount.", Toast.LENGTH_SHORT).show(); } else if (resultCode == Activity.RESULT_CANCELED) { // the user canceled Log.d("mylog", "user canceled"); } else { // handle errors here, an exception may be available in Exception error = (Exception) data.getSerializableExtra(DropInActivity.EXTRA_ERROR); System.out.println("Rajan_mylog_Error : " + error.toString()); } } //GooglePay if (requestCode == GOOGLE_PAY_REQUEST_CODE) { // Process based on the data in response. // System.out.println("Rajan_googlepay_result"+ requestCode + "resultCode" + resultCode); // System.out.println("Rajan_googlepay_result"+ data.toString() + data.getStringExtra("Status")); // System.out.println("Rajan_googlepay_result"+ data.toString() + data.getStringExtra("response")); String status = data.getStringExtra("Status"); if (status.equalsIgnoreCase("SUCCESS")) { try { instaorderid = data.getStringExtra("txnRef"); instatxnid = data.getStringExtra("txnId"); addamount = googleamount; instapaymentid = data.getStringExtra("txnRef"); instatoken = "12345"; // Loading jsonarray in Background Thread new OneLoadAllProducts().execute(); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(this, "Payment Failed", Toast.LENGTH_SHORT).show(); } } // //Traknpay // if (requestCode == PGConstants.REQUEST_CODE) { // if (resultCode == Activity.RESULT_OK) { // try { // String paymentResponse = data.getStringExtra(PGConstants.PAYMENT_RESPONSE); // System.out.println("paymentResponse: " + paymentResponse); // if (paymentResponse.equals("null")) { // System.out.println("Transaction Error!"); // Toast.makeText(this, "Payment Failed", Toast.LENGTH_SHORT).show(); // } else { // JSONObject response = new JSONObject(paymentResponse); // String status = response.getString("response_message"); // if (status.contains("successful")) { // // try { // // instaorderid = response.getString("transaction_id"); // instatxnid = response.getString("transaction_id"); // instapaymentid = response.getString("transaction_id"); // instatoken = "12345"; // // // Loading jsonarray in Background Thread // new OneLoadAllProducts().execute(); // // } catch (Exception e) { // e.printStackTrace(); // } // } else { // Toast.makeText(this, "Payment Failed", Toast.LENGTH_SHORT).show(); // } // } // // } catch (JSONException e) { // e.printStackTrace(); // } // // } // if (resultCode == Activity.RESULT_CANCELED) { // //Write your code if there's no result // Toast.makeText(this, "Payment Failed", Toast.LENGTH_SHORT).show(); // } // // } } public void onBraintreeSubmit(String email, String phone, String amount, String purpose, String buyername) { addamount = amount; paypalamount = amount; DropInRequest dropInRequest = new DropInRequest() .clientToken(token); startActivityForResult(dropInRequest.getIntent(this), REQUEST_CODE); } class OneLoadAllProductsPayPalSendNonceDetails extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MyWalletActivity.this); pDialog.setMessage("Loading Please wait..."); pDialog.setIndeterminate(true); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url */ protected String doInBackground(String... args) { // Building Parameters // getting JSON string from URL String json = jsonParserString.makeHttpRequest(send_payment_details, "POST", paramHash); // Check your log cat for JSON reponse // Log.d("All jsonarray: ", json.toString()); try { // Checking for SUCCESS TAG if (json.contains("Successful")) { Toast.makeText(MyWalletActivity.this, "Transaction successful", Toast.LENGTH_LONG).show(); } else Toast.makeText(MyWalletActivity.this, "Transaction failed", Toast.LENGTH_LONG).show(); Log.d("mylog", "Final Response: " + json.toString()); } catch (Exception e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /* Updating parsed JSON data into ListView */ // Loading jsonarray in Background Thread new OneLoadAllProductsPayPal().execute(); } }); } } private class HttpRequest extends AsyncTask { ProgressDialog progress; @Override protected void onPreExecute() { super.onPreExecute(); progress = new ProgressDialog(MyWalletActivity.this, android.R.style.Theme_DeviceDefault_Dialog); progress.setCancelable(false); progress.setMessage("We are contacting our servers for token, Please wait"); progress.setTitle("Getting token"); progress.show(); } @Override protected Object doInBackground(Object[] objects) { HttpClient client = new HttpClient(); client.get(get_token, new HttpResponseCallback() { @Override public void success(String responseBody) { Log.d("mylog", responseBody); runOnUiThread(new Runnable() { @Override public void run() { // Toast.makeText(MyWalletActivity.this, "Successfully got token", Toast.LENGTH_SHORT).show(); } }); token = responseBody; } @Override public void failure(Exception exception) { final Exception ex = exception; runOnUiThread(new Runnable() { @Override public void run() { System.out.println("Rajan_paypal_gettoken_failed" + ex.toString()); // Toast.makeText(MyWalletActivity.this, "Failed to get token: ", Toast.LENGTH_LONG).show(); } }); } }); return null; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); progress.dismiss(); } } //Razorpay public void startPayment(String email, String phone, String amount, String purpose, String buyername) { /* You need to pass current activity in order to let Razorpay create CheckoutActivity */ final Activity activity = this; final Checkout co = new Checkout(); co.setKeyID(config.ApiKey); try { JSONObject options = new JSONObject(); options.put("name", buyername); options.put("description", purpose); //You can omit the image option to fetch the image from dashboard options.put("image", "https://s3.amazonaws.com/rzp-mobile/images/rzp.png"); options.put("currency", config.Razorpay_currency); options.put("amount", Integer.parseInt(amount)*100); JSONObject preFill = new JSONObject(); preFill.put("email", email); preFill.put("contact", phone); options.put("prefill", preFill); co.open(activity, options); } catch (Exception e) { Toast.makeText(activity, "Error in payment: " + e.getMessage(), Toast.LENGTH_SHORT) .show(); e.printStackTrace(); } } /** * The name of the function has to be * onPaymentSuccess * Wrap your code in try catch, as shown, to ensure that this method runs correctly */ @SuppressWarnings("unused") @Override public void onPaymentSuccess(String razorpayPaymentID) { // getting JSON string from URL JSONObject json = null; try { System.out.println("Rajan_Payment Successful: " + razorpayPaymentID); instaorderid = razorpayPaymentID; instatxnid = razorpayPaymentID; addamount = planprice; instapaymentid = "CHECKSUMHASH"; instatoken = "MID"; // Loading jsonarray in Background Thread new OneLoadAllProducts().execute(); } catch (Exception e) { System.out.println("Rajan_Exception in onPaymentSuccess"+ e.getMessage()); e.printStackTrace(); } } /** * The name of the function has to be * onPaymentError * Wrap your code in try catch, as shown, to ensure that this method runs correctly */ @SuppressWarnings("unused") @Override public void onPaymentError(int code, String response) { try { Toast.makeText(this, "Payment failed: " + code + " " + response, Toast.LENGTH_SHORT).show(); } catch (Exception e) { System.out.println("Rajan_Exception in onPaymentError"+ e.getMessage()); e.printStackTrace(); } } // //Paykun // @Subscribe(sticky = true, threadMode = ThreadMode.MAIN) // public void getResults(Events.PaymentMessage message) { // if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_SUCCESS)){ // // do your stuff here // // message.getTransactionId() will return your failed or succeed transaction id // /* if you want to get your transaction detail call message.getTransactionDetail() // * getTransactionDetail return all the field from server and you can use it here as per your need // * For Example you want to get Order id from detail use message.getTransactionDetail().order.orderId */ // if(!TextUtils.isEmpty(message.getTransactionId())) { //// Toast.makeText(MyWalletActivity.this, "Your Transaction is succeed with transaction id : "+message.getTransactionId() , Toast.LENGTH_SHORT).show(); // Log.v(" order id "," getting order id value : "+message.getTransactionDetail().order.orderId); // // try { // // instaorderid = message.getTransactionDetail().order.orderId; // instatxnid = message.getTransactionId(); // addamount = planprice; // instapaymentid = message.getTransactionId(); // instatoken = "12345"; // // // Loading jsonarray in Background Thread // new OneLoadAllProducts().execute(); // // } catch (Exception e) { // e.printStackTrace(); // } // } // } // else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_FAILED)){ // // do your stuff here // Toast.makeText(MyWalletActivity.this,"Your Transaction is failed",Toast.LENGTH_SHORT).show(); // } // else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_SERVER_ISSUE)){ // // do your stuff here // Toast.makeText(MyWalletActivity.this,PaykunHelper.MESSAGE_SERVER_ISSUE,Toast.LENGTH_SHORT).show(); // }else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_ACCESS_TOKEN_MISSING)){ // // do your stuff here // Toast.makeText(MyWalletActivity.this,"Access Token missing",Toast.LENGTH_SHORT).show(); // } // else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_MERCHANT_ID_MISSING)){ // // do your stuff here // Toast.makeText(MyWalletActivity.this,"Merchant Id is missing",Toast.LENGTH_SHORT).show(); // } // else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_INVALID_REQUEST)){ // Toast.makeText(MyWalletActivity.this,"Invalid Request",Toast.LENGTH_SHORT).show(); // } // else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_NETWORK_NOT_AVAILABLE)){ // Toast.makeText(MyWalletActivity.this,"Network is not available",Toast.LENGTH_SHORT).show(); // } // } @Override protected void onStart() { super.onStart(); // //Paykun // // Register this activity to listen to event. // GlobalBus.getBus().register(this); } @Override protected void onStop() { super.onStop(); // //Paykun // // Unregister from activity // GlobalBus.getBus().unregister(this); } }
true
03cb369780f82c1a525c2a57dd7500cba73678c4
Java
anwajler/p2pm
/sources/pubsub/src/main/java/pl/edu/pjwstk/mteam/pubsub/core/RuleSet.java
UTF-8
3,009
3.03125
3
[]
no_license
package pl.edu.pjwstk.mteam.pubsub.core; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; /** * Class representing set of rules. * * @author Paulina Adamska [email protected] */ public abstract class RuleSet{ protected static final byte MODIFICATION_ADDRULE = 0; protected static final byte MODIFICATION_REMOVERULE = 1; /** * Rules stored in this set (indexed by operation type, they are * associated with). */ protected Hashtable<Short, Rule> rules; /** * Creates new set of rules. */ public RuleSet(){ rules = new Hashtable<Short, Rule>(); } /** * Checks whether specified operation isn't against defined rules. * @param o Operation to be checked. * @return Value indicating, whether specified operation is OK according to * defined rules. */ protected boolean matches(Operation o){ boolean result = false; Rule r = rules.get(o.getType()); if(r != null){ result = r.matches(o); } return result; } /** * Adds new rule or overrides existing one (if there * already is any rule for specified operation). * @param newRule New rule to be added to this set. * @return Replaced rule for specified operation (if it already * existed) or <code>null</code> otherwise. */ public Rule addRule(Rule newRule){ return rules.put(newRule.getOperation().getType(), newRule); } /** * Removes rule from this set. * @param operationType Value indicating, which rule remove. * @return Removed rule or <code>null</code> if there was no rule for * specified operation. */ public Rule removeRule(short operationType){ return rules.remove(operationType); } /** * @param operationType Type of operation requested rule is associated with. * @return Rule for operation of specified type or <code>null</code> if it * is not defined in this set. */ public Rule getRule(short operationType){ return rules.get(operationType); } public byte[] encode(){ ByteArrayOutputStream ostr = new ByteArrayOutputStream(); DataOutputStream dtstr = new DataOutputStream(ostr); try { //writing rules number dtstr.writeInt(rules.size()); Collection<Rule> rcont = rules.values(); Iterator<Rule> it = rcont.iterator(); while(it.hasNext()){ Rule r = (Rule)it.next(); byte[] encRule = r.encode(); //writing rule object length and rule itself dtstr.writeInt(encRule.length); dtstr.write(encRule); } } catch (IOException e) { e.printStackTrace(); } return ostr.toByteArray(); } public String toString(){ Collection<Rule> rcont = rules.values(); Iterator<Rule> it = rcont.iterator(); String result = "\nRules:\n"; int i = 0; while(it.hasNext()){ i++; result += i+") "+it.next(); } return result; } }
true
999f316ad8161154c05cdcaa031ece8c45398db6
Java
balavart/Marketplace
/src/test/java/com/epam/balaian/hibernate/services/UserServiceTest.java
UTF-8
2,573
2.296875
2
[]
no_license
package com.epam.balaian.hibernate.services; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.epam.balaian.hibernate.dao.UserDAO; import com.epam.balaian.hibernate.model.User; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; class UserServiceTest { @Mock private UserDAO userDAO; @InjectMocks private UserService userService; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); } @Test void checkUserAdditionTrue() { User addedUser = new User(1L); given(userDAO.addUser(any(User.class))).willReturn(addedUser); final boolean actualResult = userService.checkUserAddition(addedUser); assertThat(actualResult).isTrue(); verify(userDAO, times(1)).addUser(addedUser); } @Test void checkUserAdditionFalse() { given(userDAO.addUser(any(User.class))).willReturn(null); final boolean actualResult = userService.checkUserAddition(new User(1L)); assertThat(actualResult).isFalse(); verify(userDAO, times(1)).addUser(new User(1L)); } @Test void checkUserAdditionException() { assertThrows( Exception.class, () -> { given(userDAO.addUser(any(User.class))).willThrow(Exception.class); userService.checkUserAddition(any(User.class)); }); } @Test public void checkUserPresenceTrue() { User userReceived = new User(1L); given(userDAO.getUserById(anyLong())).willReturn(userReceived); final boolean actualResult = userService.checkUserPresence(userReceived); assertThat(actualResult).isTrue(); verify(userDAO, times(1)).getUserById(1L); } @Test public void checkUserPresenceFalse() { given(userDAO.getUserById(anyLong())).willReturn(null); final boolean actualResult = userService.checkUserPresence(new User(1L)); assertThat(actualResult).isFalse(); verify(userDAO, times(1)).getUserById(1L); } @Test public void checkUserPresenceException() { assertThrows( Exception.class, () -> { given(userDAO.getUserById(anyLong())).willThrow(Exception.class); userService.checkUserPresence(any(User.class)); }); } }
true
a9b5434d155a46f5fe66e612688a532592d6467b
Java
sonatype/sonatype-archetype
/archetype-common/src/main/java/org/apache/maven/archetype/ui/DefaultArchetypeGenerationQueryer.java
UTF-8
3,634
2.078125
2
[]
no_license
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.maven.archetype.ui; import org.apache.maven.archetype.common.ArchetypeConfiguration; import org.apache.maven.archetype.ui.prompt.Formatter; import org.apache.maven.archetype.ui.prompt.Prompter; import org.apache.maven.archetype.ui.prompt.PrompterException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; import java.util.Map; import static org.fusesource.jansi.Ansi.Attribute.INTENSITY_BOLD; import static org.fusesource.jansi.Ansi.Color.CYAN; import static org.fusesource.jansi.Ansi.Color.GREEN; import static org.fusesource.jansi.Ansi.ansi; @Component(role = ArchetypeGenerationQueryer.class) public class DefaultArchetypeGenerationQueryer implements ArchetypeGenerationQueryer, Initializable { @Requirement private Prompter prompter; public void initialize() throws InitializationException { prompter.setFormatter(new Formatter() { public String format(String message, List<String> possibleValues, String defaultReply) { if (defaultReply != null && defaultReply.trim().length() != 0) { return String.format("%s (%s)", message, ansi().fg(CYAN).a(defaultReply).reset()); } return message; } }); } public boolean confirmConfiguration(ArchetypeConfiguration archetypeConfiguration) throws PrompterException { StringWriter buff = new StringWriter(); PrintWriter out = new PrintWriter(buff); out.println(ansi().a(INTENSITY_BOLD).a("Confirm properties configuration").reset().a("...")); for (Map.Entry entry : archetypeConfiguration.getProperties().entrySet()) { out.format( "%s=%s", entry.getKey(), entry.getValue()).println(); } out.flush(); String answer = prompter.prompt(buff.toString(), "Y"); return "Y".equalsIgnoreCase(answer); } public String getPropertyValue(String requiredProperty, String defaultValue) throws PrompterException { StringWriter buff = new StringWriter(); PrintWriter out = new PrintWriter(buff); out.format("%s '%s'", ansi().a(INTENSITY_BOLD).a("Define value for property").reset(), ansi().fg(GREEN).a(requiredProperty).reset()); out.flush(); if ((defaultValue != null) && !defaultValue.equals("null")) { return prompter.prompt(buff.toString(), defaultValue); } else { return prompter.prompt(buff.toString()); } } }
true
9c761bf31a000e7bbd744fb99b65ace65f584b9b
Java
zzj0222/SpringCloudProject
/demo-parent/demo-member/src/main/java/com/demo/member/service/impl/FeignServiceImpl.java
UTF-8
480
1.648438
2
[]
no_license
//package com.demo.member.service.impl; // // //import com.demo.member.service.FeignService; //import com.demo.product.model.Product; //import org.springframework.stereotype.Service; // //import javax.annotation.Resource; //import java.util.List; // ///** // * @author zzj // * @create 2018-11-07 10:25 // * */ //@Service //public class FeignServiceImpl implements FeignService { // // @Override // public List<Product> getProductList() { // return null; // } //}
true
77313980ba06af668c17b181dcc68d11241d5535
Java
VladShapeshifter/BruceEckelTasks
/src/net/mindview/chapter11/PriorityQueueUse.java
UTF-8
483
2.953125
3
[]
no_license
package net.mindview.chapter11; import java.util.Iterator; import java.util.PriorityQueue; import java.util.Random; public class PriorityQueueUse { public static void main(String[] args) { PriorityQueue<Double> queue = new PriorityQueue<>(); Random rand = new Random(); for (int i = 0; i < 10; i++) { queue.offer(rand.nextDouble()); } Iterator<Double> it = queue.iterator(); while (it.hasNext()) { } } }
true
16df4f61eefe7874585d07ffd709d8f8fba4eee9
Java
sun-pyo/Network-Omock
/OmockClient/src/TimeMsg.java
UHC
545
2.46875
2
[]
no_license
// ChatMsg.java ä ޽ ObjectStream . import java.awt.Color; import java.awt.event.MouseEvent; import java.io.Serializable; import java.util.ArrayList; import javax.swing.ImageIcon; class TimeMsg implements Serializable { private static final long serialVersionUID = 1L; public String code; public String player; public int roomnum; public String time; public TimeMsg(String player, String code, int roomnum, String time) { this.code = code; this.player = player; this.roomnum = roomnum; this.time = time; } }
true
492db0e4463e30b80ead7e3a6bcca19313056653
Java
Madrid-7/Java_test
/2019_11_16_2/src/List.java
UTF-8
1,568
3.78125
4
[]
no_license
class ListNode { public int data; public ListNode next; public ListNode (int data) { this.data = data; this.next = null; } } class List { public ListNode head; public List() { this.head = null; } public void addFirst(int data) { if(this.head == null) { this.head = new ListNode(data); } else { ListNode node = new ListNode(data); node.next = this.head; this.head = node; } } public void printList() { ListNode now = this.head; while (now != null) { System.out.print(now.data + " "); now = now.next; } System.out.println(); } } class ListMake { public ListNode mergeTwoLists (ListNode headA, ListNode headB) { ListNode newHead = new ListNode(-1); ListNode tmp = newHead; while (headA != null && headB != null) { if(headA.data > headB.data) { tmp.next = headB; headB = headB.next; tmp = tmp.next; } else { tmp.next = headA; headA = headA.next; tmp = tmp.next; } } if(headA == null) { tmp.next = headB; } else { tmp.next = headA; } return newHead.next; } public void print(ListNode tmp) { while (tmp != null) { System.out.print(tmp.data +" "); tmp = tmp.next; } System.out.println(); } }
true
ab3f25f243261ca2b8f2ac829d7825167c4f2cc2
Java
WWWbinWWW/SpringPractice2
/practice2/src/main/java/org/wu/practice2/Practice2Application.java
UTF-8
1,316
2.40625
2
[]
no_license
package org.wu.practice2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList; import java.util.List; import static org.springframework.web.bind.annotation.RequestMethod.GET; @Controller @SpringBootApplication public class Practice2Application { public static void main(String[] args) { SpringApplication.run(Practice2Application.class, args); } @RequestMapping(value = "/",method = GET) public String index(Model model) { Person title = new Person("SpringBoot学习小组", 2018, 0); List<Person> people = new ArrayList<>(); Person p1 = new Person("郑璐琪", 18, 0); Person p2 = new Person("杨帅", 18, 0); Person p3 = new Person("杨伟民", 18, 0); Person p4 = new Person( "伍斌", 18, 0); Person p5 = new Person( "洪论武",18, 0); people.add(p1); people.add(p2); people.add(p3); people.add(p4); people.add(p5); model.addAttribute("GTitle", title); model.addAttribute("people", people); return "index"; } }
true
b65dd2eccadeb347f005878e08ef0010e9b27703
Java
bkumar1/Publications
/src/main/java/com/keywords/publications/service/PublicationService.java
UTF-8
1,081
2.078125
2
[]
no_license
package com.keywords.publications.service; import org.springframework.data.jpa.repository.Query; import com.keywords.publications.exception.PublicationException; import com.keywords.publications.model.PublicationRequest; import com.keywords.publications.model.PublicationResponse; /** * @author BrijendraK * */ public interface PublicationService { public PublicationResponse createPublication(PublicationRequest publicationRequest) throws PublicationException; public PublicationResponse deletePublication(PublicationRequest publicationRequest) throws PublicationException; public PublicationResponse updatePublication(PublicationRequest publicationRequest) throws PublicationException; @Query("SELECT P.titile FROM PublicationRequest P WHERE p.name= (:name) and p.genure=(:genure)") public PublicationResponse getNovels(String name,String genure) throws PublicationException; @Query("SELECT P.titile FROM PublicationRequest P WHERE p.name= (:name) and p.hero=(:hero)") public PublicationResponse getComics(String name,String hero) throws PublicationException; }
true
d7a6a887ccf01145db11b8f9b052d346b74a3c20
Java
MichalSzewczyk/decision-tree
/src/main/java/com/szewczyk/decisiontree/logic/Tree.java
UTF-8
195
2.109375
2
[]
no_license
package com.szewczyk.decisiontree.logic; import java.util.Set; public interface Tree { Attribute buildAndReturnRootAttribute(); Set<Attribute> getAttributes(); String toString(); }
true
7ba2569f0647d481121e6a1db7c60a019ed0e3f5
Java
teliwal/yanport
/src/main/java/com/ihoover/OutOfGridException.java
UTF-8
154
1.953125
2
[]
no_license
package com.ihoover; public class OutOfGridException extends Exception{ public OutOfGridException(String message) { super(message); } }
true
2ea8c01072395d218902e051c91e4692f4836b50
Java
wicknicks/cuenet
/src/test/java/esl/cuenet/mapper/parsers/MappingParserTest.java
UTF-8
2,281
2.53125
3
[]
no_license
package esl.cuenet.mapper.parsers; import esl.cuenet.mapper.parser.MappingParser; import esl.cuenet.mapper.parser.ParseException; import esl.cuenet.mapper.tree.IParseTree; import esl.cuenet.mapper.tree.IParseTreeCreator; import org.junit.Test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.StringReader; public class MappingParserTest { public class ParseTreeCreatorTest implements IParseTreeCreator { @Override public void addOperator(String label) { System.out.println("Operator: " + label); } @Override public void addOperand(String operandValue) { System.out.println("Operand: " + operandValue); } @Override public void startSExpression() { } @Override public void endSExpression() { } @Override public void eof() { } @Override public IParseTree getTree() { return null; } } @Test public void doTest() throws ParseException { String example1 = "(:axioms\n" + " (:map @yale_bib:book book)\n" + " (:map @cmu_bib:book book))"; String example2 = "(:axioms\n" + " (:map @yale_bib:Book Book)\n" + " (:map @cmu_bib:Book Book))"; String example3 = "(:name (:lookup first-name) (:lookup last-name))"; parseFile("./src/main/javacc/test/test.2.map"); test(example1); test(example2); test(example3); } private void test(String example) throws ParseException { MappingParser parser = null; parser = new MappingParser( new StringReader(example)); parser.setIParseTreeCreator(new ParseTreeCreatorTest()); parser.parse_document(); System.out.println(""); } public void parseFile(String filename) throws ParseException { try { MappingParser parser = new MappingParser( new FileInputStream(filename)); parser.setIParseTreeCreator(new ParseTreeCreatorTest()); parser.parse_document(); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println(""); } }
true
62393b4d300e1dc6a66e9a21a85906fc0387ec93
Java
yexiaoyu/spring-boot-template
/gx-question-modules/gx-question-service/src/main/java/com/guanxun/service/UserService.java
UTF-8
927
2.109375
2
[]
no_license
package com.guanxun.service; import com.guanxun.mapper.*; import com.guanxun.model.*; import org.springframework.beans.factory.annotation.*; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.*; import java.util.List; @Service public class UserService { @Autowired private UserMapper userMapper; @Cacheable(value = "userCache") public User load(String usreId) { return userMapper.load(usreId); } public int insert(User user){ return userMapper.insert(user); } public int delete(int id){ return userMapper.delete(id); } public int update(User user){ return userMapper.update(user); } public List<User> findList(User user){ return userMapper.findList(user); } public List<User> findByNameOrAge(String name, Integer age){ return userMapper.findByNameOrAge(name, age); } }
true
36a7035f185347913967226f250d01d9f7a12a32
Java
brooktran/jeelee
/jchat/src/JTalkServer.java
UTF-8
11,825
2.859375
3
[]
no_license
/* * Simple Chat room Server written by Aviad Golan... */ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Button; import java.awt.Panel; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.TextField; import java.awt.TextArea; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.PrintWriter; import java.net.*; import java.util.Vector; public class JTalkServer extends Frame implements ActionListener, Runnable { //Data members: private static final long serialVersionUID = 1L; //Remove nag Eclipse warning. private Panel inPanel, outPanel; //Panels private TextArea output; //Output messages private int outCnt, maxCon,conTot; //Server properties private Button btnStart, btnExit; //Buttons private TextField status, port; //Editable text fields private Label lblPort; //Port label private ServerSocket inSock; //Server main socket mgr private Socket socket; //Temp Socket private boolean running; //Run flag private Thread thListen; //Listening thread private Vector cliSocks; //Clients sockets list private Vector cliNames; //Clients names list private Vector cliRoom; //Clients rooms list public ChatRoomsManager roomMgr; //Class Room Manager //Constructor public JTalkServer(String caption) { super(caption); setSize(new Dimension(500,500)); setLayout(new BorderLayout()); //Set Starting values: maxCon = 200; conTot = 0; inSock = null; outCnt = 1; running = false; cliSocks = new Vector(maxCon); cliNames = new Vector(maxCon); cliRoom = new Vector(maxCon); roomMgr = new ChatRoomsManager(maxCon, 20); //Create the panels and buttons: outPanel = new Panel(new BorderLayout()); inPanel = new Panel(new FlowLayout()); inPanel.setBackground(Color.WHITE); outPanel.setBackground(Color.WHITE); output = new TextArea(); //output.setEnabled(false); output.setEditable(false); output.setBackground(Color.WHITE); outPanel.add(output, BorderLayout.CENTER); status = new TextField(" - To start server press 'Start Server' button... - "); status.setBackground(Color.PINK); status.setEditable(false); outPanel.add(status, BorderLayout.NORTH); btnStart = new Button("Start Server"); btnStart.addActionListener(this); btnStart.setBackground(Color.WHITE); inPanel.add(btnStart); btnExit = new Button("Exit"); btnExit.addActionListener(this); btnExit.setBackground(Color.BLACK); btnExit.setForeground(Color.WHITE); inPanel.add(btnExit); lblPort = new Label("Port:"); inPanel.add(lblPort); port = new TextField("3333"); inPanel.add(port); add(outPanel,BorderLayout.CENTER); add(inPanel, BorderLayout.SOUTH); setVisible(true); } //Buttons buttons and more buttons: public void actionPerformed(ActionEvent e) { //Start server button: if (e.getSource() == btnStart) { if (e.getActionCommand() == "Start Server") { btnStart.setLabel("Stop Server"); startServer(); } else { btnStart.setLabel("Start Server"); stopServer(); } } //Exit button: if (e.getSource() == btnExit) { stopServer(); System.exit(0); } } //Start server method: public void startServer() { //Tell admin we are starting. status("Starting Server please wait...\n", Color.YELLOW); //Set the listening socket: if (inSock == null) { try { inSock = new ServerSocket(Integer.parseInt(port.getText())); } catch (IOException e) { output("Error opening Socket: " + e.getMessage() + "\n"); stopServer(); } try { //We wait a bit here (for the flow)... Thread.sleep(1000); } catch (Exception e){ output(e.getMessage()); } output("Listening to port:" + port.getText() + "\n"); } else { output("Server is already running...\n"); } //We got here (phew) all is good so far... running = true; //redirect the main to the listening thread thListen = new Thread(this); thListen.start(); //show it and be proud: status("Server is Running...\n", Color.GREEN); } //The listening thread (will dispatch new thread at each connection -TCP) //I know UDP is a better approach here(for efficiency not security) but this will do just fine... public void run() { //run forever(or until you die muhahaha....): while (running){ //Accept any in bound connection request (to the limit): try { if (inSock != null) { socket = inSock.accept(); new ServerThread(this, socket).start(); //document connected peers: output("connected local port=" + socket.getLocalPort() + "remote port=" + socket.getPort() + "\n"); } } catch (IOException e) { output("Closing Sockets:\n"); output(e.getMessage() + "\n"); break; } } //kill listening thread: stopServer(); thListen.stop(); thListen.destroy(); } //Name check method (only 1 unique name for each user): synchronized boolean isNameTaken(String name) { int i; //check for names: for (i=0 ; i<cliNames.size() ; i++) { if (cliNames.get(i).equals(name)) { return true; } } return false; } //Add a client to client list: synchronized void addClient(Socket socket, String name) { cliSocks.add(socket); cliNames.add(name); cliRoom.add("Lobby"); roomMgr.memberJoin(name, "Lobby", null); output("User:" + name + " in Socket:" + socket.toString() + "Connected...\n"); conTot++; } //Remove a client from clients list: synchronized void removeClient(Socket socket, String name) { int i; for (i=0 ; i<cliNames.size() ; i++) { if ((cliNames.get(i) == name) && (cliSocks.get(i) == socket)) { roomMgr.memberLeave(name, getRoomName(socket)); cliRoom.remove(i); break; } } cliNames.remove(name); cliSocks.remove(socket); output("User:" + name + " in Socket:" + socket.toString() + " Disconnected...\n"); conTot--; } //Client wants to change his name (who am i to stop him?) synchronized void setClientName(Socket socket, String oldName, String newName) { int i; for (i=0 ; i<cliNames.size() ; i++) { if ((cliNames.get(i) == oldName) && (cliSocks.get(i) == socket)) { cliNames.set(i, newName); break; } } } //Clients room indexes synchronized void setClientRoom(Socket socket, String roomName) { int i; for (i=0 ; i<cliNames.size() ; i++) { if (cliSocks.elementAt(i).equals(socket)) { cliRoom.set(i, roomName); return; } } } //get the room name associated with socket public String getRoomName(Socket socket) { int i; for (i=0 ; i<cliNames.size() ; i++) { if (cliSocks.get(i) == socket) { return (String)cliRoom.get(i); } } //if something is wrong kick user to lobby //We should never get here... return "Lobby"; } //Stop server logic: public void stopServer() { status("Stopping Server please wait...\n", Color.YELLOW); if (inSock != null) { try { //Tell everyone server is going down: msgBrodcast("[ Server is now shutting down, sorry for that :) ]"); msgBrodcast("//diss"); inSock.close(); } catch (IOException e) { output("Error Closing Socket: " + e.getMessage() + "\n"); return; } inSock = null; try { //We wait a bit here... Thread.sleep(1200); } catch (Exception e){ System.out.println(e.getMessage()); } } //Set status to idle running = false; status("Server stopped...\n", Color.RED); } //This method will broadcast too all a message: synchronized void msgBrodcast(String msg) throws IOException { int i; PrintWriter tmpPw; Socket tmpSock; for(i=0 ; i<cliSocks.size() ; i++) { tmpSock = (Socket)cliSocks.elementAt(i); tmpPw = new PrintWriter(tmpSock.getOutputStream(),true); tmpPw.println(msg); tmpPw.flush(); } } //This method will broadcast to members in a room a message: synchronized void msgBrodcastRoom(String roomName, String msg) throws IOException { int i; PrintWriter tmpPw; Socket tmpSock; for(i=0 ; i<cliSocks.size() ; i++) { if (cliRoom.elementAt(i).equals(roomName)) { tmpSock = (Socket)cliSocks.elementAt(i); tmpPw = new PrintWriter(tmpSock.getOutputStream(),true); tmpPw.println(msg); tmpPw.flush(); } } } //This method will send a message to a specific user: synchronized void msgSendMember(String memberName, String msg) throws IOException { int i; PrintWriter tmpPw; Socket tmpSock; for(i=0 ; i<cliSocks.size() ; i++) { if (cliNames.elementAt(i).equals(memberName)) { tmpSock = (Socket)cliSocks.elementAt(i); tmpPw = new PrintWriter(tmpSock.getOutputStream(),true); tmpPw.println(msg); tmpPw.flush(); } } } //This method will update all users their friends lists: public void friendsBrodcast() { StringBuffer friendsList = new StringBuffer("//fr "); int i; for (i=0 ; i<cliNames.size() ; i++) { if (cliNames.get(i) != null) friendsList.append(cliNames.get(i)); if (i != cliNames.size()) { friendsList.append(","); } } try { msgBrodcast(friendsList.toString()); } catch (Exception e) { output("Error: " + e.getMessage()); } } //This method will update all users in a room their friends list: public void friendsRoomBrodcast(String roomName) { StringBuffer friendsList = new StringBuffer("//fr "); int i; for (i=0 ; i<cliSocks.size() ; i++) { if (cliRoom.elementAt(i).equals(roomName)) { if (cliNames.elementAt(i) != null) { if (roomMgr.isAdmin((String)cliNames.elementAt(i), (String)cliRoom.elementAt(i))) { friendsList.append("@" + cliNames.elementAt(i)); friendsList.append(","); } else { if (roomMgr.isWritePermission((String)cliNames.elementAt(i), (String)cliRoom.elementAt(i))) { friendsList.append(cliNames.elementAt(i)); friendsList.append(","); } else { friendsList.append("(-)" + cliNames.elementAt(i)); friendsList.append(","); } } } } } try { msgBrodcastRoom(roomName, friendsList.toString()); } catch (Exception e) { output("Error: " + e.getMessage()); } } //This method will check available user: synchronized boolean isClientExists(String clientName) throws IOException { int i; for(i=0 ; i<cliSocks.size() ; i++) { if (cliNames.elementAt(i).equals(clientName)) { return true; } } return false; } //Test if server is full: public boolean isServerFull() { if (conTot < maxCon) { return false; } else { return true; } } //Output method will append to log: public void output(String msg) { output.append("[" + outCnt + "] " + msg); outCnt++; } //Status will set the current server status: public void status(String msg, Color c) { status.setText(msg); status.setForeground(Color.BLACK); status.setBackground(c); output.append("[" + outCnt + "] " + msg); outCnt++; } //Finalize, if all goes as planned exit nicely... protected void finalize() throws Throwable { if (running) { stopServer(); } super.finalize(); } } /* EOF */
true
7b58aac8e0839fafd3effd60ce164cfea83aeb95
Java
LBCesar/WarehouseManagmentSystem
/app/src/main/java/com/example/warehousemanagmentsystem491b/Employee/DisplayCustomer.java
UTF-8
1,429
2.40625
2
[]
no_license
package com.example.warehousemanagmentsystem491b.Employee; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity; import com.example.warehousemanagmentsystem491b.R; import java.util.ArrayList; import java.util.List; public class DisplayCustomer extends AppCompatActivity { private ListView listView; private List<String> customerList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_customer); listView = findViewById(R.id.customer_listview); customerList = new ArrayList<>(); initializeList(); ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, customerList); listView.setAdapter(mAdapter); } public void initializeList() { customerList.add("Customer 1"); customerList.add("Customer 2"); customerList.add("Customer 3"); customerList.add("Customer 4"); customerList.add("Customer 5"); customerList.add("Customer 6"); customerList.add("Customer 7"); customerList.add("Customer 8"); customerList.add("Customer 9"); customerList.add("Customer 10"); customerList.add("Customer 11"); customerList.add("Customer 12"); } }
true
36a5f1c0ee917ad8c652b46691388fbf754df930
Java
lordjoe/spectra-cluster
/spectra-cluster-quality/branches/development/src/main/java/uk/ac/ebi/pride/spectracluster/clustersmilarity/AbstractClusterWriter.java
UTF-8
992
2.171875
2
[]
no_license
package uk.ac.ebi.pride.spectracluster.clustersmilarity; import com.lordjoe.utilities.TypedPredicate; import com.lordjoe.utilities.TypedVisitor; import uk.ac.ebi.pride.spectracluster.cluster.IPeptideSpectralCluster; import uk.ac.ebi.pride.spectracluster.io.DotClusterClusterAppender; import javax.annotation.Nonnull; /** * @author Rui Wang * @version $Id$ */ public class AbstractClusterWriter implements TypedVisitor<IPeptideSpectralCluster> { private final Appendable writer; private final OrPredicate<IPeptideSpectralCluster> tests; public AbstractClusterWriter(Appendable writer, TypedPredicate<IPeptideSpectralCluster>... testClauses) { this.writer = writer; tests = new OrPredicate(testClauses); } @Override public void visit(@Nonnull IPeptideSpectralCluster pT) { if (tests.apply(pT)) new DotClusterClusterAppender().appendCluster(writer, pT); } public Appendable getWriter() { return writer; } }
true
998564975009d4cc985337c49e30d38c483e7820
Java
desarrollosrosarinos/opensqldroid
/app/src/main/java/ar/com/desarrollosrosarinos/opensqldroid/threads/QueriesRunnerInterface.java
UTF-8
211
1.578125
2
[]
no_license
package ar.com.desarrollosrosarinos.opensqldroid.threads; public interface QueriesRunnerInterface { public void onProgressUpdate(Float progress); public void onQueryFinished(int code,String result); }
true
9979f036e264d89295683f7c3e58fa32f7a9c335
Java
cmzmasek/forester
/forester/java/src/org/forester/phylogeny/data/NodeData.java
UTF-8
17,293
1.953125
2
[]
no_license
// $Id: // FORESTER -- software libraries and applications // for evolutionary biology research and applications. // // Copyright (C) 2008-2009 Christian M. Zmasek // Copyright (C) 2008-2009 Burnham Institute for Medical Research // Copyright (C) 2000-2001 Washington University School of Medicine // and Howard Hughes Medical Institute // All rights reserved // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA // // Contact: phylosoft @ gmail . com // WWW: https://sites.google.com/site/cmzmasek/home/software/forester package org.forester.phylogeny.data; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; import org.forester.io.parsers.phyloxml.PhyloXmlUtil; import org.forester.phylogeny.data.Property.AppliesTo; import org.forester.util.ForesterUtil; public class NodeData implements PhylogenyData { private String _node_name; private Event _event; private List<Sequence> _sequences; private List<Taxonomy> _taxonomies; private List<Distribution> _distributions; private Date _date; private BinaryCharacters _binary_characters; private PropertiesList _properties; private List<Reference> _references; private List<Double> _vector; private NodeVisualData _node_visual_data; public NodeData() { init(); } private void init() { _node_name = ""; _event = null; _sequences = null; _taxonomies = null; _distributions = null; _date = null; _binary_characters = null; _properties = null; _references = null; _vector = null; _node_visual_data = null; } public void addDistribution( final Distribution distribution ) { if ( _distributions == null ) { _distributions = new ArrayList<Distribution>(); } _distributions.add( distribution ); } public void addReference( final Reference reference ) { if ( _references == null ) { _references = new ArrayList<Reference>(); } _references.add( reference ); } public void addSequence( final Sequence sequence ) { if ( _sequences == null ) { _sequences = new ArrayList<Sequence>(); } _sequences.add( sequence ); } public void addTaxonomy( final Taxonomy taxonomy ) { if ( _taxonomies == null ) { _taxonomies = new ArrayList<Taxonomy>(); } _taxonomies.add( taxonomy ); } @Override public StringBuffer asSimpleText() { throw new UnsupportedOperationException(); } @Override public StringBuffer asText() { throw new UnsupportedOperationException(); } @Override public PhylogenyData copy() { final NodeData new_data = new NodeData(); new_data.setNodeName( getNodeName() ); if ( ( getSequences() != null ) && ( getSequences().size() > 0 ) ) { new_data.setSequences( new ArrayList<Sequence>() ); for( final Sequence s : getSequences() ) { if ( s != null ) { new_data.addSequence( ( Sequence ) s.copy() ); } } } if ( isHasEvent() ) { new_data.setEvent( ( Event ) getEvent().copy() ); } if ( ( getTaxonomies() != null ) && ( getTaxonomies().size() > 0 ) ) { new_data.setTaxonomies( new ArrayList<Taxonomy>() ); for( final Taxonomy t : getTaxonomies() ) { if ( t != null ) { new_data.addTaxonomy( ( Taxonomy ) t.copy() ); } } } if ( isHasBinaryCharacters() ) { new_data.setBinaryCharacters( ( BinaryCharacters ) getBinaryCharacters().copy() ); } if ( ( getReferences() != null ) && ( getReferences().size() > 0 ) ) { new_data.setReferences( new ArrayList<Reference>() ); for( final Reference r : getReferences() ) { if ( r != null ) { new_data.addReference( ( Reference ) r.copy() ); } } } if ( ( getDistributions() != null ) && ( getDistributions().size() > 0 ) ) { new_data.setDistributions( new ArrayList<Distribution>() ); for( final Distribution d : getDistributions() ) { if ( d != null ) { new_data.addDistribution( ( Distribution ) d.copy() ); } } } if ( ( getNodeVisualData() != null ) && !getNodeVisualData().isEmpty() ) { new_data.setNodeVisualData( ( NodeVisualData ) getNodeVisualData().copy() ); } if ( isHasDate() ) { new_data.setDate( ( Date ) getDate().copy() ); } if ( isHasProperties() ) { new_data.setProperties( ( PropertiesList ) getProperties().copy() ); } return new_data; } public BinaryCharacters getBinaryCharacters() { return _binary_characters; } public Date getDate() { return _date; } /** * Convenience method -- always returns the first Distribution. * * @return Distribution */ public Distribution getDistribution() { return getDistribution( 0 ); } public Distribution getDistribution( final int index ) { if ( _distributions == null ) { return null; } return _distributions.get( index ); } public List<Distribution> getDistributions() { return _distributions; } public Event getEvent() { return _event; } public PropertiesList getProperties() { return _properties; } /** * Convenience method -- always returns the first Reference. * * @return Reference * */ public Reference getReference() { return getReference( 0 ); } public Reference getReference( final int index ) { if ( _references == null ) { return null; } return _references.get( index ); } public List<Reference> getReferences() { return _references; } /** * Convenience method -- always returns the first Sequence. * * @return Sequence */ public Sequence getSequence() { return getSequence( 0 ); } public Sequence getSequence( final int index ) { if ( _sequences == null ) { return null; } return _sequences.get( index ); } public List<Sequence> getSequences() { return _sequences; } public List<Taxonomy> getTaxonomies() { return _taxonomies; } /** * Convenience method -- always returns the first Taxonomy. * * @return Taxonomy * */ public Taxonomy getTaxonomy() { return getTaxonomy( 0 ); } public Taxonomy getTaxonomy( final int index ) { if ( _taxonomies == null ) { return null; } return _taxonomies.get( index ); } @Override public boolean isEqual( final PhylogenyData data ) { throw new NoSuchMethodError(); } public boolean isHasBinaryCharacters() { return getBinaryCharacters() != null; } public boolean isEmpty() { return ( ForesterUtil.isEmpty( _node_name ) && !isHasSequence() && !isHasTaxonomy() && !isHasBinaryCharacters() && !isHasDate() && !isHasDistribution() && !isHasEvent() && !isHasProperties() && !isHasReference() && ( ( _vector == null ) || _vector .isEmpty() ) ); } public boolean isHasDate() { return ( getDate() != null ) && ( !ForesterUtil.isEmpty( getDate().getDesc() ) || !ForesterUtil.isNull( getDate().getMax() ) || !ForesterUtil.isNull( getDate().getMin() ) || !ForesterUtil.isNull( getDate().getValue() ) || !ForesterUtil .isEmpty( getDate().getUnit() ) ); } public boolean isHasDistribution() { return ( ( ( getDistributions() != null ) && ( getDistributions().size() > 0 ) ) && ( ( !ForesterUtil .isEmpty( getDistribution().getDesc() ) ) || ( ( getDistribution().getPoints() != null ) && ( getDistribution().getPoints().size() > 0 ) ) || ( ( getDistribution() .getPolygons() != null ) && ( getDistribution().getPolygons().size() > 0 ) ) ) ); } public boolean isHasEvent() { return getEvent() != null; } public boolean isHasProperties() { return ( getProperties() != null ) && ( getProperties().size() > 0 ); } public boolean isHasReference() { return ( ( getReferences() != null ) && ( getReferences().size() > 0 ) ) && ( !ForesterUtil.isEmpty( getReference().getDoi() ) || !ForesterUtil.isEmpty( getReference() .getDescription() ) ); } public boolean isHasSequence() { return ( getSequences() != null ) && ( getSequences().size() > 0 ) && ( getSequences().get( 0 ) != null ); } public boolean isHasTaxonomy() { return ( getTaxonomies() != null ) && ( getTaxonomies().size() > 0 ) && ( getTaxonomies().get( 0 ) != null ); } public void setBinaryCharacters( final BinaryCharacters binary_characters ) { _binary_characters = binary_characters; } public void setDate( final Date date ) { _date = date; } /** * Convenience method -- always sets the first Distribution. * */ public void setDistribution( final Distribution distribution ) { if ( _distributions == null ) { _distributions = new ArrayList<Distribution>(); } if ( _distributions.size() == 0 ) { _distributions.add( distribution ); } else { _distributions.set( 0, distribution ); } } public void setDistribution( final int index, final Distribution distribution ) { if ( _distributions == null ) { _distributions = new ArrayList<Distribution>(); } _distributions.set( index, distribution ); } private void setDistributions( final List<Distribution> distributions ) { _distributions = distributions; } public void setEvent( final Event event ) { _event = event; } public void setProperties( final PropertiesList custom_data ) { _properties = custom_data; } public void setReference( final int index, final Reference reference ) { if ( _references == null ) { _references = new ArrayList<Reference>(); } _references.set( index, reference ); } /** * Convenience method -- always sets the first Reference. * */ public void setReference( final Reference reference ) { if ( _references == null ) { _references = new ArrayList<Reference>(); } if ( _references.size() == 0 ) { _references.add( reference ); } else { _references.set( 0, reference ); } } private void setReferences( final List<Reference> references ) { _references = references; } public void setSequence( final int index, final Sequence sequence ) { if ( _sequences == null ) { _sequences = new ArrayList<Sequence>(); } _sequences.set( index, sequence ); } /** * Convenience method -- always sets the first Sequence. * */ public void setSequence( final Sequence sequence ) { if ( _sequences == null ) { _sequences = new ArrayList<Sequence>(); } if ( _sequences.size() == 0 ) { _sequences.add( sequence ); } else { _sequences.set( 0, sequence ); } } private void setSequences( final List<Sequence> sequences ) { _sequences = sequences; } private void setTaxonomies( final List<Taxonomy> taxonomies ) { _taxonomies = taxonomies; } public void setTaxonomy( final int index, final Taxonomy taxonomy ) { if ( _taxonomies == null ) { _taxonomies = new ArrayList<Taxonomy>(); } _taxonomies.set( index, taxonomy ); } /** * Convenience method -- always sets the first Taxonomy. * */ public void setTaxonomy( final Taxonomy taxonomy ) { if ( _taxonomies == null ) { _taxonomies = new ArrayList<Taxonomy>(); } if ( _taxonomies.size() == 0 ) { _taxonomies.add( taxonomy ); } else { _taxonomies.set( 0, taxonomy ); } } @Override public StringBuffer toNHX() { final StringBuffer sb = new StringBuffer(); if ( isHasTaxonomy() ) { sb.append( getTaxonomy().toNHX() ); } if ( isHasSequence() ) { sb.append( getSequence().toNHX() ); } if ( isHasEvent() ) { sb.append( getEvent().toNHX() ); } return sb; } @Override public void toPhyloXML( final Writer writer, final int level, final String indentation ) throws IOException { if ( isHasTaxonomy() ) { for( final Taxonomy t : getTaxonomies() ) { if ( !t.isEmpty() ) { t.toPhyloXML( writer, level, indentation ); } } } if ( isHasSequence() ) { for( final Sequence s : getSequences() ) { if ( !s.isEmpty() ) { s.toPhyloXML( writer, level, indentation ); } } } if ( isHasEvent() ) { getEvent().toPhyloXML( writer, level, indentation ); } if ( isHasBinaryCharacters() ) { getBinaryCharacters().toPhyloXML( writer, level, indentation ); } if ( isHasDistribution() ) { for( final Distribution d : getDistributions() ) { d.toPhyloXML( writer, level, indentation ); } } if ( isHasDate() ) { getDate().toPhyloXML( writer, level, indentation ); } if ( isHasReference() ) { for( final Reference r : getReferences() ) { r.toPhyloXML( writer, level, indentation ); } } if ( isHasProperties() ) { getProperties().toPhyloXML( writer, level, indentation.substring( 0, indentation.length() - 2 ) ); } if ( ( level == 0 ) && ( getNodeVisualData() != null ) && !getNodeVisualData().isEmpty() ) { getNodeVisualData().toPhyloXML( writer, level, indentation.substring( 0, indentation.length() - 2 ) ); } if ( ( getVector() != null ) && !getVector().isEmpty() && ( ( getProperties() == null ) || getProperties() .getPropertiesWithGivenReferencePrefix( PhyloXmlUtil.VECTOR_PROPERTY_REF ).isEmpty() ) ) { final List<Property> ps = vectorToProperties( getVector() ); final String my_indent = indentation.substring( 0, indentation.length() - 2 ); for( final Property p : ps ) { p.toPhyloXML( writer, level, my_indent ); } } } private List<Property> vectorToProperties( final List<Double> vector ) { final List<Property> properties = new ArrayList<Property>(); for( int i = 0; i < vector.size(); ++i ) { properties.add( new Property( PhyloXmlUtil.VECTOR_PROPERTY_REF + i, String.valueOf( vector.get( i ) ), "", PhyloXmlUtil.VECTOR_PROPERTY_TYPE, AppliesTo.NODE ) ); } return properties; } public void setVector( final List<Double> vector ) { _vector = vector; } public List<Double> getVector() { return _vector; } public String getNodeName() { return _node_name; } public void setNodeName( final String node_name ) { _node_name = node_name; } public void setNodeVisualData( final NodeVisualData node_visual_data ) { _node_visual_data = node_visual_data; } public NodeVisualData getNodeVisualData() { return _node_visual_data; } }
true
7b5fed92887ff0f7e70c5bc11f33ac4465d54f76
Java
Jackwong5188/heima_project
/health_project/health_parent/health_service/src/main/java/com/itheima/health/service/impl/SetmealServiceImpl.java
UTF-8
9,372
2.3125
2
[]
no_license
package com.itheima.health.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.itheima.health.constant.RedisConstant; import com.itheima.health.dao.CheckItemDao; import com.itheima.health.dao.SetmealDao; import com.itheima.health.entity.PageResult; import com.itheima.health.pojo.CheckGroup; import com.itheima.health.pojo.CheckItem; import com.itheima.health.pojo.Setmeal; import com.itheima.health.service.CheckItemService; import com.itheima.health.service.SetmealService; import com.itheima.health.utils.QiniuUtils; import freemarker.template.Configuration; import freemarker.template.Template; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import redis.clients.jedis.JedisPool; import java.io.*; import java.util.HashMap; import java.util.List; import java.util.Map; @Service // dubbo提供 @Transactional public class SetmealServiceImpl implements SetmealService { @Autowired SetmealDao setmealDao; @Autowired JedisPool jedisPool; @Autowired // 注入FreeMarkerConfigurer FreeMarkerConfigurer freeMarkerConfigurer; @Value("${out_put_path}") //从属性文件读取输出目录的路径 String outputpath; //添加套餐,同时需要设置套餐和检查组的关联关系 @Override public void add(Setmeal setmeal, Integer[] checkgroupIds) { setmealDao.add(setmeal); //设置套餐和检查组的多对多关系 setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds); //将图片名称保存到Redis jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCE,setmeal.getImg()); //新增套餐后需要重新生成静态页面 generateMobileStaticHtml(); } //生成静态页面 public void generateMobileStaticHtml() { //准备模板文件中所需的数据 List<Setmeal> setmealList = this.findAll(); //生成套餐列表静态页面 generateMobileSetmealListHtml(setmealList); //生成套餐详情静态页面(多个) generateMobileSetmealDetailHtml(setmealList); } //生成套餐列表静态页面 public void generateMobileSetmealListHtml(List<Setmeal> setmealList) { Map<String,Object> map = new HashMap<>(); map.put("setmealList",setmealList); // 生成静态页面(参数1:静态页面的ftl文件名,参数2:静态页面的名称,参数三:map) this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",map); } //生成套餐详情静态页面(多个) public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) { for (Setmeal setmeal : setmealList) { Map<String,Object> map = new HashMap<>(); map.put("setmeal",this.findById(setmeal.getId())); // 生成静态页面(参数1:静态页面的ftl文件名,参数2:静态页面的名称,参数三:map) this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map); } } // 生成静态页面(参数1:静态页面的ftl文件名,参数2:静态页面的名称,参数三:map) public void generateHtml(String templateName,String htmlPageName,Map<String,Object> map) { Configuration configuration = freeMarkerConfigurer.getConfiguration(); Writer out = null; try { // 加载模版文件 Template template = configuration.getTemplate(templateName); // 生成数据 File docFile = new File(outputpath + "\\" + htmlPageName); out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile))); // 输出文件 template.process(map,out); } catch (Exception e) { e.printStackTrace(); } finally { try { if(out != null){ out.flush(); } } catch (IOException e2) { e2.printStackTrace(); } } } @Override public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) { // 二:使用Mybatis的分页插件,不使用分页的查询,也能完成(即不使用limit),在applicationContext-dao.xml中定义分页插件 // 1:初始化数据 PageHelper.startPage(currentPage,pageSize); // 2:查询,第一种,返回Page (Page由Mybatis的分页插件提供) Page<Setmeal> page = setmealDao.findPage(queryString); // 3:封装PageResult return new PageResult(page.getTotal(),page.getResult()); } @Override public Setmeal findById(Integer id) { return setmealDao.findById(id); } @Override public List<Integer> findCheckGroupIdsBySetmealId(Integer id) { return setmealDao.findCheckGroupIdsBySetmealId(id); } //编辑套餐,同时需要更新和检查组的关联关系 @Override public void edit(Setmeal setmeal, Integer[] checkgroupIds) { // 使用套餐id,查询数据库对应的套餐,获取数据库存放的img Setmeal setmeal_db = setmealDao.findById(setmeal.getId()); String img = setmeal_db.getImg(); // 如果页面传递的图片名称和数据库存放的图片名称不一致,说明图片更新,需要删除七牛云之前数据库的图片 if(setmeal.getImg() != null && !setmeal.getImg().equals(img)){ //删除七牛云之前数据库的图片 QiniuUtils.deleteFileFromQiniu(img); //将图片名称从Redis中删除,key值为setmealPicDbResources jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCE,img); //将图片名称从Redis中删除,key值为setmealPicResources jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCE,img); // 将页面更新的图片,存放到key值为SETMEAL_PIC_DB_RESOURCES的redis中 jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCE,setmeal.getImg()); } //1:根据套餐id删除中间表数据(清理原有关联关系) setmealDao.deleteAssociation(setmeal.getId()); //2:向中间表(t_setmeal_checkgroup)插入数据(建立套餐和检查组关联关系) addSetmealAndCheckGroup(setmeal.getId(),checkgroupIds); //3:更新套餐基本信息 setmealDao.edit(setmeal); // 重新使用Freemarker生成静态页面 generateMobileStaticHtml(); } // 删除套餐 @Override public void delete(Integer id) throws RuntimeException { // 使用套餐id,查询数据库对应的套餐,获取数据库存放的img Setmeal setmeal_db = setmealDao.findById(id); String img = setmeal_db.getImg(); // 需要先删除七牛云之前数据库的图片 if(img != null && !"".equals(img)){ //删除七牛云之前数据库的图片 QiniuUtils.deleteFileFromQiniu(img); //将图片名称从Redis中删除,key值为setmealPicDbResources jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCE,img); //将图片名称从Redis中删除,key值为setmealPicResources jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCE,img); } //使用套餐id,查询套餐和检查组中间表 Long count = setmealDao.findSetmealAndCheckGroupBySetmealId(id); if(count>0){ throw new RuntimeException("当前套餐和检查组之间存在关联关系,不能删除"); } setmealDao.delete(id); // 重新使用Freemarker生成静态页面 generateMobileStaticHtml(); } @Override public List<Setmeal> findAll() { return setmealDao.findAll(); } //查找套餐数量 @Override public List<Map<String, Object>> findSetmealCount() { return setmealDao.findSetmealCount(); } //向中间表(t_setmeal_checkgroup)插入数据(建立检查组和检查项关联关系) public void addSetmealAndCheckGroup(Integer setmealId,Integer[] checkgroupIds){ if(checkgroupIds != null && checkgroupIds.length>0){ for (Integer checkgroupId : checkgroupIds) { Map<String,Integer> map = new HashMap<>(); map.put("setmeal_id",setmealId); map.put("checkgroup_id",checkgroupId); setmealDao.setSetmealAndCheckGroup(map); } } } //设置套餐和检查组的多对多关系 private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) { if(checkgroupIds != null && checkgroupIds.length>0){ for (Integer checkgroupId : checkgroupIds) { Map<String, Integer> map = new HashMap<>(); map.put("checkgroup_id",checkgroupId); map.put("setmeal_id",id); setmealDao.setSetmealAndCheckGroup(map); } } } }
true
a74782db67ee25170573410fa418445b476d8977
Java
317432023/la
/la-api/src/main/java/com/jeetx/service/lottery/LotteryRobotPlantConfigService.java
UTF-8
353
1.65625
2
[]
no_license
package com.jeetx.service.lottery; import com.jeetx.bean.lottery.LotteryRobotPlantConfig; import com.jeetx.service.dao.DAO; public interface LotteryRobotPlantConfigService extends DAO<LotteryRobotPlantConfig> { public LotteryRobotPlantConfig findLotteryRobotPlantConfig(Integer lotteryRoomId); public void initRobotPlantConfig() throws Exception; }
true
b49d7edc973c12e2a68e017744fea7cd4770f89c
Java
Ionuc/books_summaries
/summaries/UllinkInterview/src/main/java/com/imesaros/ullinkinterview/livecoding/CustomStackWithArray.java
UTF-8
1,643
4.09375
4
[]
no_license
package com.imesaros.ullinkinterview.livecoding; /** * Custom Stack: Design a stack that supports the following operations: - push <number> --> pushes a number on top of the stack - pop --> returns the number removed from the top of the stack - inc <number_of_elements> <increment> --> increment the last <number_of_elements>(the numbers at the bottom of the stack) by <increment> */ public class CustomStackWithArray implements CustomStack{ private Integer[] values; private int nrOfValues = 0; public CustomStackWithArray(int initialSize){ if (initialSize <= 0){ throw new UnsupportedOperationException("Cannot create customStack with initial size negative"); } values = new Integer[initialSize]; } @Override public void push (Integer n){ resizeIfNeeded(); values[nrOfValues] = n; nrOfValues ++; } private void resizeIfNeeded(){ if (values.length == nrOfValues){ Integer[] newValues = new Integer[nrOfValues*2]; for (int i = 0; i < nrOfValues ; i ++){ newValues[i] = values[i]; } values = newValues; } } @Override public Integer pop(){ if (nrOfValues == 0){ return null; } Integer value = values[nrOfValues-1]; values[nrOfValues-1] = null; nrOfValues --; return value; } @Override public void inc(Integer nrOfElement, Integer increment){ if (nrOfElement >= nrOfValues){ return; } values[nrOfValues-nrOfElement-1] += increment; } }
true
56a9a95e7bc38e1aff1fa3d6936889756a48ed27
Java
xujunmeng/DesignPattern
/src/main/java/xxldemo/行为型/责任链/Client.java
UTF-8
326
2.28125
2
[]
no_license
package xxldemo.行为型.责任链; /** * @author james * @date 2020/6/24 */ public class Client { public static void main(String[] args) { Handler handler1 = new ConcreteHandler1(null); Handler handler2 = new ConcreteHandler2(handler1); handler2.handleRequest(RequestType.TYPE1); } }
true
d0488875af7fee8d23b41dceaf5e817589d3c19f
Java
AdelinGhanaem/jads
/src/main/java/com/sorting/Main.java
UTF-8
271
2.75
3
[]
no_license
package com.sorting; public class Main { public static void main(String[] args) { InversionsCounter algorithm = new InversionsCounter(); Integer[] integer = new Integer[]{6,5,4,3,2,1}; Integer count = algorithm.count(integer); System.out.print(count); } }
true
f64373b28e29f4b4fc84c0ce0aa0e67803eb525c
Java
Corrun/groupe-10
/src/jeuDesPetitsCheveaux/TypeCase.java
UTF-8
74
1.710938
2
[]
no_license
package jeuDesPetitsCheveaux; public enum TypeCase { VIDE, QUESTIONS; }
true
a935db0a08e198d2a8f7abb0751244b97eaf7b2f
Java
fqlovecoding/ffq_jfinal
/src/main/java/com/ffq/util/BaseConfig.java
UTF-8
1,026
1.984375
2
[]
no_license
package com.ffq.util; import com.jfinal.config.Constants; import com.jfinal.config.Handlers; import com.jfinal.config.Interceptors; import com.jfinal.config.JFinalConfig; import com.jfinal.config.Plugins; import com.jfinal.config.Routes; import com.jfinal.template.Engine; /** * @ClassName: BaseConfig * @Description: 全局配置 * @version: V1.0 * @date: 2019年5月23日 下午1:45:25 */ public class BaseConfig extends JFinalConfig { @Override public void configConstant(Constants me) { me.setDevMode(true); } @Override public void configRoute(Routes me) { RouteConfig.cfg(me); } @Override public void configEngine(Engine me) { //只需要后端接口,故这里不需要配置任何模板相关 } @Override public void configPlugin(Plugins me) { ModelConfig.cfg(me); } @Override public void configInterceptor(Interceptors me) { //拦截器一般与权限相关暂不需要 } @Override public void configHandler(Handlers me) { //拦截器一般与权限相关暂不需要 } }
true
c572d0c1476fafbe1150e67f66f1c6dff570004f
Java
sandance/MyPractice
/4C/Main.java
UTF-8
456
3.125
3
[]
no_license
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); HashMap<String, Integer > map = new HashMap<String, Integer> (); for (int i =0; i<n ; i++){ String s= sc.next(); if(!map.containsKey(s)) { System.out.println("OK"); map.put(s,1); } else { System.out.println(s+map.get(s)); map.put(s, map.get(s)+1); } } } }
true
c106fce665f9f88a79ac542a5e07d8f5fb3f4717
Java
svanini/CollegeDatabaseApplication
/app/src/main/java/com/example/collegedatabaseapplication/Activities/MainActivity.java
UTF-8
2,467
2.296875
2
[]
no_license
package com.example.collegedatabaseapplication.Activities; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.example.collegedatabaseapplication.Entities.Instructor; import com.example.collegedatabaseapplication.ArrayAdapters.InstructorArrayAdapter; import com.example.collegedatabaseapplication.ViewModels.InstructorViewModel; import com.example.collegedatabaseapplication.R; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView instructorsListView; private InstructorViewModel instructorViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); instructorsListView = findViewById(R.id.instructorsListView); instructorViewModel = new InstructorViewModel(getApplication()); instructorViewModel.getAllInstructors().observe(this, new Observer<List<Instructor>>() { @Override public void onChanged(List<Instructor> instructors) { if (instructors == null) { return; } InstructorArrayAdapter adapter = new InstructorArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, instructors); instructorsListView.setAdapter(adapter); } }); findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), AddInstructorActivity.class); startActivityForResult(intent, 0); } }); instructorsListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Instructor item = (Instructor) parent.getItemAtPosition(position); Intent intent = new Intent(getApplicationContext(), CourseListActivity.class); intent.putExtra("instructorId", item.id); startActivity(intent); } }); } }
true
c2b8d349e2ca775b46dcc7af250ad106120fc784
Java
zapa4234/PocketCS
/app/src/main/java/edu/csumb/moli9479/applicationpocketcs/CategoryDataDisplay.java
UTF-8
11,204
2.328125
2
[]
no_license
package edu.csumb.moli9479.applicationpocketcs; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.koushikdutta.ion.Ion; import java.util.HashMap; public class CategoryDataDisplay extends AppCompatActivity implements OnClickListener{ private int categoryID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_category_data_display); Button previous = (Button)findViewById(R.id.previousActivity); Button mainMenu = (Button)findViewById(R.id.mainMenu); previous.setOnClickListener(this); mainMenu.setOnClickListener(this); OurSQLiteDatabase database = OurSQLiteDatabase.getDatabase(this); try { if(getIntent().getExtras().getBoolean("isAdding")) { System.out.println(getIntent().getExtras().getInt("categoryToAdd")); System.out.println(getIntent().getExtras().getString("categoryName")); System.out.println(getIntent().getExtras().getString("categoryDescription")); System.out.println(getIntent().getExtras().getString("categoryImage")); System.out.println(getIntent().getExtras().getString("categoryLink")); categoryID = getIntent().getExtras().getInt("categoryToAdd"); switch (getIntent().getExtras().getInt("categoryToAdd")) { case 0: Algorithms algorithm = new Algorithms(); algorithm.setName(getIntent().getExtras().getString("categoryName")); algorithm.setDescription(getIntent().getExtras().getString("categoryDescription")); algorithm.setRuntime(getIntent().getExtras().getString("categoryRuntime")); algorithm.setImage(getIntent().getExtras().getString("categoryImage")); algorithm.setHelpfulLink(getIntent().getExtras().getString("categoryLink")); algorithm.setCategoryID(getIntent().getExtras().getInt("categoryInputNumber")); algorithm.setUserID(database.getAllAlgorithms().size()); database.addAlgorithm(algorithm); displayAlgorithmData(algorithm); break; case 1: DataStructures dataStructures = new DataStructures(); dataStructures.setName(getIntent().getExtras().getString("categoryName")); dataStructures.setDescription(getIntent().getExtras().getString("categoryDescription")); dataStructures.setRuntime(getIntent().getExtras().getString("categoryRuntime")); dataStructures.setImage(getIntent().getExtras().getString("categoryImage")); dataStructures.setHelpfulLink(getIntent().getExtras().getString("categoryLink")); dataStructures.setCategoryID(getIntent().getExtras().getInt("categoryInputNumber")); database.addDataStructure(dataStructures); displayDataStructureData(dataStructures); break; case 2: SoftwareDesign softwareDesign = new SoftwareDesign(); softwareDesign.setName(getIntent().getExtras().getString("categoryName")); softwareDesign.setDescription(getIntent().getExtras().getString("categoryDescription")); softwareDesign.setBenefits(getIntent().getExtras().getString("categoryBenefits")); softwareDesign.setCosts(getIntent().getExtras().getString("categoryCosts")); softwareDesign.setImage(getIntent().getExtras().getString("categoryImage")); softwareDesign.setHelpfulLink(getIntent().getExtras().getString("categoryLink")); softwareDesign.setCategoryID(getIntent().getExtras().getInt("categoryInputNumber")); softwareDesign.setUserID(database.getAllSoftwareDesigns().size()); database.addSoftwareDesign(softwareDesign); displaySoftwareDesignPatternData(softwareDesign); break; default: System.out.println("Error adding to database"); break; } } else { categoryID = getIntent().getExtras().getInt("categoryID"); switch (getIntent().getExtras().getInt("categoryID")) { case 0: HashMap<Integer, Algorithms> algorithms = database.getAllAlgorithms(); for (HashMap.Entry<Integer, Algorithms> algorithm : algorithms.entrySet()) { if(algorithm.getValue().getName().equals(getIntent().getExtras().getString("algorithmName"))) { displayAlgorithmData(algorithm.getValue()); break; } } break; case 1: HashMap<Integer, DataStructures> dataStructures = database.getAllDataStructures(); for (HashMap.Entry<Integer, DataStructures> dataStructure : dataStructures.entrySet()) { if(dataStructure.getValue().getName().equals(getIntent().getExtras().getString("dataStructureName"))) { displayDataStructureData(dataStructure.getValue()); break; } } break; case 2: HashMap<Integer, SoftwareDesign> softwareDesignPatterns = database.getAllSoftwareDesigns(); for (HashMap.Entry<Integer, SoftwareDesign> softwareDesign : softwareDesignPatterns.entrySet()) { if(softwareDesign.getValue().getName().equals(getIntent().getExtras().getString("softwareDesignName"))) { displaySoftwareDesignPatternData(softwareDesign.getValue()); break; } } break; default: break; } } }catch (Exception e) { System.out.println("Addition cancelled"); categoryID = getIntent().getExtras().getInt("categoryID"); } //http://bit.ly/2fXkXLa //algorithms1.setHelpfulLink("http://www.cc.gatech.edu/classes/cs3158_98_fall/quicksort.html"); //http://b.gatech.edu/2gLvfPF //http://bit.ly/2gNmW3x } public void displayAlgorithmData(Algorithms algorithm) { System.out.println(algorithm); TextView name = (TextView)findViewById((R.id.name)); name.setText(algorithm.getName()); TextView description = (TextView)findViewById(R.id.description); description.setText(algorithm.getDescription()); TextView runtime = (TextView)findViewById(R.id.runtime); runtime.setText(algorithm.getRuntime()); ImageView pseudocode = (ImageView)findViewById(R.id.pseudocode); try { Ion.with(pseudocode).load(algorithm.getImage()); } catch (Exception e) { e.printStackTrace(); } TextView links = (TextView)findViewById(R.id.links); links.setText(algorithm.getHelpfulLink()); Linkify.addLinks(links, Linkify.ALL); links.setLinksClickable(true); links.setMovementMethod(LinkMovementMethod.getInstance()); links.setHighlightColor(Color.BLUE); } public void displayDataStructureData(DataStructures dataStructure) { System.out.println(dataStructure); TextView name = (TextView)findViewById(R.id.name); name.setText(dataStructure.getName()); TextView description = (TextView)findViewById(R.id.description); description.setText(dataStructure.getDescription()); TextView runtime = (TextView)findViewById(R.id.runtime); runtime.setText(dataStructure.getRuntime()); ImageView pseudocode = (ImageView)findViewById(R.id.pseudocode); try { Ion.with(pseudocode).load(dataStructure.getImage()); } catch (Exception e) { e.printStackTrace(); } TextView links = (TextView)findViewById(R.id.links); links.setText(dataStructure.getHelpfulLink()); Linkify.addLinks(links, Linkify.ALL); links.setLinksClickable(true); links.setMovementMethod(LinkMovementMethod.getInstance()); links.setHighlightColor(Color.BLUE); } public void displaySoftwareDesignPatternData(SoftwareDesign softwareDesign) { System.out.println(softwareDesign); LinearLayout costLayout = (LinearLayout)findViewById(R.id.costs); TextView name = (TextView)findViewById(R.id.name); name.setText(softwareDesign.getName()); TextView description = (TextView)findViewById(R.id.description); description.setText(softwareDesign.getDescription()); TextView benefits = (TextView)findViewById(R.id.runtime); benefits.setText(softwareDesign.getBenefits()); TextView costs = new TextView(this); costs.setText(softwareDesign.getCosts()); costLayout.addView(costs); ImageView pseudocode = (ImageView)findViewById(R.id.pseudocode); try { Ion.with(pseudocode).load(softwareDesign.getImage()); } catch (Exception e) { e.printStackTrace(); } TextView links = (TextView)findViewById(R.id.links); links.setText(softwareDesign.getHelpfulLink()); Linkify.addLinks(links, Linkify.ALL); links.setLinksClickable(true); links.setMovementMethod(LinkMovementMethod.getInstance()); links.setHighlightColor(Color.BLUE); } public void onClick(View v) { Intent intent; Bundle extraInfo = new Bundle(); switch (v.getId()) { case R.id.previousActivity: intent = new Intent(this, CategoryScreen.class); extraInfo.putInt("categoryScreen", categoryID); intent.putExtras(extraInfo); startActivity(intent); break; case R.id.mainMenu: intent = new Intent(this, MainActivity.class); startActivity(intent); break; default: break; } } }
true
e4311f9358e274cd877c3009e46be0c17f26fa17
Java
shockwave4488/FRC-2018-Public
/main/java/org/usfirst/frc/team4488/robot/systems/Manipulator.java
UTF-8
13,256
2.03125
2
[ "MIT" ]
permissive
package org.usfirst.frc.team4488.robot.systems; import JavaRoboticsLib.ControlSystems.SimPID; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.NeutralMode; import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc.team4488.lib.util.PreferenceDoesNotExistException; import org.usfirst.frc.team4488.lib.util.PreferencesParser; import org.usfirst.frc.team4488.robot.Constants; import org.usfirst.frc.team4488.robot.Robot; import org.usfirst.frc.team4488.robot.RobotMap; import org.usfirst.frc.team4488.robot.loops.Loop; import org.usfirst.frc.team4488.robot.loops.Looper; import org.usfirst.frc.team4488.robot.operator.Controllers; import org.usfirst.frc.team4488.robot.operator.Logging; import org.usfirst.frc.team4488.robot.sensors.ArduinoAnalog; import org.usfirst.frc.team4488.robot.systems.PowerCore.ShifterState; public class Manipulator extends Subsystem { private WPI_TalonSRX m_slider1; private Solenoid clamp; private Solenoid rotater; private ArduinoAnalog arduinoAnalog; private SimPID pid; private PreferencesParser prefs = PreferencesParser.getInstance(); private boolean canRotateDown = false; private int RAMPRATE = 0; private double desiredPosition = 0; private double desiredSpeed = 0; // Ticks per 100 MS private double ticksToInches = 835; private double ticksPerRev = 4096; private double diameter = 1.75; private double powerCeiling = 1; private boolean xLastPressed = false; private boolean rightBumperLastPressed = false; private boolean rightTriggerLastPressed = false; private boolean isClamped = false; private boolean isRotated = false; private boolean isLatched = false; private boolean hasCube = false; private boolean locked = false; private boolean scoreRoutineRun = false; private static Manipulator sInstance; private Logging logger = Logging.getInstance(); private Controllers xbox; private Loop mLoop = new Loop() { @Override public void onStart(double timestamp) { canRotateDown = false; logger.writeToLogFormatted(this, "begin Manipulator.onStart"); synchronized (Manipulator.this) { setPosition(getPosition()); desiredPosition = getPosition(); clamp(); rotate(false); setHasCube(false); scoreRoutineRun = false; arduinoAnalog = ArduinoAnalog.getInstance(); xbox = Controllers.getInstance(); } } /** TODO */ @Override public void onLoop(double timestamp) { synchronized (Manipulator.this) { if (Forklift.getInstance().getCurrentHeight() < Constants.overrideManipHeight && !Robot.isAuto && canRotateDown && PowerCore.getInstance().getShifterState() == ShifterState.Forklift) { rotateDown(); setPosition(0); } if (!Robot.isAuto && Forklift.getInstance().getCurrentHeight() > Constants.liftSafetyCheckHeight) { canRotateDown = true; } if (!locked) { pid.setDesiredValue(desiredPosition); double power = pid.calcPID(getPosition()); SmartDashboard.putNumber("ManipPower", power); if (getPosition() >= Constants.manipulatorMax && power > 0) { power = 0; } else if (getPosition() <= Constants.manipulatorMin && power < 0) { power = 0; } set(power); } } } @Override public void onStop(double timestamp) { rotateUp(); clamp.set(false); isClamped = true; stop(); logger.writeToLogFormatted(this, "ending Manipulator.onStop"); } }; /** @return gets instance of manipulator */ public static Manipulator getInstance() { if (sInstance == null) { sInstance = new Manipulator(); } return sInstance; } public Manipulator() { logger.writeToLogFormatted(this, "begin Manipulator Constructor"); m_slider1 = new WPI_TalonSRX(RobotMap.MANIPULATOR_MOTOR); clamp = new Solenoid(RobotMap.MANIPULATOR_CLAMP); rotater = new Solenoid(RobotMap.MANIPULATOR_ROTATER); pid = new SimPID(); try { pid.setConstants( prefs.getDouble("ManipulatorP"), prefs.getDouble("ManipulatorI"), prefs.getDouble("ManipulatorD")); pid.setErrorEpsilon(prefs.getDouble("ManipulatorEps")); } catch (PreferenceDoesNotExistException e) { pid.setConstants(0.01, 0, 0); System.out.println("PID caught"); } pid.setDoneRange(0.125); m_slider1.configOpenloopRamp(RAMPRATE, 0); m_slider1.setNeutralMode(NeutralMode.Coast); m_slider1.setSensorPhase(true); m_slider1.setInverted(true); logger = Logging.getInstance(); } public void lock() { locked = true; } public void unLock() { locked = false; } public void setPosition(double newPosition) { if (newPosition != desiredPosition) logger.writeToLogFormatted(this, "setPosition(" + newPosition + ")"); if (desiredPosition > Constants.manipulatorSafeMax) { desiredPosition = Constants.manipulatorSafeMax; } else if (desiredPosition < Constants.manipulatorSafeMin) { desiredPosition = Constants.manipulatorSafeMin; } else { desiredPosition = newPosition; } } /** @return retrives the desired position of the manipulator */ public double getDesiredPosition() { return pid.getDesiredVal(); } /** @return gets the position of the manipulator */ public double getPosition() { return m_slider1.getSensorCollection().getQuadraturePosition() / ticksToInches; } /** @return tells of the manipulator is at its wanted position */ public boolean atDesiredPosition() { return pid.isDone(); } public void setDoneRange(double doneRange) { pid.setDoneRange(doneRange); } public void clamp() { if (Forklift.getInstance().getCurrentHeight() > Constants.liftSafetyCheckHeight || Intake.getInstance().isDeployed()) { clamp.set(false); isClamped = true; } } public void unClamp() { if (Forklift.getInstance().getCurrentHeight() > Constants.liftSafetyCheckHeight || Intake.getInstance().isDeployed()) { clamp.set(true); isClamped = false; hasCube = false; } } /** @return tells if the clamp is clamped */ public boolean isClamped() { return isClamped; } private void rotate(boolean val) { rotater.set(val); isRotated = val; } public void rotateDown() { rotate(true); } public void rotateUp() { rotate(false); } public boolean isRotated() { return isRotated; } private void set(double power) { if ((getPosition() > Constants.manipulatorMax && power > 0) || (getPosition() < Constants.manipulatorMin && power < 0)) { m_slider1.set(ControlMode.PercentOutput, 0); } else { m_slider1.set(ControlMode.PercentOutput, power); } } public void setPower(double power) { set(power); } public void bypassSetPower(double power) { m_slider1.set(ControlMode.PercentOutput, power); } public void slide(double throttle) { throttle = handleDeadband(throttle, .1); double pwm; double linearPower; linearPower = throttle; pwm = linearPower; if (pwm > 1.0) { pwm = 1.0; } else if (pwm < -1.0) { pwm = -1.0; } set(pwm); } /** * @param val * @param deadband * @return handles controller deadband */ private double handleDeadband(double val, double deadband) { if (Math.abs(val) > Math.abs(deadband)) { if (val > 0) { return (val - deadband) / (1 - deadband); } else { return (val + deadband) / (1 - deadband); } } else { return 0.0; } } // Doesnt work public void driveToSpeed(double ips) { configSpeedControl(); double ticksPer100MS = (ips * ticksToInches) / 10; // Divide by 10 to turn ticks per second into ticks per 100MS System.out.println(ticksPer100MS); desiredPosition = getPosition(); m_slider1.set(ControlMode.Velocity, ticksPer100MS); } /** @return Status of the hall effect */ public boolean getHallEffect() { return arduinoAnalog.getHallEffect(); } @Override public void stop() { set(0); desiredPosition = getPosition(); m_slider1.setNeutralMode(NeutralMode.Coast); logger.writeToLogFormatted(this, "stop()"); } public void zeroAtCurrent() { m_slider1 .getSensorCollection() .setQuadraturePosition((int) (Constants.manipulatorZeroOffset * ticksToInches), 0); logger.writeToLogFormatted(this, "Manipulator re-zeroed"); } @Override public void zeroSensors() { arduinoAnalog = ArduinoAnalog.getInstance(); if (!isLatched) { SmartDashboard.putBoolean("hall effect", getHallEffect()); if (getHallEffect() && arduinoAnalog.isGoodData()) { m_slider1 .getSensorCollection() .setQuadraturePosition((int) (Constants.manipulatorZeroOffset * ticksToInches), 0); isLatched = true; logger.writeToLogFormatted(this, "Manip zeroed"); } } } @Override public void registerEnabledLoops(Looper enabledLooper) { enabledLooper.register(mLoop); } @Override public void updatePrefs() { try { pid.setConstants( prefs.getDouble("ManipulatorP"), prefs.getDouble("ManipulatorI"), prefs.getDouble("ManipulatorD")); pid.setErrorEpsilon(prefs.getDouble("ManipulatorEps")); } catch (PreferenceDoesNotExistException e) { pid.setConstants(0.01, 0, 0); System.out.println("PID caught"); } pid.setErrorEpsilon(0.125); } /** * If the x button is presses, the manipulator will clamp or unclamp. If the right stick is * pressed the manip will go to zero. If the right stick is moved right, the manip goes right. If * the right stick goes left, the manip goes left. If in auto state and the a button is pressed, * the routine to score on scale will run. If in manual mode and the b button is pressed the manip * will rotate or unrotate. */ @Override public void controllerUpdate() { if (xbox.getX(xbox.m_secondary) && !xLastPressed) { if (isClamped) { unClamp(); } else { clamp(); } } xLastPressed = xbox.getX(xbox.m_secondary); if (xbox.getDPadPressed(xbox.m_secondary)) { rotateUp(); } if (xbox.getRightStickPress(xbox.m_secondary)) { // RoutineManager.getInstance().addAction(new MoveManipulator(0)); setPosition(0); } if (xbox.getRightBumper(xbox.m_secondary) && !rightBumperLastPressed) { rotate(!isRotated); } rightBumperLastPressed = xbox.getRightBumper(xbox.m_secondary); if (!locked && Forklift.getInstance().getCurrentHeight() > Constants.minSafeLiftHeight) { double stickValue = handleDeadband(xbox.getRightStickX(xbox.m_secondary), 0.15) / -1.5; stickValue = Math.pow(stickValue, 3); stickValue *= 2; if (stickValue != 0) { setPosition(getDesiredPosition() + stickValue); } } } @Override public void updateSmartDashboard() { SmartDashboard.putNumber( "Manipulator ticks", m_slider1.getSensorCollection().getQuadraturePosition()); SmartDashboard.putNumber("Manipulator inches", getPosition()); SmartDashboard.putNumber("Manipulator Desired Position", desiredPosition); SmartDashboard.putNumber("Manipulator Speed", m_slider1.getSelectedSensorVelocity(0)); SmartDashboard.putBoolean("Manip Has Cube", hasCube); } @Override public void writeToLog() {} private void configSpeedControl() { m_slider1.set(ControlMode.Velocity, 0); m_slider1.configNominalOutputReverse(0, 0); m_slider1.configNominalOutputForward(0, 0); m_slider1.configPeakOutputReverse(-1, 0); m_slider1.configPeakOutputForward(1, 0); m_slider1.selectProfileSlot(0, 0); try { m_slider1.config_kP(0, prefs.getDouble("ManipulatorVelocityP"), 0); m_slider1.config_kI(0, prefs.getDouble("ManipulatorVelocityI"), 0); m_slider1.config_kD(0, prefs.getDouble("ManipulatorVelocityD"), 0); m_slider1.config_kF(0, prefs.getDouble("ManipulatorVelocityF"), 0); } catch (PreferenceDoesNotExistException e) { m_slider1.config_kP(0, 0.01, 0); m_slider1.config_kI(0, 0, 0); m_slider1.config_kD(0, 0, 0); m_slider1.config_kF(0, 0, 0); } m_slider1.config_IntegralZone(0, 0, 0); m_slider1.configClosedloopRamp(0, 0); } public void setCeiling(double newCeiling) { powerCeiling = newCeiling; } public void setHasCube(boolean val) { hasCube = val; } public boolean hasCube() { return hasCube; } @Override public void reset() { isLatched = false; hasCube = false; } public double getDoneRange() { return pid.getDoneRangeVal(); } }
true
8857a32cb1eddd05dd93c05e3a9cab63cebb012e
Java
GlaucoSouza/Ultra_vision
/src/options/updateCustomer.java
UTF-8
284
1.5625
2
[]
no_license
package options; import java.util.ArrayList; /** * I did not manage to work with this class * but it should update a customer's information like name, email or their subscription * @author Glauco * */ public class updateCustomer { public updateCustomer() { } }
true
caae68bc93162950028cd58de1157e12e1bf2ecd
Java
rahul-me/e-ope
/src/com/gridscape/sep/org/zigbee/sep/FileLink.java
UTF-8
829
1.890625
2
[]
no_license
package com.gridscape.sep.org.zigbee.sep; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * This element MUST be set to the URI of the most recent File being loaded/activated by the LD. In the case of file status 0, this element MUST be omitted. * * <p>Java class for FileLink complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="FileLink"> * &lt;complexContent> * &lt;extension base="{http://zigbee.org/sep}Link"> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "FileLink") public class FileLink extends Link { }
true
7821a0efa73f56e12b410dece74c340671c34dc2
Java
murugaraja/Spring
/Spring Examples/SpringExample6/src/JSON.java
UTF-8
119
1.90625
2
[]
no_license
public class JSON implements Opt{ @Override public void read() { } @Override public void write() { } }
true
b1cd10ed4838cfeeec6f9b02754c5b9d531358d2
Java
vyphanduy1234/Android_Project
/app/src/main/java/com/example/lenovo/my_project/view/IBaseView.java
UTF-8
98
1.570313
2
[]
no_license
package com.example.lenovo.my_project.view; public interface IBaseView { void initView(); }
true
d5db6791411196f1b8bfb68409a1f4c2cfca9ffa
Java
LeogenWP/homeWork_1.5
/src/main/java/com/LeogenWP/basepatterns/behavioral/strategy/Speaking.java
UTF-8
196
2.296875
2
[]
no_license
package com.LeogenWP.basepatterns.behavioral.strategy; public class Speaking implements Activity { @Override public void doActivity() { System.out.println("speaking..."); } }
true
58b8ceae75c9233dbd05e3a6f3c9737b25de945c
Java
Shadow493/anathema
/Character_MeritsFlaws/src/net/sf/anathema/character/meritsflaws/presenter/MeritsFlawsViewProperties.java
UTF-8
3,453
2.03125
2
[]
no_license
package net.sf.anathema.character.meritsflaws.presenter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.Icon; import javax.swing.ListCellRenderer; import net.sf.anathema.character.meritsflaws.model.perk.PerkCategory; import net.sf.anathema.character.meritsflaws.model.perk.PerkType; import net.sf.anathema.framework.presenter.resources.BasicUi; import net.sf.anathema.framework.view.IdentificateSelectCellRenderer; import net.sf.anathema.lib.resources.IResources; import net.sf.anathema.lib.util.IIdentificate; import net.sf.anathema.lib.util.Identificate; public class MeritsFlawsViewProperties implements IMeritsFlawsViewProperties { private final IResources resources; private final IMeritsFlawsModel meritsFlawsModel; public MeritsFlawsViewProperties(IMeritsFlawsModel meritsFlawsModel, IResources resources) { this.meritsFlawsModel = meritsFlawsModel; this.resources = resources; } public String getSelectedString() { return resources.getString("Perks.Selected.Title"); //$NON-NLS-1$ } public String getDetailsString() { return resources.getString("Perks.Details.Title"); //$NON-NLS-1$ } public String getSelectionString() { return resources.getString("Perks.Available.Title"); //$NON-NLS-1$ } public Icon getAddIcon() { return new BasicUi(resources).getAddIcon(); } public Icon getRemoveIcon() { return new BasicUi(resources).getRemoveIcon(); } public String getTypeString() { return resources.getString("Perks.Available.Filter.Type"); //$NON-NLS-1$ } public String getCategoryString() { return resources.getString("Perks.Available.Filter.Category"); //$NON-NLS-1$ } public IIdentificate[] getCategoryFilters() { java.util.List<IIdentificate> categoryList = new ArrayList<IIdentificate>(); categoryList.add(null); Collections.addAll(categoryList, PerkCategory.values()); return categoryList.toArray(new IIdentificate[categoryList.size()]); } public IIdentificate[] getTypeFilters() { List<IIdentificate> categoryList = new ArrayList<IIdentificate>(); categoryList.add(null); Collections.addAll(categoryList, PerkType.values()); return categoryList.toArray(new IIdentificate[categoryList.size()]); } public ListCellRenderer getTypeFilterListRenderer() { return new IdentificateSelectCellRenderer("Perks.Available.Filter.Type.", resources) { //$NON-NLS-1$\ private static final long serialVersionUID = 4029188311502420644L; @Override protected String getNullValue() { return getCustomizedDisplayValue(new Identificate("All")); //$NON-NLS-1$ } }; } public ListCellRenderer getCategoryFilterListRenderer() { return new IdentificateSelectCellRenderer("Perks.Available.Filter.Category.", resources) { //$NON-NLS-1$\ private static final long serialVersionUID = -311282298063913853L; @Override protected String getNullValue() { return getCustomizedDisplayValue(new Identificate("All")); //$NON-NLS-1$ } }; } public ListCellRenderer getAvailableListRenderer() { return new MeritsFlawsAvailableCellRenderer(meritsFlawsModel, resources); } public ListCellRenderer getSelectionListRenderer() { return new MeritsFlawsSelectedCellRenderer(resources, meritsFlawsModel); } }
true
04dc5f8668e1df55f4b54c73d8f904afb07c6fcb
Java
Bartek321/Projekt-Java
/Threads/src/Pack/Notify.java
UTF-8
806
2.78125
3
[]
no_license
package Pack; public class Notify { private Integer stationId; private String type; private String date; private Double value; public Notify(Integer stationId, String type, String date, Double value) { this.stationId = stationId; this.type = type; this.date = date; this.value = value; } public void setStationId(Integer stationId) { this.stationId = stationId; } public void setType(String type) { this.type = type; } public void setDate(String date) { this.date = date; } public void setValue(Double value) { this.value = value; } public Integer getStationId() { return stationId; } public String getType() { return type; } public String getDate() { return date; } public Double getValue() { return value; } }
true
5d9388ba4c5e4a1ec8deb8371f5e2fd447637a57
Java
tpenakov/otaibe-commons-quarkus
/otaibe-commons-quarkus-web/src/main/java/org/otaibe/commons/quarkus/web/domain/AbstractMicroRs.java
UTF-8
452
2.0625
2
[ "MIT" ]
permissive
package org.otaibe.commons.quarkus.web.domain; import lombok.Data; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.List; @Data @NoArgsConstructor public class AbstractMicroRs<T> { List<T> result; Page page; ErrorRs error; Long totalResults; public void add(T entity) { if (getResult() == null) { setResult(new ArrayList<>()); } getResult().add(entity); } }
true
e3a1e46cb53e207dadd7606d4dcd9cb45ea456ce
Java
shakim/openstack-java-sdk
/quantum-client/src/main/java/org/openstack/quantum/api/networks/ListNetworks.java
UTF-8
465
2.03125
2
[ "Apache-2.0" ]
permissive
package org.openstack.quantum.api.networks; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import org.openstack.quantum.client.QuantumCommand; import org.openstack.quantum.model.Networks; public class ListNetworks implements QuantumCommand<Networks> { public ListNetworks() { } public Networks execute(WebTarget target) { return target.path("v2.0").path("networks").request(MediaType.APPLICATION_JSON).get(Networks.class); } }
true
5cfa94a5db06c37511d5825b4bc6157bc97c4b85
Java
Hurson/mysql
/ADS1.0/src/java/com/avit/ads/dtmb/bean/DAdPosition.java
UTF-8
3,666
2.140625
2
[]
no_license
package com.avit.ads.dtmb.bean; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; @Entity @Table(name = "d_advertposition") public class DAdPosition implements Serializable { private static final long serialVersionUID = 2284044631669410533L; private Integer id; /** * 广告位名称 */ private String positionName; /** *广告位code */ private String positionCode; /** * 广告位类型1、单向实时;2、单向非实时;3、字幕 */ private String positionType; /** * 高标清标示位 */ private String isHd; /** * 素材类型1、图片;2、视频;3、文字 */ private String resourceType; /** * 素材个数 */ private int resourceCount; /** * 素材规格ID */ private Integer specificationId; /** * 策略列表,多个用“|”分割 */ private String ployTypes; /** * 主策略类型(用来求笛卡尔积,时段和区域除外) */ private String mainPloy; /** * 描述 */ private String description; private String position; private String filePath=""; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="POSITION_NAME") public String getPositionName() { return positionName; } public void setPositionName(String positionName) { this.positionName = positionName; } @Column(name="POSITION_CODE") public String getPositionCode() { return positionCode; } public void setPositionCode(String positionCode) { this.positionCode = positionCode; } @Column(name="POSITION_TYPE") public String getPositionType() { return positionType; } public void setPositionType(String positionType) { this.positionType = positionType; } @Column(name="IS_HD") public String getIsHd() { return isHd; } public void setIsHd(String isHd) { this.isHd = isHd; } @Column(name="RESOURCE_TYPE") public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } @Column(name="RESOURCE_COUNT") public int getResourceCount() { return resourceCount; } public void setResourceCount(int resourceCount) { this.resourceCount = resourceCount; } @Column(name="SPECIFICATION_ID") public Integer getSpecificationId() { return specificationId; } public void setSpecificationId(Integer specificationId) { this.specificationId = specificationId; } @Column(name="PLOY_TYPES") public String getPloyTypes() { return ployTypes; } public void setPloyTypes(String ployTypes) { this.ployTypes = ployTypes; } @Column(name="MAIN_PLOY") public String getMainPloy() { return mainPloy; } public void setMainPloy(String mainPloy) { this.mainPloy = mainPloy; } @Column(name="DESCRIPTION") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Column(name="POSITION") public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } @Transient public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } }
true
93c6c67e1b1e1fb6de59cee5045a077d2b107f40
Java
mikeguan1999/Somniphobia
/core/src/edu/cornell/gdiac/somniphobia/game/controllers/PlatformController.java
UTF-8
8,764
2.28125
2
[]
no_license
package edu.cornell.gdiac.somniphobia.game.controllers; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Filter; import edu.cornell.gdiac.somniphobia.WorldController; import edu.cornell.gdiac.somniphobia.game.models.PlatformModel; import edu.cornell.gdiac.somniphobia.obstacle.*; import edu.cornell.gdiac.util.*; import java.util.Iterator; public class PlatformController { /** This values so light only interacts with light and dark only interacts with dark*/ private final short CATEGORY_LPLAT = 0x0001; //0000000000000001 private final short CATEGORY_DPLAT = 0x0002; //0000000000000010 private final short CATEGORY_SOMNI = 0x0004; //0000000000000100 private final short CATEGORY_PHOBIA = 0x0008; //0000000000001000 private final short CATEGORY_COMBINED = 0x0010; //0000000000010000 private final short CATEGORY_ALLPLAT = 0x0020; /** short values for masking bits*/ private final short MASK_LPLAT = CATEGORY_SOMNI | CATEGORY_COMBINED; private final short MASK_DPLAT = CATEGORY_PHOBIA | CATEGORY_COMBINED; private final short MASK_SOMNI = CATEGORY_LPLAT | CATEGORY_ALLPLAT; private final short MASK_PHOBIA = CATEGORY_DPLAT | CATEGORY_ALLPLAT; private final short MASK_COMBINED = CATEGORY_DPLAT | CATEGORY_LPLAT | CATEGORY_ALLPLAT; private final short MASK_ALLPLAT = CATEGORY_SOMNI | CATEGORY_PHOBIA | CATEGORY_COMBINED; public static final float rainingCooldown = 50; public static final float respawnCooldown = 300; /** Filters for objects*/ public Filter lightplatf; public Filter darkplatf; public Filter somnif; public Filter phobiaf; public Filter combinedf; public Filter allf; public Filter [] filters; WorldController worldController; /** shared objects */ protected PooledList<Obstacle> sharedObjects = new PooledList<Obstacle>(); /** shared objects */ protected PooledList<Obstacle> lightObjects = new PooledList<Obstacle>(); /** shared objects */ protected PooledList<Obstacle> darkObjects = new PooledList<Obstacle>(); /** moving objects */ protected PooledList<Obstacle> movingObjects = new PooledList<Obstacle>(); /** platforms that are raining out of the world **/ protected PooledList<Obstacle> currRainingPlatforms = new PooledList<>(); /** platforms that are respawning **/ protected PooledList<Obstacle> respawningPlatforms = new PooledList<>(); /** Vector2 cache */ private Vector2 vector; private Vector2 vector2; /** * Constructor for platform controller. Creates all the necessary filters. */ public PlatformController() { this.worldController = worldController; lightplatf = new Filter(); lightplatf.categoryBits = CATEGORY_LPLAT; lightplatf.maskBits = MASK_LPLAT; darkplatf = new Filter(); darkplatf.categoryBits = CATEGORY_DPLAT; darkplatf.maskBits = MASK_DPLAT; somnif = new Filter(); somnif.categoryBits = CATEGORY_SOMNI; somnif.maskBits = MASK_SOMNI; phobiaf = new Filter(); phobiaf.categoryBits = CATEGORY_PHOBIA; phobiaf.maskBits = MASK_PHOBIA; combinedf = new Filter(); combinedf.categoryBits = CATEGORY_COMBINED; combinedf.maskBits = MASK_COMBINED; allf = new Filter(); allf.categoryBits = CATEGORY_ALLPLAT; allf.maskBits = MASK_ALLPLAT; Filter [] fs = {lightplatf, darkplatf, allf, somnif, phobiaf, combinedf}; filters = fs; vector = new Vector2(); vector2 = new Vector2(); } /** * Sets the worldController * @param worldController the worldController */ public void setWorldController(WorldController worldController) { this.worldController = worldController; } /** * Takes in a list of obstacles and applys the corresponding filter to the data. * @param objects */ public void applyFilters(PooledList<Obstacle> objects){ for( Obstacle o : objects){ if(o instanceof PlatformModel){ o.setFilterData(filters[o.getTag() - 1]); } } } /** * Sets the light objects * @param lightObjects */ public void setLightObjects(PooledList<Obstacle> lightObjects) { this.lightObjects = lightObjects; } /** * Sets the dark objects * @param darkObjects */ public void setDarkObjects(PooledList<Obstacle> darkObjects) { this.darkObjects = darkObjects; } /** * Sets the shared objects * @param sharedObjects */ public void setSharedObjects(PooledList<Obstacle> sharedObjects) { this.sharedObjects = sharedObjects; } /** * Sets the currently raining platforms objects * @param currRainingPlatforms */ public void setCurrRainingPlatforms(PooledList<Obstacle> currRainingPlatforms) { this.currRainingPlatforms = currRainingPlatforms; } /** * Sets the moving objects * @param movingObjects */ public void setMovingObjects(PooledList<Obstacle> movingObjects) { this.movingObjects = movingObjects; } /** * Updates platform states */ public void update(float dt){ for (Obstacle obstacle : movingObjects) { PlatformModel platform = (PlatformModel) obstacle; Vector2 position = vector.set(platform.getLeftX(), platform.getBottomY());; PooledList<Vector2> paths = platform.getPaths(); Vector2 nextDestination = paths.getHead(); //if overshot (destination - position opposite sign as velocity), switch destination if (!obstacle.getLinearVelocity().isZero() && (Math.signum(nextDestination.x - position.x) != Math.signum(platform.getLinearVelocity().x) || Math.signum(nextDestination.y - position.y) != Math.signum(platform.getLinearVelocity().y))) { position.set(nextDestination); platform.setVY(0); platform.setVX(0); platform.setX(position.x + platform.getWidth()/2); platform.setY(position.y + platform.getHeight()/2); } // Switch destination if arrived if (position.equals(nextDestination)) { paths.add(paths.poll()); nextDestination = paths.getHead(); } Vector2 nextPath = vector2.set(nextDestination).sub(position).nor(); if (nextPath.isZero()) platform.setVelocity(0); platform.setLinearVelocity(nextPath.scl(platform.getVelocity())); } Iterator<Obstacle> currRainingPlatIt = currRainingPlatforms.iterator(); while (currRainingPlatIt.hasNext()) { PlatformModel platform = (PlatformModel) currRainingPlatIt.next(); if (platform.getRainingCooldown() <= 0) { platform.setActive(false); // platform.deactivatePhysics(worldController.getWorld()); lightObjects.remove(platform); darkObjects.remove(platform); sharedObjects.remove(platform); // platform.markRemoved(true); //Remove from curr raining and add to respawn list currRainingPlatforms.remove(platform); respawningPlatforms.add(platform); platform.setRespawnCooldown(respawnCooldown); } else { platform.setRainingCooldown(platform.getRainingCooldown() - 1); } } Iterator<Obstacle> respawningPlatIt = respawningPlatforms.iterator(); while (respawningPlatIt.hasNext()) { PlatformModel platform = (PlatformModel) respawningPlatIt.next(); if (platform.getRespawnCooldown() <= 0) { respawningPlatforms.remove(platform); switch (platform.getTag()) { case PlatformModel.light: lightObjects.add(platform); break; case PlatformModel.dark: darkObjects.add(platform); break; case PlatformModel.shared: sharedObjects.add(platform); break; default: break; } platform.setActive(true); platform.setCurrentlyRaining(false); platform.setRainingCooldown(rainingCooldown); } else { platform.setRespawnCooldown(platform.getRespawnCooldown() - 1); } } } }
true
ca6c54e16341fa6b45927bb7e9fb245e7b399230
Java
rafaelmedeirosjob/oilprice
/API/challenge/src/main/java/br/com/indra/challenge/repository/MunicipioRepository.java
UTF-8
270
1.859375
2
[]
no_license
package br.com.indra.challenge.repository; import org.springframework.data.jpa.repository.JpaRepository; import br.com.indra.challenge.model.Municipio; public interface MunicipioRepository extends JpaRepository<Municipio, Long>{ Municipio findByNome(String nome); }
true
ae474dd1c6bb851ed69cb6f5df6c312936151d9c
Java
hisun-zzb-team/hisun-zzb
/src/main/java/com/hisun/saas/zzb/a/dao/impl/A17DaoImpl.java
UTF-8
639
1.53125
2
[]
no_license
/* * Copyright (c) 2018. Hunan Hisun Union Information Technology Co, Ltd. All rights reserved. * http://www.hn-hisun.com * 注意:本内容知识产权属于湖南海数互联信息技术有限公司所有,除非取得商业授权,否则不得用于商业目的. */ package com.hisun.saas.zzb.a.dao.impl; import com.hisun.saas.sys.tenant.base.dao.imp.TenantBaseDaoImpl; import com.hisun.saas.zzb.a.dao.A17Dao; import com.hisun.saas.zzb.a.entity.A17; import org.springframework.stereotype.Repository; /** * @author Marco {[email protected]} */ @Repository public class A17DaoImpl extends TenantBaseDaoImpl<A17,String> implements A17Dao { }
true
8c8e21e5a4f226a8401582795f203abb7f279ddb
Java
m1cron/mireaPDF
/src/main/java/ru/micron/ui/UiConstants.java
UTF-8
1,121
2.140625
2
[ "MIT" ]
permissive
package ru.micron.ui; import java.awt.Color; import java.awt.Font; import lombok.AccessLevel; import lombok.NoArgsConstructor; @NoArgsConstructor(access = AccessLevel.PRIVATE) public class UiConstants { public static final int FRAME_WIDTH = 725; public static final int FRAME_HEIGHT = 530; public static final int FRAME_FONT = Font.PLAIN; public static final int FRAME_SIZE = 14; public static final Color FRAME_COLOR = Color.WHITE; public static final String TITLE = "MIREA PDF"; public static final String ICON_PNG = "/icon.png"; public static final String DIALOG = "Dialog"; public static final String CHECK_MAKE_DOCX = "Make DOCX?"; public static final String BTN_MAKE_PDF = "Make PDF"; public static final Font DEFAULT_FONT = new Font(DIALOG, FRAME_FONT, FRAME_SIZE); public static final int ROWS_SIZE = 10; public static final int COLUMNS_SIZE = 20; public static final int TEACHER_FIELD_SIZE = 20; public static final int STUDENT_FIELD_SIZE = 20; public static final int GROUP_FIELD_SIZE = 13; public static final int PRAC_NUM_FIELD_SIZE = 6; }
true
1c3ab52f8529c0b400f3d631d3e0527487af7f0a
Java
IRH01/boast-west-journey
/src/main/java/com/hhly/smartdata/util/DateUtil.java
UTF-8
5,096
3.5
4
[]
no_license
package com.hhly.smartdata.util; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtil{ /** * 解析日期成对应的字符串 yyyy-MM-dd HH:mm:ss * * @param date 日期 * @return 字符串 */ public static String date2String(Date date){ if(date == null){ return null; } String pattern = "yyyy-MM-dd HH:mm:ss"; return date2String(date, pattern); } /** * 解析日期成对应的字符串 * * @param date 日期 * @param pattern 日期正则格式 * @return 字符串 */ public static String date2String(Date date, String pattern){ if(date == null){ return null; } SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.format(date); } /** * 解析字符串成对应的日期格式 yyyy-MM-dd HH:mm:ss * * @param dateStr 日期字符串 * @return 日期 */ public static Date string2Date(String dateStr){ String pattern = "yyyy-MM-dd HH:mm:ss"; return string2Date(dateStr, pattern); } /** * 解析字符串成对应的日期格式 * * @param dateStr * @param pattern * @return */ public static Date string2Date(String dateStr, String pattern){ try{ SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.parse(dateStr); }catch(Exception e){ e.printStackTrace(); return null; } } /** * 日期时间增加相应的时间,调用案例如: * <p><code>add(Calendar.DAY_OF_MONTH, -5)</code>. * * @param field the calendar field .See {@link java.util.Calendar}. * @param amount the amount of date or time to be added to the field. */ public static Date add(Date date, int field, int amount){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(field, amount); return calendar.getTime(); } /** * 根据日期设置时分秒,获取新的时间 * * @param date * @param hour * @param minute * @param second * @return */ public static Date getTime(Date date, int hour, int minute, int second){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, second); return calendar.getTime(); } /** * 获取前一天的日期字符串 * * @param date * @return String ,"yyyy-MM-dd" */ public static String getYesterdayStr(Date date){ if(date == null){ return ""; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_YEAR, -1);//日期加-1天 return sdf.format(calendar.getTime()); } /** * 获取前一月的日期字符串 * * @param date * @return String ,"yyyy-MM" */ public static String getLastMonthStr(Date date){ if(date == null){ return ""; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, -1);//日期加-1月 return sdf.format(calendar.getTime()); } public static String getLastMonthFirstDayStr(Date date){ if(date == null){ return ""; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, -1);//日期加-1月 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); return sdf.format(calendar.getTime()); } public static String getLastMonthEndDayStr(Date date){ if(date == null){ return ""; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, -1);//日期加-1月 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); return sdf.format(calendar.getTime()); } /** * 获取前30分钟的日期 * * @param date * @return String ,"yyyy-MM-dd HH:mm:ss" */ public static String getFirstThirtyMinStr(Date date){ if(date == null){ return ""; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar beforeTime = Calendar.getInstance(); beforeTime.add(Calendar.MINUTE, -30);// 时间差值 Date beforeD = beforeTime.getTime(); return sdf.format(beforeD); } }
true
758c4fe794659491a8b0288fa9b1521a4fc911df
Java
fengdongfei/greemDao-database
/app/src/main/java/net/cps/myapplication/backup/Utils.java
UTF-8
6,251
2.078125
2
[]
no_license
package net.cps.myapplication.backup; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.support.v4.content.FileProvider; import android.support.v7.app.AlertDialog; import android.util.Log; import com.snatik.storage.Storage; import net.cps.myapplication.BApp; import net.cps.myapplication.R; import net.cps.myapplication.model.BackupBean; import org.ocpsoft.prettytime.PrettyTime; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Utils { public static final String BACKUP_DIR = "backup_money_mitu"; public static final String SUFFIX = ".db"; public static final String AUTO_BACKUP_PREFIX = "Money_keep_BackupAuto"; public static final String USER_BACKUP_PREFIX = "Money_keep_BackupUser"; public static final String BACKUP_SUFFIX = BApp.getInstance().getString(R.string.text_before_reverting); public static final String fileName = AUTO_BACKUP_PREFIX + SUFFIX; public static void startBackUp(Activity activity, final String filename){ new AlertDialog.Builder(activity) .setTitle(R.string.text_backup) .setMessage(R.string.text_backup_save) .setNegativeButton(R.string.text_button_cancel, null) .setPositiveButton(R.string.text_affirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { backupDB(filename); } }) .create() .show(); } private static boolean backupDB(String fileName) { Storage storage = new Storage(BApp.getInstance()); boolean isWritable = Storage.isExternalWritable(); if (!isWritable) { return false; } String path = storage.getExternalStorageDirectory() + File.separator + BACKUP_DIR; if (!storage.isDirectoryExists(path)) { storage.createDirectory(path); } String filePath = path + File.separator + fileName; if (!storage.isFileExist(filePath)) { // 创建空文件,在模拟器上测试,如果没有这个文件,复制的时候会报 FileNotFound storage.createFile(filePath, ""); } Log.d("filePath", "backupDB: " + filePath); return storage.copy(BApp.getInstance().getDatabasePath(BApp.getDBName()).getPath(), path + File.separator + fileName); } public static void startRestoreDb(final Activity activity, List<BackupBean> backupBeans){ BackupFliesDialog dialog = new BackupFliesDialog(activity, backupBeans); dialog.setOnItemClickListener(new BackupFliesDialog.OnItemClickListener() { @Override public void onClick(File file) { boolean issuccess= restoreDB(file.getPath()); if (issuccess){ Utils.restart(activity); } } }); dialog.show(); } public static boolean restoreDB(String restoreFile) { Storage storage = new Storage(BApp.getInstance()); if (storage.isFileExist(restoreFile)) { // 恢复之前,备份一下最新数据 String fileName = "MoneyKeeperBackup" + DateUtils.getCurrentDateString() + BACKUP_SUFFIX + SUFFIX; boolean isBackupSuccess = backupDB(fileName); boolean isRestoreSuccess = storage.copy(restoreFile, BApp.getInstance().getDatabasePath(BApp.getDBName()).getPath()); return isBackupSuccess && isRestoreSuccess; } return false; } //显示文件浏览器 public static void showFileChooser(Activity activity) { Storage storage = new Storage(BApp.getInstance()); boolean isWritable = Storage.isExternalWritable(); if (!isWritable) { return ; } String path = storage.getExternalStorageDirectory() + File.separator + BACKUP_DIR; if (!storage.isDirectoryExists(path)) { storage.createDirectory(path); } String filePath = path + File.separator + fileName; File file = new File(filePath); //获取父目录 File parentFlie = new File(file.getParent()); Intent intent = new Intent(Intent.ACTION_VIEW); //判断是否是AndroidN以及更高的版本 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri contentUri = FileProvider.getUriForFile(activity, activity.getPackageName()+ ".fileprovider", parentFlie); intent.setDataAndType(contentUri, "application/vnd.android.package-archive"); } else { intent.setDataAndType(Uri.fromFile(parentFlie), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } activity.startActivity(intent); } public static List<BackupBean> getBackupFiles() { Storage storage = new Storage(BApp.getInstance()); String dir = storage.getExternalStorageDirectory() + File.separator + BACKUP_DIR; List<BackupBean> backupBeans = new ArrayList<>(); BackupBean bean; List<File> files = storage.getFiles(dir, "[\\S]*\\.db"); if (files == null) { return backupBeans; } File fileTemp; PrettyTime prettyTime = new PrettyTime(); for (int i = 0; i < files.size(); i++) { fileTemp = files.get(i); bean = new BackupBean(); bean.file = fileTemp; bean.name = fileTemp.getName(); bean.size = storage.getReadableSize(fileTemp); bean.time = prettyTime.format(new Date(fileTemp.lastModified())); backupBeans.add(bean); } return backupBeans; } public static void restart(Activity activity){ final Intent intent = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); activity.startActivity(intent); } }
true
087cd644b34f25b25a160ecc2c261e069e5ae5be
Java
plasklab/yoshise-icpc
/ALDS1/8_C/src/Main.java
UTF-8
2,260
3.09375
3
[]
no_license
import java.util.Scanner; public class Main { static Node r; public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int x; String com; int cnt=0; for(int i=0; i<n; i++){ com = sc.next(); if(com.equals("insert")){ x = sc.nextInt(); insert(new Node(x, null, null, null)); } else if (com.equals("find")){ x = sc.nextInt(); if(find(r, x) != null) System.out.println("yes"); else System.out.println("no"); } else if (com.equals("delete")){ x = sc.nextInt(); treeDelete(find(r, x)); } else if (com.equals("print")){ inorder(r); System.out.println(); preorder(r); System.out.println(); } } } static Node treeMinimum(Node x){ while( x.l != null) x = x.l; return x; } static Node treeSuccessor(Node x){ if (x.r != null) return treeMinimum(x.r); Node y = x.p; while(y != null && x == y.r) { x = y; y = y.p; } return y; } static void treeDelete(Node z) { Node y; Node x; if(z.l == null || z.r == null) y=z; else y = treeSuccessor(z); if(y.l != null){ x = y.l; } else { x = y.r; } if (x != null) { x.p = y.p; } if (y.p == null){ r = x; } else { if (y == y.p.l){ y.p.l = x; } else { y.p.r = x; } } if (y != z) { z.key = y.key; } } static Node find(Node u, int k){ while (u != null && k != u.key){ if(k < u.key) u = u.l; else u = u.r; } return u; } static void insert(Node z){ Node y = null; Node x = r; while (x != null){ y = x; if (z.key < x.key){ x = x.l; } else { x = x.r; } } z.p = y; if (y == null){ r = z; } else { if(z.key < y.key){ y.l = z; } else { y.r = z; } } } static void inorder(Node u){ if (u == null) return; inorder(u.l); System.out.print(" " + u.key); inorder(u.r); } static void preorder(Node u) { if (u == null) return; System.out.print(" " + u.key); preorder(u.l); preorder(u.r); } } class Node { int key; Node p = null; Node l = null; Node r = null; public Node(int key, Node p,Node l, Node r) { this.key = key; this.l = l; this.r = r; this.p = p; } }
true
9afc3830ab5025b93de6cda2ee1e7749797312b3
Java
hw233/app2-java
/center/src/com/chuangyou/xianni/state/condition/magicwp/MagicWpStateCondition.java
UTF-8
3,450
2.296875
2
[]
no_license
package com.chuangyou.xianni.state.condition.magicwp; import java.util.Map; import com.chuangyou.xianni.entity.magicwp.MagicwpInfo; import com.chuangyou.xianni.entity.state.StateConditionConfig; import com.chuangyou.xianni.entity.state.StateConditionInfo; import com.chuangyou.xianni.event.EventNameType; import com.chuangyou.xianni.event.ObjectEvent; import com.chuangyou.xianni.event.ObjectListener; import com.chuangyou.xianni.player.GamePlayer; import com.chuangyou.xianni.state.condition.BaseStateCondition; /** * 法宝 * @author laofan * */ public class MagicWpStateCondition extends BaseStateCondition { public MagicWpStateCondition(StateConditionInfo info, StateConditionConfig config, GamePlayer player) { super(info, config, player); // TODO Auto-generated constructor stub } @Override public void addTrigger(GamePlayer player) { // TODO Auto-generated method stub this.listener = new ObjectListener() { @Override public void onEvent(ObjectEvent event) { // TODO Auto-generated method stub MagicwpInfo tempInfo = (MagicwpInfo) event.getObject(); int targetId = config.getTargetId(); if(targetId == 3){ if(tempInfo.getMagicwpId() == config.getTargetNum()){ info.setProcess(player.getMagicwpInventory().getMagicwpInfo(config.getTargetNum()).getLevel()); } }else if(targetId == 4){ info.setProcess(getCountLv(player.getMagicwpInventory().getMagicwpInfoMap(),config.getTargetId1())); }else if(targetId == 5){ if(tempInfo.getMagicwpId() == config.getTargetNum()){ info.setProcess(player.getMagicwpInventory().getMagicwpInfo(config.getTargetNum()).getGrade()); } }else if(targetId == 6){ info.setProcess(getCountGrade(player.getMagicwpInventory().getMagicwpInfoMap(),config.getTargetId1())); } } }; player.addListener(listener, EventNameType.MAGICWP); } @Override public void removeTrigger(GamePlayer player) { // TODO Auto-generated method stub player.removeListener(listener, EventNameType.MAGICWP); } @Override public void initProcess() { // TODO Auto-generated method stub int targetId = config.getTargetId(); if(targetId == 3){ if(player.getMagicwpInventory().getMagicwpInfo(config.getTargetNum())!=null){ info.setProcess(player.getMagicwpInventory().getMagicwpInfo(config.getTargetNum()).getLevel()); } }else if(targetId == 4){ info.setProcess(getCountLv(player.getMagicwpInventory().getMagicwpInfoMap(),config.getTargetId1())); }else if(targetId == 5){ if(player.getMagicwpInventory().getMagicwpInfo(config.getTargetNum())!=null){ info.setProcess(player.getMagicwpInventory().getMagicwpInfo(config.getTargetNum()).getGrade()); } }else if(targetId == 6){ info.setProcess(getCountGrade(player.getMagicwpInventory().getMagicwpInfoMap(),config.getTargetId1())); } } protected int getCountLv(Map<Integer, MagicwpInfo> map,int num){ int count=0; for (MagicwpInfo mountEquip : map.values()) { if(mountEquip.getLevel()>=num){ count ++; } } return count; } protected int getCountGrade(Map<Integer, MagicwpInfo> map,int num){ int count=0; for (MagicwpInfo mountEquip : map.values()) { if(mountEquip.getGrade()>=num){ count ++; } } return count; } @Override public boolean commitProcess() { // TODO Auto-generated method stub return false; } @Override public void initListener() { // TODO Auto-generated method stub } }
true
e02a665c248c520527274a224e7ac8649c61d51c
Java
jarekpc/TestGit1
/src/main/java/com/jarek/Main.java
UTF-8
960
3.5
4
[]
no_license
package com.jarek; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { LocalDateTime localDateTime = LocalDateTime.now(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.printf("Godzina i data %s \n", dateTimeFormatter.format(localDateTime)); long n = 45012; System.out.format("%d%n",n); System.out.println("Printing even numbers: " + n); Person jarek = new Person("Jarek", "Zyzak", 38); Person monika = new Person("Monika", "Zyzak", 34); Person wojtek = new Person("Wojciech", "Borkała", 34); List<Person> personList = Arrays.asList(jarek, monika,wojtek); personList.stream().filter(u -> u.getAge() > 33).map(map -> map.getFirstName()).forEach(System.out::println); } }
true
35969b5a3c036f3d399ccda9e855ae54ab63d722
Java
PRIDE-Toolsuite/pride-inspector
/src/main/java/uk/ac/ebi/pride/toolsuite/gui/utils/SortOrderUtils.java
UTF-8
834
2.921875
3
[ "Apache-2.0" ]
permissive
package uk.ac.ebi.pride.toolsuite.gui.utils; import javax.swing.*; /** * @author ypriverol * @author rwang */ public class SortOrderUtils { /** * Convenience to check if the order is sorted. * @return false if unsorted, true for ascending/descending. */ public static boolean isSorted(SortOrder order) { return order != SortOrder.UNSORTED; } public static boolean isSorted(SortOrder order, boolean ascending) { return isSorted(order) && (ascending == isAscending(order)); } /** * Convenience to check for ascending sort order. * PENDING: is this helpful at all? * * @return true if ascendingly sorted, false for unsorted/descending. */ public static boolean isAscending(SortOrder order) { return order == SortOrder.ASCENDING; } }
true
19f6b354dbb7e9d3509b6e5154a6f71be23be3dc
Java
javarias/acsBaciCodeGen
/vvaras.acsBaciCodeGen.model/src/baciCodeGen/BACIProperties/RWlong.java
UTF-8
5,264
2.375
2
[]
no_license
/** */ package baciCodeGen.BACIProperties; import baciCodeGen.PropertyDefinition; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>RWlong</b></em>'. * <!-- end-user-doc --> * * <!-- begin-model-doc --> * Read Write Long Property * <!-- end-model-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link baciCodeGen.BACIProperties.RWlong#getMaxValue <em>Max Value</em>}</li> * <li>{@link baciCodeGen.BACIProperties.RWlong#getMinValue <em>Min Value</em>}</li> * </ul> * * @see baciCodeGen.BACIProperties.BACIPropertiesPackage#getRWlong() * @model extendedMetaData="name='RWlong' kind='empty'" * @generated */ public interface RWlong extends Plong1, PropertyDefinition { /** * Returns the value of the '<em><b>Max Value</b></em>' attribute. * The default value is <code>"2147483647"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * Same type and units as parameter Property * This characteristic represents the maximum value that can be used to SET a writable property. * It should not be confused with the graph_max characteristic. The max_value represents the maximum value that can be SET, but the actual value reached by the property can in many case be higher (and defined by graph_max). * For example while a device moves to the maximum allowerd set position, there can be an overshoot. Typically devices of this kind have a soft and an hard upper limit. * * <!-- end-model-doc --> * @return the value of the '<em>Max Value</em>' attribute. * @see #isSetMaxValue() * @see #unsetMaxValue() * @see #setMaxValue(int) * @see baciCodeGen.BACIProperties.BACIPropertiesPackage#getRWlong_MaxValue() * @model default="2147483647" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Int" * extendedMetaData="kind='attribute' name='max_value'" * @generated */ int getMaxValue(); /** * Sets the value of the '{@link baciCodeGen.BACIProperties.RWlong#getMaxValue <em>Max Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Max Value</em>' attribute. * @see #isSetMaxValue() * @see #unsetMaxValue() * @see #getMaxValue() * @generated */ void setMaxValue(int value); /** * Unsets the value of the '{@link baciCodeGen.BACIProperties.RWlong#getMaxValue <em>Max Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetMaxValue() * @see #getMaxValue() * @see #setMaxValue(int) * @generated */ void unsetMaxValue(); /** * Returns whether the value of the '{@link baciCodeGen.BACIProperties.RWlong#getMaxValue <em>Max Value</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Max Value</em>' attribute is set. * @see #unsetMaxValue() * @see #getMaxValue() * @see #setMaxValue(int) * @generated */ boolean isSetMaxValue(); /** * Returns the value of the '<em><b>Min Value</b></em>' attribute. * The default value is <code>"-2147483648"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * Same type and units as parameter Property * This characteristic represents the minimum value that can be used to SET a writable property. * It should not be confused with the graph_min characteristic. The min_value represents the minimum value that can be SET, but the actual value reached by the property can in many case be lower (and defined by graph_min). * For example while a device moves to the minimum allowerd set position, there can be an overshoot. Typically devices of this kind have a soft and an hard lower limit. * * <!-- end-model-doc --> * @return the value of the '<em>Min Value</em>' attribute. * @see #isSetMinValue() * @see #unsetMinValue() * @see #setMinValue(int) * @see baciCodeGen.BACIProperties.BACIPropertiesPackage#getRWlong_MinValue() * @model default="-2147483648" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Int" * extendedMetaData="kind='attribute' name='min_value'" * @generated */ int getMinValue(); /** * Sets the value of the '{@link baciCodeGen.BACIProperties.RWlong#getMinValue <em>Min Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Min Value</em>' attribute. * @see #isSetMinValue() * @see #unsetMinValue() * @see #getMinValue() * @generated */ void setMinValue(int value); /** * Unsets the value of the '{@link baciCodeGen.BACIProperties.RWlong#getMinValue <em>Min Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetMinValue() * @see #getMinValue() * @see #setMinValue(int) * @generated */ void unsetMinValue(); /** * Returns whether the value of the '{@link baciCodeGen.BACIProperties.RWlong#getMinValue <em>Min Value</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Min Value</em>' attribute is set. * @see #unsetMinValue() * @see #getMinValue() * @see #setMinValue(int) * @generated */ boolean isSetMinValue(); } // RWlong
true
b801fa95a229374fce6b91a97f875b74e7797aa6
Java
leoJerez/elecciones-consejos-comunales
/branches/integracion_eclipse/src/org/eleccion_comunal/model/dao/EstadoDAO.java
UTF-8
386
2.046875
2
[]
no_license
package org.eleccion_comunal.model.dao; import org.eleccion_comunal.model.dto.Estado; public class EstadoDAO extends DAOGenerico { private static EstadoDAO instancia; public static EstadoDAO getInstancia() { if (instancia == null) { instancia = new EstadoDAO(); } return instancia; } private EstadoDAO() { super(Estado.class); } }
true
c7b9829bbcf4aab66a7a3cc7604fad6a6a6a06f7
Java
edertrevisoli/bluebird
/bluebird/src/main/java/com/bluebird/config/ApplicationJSF.java
UTF-8
1,783
1.960938
2
[]
no_license
package com.bluebird.config; import java.util.HashMap; import javax.faces.webapp.FacesServlet; import org.springframework.beans.factory.config.CustomScopeConfigurer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages="com.bluebird") @EntityScan(basePackages = "com.bluebird") public class ApplicationJSF extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(ApplicationJSF.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(ApplicationJSF.class); } @SuppressWarnings("serial") @Bean public org.springframework.beans.factory.config.CustomScopeConfigurer customScopeConfigurer(){ CustomScopeConfigurer csc = new CustomScopeConfigurer(); csc.setScopes(new HashMap<String, Object>() {{ put("view", new com.bluebird.config.ViewScope()); }}); return csc; } @Bean public ServletRegistrationBean servletRegistrationBean() { FacesServlet servlet = new FacesServlet(); ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "*.xhtml", "*.jsf"); return servletRegistrationBean; } }
true
8c420697eb0948958babe469ad08e72b4b4d6d75
Java
Akshansh986/Suzik
/suzik/src/main/java/com/blackMonster/suzik/sync/Syncer.java
UTF-8
6,288
2.09375
2
[]
no_license
package com.blackMonster.suzik.sync; import static com.blackMonster.suzik.util.LogUtils.*; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.SystemClock; import android.support.v4.content.LocalBroadcastManager; import com.blackMonster.suzik.AppConfig; import com.blackMonster.suzik.MainPrefs; import com.blackMonster.suzik.musicstore.userActivity.UserActivityQueueSyncer; import com.blackMonster.suzik.sync.contacts.ContactsSyncer; import com.blackMonster.suzik.sync.music.AddedSongsResponseHandler; import com.blackMonster.suzik.sync.music.SongsSyncer; import com.blackMonster.suzik.util.NetworkUtils; import com.crashlytics.android.Crashlytics; /** * Steps to use syncer * * 1) extend syncer. 2) add unimplemented method. 3) register as service in * manifest. 4) register in startOnNetAvailable function in at the bottom of * this class. 5) return null in getBroadcastString() if you don't want * broadcast. * * Retry mechanism work with backoff algoritm. * * @author akshanshsingh * */ public abstract class Syncer extends IntentService { private static final String TAG = "SyncManager"; private static final long BATCHING_REQUEST_WAIT_TIME_MS = 3000; public static final int STATUS_OK = 1; public static final int STATUS_ERROR = 2; public static final int STATUS_DEVICE_OFFLINE = 3; public static final String SHOULD_RETRY = "shudRtry"; private boolean shouldRetry = true; private int[] retryTimes={1,5,20,120,360,720,1440,1440}; //In minutes public Syncer() { super(TAG); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override protected void onHandleIntent(Intent intent) { LOGD(TAG, "onHandleIntent " + getClass().getSimpleName()); if (intent != null) shouldRetry = intent.getBooleanExtra(SHOULD_RETRY,true); LOGD(TAG,"retry : " + shouldRetry); syncNow(); } private void syncNow() { if (!NetworkUtils.isInternetAvailable(this)) { LOGD(TAG, "Net not available"); if (shouldRetry) MainPrefs.setCallOnNetAvailable( getOnNetAvailablePrefsName(getClass()), true, this); broadcastResult(STATUS_DEVICE_OFFLINE); return; } try { LOGD(TAG, "calling : " + getClass().getSimpleName()); if (onPerformSync() == false) { onFailure(); } else { onSucess(); } } catch (Exception e1) { e1.printStackTrace(); Crashlytics.logException(e1); onFailure(); } } private void onSucess() { broadcastResult(STATUS_OK); if (shouldRetry) MainPrefs.setSyncFailureCount(getSyncFailureCountPrefsName(getClass()), 0, this); } private void onFailure() { LOGD(TAG, "failedSync " + getClass().getSimpleName()); broadcastResult(STATUS_ERROR); if (!shouldRetry) return; incrementFailureCount(); Long time = getNextRetryTimeInMs(); if (time != null) { callFuture(time); } else { if (MainPrefs.getSyncFailureCount( getSyncFailureCountPrefsName(getClass()), this) > retryTimes.length) { LOGD(TAG, "Retry maximum limit reached"); } MainPrefs.setSyncFailureCount( getSyncFailureCountPrefsName(getClass()), 0, this); LOGE(TAG, "Error getting retry time " + getClass().getSimpleName()); } } private void incrementFailureCount() { int failure = MainPrefs.getSyncFailureCount( getSyncFailureCountPrefsName(getClass()), this) + 1; MainPrefs.setSyncFailureCount(getSyncFailureCountPrefsName(getClass()), failure, this); } private Long getNextRetryTimeInMs() { int fail = MainPrefs.getSyncFailureCount( getSyncFailureCountPrefsName(getClass()), this) - 1; if (fail < 0 || fail >= retryTimes.length) return null; return retryTimes[fail] * AppConfig.MINUTE_IN_MILLISEC; } private void callFuture(long time) { callFuture(getClass(), time, this); } public static void callFuture(Class cls, long timeMS, Context context) { LOGD(TAG, "calling after " + timeMS + " ms " + cls.getSimpleName()); Intent intent = new Intent(context, cls); PendingIntent operation = PendingIntent.getService(context, -1, intent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager am = ((AlarmManager) context .getSystemService(Context.ALARM_SERVICE)); am.cancel(operation); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + timeMS, operation); } /** * Start syncing after a fixed time, and resets timer if new request comes * in that time period. * * @param cls * @param context */ public static void batchRequest(Class cls, Context context) { callFuture(cls, BATCHING_REQUEST_WAIT_TIME_MS, context); } public abstract boolean onPerformSync() throws Exception; public abstract String getBroadcastString(); // // public String getCurrentClassName() { // return getClass().getSimpleName(); // } public static void startOnNetAvaiable(Context context) { LOGD(TAG, "startOnNetAvaiable"); registerOnNetAvailable(SongsSyncer.class, context); registerOnNetAvailable(AddedSongsResponseHandler.class, context); registerOnNetAvailable(ContactsSyncer.class, context); registerOnNetAvailable(UserActivityQueueSyncer.class, context); } private static void registerOnNetAvailable(Class javaClass, Context context) { String caller = getOnNetAvailablePrefsName(javaClass); if (MainPrefs.shouldCallOnNetAvailable(caller, context)) { MainPrefs.setCallOnNetAvailable(caller, false, context); context.startService(new Intent(context, javaClass)); } } private static String getOnNetAvailablePrefsName(Class javaClass) { return "OnNA" + javaClass.getSimpleName(); } private static String getSyncFailureCountPrefsName(Class javaClass) { return "FailCount" + javaClass.getSimpleName(); } private void broadcastResult(int result) { if (getBroadcastString() == null) return; Intent intent = new Intent(getBroadcastString()).putExtra( getBroadcastString(), result); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } }
true
e80ccc326d1e05fe0af8c08057a6fe4ecfaa0990
Java
nakampe/Jenkins
/src/test/java/co/za/nakampe/wwwdot/SetswanaGreetingTest.java
UTF-8
283
2.09375
2
[]
no_license
package co.za.nakampe.wwwdot; import org.junit.Test; import static org.junit.Assert.assertEquals; public class SetswanaGreetingTest{ @Test public void shouldReturnMessage(){ Greeting greeting = new SetswanaGreeting("Dumela"); assertEquals("Dumela",greeting.getMessage()); } }
true
a7781cda070ecf19ef6966e8064ba4cc0be51e09
Java
GBHBY/JUC
/src/com/gyb/test/JoinTest.java
UTF-8
699
2.859375
3
[]
no_license
package com.gyb.test; /** * Description: * * @author GB * @date 2022/8/12 9:18 */ public class JoinTest { public static void main(String[] args) throws InterruptedException { Runnable x = new Runnable() { @Override public void run() { try { Thread.sleep(3000); System.out.println(Thread.currentThread().getName() + "========="); } catch (InterruptedException e) { e.printStackTrace(); } } }; Thread thread = new Thread(x); thread.start(); thread.join(); System.out.println("890890"); } }
true
b38754b5730f14bc805b15ee09766d0ea9f424c4
Java
bokyoung89/JavaFramework
/Java/src/day0508/ex02/FileClass/ex02CreateNewFolder.java
UTF-8
1,294
3.6875
4
[]
no_license
package day0508.ex02.FileClass; import java.io.File; public class ex02CreateNewFolder { public static void main(String[] args) { String filePath = "C:/MyWork/MyFolder"; File file = new File(filePath); boolean isExist = file.exists(); // 디렉토리 존재 여부 System.out.println("exist()=" + isExist); //======= 디렉토리 생성 ========= //C:/MyWork 디렉토리가 있어야 MyFolder가 생성된다. if(!isExist) { System.out.println("======= mkdir() ========="); file.mkdir(); } //======= File 정보 ========= System.out.println("======= File 정보 ========="); String fileAbsolutePath = file.getAbsolutePath(); System.out.println("getAbsolutePath()" + fileAbsolutePath); isExist = file.exists(); System.out.println("exist()=" + isExist); String name = file.getName(); System.out.println("getName()=" + name); boolean isDirectory = file.isDirectory(); System.out.println("isDirectory()=" + isDirectory); //======= 디렉토리 삭제 ========= System.out.println("======== delete() =========="); //빈 폴더만 삭제 가능 boolean isDelete = file.delete(); System.out.println("delete()=" + isDelete); isExist = file.exists(); System.out.println("exist()=" + isExist); } }
true
400f30afd29008a1171146f2234f40d993791027
Java
SudhansuSelenium/Java-Program-for-practice
/src/JavaProgram/ReverseEachWord.java
UTF-8
411
3.5
4
[]
no_license
package JavaProgram; import java.util.Arrays; public class ReverseEachWord { public static void main(String[] args) { // Take a string //Split the string into array //Using for loop and taking split length and reduce the size //print the reverse String str = "THIS IS DEMO"; String[] split = str.split(" "); for(int i= split.length-1;i>=0;i--) { System.out.print(split[i] +" "); } } }
true
cd9361b8f27d44a36995b17976d11d74180b4d87
Java
caol-mc/TradingPlatform
/TradingPlatform/src/main/java/com/fdmgroup/tradingplatform/tests/Register.java
UTF-8
1,826
2.0625
2
[]
no_license
package com.fdmgroup.tradingplatform.tests; import static org.junit.Assert.*; import java.io.IOException; import java.util.Random; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import com.fdmgroup.driverutilities.DriverUtilities; import com.fdmgroup.selenium.datafile.DataFile; import pageObjects.HomePage; import pageObjects.RegisterPage; public class Register { private WebDriver driver; private Random r = new Random(); int x = r.nextInt(10000); @Before public void preConditions(){ DriverUtilities myDriverUtilities = new DriverUtilities(); driver = myDriverUtilities.getDriver(); driver.get("http://unxbtn001/TradingPlatform_CLEAN/"); } @After public void tearDown(){ driver.quit(); } @Test public void registerSuccess() throws IOException{ HomePage.registerLink(driver).click(); assertEquals(DataFile.registerHeading, driver.findElement(By.tagName("h3")).getText()); RegisterPage.title(driver).sendKeys("Mr"); RegisterPage.firstnameField(driver).sendKeys("Caol"); RegisterPage.surnameField(driver).sendKeys("McNamara"); RegisterPage.emailField(driver).sendKeys("caol"+ x +"@test.com"); RegisterPage.usernameField(driver).sendKeys("caol"+x); RegisterPage.passwordField(driver).sendKeys("Password1"); RegisterPage.confirmPasswordField(driver).sendKeys("Password1"); RegisterPage.securityQuestion(driver).sendKeys("Who is your favourite left handed person"); RegisterPage.securityAnswer(driver).sendKeys("Caol"); RegisterPage.confirmsecurityAnswer(driver).sendKeys("Caol"); RegisterPage.submitbutton(driver).click(); assertEquals("caol"+x, RegisterPage.confirmAccount(driver).getText().substring(17)); } }
true
8d6dfd37f8759a6eb8255331da4009e18c4d4d55
Java
GPC-debug/lab-1
/src/main/java/Test/TEst.java
UTF-8
1,219
2.671875
3
[]
no_license
package Test; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.nio.charset.StandardCharsets; /** * @author [email protected] * @date 2019/11/11 * @Description todo * important_dependency todo */ public class TEst { private static final String PROPERTIES_FILE = "./123"; private static final String ENCODING_WRITE = "GBK"; private static final String ENCODING_READ = "UTF-8"; public static void main(String[] args) throws Exception { //saveFile(); read(); } static void saveFile() throws Exception { OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(PROPERTIES_FILE), ENCODING_WRITE); writer.write("我f是f张df言sdaf琦"); writer.flush(); writer.close(); } static void read() throws Exception { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(PROPERTIES_FILE), ENCODING_READ)); String s = bufferedReader.readLine(); System.out.println(s); } }
true
6679c594ac6ce084f687365ee39f7b169608c035
Java
ZjanPreijde/Java-Programming-Masterclass
/JavaPrograms/05. MyProjects/03-GameConnect/src/com/masterclass/ISaveable.java
UTF-8
174
2.109375
2
[]
no_license
package com.masterclass; import java.util.ArrayList; public interface ISaveable { boolean storeValue( String value, String extraInfo ); ArrayList returnValues(); }
true
97176bef313d2b96dd27bbf2fe073bbd5bcc11ee
Java
wherego/NowsTop-master
/NewsTop-master/app/src/main/java/com/pengwl/newstop/https/HttpService.java
UTF-8
519
1.953125
2
[]
no_license
package com.pengwl.newstop.https; import com.pengwl.newstop.entry.HttpResult; import com.pengwl.newstop.entry.Subject; import java.util.List; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.Query; import rx.Observable; /** * Created by pengwl on 2016/11/25 0025. */ public interface HttpService { @Headers("Cache-Control: public, max-age=3600") @GET("top250") Observable<HttpResult<List<Subject>>> getTopMovie(@Query("start") int start, @Query("count") int count); }
true
5e916ba58247cdea4dcc4096bfab90f0a3207a79
Java
RaviTejaKomma/HangMan
/app/src/main/java/com/example/raviteja/hangman/MainActivity.java
UTF-8
655
1.96875
2
[ "Apache-2.0" ]
permissive
package com.example.raviteja.hangman; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // when start button is pressed // public void start_game(View view) { Intent i = new Intent(this,GameActivity.class); startActivity(i); } }
true
26c107b54195ad7b4dcb991f8121150c31f0b641
Java
gradle/performance-comparisons
/large-multiproject/project83/src/test/java/org/gradle/test/performance83_4/Test83_375.java
UTF-8
292
1.828125
2
[]
no_license
package org.gradle.test.performance83_4; import static org.junit.Assert.*; public class Test83_375 { private final Production83_375 production = new Production83_375("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
true
229cf3f393376398917b63af50d2a1121a087c95
Java
sptrakesh/sptwebmail
/src/test/com/sptci/mail/StoreManagerConnectTest.java
UTF-8
1,202
2.5
2
[ "Apache-2.0" ]
permissive
package com.sptci.mail; import static junit.framework.Assert.*; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for testing the connect method in the {@link * com.sptci.mail.StoreManager} class. * * <p>Copyright 2007 <a href='http://sptci.com/' target='_new'>Sans Pareil Technologies, Inc</a>.</p> * @author Rakesh Vidyadharan 2007-03-16 * @version $Id: StoreManagerConnectTest.java 52 2009-03-10 19:11:21Z sptrakesh $ */ public class StoreManagerConnectTest extends TestCase { static String user = System.getProperty( "mail.username" ); static String password = System.getProperty( "mail.password" ); public static Test suite() { return new TestSuite( StoreManagerConnectTest.class ); } /** * Test connection to mail store using a new instance of StoreManager. */ public void testConnect() throws Exception { MailSession session = CreateMailSessionTest.session; StoreManager manager = new StoreManager( session ); manager.connect( user, password ); assertNotNull( "Ensure store set in session", session.getStore() ); assertNotNull( "Ensure user set in session", session.getSession() ); } }
true
d02d60f6edd53dd0ccdceb070d902ac2fba903e8
Java
j-rust/435-pa2
/src/com/jrust/IDFCacheMap.java
UTF-8
796
2.265625
2
[]
no_license
package com.jrust; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; /** * Created by Jonathan Rust on 3/23/16. */ public class IDFCacheMap extends Mapper<LongWritable, Text, Text, Text> { /** * Method used solely to cache tfidf values for use later on in author detection * Input is a line from IDFReduce output * @param key * @param value * @param context */ @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] split = value.toString().split("\t"); String term = split[1]; String idf = split[3]; context.write(new Text(term), new Text(idf)); } }
true
eac48dfd3d3b0d6ea47d25aad3acc095f0e6da48
Java
AngelWongs/egou_parent
/egou_product_parent/egou_product_service/src/main/java/cn/ken/egou/controller/ProductExtController.java
UTF-8
5,224
2.28125
2
[]
no_license
package cn.ken.egou.controller; import cn.ken.egou.query.ProductExtQuery; import cn.ken.egou.service.IProductExtService; import cn.ken.egou.domain.ProductExt; import cn.ken.egou.utils.AjaxResult; import cn.ken.egou.utils.PageList; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.plugins.Page; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; @RestController @RequestMapping("/productExt") public class ProductExtController { @Autowired public IProductExtService productExtService; /** * 保存和修改公用的 * @param productExt 传递的实体 * @return Ajaxresult转换结果 */ @RequestMapping(value="/save",method= RequestMethod.POST) public AjaxResult save(@RequestBody ProductExt productExt){ try { if(productExt.getId()!=null){ productExtService.updateById(productExt); }else{ productExtService.insert(productExt); } return AjaxResult.me(); } catch (Exception e) { e.printStackTrace(); return AjaxResult.me().setMsg("保存对象失败!"+e.getMessage()); } } /** * 删除对象信息 * @param id * @return */ @RequestMapping(value="/{id}",method=RequestMethod.DELETE) public AjaxResult delete(@PathVariable("id") Long id){ try { productExtService.deleteById(id); return AjaxResult.me(); } catch (Exception e) { e.printStackTrace(); return AjaxResult.me().setMsg("删除对象失败!"+e.getMessage()); } } //获取用户 @RequestMapping(value = "/{id}",method = RequestMethod.GET) public ProductExt get(@PathVariable("id")Long id) { return productExtService.selectById(id); } /** * 查看所有的员工信息 * @return */ @RequestMapping(value = "/list",method = RequestMethod.GET) public List<ProductExt> list(){ return productExtService.selectList(null); } /** * 分页查询数据 * * @param query 查询对象 * @return PageList 分页对象 */ @RequestMapping(value = "/json",method = RequestMethod.POST) public PageList<ProductExt> json(@RequestBody ProductExtQuery query) { Page<ProductExt> page = new Page<ProductExt>(query.getPage(),query.getRows()); page = productExtService.selectPage(page); return new PageList<ProductExt>(page.getTotal(),page.getRecords()); } /** * 根据productid添加/修改显示属性 * @param */ @RequestMapping(value = "/saveSpecificationByProductTypeId",method = RequestMethod.POST) public AjaxResult saveByProductTypeId(@RequestBody Map map){ //获取productId String productId = map.get("productId").toString(); //获取去显示属性信息(list) List displayProperties = (List) map.get("specificationByProductTypeId"); if (productId!=null && !productId.isEmpty() && displayProperties!=null){ try { productExtService.saveByProductTypeId(new Long(productId),displayProperties); return AjaxResult.me().setSuccess(true).setMsg("操作OK"); }catch (Exception e){ } } return AjaxResult.me().setSuccess(false).setMsg("操作false"); } //保存sku属性到到数据库 sku表/product_ext /** productId:61 selectAllSKUByProductTypeId: [ {id=38, specName=颜色, productTypeId=197, type=true, value=null, skuValue=[红, 蓝]}, {id=39, specName=内存, productTypeId=197, type=true, value=null, skuValue=[4g, 6g]}, {id=40, specName=版本, productTypeId=197, type=true, value=null, skuValue=[1]} ] skuDatas: [ {颜色=红, 内存=4g, 版本=1, price=4, availableStock=1}, {颜色=红, 内存=6g, 版本=1, price=6, availableStock=1}, {颜色=蓝, 内存=4g, 版本=1, price=4, availableStock=1}, {颜色=蓝, 内存=6g, 版本=1, price=6, availableStock=1} ] */ @RequestMapping(value = "/saveAllSKUSpecificationByProductTypeId",method = RequestMethod.POST) public void saveAllSKUSpecificationByProductTypeId(@RequestBody Map map){ //获取productId String productId = map.get("productId").toString(); System.out.println("productId:"+ productId); //获取去skudata属性信息(list) List<Map<String,Object>> selectAllSKUByProductTypeId = (List<Map<String,Object>>) map.get("selectAllSKUByProductTypeId"); // String selectAllSKUByProductTypeIdJson = JSONObject.toJSONString(selectAllSKUByProductTypeId); System.out.println("selectAllSKUByProductTypeId:"+selectAllSKUByProductTypeId); List<Map<String,Object>> skuDatas = (List<Map<String, Object>>) map.get("skuDatas"); // String skuDatasJson = JSONObject.toJSONString(skuDatas); System.out.println("skuDatas:"+skuDatas); productExtService.saveAllSKUByProductId(productId,selectAllSKUByProductTypeId,skuDatas); } }
true
242e3768b488e992bbbcbba898abdd2d4ce2d7ce
Java
GuaiShushujie12138/Dingding
/src/com/guaishushu/control/ToBookList.java
UTF-8
8,881
2.359375
2
[]
no_license
package com.guaishushu.control; import java.io.IOException; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.guaishushu.bean.Category; import com.guaishushu.bean.CategoryDetail; import com.guaishushu.bean.PriceRank; import com.guaishushu.bean.Product; import com.guaishushu.bean.Publish; import com.guaishushu.dao.BookDao; import com.guaishushu.dao.BookDaoImpl; import com.guaishushu.dao.CategoryDao; import com.guaishushu.dao.CategoryDaoImpl; import com.guaishushu.sort.BookDateComparator; import com.guaishushu.sort.BookPriceComparator; import com.guaishushu.sort.BookSaleNumComparator; public class ToBookList extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); BookDao bookDao = new BookDaoImpl(); CategoryDao categoryDao = new CategoryDaoImpl(); // 判断用户点击的是大的图书分类还是小的图书分类 String type = request.getParameter("type"); HttpSession session = request.getSession(); // 查询所有的出版社 Set<Publish> publishs = bookDao.findAllPublish(); // 查询所有的图书价格区间(PriceRank) Set<PriceRank> ranks = bookDao.findallPriceRanks(); // 查询热卖的图书(最多显示四本) Set<Product> set = bookDao.findHotBooks(2); Set<Product> hot_books = new TreeSet<Product>(); int flag = 0; Iterator<Product> it1 = set.iterator(); while (it1.hasNext()) { flag++; Product book = it1.next(); hot_books.add(book); if (flag >= 4) { break; } } // 把热卖图书放进request中 request.setAttribute("hot_books", hot_books); // 把出版社放进request中 request.setAttribute("publishs", publishs); request.setAttribute("ranks", ranks); // 分类名字 // 大分类 String categoryName = ""; // 小分类 String detailName = ""; /** * 分页1 */ // 获取当前页的页码数 int pageNow = 1;// 默认是第一页 String pageNowMsg = request.getParameter("pageNow"); if (pageNowMsg != null && !"".equals(pageNowMsg) && !"null".equals(pageNowMsg) && !"undefined".equals(pageNowMsg)) { pageNow = Integer.parseInt(pageNowMsg); } // 设置一个页面显示的图书条数 int pageSize = 6; // 查询当前条件下的图书总数 int counts = 0; // 页面总数 int pageCount = 0; // booklist中的图书 Set<Product> books = null; // 获取筛选的条件 String rankMsg = request.getParameter("rank"); String publishMsg = request.getParameter("publish"); System.out.println("rankMsg : " + rankMsg); System.out.println("publishMsg : " + publishMsg); long rank_id = -1; long publish_id = -1; if (rankMsg != null && !"".equals(rankMsg) && !"null".equals(rankMsg)) { rank_id = Long.parseLong(rankMsg); } if (publishMsg != null && !"".equals(publishMsg) && !"null".equals(publishMsg)) { publish_id = Long.parseLong(publishMsg); } long type_id = 0; if ("category".equals(type)) { type_id = Long.parseLong(request.getParameter("category_id")); Category category = categoryDao.findCategoryByCategoryId(type_id); categoryName = category.getName(); detailName = categoryName; } else if ("detail".equals(type)) { type_id = Long.parseLong(request.getParameter("detail_id")); CategoryDetail detail = categoryDao.findDetailByDetailId(type_id); Category category = categoryDao.findCategoryByCategoryId(detail .getCategory().getId()); categoryName = category.getName(); detailName = detail.getName(); } // 把大小分类的名字放进request中 request.setAttribute("categoryName", categoryName); request.setAttribute("detailName", detailName); // if ("category".equals(type)) { // // 大分类 // long category_id = Long.parseLong(request // .getParameter("category_id")); // // if (rank_id != -1 && publish_id != -1) { // books = bookDao.findBooksByCategoryIdAndPublishAndRank( // category_id, publish_id, rank_id); // } else if (rank_id != -1 && publish_id == -1) { // books = bookDao.findBooksByCategoryIdAndRank(category_id, // rank_id); // } else if (rank_id == -1 && publish_id != -1) { // books = bookDao.findBooksByCategoryIdAndPublish(category_id, // publish_id); // } else { // books = bookDao.findBooksByCategoryId(category_id); // } // // } else if ("detail".equals(type)) { // // 小分类 // long detail_id = Long.parseLong(request.getParameter("detail_id")); // // if (rank_id != -1 && publish_id != -1) { // books = bookDao.findBooksByDetailIdAndPublishAndRank(detail_id, // publish_id, rank_id); // } else if (rank_id != -1 && publish_id == -1) { // books = bookDao.findBooksByDetailIdAndRank(detail_id, rank_id); // } else if (rank_id == -1 && publish_id != -1) { // books = bookDao.findBooksByDetailIdAndPublish(detail_id, // publish_id); // } else { // books = bookDao.findBooksByDetailId(detail_id); // } // // } // 查询出所有的图书来 books = bookDao.findAllBooks(type, type_id, rank_id, publish_id); // 判断是否还有其他附加条件 // 排序条件 String sort = request.getParameter("sort"); System.out.println("sort : " + sort); Iterator<Product> it = books.iterator(); if ("sale_num".equals(sort)) { // 如果是按照销量排序 Set<Product> saleBooks = new TreeSet<Product>( new BookSaleNumComparator()); while (it.hasNext()) { saleBooks.add(it.next()); } books = saleBooks; /** * 分页2.1 */ // 图书总数 counts = books.size(); // 页面数 pageCount = (counts + pageSize - 1) / pageSize; Set<Product> booksNow = new TreeSet<Product>( new BookSaleNumComparator()); Iterator<Product> it_old = books.iterator(); int i = 0; while (it_old.hasNext()) { i++; if (i > (pageNow - 1) * pageSize && i <= pageNow * pageSize) { booksNow.add(it_old.next()); } else { it_old.next(); } } books = booksNow; } else if ("price".equals(sort)) { // 如果是按照价格排序 Set<Product> saleBooks = new TreeSet<Product>( new BookPriceComparator()); while (it.hasNext()) { saleBooks.add(it.next()); } books = saleBooks; /** * 分页2.2 */ // 图书总数 counts = books.size(); // 页面数 pageCount = (counts + pageSize - 1) / pageSize; Set<Product> booksNow = new TreeSet<Product>( new BookPriceComparator()); Iterator<Product> it_old = books.iterator(); int i = 0; while (it_old.hasNext()) { i++; if (i > (pageNow - 1) * pageSize && i <= pageNow * pageSize) { booksNow.add(it_old.next()); } else { it_old.next(); } } books = booksNow; } else if ("new_product".equals(sort)) { // 如果是按照出版日期排序 Set<Product> saleBooks = new TreeSet<Product>( new BookDateComparator()); while (it.hasNext()) { saleBooks.add(it.next()); } books = saleBooks; /** * 分页2.3 */ // 图书总数 counts = books.size(); // 页面数 pageCount = (counts + pageSize - 1) / pageSize; Set<Product> booksNow = new TreeSet<Product>( new BookDateComparator()); Iterator<Product> it_old = books.iterator(); int i = 0; while (it_old.hasNext()) { i++; if (i > (pageNow - 1) * pageSize && i <= pageNow * pageSize) { booksNow.add(it_old.next()); } else { it_old.next(); } } books = booksNow; } else { // 默认排序 /** * 分页2.4 */ // 图书总数 counts = books.size(); System.out.println("counts : " + counts); // 页面数 pageCount = (counts + pageSize - 1) / pageSize; System.out.println("pageCount : " + pageCount); Set<Product> booksNow = new TreeSet<Product>(); Iterator<Product> it_old = books.iterator(); int i = 0; while (it_old.hasNext()) { i++; if (i > (pageNow - 1) * pageSize && i <= pageNow * pageSize) { booksNow.add(it_old.next()); } else { it_old.next(); } } books = booksNow; } /** * 分页3 */ // 把页面总数和当前页放进request中 request.setAttribute("pageNow", pageNow); request.setAttribute("pageCount", pageCount); // 存放图书到request中 request.setAttribute("books", books); // 跳转 request.getRequestDispatcher("WEB-INF/bookshop/booklist.jsp").forward( request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true
3f1d81bad236d9af9e4f7f932e36a7354a18e8f5
Java
devlopper/org.cyk.system.root
/root-persistence-impl-jpa/src/main/java/org/cyk/system/root/persistence/impl/GenericDaoImpl.java
UTF-8
2,961
2.09375
2
[]
no_license
package org.cyk.system.root.persistence.impl; import java.util.Collection; import org.cyk.system.root.model.AbstractIdentifiable; import org.cyk.system.root.model.globalidentification.GlobalIdentifier.SearchCriteria; import org.cyk.system.root.persistence.api.GenericDao; public class GenericDaoImpl extends AbstractPersistenceService<AbstractIdentifiable> implements GenericDao { private static final long serialVersionUID = 5597848028969504927L; /*-------------------------------------------------------------------------------------------*/ @Override public AbstractIdentifiable refresh(AbstractIdentifiable identifiable) { entityManager.refresh(identifiable); return identifiable; } @Override public <T extends AbstractIdentifiable> T read(Class<T> aClass, String code) { return inject(PersistenceInterfaceLocator.class).injectTyped(aClass).read(code); } /*--------------------------------------------------------------------------------------------*/ @SuppressWarnings("unchecked") @Override public GenericDao use(Class<? extends AbstractIdentifiable> aClass) { clazz = (Class<AbstractIdentifiable>) aClass; return this; } @Override public Collection<AbstractIdentifiable> readByGlobalIdentifierSearchCriteria(SearchCriteria globalIdentifierSearchCriteria) { throwNotYetImplemented(); return null; } @Override public Long countByGlobalIdentifierSearchCriteria(SearchCriteria globalIdentifierSearchCriteria) { throwNotYetImplemented(); return null; } @Override public AbstractIdentifiable readFirstWhereExistencePeriodFromDateIsLessThan(AbstractIdentifiable identifiable) { throwNotYetImplemented(); return null; } @Override public Collection<AbstractIdentifiable> readWhereExistencePeriodFromDateIsLessThan(AbstractIdentifiable identifiable) { throwNotYetImplemented(); return null; } @Override public AbstractIdentifiable read(String globalIdentifierCode) { throwNotYetImplemented(); return null; } @Override public Collection<AbstractIdentifiable> read(Collection<String> globalIdentifierCodes) { throwNotYetImplemented(); return null; } @Override public Long countWhereExistencePeriodFromDateIsLessThan(AbstractIdentifiable identifiable) { throwNotYetImplemented(); return null; } @Override public Collection<AbstractIdentifiable> readWhereExistencePeriodFromDateIsGreaterThan(AbstractIdentifiable identifiable) { throwNotYetImplemented(); return null; } @Override public Long countWhereExistencePeriodFromDateIsGreaterThan(AbstractIdentifiable identifiable) { throwNotYetImplemented(); return null; } @Override public Collection<AbstractIdentifiable> readWhereOrderNumberIsGreaterThan(AbstractIdentifiable identifiable) { throwNotYetImplemented(); return null; } @Override public Long countWhereOrderNumberIsGreaterThan(AbstractIdentifiable identifiable) { throwNotYetImplemented(); return null; } }
true
003430157271d124564a7c9ff38a47682da13d56
Java
jianzhaojohn/Habit-Rabbit
/app/src/main/java/comjianzhaojohnhabit_rabbit/httpsgithub/habit_rabbit/AboutusActivity.java
UTF-8
2,815
2.078125
2
[]
no_license
package comjianzhaojohnhabit_rabbit.httpsgithub.habit_rabbit; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import java.io.File; public class AboutusActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_aboutus2); } public void github(View view) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/jianzhaojohn/Habit-Rabbit")); startActivity(browserIntent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.navigation_menu, menu); return true; } /** * This hook is called whenever an item in your options menu is selected. * * @param item-The menu item that was selected. * @return boolean Return false to allow normal menu processing to proceed, true to consume it here. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.nav_Profile: startActivity(new Intent(AboutusActivity.this, ProfileActivity.class)); break; case R.id.nav_agenda: startActivity(new Intent(AboutusActivity.this, CalendarActivity.class)); break; case R.id.nav_habits: startActivity(new Intent(AboutusActivity.this, HabitListActivity.class)); break; case R.id.nav_logout: try { // getApplicationContext().deleteFile("autionloginfile"); File autologin = getApplicationContext().getFileStreamPath("autionloginfile"); autologin.delete(); // clear and delete data file, then logout SharedPref.clearAll(AboutusActivity.this); String fileName = SharedPref.FILE_NAME; File file = new File(this.getFilesDir().getParent() + "/shared_prefs/" + fileName + ".xml"); file.delete(); Intent intent = new Intent(this, LoginActivity.class); intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TOP | intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } catch (Exception e) { } break; default: } return super.onOptionsItemSelected(item); } }
true
1a3af7053595f6c5eb54bdf6713bae342bde6c17
Java
majaBai/algorithms-4th
/graphs/src/Search.java
UTF-8
1,018
3.359375
3
[]
no_license
import edu.princeton.cs.algs4.In; public class Search{ private Graph G; private int S; public Search(Graph g, int s){ this.G = g; this.S = s; } // check: is v connected with S public boolean marked(int v){ return G.connected(S, v); } // the count of vertexes, which connect with S public int count(){ return G.vertexesConnectedWith(S); } public static void main(String[] args){ // % java Search tinyG.txt 0 Graph G = new Graph(new In(args[0])); int s = Integer.parseInt(args[1]); Search search = new Search(G, s); for(int i = 0; i < G.V(); i++){ if(search.marked(i)){ System.out.print(i + " "); } } System.out.println(" "); System.out.println("the connected vertexes count: " + search.count()); if(search.count() != G.V()){ System.out.println("not connected"); } else System.out.println("connected"); } }
true
4425839d158dd5a2b41850375c3afcaf61cbf333
Java
linjukrishnan/egrocercustomer
/egrocer-customer/src/main/java/com/java/egrocer/customer/model/Cart.java
UTF-8
698
2.28125
2
[]
no_license
package com.java.egrocer.customer.model; public class Cart { private long cartId; private long productId; private int quantity; private long customerId; public long getCartId() { return cartId; } public void setCartId(long cartId) { this.cartId = cartId; } public long getProductId() { return productId; } public void setProductId(long productId) { this.productId = productId; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public long getCustomerId() { return customerId; } public void setCustomerId(long customerId) { this.customerId = customerId; } }
true
272957b6e47f6203573674c38bdfcf9936c5cafb
Java
bhaskarkoley87/SKUPromotionEngine
/src/main/java/com/bhk/eng/rules/Calculator.java
UTF-8
193
1.84375
2
[]
no_license
package com.bhk.eng.rules; import com.bhk.eng.beans.OrderDetails; public interface Calculator { public OrderDetails calculationOrder(OrderDetails orderDetails) throws Exception; }
true
e5e3bde9b9139ba384225003d571e0a32f0a4f66
Java
GlobalDataverseCommunityConsortium/dataverse
/src/test/java/edu/harvard/iq/dataverse/api/DuplicateFilesIT.java
UTF-8
23,459
2.375
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
package edu.harvard.iq.dataverse.api; import com.jayway.restassured.RestAssured; import com.jayway.restassured.parsing.Parser; import com.jayway.restassured.path.json.JsonPath; import com.jayway.restassured.response.Response; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.json.Json; import javax.json.JsonObjectBuilder; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.CREATED; import static javax.ws.rs.core.Response.Status.OK; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import org.junit.BeforeClass; import org.junit.Test; /** * Make assertions about duplicate file names (and maybe in the future, * duplicate MD5s). */ public class DuplicateFilesIT { @BeforeClass public static void setUpClass() { RestAssured.baseURI = UtilIT.getRestAssuredBaseUri(); } @Test public void uploadTwoFilesWithSameNameSameDirectory() throws IOException { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); createUser.then().assertThat() .statusCode(OK.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDataset = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDataset.prettyPrint(); createDataset.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDataset); Path pathtoReadme1 = Paths.get(Files.createTempDirectory(null) + File.separator + "README.md"); Files.write(pathtoReadme1, "File 1".getBytes()); System.out.println("README: " + pathtoReadme1); Response uploadReadme1 = UtilIT.uploadFileViaNative(datasetId.toString(), pathtoReadme1.toString(), apiToken); uploadReadme1.prettyPrint(); uploadReadme1.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.files[0].label", equalTo("README.md")); Path pathtoReadme2 = Paths.get(Files.createTempDirectory(null) + File.separator + "README.md"); Files.write(pathtoReadme2, "File 2".getBytes()); System.out.println("README: " + pathtoReadme2); Response uploadReadme2 = UtilIT.uploadFileViaNative(datasetId.toString(), pathtoReadme2.toString(), apiToken); uploadReadme2.prettyPrint(); uploadReadme2.then().assertThat() .statusCode(OK.getStatusCode()) // Note that "README.md" was changed to "README-1.md". This is a feature. It's what the GUI does. .body("data.files[0].label", equalTo("README-1.md")); } @Test public void uploadTwoFilesWithSameNameDifferentDirectories() throws IOException { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); createUser.then().assertThat() .statusCode(OK.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDataset = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDataset.prettyPrint(); createDataset.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDataset); Path pathtoReadme1 = Paths.get(Files.createTempDirectory(null) + File.separator + "README.md"); Files.write(pathtoReadme1, "File 1".getBytes()); System.out.println("README: " + pathtoReadme1); JsonObjectBuilder json1 = Json.createObjectBuilder() .add("description", "Description of the whole project."); Response uploadReadme1 = UtilIT.uploadFileViaNative(datasetId.toString(), pathtoReadme1.toString(), json1.build(), apiToken); uploadReadme1.prettyPrint(); uploadReadme1.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.files[0].label", equalTo("README.md")); Path pathtoReadme2 = Paths.get(Files.createTempDirectory(null) + File.separator + "README.md"); Files.write(pathtoReadme2, "File 2".getBytes()); System.out.println("README: " + pathtoReadme2); JsonObjectBuilder json2 = Json.createObjectBuilder() .add("description", "Docs for the code.") .add("directoryLabel", "code"); Response uploadReadme2 = UtilIT.uploadFileViaNative(datasetId.toString(), pathtoReadme2.toString(), json2.build(), apiToken); uploadReadme2.prettyPrint(); uploadReadme2.then().assertThat() .statusCode(OK.getStatusCode()) // The file name is still "README.md" (wasn't renamed) // because the previous file was in a different directory. .body("data.files[0].label", equalTo("README.md")); } @Test public void renameFileToSameName() throws IOException { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); createUser.then().assertThat() .statusCode(OK.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDataset = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDataset.prettyPrint(); createDataset.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDataset); Path pathtoReadme1 = Paths.get(Files.createTempDirectory(null) + File.separator + "README.md"); Files.write(pathtoReadme1, "File 1".getBytes()); System.out.println("README: " + pathtoReadme1); Response uploadReadme1 = UtilIT.uploadFileViaNative(datasetId.toString(), pathtoReadme1.toString(), apiToken); uploadReadme1.prettyPrint(); uploadReadme1.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.files[0].label", equalTo("README.md")); Integer idOfReadme1 = JsonPath.from(uploadReadme1.getBody().asString()).getInt("data.files[0].dataFile.id"); System.out.println("id: " + idOfReadme1); Path pathtoReadme2 = Paths.get(Files.createTempDirectory(null) + File.separator + "README2.md"); Files.write(pathtoReadme2, "File 2".getBytes()); System.out.println("README: " + pathtoReadme2); Response uploadReadme2 = UtilIT.uploadFileViaNative(datasetId.toString(), pathtoReadme2.toString(), apiToken); uploadReadme2.prettyPrint(); uploadReadme2.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.files[0].label", equalTo("README2.md")); Long idOfReadme2 = JsonPath.from(uploadReadme2.getBody().asString()).getLong("data.files[0].dataFile.id"); System.out.println("id: " + idOfReadme2); JsonObjectBuilder renameFile = Json.createObjectBuilder() .add("label", "README.md"); Response renameFileResponse = UtilIT.updateFileMetadata(String.valueOf(idOfReadme2), renameFile.build().toString(), apiToken); renameFileResponse.prettyPrint(); renameFileResponse.then().assertThat() .statusCode(BAD_REQUEST.getStatusCode()) .body("message", equalTo("Filename already exists at README.md")); // This "registerParser" is to avoid this error: Expected response body to be verified as JSON, HTML or XML but content-type 'text/plain' is not supported out of the box. RestAssured.registerParser("text/plain", Parser.JSON); Response getMetadataResponse = UtilIT.getDataFileMetadataDraft(idOfReadme2, apiToken); getMetadataResponse.prettyPrint(); getMetadataResponse.then().assertThat() .statusCode(OK.getStatusCode()) // The rename was rejected. It's still README2.md. .body("label", equalTo("README2.md")); } @Test public void moveFileToDirectoryContainingSameFileName() throws IOException { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); createUser.then().assertThat() .statusCode(OK.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDataset = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDataset.prettyPrint(); createDataset.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDataset); Path pathtoReadme1 = Paths.get(Files.createTempDirectory(null) + File.separator + "README.md"); Files.write(pathtoReadme1, "File 1".getBytes()); System.out.println("README: " + pathtoReadme1); JsonObjectBuilder json = Json.createObjectBuilder() .add("description", "Docs for the code.") .add("directoryLabel", "code"); Response uploadReadme1 = UtilIT.uploadFileViaNative(datasetId.toString(), pathtoReadme1.toString(), json.build(), apiToken); uploadReadme1.prettyPrint(); uploadReadme1.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.files[0].label", equalTo("README.md")); Integer idOfReadme1 = JsonPath.from(uploadReadme1.getBody().asString()).getInt("data.files[0].dataFile.id"); System.out.println("id: " + idOfReadme1); Path pathtoReadme2 = Paths.get(Files.createTempDirectory(null) + File.separator + "README.md"); Files.write(pathtoReadme2, "File 2".getBytes()); System.out.println("README: " + pathtoReadme2); Response uploadReadme2 = UtilIT.uploadFileViaNative(datasetId.toString(), pathtoReadme2.toString(), apiToken); uploadReadme2.prettyPrint(); uploadReadme2.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.files[0].label", equalTo("README.md")); Long idOfReadme2 = JsonPath.from(uploadReadme2.getBody().asString()).getLong("data.files[0].dataFile.id"); System.out.println("id: " + idOfReadme2); JsonObjectBuilder moveFile = Json.createObjectBuilder() .add("directoryLabel", "code"); Response moveFileResponse = UtilIT.updateFileMetadata(String.valueOf(idOfReadme2), moveFile.build().toString(), apiToken); moveFileResponse.prettyPrint(); moveFileResponse.then().assertThat() .statusCode(BAD_REQUEST.getStatusCode()) .body("message", equalTo("Filename already exists at code/README.md")); } /** * In this test we make sure that other changes in the absence of label and * directoryLabel go through, such as changing a file description. */ @Test public void modifyFileDescription() throws IOException { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); createUser.then().assertThat() .statusCode(OK.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDataset = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDataset.prettyPrint(); createDataset.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDataset); Path pathtoReadme1 = Paths.get(Files.createTempDirectory(null) + File.separator + "README.md"); Files.write(pathtoReadme1, "File 1".getBytes()); System.out.println("README: " + pathtoReadme1); Response uploadReadme1 = UtilIT.uploadFileViaNative(datasetId.toString(), pathtoReadme1.toString(), apiToken); uploadReadme1.prettyPrint(); uploadReadme1.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.files[0].label", equalTo("README.md")); Integer idOfReadme1 = JsonPath.from(uploadReadme1.getBody().asString()).getInt("data.files[0].dataFile.id"); System.out.println("id: " + idOfReadme1); JsonObjectBuilder updateFileMetadata = Json.createObjectBuilder() .add("description", "This file is awesome."); Response updateFileMetadataResponse = UtilIT.updateFileMetadata(String.valueOf(idOfReadme1), updateFileMetadata.build().toString(), apiToken); updateFileMetadataResponse.prettyPrint(); updateFileMetadataResponse.then().statusCode(OK.getStatusCode()); } /** * In this test we make sure that that if you keep the label the same, you * are still able to change other metadata such as file description. */ @Test public void modifyFileDescriptionSameLabel() throws IOException { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); createUser.then().assertThat() .statusCode(OK.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDataset = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDataset.prettyPrint(); createDataset.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDataset); Path pathtoReadme1 = Paths.get(Files.createTempDirectory(null) + File.separator + "README.md"); Files.write(pathtoReadme1, "File 1".getBytes()); System.out.println("README: " + pathtoReadme1); JsonObjectBuilder json1 = Json.createObjectBuilder() .add("directoryLabel", "code"); Response uploadReadme1 = UtilIT.uploadFileViaNative(datasetId.toString(), pathtoReadme1.toString(), json1.build(), apiToken); uploadReadme1.prettyPrint(); uploadReadme1.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.files[0].label", equalTo("README.md")); Integer idOfReadme1 = JsonPath.from(uploadReadme1.getBody().asString()).getInt("data.files[0].dataFile.id"); System.out.println("id: " + idOfReadme1); JsonObjectBuilder updateFileMetadata = Json.createObjectBuilder() .add("label", "README.md") .add("directoryLabel", "code") .add("description", "This file is awesome."); Response updateFileMetadataResponse = UtilIT.updateFileMetadata(String.valueOf(idOfReadme1), updateFileMetadata.build().toString(), apiToken); updateFileMetadataResponse.prettyPrint(); updateFileMetadataResponse.then().statusCode(OK.getStatusCode()); } /** * What if the directory for the file exists and you pass the filename * (label) while changing the description? This should be allowed. */ @Test public void existingDirectoryPassLabelChangeDescription() throws IOException { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); createUser.then().assertThat() .statusCode(OK.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDataset = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDataset.prettyPrint(); createDataset.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDataset); Path pathToFile = Paths.get(Files.createTempDirectory(null) + File.separator + "label"); Files.write(pathToFile, "File 1".getBytes()); System.out.println("file: " + pathToFile); JsonObjectBuilder json1 = Json.createObjectBuilder() .add("directory", "code"); Response uploadFile = UtilIT.uploadFileViaNative(datasetId.toString(), pathToFile.toString(), json1.build(), apiToken); uploadFile.prettyPrint(); uploadFile.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.files[0].label", equalTo("label")); Integer idOfFile = JsonPath.from(uploadFile.getBody().asString()).getInt("data.files[0].dataFile.id"); System.out.println("id: " + idOfFile); JsonObjectBuilder updateFileMetadata = Json.createObjectBuilder() .add("label", "label") .add("description", "This file is awesome."); Response updateFileMetadataResponse = UtilIT.updateFileMetadata(String.valueOf(idOfFile), updateFileMetadata.build().toString(), apiToken); updateFileMetadataResponse.prettyPrint(); updateFileMetadataResponse.then().statusCode(OK.getStatusCode()); } /** * This test is for the following scenario. * * What if the database has null for the directoryLabel? What if you pass in * directory as “” (because you don’t realize you can just not pass it). * when it check and compares, the old directory is null. so will that mean * labelChange = true and it will fail even though you didn’t really change * the directory? * * While "labelChange" does end up being true, * IngestUtil.conflictsWithExistingFilenames returns false, so the change is * allowed to go through. The description is allowed to be changed and the * directoryLabel remains null even though the user passed in an empty * string, which is what we want. */ @Test public void existingDirectoryNullPassEmptyStringChangeDescription() throws IOException { Response createUser = UtilIT.createRandomUser(); createUser.prettyPrint(); createUser.then().assertThat() .statusCode(OK.getStatusCode()); String username = UtilIT.getUsernameFromResponse(createUser); String apiToken = UtilIT.getApiTokenFromResponse(createUser); Response createDataverseResponse = UtilIT.createRandomDataverse(apiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createDataset = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, apiToken); createDataset.prettyPrint(); createDataset.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDataset); Path pathToFile = Paths.get(Files.createTempDirectory(null) + File.separator + "file1.txt"); Files.write(pathToFile, "File 1".getBytes()); System.out.println("file: " + pathToFile); JsonObjectBuilder json1 = Json.createObjectBuilder() .add("description", "This is my file."); Response uploadFile = UtilIT.uploadFileViaNative(datasetId.toString(), pathToFile.toString(), json1.build(), apiToken); uploadFile.prettyPrint(); uploadFile.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.files[0].label", equalTo("file1.txt")); Integer idOfFile = JsonPath.from(uploadFile.getBody().asString()).getInt("data.files[0].dataFile.id"); System.out.println("id: " + idOfFile); JsonObjectBuilder updateFileMetadata = Json.createObjectBuilder() // It doesn't make sense to pass "" as a directoryLabel. .add("directoryLabel", "") .add("description", "This file is awesome."); Response updateFileMetadataResponse = UtilIT.updateFileMetadata(String.valueOf(idOfFile), updateFileMetadata.build().toString(), apiToken); updateFileMetadataResponse.prettyPrint(); updateFileMetadataResponse.then().statusCode(OK.getStatusCode()); Response datasetJson = UtilIT.nativeGet(datasetId, apiToken); datasetJson.prettyPrint(); datasetJson.then().assertThat() .statusCode(OK.getStatusCode()) .body("data.latestVersion.files[0].label", equalTo("file1.txt")) .body("data.latestVersion.files[0].description", equalTo("This file is awesome.")) // Even though we tried to set directoryValue to "" above, it's correctly null in the database. .body("data.latestVersion.files[0].directoryLabel", nullValue()); } }
true
7b31dc28f9b7a1b92ad5e09bc3f0fc5bd7e7cfff
Java
benjaminsoellner/TUD_MobilisMiddleware
/MobilisMedia/src/de/tudresden/inf/rn/mobilis/media/activities/RepositorySubActivityHandler.java
UTF-8
3,529
2.25
2
[]
no_license
package de.tudresden.inf.rn.mobilis.media.activities; import android.content.Intent; import android.os.Handler; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import de.tudresden.inf.rn.mobilis.media.ConstMMedia; import de.tudresden.inf.rn.mobilis.media.parcelables.ConditionParcel; import de.tudresden.inf.rn.mobilis.media.parcelables.RepositoryItemParcel; public class RepositorySubActivityHandler extends Handler { private int arg2; private Messenger toParentMessenger; private Messenger fromParentMessenger; private SubActivityListener subActivityListener; public RepositorySubActivityHandler(Intent startingIntent) { this.fromParentMessenger = new Messenger( this ); this.toParentMessenger = (Messenger) startingIntent.getParcelableExtra( ConstMMedia.intent.extra.PAR_PARENTMESSENGER ); this.arg2 = startingIntent.getIntExtra( ConstMMedia.intent.extra.INT_CHILDARG2, 0 ); } public void setSubActivityListener(RepositorySubActivityHandler.SubActivityListener l) { this.subActivityListener = l; } protected void trySendToParent(Message m) { try { this.toParentMessenger.send(m); } catch (RemoteException e) { } } public void subActivityRegister() { Message m = Message.obtain(); m.what = ConstMMedia.message.WHAT_SUBACTIVITY_REGISTER; m.arg1 = ConstMMedia.message.ARG1_INFO; m.arg2 = this.arg2; m.getData().putParcelable(ConstMMedia.message.data.PAR_CHILDMESSENGER, this.fromParentMessenger); this.trySendToParent(m); } public void subActivityUnregister() { Message m = Message.obtain(); m.what = ConstMMedia.message.WHAT_SUBACTIVITY_UNREGISTER; m.arg1 = ConstMMedia.message.ARG1_INFO; m.arg2 = this.arg2; this.trySendToParent(m); } public void subActivityUpdate(ConditionParcel condition) { Message m = Message.obtain(); m.what = ConstMMedia.message.WHAT_SUBACTIVITY_UPDATE; m.arg1 = ConstMMedia.message.ARG1_INFO; m.arg2 = this.arg2; m.getData().putParcelable(ConstMMedia.message.data.PAR_CONDITION, condition); this.trySendToParent(m); } public void subActivityDisplay(RepositoryItemParcel repositoryItem) { Message m = Message.obtain(); m.what = ConstMMedia.message.WHAT_SUBACTIVITY_DISPLAY; m.arg1 = ConstMMedia.message.ARG1_INFO; m.arg2 = this.arg2; m.getData().putParcelable(ConstMMedia.message.data.PAR_REPOSITORYITEM, repositoryItem); this.trySendToParent(m); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (this.subActivityListener == null) return; switch (msg.what) { case ConstMMedia.message.WHAT_SUBACTIVITY_HIDE: this.subActivityListener.onSubActivityHide(); break; case ConstMMedia.message.WHAT_SUBACTIVITY_SHOW: this.subActivityListener.onSubActivityShow(); break; case ConstMMedia.message.WHAT_SUBACTIVITY_OUTDATE: this.subActivityListener.onSubActivityOutdate(); break; case ConstMMedia.message.WHAT_SUBACTIVITY_UPDATE: if (msg.arg1 == ConstMMedia.message.ARG1_SUCCESS) this.subActivityListener.onSubActivityUpdate( (RepositoryItemParcel[]) msg.getData().getParcelableArray(ConstMMedia.message.data.PARA_REPOSITORYITEM) ); else this.subActivityListener.onSubActivityUpdateError(); } } public static interface SubActivityListener { public void onSubActivityHide(); public void onSubActivityShow(); public void onSubActivityOutdate(); public void onSubActivityUpdate(RepositoryItemParcel[] items); public void onSubActivityUpdateError(); } }
true
35c6ed1d4919d2c65158cedccfde3335ce897444
Java
ExecTec/fdp1-2017-modulo1-1
/src/aula2/Calculadora.java
UTF-8
184
2.453125
2
[]
no_license
package aula2; public class Calculadora { char tamanho; String marca; int somar(int n1, int n2) { return n1 + n2; } int subtrair(int n1, int n2){ return n1-n2; } }
true
492178597afe57ee94f63a706dedc523af9d41aa
Java
bellmit/MetooMall
/src/com/metoo/foundation/dao/SysLogDAO.java
UTF-8
254
1.671875
2
[]
no_license
package com.metoo.foundation.dao; import org.springframework.stereotype.Repository; import com.metoo.core.base.GenericDAO; import com.metoo.foundation.domain.SysLog; @Repository("sysLogDAO") public class SysLogDAO extends GenericDAO<SysLog> { }
true
ada0cbc12c02adc562e1b862d2e8ba90bab4527a
Java
osuisumi/aa
/aip-survey/aip-survey-mobile-support/src/main/java/com/haoyu/aip/survey/mobile/entity/MSurveySubmission.java
UTF-8
529
1.851563
2
[]
no_license
package com.haoyu.aip.survey.mobile.entity; import java.io.Serializable; import com.haoyu.sip.core.entity.User; public class MSurveySubmission implements Serializable{ private static final long serialVersionUID = 3388226201045147531L; private String response; private User user; public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
true
f6838179ee2f0b7c560ef7bfac541c221082c58d
Java
mash-up-kr/Thing-BackEnd
/src/main/java/com/mashup/thing/review/service/DeleteReviewService.java
UTF-8
1,616
2.109375
2
[]
no_license
package com.mashup.thing.review.service; import com.mashup.thing.exception.review.NotFoundReviewException; import com.mashup.thing.exception.youtuber.NotFoundYouTuBerException; import com.mashup.thing.review.domain.ReviewRepository; import com.mashup.thing.review.domain.Review; import com.mashup.thing.review.dto.ReqDeleteReviewDto; import com.mashup.thing.youtuber.domain.YouTuberRepository; import com.mashup.thing.youtuber.domain.YouTuber; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class DeleteReviewService { private final YouTuberRepository youTuberRepository; private final ReviewRepository reviewRepository; public DeleteReviewService(YouTuberRepository youTuberRepository, ReviewRepository reviewRepository) { this.youTuberRepository = youTuberRepository; this.reviewRepository = reviewRepository; } @Transactional public void delete(Long reviewId, ReqDeleteReviewDto reqDeleteReviewDto) { Review review = reviewRepository.findByIdAndUserIdAndYouTuberId(reviewId, reqDeleteReviewDto.getUserId(), reqDeleteReviewDto.getYouTuberId()).orElseThrow(NotFoundReviewException::new); reviewRepository.delete(review); YouTuber youTuber = youTuberRepository.findById(review.getYouTuberId()) .orElseThrow(NotFoundYouTuBerException::new); if (review.isLike()) { youTuber.decreaseLikeReviewCount(); return; } youTuber.decreaseNoReviewCount(); } }
true
4d464145def8fa423e543d77dcbf5924402be64b
Java
Novanet-/AI-CW1
/AI CW1/src/game/GameResult.java
UTF-8
1,336
2.96875
3
[]
no_license
package game; import java.util.Stack; import game.board.BoardState; public class GameResult { private boolean solutionFound; private Stack<BoardState> solutionPath; private Integer nodesExpanded, agentMoves; /** * An object containing the board states that lead to the goal state of a of a run of the board game, the number of * nodes expanded to calculate it, and the number of moves the agent needs to take to reach that goal state * * @param solutionPath * Stack of board states that the agent moves to reach goal state * @param nodesExpanded * The number of nodes expanded to calculate solution * @param agentMoves * The number of moves the agent has to take to reach the goal state from the start state */ public GameResult(boolean solutionFound, Stack<BoardState> solutionPath, Integer nodesExpanded, Integer agentMoves) { super(); this.solutionFound = solutionFound; this.solutionPath = solutionPath; this.nodesExpanded = nodesExpanded; this.agentMoves = agentMoves; } public boolean isSolutionFound() { return solutionFound; } public Stack<BoardState> getSolutionPath() { return solutionPath; } public Integer getNodesExpanded() { return nodesExpanded; } public Integer getAgentMoves() { return agentMoves; } }
true
1e3841ecf56be5a230db424e77a7a93a8ca22258
Java
ctf/CTF-Android
/temp/wrappers/RoomPrintJob.java
UTF-8
1,381
2.640625
3
[]
no_license
package ca.mcgill.science.ctf.wrappers; import android.os.Parcel; import android.os.Parcelable; import ca.mcgill.science.ctf.enums.Room; import ca.mcgill.science.ctf.tepid.PrintJob; /** * Created by Allan Wang on 28/12/2016. * <p> * Wrapper class for Room and PrintJob[] */ public class RoomPrintJob implements Parcelable { public final Room room; public PrintJob[] printJobs; public RoomPrintJob(Room room, PrintJob[] printJobs) { this.room = room; this.printJobs = printJobs; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.room == null ? -1 : this.room.ordinal()); dest.writeTypedArray(this.printJobs, flags); } protected RoomPrintJob(Parcel in) { int tmpRoom = in.readInt(); this.room = tmpRoom == -1 ? null : Room.values()[tmpRoom]; this.printJobs = in.createTypedArray(PrintJob.CREATOR); } public static final Parcelable.Creator<RoomPrintJob> CREATOR = new Parcelable.Creator<RoomPrintJob>() { @Override public RoomPrintJob createFromParcel(Parcel source) { return new RoomPrintJob(source); } @Override public RoomPrintJob[] newArray(int size) { return new RoomPrintJob[size]; } }; }
true
4711966d1e106526ada001ebe489a179f2a0ad0a
Java
PeteChu/ExchangeTH_Android--Java
/app/src/main/java/com/example/schecterza/exchangerate2/view/CurrencyListItem.java
UTF-8
7,911
2.09375
2
[]
no_license
package com.example.schecterza.exchangerate2.view; import android.annotation.TargetApi; import android.content.Context; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import android.util.AttributeSet; import android.widget.FrameLayout; import android.widget.TextView; import com.example.schecterza.exchangerate2.R; import com.example.schecterza.exchangerate2.dao.CurrencyRate.*; import org.w3c.dom.Text; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by schecterza on 6/22/2017 AD. */ public class CurrencyListItem extends FrameLayout { Object bankData; int position; String bankName; KTB ktb; KBANK kbank; BAY bay; SCB scb; UOB uob; BOT bot; SIA sia; BBL bbl; GSB gsb; TMB tmb; SIAM siam; YENJIT yenjit; TextView tvCurrencyRate; TextView tvCurrencyBuy; TextView tvCurrencySell; public CurrencyListItem(@NonNull Context context, int position, Object bankData, String bankName) { super(context); this.position = position; this.bankName = bankName; this.bankData = bankData; setBank(bankName); initInflate(); initInstances(); } public CurrencyListItem(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); ButterKnife.bind(this); initInflate(); initInstances(); } public CurrencyListItem(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); ButterKnife.bind(this); initInflate(); initInstances(); } @TargetApi(21) public CurrencyListItem(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); ButterKnife.bind(this); initInflate(); initInstances(); } private void initInflate() { inflate(getContext(), R.layout.listview_currency_rate, this); } private void initInstances() { tvCurrencyRate = (TextView) findViewById(R.id.tv_currency_rate); tvCurrencyBuy = (TextView) findViewById(R.id.tv_currency_buy); tvCurrencySell = (TextView) findViewById(R.id.tv_currency_sell); setListItem(); } private void setListItem() { switch (bankName) { case "KTB": tvCurrencyRate.setText(ktb.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(ktb.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(ktb.getExchangeRateList().get(position).getSellingBankNotes()); break; case "KBANK": tvCurrencyRate.setText(kbank.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(kbank.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(kbank.getExchangeRateList().get(position).getSellingBankNotes()); break; case "BAY": tvCurrencyRate.setText(bay.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(bay.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(bay.getExchangeRateList().get(position).getSellingBankNotes()); break; case "SCB": tvCurrencyRate.setText(scb.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(scb.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(scb.getExchangeRateList().get(position).getSellingBankNotes()); break; case "UOB": tvCurrencyRate.setText(uob.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(uob.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(uob.getExchangeRateList().get(position).getSellingBankNotes()); break; case "BOT": tvCurrencyRate.setText(bot.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(bot.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(bot.getExchangeRateList().get(position).getSellingBankNotes()); break; case "SIA": tvCurrencyRate.setText(sia.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(sia.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(sia.getExchangeRateList().get(position).getSellingBankNotes()); break; case "BBL": tvCurrencyRate.setText(bbl.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(bbl.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(bbl.getExchangeRateList().get(position).getSellingBankNotes()); break; case "GSB": tvCurrencyRate.setText(gsb.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(gsb.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(gsb.getExchangeRateList().get(position).getSellingBankNotes()); break; case "TMB": tvCurrencyRate.setText(tmb.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(tmb.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(tmb.getExchangeRateList().get(position).getSellingBankNotes()); break; case "SIAM": tvCurrencyRate.setText(siam.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(siam.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(siam.getExchangeRateList().get(position).getSellingBankNotes()); break; case "YENJIT": tvCurrencyRate.setText(yenjit.getExchangeRateList().get(position).getCurrencyCode()); tvCurrencyBuy.setText(yenjit.getExchangeRateList().get(position).getBuyingBankNotes()); tvCurrencySell.setText(yenjit.getExchangeRateList().get(position).getSellingBankNotes()); break; } } private void setBank(String bankName) { switch (bankName) { case "KTB": ktb = (KTB) bankData; break; case "KBANK": kbank = (KBANK) bankData; break; case "BAY": bay = (BAY) bankData; break; case "SCB": scb = (SCB) bankData; break; case "UOB": uob = (UOB) bankData; break; case "BOT": bot = (BOT) bankData; break; case "SIA": sia = (SIA) bankData; break; case "BBL": bbl = (BBL) bankData; break; case "GSB": gsb = (GSB) bankData; break; case "TMB": tmb = (TMB) bankData; break; case "SIAM": siam = (SIAM) bankData; break; case "YENJIT": yenjit = (YENJIT) bankData; break; } } }
true
1ea9da2cdd47a38bd64ae14c7eac563c1c01e98b
Java
aniltelaprolu/InventryAngular
/Inventory-17-Jan-2018/inventory-parent/inventory-common/src/main/java/com/inventory/common/modal/entitlement/InvUserAddress.java
UTF-8
3,645
2.125
2
[]
no_license
package com.inventory.common.modal.entitlement; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.validator.constraints.NotEmpty; import com.inventory.common.constants.AppConstants.ADDRESSTYPE; import com.inventory.common.modal.base.BaseAuditModel; @Table(name = "inv_user_address") @Entity public class InvUserAddress extends BaseAuditModel { /** * */ private static final long serialVersionUID = -3215112523372344591L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "address_id") private Long addressId; @NotEmpty(message = "Please provide the Address") @Column(name = "address_line1") private String addressLine1; @NotEmpty(message = "Please provide the Address") @Column(name="address_line2") private String addressLine2; @Column(name="address_line3") private String addressLine3; @NotEmpty(message = "Please provide the pincode") @Column(name="pincode") private String pincode; @NotEmpty(message = "Please provide the City") @Column(name="city") private String city; @NotEmpty(message = "Please provide the State") @Column(name="state") private String state; @NotEmpty(message = "Please provide the Country") @Column(name="country") private String country; @NotEmpty(message = "Please provide the Address type") @Column(name = "address_type") @Enumerated(EnumType.STRING) private ADDRESSTYPE addressType; /** * @return the addressId */ public Long getAddressId() { return addressId; } /** * @param addressId the addressId to set */ public void setAddressId(Long addressId) { this.addressId = addressId; } /** * @return the addressLine1 */ public String getAddressLine1() { return addressLine1; } /** * @param addressLine1 the addressLine1 to set */ public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } /** * @return the addressLine2 */ public String getAddressLine2() { return addressLine2; } /** * @param addressLine2 the addressLine2 to set */ public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } /** * @return the addressLine3 */ public String getAddressLine3() { return addressLine3; } /** * @param addressLine3 the addressLine3 to set */ public void setAddressLine3(String addressLine3) { this.addressLine3 = addressLine3; } /** * @return the pincode */ public String getPincode() { return pincode; } /** * @param pincode the pincode to set */ public void setPincode(String pincode) { this.pincode = pincode; } /** * @return the city */ public String getCity() { return city; } /** * @param city the city to set */ public void setCity(String city) { this.city = city; } /** * @return the state */ public String getState() { return state; } /** * @param state the state to set */ public void setState(String state) { this.state = state; } /** * @return the country */ public String getCountry() { return country; } /** * @param country the country to set */ public void setCountry(String country) { this.country = country; } /** * @return the addressType */ public ADDRESSTYPE getAddressType() { return addressType; } /** * @param addressType the addressType to set */ public void setAddressType(ADDRESSTYPE addressType) { this.addressType = addressType; } }
true
79c3e3e18608ad1afb9a015f69108f6c74828202
Java
zhangyaojun95/mybatis_plus
/src/main/java/com/atguigu/mybatisplus/entity/User.java
UTF-8
988
2.125
2
[]
no_license
package com.atguigu.mybatisplus.entity; import com.baomidou.mybatisplus.annotation.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.time.LocalDateTime; /** * @description * @author: ZYJ * @Date: create in 2021/9/18 11:11 **/ @AllArgsConstructor @NoArgsConstructor @Data @TableName(value = "user") public class User implements Comparable<User>{ @TableId(type = IdType.ASSIGN_ID,value = "id") private Long id; private String loginId; private String password; private String userName; private String email; @TableField(value = "create_time",fill = FieldFill.INSERT) private LocalDateTime createTime; @TableField(value = "update_time",fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime; @TableLogic @TableField(value = "is_deleted") private Integer deleted; @Override public int compareTo(User user) { return id.compareTo(user.getId()); } }
true
6d6201c01b0046f157ed684e7541010b03cb9c33
Java
albenw/myExcelUtil
/src/main/java/com/albenw/excel/base/reader/ExcelReader.java
UTF-8
4,329
2.34375
2
[]
no_license
package com.albenw.excel.base.reader; import com.albenw.excel.base.IndexingField; import com.albenw.excel.base.constant.ParserTypeEnum; import com.albenw.excel.base.context.ReaderContext; import com.albenw.excel.base.listener.ReadEventListener; import com.albenw.excel.base.parser.DomParserWrapper; import com.albenw.excel.base.parser.ParserWrapper; import com.albenw.excel.base.parser.ReadParser; import com.albenw.excel.base.parser.SaxParserWrapper; import com.albenw.excel.exception.ErrorCode; import com.albenw.excel.exception.ExcelException; import com.albenw.excel.util.CollectionUtil; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import java.io.InputStream; import java.util.List; /** * @author alben.wong * @since 2019-01-31. */ @Getter @Setter @Slf4j public class ExcelReader { private ParserWrapper parserWrapper; private ReaderContext context; public void read(InputStream in) throws Exception{ ReadParser readParser = parserWrapper.createReadParser(in, context); readParser.execute(in, context); } private <T> ExcelReader(Class<T> targetClass, ParserTypeEnum parserType, Integer sheetNum, Integer startRow, ReadEventListener listener, Integer batchSize, List<IndexingField> fields){ this.context = new ReaderContext<T>(targetClass, parserType, sheetNum, startRow, listener, batchSize, fields); switch (parserType){ case DOM: parserWrapper = new DomParserWrapper(); break; case SAX: parserWrapper = new SaxParserWrapper(); break; default: break; } } public static <T> Builder<T> newBuilder() { return new Builder(); } @Setter @Getter public static class Builder<T> { private Class<T> targetClass; private Integer sheetNum; private ParserTypeEnum parserType; private ReadEventListener listener; private Integer batchSize; private Integer startRow; private List<IndexingField> fields; public Builder<T> targetClass(Class<T> clz) { this.setTargetClass(clz); return this; } public Builder<T> sheetNum(int sheetNum) { this.setSheetNum(sheetNum); return this; } public Builder<T> parserType(ParserTypeEnum parserType){ this.parserType = parserType; return this; } public Builder<T> startRow(Integer startRow){ this.startRow = startRow; return this; } public Builder<T> addListener(ReadEventListener<T> listener){ this.listener = listener; return this; } public ExcelReader build() throws ExcelException { checkBuildParameter(); return new ExcelReader(this.targetClass, this.parserType, this.sheetNum, this.startRow, this.listener, this.batchSize, this.fields); } private void checkBuildParameter() throws ExcelException { //默认第一个sheet if(this.sheetNum == null){ this.sheetNum = 0; } //默认第二行开始 if(this.startRow == null){ this.startRow = 1; } if(this.batchSize == null){ this.batchSize = 100; } if(this.targetClass == null){ throw new ExcelException(ErrorCode.PARAMETER_ERROR, "缺少targetClass参数"); } List<IndexingField> indexingFields = CollectionUtil.sortImportFieldByIndex(targetClass); if(CollectionUtil.isEmpty(indexingFields)){ throw new ExcelException(ErrorCode.PARAMETER_ERROR, String.format("%s类缺少ImportField注解", this.targetClass.getName())); } this.fields = indexingFields; if(parserType == null){ throw new ExcelException(ErrorCode.PARAMETER_ERROR, "缺少parserType参数"); } if(ParserTypeEnum.SAX.equals(parserType) && this.listener == null){ throw new ExcelException(ErrorCode.PARAMETER_ERROR, "SAX模式下必须listener"); } } } }
true
f617bb72c1bfbc3c8f63d0e0ea9c74f90491afb4
Java
samuerio/component-poi
/src/main/java/com/issun/component/hssfworkbook/bean/type/ExcelModeType.java
UTF-8
287
2.515625
3
[]
no_license
package com.issun.component.hssfworkbook.bean.type; /** * Excel模式:导入和导出 * * @author ZHe */ public enum ExcelModeType { IMPORT(0),EXPORT(1); private int type; ExcelModeType(int type){ this.type = type; } public int getType(){ return this.type; } }
true
7bad86b285606ce41bef701d497fb15b740c0411
Java
sunli7758521/blue_client
/client/system_common/src/main/java/com/msj/goods/mapper/IntegralRecordMapper.java
UTF-8
432
1.71875
2
[]
no_license
package com.msj.goods.mapper; import com.msj.goods.entity.IntegralRecord; import com.baomidou.mybatisplus.mapper.BaseMapper; import java.util.List; import java.util.Map; /** * <p> * 商品兑换记录表 Mapper 接口 * </p> * * @author sun li * @since 2018-11-05 */ public interface IntegralRecordMapper extends BaseMapper<IntegralRecord> { // 查询所有人的兑换记录 List<Map> selectAllCountYDScore(); }
true
2bc8b9427118d633dc619240caab504803531860
Java
Jameslxm/EggplantFastPass
/app/src/main/java/com/james/eggplantfastpass/holder/ThreeViewHolder.java
UTF-8
465
2.109375
2
[ "Apache-2.0" ]
permissive
package com.james.eggplantfastpass.holder; import android.view.View; import com.james.eggplantfastpass.adapter.MultiTypeAdapter; import com.james.eggplantfastpass.model.Three; /** * Created by yq05481 on 2017/1/3. */ public class ThreeViewHolder extends BaseViewHolder<Three> { public ThreeViewHolder(View itemView) { super(itemView); } @Override public void setUpView(Three model, int position, MultiTypeAdapter adapter) { } }
true
df65a09197938354d62e110fb8a0da79a2421d69
Java
EniacHome/AndroidApp
/app/src/main/java/com/eniacdevelopment/eniachometwo/Fragments/SecurityFragment.java
UTF-8
4,436
2.203125
2
[]
no_license
package com.eniacdevelopment.eniachometwo.Fragments; /** * Created by denni on 1/4/2017. */ import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.StrictMode; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Switch; import android.widget.Toast; import com.eniacdevelopment.EniacHome.DataModel.Alarm.AlarmStatus; import com.eniacdevelopment.eniachometwo.Activities.MainActivity; import com.eniacdevelopment.eniachometwo.R; import java.util.ArrayList; import java.util.List; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; public class SecurityFragment extends IFragment implements SwipeRefreshLayout.OnRefreshListener { private View view; private SwipeRefreshLayout swipeRefreshLayout; private WebTarget webTarget; Switch alarmSwitch; EditText alarmLevelEditText; public SecurityFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_security, container, false); if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } webTarget = ((MainActivity)getActivity()).getWebTarget(); initFragmentData(); return view; } private void initFragmentData() { swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.SwipeRefreshSecurity); swipeRefreshLayout.setOnRefreshListener(this); alarmSwitch = (Switch) view.findViewById(R.id.alarm_switch); alarmLevelEditText = (EditText) view.findViewById(R.id.alarm_level); new getAlarmDataTask().execute(); } @Override public int getFragmentTitle() { return 2; } @Override public String getFragmentTag() { return "FRAGMENT_SECURITY"; } @Override public void onPause() { super.onPause(); if (swipeRefreshLayout != null) { swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setEnabled(false); swipeRefreshLayout.destroyDrawingCache(); swipeRefreshLayout.clearAnimation(); } } @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(false); new getAlarmDataTask().execute(); } },2000); } class getAlarmDataTask extends AsyncTask<Void,Void,AlarmStatus> { @Override protected AlarmStatus doInBackground(Void... params) { try { Response response = webTarget.path("alarm").request().get(); return response.readEntity(AlarmStatus.class); } catch (RuntimeException e) { return null; } } @Override protected void onPostExecute(final AlarmStatus status) { if (status != null) { alarmSwitch.setChecked(status.Enabled); alarmSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (alarmSwitch.isChecked()) { String alarmLevel = alarmLevelEditText.getText().toString().isEmpty() ? String.valueOf(status.Level) : alarmLevelEditText.getText().toString(); webTarget.path("alarm").path("enable").path(alarmLevel).request().get(); } else { webTarget.path("alarm").path("disable").request().get(); } } }); alarmLevelEditText.setText(String.valueOf(status.Level)); } else { Toast.makeText(getContext(),getString(R.string.communication_failed),Toast.LENGTH_LONG); } } } }
true
cece430f5ef32ea0acfd363a3f59a956724e8ec5
Java
GueniPlayz/BanSystem-Recode
/bansystem-bukkit/src/de/papiertuch/bukkit/events/BukkitPlayerLoginNotifyEvent.java
UTF-8
411
1.96875
2
[]
no_license
package de.papiertuch.bukkit.events; import lombok.AllArgsConstructor; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import java.util.UUID; @AllArgsConstructor public class BukkitPlayerLoginNotifyEvent extends Event { private UUID uuid; private boolean state; private HandlerList handlers; @Override public HandlerList getHandlers() { return null; } }
true
6a662844e177bdf96330b0923205b27caa06fe23
Java
Yangzhichao1125/note
/yangyou/yy-upload/src/test/java/com/yangyou/uploade/FdfsTest.java
UTF-8
2,061
1.90625
2
[]
no_license
package com.yangyou.uploade; import com.aliyun.oss.internal.OSSUploadOperation; import com.github.tobato.fastdfs.domain.StorePath; import com.github.tobato.fastdfs.domain.ThumbImageConfig; import com.github.tobato.fastdfs.service.FastFileStorageClient; import com.yangyou.upload.LyUploadService; import com.yangyou.upload.controller.UploadController; import com.yangyou.upload.util.OSSUploadUtil; import com.yangyou.upload.util.OssUtil; import org.apache.http.entity.ContentType; 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.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * This is Description * * @author yang * @date 2019/12/10 */ @RunWith(SpringRunner.class) @SpringBootTest(classes = LyUploadService.class) public class FdfsTest { @Autowired private FastFileStorageClient storageClient; @Autowired private ThumbImageConfig thumbImageConfig; @Autowired OssUtil ossUtil; @Test public void testUpload() throws FileNotFoundException { File file = new File("/Users/yang/Pictures/down/2019-09-15/1568512396340.jpg"); FileInputStream fileInputStream = new FileInputStream(file); MultipartFile multipartFile = null; try { multipartFile = new MockMultipartFile("copy"+file.getName(),file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream); } catch (IOException e) { e.printStackTrace(); } String type = multipartFile.getContentType(); String url = ossUtil.uploadFile(type, multipartFile); System.out.println("str = " + url); } public static void main(String[] args) { String endpoint = ""; } }
true
68f083fb6d6af3f6148305b76053b3444499d7a1
Java
jiaxinGong/springboot-dubbo2
/dubbo-web/src/main/java/com/jiaxin/dubbo/Application.java
UTF-8
2,352
1.992188
2
[]
no_license
package com.jiaxin.dubbo; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication //@MapperScan("com.welab.thor.mybatis.mapper") @ImportResource({"classpath:/applicationContext.xml"}) @EnableScheduling //@EnableApolloConfig //@PropertySource({"application.properties","server.properties"}) @PropertySource({"classpath:/server.properties"})// application.properties默认会加载,无需指定 public class Application{ //public class Application extends SpringBootServletInitializer { private static Logger LOG = LoggerFactory.getLogger(Application.class); /** * 采用FastJson代替默认的com.fasterxml.jackson */ @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); } public static void main(String[] args) { try { SpringApplication.run(Application.class, args); } catch (Exception e) { LOG.error("Start FAIL.", e); } } // @Override // protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { // return builder.sources(Application.class); // } }
true