blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 28 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9b70bf3c1380fc5f82dd6fbc0d4948d248749a83 | 6408198f4484ad230fb2ba898fcd2a4746a772b1 | /src/org/AHHN/com/annotation/Main.java | 40338813e472bf276915bda3d945c39cacd1721d | [] | no_license | TianYunZi/SpringPractise | ca240797c869cc6ad9777f89d1852d18abf9e254 | 787f234f85528b2f072b27a57a8f0d668cb02e91 | refs/heads/master | 2021-01-10T15:13:14.765917 | 2016-02-29T00:01:34 | 2016-02-29T00:01:34 | 52,445,313 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,017 | java | package org.AHHN.com.annotation;
import org.AHHN.com.annotation.controller.UserController;
import org.AHHN.com.annotation.repository.UserRepositoryImpl;
import org.AHHN.com.annotation.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by XJX on 2016/2/28.
*/
public class Main {
public static void main(String[] args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-annotation.xml");
// TestObject testObject=(TestObject)ctx.getBean("testObject");
// System.out.println(testObject);
//
UserController userController=(UserController)ctx.getBean("userController");
userController.execute();
System.out.println(userController);
//
// UserService userService=(UserService)ctx.getBean("userService");
// System.out.println(userService);
// UserRepositoryImpl userRepository=(UserRepositoryImpl)ctx.getBean("userRepository");
// System.out.println(userRepository);
}
}
| [
"zxysegh@gmail.com"
] | zxysegh@gmail.com |
deed63cf875b95a15ca3121e41915eb13246a6d0 | 92b1387c0e2a1d3c3be07bfcd35b5b34d4fd2447 | /ncpdp/models/org.ncpdp.uml.telecom/src/org/ncpdp/uml/telecom/util/TelecomValidator.java | 865171154426d87d56fd9393253080fdfb836150 | [] | no_license | swmuir/xxxxx | acfe945bb61344b05d624583ad99e37265a01fa7 | 7283be138f37955fb4a4905545628fe264a94da2 | refs/heads/master | 2021-01-19T14:57:24.884955 | 2012-07-19T13:37:16 | 2012-07-19T13:37:16 | 37,691,941 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,117 | java | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.ncpdp.uml.telecom.util;
import java.util.Map;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.util.EObjectValidator;
import org.ncpdp.uml.telecom.*;
/**
* <!-- begin-user-doc -->
* The <b>Validator</b> for the model.
* <!-- end-user-doc -->
* @see org.ncpdp.uml.telecom.TelecomPackage
* @generated
*/
public class TelecomValidator extends EObjectValidator {
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final TelecomValidator INSTANCE = new TelecomValidator();
/**
* A constant for the {@link org.eclipse.emf.common.util.Diagnostic#getSource() source} of diagnostic {@link org.eclipse.emf.common.util.Diagnostic#getCode() codes} from this package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.common.util.Diagnostic#getSource()
* @see org.eclipse.emf.common.util.Diagnostic#getCode()
* @generated
*/
public static final String DIAGNOSTIC_SOURCE = "org.ncpdp.uml.telecom";
/**
* The {@link org.eclipse.emf.common.util.Diagnostic#getCode() code} for constraint 'Transmission Transaction Header Segment' of 'Transmission'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final int TRANSMISSION__TRANSMISSION_TRANSACTION_HEADER_SEGMENT = 1;
/**
* A constant with a fixed name that can be used as the base value for additional hand written constants.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final int GENERATED_DIAGNOSTIC_CODE_COUNT = 1;
/**
* A constant with a fixed name that can be used as the base value for additional hand written constants in a derived class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static final int DIAGNOSTIC_CODE_COUNT = GENERATED_DIAGNOSTIC_CODE_COUNT;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TelecomValidator() {
super();
}
/**
* Returns the package of this validator switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EPackage getEPackage() {
return TelecomPackage.eINSTANCE;
}
/**
* Calls <code>validateXXX</code> for the corresponding classifier of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean validate(int classifierID, Object value, DiagnosticChain diagnostics, Map<Object, Object> context) {
switch (classifierID) {
case TelecomPackage.DOCUMENT_ROOT:
return validateDocumentRoot((DocumentRoot)value, diagnostics, context);
case TelecomPackage.TRANSMISSION:
return validateTransmission((Transmission)value, diagnostics, context);
case TelecomPackage.TRANSACTION_HEADER_SEGMENT:
return validateTransactionHeaderSegment((TransactionHeaderSegment)value, diagnostics, context);
case TelecomPackage.FIELD:
return validateField((Field)value, diagnostics, context);
case TelecomPackage.WORKERS_COMPENSATION_SEGMENT:
return validateWorkersCompensationSegment((WorkersCompensationSegment)value, diagnostics, context);
case TelecomPackage.PRIOR_AUTHORIZATION_SEGMENT:
return validatePriorAuthorizationSegment((PriorAuthorizationSegment)value, diagnostics, context);
case TelecomPackage.PRICING_SEGMENT:
return validatePricingSegment((PricingSegment)value, diagnostics, context);
case TelecomPackage.PRESCRIBER_SEGMENT:
return validatePrescriberSegment((PrescriberSegment)value, diagnostics, context);
case TelecomPackage.PHARMACY_PROVIDER_SEGMENT:
return validatePharmacyProviderSegment((PharmacyProviderSegment)value, diagnostics, context);
case TelecomPackage.PATIENT_SEGMENT:
return validatePatientSegment((PatientSegment)value, diagnostics, context);
case TelecomPackage.NARRATIVE_SEGMENT:
return validateNarrativeSegment((NarrativeSegment)value, diagnostics, context);
case TelecomPackage.INSURANCE_SEGMENT:
return validateInsuranceSegment((InsuranceSegment)value, diagnostics, context);
case TelecomPackage.FACILITY_SEGMENT:
return validateFacilitySegment((FacilitySegment)value, diagnostics, context);
case TelecomPackage.DURPPS_SEGMENT:
return validateDURPPSSegment((DURPPSSegment)value, diagnostics, context);
case TelecomPackage.COUPON_SEGMENT:
return validateCouponSegment((CouponSegment)value, diagnostics, context);
case TelecomPackage.COORDINATIONOF_BENEFITS_OTHER_PAYMENTS_SEGMENT:
return validateCoordinationofBenefitsOtherPaymentsSegment((CoordinationofBenefitsOtherPaymentsSegment)value, diagnostics, context);
case TelecomPackage.CLINICAL_SEGMENT:
return validateClinicalSegment((ClinicalSegment)value, diagnostics, context);
case TelecomPackage.CLAIM_SEGMENT:
return validateClaimSegment((ClaimSegment)value, diagnostics, context);
case TelecomPackage.ADDITIONAL_DOCUMENTATION_SEGMENT:
return validateAdditionalDocumentationSegment((AdditionalDocumentationSegment)value, diagnostics, context);
case TelecomPackage.COMPOUND_SEGMENT:
return validateCompoundSegment((CompoundSegment)value, diagnostics, context);
case TelecomPackage.RESPONSE:
return validateResponse((Response)value, diagnostics, context);
case TelecomPackage.RESPONSE_HEADER_SEGMENT:
return validateResponseHeaderSegment((ResponseHeaderSegment)value, diagnostics, context);
case TelecomPackage.RESPONSE_CLAIM_SEGMENT:
return validateResponseClaimSegment((ResponseClaimSegment)value, diagnostics, context);
case TelecomPackage.RESPONSE_COORDINATIONOF_BENEFITS_OTHER_PAYERS_SEGMENT:
return validateResponseCoordinationofBenefitsOtherPayersSegment((ResponseCoordinationofBenefitsOtherPayersSegment)value, diagnostics, context);
case TelecomPackage.RESPONSE_DURPPS_SEGMENT:
return validateResponseDURPPSSegment((ResponseDURPPSSegment)value, diagnostics, context);
case TelecomPackage.RESPONSE_INSURANCE_SEGMENT:
return validateResponseInsuranceSegment((ResponseInsuranceSegment)value, diagnostics, context);
case TelecomPackage.RESPONSE_MESSAGE_SEGMENT:
return validateResponseMessageSegment((ResponseMessageSegment)value, diagnostics, context);
case TelecomPackage.RESPONSE_PATIENT_SEGMENT:
return validateResponsePatientSegment((ResponsePatientSegment)value, diagnostics, context);
case TelecomPackage.RESPONSE_PRICING_SEGMENT:
return validateResponsePricingSegment((ResponsePricingSegment)value, diagnostics, context);
case TelecomPackage.RESPONSE_PRIOR_AUTHORIZATION_SEGMENT:
return validateResponsePriorAuthorizationSegment((ResponsePriorAuthorizationSegment)value, diagnostics, context);
case TelecomPackage.RESPONSE_STATUS_SEGMENT:
return validateResponseStatusSegment((ResponseStatusSegment)value, diagnostics, context);
default:
return true;
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateDocumentRoot(DocumentRoot documentRoot, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(documentRoot, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateTransactionHeaderSegment(TransactionHeaderSegment transactionHeaderSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(transactionHeaderSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateField(Field field, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(field, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateClaimSegment(ClaimSegment claimSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(claimSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateClinicalSegment(ClinicalSegment clinicalSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(clinicalSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateCompoundSegment(CompoundSegment compoundSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(compoundSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateWorkersCompensationSegment(WorkersCompensationSegment workersCompensationSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(workersCompensationSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateInsuranceSegment(InsuranceSegment insuranceSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(insuranceSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateCoordinationofBenefitsOtherPaymentsSegment(CoordinationofBenefitsOtherPaymentsSegment coordinationofBenefitsOtherPaymentsSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(coordinationofBenefitsOtherPaymentsSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validatePatientSegment(PatientSegment patientSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(patientSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponsePatientSegment(ResponsePatientSegment responsePatientSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(responsePatientSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponseInsuranceSegment(ResponseInsuranceSegment responseInsuranceSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(responseInsuranceSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponseDURPPSSegment(ResponseDURPPSSegment responseDURPPSSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(responseDURPPSSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validatePricingSegment(PricingSegment pricingSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(pricingSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validatePriorAuthorizationSegment(PriorAuthorizationSegment priorAuthorizationSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(priorAuthorizationSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponseStatusSegment(ResponseStatusSegment responseStatusSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(responseStatusSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateAdditionalDocumentationSegment(AdditionalDocumentationSegment additionalDocumentationSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(additionalDocumentationSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponseMessageSegment(ResponseMessageSegment responseMessageSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(responseMessageSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponseClaimSegment(ResponseClaimSegment responseClaimSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(responseClaimSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateFacilitySegment(FacilitySegment facilitySegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(facilitySegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateCouponSegment(CouponSegment couponSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(couponSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponseCoordinationofBenefitsOtherPayersSegment(ResponseCoordinationofBenefitsOtherPayersSegment responseCoordinationofBenefitsOtherPayersSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(responseCoordinationofBenefitsOtherPayersSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateDURPPSSegment(DURPPSSegment durppsSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(durppsSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponse(Response response, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(response, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponseHeaderSegment(ResponseHeaderSegment responseHeaderSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(responseHeaderSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponsePricingSegment(ResponsePricingSegment responsePricingSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(responsePricingSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateResponsePriorAuthorizationSegment(ResponsePriorAuthorizationSegment responsePriorAuthorizationSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(responsePriorAuthorizationSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validatePrescriberSegment(PrescriberSegment prescriberSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(prescriberSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validatePharmacyProviderSegment(PharmacyProviderSegment pharmacyProviderSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(pharmacyProviderSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNarrativeSegment(NarrativeSegment narrativeSegment, DiagnosticChain diagnostics, Map<Object, Object> context) {
return validate_EveryDefaultConstraint(narrativeSegment, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateTransmission(Transmission transmission, DiagnosticChain diagnostics, Map<Object, Object> context) {
boolean result = validate_EveryMultiplicityConforms(transmission, diagnostics, context);
if (result || diagnostics != null) result &= validate_EveryDataValueConforms(transmission, diagnostics, context);
if (result || diagnostics != null) result &= validate_EveryReferenceIsContained(transmission, diagnostics, context);
if (result || diagnostics != null) result &= validate_EveryProxyResolves(transmission, diagnostics, context);
if (result || diagnostics != null) result &= validate_UniqueID(transmission, diagnostics, context);
if (result || diagnostics != null) result &= validate_EveryKeyUnique(transmission, diagnostics, context);
if (result || diagnostics != null) result &= validate_EveryMapEntryUnique(transmission, diagnostics, context);
if (result || diagnostics != null) result &= validateTransmission_TransmissionTransactionHeaderSegment(transmission, diagnostics, context);
return result;
}
/**
* Validates the TransmissionTransactionHeaderSegment constraint of '<em>Transmission</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateTransmission_TransmissionTransactionHeaderSegment(Transmission transmission, DiagnosticChain diagnostics, Map<Object, Object> context) {
return transmission.TransmissionTransactionHeaderSegment(diagnostics, context);
}
/**
* Returns the resource locator that will be used to fetch messages for this validator's diagnostics.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
// TODO
// Specialize this to return a resource locator for messages specific to this validator.
// Ensure that you remove @generated or mark it @generated NOT
return super.getResourceLocator();
}
} //TelecomValidator
| [
"seanmuir@0837804a-1577-0410-aeab-e204489bf47d"
] | seanmuir@0837804a-1577-0410-aeab-e204489bf47d |
124edd0919d53f2808d55eda6b798bd309e6064d | d727e53f2e557c88bcf59aa49f49ca5bbb7e6654 | /src/com/massivecraft/mcore/util/TimeUnit.java | b008654fe3a11a17f3f9b68990f89ff092822aeb | [] | no_license | riking/mcore | 108ea59ac2e6d7a9e658455984fbe6cb8dfd59a8 | f78872c15755ead8ed19051be3e08e19220fbb40 | refs/heads/master | 2021-01-17T23:50:30.851298 | 2013-08-29T08:55:35 | 2013-08-29T08:55:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,087 | java | package com.massivecraft.mcore.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.TreeSet;
public class TimeUnit implements Comparable<TimeUnit>
{
// -------------------------------------------- //
// CONSTANTS
// -------------------------------------------- //
public static final long MILLIS_PER_MILLISECOND = 1L;
public static final long MILLIS_PER_SECOND = 1000L * MILLIS_PER_MILLISECOND;
public static final long MILLIS_PER_MINUTE = 60L * MILLIS_PER_SECOND;
public static final long MILLIS_PER_HOUR = 60L * MILLIS_PER_MINUTE;
public static final long MILLIS_PER_DAY = 24L * MILLIS_PER_HOUR;
public static final long MILLIS_PER_WEEK = 7L * MILLIS_PER_DAY;
public static final long MILLIS_PER_MONTH = 31L * MILLIS_PER_DAY;
public static final long MILLIS_PER_MONTHUP = 32L * MILLIS_PER_DAY;
public static final long MILLIS_PER_YEAR = 365L * MILLIS_PER_DAY;
public static final TimeUnit YEAR = new TimeUnit(MILLIS_PER_YEAR, "year", "years", "year", "years", "y", "year", "years");
public static final TimeUnit MONTH = new TimeUnit(MILLIS_PER_MONTH, "month", "months", "month", "months", "month", "months");
public static final TimeUnit WEEK = new TimeUnit(MILLIS_PER_WEEK, "week", "weeks", "week", "weeks", "w", "week", "weeks");
public static final TimeUnit DAY = new TimeUnit(MILLIS_PER_DAY, "day", "days", "day", "days", "d", "day", "days");
public static final TimeUnit HOUR = new TimeUnit(MILLIS_PER_HOUR, "hour", "hours", "h", "h", "h", "hs", "hour", "hours");
public static final TimeUnit MINUTE = new TimeUnit(MILLIS_PER_MINUTE, "minute", "minutes", "min", "min", "m", "min", "mins", "minute", "minutes");
public static final TimeUnit SECOND = new TimeUnit(MILLIS_PER_SECOND, "second", "seconds", "s", "s", "s", "sec", "secs", "second", "seconds");
public static final TimeUnit MILLISECOND = new TimeUnit(MILLIS_PER_MILLISECOND, "millisecond", "milliseconds", "ms", "ms", "millis", "millisec", "millisecs", "millisecond", "milliseconds", "ms", "msec", "msecs", "msecond", "mseconds");
// -------------------------------------------- //
// REGISTRY
// -------------------------------------------- //
private static final TreeSet<TimeUnit> all = new TreeSet<TimeUnit>();
public static TreeSet<TimeUnit> getAll() { return new TreeSet<TimeUnit>(all); }
public static TreeSet<TimeUnit> getAllButMillis()
{
TreeSet<TimeUnit> ret = new TreeSet<TimeUnit>(all);
ret.remove(MILLISECOND);
return ret;
}
public static TreeSet<TimeUnit> getAllButMillisAndSeconds()
{
TreeSet<TimeUnit> ret = new TreeSet<TimeUnit>(all);
ret.remove(MILLISECOND);
ret.remove(SECOND);
return ret;
}
public static TimeUnit get(String timeUnitString)
{
if (timeUnitString == null) return null;
String timeUnitStringLowerCase = timeUnitString.toLowerCase();
for(TimeUnit timeUnit : all)
{
for (String alias : timeUnit.aliases)
{
if (alias.equals(timeUnitStringLowerCase))
{
return timeUnit;
}
}
}
return null;
}
public static boolean register(TimeUnit timeUnit)
{
return all.add(timeUnit);
}
static
{
register(YEAR);
register(MONTH);
register(WEEK);
register(DAY);
register(HOUR);
register(MINUTE);
register(SECOND);
register(MILLISECOND);
}
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
public final long millis;
public final String singularName;
public final String pluralName;
public final String singularUnit;
public final String pluralUnit;
public final Collection<String> aliases;
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
private TimeUnit(long millis, String singularName, String pluralName, String singularUnit, String pluralUnit, String... aliases)
{
this.millis = millis;
this.singularName = singularName;
this.pluralName = pluralName;
this.singularUnit = singularUnit;
this.pluralUnit = pluralUnit;
this.aliases = new ArrayList<String>(Arrays.asList(aliases));
}
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
public String getUnitString(long amount)
{
if (amount == 1) return this.singularUnit;
return this.pluralUnit;
}
public String getNameString(long amount)
{
if (amount == 1) return this.singularName;
return this.pluralName;
}
// -------------------------------------------- //
// BASIC
// -------------------------------------------- //
@Override
public String toString()
{
return this.singularName;
}
@Override
public int compareTo(TimeUnit that)
{
return Long.valueOf(this.millis).compareTo(that.millis) * -1;
}
@Override
public final boolean equals(Object other)
{
if (! (other instanceof TimeUnit)) return false;
return this.millis == ((TimeUnit)other).millis;
}
}
| [
"olof@sylt.nu"
] | olof@sylt.nu |
73b59d32255dd85a03ce951c9ddc3836bf27ed86 | 52ec70772f4d5ce1dcd4caaf1f4e8e2ee48422f2 | /app/src/test/java/com/company/services/ExampleUnitTest.java | 34a01cac919c893557de156f104e5318c72432f2 | [] | no_license | esraafathy225/Services | 9c20f467295c9a449827a55cf0f7a49ef79ae182 | b78073b12834e8bdb0fc65ab067a8151f6c8a988 | refs/heads/master | 2023-03-10T20:34:16.510131 | 2021-02-24T13:45:31 | 2021-02-24T13:45:31 | 341,914,099 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 381 | java | package com.company.services;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"esraa.fathy225@gmail.com"
] | esraa.fathy225@gmail.com |
f4aa21479e6160a6c8f6afa1092ebda20ea4f165 | eae28aa2e7a8d47e3c79d9353f372d1a953247ba | /app/src/main/java/edu/umb/external/CustomAutoCompleteView.java | 0a786aa2c99e4499e5fcb7e34155afd279717d28 | [
"MIT"
] | permissive | ranjandahal/BostonMbta | 2deb9fb015871b89f4b2af98aeab0f0de8d668ee | af20968683f717bf4caee8838286d6fb2fbc7fcd | refs/heads/master | 2022-02-27T11:42:39.522073 | 2019-11-14T02:29:27 | 2019-11-14T02:29:27 | 73,563,134 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,175 | java | package edu.umb.external;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AutoCompleteTextView;
import edu.umb.subway.R;
/**
* Created by Ranjan on 11/18/2016.
*/
public class CustomAutoCompleteView extends AutoCompleteTextView {
boolean cleared = false;
public CustomAutoCompleteView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomAutoCompleteView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomAutoCompleteView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
// this is how to disable AutoCompleteTextView filter
@Override
protected void performFiltering(final CharSequence text, final int keyCode) {
String filterText = "";
super.performFiltering(filterText, keyCode);
}
void init() {
// Set the bounds of the button
this.setCompoundDrawablesWithIntrinsicBounds(null, null,
imgClearButton, null);
// if the clear button is pressed, fire up the handler. Otherwise do nothing
this.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
CustomAutoCompleteView et = CustomAutoCompleteView.this;
if (et.getCompoundDrawables()[2] == null)
return false;
if (event.getAction() != MotionEvent.ACTION_UP)
return false;
if (event.getX() > et.getWidth() - et.getPaddingRight() - imgClearButton.getIntrinsicWidth()) {
onClearListener.onClear();
cleared = true;
}
return false;
}
});
}
public void setImgClearButton(Drawable imgClearButton) {
this.imgClearButton = imgClearButton;
}
public void setOnClearListener(final OnClearListener clearListener) {
this.onClearListener = clearListener;
}
public void hideClearButton() {
this.setCompoundDrawables(null, null, null, null);
}
public void showClearButton() {
this.setCompoundDrawablesWithIntrinsicBounds(null, null, imgClearButton, null);
}
// if not set otherwise, the default clear listener clears the text in the
// text view
private OnClearListener defaultClearListener = new OnClearListener() {
@Override
public void onClear() {
CustomAutoCompleteView et = CustomAutoCompleteView.this;
et.setText("");
}
};
private OnClearListener onClearListener = defaultClearListener;
// The image we defined for the clear button
public Drawable imgClearButton = getResources().getDrawable(
R.drawable.abc_ic_clear_holo_light);
public interface OnClearListener {
void onClear();
}
}
| [
"ranjan.dahal@live.com"
] | ranjan.dahal@live.com |
5b935176694db1bd383e1a199df407ca6bffd40d | d12db7e6171e03a3baf13c4972183408e0fd57d3 | /extentmerge/src/main/java/com/relevantcodes/extentmerge/DataAggregator.java | e8b37ab8aa903335be4b75dd5d7d4550ffbeae4a | [
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] | permissive | ursmurli/extentreports | be50b0f366a407d3dd8ee463d68003e8d644979f | a0d328330bd84c5c2e327c0a6cea3c3f039a2f31 | refs/heads/master | 2020-12-26T04:56:45.569037 | 2015-10-09T18:27:07 | 2015-10-09T18:27:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 956 | java | /*
* The MIT License (MIT)
*
* Copyright (c) 2015, Anshoo Arora (Relevant Codes)
*/
package com.relevantcodes.extentmerge;
import java.util.ArrayList;
import java.util.List;
class DataAggregator implements IAggregator {
private List<IAggregator> aggregatorList;
public DataAggregator(List<String> directoryList, List<String> htmlFilePathList, List<String> databaseFilePathList) {
aggregatorList = new ArrayList<IAggregator>();
aggregatorList.add(new FileInfoAggregator(htmlFilePathList));
aggregatorList.add(new DirectoryInfoAggregator(directoryList));
aggregatorList.add(new DatabaseInfoAggregator(databaseFilePathList));
}
public List<Report> getAggregatedData() {
List<Report> reportList = new ArrayList<Report>();
List<Report> list;
for (IAggregator aggregator : aggregatorList) {
list = aggregator.getAggregatedData();
if (list != null) {
reportList.addAll(list);
}
}
return reportList;
}
}
| [
"anshooarora@gmail.com"
] | anshooarora@gmail.com |
a48237de45966f8aa5db5c190d37cc1f30915d40 | e7870e420ef4c2479d6f46a56db65f65427104da | /src/test/java/org/isouth/tree/BinaryTreeTest.java | 57995044cbe352c9e6b50954e763a9852ef1e33a | [
"MIT"
] | permissive | qiyi/tree | 175c7e31b2882f6e21b2f6bb6e7c269c827764a8 | 37c180a1dafd6131f156fca36ac96b75723cd235 | refs/heads/master | 2021-09-14T03:29:24.619749 | 2018-05-07T17:10:43 | 2018-05-07T17:10:43 | 109,284,212 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 782 | java | package org.isouth.tree;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class BinaryTreeTest {
@Test
public void testTree() {
Tree<Object> tree = new BinaryTree<>();
tree.add(6, "6");
tree.add(6, "6.1");
tree.add(3, "3");
tree.add(8, "8");
tree.add(7, "7");
tree.add(9, "9");
tree.add(2, "2");
tree.add(10, "10");
Object r1 = tree.get(9);
assertEquals("9", r1);
List<Object> results = tree.rangeSearch(3, 9);
System.out.println(results);
tree.delete(8);
Object r2 = tree.get(8);
assertNull(r2);
System.out.println(tree.toString());
}
}
| [
"bphanzhu@gmail.com"
] | bphanzhu@gmail.com |
8a05b1d38c77aee9aeb87282983be9e14d222248 | e97cc54f31b9785b7dca8458609a96a26d704951 | /src/com/narayan/Java_How_To_Program/DepositSlot.java | 5d59b6121a45971e0267a78520612ffb87117d0a | [] | no_license | narayansau/ATM_CASE_STUDY | cd6c0bba6e6bdfb6a08c1493940c4d9689cdd547 | a96aac9173764e4e4773053bfed9a2821139b76d | refs/heads/master | 2020-07-12T15:31:08.901805 | 2019-08-28T05:06:26 | 2019-08-28T05:06:26 | 204,852,378 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 70 | java | package com.narayan.Java_How_To_Program;
public class DepositSlot{
}
| [
"narayansau@yahoo.com"
] | narayansau@yahoo.com |
340124c905b7dec6f64864035b89316a89fa6ab8 | c9f7d47de4ae1b3051a9331a3346a7be280dde22 | /learning-06/src/main/java/top/liubowen/learning06/Application.java | 2d7399a5452f015f0604f270659e7e66fe974f3c | [] | no_license | MoringSatr/spinng-boot-learning | 163a43d537b72e0a83c3e74a07b609809719253d | c340a8ffaccda16629a11573923589cb551e9804 | refs/heads/master | 2020-03-11T07:27:59.716062 | 2018-12-25T11:20:39 | 2018-12-25T11:20:39 | 129,857,435 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 315 | java | package top.liubowen.learning06;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| [
"liubowen"
] | liubowen |
5aa6bdd2ee4840ef2dc20e4805315c003b35fceb | aa99e8760ef5e7f528a70b168eb9379e634ee4fe | /src/main/java/com/jhipster/blog/config/LocaleConfiguration.java | fb4f8b7925a4ca345137d74805aeada9857d84cc | [] | no_license | MichelliBrito/jhipster-gateway | dff6b6db3cba3e8eb3f169d1263a787a98ce7f5e | 9ebe6fb97d586c3c3a86c4a076db0a5debf16010 | refs/heads/master | 2022-12-22T22:52:58.907650 | 2020-03-01T01:40:37 | 2020-03-01T01:40:37 | 244,048,715 | 9 | 0 | null | 2022-12-16T05:13:23 | 2020-02-29T22:08:48 | Java | UTF-8 | Java | false | false | 1,060 | java | package com.jhipster.blog.config;
import io.github.jhipster.config.locale.AngularCookieLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
@Configuration
public class LocaleConfiguration implements WebMvcConfigurer {
@Bean(name = "localeResolver")
public LocaleResolver localeResolver() {
AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver();
cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY");
return cookieLocaleResolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
registry.addInterceptor(localeChangeInterceptor);
}
}
| [
"michellidibrito@gmail.com"
] | michellidibrito@gmail.com |
0d42e70dc3ad04716c41fe01983f780435b6b757 | c47cc7508b591503ebc24d5b8245798f0e4865f2 | /ID3/src/com/houzhi/id3/uitl/FactoryImp.java | 15002f14aaf3cfc26436d1b2cbcaba62ce351ae4 | [] | no_license | xxxzhi/id3test | ea6e16942fd18139d05fc45e09f91926fade9679 | 13c162b0c1b79224c6091ab28ae67c9a69db00d4 | refs/heads/master | 2020-04-02T02:35:57.083946 | 2013-06-04T07:57:39 | 2013-06-04T07:57:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 665 | java | package com.houzhi.id3.uitl;
import java.util.ArrayList;
import java.util.List;
public interface FactoryImp<T> {
public List<T> getListAttribute();
/**
* 获得标志,将各种属性类型,统一转变成装箱类型Integer
* @return
*/
public Integer id(T t);
/**
* 所有的id标号 改标号的长度应该与amount() 相同。即标号集
* @return
*/
public List<Integer> idList();
/**
* 找到 该id 在所有id 中的位置
* @param id
* @return
*/
public int idPosition(Integer id);
/**
* 产生一个属性
* @param id
* @return
*/
public Attribute factory(int id);
public Attribute factory(T t);
}
| [
"xxxzhi91@gmail.com"
] | xxxzhi91@gmail.com |
3a2a2ed74aa0c3c2a3eaffa2b91f420de3f38baf | 91336c4fe5bcfa47b4ba2892e8b18e51c8943c42 | /src/main/java/week15d03/PostFinder.java | 9c82102bd80591eae48135cadd781a911f1550c0 | [] | no_license | Radacs-Bence/training-solutions | cf8a701f73ce984cb75c6b0a2c87f0b4cbbc28a4 | 48ed3f840c388eaefa86399cceea83d407eaa485 | refs/heads/master | 2023-03-08T02:41:19.822357 | 2021-02-21T00:17:21 | 2021-02-21T00:17:21 | 308,308,748 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,348 | java | package week15d03;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PostFinder {
private List<Post> posts;
public PostFinder(List<Post> posts) {
this.posts = posts;
}
public List<Post> findPosts(String user){
LocalDate now = LocalDate.now();
return posts.stream()
.filter(post -> post.getPublishedAt().isBefore(now) || post.getOwner().equals(user))
.filter(post -> (post.getTitle() != null && !post.getTitle().isEmpty())
&& (post.getContent() != null && !post.getContent().isEmpty()))
.filter(post -> post.getDeletedAt() == null || post.getDeletedAt().isAfter(now))
.collect(Collectors.toList());
}
public static void main(String[] args) {
List<Post> testData = Arrays.asList(
new Post("My First Post", LocalDate.of(2018, 1, 6), LocalDate.of(2019, 6, 19), "Tartalom", "Pista"),
new Post("My Article", LocalDate.of(2019, 3, 18), null, "Tartalom", "Pista"),
new Post("I like Java", LocalDate.of(2020, 2, 20), null, "Tartalom", "Pista")
);
PostFinder postFinder = new PostFinder(testData);
System.out.println(postFinder.findPosts("Pista"));
}
}
| [
"bence.radacs@gmail.com"
] | bence.radacs@gmail.com |
a5d63744106c9147f62d5d1883b38e35708047f3 | 5c3f7f329dc1c4daef4a549bcd5ee005faa97fe8 | /semiProjectGroup1/src/controller/Admin_MoviePeopleUpdateController.java | 4763bd4c688f794e8734f2bd7e73b086988c9a85 | [] | no_license | jhta1st/semiProjectGroup1 | eb71ec2199800e4432f41556232a55991f5a8c02 | 5619502e8b96d27093033c419e21af302d2325a9 | refs/heads/master | 2020-05-04T19:30:32.697703 | 2019-04-16T10:59:17 | 2019-04-16T10:59:17 | 179,396,798 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 2,808 | java | package controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import dao.Admin_CharInfoDao;
import vo.Admin_CharInfoVo;
@WebServlet("/admin/MoviePeopleUpdate.do")
public class Admin_MoviePeopleUpdateController extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int charNum=Integer.parseInt(req.getParameter("charNum"));
Admin_CharInfoDao dao=Admin_CharInfoDao.getInstance();
Admin_CharInfoVo vo=dao.detail(charNum);
req.setAttribute("vo", vo);
req.setAttribute("pages", "/Admin/admin_MoviePeopleUpdate.jsp");
req.getRequestDispatcher("/main/layout.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String dir=req.getServletContext().getRealPath("/Movie/images/char");
MultipartRequest mr=new MultipartRequest(
req,
dir,
1024*1024*5,
"utf-8",
new DefaultFileRenamePolicy()
);
Admin_CharInfoDao dao= Admin_CharInfoDao.getInstance();
int charNum=Integer.parseInt(mr.getParameter("charNum"));
Admin_CharInfoVo vo=dao.detail(charNum);
String charName=mr.getParameter("charName");
String charOrgFileName=mr.getOriginalFileName("file2");//전송된 파일명
int n=0;
if(charOrgFileName!=null){//수정할 파일이 전송된 경우
String savefile=mr.getFilesystemName("file2");//저장된 파일명
File f1=mr.getFile("file2");
Admin_CharInfoVo vo1=new Admin_CharInfoVo(charNum, charName, charOrgFileName, savefile);
n=dao.update(vo1);
//3. 기존파일삭제
String charSavFileName=vo.getCharSavFileName();
File f=new File(dir +"\\" + charSavFileName);
if(f.delete()){
}
}else{//수정할 파일이 전송되지 않은 경우
//기존정보 그대로 유지하기
Admin_CharInfoVo vo2=new Admin_CharInfoVo(charNum, charName, vo.getCharOrgFileName(), vo.getCharSavFileName());
n=dao.update(vo2);
}
if(n>0){
req.setAttribute("pages", "/admin/MoviePeopleList.do");
req.getRequestDispatcher("/main/layout.jsp").forward(req, resp);
}else{
req.setAttribute("code", "fail");
req.setAttribute("pages", "/User/user_result.jsp");
req.getRequestDispatcher("/main/layout.jsp").forward(req, resp);
}
}
}
| [
"JHTA@JHTA-PC"
] | JHTA@JHTA-PC |
94f5f22dc51c68a5f8d27ac6feddd9cd49d51efc | e0bd9898ab4afa3d781958a06e406182daf0d7e8 | /src/pl/javastart/forms/servlet/InputServlet.java | b40734a14443ffd608408d4995b7f20b71d1a751 | [] | no_license | eMIKARp/JEE_Excercise_2 | f37a735816c2760340c4cfa13323bcf3b521e4da | 7b6d29c9987199bcc1407c79107d1c783c04c586 | refs/heads/master | 2020-03-13T08:14:19.674901 | 2018-04-25T20:18:28 | 2018-04-25T20:18:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,025 | java | package pl.javastart.forms.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pl.javastart.forms.bean.User;
@WebServlet("/InputServlet")
public class InputServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public InputServlet()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
User user = createUserFromRequest(request);
sendResponse(user, response);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
User user = createUserFromRequest(req);
sendResponse(user, resp);
}
public User createUserFromRequest(HttpServletRequest request)
{
User user = new User();
user.setUsername(request.getParameter("username"));
user.setGender(request.getParameter("gender"));
user.setHobby(request.getParameterValues("hobby"));
user.setPassword(request.getParameter("password"));
return user;
}
public void sendResponse(User user, HttpServletResponse response) throws IOException
{
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<body>");
writer.println("<h2>Dane pobrano pomyślnie</h2>");
writer.print("<div>");
writer.println(user.getUsername()+"<br>");
writer.println(user.getPassword()+"<br>");
writer.println(user.getGender()+"<br>");
if (user.getHobby()!= null)
{
writer.println("Hobby:<br>");
for (String hobby: user.getHobby())
writer.println(" "+hobby+"<br>");
}
writer.print("</div>");
writer.println("</body>");
writer.println("</html>");
}
}
| [
"emil.karpowicz@gmail.com"
] | emil.karpowicz@gmail.com |
4f7efd73b176b0e29353e2f76506b160c68b75b8 | e12af772256dccc4f44224f68b7a3124673d9ced | /jitsi/src/net/java/sip/communicator/plugin/sip2sipaccregwizz/Sip2SipAccRegWizzActivator.java | be62d3718e3d80f96a4092035c5bdc5b49a9125d | [] | no_license | leshikus/dataved | bc2f17d9d5304b3d7c82ccb0f0f58c7abcd25b2a | 6c43ab61acd08a25b21ed70432cd0294a5db2360 | refs/heads/master | 2021-01-22T02:33:58.915867 | 2016-11-03T08:35:22 | 2016-11-03T08:35:22 | 32,135,163 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,587 | java | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.plugin.sip2sipaccregwizz;
import java.util.*;
import org.osgi.framework.*;
import net.java.sip.communicator.service.browserlauncher.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.resources.*;
/**
* Registers the <tt>GoogleTalkAccountRegistrationWizard</tt> in the UI Service.
*
* @author Lubomir Marinov
* @author Yana Stamcheva
*/
public class Sip2SipAccRegWizzActivator
implements BundleActivator
{
/**
* The bundle context.
*/
public static BundleContext bundleContext;
/**
* The browser launcher service.
*/
private static BrowserLauncherService browserLauncherService;
/**
* The resources service.
*/
private static ResourceManagementService resourcesService;
/**
* The ui service.
*/
private static UIService uiService;
/**
* Starts this bundle.
* @param bc BundleContext
* @throws Exception
*/
public void start(BundleContext bc)
throws Exception
{
bundleContext = bc;
System.setProperty(
"http.agent",
System.getProperty("sip-communicator.application.name")
+ "/"
+ System.getProperty("sip-communicator.version"));
uiService =
(UIService) bundleContext.getService(bundleContext
.getServiceReference(UIService.class.getName()));
Sip2SipAccountRegistrationWizard wizard
= new Sip2SipAccountRegistrationWizard(uiService
.getAccountRegWizardContainer());
Hashtable<String, String> containerFilter
= new Hashtable<String, String>();
containerFilter.put(
ProtocolProviderFactory.PROTOCOL,
Sip2SipAccountRegistrationWizard.PROTOCOL);
bundleContext.registerService(
AccountRegistrationWizard.class.getName(),
wizard,
containerFilter);
}
public void stop(BundleContext bundleContext) throws Exception {}
/**
* Returns the <tt>UIService</tt>.
*
* @return the <tt>UIService</tt>
*/
public static UIService getUIService()
{
return uiService;
}
/**
* Returns the <tt>BrowserLauncherService</tt> obtained from the bundle
* context.
* @return the <tt>BrowserLauncherService</tt> obtained from the bundle
* context
*/
public static BrowserLauncherService getBrowserLauncher()
{
if (browserLauncherService == null)
{
browserLauncherService
= (BrowserLauncherService) bundleContext.getService(
bundleContext.getServiceReference(
BrowserLauncherService.class.getName()));
}
return browserLauncherService;
}
/**
* Returns the service giving access to resources.
* @return the service giving access to resources
*/
public static ResourceManagementService getResources()
{
if (resourcesService == null)
resourcesService = ResourceManagementServiceUtils
.getService(Sip2SipAccRegWizzActivator.bundleContext);
return resourcesService;
}
}
| [
"alexei.fedotov@917aa43a-1baf-11df-844d-27937797d2d2"
] | alexei.fedotov@917aa43a-1baf-11df-844d-27937797d2d2 |
9956b806ed9944b66abe8cbcec4fe450b3d1ce94 | c53d2df47f3092851bd43bf3c7a0298c620887c2 | /src/main/java/io/quezone/registration/config/audit/AuditEventConverter.java | 31c0598d00da332d86c0db49698c422cebb12e5d | [] | no_license | vunguyenthe/RegistrationService | 3df24e38c8589159e21d7960524d1c7641c0a3e6 | 4c704a68ae13841aadce40cb2fc8b372761bd0d9 | refs/heads/master | 2020-03-28T00:12:41.037559 | 2018-09-04T17:47:26 | 2018-09-04T17:47:26 | 147,385,340 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,209 | java | package io.quezone.registration.config.audit;
import io.quezone.registration.domain.PersistentAuditEvent;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import java.util.*;
@Component
public class AuditEventConverter {
/**
* Convert a list of PersistentAuditEvent to a list of AuditEvent
*
* @param persistentAuditEvents the list to convert
* @return the converted list.
*/
public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
if (persistentAuditEvents == null) {
return Collections.emptyList();
}
List<AuditEvent> auditEvents = new ArrayList<>();
for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
auditEvents.add(convertToAuditEvent(persistentAuditEvent));
}
return auditEvents;
}
/**
* Convert a PersistentAuditEvent to an AuditEvent
*
* @param persistentAuditEvent the event to convert
* @return the converted list.
*/
public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) {
if (persistentAuditEvent == null) {
return null;
}
return new AuditEvent(persistentAuditEvent.getAuditEventDate(), persistentAuditEvent.getPrincipal(),
persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
}
/**
* Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
*
* @param data the data to convert
* @return a map of String, Object
*/
public Map<String, Object> convertDataToObjects(Map<String, String> data) {
Map<String, Object> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
results.put(entry.getKey(), entry.getValue());
}
}
return results;
}
/**
* Internal conversion. This method will allow to save additional data.
* By default, it will save the object as string
*
* @param data the data to convert
* @return a map of String, String
*/
public Map<String, String> convertDataToStrings(Map<String, Object> data) {
Map<String, String> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
// Extract the data that will be saved.
if (entry.getValue() instanceof WebAuthenticationDetails) {
WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue();
results.put("remoteAddress", authenticationDetails.getRemoteAddress());
results.put("sessionId", authenticationDetails.getSessionId());
} else {
results.put(entry.getKey(), Objects.toString(entry.getValue()));
}
}
}
return results;
}
}
| [
"jhipster-bot@jhipster.tech"
] | jhipster-bot@jhipster.tech |
0b0d97e28a9cc6d346d2eff59f81e35dfc21bb68 | 48e835e6f176a8ac9ae3ca718e8922891f1e5a18 | /benchmark/training/org/springsource/loaded/test/IncrementalTypeDescriptorTests.java | b7e006f4c0ab0de3fd74cb25a34496f896ccfbb7 | [] | no_license | STAMP-project/dspot-experiments | f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5 | 121487e65cdce6988081b67f21bbc6731354a47f | refs/heads/master | 2023-02-07T14:40:12.919811 | 2019-11-06T07:17:09 | 2019-11-06T07:17:09 | 75,710,758 | 14 | 19 | null | 2023-01-26T23:57:41 | 2016-12-06T08:27:42 | null | UTF-8 | Java | false | false | 6,435 | java | /**
* Copyright 2010-2012 VMware and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springsource.loaded.test;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.springsource.loaded.ClassRenamer;
import org.springsource.loaded.IncrementalTypeDescriptor;
import org.springsource.loaded.MethodMember;
import org.springsource.loaded.TypeDescriptor;
import org.springsource.loaded.TypeRegistry;
/**
* Tests for TypeDescriptor usage.
*
* @author Andy Clement
* @since 1.0
*/
/**
*
*
* @author Andy Clement
*/
public class IncrementalTypeDescriptorTests extends SpringLoadedTests {
/**
* Test comparison of two simple classes.
*/
@Test
public void simpleExtractor() {
TypeRegistry registry = getTypeRegistry("");
byte[] bytes = loadBytesForClass("data.SimpleClass");
TypeDescriptor typeDescriptor = extract(bytes, true);
byte[] bytes2 = ClassRenamer.rename("data.SimpleClass", loadBytesForClass("data.SimpleClass002"));
TypeDescriptor typeDescriptor2 = extract(bytes2, true);
IncrementalTypeDescriptor itd = new IncrementalTypeDescriptor(typeDescriptor);
itd.setLatestTypeDescriptor(typeDescriptor2);
List<MethodMember> newMethods = itd.getNewOrChangedMethods();
Assert.assertEquals(1, newMethods.size());
Assert.assertEquals("0x1 bar()Ljava/lang/String;", newMethods.get(0).toString());
List<MethodMember> deletedMethods = itd.getDeletedMethods();
Assert.assertEquals(1, deletedMethods.size());
Assert.assertEquals("0x1 foo()V", deletedMethods.get(0).toString());
}
// @Test
// public void newversionDescriptor() {
// byte[] classBytes = loadBytesForClass("data.SimpleClassFour");
// TypeDescriptor td = TypeDescriptorExtractor.extractFor(classBytes);
//
// byte[] classBytes2 = retrieveRename("data.SimpleClassFour", "data.SimpleClassFour002");
// TypeDescriptor td2 = TypeDescriptorExtractor.extractFor(classBytes2);
//
// IncrementalTypeDescriptor nvtd = new IncrementalTypeDescriptor(td);
// nvtd.setLatestTypeDescriptor(td2);
//
// // Now ask it questions about the changes
// List<MethodMember> ms = nvtd.getNewOrChangedMethods();
// Assert.assertEquals(2, ms.size());
//
// MethodMember rm = grabFrom(ms, "extraOne");
// Assert.assertNotNull(rm);
// Assert.assertEquals("0x1 extraOne(Ljava/lang/String;)V", rm.toString());
//
// rm = grabFrom(ms, "extraTwo");
// Assert.assertNotNull(rm);
// Assert.assertEquals("0x9 extraTwo(I)Ljava/lang/Double;", rm.toString());
// //
// // boolean b = nvtd.defines(false, "extraOne", "(Ljava/lang/String;)V");
// // Assert.assertTrue(b);
// //
// // b = nvtd.defines(true, "extraOne", "(Ljava/lang/String;)V");
// // Assert.assertFalse(b);
// }
// regular method deleted
@Test
public void deletedMethods() throws Exception {
TypeRegistry registry = getTypeRegistry("");
byte[] bytes = loadBytesForClass("typedescriptor.A");
TypeDescriptor typeDescriptor = extract(bytes, true);
byte[] bytes2 = ClassRenamer.rename("typedescriptor.A", loadBytesForClass("typedescriptor.A2"));
TypeDescriptor typeDescriptor2 = extract(bytes2, true);
IncrementalTypeDescriptor itd = new IncrementalTypeDescriptor(typeDescriptor);
itd.setLatestTypeDescriptor(typeDescriptor2);
Assert.assertEquals(1, itd.getDeletedMethods().size());
Assert.assertEquals("0x1 m()V", itd.getDeletedMethods().get(0).toString());
}
// overridden (caught) method deleted
@Test
public void deletedMethods2() throws Exception {
TypeRegistry registry = getTypeRegistry("");
byte[] bytes = loadBytesForClass("typedescriptor.B");
TypeDescriptor typeDescriptor = extract(bytes, true);
byte[] bytes2 = ClassRenamer.rename("typedescriptor.B", loadBytesForClass("typedescriptor.B2"));
TypeDescriptor typeDescriptor2 = extract(bytes2, true);
IncrementalTypeDescriptor itd = new IncrementalTypeDescriptor(typeDescriptor);
itd.setLatestTypeDescriptor(typeDescriptor2);
List<MethodMember> deleted = itd.getDeletedMethods();
System.out.println(deleted);
Assert.assertEquals(1, deleted.size());
Assert.assertEquals("0x1 m()V", deleted.get(0).toString());
}
// More subtle changes (modifier flags)
@Test
public void changedModifiers() throws Exception {
TypeRegistry registry = getTypeRegistry("");
byte[] bytes = loadBytesForClass("typedescriptor.C");
TypeDescriptor typeDescriptor = extract(bytes, true);
byte[] bytes2 = ClassRenamer.rename("typedescriptor.C", loadBytesForClass("typedescriptor.C2"));
TypeDescriptor typeDescriptor2 = extract(bytes2, true);
IncrementalTypeDescriptor itd = new IncrementalTypeDescriptor(typeDescriptor);
itd.setLatestTypeDescriptor(typeDescriptor2);
System.out.println(itd.toString(true));
List<MethodMember> changed = itd.getNewOrChangedMethods();
MethodMember m = getMethod(changed, "staticMethod");
Assert.assertTrue(IncrementalTypeDescriptor.isNowNonStatic(m));
m = getMethod(changed, "instanceMethod");
Assert.assertTrue(IncrementalTypeDescriptor.isNowStatic(m));
m = getMethod(changed, "publicMethod1");
Assert.assertTrue(IncrementalTypeDescriptor.hasVisibilityChanged(m));
// TODO Not detected as protected methods always made public in reloadable types... is that OK?
// m = getMethod(changed, "publicMethod2");
// Assert.assertTrue(IncrementalTypeDescriptor.hasVisibilityChanged(m));
m = getMethod(changed, "publicMethod3");
Assert.assertTrue(IncrementalTypeDescriptor.hasVisibilityChanged(m));
}
}
| [
"benjamin.danglot@inria.fr"
] | benjamin.danglot@inria.fr |
72c517d72823435025fee32fe3d672fb4bb3bb00 | e86af6202bf90ef58c7ce429521c65fee8c3aa28 | /app/src/main/java/com/ehc/rovnostandroid/app/AppConstants.java | 5e6d7e889e91423e47143e110d43f34d07eb40ff | [] | no_license | sathishravula/RovnostAndroid | d057d04ae6389341c420659b14982702591d6ae5 | 073cf690ecd40f488ce5e85f90a1574652bc36cf | refs/heads/master | 2021-01-10T04:03:22.881986 | 2016-02-25T08:10:38 | 2016-02-25T08:10:38 | 51,909,557 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,057 | java | package com.ehc.rovnostandroid.app;
import android.os.Environment;
public class AppConstants {
// public static final String BASE_URL = "http://162.243.185.88/rems_new/";
public static final String BASE_URL = "http://162.243.185.88/";
public static final String WEBSERVICE_BASE_URL = "http://162.243.185.88/webservices";
public static final String BASIC_PROFILE = "profile";
public static final String COMPANY_DETAILS = "company_details";
public static final String BUILDER_DETAILS = "builder_details";
public static final String AUTH_KEY = "auth_key";
public static final String USER_ID = "user_id";
public static final String TRANSPARENT = "transparent";
public static final String OPAQUE = "opaque";
public static final String OVERRIDDEN = "override";
public static final String CUSTOMER = "customer";
public static final String LOGO = "logo";
public static final String USER_NAME = "user_name";
public static final String LOGIN_STATUS = "login_status";
public static final String USER_ROLE_ID = "user_role_id";
public static final String COMPANY_ID = "company_id";
public static final String REMS_APP = "REMS_app";
public static final String SUCCESS = "1";
public static final String LOADING = "Loading...";
public static final String SCHEDULE_PANEL = "schedule_panel";
public static final String ACTIVE = "Active";
public static final String IN_ACTIVE = "InActive";
public static final String EMAIL = "email";
public static final String AUTHENTICATING = "Authenticating...";
public static final String PROJECT = "project";
public static final String ERROR = "Error";
public static final String PROJECT_DETAILS = "project_details";
public static final String EDIT_PLAN_SYNC_STATUS = "edit_plan_sync_status";
public static final String BUILDER = "builder";
public static final String PDF_PATH = Environment
.getExternalStorageDirectory().getPath() + "/REMS/PDF";
public static final String IMAGES_PATH = Environment
.getExternalStorageDirectory().getPath() + "/REMS/IMAGES";
}
| [
"sathish@eggheadcreative.com"
] | sathish@eggheadcreative.com |
0a42d017a2ec77c84a88f1ffbb3216e03f833468 | 5f523ed0aceef25bc307ca24befa41f33a785957 | /app/src/main/java/edu/miracostacollege/cs134/sandiegomusicevents/model/MusicEvent.java | e8c8e99a1fe9eeb5f950f932609d27871b7304a1 | [] | no_license | JoshShor/SanDiegoMusicEvents | 490c487fac9627b5752122c217a5c6050c97e837 | 7df3f64c73d6b7ba114a397fe32a1903d7b4439c | refs/heads/master | 2023-03-08T20:28:51.935049 | 2019-02-19T23:21:55 | 2019-02-19T23:21:55 | 171,565,996 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,773 | java | package edu.miracostacollege.cs134.sandiegomusicevents.model;
/**
* The MusicEvent class is a place holder for data corresponding to music events
* occurring within San Diego County. Currently, two arrays contain the data: one array
* stores the titles of each upcoming music event, while the other maintains the details
* about the event.
*
* @author Alexis Miles
* @version 2.0
*/
public class MusicEvent {
//Every instance variable in Java class should mimic the JSON file
private String mArtist;
private String mDate;
private String mDay;
private String mTime;
private String mVenue;
private String mCity;
private String mState;
private String mImageName;
public String getArtist() {
return mArtist;
}
public String getDate() {
return mDate;
}
public String getDay() {
return mDay;
}
public String getTime() {
return mTime;
}
public String getVenue() {
return mVenue;
}
public String getCity() {
return mCity;
}
public String getState() {
return mState;
}
public String getImageName() {
return mImageName;
}
public void setArtist(String artist) {
mArtist = artist;
}
public void setDate(String date) {
mDate = date;
}
public void setDay(String day) {
mDay = day;
}
public void setTime(String time) {
mTime = time;
}
public void setVenue(String venue) {
mVenue = venue;
}
public void setCity(String city) {
mCity = city;
}
public void setState(String state) {
mState = state;
}
public void setImageName(String imageName) {
mImageName = imageName;
}
}
| [
"jtshor@gmail.com"
] | jtshor@gmail.com |
d5259a4f011ff764f2f7f205898c03caea00c315 | be25b2c018dbacd8147a8fbfbc66f257b050ea1f | /workbench/source_gen/jetbrains/mps/ide/actions/ShowModuleDependencyLoop_Action.java | 5f099811fad82131f769bbca0d143add710d884c | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | blutkind/MPS | f5bef8c27c3cb65940ba74a5d1942fdab35ee096 | cac72cce91d98dec40bbadf7a049ed9dbbc18231 | refs/heads/master | 2020-04-08T01:22:10.782234 | 2011-12-09T20:58:07 | 2011-12-09T20:58:07 | 2,950,220 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,352 | java | package jetbrains.mps.ide.actions;
/*Generated by MPS */
import jetbrains.mps.plugins.pluginparts.actions.GeneratedAction;
import javax.swing.Icon;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.intellij.openapi.actionSystem.AnActionEvent;
import java.util.Map;
import javax.swing.tree.TreeNode;
import jetbrains.mps.internal.collections.runtime.MapSequence;
import jetbrains.mps.ide.depanalyzer.ModuleDependencyNode;
import org.jetbrains.annotations.NotNull;
import jetbrains.mps.workbench.MPSDataKeys;
import com.intellij.openapi.project.Project;
import jetbrains.mps.plugins.projectplugins.ProjectPluginManager;
public class ShowModuleDependencyLoop_Action extends GeneratedAction {
private static final Icon ICON = null;
protected static Log log = LogFactory.getLog(ShowModuleDependencyLoop_Action.class);
public ShowModuleDependencyLoop_Action() {
super("Show Cycle Paths", "Show All Cycle Paths for Selected Module", ICON);
this.setIsAlwaysVisible(false);
this.setExecuteOutsideCommand(false);
}
public boolean isApplicable(AnActionEvent event, final Map<String, Object> _params) {
return check_mdxcvg_a0a0((as_hir9am_a0a0a0a(((TreeNode) MapSequence.fromMap(_params).get("treenode")), ModuleDependencyNode.class)));
}
public void doUpdate(@NotNull AnActionEvent event, final Map<String, Object> _params) {
try {
{
boolean enabled = this.isApplicable(event, _params);
this.setEnabledState(event.getPresentation(), enabled);
}
} catch (Throwable t) {
if (log.isErrorEnabled()) {
log.error("User's action doUpdate method failed. Action:" + "ShowModuleDependencyLoop", t);
}
this.disable(event.getPresentation());
}
}
protected boolean collectActionData(AnActionEvent event, final Map<String, Object> _params) {
if (!(super.collectActionData(event, _params))) {
return false;
}
MapSequence.fromMap(_params).put("project", event.getData(MPSDataKeys.PROJECT));
if (MapSequence.fromMap(_params).get("project") == null) {
return false;
}
MapSequence.fromMap(_params).put("treenode", event.getData(MPSDataKeys.LOGICAL_VIEW_NODE));
if (MapSequence.fromMap(_params).get("treenode") == null) {
return false;
}
return true;
}
public void doExecute(@NotNull final AnActionEvent event, final Map<String, Object> _params) {
try {
((Project) MapSequence.fromMap(_params).get("project")).getComponent(ProjectPluginManager.class).getTool(ModuleDependenies_Tool.class).ShowLoops(as_hir9am_a0a0a0a0d(((TreeNode) MapSequence.fromMap(_params).get("treenode")), ModuleDependencyNode.class));
} catch (Throwable t) {
if (log.isErrorEnabled()) {
log.error("User's action execute method failed. Action:" + "ShowModuleDependencyLoop", t);
}
}
}
private static boolean check_mdxcvg_a0a0(ModuleDependencyNode checkedDotOperand) {
if (null != checkedDotOperand) {
return checkedDotOperand.isCyclic();
}
return false;
}
private static <T> T as_hir9am_a0a0a0a(Object o, Class<T> type) {
return (type.isInstance(o) ?
(T) o :
null
);
}
private static <T> T as_hir9am_a0a0a0a0d(Object o, Class<T> type) {
return (type.isInstance(o) ?
(T) o :
null
);
}
}
| [
"Michael.Vlassiev@jetbrains.com"
] | Michael.Vlassiev@jetbrains.com |
f1e92d8e6578d1a1ad318c7fd2fb2360dd24c1fd | c2b23ef23b9fa83d352d8b27bcad26352228f573 | /src/main/java/com/itluobo/wordtool/web/filter/CORSFilter.java | 808566757e2a140a83d0120475bcca491d10e08f | [] | no_license | kenvifire/wordparser | 0643f9b0139e106c467f24d6e230d4ea4cdb691e | ac106cd4c7f11013bdd8b4349dd3c1ecf9525f60 | refs/heads/master | 2021-01-15T15:33:44.600303 | 2016-10-10T11:17:16 | 2016-10-10T11:17:16 | 54,709,759 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,230 | java | package com.itluobo.wordtool.web.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by kenvi on 16/10/10.
*/
@Component
public class CORSFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
String origin = (String) servletRequest.getRemoteHost()+":"+servletRequest.getRemotePort();
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Credentials","true");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
| [
"kenvi.zhu@dianping.com"
] | kenvi.zhu@dianping.com |
7d9c0224a8d9a623b5955b3926ac396513406983 | 4ae320c45dbe8380746e63ab765086a1f4ead5da | /spring_mybatis_four_way/src/main/java/edu/bit/ex/board3/BService3.java | 14c911127e6219249a796684d20208a663f2f94c | [] | no_license | parkhyesu/spring | 352e08ab2b7612221dd01d318344afa5ec738e16 | cbc06b4f8771c38c1877fc986b5256779300d488 | refs/heads/master | 2022-12-26T09:28:51.299071 | 2020-02-12T03:50:19 | 2020-02-12T03:50:19 | 239,920,080 | 0 | 0 | null | 2022-12-16T06:45:37 | 2020-02-12T03:38:22 | HTML | UHC | Java | false | false | 335 | java | package edu.bit.ex.board3;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
//이건 객체 생성 new
@Service
public class BService3 {
@Inject
BoardMapper boardMapper;
public List<BoardVO> selectBoardList() throws Exception{
return boardMapper.selectBoardList();
}
}
| [
"phs06140@gmail.com"
] | phs06140@gmail.com |
d152e4170c33fad3c41f4d74af588efe1b21ded6 | 34a1d5ff58b7507aa47899634e1ce260960b7391 | /app/src/main/java/com/wdysolutions/notes/Globals/Petty_Cash/Request/PettyCash_request_model.java | e63fe5beaef1354e81846923243ee05ad3d20e87 | [] | no_license | skiedflakes/Notes | 26740f8d59bd6a1c13e920d30bf89a28f67b8a35 | d14a989c16022706b948c652aefabe897a49ff8c | refs/heads/master | 2022-04-07T12:54:46.034864 | 2020-01-28T06:44:58 | 2020-01-28T06:44:58 | 216,951,641 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,112 | java | package com.wdysolutions.notes.Globals.Petty_Cash.Request;
public class PettyCash_request_model {
String id, credit_method_test, count, pcv, date_requested, amount, remarks, date_encoded, created_by, br_id, receipt_status,
receipt_status_color, userID, stats, stats_color, hid, liquidate_stats, liquidate_color, declared_status, declared_status_color,
rfr_status, rfr_status_color, dnr_stat, liquidation_stat, rep_stats, rep_stat, approved_by;
public PettyCash_request_model(String id, String credit_method_test, String count, String pcv, String date_requested, String amount,
String remarks, String date_encoded, String created_by, String br_id, String receipt_status, String receipt_status_color,
String userID, String stats, String stats_color, String hid, String liquidate_stats, String liquidate_color, String declared_status, String declared_status_color,
String rfr_status, String rfr_status_color, String dnr_stat, String liquidation_stat, String rep_stats, String rep_stat, String approved_by){
this.id = id;
this.credit_method_test = credit_method_test;
this.count = count;
this.pcv = pcv;
this.date_requested = date_requested;
this.amount = amount;
this.remarks = remarks;
this.date_encoded = date_encoded;
this.created_by = created_by;
this.br_id = br_id;
this.receipt_status = receipt_status;
this.receipt_status_color = receipt_status_color;
this.userID = userID;
this.stats = stats;
this.stats_color = stats_color;
this.hid = hid;
this.liquidate_stats = liquidate_stats;
this.liquidate_color = liquidate_color;
this.declared_status = declared_status;
this.declared_status_color = declared_status_color;
this.rfr_status = rfr_status;
this.rfr_status_color = rfr_status_color;
this.dnr_stat = dnr_stat;
this.liquidation_stat = liquidation_stat;
this.rep_stats = rep_stats;
this.rep_stat = rep_stat;
this.approved_by = approved_by;
}
public String getRemarks() {
return remarks;
}
public String getDate_requested() {
return date_requested;
}
public String getCreated_by() {
return created_by;
}
public String getAmount() {
return amount;
}
public String getId() {
return id;
}
public String getApproved_by() {
return approved_by;
}
public String getBr_id() {
return br_id;
}
public String getCount() {
return count;
}
public String getCredit_method_test() {
return credit_method_test;
}
public String getDate_encoded() {
return date_encoded;
}
public String getDeclared_status() {
return declared_status;
}
public String getHid() {
return hid;
}
public String getDeclared_status_color() {
return declared_status_color;
}
public String getDnr_stat() {
return dnr_stat;
}
public String getLiquidate_color() {
return liquidate_color;
}
public String getLiquidate_stats() {
return liquidate_stats;
}
public String getPcv() {
return pcv;
}
public String getLiquidation_stat() {
return liquidation_stat;
}
public String getReceipt_status() {
return receipt_status;
}
public String getReceipt_status_color() {
return receipt_status_color;
}
public String getRep_stat() {
return rep_stat;
}
public String getRep_stats() {
return rep_stats;
}
public String getRfr_status() {
return rfr_status;
}
public String getRfr_status_color() {
return rfr_status_color;
}
public String getStats() {
return stats;
}
public String getStats_color() {
return stats_color;
}
public String getUserID() {
return userID;
}
}
| [
"jay@Jays-Mac-mini.local"
] | jay@Jays-Mac-mini.local |
c8188745852f86bde48fa6d26393761e536163e8 | 17e8438486cb3e3073966ca2c14956d3ba9209ea | /dso/tags/3.0.0/code/base/dso-l2/src/com/tc/management/L2Management.java | 651b6141dd3f5f1e58474ff989a0fa33c2fbd0a2 | [] | no_license | sirinath/Terracotta | fedfc2c4f0f06c990f94b8b6c3b9c93293334345 | 00a7662b9cf530dfdb43f2dd821fa559e998c892 | refs/heads/master | 2021-01-23T05:41:52.414211 | 2015-07-02T15:21:54 | 2015-07-02T15:21:54 | 38,613,711 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,254 | java | /*
* All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright
* notice. All rights reserved.
*/
package com.tc.management;
import com.sun.jmx.remote.generic.DefaultConfig;
import com.sun.jmx.remote.generic.ServerSynchroMessageConnection;
import com.sun.jmx.remote.generic.SynchroCallback;
import com.sun.jmx.remote.generic.SynchroMessageConnectionServer;
import com.sun.jmx.remote.generic.SynchroMessageConnectionServerImpl;
import com.sun.jmx.remote.socket.SocketConnectionServer;
import com.tc.async.api.Sink;
import com.tc.config.schema.setup.L2TVSConfigurationSetupManager;
import com.tc.exception.TCRuntimeException;
import com.tc.logging.CustomerLogging;
import com.tc.logging.JMXLogging;
import com.tc.logging.TCLogger;
import com.tc.logging.TCLogging;
import com.tc.management.beans.L2Dumper;
import com.tc.management.beans.L2MBeanNames;
import com.tc.management.beans.LockStatisticsMonitorMBean;
import com.tc.management.beans.TCDumper;
import com.tc.management.beans.TCServerInfoMBean;
import com.tc.management.beans.object.ObjectManagementMonitor;
import com.tc.management.beans.object.ServerDBBackup;
import com.tc.net.protocol.tcm.ChannelID;
import com.tc.statistics.StatisticsAgentSubSystemImpl;
import com.tc.statistics.beans.StatisticsMBeanNames;
import com.tc.statistics.beans.impl.StatisticsGatewayMBeanImpl;
import com.tc.util.concurrent.TCExceptionResultException;
import com.tc.util.concurrent.TCFuture;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.rmi.server.RMISocketFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.generic.GenericConnectorServer;
import javax.management.remote.generic.MessageConnectionServer;
import javax.management.remote.message.MBeanServerRequestMessage;
import javax.management.remote.message.Message;
import javax.management.remote.rmi.RMIConnectorServer;
import javax.management.remote.rmi.RMIJRMPServerImpl;
import javax.security.auth.Subject;
public class L2Management extends TerracottaManagement {
private static final TCLogger logger = TCLogging.getLogger(L2Management.class);
private MBeanServer mBeanServer;
private JMXConnectorServer jmxConnectorServer;
private final L2TVSConfigurationSetupManager configurationSetupManager;
private final TCServerInfoMBean tcServerInfo;
private final TCDumper tcDumper;
private final ObjectManagementMonitor objectManagementBean;
private final LockStatisticsMonitorMBean lockStatistics;
private final StatisticsAgentSubSystemImpl statisticsAgentSubSystem;
private final StatisticsGatewayMBeanImpl statisticsGateway;
private static final Map rmiRegistryMap = new HashMap();
private final int jmxPort;
private final InetAddress bindAddress;
private final ServerDBBackup serverDbBackupBean;
private final Sink remoteEventsSink;
public L2Management(TCServerInfoMBean tcServerInfo, LockStatisticsMonitorMBean lockStatistics,
StatisticsAgentSubSystemImpl statisticsAgentSubSystem,
StatisticsGatewayMBeanImpl statisticsGateway,
L2TVSConfigurationSetupManager configurationSetupManager, TCDumper tcDumper,
InetAddress bindAddr, int port, Sink remoteEventsSink) throws MBeanRegistrationException,
NotCompliantMBeanException, InstanceAlreadyExistsException {
this.tcServerInfo = tcServerInfo;
this.lockStatistics = lockStatistics;
this.configurationSetupManager = configurationSetupManager;
this.statisticsAgentSubSystem = statisticsAgentSubSystem;
this.statisticsGateway = statisticsGateway;
this.tcDumper = tcDumper;
this.bindAddress = bindAddr;
this.jmxPort = port;
this.remoteEventsSink = remoteEventsSink;
try {
objectManagementBean = new ObjectManagementMonitor();
} catch (NotCompliantMBeanException ncmbe) {
throw new TCRuntimeException(
"Unable to construct one of the L2 MBeans: this is a programming error in one of those beans",
ncmbe);
}
try {
serverDbBackupBean = new ServerDBBackup(configurationSetupManager);
} catch (NotCompliantMBeanException ncmbe) {
throw new TCRuntimeException(
"Unable to construct one of the L2 MBeans: this is a programming error in one of those beans",
ncmbe);
}
// LKC-2990 and LKC-3171: Remove the JMX generic optional logging
java.util.logging.Logger jmxLogger = java.util.logging.Logger.getLogger("javax.management.remote.generic");
jmxLogger.setLevel(java.util.logging.Level.OFF);
// DEV-1304: ClientCommunicatorAdmin uses a different logger
jmxLogger = java.util.logging.Logger.getLogger("javax.management.remote.misc");
jmxLogger.setLevel(java.util.logging.Level.OFF);
final List jmxServers = MBeanServerFactory.findMBeanServer(null);
if (jmxServers != null && !jmxServers.isEmpty()) {
mBeanServer = (MBeanServer) jmxServers.get(0);
} else {
mBeanServer = MBeanServerFactory.createMBeanServer();
}
registerMBeans();
statisticsGateway.addStatisticsAgent(ChannelID.NULL_ID, mBeanServer);
}
/**
* Keep track of RMI Registries by jmxPort. In 1.5 and forward you can create multiple RMI Registries in a single VM.
*/
private static Registry getRMIRegistry(int jmxPort, RMIClientSocketFactory csf, RMIServerSocketFactory ssf)
throws RemoteException {
Integer key = new Integer(jmxPort);
Registry registry = (Registry) rmiRegistryMap.get(key);
if (registry == null) {
rmiRegistryMap.put(key, registry = LocateRegistry.createRegistry(jmxPort, csf, ssf));
}
return registry;
}
// DEV-1060
private static class BindAddrSocketFactory extends RMISocketFactory implements Serializable {
private final InetAddress bindAddr;
public BindAddrSocketFactory() {
this(null);
}
public BindAddrSocketFactory(InetAddress bindAddress) {
this.bindAddr = bindAddress;
}
@Override
public ServerSocket createServerSocket(int port) throws IOException {
return new ServerSocket(port, 0, this.bindAddr);
}
@Override
public Socket createSocket(String dummy, int port) throws IOException {
return new Socket(bindAddr, port);
}
@Override
public int hashCode() {
return bindAddr.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj == null || getClass() != obj.getClass()) { return false; }
BindAddrSocketFactory other = (BindAddrSocketFactory) obj;
return bindAddr.equals(other.bindAddr);
}
}
public synchronized void start() throws Exception {
JMXServiceURL url;
Map env = new HashMap();
String authMsg = "Authentication OFF";
String credentialsMsg = "";
env.put("jmx.remote.x.server.connection.timeout", new Long(Long.MAX_VALUE));
env.put("jmx.remote.server.address.wildcard", "false");
if (configurationSetupManager.commonl2Config().authentication()) {
String pwd = configurationSetupManager.commonl2Config().authenticationPasswordFile();
String access = configurationSetupManager.commonl2Config().authenticationAccessFile();
if (!new File(pwd).exists()) CustomerLogging.getConsoleLogger().error("Password file does not exist: " + pwd);
if (!new File(access).exists()) CustomerLogging.getConsoleLogger().error("Access file does not exist: " + access);
env.put("jmx.remote.x.password.file", pwd);
env.put("jmx.remote.x.access.file", access);
authMsg = "Authentication ON";
credentialsMsg = "Credentials: " + configurationSetupManager.commonl2Config().authenticationPasswordFile() + " "
+ configurationSetupManager.commonl2Config().authenticationAccessFile();
url = new JMXServiceURL("service:jmx:rmi://");
RMISocketFactory socketFactory = new BindAddrSocketFactory(bindAddress);
RMIClientSocketFactory csf = bindAddress.isAnyLocalAddress() ? null : socketFactory;
RMIServerSocketFactory ssf = socketFactory;
RMIJRMPServerImpl server = new RMIJRMPServerImpl(jmxPort, csf, ssf, env);
jmxConnectorServer = new RMIConnectorServer(url, env, server, mBeanServer);
jmxConnectorServer.start();
getRMIRegistry(jmxPort, csf, ssf).bind("jmxrmi", server);
String urlHost = bindAddress.getHostAddress();
CustomerLogging.getConsoleLogger().info(
"JMX Server started. " + authMsg + " - Available at URL["
+ "Service:jmx:rmi:///jndi/rmi://" + urlHost + ":" + jmxPort
+ "/jmxrmi" + "]");
if (!credentialsMsg.equals("")) CustomerLogging.getConsoleLogger().info(credentialsMsg);
} else {
// DEV-1060
url = new JMXServiceURL("jmxmp", bindAddress.getHostAddress(), jmxPort);
MessageConnectionServer msgConnectionServer = new SocketConnectionServer(url, env);
// We use our own connection server classes here so that we can intervene when remote jmx requests come in.
// Specifically we take every request and instead of processing it directly in the JMX thread, we pass the request
// off to a thread pool. The whole point of doing is that the JMX runtime likes to use Thread.interrupt() which we
// don't want happening in our code. Pushing the requests into our own threads provides isolation from these
// interrupts (see DEV-1955)
SynchroMessageConnectionServer synchroMessageConnectionServer = new TCSynchroMessageConnectionServer(
remoteEventsSink,
msgConnectionServer,
env);
env.put(DefaultConfig.SYNCHRO_MESSAGE_CONNECTION_SERVER, synchroMessageConnectionServer);
jmxConnectorServer = new GenericConnectorServer(env, mBeanServer);
jmxConnectorServer.start();
CustomerLogging.getConsoleLogger().info("JMX Server started. Available at URL[" + url + "]");
}
}
public synchronized void stop() throws IOException, InstanceNotFoundException, MBeanRegistrationException {
unregisterMBeans();
if (jmxConnectorServer != null) {
jmxConnectorServer.stop();
}
}
@Override
public Object findMBean(ObjectName objectName, Class mBeanInterface) throws IOException {
return findMBean(objectName, mBeanInterface, mBeanServer);
}
public MBeanServer getMBeanServer() {
return mBeanServer;
}
public JMXConnectorServer getJMXConnServer() {
return jmxConnectorServer;
}
public ObjectManagementMonitor findObjectManagementMonitorMBean() {
return objectManagementBean;
}
public ServerDBBackup findServerDbBackupMBean() {
return serverDbBackupBean;
}
private void registerMBeans() throws MBeanRegistrationException, NotCompliantMBeanException,
InstanceAlreadyExistsException {
mBeanServer.registerMBean(tcServerInfo, L2MBeanNames.TC_SERVER_INFO);
mBeanServer.registerMBean(JMXLogging.getJMXAppender().getMBean(), L2MBeanNames.LOGGER);
mBeanServer.registerMBean(objectManagementBean, L2MBeanNames.OBJECT_MANAGEMENT);
mBeanServer.registerMBean(serverDbBackupBean, L2MBeanNames.SERVER_DB_BACKUP);
mBeanServer.registerMBean(lockStatistics, L2MBeanNames.LOCK_STATISTICS);
if (statisticsAgentSubSystem.isActive()) {
statisticsAgentSubSystem.registerMBeans(mBeanServer);
}
mBeanServer.registerMBean(statisticsGateway, StatisticsMBeanNames.STATISTICS_GATEWAY);
mBeanServer.registerMBean(new L2Dumper(tcDumper, mBeanServer), L2MBeanNames.DUMPER);
}
private void unregisterMBeans() throws InstanceNotFoundException, MBeanRegistrationException {
mBeanServer.unregisterMBean(L2MBeanNames.TC_SERVER_INFO);
mBeanServer.unregisterMBean(L2MBeanNames.LOGGER);
mBeanServer.unregisterMBean(L2MBeanNames.OBJECT_MANAGEMENT);
mBeanServer.unregisterMBean(L2MBeanNames.LOCK_STATISTICS);
mBeanServer.unregisterMBean(L2MBeanNames.SERVER_DB_BACKUP);
if (statisticsAgentSubSystem.isActive()) {
statisticsAgentSubSystem.unregisterMBeans(mBeanServer);
}
mBeanServer.unregisterMBean(StatisticsMBeanNames.STATISTICS_GATEWAY);
mBeanServer.unregisterMBean(L2MBeanNames.DUMPER);
}
public static class TCSynchroMessageConnectionServer extends SynchroMessageConnectionServerImpl {
private final Sink remoteEventsSink;
public TCSynchroMessageConnectionServer(Sink remoteEventsSink, MessageConnectionServer msServer, Map env) {
super(msServer, env);
this.remoteEventsSink = remoteEventsSink;
}
@Override
public ServerSynchroMessageConnection accept() throws IOException {
return new ServerSynchroMessageConnectionWrapper(remoteEventsSink, super.accept());
}
}
private static class ServerSynchroMessageConnectionWrapper implements ServerSynchroMessageConnection {
private final ServerSynchroMessageConnection conn;
private final Sink queue;
public ServerSynchroMessageConnectionWrapper(Sink queue, ServerSynchroMessageConnection conn) {
this.queue = queue;
this.conn = conn;
}
public void close() throws IOException {
conn.close();
}
public void connect(Map env) throws IOException {
conn.connect(env);
}
public String getConnectionId() {
return conn.getConnectionId();
}
public Subject getSubject() {
return conn.getSubject();
}
public void sendOneWay(Message msg) throws IOException, UnsupportedOperationException {
conn.sendOneWay(msg);
}
public void setCallback(SynchroCallback cb) {
conn.setCallback(new SynchroCallbackWrapper(queue, cb));
}
}
private static class SynchroCallbackWrapper implements SynchroCallback {
private final SynchroCallback callback;
private final Sink remoteEventsSink;
public SynchroCallbackWrapper(Sink remoteEventsSink, SynchroCallback cb) {
this.remoteEventsSink = remoteEventsSink;
this.callback = cb;
}
public void connectionException(Exception ie) {
callback.connectionException(ie);
}
public Message execute(Message request) {
if (request instanceof MBeanServerRequestMessage) {
TCFuture future = new TCFuture();
remoteEventsSink.add(new CallbackExecuteContext(Thread.currentThread().getContextClassLoader(), callback,
request, future));
try {
return (Message) future.get();
} catch (InterruptedException e) {
logger.debug("remote JMX call interrupted");
return null;
} catch (TCExceptionResultException e) {
throw new RuntimeException(e.getCause());
}
}
return callback.execute(request);
}
}
}
| [
"foshea@7fc7bbf3-cf45-46d4-be06-341739edd864"
] | foshea@7fc7bbf3-cf45-46d4-be06-341739edd864 |
40c36b0c510d72db2332c11e85854a3dbd921332 | 82864dd67c588beed55897828ce4b500a75a0017 | /de4a-connector/src/main/java/eu/de4a/connector/model/RequestorRequest.java | a50adfcfc32163fa391e548f859b140f8b73b444 | [] | no_license | imrvo/de4a | 52c8eb59dd2b5172304b59da20b4407b411aa685 | 21b6da2d17a324b4002cbd8b684e464c78c99daf | refs/heads/master | 2023-04-09T18:39:24.280026 | 2021-04-16T11:26:46 | 2021-04-16T11:26:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,603 | java | package eu.de4a.connector.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = "requestor_request")
@XmlRootElement
public class RequestorRequest {
@Id
private String idrequest;
private String evidenceServiceUri;
private String returnServiceUri;
private String dataOwnerId;
private String canonicalEvidenceTypeId;
private String senderId;
private boolean done;
public String getIdrequest() {
return idrequest;
}
public void setIdrequest(String idrequest) {
this.idrequest = idrequest;
}
public String getEvidenceServiceUri() {
return evidenceServiceUri;
}
public void setEvidenceServiceUri(String evidenceServiceUri) {
this.evidenceServiceUri = evidenceServiceUri;
}
public String getReturnServiceUri() {
return returnServiceUri;
}
public void setReturnServiceUri(String returnServiceUri) {
this.returnServiceUri = returnServiceUri;
}
public String getDataOwnerId() {
return dataOwnerId;
}
public void setDataOwnerId(String dataOwnerId) {
this.dataOwnerId = dataOwnerId;
}
public String getCanonicalEvidenceTypeId() {
return canonicalEvidenceTypeId;
}
public void setCanonicalEvidenceTypeId(String canonicalEvidenceTypeId) {
this.canonicalEvidenceTypeId = canonicalEvidenceTypeId;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}
| [
"aosunacab@yahoo.com"
] | aosunacab@yahoo.com |
fdb67f5646e6d07246eab981e6a30ffb7780981b | 1997f9b324e35c634d0de5d2566116823e07a021 | /src/java/negocio/bo/LibroBo.java | f19713afb96651cc0f700202487855eca43a39f7 | [] | no_license | enzocr/BibliotecaWeb | 05a8ca00094609f080bfe62ea7ad2b57fddf112a | 904565528408c5dc936dcf38dbe188003bdb73da | refs/heads/master | 2022-09-28T05:50:19.886329 | 2020-06-01T20:37:36 | 2020-06-01T20:37:36 | 264,513,583 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,108 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package negocio.bo;
import datos.LibroDao;
import java.util.List;
import negocio.clases.Libro;
/**
*
* @author enzoq
*/
public class LibroBo {
private LibroDao dao;
public LibroBo() {
this.dao = new LibroDao();
}
public int insert(Libro lb) {
lb.setPrecio(lb.getPrecio() + (lb.getPrecio() * 0.13));
return dao.insert(lb);
}
public List<Libro> getAll() {
return dao.getAllLibros();
}
public LibroDao getDao() {
return dao;
}
public void setDao(LibroDao dao) {
this.dao = dao;
}
public int update(Libro lb) {
return getDao().update(lb);
}
public int delete(Libro lb) {
return getDao().delete(lb);
}
public Libro getById(int codigo) {
return getDao().getById(codigo);
}
public List<Libro> getByName(String text) {
return getDao().getByName(text);
}
}
| [
"equartinoz@ucenfotec.ac.cr"
] | equartinoz@ucenfotec.ac.cr |
e24e56a122ef515d50ba5b49e10c3c996f778e34 | f8c3a6a1c14ad460c6386306cf8174f047a730b8 | /client/src/ui/views/InfoView.java | e7fb4769455eeee8717ae0fe8bac7c7eeba820fe | [] | no_license | lyudmil/unabomber | e3ad1ba9b4d907954e8853f68177bb43e7c692d0 | 03d14ca9818d337c865aaa3d33c263774e061746 | refs/heads/master | 2021-01-17T05:34:30.638452 | 2011-02-01T00:33:58 | 2011-02-01T00:33:58 | 1,024,593 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,176 | java | package ui.views;
import unabomber.client.R;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class InfoView extends ListActivity{
private String[] info = new String[]{"Help", "Credits"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, info));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setFocusable(true);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position){
case 0:
Intent help = new Intent(InfoView.this, HelpView.class );
startActivity(help);
return;
case 1:
Intent credits = new Intent(InfoView.this, CreditsView.class);
startActivity(credits);
return;
}
}
});
}
}
| [
"lyudmil.i.angelov@gmail.com"
] | lyudmil.i.angelov@gmail.com |
60dac2047172e385ee088753b7cfa68b1af0645d | af2ab357131f300a0882f2b3400dc911a8df1566 | /app/src/main/java/com/ings/gogo/homehuiwxapi/view/impl/WelcomeActivityView.java | a6a9204eaf74f1aa7ee1a8385d8190b78dae01e7 | [] | no_license | lijiangyato/HomeHui | f26e2fc080d3262fdff59ec410882b6b53c5be12 | d1040061adf2501a1c42bb2b9c7b8674065da1d9 | refs/heads/master | 2021-08-30T15:08:33.593984 | 2017-12-18T11:35:11 | 2017-12-18T11:35:11 | 110,217,050 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 327 | java | package com.ings.gogo.homehuiwxapi.view.impl;
/*
@公司:贵州家汇互联网科技有限公司
@作者:LiJiang
@邮箱:yaoyaoling8888@gmail.com
@时间: admin 2017/10/7.
@作用:微信支付
*/
import com.ings.gogo.homehuiwxapi.view.IWelcomeActivityView;
public class WelcomeActivityView implements IWelcomeActivityView{
}
| [
"1755036940@qq.com"
] | 1755036940@qq.com |
d0597048030942b98c76494690daf7b25f267a04 | ba26af1bfe70673303f39fb34bf83f5c08ed5905 | /analysis/src/main/java/org/apache/calcite/rex/RexSqlConvertlet.java | 041aa59c853721365027834833b511a3d07859a1 | [
"MIT"
] | permissive | GinPonson/Quicksql | 5a4a6671e87b3278e2d77eee497a4910ac340617 | e31f65fb96ea2f2c373ba3acc43473a48dca10d1 | refs/heads/master | 2020-07-30T06:23:41.805009 | 2019-09-22T08:50:18 | 2019-09-22T08:50:18 | 210,116,844 | 0 | 0 | MIT | 2019-09-22T08:48:23 | 2019-09-22T08:48:23 | null | UTF-8 | Java | false | false | 1,455 | java | /*
* 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.calcite.rex;
import org.apache.calcite.sql.SqlNode;
/**
* Converts a {@link RexNode} expression into a {@link SqlNode} expression.
*/
public interface RexSqlConvertlet {
//~ Methods ----------------------------------------------------------------
/**
* Converts a {@link RexCall} to a {@link SqlNode} expression.
*
* @param converter to use in translating
* @param call RexCall to translate
* @return SqlNode, or null if translation was unavailable
*/
SqlNode convertCall(
RexToSqlNodeConverter converter,
RexCall call);
}
// End RexSqlConvertlet.java
| [
"xushengguo-xy@360.cn"
] | xushengguo-xy@360.cn |
20707c2cb7898a1a10c3d10ec00004081cbe5d8a | 70123d8b25800e4a1743626822eb651c38513cd7 | /web/OfficeSuite/src/java/com/rift/coad/office/client/IconConstants.java | 5225068e1fa296101f9a16e38b935b9250f11f67 | [] | no_license | brettchaldecott/dipforge | bb9205cddaba60d61ab7f65b58c22a058264b698 | ca2fe194156754d142fc48fdb8b963f37aa7c6a3 | refs/heads/master | 2021-03-19T12:14:25.926735 | 2016-01-22T12:06:22 | 2016-01-22T12:06:22 | 1,043,676 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,230 | java | /*
* OfficeSuite: The office suite for coadunation.
* Copyright (C) 2010 2015 Burntjam
*
* 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
*
* IconConstants.java
*/
// package path
package com.rift.coad.office.client;
/**
* This class contants the constants
*
* @author brett chaldecott
*/
public class IconConstants {
/**
* The documents share
*/
public final static String DOCUMENTS = "folder.png";
/**
* The email icon
*/
public final static String EMAIL = "internet-mail.png";
}
| [
"brett.chaldecott@gmail.com"
] | brett.chaldecott@gmail.com |
f3fae2d6ab92f1c81ca13377ab53638e0072a6a1 | 796c3d8c0b2ee3266ca7bbc348d9d7dd05e75cd6 | /e-app-server/src/main/java/de/sb85/eapp/server/api/v1/booking/BookingAnonymRequest.java | 66bd49a40b53811f742f16aa05a67a5894b33fe3 | [
"MIT"
] | permissive | StBrautzsch/e-app | 124a1a923f3cdc0e2e7cb8d333ebcce53aef3928 | 4a65de0c23ede06468ae3d4a553e6d53404c9741 | refs/heads/main | 2023-04-24T14:13:23.411916 | 2021-05-01T09:33:11 | 2021-05-01T09:33:11 | 362,889,359 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 458 | java | package de.sb85.eapp.server.api.v1.booking;
import de.sb85.eapp.server.api.v1.BookingRequest;
public class BookingAnonymRequest extends BookingRequest {
private String name;
private String mail;
private String tel;
BookingAnonymRequest() {
super();
}
public String getName() {
return name;
}
public String getMail() {
return mail;
}
public String getTel() {
return tel;
}
}
| [
"st.brautzsch@gmx.de"
] | st.brautzsch@gmx.de |
0ed173529ff28cd24738eb51811c482c457fc2e3 | bfe555829c44521696bab62ebc5e374698f74cfe | /webapi-sponge/src/main/java/valandur/webapi/serialize/view/data/PoweredDataView.java | 4ed8a3dea80c1349436ac867e386d798f4b7a846 | [
"MIT"
] | permissive | jxsd1234a/Web-API | 464b38a909d2349d7ac1a655d3f93861f3c4334c | 8ec9e41e58b6655adfd1343069dccc3feb1469c4 | refs/heads/master | 2022-11-10T14:53:37.403195 | 2020-07-01T02:51:40 | 2020-07-01T02:51:40 | 267,387,574 | 0 | 0 | MIT | 2020-05-27T17:46:23 | 2020-05-27T17:46:22 | null | UTF-8 | Java | false | false | 446 | java | package valandur.webapi.serialize.view.data;
import com.fasterxml.jackson.annotation.JsonValue;
import org.spongepowered.api.data.manipulator.mutable.block.PoweredData;
import valandur.webapi.serialize.BaseView;
public class PoweredDataView extends BaseView<PoweredData> {
@JsonValue
public boolean powered;
public PoweredDataView(PoweredData value) {
super(value);
this.powered = value.powered().get();
}
}
| [
"inithilian@gmail.com"
] | inithilian@gmail.com |
fc65e12e63920711ff0fa9f543d549296949b2c1 | fbf9e6efabc0bd86a08cd5dddbfd7c4e524f3ac8 | /src/main/java/io/renren/datasources/DataSourceTestService.java | fefb1677250b2ad403e5d3b47e6de0f44e5f64fb | [] | no_license | a287931704/performanceTestSystem | 806df49621a15bf79ed76224bbb23192725f1c1e | aeaf85c65c8e1086f5ea68759635ce4d5edc1b4d | refs/heads/master | 2022-10-20T17:58:14.010778 | 2020-08-11T07:57:07 | 2020-08-11T07:57:07 | 223,900,284 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 735 | java | package io.renren.datasources;
import io.renren.datasources.annotation.DataSource;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 测试
* @author smooth
* @email 287931704@qq.com
* @date 2017/9/16 23:10
*/
@Service
public class DataSourceTestService {
@Autowired
private UserService userService;
public UserEntity queryObject(Long userId){
return userService.queryObject(userId);
}
@DataSource(name = DataSourceNames.SECOND)
public UserEntity queryObject2(Long userId){
return userService.queryObject(userId);
}
}
| [
"287931704@qq.com"
] | 287931704@qq.com |
cf7c64e41522bdc4cc37fd8a6d0afd1ffa2868e3 | 47f94388b58ea23eed63b85e4fc4d9df83618b72 | /src/BuyStock.java | ce155e38b8f97e598337a7be5ec91f9b71ec51b8 | [
"BSD-3-Clause"
] | permissive | shub0/algorithm-data-structure | a61c215f11141080759795daf6d78c5fa2189855 | 8221d10f201d001abcb15b27c9cf4b8cd5060f1f | refs/heads/master | 2021-01-18T11:21:29.509366 | 2017-03-01T07:18:12 | 2017-03-01T07:18:12 | 18,278,451 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,185 | java | /**
*
* BuyStock.java
* Nov 26, 2012
*/
/**
* @author Shubo Liu
* Time and space complexity is O(n)
*/
public class BuyStock {
// limit two transitions
public int maxProfit3(int[] prices){
int len = prices.length;
if (len < 2) return 0;
else{
int[] Profit = new int[len];
int profit = 0;
// assume buy at the beginning of period
int buyPrice = prices[0];
for (int index = 0; index < len; index++){
if (prices[index] > buyPrice){
// if sell stock at index time
// make a comparison
profit = Math.max(profit, prices[index] - buyPrice);
}else{
buyPrice = prices[index];
}
Profit[index] += profit;
}
// assume sell at the end of period
int sellPrice = prices[len - 1];
profit = 0;
Profit[len - 1] += profit;
for (int index = len - 2; index > -1; index --){
if (prices[index] < sellPrice){
// buy stock at index time
profit = Math.max(profit, sellPrice - prices[index]);
}else{
sellPrice = prices[index];
}
Profit[index] += profit;
}
int maxProfit = Profit[0];
for (int index = 1; index < len; index++){
if (Profit[index] > maxProfit)
maxProfit = Profit[index];
}
return maxProfit;
}
}
public int maxProfit2(int[] prices){
boolean share = false;
int buyPrice = prices[0];
int profit = 0;
for(int index = 0; index < prices.length - 1; index ++){
if (prices[index] < prices[index + 1]){
if (!share){
buyPrice = prices[index];
share = true;
}
}else{
if (share){
profit += (prices[index] - buyPrice);
share = false;
}
}
}
if (share) profit += (prices[prices.length - 1] - buyPrice);
return profit;
}
// limit one transition
public int maxProfit(int[] prices){
int buyPrice = prices[0];
int profit = 0;
for (int index = 0; index < prices.length; index ++){
if (prices[index] < buyPrice) buyPrice = prices[index];
else{
profit = Math.max(profit, prices[index] - buyPrice);
}
}
return profit;
}
public static void main(String[] args){
int[] prices = {5,4,3,6,8,10,9,15};
BuyStock myTest = new BuyStock();
System.out.println(myTest.maxProfit2(prices));
}
}
| [
"shubo@adap.tv"
] | shubo@adap.tv |
930e3dedd9738916b47fe26f8297acc7de72f249 | 0f0603535d370ee0377a27f04f2735a4e305e88f | /HackerRank_Questions/SubarrayWithLargestSum.java | 7dd7f059e802c4d2c97c5d4b3b40b1487593d68a | [] | no_license | ishu2/DS-and-Algorithms | a35f6983222f15c3273328bf74bfe79ff3261b96 | 3b400915ed011144e8d577e95a485e0a23f1e90c | refs/heads/master | 2022-01-16T11:08:51.979218 | 2017-10-10T06:26:34 | 2017-10-10T06:26:34 | 106,179,778 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 897 | java | // KADANE'S ALGORITHM
package HackerRank_Questions;
public class SubarrayWithLargestSum {
public static int maxSubarraySum(int[] arr)
{
if(arr.length==0)
{
return 0;
}
if(arr.length==1)
{
return arr[0];
}
int sum=arr[0];
int end=arr[0];
for(int i=1;i<arr.length;i++)
{
sum=sum+arr[i];
if(sum>=end)
{
end=sum;
}
if(sum<=0)
{
sum=0;
}
}
return end;
}
public static int maxSubarraySumUsingDP(int[] arr)
{
if(arr.length==0)
{
return 0;
}
if(arr.length==1)
{
return arr[0];
}
int res=arr[0];
int finalRes=arr[0];
int i=0;
while(i<arr.length)
{
res=Math.max(arr[i], res+arr[i]);
finalRes=Math.max(res, finalRes);
i++;
}
return finalRes;
}
public static void main(String[] args) {
int[] arr={-20,-3,-10,-50,-40,-9};
int res=maxSubarraySumUsingDP(arr);
System.out.println(res);
}
}
| [
"rathiishita123@gmail.com"
] | rathiishita123@gmail.com |
ea8c10555e24c4aca0d52172022727824c89aa63 | cfc60fc1148916c0a1c9b421543e02f8cdf31549 | /src/testcases/CWE617_Reachable_Assertion/CWE617_Reachable_Assertion__connect_tcp_54a.java | 700a727d7a265a3d8ca061e7c1022267dffe9e33 | [
"LicenseRef-scancode-public-domain"
] | permissive | zhujinhua/GitFun | c77c8c08e89e61006f7bdbc5dd175e5d8bce8bd2 | 987f72fdccf871ece67f2240eea90e8c1971d183 | refs/heads/master | 2021-01-18T05:46:03.351267 | 2012-09-11T16:43:44 | 2012-09-11T16:43:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,685 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE617_Reachable_Assertion__connect_tcp_54a.java
Label Definition File: CWE617_Reachable_Assertion.label.xml
Template File: sources-sink-54a.tmpl.java
*/
/*
* @description
* CWE: 617 Assertion is reachable
* BadSource: connect_tcp Read data using an outbound tcp connection
* GoodSource: A hardcoded string
* Sinks:
* BadSink : possibility of assertion being triggered
* Flow Variant: 54 Data flow: data passed as an argument from one method through three others to a fifth; all five functions are in different classes in the same package
*
* */
package testcases.CWE617_Reachable_Assertion;
import testcasesupport.*;
import javax.servlet.http.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Logger;
public class CWE617_Reachable_Assertion__connect_tcp_54a extends AbstractTestCase
{
public void bad() throws Throwable
{
String data;
Logger log_bad = Logger.getLogger("local-logger");
data = ""; /* init data */
Socket sock = null;
BufferedReader buffread = null;
InputStreamReader instrread = null;
try {
/* Read data using an outbound tcp connection */
sock = new Socket("host.example.org", 39544);
/* read input from socket */
instrread = new InputStreamReader(sock.getInputStream());
buffread = new BufferedReader(instrread);
data = buffread.readLine();
}
catch( IOException ioe )
{
log_bad.warning("Error with stream reading");
}
finally {
/* clean up stream reading objects */
try {
if( buffread != null )
{
buffread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing buffread");
}
finally {
try {
if( instrread != null )
{
instrread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing instrread");
}
}
/* clean up socket objects */
try {
if( sock != null )
{
sock.close();
}
}
catch( IOException e )
{
log_bad.warning("Error closing sock");
}
}
(new CWE617_Reachable_Assertion__connect_tcp_54b()).bad_sink(data );
}
public void good() throws Throwable
{
goodG2B();
}
/* goodG2B() - use goodsource and badsink */
private void goodG2B() throws Throwable
{
String data;
java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
/* FIX: Use a hardcoded string */
data = "foo";
(new CWE617_Reachable_Assertion__connect_tcp_54b()).goodG2B_sink(data );
}
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
| [
"amitf@chackmarx.com"
] | amitf@chackmarx.com |
f353401259643a5ad6332fb79b4154a47d94c395 | 41ce5edf2e270e321dddd409ffac11ab7f32de86 | /4/com/android/phone/PhoneApp.java | fc3d7f0c79a9adc27fbbfc141fcc529c632381e2 | [] | no_license | danny-source/SDK_Android_Source_03-14 | 372bb03020203dba71bc165c8370b91c80bc6eaa | 323ad23e16f598d5589485b467bb9fba7403c811 | refs/heads/master | 2020-05-18T11:19:29.171830 | 2014-03-29T12:12:44 | 2014-03-29T12:12:44 | 18,238,039 | 2 | 2 | null | null | null | null | UTF-8 | Java | false | false | 51,958 | java | /*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.phone;
import android.app.Activity;
import android.app.Application;
import android.app.KeyguardManager;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncResult;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.IPowerManager;
import android.os.LocalPowerManager;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.preference.PreferenceManager;
import android.provider.Settings.System;
import android.telephony.ServiceState;
import android.util.Config;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
import com.android.internal.telephony.cdma.EriInfo;
import com.android.internal.telephony.IccCard;
import com.android.internal.telephony.MmiCode;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.TelephonyIntents;
/**
* Top-level Application class for the Phone app.
*/
public class PhoneApp extends Application {
/* package */ static final String LOG_TAG = "PhoneApp";
/**
* Phone app-wide debug level:
* 0 - no debug logging
* 1 - normal debug logging if ro.debuggable is set (which is true in
* "eng" and "userdebug" builds but not "user" builds)
* 2 - ultra-verbose debug logging
*
* Most individual classes in the phone app have a local DBG constant,
* typically set to
* (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1)
* or else
* (PhoneApp.DBG_LEVEL >= 2)
* depending on the desired verbosity.
*/
/* package */ static final int DBG_LEVEL = 1;
private static final boolean DBG =
(PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2);
// Message codes; see mHandler below.
private static final int EVENT_SIM_ABSENT = 1;
private static final int EVENT_SIM_LOCKED = 2;
private static final int EVENT_SIM_NETWORK_LOCKED = 3;
private static final int EVENT_WIRED_HEADSET_PLUG = 7;
private static final int EVENT_SIM_STATE_CHANGED = 8;
private static final int EVENT_UPDATE_INCALL_NOTIFICATION = 9;
private static final int EVENT_DATA_ROAMING_DISCONNECTED = 10;
private static final int EVENT_DATA_ROAMING_OK = 11;
private static final int EVENT_UNSOL_CDMA_INFO_RECORD = 12;
// The MMI codes are also used by the InCallScreen.
public static final int MMI_INITIATE = 51;
public static final int MMI_COMPLETE = 52;
public static final int MMI_CANCEL = 53;
// Don't use message codes larger than 99 here; those are reserved for
// the individual Activities of the Phone UI.
/**
* Allowable values for the poke lock code (timeout between a user activity and the
* going to sleep), please refer to {@link com.android.server.PowerManagerService}
* for additional reference.
* SHORT uses the short delay for the timeout (SHORT_KEYLIGHT_DELAY, 6 sec)
* MEDIUM uses the medium delay for the timeout (MEDIUM_KEYLIGHT_DELAY, 15 sec)
* DEFAULT is the system-wide default delay for the timeout (1 min)
*/
public enum ScreenTimeoutDuration {
SHORT,
MEDIUM,
DEFAULT
}
/**
* Allowable values for the wake lock code.
* SLEEP means the device can be put to sleep.
* PARTIAL means wake the processor, but we display can be kept off.
* FULL means wake both the processor and the display.
*/
public enum WakeState {
SLEEP,
PARTIAL,
FULL
}
private static PhoneApp sMe;
// A few important fields we expose to the rest of the package
// directly (rather than thru set/get methods) for efficiency.
Phone phone;
CallNotifier notifier;
Ringer ringer;
BluetoothHandsfree mBtHandsfree;
PhoneInterfaceManager phoneMgr;
int mBluetoothHeadsetState = BluetoothHeadset.STATE_ERROR;
int mBluetoothHeadsetAudioState = BluetoothHeadset.STATE_ERROR;
boolean mShowBluetoothIndication = false;
// Internal PhoneApp Call state tracker
CdmaPhoneCallState cdmaPhoneCallState;
// The InCallScreen instance (or null if the InCallScreen hasn't been
// created yet.)
private InCallScreen mInCallScreen;
// The currently-active PUK entry activity and progress dialog.
// Normally, these are the Emergency Dialer and the subsequent
// progress dialog. null if there is are no such objects in
// the foreground.
private Activity mPUKEntryActivity;
private ProgressDialog mPUKEntryProgressDialog;
private boolean mIsSimPinEnabled;
private String mCachedSimPin;
// True if a wired headset is currently plugged in, based on the state
// from the latest Intent.ACTION_HEADSET_PLUG broadcast we received in
// mReceiver.onReceive().
private boolean mIsHeadsetPlugged;
private WakeState mWakeState = WakeState.SLEEP;
private ScreenTimeoutDuration mScreenTimeoutDuration = ScreenTimeoutDuration.DEFAULT;
private boolean mIgnoreTouchUserActivity = false;
private IBinder mPokeLockToken = new Binder();
private IPowerManager mPowerManagerService;
private PowerManager.WakeLock mWakeLock;
private PowerManager.WakeLock mPartialWakeLock;
private KeyguardManager mKeyguardManager;
private KeyguardManager.KeyguardLock mKeyguardLock;
// Broadcast receiver for various intent broadcasts (see onCreate())
private final BroadcastReceiver mReceiver = new PhoneAppBroadcastReceiver();
// Broadcast receiver purely for ACTION_MEDIA_BUTTON broadcasts
private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver();
/** boolean indicating restoring mute state on InCallScreen.onResume() */
private boolean mShouldRestoreMuteOnInCallResume;
/**
* Set the restore mute state flag. Used when we are setting the mute state
* OUTSIDE of user interaction {@link PhoneUtils#startNewCall(Phone)}
*/
/*package*/void setRestoreMuteOnInCallResume (boolean mode) {
mShouldRestoreMuteOnInCallResume = mode;
}
/**
* Get the restore mute state flag.
* This is used by the InCallScreen {@link InCallScreen#onResume()} to figure
* out if we need to restore the mute state for the current active call.
*/
/*package*/boolean getRestoreMuteOnInCallResume () {
return mShouldRestoreMuteOnInCallResume;
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_SIM_LOCKED:
// mIsSimPinEnabled = true;
//
// if (Config.LOGV) Log.v(LOG_TAG, "show sim unlock panel");
// SimPinUnlockPanel pinUnlockPanel = new SimPinUnlockPanel(
// PhoneApp.getInstance());
// pinUnlockPanel.show();
break;
case EVENT_SIM_ABSENT:
// Don't need this now that the lock screen handles this case
// if (Config.LOGV) Log.v(LOG_TAG, "show sim missing panel");
// SimMissingPanel missingPanel = new SimMissingPanel(
// PhoneApp.getInstance());
// missingPanel.show();
break;
case EVENT_SIM_NETWORK_LOCKED:
if (getResources().getBoolean(R.bool.ignore_sim_network_locked_events)) {
// Some products don't have the concept of a "SIM network lock"
Log.i(LOG_TAG, "Ignoring EVENT_SIM_NETWORK_LOCKED event; "
+ "not showing 'SIM network unlock' PIN entry screen");
} else {
// Normal case: show the "SIM network unlock" PIN entry screen.
// The user won't be able to do anything else until
// they enter a valid SIM network PIN.
Log.i(LOG_TAG, "show sim depersonal panel");
IccNetworkDepersonalizationPanel ndpPanel =
new IccNetworkDepersonalizationPanel(PhoneApp.getInstance());
ndpPanel.show();
}
break;
case EVENT_UPDATE_INCALL_NOTIFICATION:
// Tell the NotificationMgr to update the "ongoing
// call" icon in the status bar, if necessary.
// Currently, this is triggered by a bluetooth headset
// state change (since the status bar icon needs to
// turn blue when bluetooth is active.)
NotificationMgr.getDefault().updateInCallNotification();
break;
case EVENT_DATA_ROAMING_DISCONNECTED:
NotificationMgr.getDefault().showDataDisconnectedRoaming();
break;
case EVENT_DATA_ROAMING_OK:
NotificationMgr.getDefault().hideDataDisconnectedRoaming();
break;
case MMI_COMPLETE:
onMMIComplete((AsyncResult) msg.obj);
break;
case MMI_CANCEL:
PhoneUtils.cancelMmiCode(phone);
break;
case EVENT_WIRED_HEADSET_PLUG:
// Since the presence of a wired headset or bluetooth affects the
// speakerphone, update the "speaker" state. We ONLY want to do
// this on the wired headset connect / disconnect events for now
// though, so we're only triggering on EVENT_WIRED_HEADSET_PLUG.
if (!isHeadsetPlugged() &&
(mBtHandsfree == null || !mBtHandsfree.isAudioOn())) {
// is the state is "not connected", restore the speaker state.
PhoneUtils.restoreSpeakerMode(getApplicationContext());
}
NotificationMgr.getDefault().updateSpeakerNotification();
break;
case EVENT_SIM_STATE_CHANGED:
// Marks the event where the SIM goes into ready state.
// Right now, this is only used for the PUK-unlocking
// process.
if (msg.obj.equals(IccCard.INTENT_VALUE_ICC_READY)) {
// when the right event is triggered and there
// are UI objects in the foreground, we close
// them to display the lock panel.
if (mPUKEntryActivity != null) {
mPUKEntryActivity.finish();
mPUKEntryActivity = null;
}
if (mPUKEntryProgressDialog != null) {
mPUKEntryProgressDialog.dismiss();
mPUKEntryProgressDialog = null;
}
}
break;
case EVENT_UNSOL_CDMA_INFO_RECORD:
//TODO: handle message here;
break;
}
}
};
public PhoneApp() {
sMe = this;
}
@Override
public void onCreate() {
if (Config.LOGV) Log.v(LOG_TAG, "onCreate()...");
ContentResolver resolver = getContentResolver();
if (phone == null) {
// Initialize the telephony framework
PhoneFactory.makeDefaultPhones(this);
// Get the default phone
phone = PhoneFactory.getDefaultPhone();
NotificationMgr.init(this);
phoneMgr = new PhoneInterfaceManager(this, phone);
if (getSystemService(Context.BLUETOOTH_SERVICE) != null) {
mBtHandsfree = new BluetoothHandsfree(this, phone);
startService(new Intent(this, BluetoothHeadsetService.class));
} else {
// Device is not bluetooth capable
mBtHandsfree = null;
}
ringer = new Ringer(phone);
// before registering for phone state changes
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, LOG_TAG);
// lock used to keep the processor awake, when we don't care for the display.
mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, LOG_TAG);
mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
mKeyguardLock = mKeyguardManager.newKeyguardLock(LOG_TAG);
// get a handle to the service so that we can use it later when we
// want to set the poke lock.
mPowerManagerService = IPowerManager.Stub.asInterface(
ServiceManager.getService("power"));
notifier = new CallNotifier(this, phone, ringer, mBtHandsfree);
// register for ICC status
IccCard sim = phone.getIccCard();
if (sim != null) {
if (Config.LOGV) Log.v(LOG_TAG, "register for ICC status");
sim.registerForAbsent(mHandler, EVENT_SIM_ABSENT, null);
sim.registerForLocked(mHandler, EVENT_SIM_LOCKED, null);
sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
}
// register for MMI/USSD
phone.registerForMmiComplete(mHandler, MMI_COMPLETE, null);
// register connection tracking to PhoneUtils
PhoneUtils.initializeConnectionHandler(phone);
// Register for misc other intent broadcasts.
IntentFilter intentFilter =
new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intentFilter.addAction(BluetoothIntent.HEADSET_STATE_CHANGED_ACTION);
intentFilter.addAction(BluetoothIntent.HEADSET_AUDIO_STATE_CHANGED_ACTION);
intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
registerReceiver(mReceiver, intentFilter);
// Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts,
// since we need to manually adjust its priority (to make sure
// we get these intents *before* the media player.)
IntentFilter mediaButtonIntentFilter =
new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
//
// Make sure we're higher priority than the media player's
// MediaButtonIntentReceiver (which currently has the default
// priority of zero; see apps/Music/AndroidManifest.xml.)
mediaButtonIntentFilter.setPriority(1);
//
registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter);
//set the default values for the preferences in the phone.
PreferenceManager.setDefaultValues(this, R.xml.network_setting, false);
PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false);
// Make sure the audio mode (along with some
// audio-mode-related state of our own) is initialized
// correctly, given the current state of the phone.
switch (phone.getState()) {
case IDLE:
if (DBG) Log.d(LOG_TAG, "Resetting audio state/mode: IDLE");
PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_IDLE);
PhoneUtils.setAudioMode(this, AudioManager.MODE_NORMAL);
break;
case RINGING:
if (DBG) Log.d(LOG_TAG, "Resetting audio state/mode: RINGING");
PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_RINGING);
PhoneUtils.setAudioMode(this, AudioManager.MODE_RINGTONE);
break;
case OFFHOOK:
if (DBG) Log.d(LOG_TAG, "Resetting audio state/mode: OFFHOOK");
PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK);
PhoneUtils.setAudioMode(this, AudioManager.MODE_IN_CALL);
break;
}
}
// XXX pre-load the SimProvider so that it's ready
resolver.getType(Uri.parse("content://icc/adn"));
// start with the default value to set the mute state.
mShouldRestoreMuteOnInCallResume = false;
// Register for Cdma Information Records
// TODO(Moto): Merge
// phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null);
if (phone.getPhoneName().equals("CDMA")) {
// Create an instance of CdmaPhoneCallState and initialize it to IDLE
cdmaPhoneCallState = new CdmaPhoneCallState();
cdmaPhoneCallState.CdmaPhoneCallStateInit();
}
}
/**
* Returns the singleton instance of the PhoneApp.
*/
static PhoneApp getInstance() {
return sMe;
}
Ringer getRinger() {
return ringer;
}
BluetoothHandsfree getBluetoothHandsfree() {
return mBtHandsfree;
}
static Intent createCallLogIntent() {
Intent intent = new Intent(Intent.ACTION_VIEW, null);
intent.setType("vnd.android.cursor.dir/calls");
return intent;
}
/**
* Return an Intent that can be used to bring up the in-call screen.
*
* This intent can only be used from within the Phone app, since the
* InCallScreen is not exported from our AndroidManifest.
*/
/* package */ static Intent createInCallIntent() {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
intent.setClassName("com.android.phone", getCallScreenClassName());
return intent;
}
/**
* Variation of createInCallIntent() that also specifies whether the
* DTMF dialpad should be initially visible when the InCallScreen
* comes up.
*/
/* package */ static Intent createInCallIntent(boolean showDialpad) {
Intent intent = createInCallIntent();
intent.putExtra(InCallScreen.SHOW_DIALPAD_EXTRA, showDialpad);
return intent;
}
static String getCallScreenClassName() {
return InCallScreen.class.getName();
}
/**
* Starts the InCallScreen Activity.
*/
void displayCallScreen() {
if (VDBG) Log.d(LOG_TAG, "displayCallScreen()...");
startActivity(createInCallIntent());
Profiler.callScreenRequested();
}
/**
* Helper function to check for one special feature of the CALL key:
* Normally, when the phone is idle, CALL takes you to the call log
* (see the handler for KEYCODE_CALL in PhoneWindow.onKeyUp().)
* But if the phone is in use (either off-hook or ringing) we instead
* handle the CALL button by taking you to the in-call UI.
*
* @return true if we intercepted the CALL keypress (i.e. the phone
* was in use)
*
* @see DialerActivity#onCreate
*/
boolean handleInCallOrRinging() {
if (phone.getState() != Phone.State.IDLE) {
// Phone is OFFHOOK or RINGING.
if (DBG) Log.v(LOG_TAG,
"handleInCallOrRinging: show call screen");
displayCallScreen();
return true;
}
return false;
}
boolean isSimPinEnabled() {
return mIsSimPinEnabled;
}
boolean authenticateAgainstCachedSimPin(String pin) {
return (mCachedSimPin != null && mCachedSimPin.equals(pin));
}
void setCachedSimPin(String pin) {
mCachedSimPin = pin;
}
void setInCallScreenInstance(InCallScreen inCallScreen) {
mInCallScreen = inCallScreen;
}
/**
* @return true if the in-call UI is running as the foreground
* activity. (In other words, from the perspective of the
* InCallScreen activity, return true between onResume() and
* onPause().)
*
* Note this method will return false if the screen is currently off,
* even if the InCallScreen *was* in the foreground just before the
* screen turned off. (This is because the foreground activity is
* always "paused" while the screen is off.)
*/
boolean isShowingCallScreen() {
if (mInCallScreen == null) return false;
return mInCallScreen.isForegroundActivity();
}
/**
* Dismisses the in-call UI.
*
* This also ensures that you won't be able to get back to the in-call
* UI via the BACK button (since this call removes the InCallScreen
* from the activity history.)
*/
void dismissCallScreen() {
if (mInCallScreen != null) {
mInCallScreen.finish();
}
}
/**
* Sets the activity responsible for un-PUK-blocking the device
* so that we may close it when we receive a positive result.
* mPUKEntryActivity is also used to indicate to the device that
* we are trying to un-PUK-lock the phone. In other words, iff
* it is NOT null, then we are trying to unlock and waiting for
* the SIM to move to READY state.
*
* @param activity is the activity to close when PUK has
* finished unlocking. Can be set to null to indicate the unlock
* or SIM READYing process is over.
*/
void setPukEntryActivity(Activity activity) {
mPUKEntryActivity = activity;
}
Activity getPUKEntryActivity() {
return mPUKEntryActivity;
}
/**
* Sets the dialog responsible for notifying the user of un-PUK-
* blocking - SIM READYing progress, so that we may dismiss it
* when we receive a positive result.
*
* @param dialog indicates the progress dialog informing the user
* of the state of the device. Dismissed upon completion of
* READYing process
*/
void setPukEntryProgressDialog(ProgressDialog dialog) {
mPUKEntryProgressDialog = dialog;
}
ProgressDialog getPUKEntryProgressDialog() {
return mPUKEntryProgressDialog;
}
/**
* Disables the keyguard. This is used by the phone app to allow
* interaction with the Phone UI when the keyguard would otherwise be
* active (like receiving an incoming call while the device is
* locked.)
*
* Any call to this method MUST be followed (eventually)
* by a corresponding reenableKeyguard() call.
*/
/* package */ void disableKeyguard() {
if (DBG) Log.d(LOG_TAG, "disable keyguard");
// if (DBG) Log.d(LOG_TAG, "disableKeyguard()...", new Throwable("stack dump"));
mKeyguardLock.disableKeyguard();
}
/**
* Re-enables the keyguard after a previous disableKeyguard() call.
*
* Any call to this method MUST correspond to (i.e. be balanced with)
* a previous disableKeyguard() call.
*/
/* package */ void reenableKeyguard() {
if (DBG) Log.d(LOG_TAG, "re-enable keyguard");
// if (DBG) Log.d(LOG_TAG, "reenableKeyguard()...", new Throwable("stack dump"));
mKeyguardLock.reenableKeyguard();
}
/**
* Controls how quickly the screen times out.
*
* The poke lock controls how long it takes before the screen powers
* down, and therefore has no immediate effect when the current
* WakeState (see {@link PhoneApp#requestWakeState}) is FULL.
* If we're in a state where the screen *is* allowed to turn off,
* though, the poke lock will determine the timeout interval (long or
* short).
*
* @param shortPokeLock tells the device the timeout duration to use
* before going to sleep
* {@link com.android.server.PowerManagerService#SHORT_KEYLIGHT_DELAY}.
*/
/* package */ void setScreenTimeout(ScreenTimeoutDuration duration) {
if (VDBG) Log.d(LOG_TAG, "setScreenTimeout(" + duration + ")...");
// make sure we don't set the poke lock repeatedly so that we
// avoid triggering the userActivity calls in
// PowerManagerService.setPokeLock().
if (duration == mScreenTimeoutDuration) {
return;
}
mScreenTimeoutDuration = duration;
updatePokeLock();
}
/**
* Update the state of the poke lock held by the phone app,
* based on the current desired screen timeout and the
* current "ignore user activity on touch" flag.
*/
private void updatePokeLock() {
// This is kind of convoluted, but the basic thing to remember is
// that the poke lock just sends a message to the screen to tell
// it to stay on for a while.
// The default is 0, for a long timeout and should be set that way
// when we are heading back into a the keyguard / screen off
// state, and also when we're trying to keep the screen alive
// while ringing. We'll also want to ignore the cheek events
// regardless of the timeout duration.
// The short timeout is really used whenever we want to give up
// the screen lock, such as when we're in call.
int pokeLockSetting = LocalPowerManager.POKE_LOCK_IGNORE_CHEEK_EVENTS;
switch (mScreenTimeoutDuration) {
case SHORT:
// Set the poke lock to timeout the display after a short
// timeout (5s). This ensures that the screen goes to sleep
// as soon as acceptably possible after we the wake lock
// has been released.
pokeLockSetting |= LocalPowerManager.POKE_LOCK_SHORT_TIMEOUT;
break;
case MEDIUM:
// Set the poke lock to timeout the display after a medium
// timeout (15s). This ensures that the screen goes to sleep
// as soon as acceptably possible after we the wake lock
// has been released.
pokeLockSetting |= LocalPowerManager.POKE_LOCK_MEDIUM_TIMEOUT;
break;
case DEFAULT:
default:
// set the poke lock to timeout the display after a long
// delay by default.
// TODO: it may be nice to be able to disable cheek presses
// for long poke locks (emergency dialer, for instance).
break;
}
if (mIgnoreTouchUserActivity) {
pokeLockSetting |= LocalPowerManager.POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS;
}
// Send the request
try {
mPowerManagerService.setPokeLock(pokeLockSetting, mPokeLockToken, LOG_TAG);
} catch (RemoteException e) {
Log.w(LOG_TAG, "mPowerManagerService.setPokeLock() failed: " + e);
}
}
/**
* Controls whether or not the screen is allowed to sleep.
*
* Once sleep is allowed (WakeState is SLEEP), it will rely on the
* settings for the poke lock to determine when to timeout and let
* the device sleep {@link PhoneApp#setScreenTimeout}.
*
* @param ws tells the device to how to wake.
*/
/* package */ void requestWakeState(WakeState ws) {
if (VDBG) Log.d(LOG_TAG, "requestWakeState(" + ws + ")...");
if (mWakeState != ws) {
switch (ws) {
case PARTIAL:
// acquire the processor wake lock, and release the FULL
// lock if it is being held.
mPartialWakeLock.acquire();
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
break;
case FULL:
// acquire the full wake lock, and release the PARTIAL
// lock if it is being held.
mWakeLock.acquire();
if (mPartialWakeLock.isHeld()) {
mPartialWakeLock.release();
}
break;
case SLEEP:
default:
// release both the PARTIAL and FULL locks.
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
if (mPartialWakeLock.isHeld()) {
mPartialWakeLock.release();
}
break;
}
mWakeState = ws;
}
}
/**
* If we are not currently keeping the screen on, then poke the power
* manager to wake up the screen for the user activity timeout duration.
*/
/* package */ void wakeUpScreen() {
if (mWakeState == WakeState.SLEEP) {
if (DBG) Log.d(LOG_TAG, "pulse screen lock");
try {
mPowerManagerService.userActivityWithForce(SystemClock.uptimeMillis(), false, true);
} catch (RemoteException ex) {
// Ignore -- the system process is dead.
}
}
}
/**
* Sets the wake state and screen timeout based on the current state
* of the phone, and the current state of the in-call UI.
*
* This method is a "UI Policy" wrapper around
* {@link PhoneApp#requestWakeState} and {@link PhoneApp#setScreenTimeout}.
*
* It's safe to call this method regardless of the state of the Phone
* (e.g. whether or not it's idle), and regardless of the state of the
* Phone UI (e.g. whether or not the InCallScreen is active.)
*/
/* package */ void updateWakeState() {
Phone.State state = phone.getState();
// True if the in-call UI is the foreground activity.
// (Note this will be false if the screen is currently off,
// since in that case *no* activity is in the foreground.)
boolean isShowingCallScreen = isShowingCallScreen();
// True if the InCallScreen's DTMF dialer is currently opened.
// (Note this does NOT imply whether or not the InCallScreen
// itself is visible.)
boolean isDialerOpened = (mInCallScreen != null) && mInCallScreen.isDialerOpened();
// True if the speakerphone is in use. (If so, we *always* use
// the default timeout. Since the user is obviously not holding
// the phone up to his/her face, we don't need to worry about
// false touches, and thus don't need to turn the screen off so
// aggressively.)
// Note that we need to make a fresh call to this method any
// time the speaker state changes. (That happens in
// PhoneUtils.turnOnSpeaker().)
boolean isSpeakerInUse = (state == Phone.State.OFFHOOK) && PhoneUtils.isSpeakerOn(this);
// TODO (bug 1440854): The screen timeout *might* also need to
// depend on the bluetooth state, but this isn't as clear-cut as
// the speaker state (since while using BT it's common for the
// user to put the phone straight into a pocket, in which case the
// timeout should probably still be short.)
if (DBG) Log.d(LOG_TAG, "updateWakeState: callscreen " + isShowingCallScreen
+ ", dialer " + isDialerOpened
+ ", speaker " + isSpeakerInUse + "...");
//
// (1) Set the screen timeout.
//
// Note that the "screen timeout" value we determine here is
// meaningless if the screen is forced on (see (2) below.)
//
if (!isShowingCallScreen || isSpeakerInUse) {
// Use the system-wide default timeout.
setScreenTimeout(ScreenTimeoutDuration.DEFAULT);
} else {
// We're on the in-call screen, and *not* using the speakerphone.
if (isDialerOpened) {
// The DTMF dialpad is up. This case is special because
// the in-call UI has its own "touch lock" mechanism to
// disable the dialpad after a very short amount of idle
// time (to avoid false touches from the user's face while
// in-call.)
//
// In this case the *physical* screen just uses the
// system-wide default timeout.
setScreenTimeout(ScreenTimeoutDuration.DEFAULT);
} else {
// We're on the in-call screen, and not using the DTMF dialpad.
// There's actually no touchable UI onscreen at all in
// this state. Also, the user is (most likely) not
// looking at the screen at all, since they're probably
// holding the phone up to their face. Here we use a
// special screen timeout value specific to the in-call
// screen, purely to save battery life.
setScreenTimeout(ScreenTimeoutDuration.MEDIUM);
}
}
//
// (2) Decide whether to force the screen on or not.
//
// Force the screen to be on if the phone is ringing, or if we're
// displaying the "Call ended" UI for a connection in the
// "disconnected" state.
//
boolean isRinging = (state == Phone.State.RINGING);
boolean showingDisconnectedConnection =
PhoneUtils.hasDisconnectedConnections(phone) && isShowingCallScreen;
boolean keepScreenOn = isRinging || showingDisconnectedConnection;
if (DBG) Log.d(LOG_TAG, "updateWakeState: keepScreenOn = " + keepScreenOn
+ " (isRinging " + isRinging
+ ", showingDisc " + showingDisconnectedConnection + ")");
// keepScreenOn == true means we'll hold a full wake lock:
requestWakeState(keepScreenOn ? WakeState.FULL : WakeState.SLEEP);
}
/**
* Wrapper around the PowerManagerService.preventScreenOn() API.
* This allows the in-call UI to prevent the screen from turning on
* even if a subsequent call to updateWakeState() causes us to acquire
* a full wake lock.
*/
/* package */ void preventScreenOn(boolean prevent) {
if (VDBG) Log.d(LOG_TAG, "- preventScreenOn(" + prevent + ")...");
try {
mPowerManagerService.preventScreenOn(prevent);
} catch (RemoteException e) {
Log.w(LOG_TAG, "mPowerManagerService.preventScreenOn() failed: " + e);
}
}
/**
* Sets or clears the flag that tells the PowerManager that touch
* (and cheek) events should NOT be considered "user activity".
*
* Since the in-call UI is totally insensitive to touch in most
* states, we set this flag whenever the InCallScreen is in the
* foreground. (Otherwise, repeated unintentional touches could
* prevent the device from going to sleep.)
*
* There *are* some some touch events that really do count as user
* activity, though. For those, we need to manually poke the
* PowerManager's userActivity method; see pokeUserActivity().
*/
/* package */ void setIgnoreTouchUserActivity(boolean ignore) {
if (VDBG) Log.d(LOG_TAG, "setIgnoreTouchUserActivity(" + ignore + ")...");
mIgnoreTouchUserActivity = ignore;
updatePokeLock();
}
/**
* Manually pokes the PowerManager's userActivity method. Since we
* hold the POKE_LOCK_IGNORE_TOUCH_AND_CHEEK_EVENTS poke lock while
* the InCallScreen is active, we need to do this for touch events
* that really do count as user activity (like DTMF key presses, or
* unlocking the "touch lock" overlay.)
*/
/* package */ void pokeUserActivity() {
if (VDBG) Log.d(LOG_TAG, "pokeUserActivity()...");
try {
mPowerManagerService.userActivity(SystemClock.uptimeMillis(), false);
} catch (RemoteException e) {
Log.w(LOG_TAG, "mPowerManagerService.userActivity() failed: " + e);
}
}
KeyguardManager getKeyguardManager() {
return mKeyguardManager;
}
private void onMMIComplete(AsyncResult r) {
if (VDBG) Log.d(LOG_TAG, "onMMIComplete()...");
MmiCode mmiCode = (MmiCode) r.result;
PhoneUtils.displayMMIComplete(phone, getInstance(), mmiCode, null, null);
}
private void initForNewRadioTechnology() {
if (DBG) Log.d(LOG_TAG, "initForNewRadioTechnology...");
ringer.updateRingerContextAfterRadioTechnologyChange(this.phone);
notifier.updateCallNotifierRegistrationsAfterRadioTechnologyChange();
if (mBtHandsfree != null) {
mBtHandsfree.updateBtHandsfreeAfterRadioTechnologyChange();
}
if (mInCallScreen != null) {
mInCallScreen.updateAfterRadioTechnologyChange();
}
// Update registration for ICC status after radio technology change
IccCard sim = phone.getIccCard();
if (sim != null) {
if (DBG) Log.d(LOG_TAG, "Update registration for ICC status...");
//Register all events new to the new active phone
sim.registerForAbsent(mHandler, EVENT_SIM_ABSENT, null);
sim.registerForLocked(mHandler, EVENT_SIM_LOCKED, null);
sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
}
if (phone.getPhoneName().equals("CDMA")) {
// Create an instance of CdmaPhoneCallState and initialize it to IDLE
cdmaPhoneCallState = new CdmaPhoneCallState();
cdmaPhoneCallState.CdmaPhoneCallStateInit();
}
}
/**
* Send ECBM Exit Request
*/
void sendEcbmExitRequest() {
mHandler.sendEmptyMessage(EVENT_UPDATE_INCALL_NOTIFICATION);
}
/**
* @return true if a wired headset is currently plugged in.
*
* @see Intent.ACTION_HEADSET_PLUG (which we listen for in mReceiver.onReceive())
*/
boolean isHeadsetPlugged() {
return mIsHeadsetPlugged;
}
/**
* @return true if the onscreen UI should currently be showing the
* special "bluetooth is active" indication in a couple of places (in
* which UI elements turn blue and/or show the bluetooth logo.)
*
* This depends on the BluetoothHeadset state *and* the current
* telephony state; see shouldShowBluetoothIndication().
*
* @see CallCard
* @see NotificationMgr.updateInCallNotification
*/
/* package */ boolean showBluetoothIndication() {
return mShowBluetoothIndication;
}
/**
* Recomputes the mShowBluetoothIndication flag based on the current
* bluetooth state and current telephony state.
*
* This needs to be called any time the bluetooth headset state or the
* telephony state changes.
*
* @param forceUiUpdate if true, force the UI elements that care
* about this flag to update themselves.
*/
/* package */ void updateBluetoothIndication(boolean forceUiUpdate) {
mShowBluetoothIndication = shouldShowBluetoothIndication(mBluetoothHeadsetState,
mBluetoothHeadsetAudioState,
phone);
if (forceUiUpdate) {
// Post Handler messages to the various components that might
// need to be refreshed based on the new state.
if (isShowingCallScreen()) mInCallScreen.updateBluetoothIndication();
mHandler.sendEmptyMessage(EVENT_UPDATE_INCALL_NOTIFICATION);
}
}
/**
* UI policy helper function for the couple of places in the UI that
* have some way of indicating that "bluetooth is in use."
*
* @return true if the onscreen UI should indicate that "bluetooth is in use",
* based on the specified bluetooth headset state, and the
* current state of the phone.
* @see showBluetoothIndication()
*/
private static boolean shouldShowBluetoothIndication(int bluetoothState,
int bluetoothAudioState,
Phone phone) {
// We want the UI to indicate that "bluetooth is in use" in two
// slightly different cases:
//
// (a) The obvious case: if a bluetooth headset is currently in
// use for an ongoing call.
//
// (b) The not-so-obvious case: if an incoming call is ringing,
// and we expect that audio *will* be routed to a bluetooth
// headset once the call is answered.
switch (phone.getState()) {
case OFFHOOK:
// This covers normal active calls, and also the case if
// the foreground call is DIALING or ALERTING. In this
// case, bluetooth is considered "active" if a headset
// is connected *and* audio is being routed to it.
return ((bluetoothState == BluetoothHeadset.STATE_CONNECTED)
&& (bluetoothAudioState == BluetoothHeadset.AUDIO_STATE_CONNECTED));
case RINGING:
// If an incoming call is ringing, we're *not* yet routing
// audio to the headset (since there's no in-call audio
// yet!) In this case, if a bluetooth headset is
// connected at all, we assume that it'll become active
// once the user answers the phone.
return (bluetoothState == BluetoothHeadset.STATE_CONNECTED);
default: // Presumably IDLE
return false;
}
}
/**
* Receiver for misc intent broadcasts the Phone app cares about.
*/
private class PhoneAppBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
boolean enabled = System.getInt(getContentResolver(),
System.AIRPLANE_MODE_ON, 0) == 0;
phone.setRadioPower(enabled);
} else if (action.equals(BluetoothIntent.HEADSET_STATE_CHANGED_ACTION)) {
mBluetoothHeadsetState = intent.getIntExtra(BluetoothIntent.HEADSET_STATE,
BluetoothHeadset.STATE_ERROR);
if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_STATE_CHANGED_ACTION");
if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetState);
updateBluetoothIndication(true); // Also update any visible UI if necessary
} else if (action.equals(BluetoothIntent.HEADSET_AUDIO_STATE_CHANGED_ACTION)) {
mBluetoothHeadsetAudioState =
intent.getIntExtra(BluetoothIntent.HEADSET_AUDIO_STATE,
BluetoothHeadset.STATE_ERROR);
if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_AUDIO_STATE_CHANGED_ACTION");
if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetAudioState);
updateBluetoothIndication(true); // Also update any visible UI if necessary
} else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED");
if (VDBG) Log.d(LOG_TAG, "- state: " + intent.getStringExtra(Phone.STATE_KEY));
if (VDBG) Log.d(LOG_TAG, "- reason: "
+ intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY));
// The "data disconnected due to roaming" notification is
// visible if you've lost data connectivity because you're
// roaming and you have the "data roaming" feature turned off.
boolean disconnectedDueToRoaming = false;
if ("DISCONNECTED".equals(intent.getStringExtra(Phone.STATE_KEY))) {
String reason = intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY);
if (Phone.REASON_ROAMING_ON.equals(reason)) {
// We just lost our data connection, and the reason
// is that we started roaming. This implies that
// the user has data roaming turned off.
disconnectedDueToRoaming = true;
}
}
mHandler.sendEmptyMessage(disconnectedDueToRoaming
? EVENT_DATA_ROAMING_DISCONNECTED
: EVENT_DATA_ROAMING_OK);
} else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_HEADSET_PLUG");
if (VDBG) Log.d(LOG_TAG, " state: " + intent.getIntExtra("state", 0));
if (VDBG) Log.d(LOG_TAG, " name: " + intent.getStringExtra("name"));
mIsHeadsetPlugged = (intent.getIntExtra("state", 0) == 1);
mHandler.sendMessage(mHandler.obtainMessage(EVENT_WIRED_HEADSET_PLUG, 0));
} else if (action.equals(Intent.ACTION_BATTERY_LOW)) {
if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_BATTERY_LOW");
notifier.sendBatteryLow(); // Play a warning tone if in-call
} else if ((action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) &&
(mPUKEntryActivity != null)) {
// if an attempt to un-PUK-lock the device was made, while we're
// receiving this state change notification, notify the handler.
// NOTE: This is ONLY triggered if an attempt to un-PUK-lock has
// been attempted.
mHandler.sendMessage(mHandler.obtainMessage(EVENT_SIM_STATE_CHANGED,
intent.getStringExtra(IccCard.INTENT_KEY_ICC_STATE)));
} else if (action.equals(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED)) {
String newPhone = intent.getStringExtra(Phone.PHONE_NAME_KEY);
Log.d(LOG_TAG, "Radio technology switched. Now " + newPhone + " is active.");
initForNewRadioTechnology();
} else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) {
handleServiceStateChanged(intent);
} else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
Log.d(LOG_TAG, "Emergency Callback Mode arrived in PhoneApp.");
// Send Intend to start ECBM application
Intent EcbmAlarm = new Intent(Intent.ACTION_MAIN, null);
EcbmAlarm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
EcbmAlarm.setClassName("com.android.phone", EmergencyCallbackMode.class.getName());
startActivity(EcbmAlarm);
}
}
}
/**
* Broadcast receiver for the ACTION_MEDIA_BUTTON broadcast intent.
*
* This functionality isn't lumped in with the other intents in
* PhoneAppBroadcastReceiver because we instantiate this as a totally
* separate BroadcastReceiver instance, since we need to manually
* adjust its IntentFilter's priority (to make sure we get these
* intents *before* the media player.)
*/
private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (VDBG) Log.d(LOG_TAG,
"MediaButtonBroadcastReceiver.onReceive()... event = " + event);
if ((event != null)
&& (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)
&& (event.getAction() == KeyEvent.ACTION_DOWN)) {
if (event.getRepeatCount() == 0) {
// Mute ONLY on the initial keypress.
if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: HEADSETHOOK down!");
boolean consumed = PhoneUtils.handleHeadsetHook(phone);
if (VDBG) Log.d(LOG_TAG, "==> handleHeadsetHook(): consumed = " + consumed);
if (consumed) {
abortBroadcast();
}
} else if (phone.getState() != Phone.State.IDLE) {
// As for any DOWN events other than the initial press, we consume
// (and ignore) those too if the phone is in use. (Otherwise the
// music player will handle them, which would be confusing.)
abortBroadcast();
}
}
}
}
private void handleServiceStateChanged(Intent intent) {
/**
* This used to handle updating EriTextWidgetProvider this routine
* and and listening for ACTION_SERVICE_STATE_CHANGED intents could
* be removed. But leaving just in case it might be needed in the near
* future.
*/
// If service just returned, start sending out the queued messages
ServiceState ss = ServiceState.newFromBundle(intent.getExtras());
boolean hasService = true;
boolean isCdma = false;
String eriText = "";
if (ss != null) {
int state = ss.getState();
switch (state) {
case ServiceState.STATE_OUT_OF_SERVICE:
case ServiceState.STATE_POWER_OFF:
hasService = false;
break;
}
} else {
hasService = false;
}
}
}
| [
"danny@35g.tw"
] | danny@35g.tw |
c4c6bf15e0cac4c13b2567a85883bafbd6ff568a | b92b76428acdab2121f18e1b6e5038431e51ab21 | /designpattern/src/main/java/designpattern/visitor/Element.java | a4de55fc3546070807fa9e8b08f70ccdd4019e49 | [] | no_license | DeanJons99/springbootlearn | 98d799ac1d9d6aad8f1d19dbc46b40ac0facf390 | acfa258abe0ef32896f3f860503cb5ad3bea5a04 | refs/heads/master | 2021-03-20T11:06:56.421633 | 2020-03-14T03:14:48 | 2020-03-14T03:14:48 | 247,202,270 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 95 | java | package designpattern.visitor;
public interface Element {
void accept(Visitor visitor);
}
| [
"liuqiang@wecash.net"
] | liuqiang@wecash.net |
7bf8117b5f0b8cb491afc91e7a5725a77bf72896 | e5f7709425ce1308fe5c41087099bf29700bf9a7 | /src/main/java/mca/packets/PacketOpenVillagerPrompt.java | d6aa91873d56611719666ed77218571c8acf8ad6 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | Tencao/minecraft-comes-alive | d1c622622e89a554833195ae04f643c89cb7853f | 9fde66000368411440da60cef6c2b436eec97c01 | refs/heads/master | 2021-01-11T14:45:50.414992 | 2016-08-16T18:35:45 | 2016-08-16T18:35:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,810 | java | package mca.packets;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import mca.client.gui.GuiVillagerPrompt;
import mca.entity.EntityHuman;
import mca.enums.EnumInteraction;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import radixcore.packets.AbstractPacket;
public class PacketOpenVillagerPrompt extends AbstractPacket implements IMessage, IMessageHandler<PacketOpenVillagerPrompt, IMessage>
{
private int senderId;
private int targetId;
private int interactionId;
public PacketOpenVillagerPrompt()
{
//Required
}
public PacketOpenVillagerPrompt(EntityPlayer player, EntityHuman human, EnumInteraction interaction)
{
this.senderId = player.getEntityId();
this.targetId = human.getEntityId();
this.interactionId = interaction.getId();
}
@Override
public void fromBytes(ByteBuf byteBuf)
{
senderId = byteBuf.readInt();
targetId = byteBuf.readInt();
interactionId = byteBuf.readInt();
}
@Override
public void toBytes(ByteBuf byteBuf)
{
byteBuf.writeInt(senderId);
byteBuf.writeInt(targetId);
byteBuf.writeInt(interactionId);
}
@SideOnly(Side.CLIENT)
@Override
public IMessage onMessage(PacketOpenVillagerPrompt packet, MessageContext context)
{
EntityPlayer player = this.getPlayer(context);
EntityHuman human = (EntityHuman) player.worldObj.getEntityByID(packet.targetId);
EnumInteraction interaction = EnumInteraction.fromId(packet.interactionId);
Minecraft.getMinecraft().displayGuiScreen(new GuiVillagerPrompt(player, human, interaction));
return null;
}
}
| [
"wildbamaboy@gmail.com"
] | wildbamaboy@gmail.com |
75391fc2a7c35330ef8f9e92f5e512eff238e681 | b63de905bc6f1cf994ee08cd054b2aaa99136726 | /Java/src/TestingSystem_Assignment_4/com/vti/entity/Exer6/Manager.java | 9866d01171d7407e55a474b47f7f80ff0057d29b | [] | no_license | vuthanhtrung666/Rocket_11 | 0b1bf2304fc5f9e083de17df0f51575e1e2a8239 | ed376c3be0e672b60dbab43c7fe143f9a5e4e3e7 | refs/heads/master | 2023-04-28T23:07:37.924173 | 2021-05-14T00:53:10 | 2021-05-14T00:53:10 | 343,615,692 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 264 | java | package TestingSystem_Assignment_4.com.vti.entity.Exer6;
public class Manager extends User {
public Manager(String name, double salaryRatio) {
super(name, salaryRatio);
}
@Override
public double calculatePay() {
return getSalaryRatio()*520;
}
}
| [
"vuthanhtrung666@gmail.com"
] | vuthanhtrung666@gmail.com |
53eab8bb6483e31a899697d6472f4f02f3d39729 | 0a5c4203705d619ff16a6dffea62521483d8a820 | /src/main/java/kThread/ThreadExercise1.java | e9398e9be720b3b853bd8f7c4e392968b2b5f37f | [] | no_license | Zukoss/UdemyJavaBasics | 0b886985bcf76edd416537ac0beb6cd1e944d8fa | d5e71a096ad9fc2b342a5d34b6ac5cc4de98a49f | refs/heads/master | 2023-02-28T07:35:37.313106 | 2021-02-04T16:38:27 | 2021-02-04T16:38:27 | 326,973,903 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 714 | java | package kThread;
public class ThreadExercise1 {
public static void main(String[] args) {
Thread thread = new Thread(new ThreadTimeMeter() {
@Override
public void run() {
try {
Thread.sleep(3000); } catch (InterruptedException e) { }
System.out.println("This information was writen out from anonymous class and thread.");
}
});
thread.start();
}
}
// Drugi sposób bez przypisania do obiektu!
// new Thread(new Runnable() {
// @Override
// public void run() {
// System.out.println("This information was writen out from anonymous class and thread.");
// }
// }).start();
| [
"pawelzukowski22@gmail.com"
] | pawelzukowski22@gmail.com |
52d0976d9bede8017666a9b58a331fb983282517 | be0fc7fb0e074bba519f1995ccedab153124cf43 | /app/src/main/java/com/max/explo/bibo/ui/camera/CameraSourcePreview.java | 1caf44b21d70b31ea083b8eaa7822d67efdb6936 | [] | no_license | DanielTatarkin/BiBo2 | feec6bebdcf607777aae307432e4e51b154e770c | 52874debaf57c13737d4f82c3bfcb8ab0d441941 | refs/heads/master | 2020-03-07T16:54:46.371616 | 2018-04-01T17:49:20 | 2018-04-01T17:49:20 | 127,597,104 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 7,146 | java | /*
* Copyright (C) The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.max.explo.bibo.ui.camera;
import android.Manifest;
import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.RequiresPermission;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import com.google.android.gms.common.images.Size;
import java.io.IOException;
public class CameraSourcePreview extends ViewGroup {
private static final String TAG = "CameraSourcePreview";
private Context mContext;
private SurfaceView mSurfaceView;
private boolean mStartRequested;
private boolean mSurfaceAvailable;
private CameraSource mCameraSource;
private GraphicOverlay mOverlay;
public CameraSourcePreview(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mStartRequested = false;
mSurfaceAvailable = false;
mSurfaceView = new SurfaceView(context);
mSurfaceView.getHolder().addCallback(new SurfaceCallback());
addView(mSurfaceView);
}
@RequiresPermission(Manifest.permission.CAMERA)
public void start(CameraSource cameraSource) throws IOException, SecurityException {
if (cameraSource == null) {
stop();
}
mCameraSource = cameraSource;
if (mCameraSource != null) {
mStartRequested = true;
startIfReady();
}
}
@RequiresPermission(Manifest.permission.CAMERA)
public void start(CameraSource cameraSource, GraphicOverlay overlay) throws IOException, SecurityException {
mOverlay = overlay;
start(cameraSource);
}
public void stop() {
if (mCameraSource != null) {
mCameraSource.stop();
}
}
public void release() {
if (mCameraSource != null) {
mCameraSource.release();
mCameraSource = null;
}
}
@RequiresPermission(Manifest.permission.CAMERA)
private void startIfReady() throws IOException, SecurityException {
if (mStartRequested && mSurfaceAvailable) {
mCameraSource.start(mSurfaceView.getHolder());
if (mOverlay != null) {
Size size = mCameraSource.getPreviewSize();
int min = Math.min(size.getWidth(), size.getHeight());
int max = Math.max(size.getWidth(), size.getHeight());
if (isPortraitMode()) {
// Swap width and height sizes when in portrait, since it will be rotated by
// 90 degrees
mOverlay.setCameraInfo(min, max, mCameraSource.getCameraFacing());
} else {
mOverlay.setCameraInfo(max, min, mCameraSource.getCameraFacing());
}
mOverlay.clear();
}
mStartRequested = false;
}
}
private class SurfaceCallback implements SurfaceHolder.Callback {
@Override
public void surfaceCreated(SurfaceHolder surface) {
mSurfaceAvailable = true;
try {
startIfReady();
} catch (SecurityException se) {
Log.e(TAG,"Do not have permission to start the camera", se);
} catch (IOException e) {
Log.e(TAG, "Could not start camera source.", e);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder surface) {
mSurfaceAvailable = false;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int previewWidth = 320;
int previewHeight = 240;
if (mCameraSource != null) {
Size size = mCameraSource.getPreviewSize();
if (size != null) {
previewWidth = size.getWidth();
previewHeight = size.getHeight();
}
}
// Swap width and height sizes when in portrait, since it will be rotated 90 degrees
if (isPortraitMode()) {
int tmp = previewWidth;
previewWidth = previewHeight;
previewHeight = tmp;
}
final int viewWidth = right - left;
final int viewHeight = bottom - top;
int childWidth;
int childHeight;
int childXOffset = 0;
int childYOffset = 0;
float widthRatio = (float) viewWidth / (float) previewWidth;
float heightRatio = (float) viewHeight / (float) previewHeight;
// To fill the view with the camera preview, while also preserving the correct aspect ratio,
// it is usually necessary to slightly oversize the child and to crop off portions along one
// of the dimensions. We scale up based on the dimension requiring the most correction, and
// compute a crop offset for the other dimension.
if (widthRatio > heightRatio) {
childWidth = viewWidth;
childHeight = (int) ((float) previewHeight * widthRatio);
childYOffset = (childHeight - viewHeight) / 2;
} else {
childWidth = (int) ((float) previewWidth * heightRatio);
childHeight = viewHeight;
childXOffset = (childWidth - viewWidth) / 2;
}
for (int i = 0; i < getChildCount(); ++i) {
// One dimension will be cropped. We shift child over or up by this offset and adjust
// the size to maintain the proper aspect ratio.
getChildAt(i).layout(
-1 * childXOffset, -1 * childYOffset,
childWidth - childXOffset, childHeight - childYOffset);
}
try {
startIfReady();
} catch (SecurityException se) {
Log.e(TAG,"Do not have permission to start the camera", se);
} catch (IOException e) {
Log.e(TAG, "Could not start camera source.", e);
}
}
private boolean isPortraitMode() {
int orientation = mContext.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
return false;
}
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
return true;
}
Log.d(TAG, "isPortraitMode returning false by default");
return false;
}
}
| [
"danieltatarkin@gmail.com"
] | danieltatarkin@gmail.com |
1a6509042ee4fd2c4ef060817c97b5858a851dcc | 324220b6f8c43714615d4acfe521db5ba295f039 | /src/main/java/com/forgestorm/rpg/commands/Monster.java | 80c02c54a29f7dbadc603f8f8b3e418cc46d2174 | [] | no_license | unenergizer/ForgeStorm-RPG | 1524390ef5d1d875f5578024c510001fbe51944a | 6fc23b26daf27adf08f89bdd2f205446454f6661 | refs/heads/master | 2022-09-02T06:25:07.669996 | 2016-10-23T20:27:39 | 2016-10-23T20:27:39 | 71,727,805 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 928 | java | package com.forgestorm.rpg.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.forgestorm.rpg.RPG;
import com.forgestorm.rpg.profile.monster.MonsterLoader;
import com.forgestorm.rpg.profile.monster.MonsterSaver;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class Monster implements CommandExecutor {
private final RPG PLUGIN;
@Override
public boolean onCommand(CommandSender commandSender, Command command, String label, String[] args) {
//monster save monsterType name level health
Player player = (Player) commandSender;
if (args.length == 5) {
new MonsterSaver().entitySaver(args[1], args[2], Integer.parseInt(args[3]), Integer.parseInt(args[4]), "owner", "loot");
new MonsterLoader(PLUGIN).getConfig(args[2], player.getLocation());
}
return false;
}
} | [
"unenergizer@gmail.com"
] | unenergizer@gmail.com |
ef853841f48d03c7e982d1aa094f78c6bfd4174b | ed3cb95dcc590e98d09117ea0b4768df18e8f99e | /project_1_2/src/b/i/b/h/Calc_1_2_18179.java | 2d99d056d28bb33e6ce74bc1d62ebcfd7eed7230 | [] | no_license | chalstrick/bigRepo1 | ac7fd5785d475b3c38f1328e370ba9a85a751cff | dad1852eef66fcec200df10083959c674fdcc55d | refs/heads/master | 2016-08-11T17:59:16.079541 | 2015-12-18T14:26:49 | 2015-12-18T14:26:49 | 48,244,030 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 134 | java | package b.i.b.h;
public class Calc_1_2_18179 {
/** @return the sum of a and b */
public int add(int a, int b) {
return a+b;
}
}
| [
"christian.halstrick@sap.com"
] | christian.halstrick@sap.com |
da970908190571376a6520bc6da76a5337f93d4a | 1e713abe05707d31e35935f926e97a03c66939a7 | /clara-core/src/main/java/edu/uams/clara/core/dao/thing/AbstractThingDao.java | 51a04da1a759b253bcbe9771033060c57043fb90 | [] | no_license | bianjiang/clara | b622c475a0aaaf21b150cfa8e2e4e898b510bfe1 | 1d39bb7af2b6fbcd7a8a2655036dd0ef6ffc4fba | refs/heads/master | 2020-05-18T04:15:27.034690 | 2015-06-30T15:43:47 | 2015-06-30T15:43:47 | 15,677,823 | 2 | 0 | null | 2014-02-05T14:49:36 | 2014-01-06T15:44:57 | JavaScript | UTF-8 | Java | false | false | 1,676 | java | package edu.uams.clara.core.dao.thing;
import java.util.List;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import edu.uams.clara.core.dao.AbstractDomainDao;
import edu.uams.clara.core.domain.thing.AbstractThing;
public class AbstractThingDao<T extends AbstractThing> extends
AbstractDomainDao<T> {
private static final long serialVersionUID = -256074469898692740L;
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public List<T> listThings() {
Query query = getEntityManager().createQuery(
"SELECT o FROM " + this.getDomainClassName()
+ " o WHERE o.retired = :retired ORDER BY value ASC")
.setParameter("retired", Boolean.FALSE);
return (List<T>) query.getResultList();
}
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public List<T> listUnapprovedThingsByType() {
Query query = getEntityManager().createQuery(
"SELECT o FROM " + this.getDomainClassName()
+ " o WHERE o.retired = :retired"
+ " AND o.isApproved = 0 ORDER BY value ASC")
.setParameter("retired", Boolean.FALSE);
return (List<T>) query.getResultList();
}
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public List<T> searchByName(String name) {
Query query = getEntityManager()
.createQuery(
"SELECT o FROM "
+ this.getDomainClassName()
+ " o WHERE o.retired = :retired AND o.description LIKE :name ORDER BY value ASC")
.setParameter("retired", Boolean.FALSE)
.setParameter("name", "%" + name + "%");
return (List<T>) query.getResultList();
}
}
| [
"jbian@uams.edu"
] | jbian@uams.edu |
c00ac6b3b59ccb3d0a0349d7d010b03497443e9d | d1c16a38656bd0d7ddd22a8af3638da242a0c613 | /ShareLib/src/com/gameco/moves/EndSignal.java | f21074f962b182c617a8cb6479759d15bcb86975 | [] | no_license | tedmorning/game-ecosphere | 4fb3b8a7c603b94a13429b781bd73c10e663890a | 6640a5c37139c32ec9941bd83efda8a5ccac2a49 | refs/heads/master | 2020-03-14T04:50:59.038141 | 2018-04-28T23:25:49 | 2018-04-28T23:25:49 | 131,451,133 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 713 | java | package com.gameco.moves;
import java.time.Duration;
import java.util.List;
import com.gameco.GameMove;
import com.gameco.User;
/**
* Notify about ending of game. Has lists of winners and losers.
*/
public class EndSignal extends GameMove {
protected List<User> winners;
protected List<User> losers;
public EndSignal(int num, Duration timePassed) {
super(num, timePassed);
this.winners = null;
this.losers = null;
}
public void setWinners(List<User> winners) {
this.winners = winners;
}
public void setLosers(List<User> losers) {
this.losers = losers;
}
public List<User> getWinners() {
return this.winners;
}
public List<User> getLosers() {
return this.losers;
}
}
| [
"development@daybreak.coffee"
] | development@daybreak.coffee |
4bb5f65a54f56e46a379f341e9554ce19c375d37 | 71cbe971466caf20ef665f690bac9037ad4afae4 | /sla-core/sla-tools/src/main/java/eu/atos/sla/parser/data/Penalty.java | 915030621742d57c7baf87f5e91d56a8015e024f | [
"Apache-2.0"
] | permissive | angelolencina/ops.Sla-framework | 333a2292a8c858440d8109fcf2e2b7e2e50b50a7 | 776663401292c603fab4287f47998ea65d2a31eb | refs/heads/master | 2023-08-13T13:39:09.538978 | 2016-05-05T12:09:36 | 2016-05-05T12:09:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,831 | java | package eu.atos.sla.parser.data;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import eu.atos.sla.datamodel.ICompensation.IPenalty;
import eu.atos.sla.datamodel.ICompensationDefinition.IPenaltyDefinition;
import eu.atos.sla.parser.DateTimeDeserializerJSON;
import eu.atos.sla.parser.DateTimeSerializerJSON;
/**
* A POJO Object that stores all the information from a Penalty
*
* @author rsosa
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "penalty")
public class Penalty {
@XmlElement(name = "uuid")
private String uuid;
@XmlElement(name = "agreement_id")
private String agreementId;
@JsonSerialize(using=DateTimeSerializerJSON.class)
@JsonDeserialize(using=DateTimeDeserializerJSON.class)
@XmlElement(name = "datetime")
private Date datetime;
@XmlElement(name = "definition")
private eu.atos.sla.parser.data.wsag.custom.Penalty definition;
public Penalty() {
}
public Penalty(IPenalty penalty) {
this.uuid = penalty.getUuid();
this.agreementId = penalty.getAgreementId();
this.datetime = penalty.getDatetime();
IPenaltyDefinition def = penalty.getDefinition();
this.definition = new eu.atos.sla.parser.data.wsag.custom.Penalty(
def.getAction(), def.getValueExpression(), def.getValueUnit(), def.getValidity());
}
public String getUuid() {
return uuid;
}
public String getAgreementId() {
return agreementId;
}
public Date getDatetime() {
return datetime;
}
public eu.atos.sla.parser.data.wsag.custom.Penalty getDefinition() {
return definition;
}
}
| [
"roman.sosa@atos.net"
] | roman.sosa@atos.net |
8f3e861a74a8e58ba0590ff397ce0df1118ae908 | 777a5e2c6c0436e764478cfaf36786b17bc41522 | /salesdemo/src/main/java/com/sales/app/shared/appbasicsetup/usermanagement/LoginSession.java | 179af2a4d81aae0523983441ab00ed224c181bb0 | [] | no_license | Alogrhythm/Sales-Demo | d921f470fe201b4f434824b712684787a3ce66dc | 224d1b0ce61104590feb6345f8fb67b79d4dc3e6 | refs/heads/master | 2021-01-20T17:32:49.824116 | 2016-06-16T06:07:45 | 2016-06-16T06:07:45 | 61,266,318 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,872 | java | package com.sales.app.shared.appbasicsetup.usermanagement;
import com.athena.server.pluggable.interfaces.CommonEntityInterface;
import com.sales.app.config.annotation.Complexity;
import com.sales.app.config.annotation.SourceCodeAuthorClass;
import com.spartan.server.interfaces.LoginSessionInterface;
import java.io.Serializable;
import java.util.Comparator;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.Cache;
import org.eclipse.persistence.annotations.CacheType;
import org.eclipse.persistence.config.CacheIsolationType;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.sql.Timestamp;
import com.athena.config.jsonHandler.CustomSqlTimestampJsonSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.athena.config.jsonHandler.CustomSqlTimestampJsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import javax.validation.constraints.Min;
import javax.validation.constraints.Max;
import javax.persistence.Transient;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import com.athena.server.pluggable.utils.helper.EntityValidatorHelper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.Version;
import com.sales.app.shared.EntityAudit;
import javax.persistence.Embedded;
import com.sales.app.shared.SystemInfo;
import java.lang.Override;
@Table(name = "ast_LoginSession_T")
@Entity
@Cache(type = CacheType.CACHE, isolation = CacheIsolationType.ISOLATED)
@SourceCodeAuthorClass(createdBy = "john.doe", updatedBy = "john.doe", versionNumber = "3", comments = "LoginSession", complexity = Complexity.LOW)
public class LoginSession implements Serializable, CommonEntityInterface, LoginSessionInterface, Comparator<LoginSession> {
@Column(name = "AppServerSessionId")
@JsonProperty("appServerSessionId")
@NotNull
@Size(min = 12, max = 256)
private String appServerSessionId;
@Column(name = "loginTime")
@JsonProperty("loginTime")
@NotNull
@JsonSerialize(using = CustomSqlTimestampJsonSerializer.class)
@JsonDeserialize(using = CustomSqlTimestampJsonDeserializer.class)
private Timestamp loginTime;
@Column(name = "lastAccessTime")
@JsonProperty("lastAccessTime")
@JsonSerialize(using = CustomSqlTimestampJsonSerializer.class)
@JsonDeserialize(using = CustomSqlTimestampJsonDeserializer.class)
private Timestamp lastAccessTime;
@Column(name = "logoutTime")
@JsonProperty("logoutTime")
@NotNull
@JsonSerialize(using = CustomSqlTimestampJsonSerializer.class)
@JsonDeserialize(using = CustomSqlTimestampJsonDeserializer.class)
private Timestamp logoutTime;
@Column(name = "clientIPAddress")
@JsonProperty("clientIPAddress")
@NotNull
@Size(min = 0, max = 128)
private String clientIPAddress;
@Column(name = "clientIPAddressInt")
@JsonProperty("clientIPAddressInt")
@Min(0)
private Long clientIPAddressInt;
@Column(name = "clientNetworkAddress")
@JsonProperty("clientNetworkAddress")
@Min(0)
@Max(11)
private Integer clientNetworkAddress;
@Column(name = "clientBrowser")
@JsonProperty("clientBrowser")
@NotNull
@Size(min = 0, max = 256)
private String clientBrowser;
@Column(name = "sessionData")
@JsonProperty("sessionData")
@Size(min = 0, max = 5120)
private String sessionData;
@Transient
private String primaryKey;
@Id
@Column(name = "AppSessionId")
@JsonProperty("appSessionId")
@GeneratedValue(generator = "UUIDGenerator")
@Size(min = 12, max = 256)
private String appSessionId;
@Column(name = "userId")
@JsonProperty("userId")
private String userId;
@Transient
@JsonIgnore
private EntityValidatorHelper<Object> entityValidator;
@Version
@Column(name = "versionId")
@JsonProperty("versionId")
private int versionId;
@Embedded
@JsonIgnore
private EntityAudit entityAudit = new EntityAudit();
@Embedded
private SystemInfo systemInfo = new SystemInfo();
@Transient
private String primaryDisplay;
public String getAppServerSessionId() {
return appServerSessionId;
}
public void setAppServerSessionId(String _appServerSessionId) {
if (_appServerSessionId != null) {
this.appServerSessionId = _appServerSessionId;
}
}
public Timestamp getLoginTime() {
return loginTime;
}
public void setLoginTime(Timestamp _loginTime) {
if (_loginTime != null) {
this.loginTime = _loginTime;
}
}
public Timestamp getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(Timestamp _lastAccessTime) {
this.lastAccessTime = _lastAccessTime;
}
public Timestamp getLogoutTime() {
return logoutTime;
}
public void setLogoutTime(Timestamp _logoutTime) {
if (_logoutTime != null) {
this.logoutTime = _logoutTime;
}
}
public String getClientIPAddress() {
return clientIPAddress;
}
public void setClientIPAddress(String _clientIPAddress) {
if (_clientIPAddress != null) {
this.clientIPAddress = _clientIPAddress;
}
}
public Long getClientIPAddressInt() {
return clientIPAddressInt;
}
public void setClientIPAddressInt(Long _clientIPAddressInt) {
this.clientIPAddressInt = _clientIPAddressInt;
}
public Integer getClientNetworkAddress() {
return clientNetworkAddress;
}
public void setClientNetworkAddress(Integer _clientNetworkAddress) {
this.clientNetworkAddress = _clientNetworkAddress;
}
public String getClientBrowser() {
return clientBrowser;
}
public void setClientBrowser(String _clientBrowser) {
if (_clientBrowser != null) {
this.clientBrowser = _clientBrowser;
}
}
public String getSessionData() {
return sessionData;
}
public void setSessionData(String _sessionData) {
this.sessionData = _sessionData;
}
public String getPrimaryKey() {
return appSessionId;
}
public void setPrimaryKey(String _primaryKey) {
this.primaryKey = _primaryKey;
}
public String _getPrimarykey() {
return appSessionId;
}
public String getAppSessionId() {
return appSessionId;
}
public void setAppSessionId(String _appSessionId) {
this.appSessionId = _appSessionId;
}
public String getUserId() {
return userId;
}
public void setUserId(String _userId) {
this.userId = _userId;
}
public int getVersionId() {
return versionId;
}
public void setVersionId(int _versionId) {
this.versionId = _versionId;
}
public void setPrimaryDisplay(String _primaryDisplay) {
this.primaryDisplay = _primaryDisplay;
}
public SystemInfo getSystemInfo() {
return systemInfo;
}
public void setSystemInfo(SystemInfo _systemInfo) {
this.systemInfo = _systemInfo;
}
@JsonIgnore
public boolean isHardDelete() {
if (this.systemInfo == null) {
this.systemInfo = new SystemInfo();
}
if (this.systemInfo.getActiveStatus() == -1) {
return true;
} else {
return false;
}
}
@JsonIgnore
@Override
public boolean isValid() throws SecurityException {
boolean isValid = false;
if (this.entityValidator != null) {
isValid = this.entityValidator.validateEntity(this);
this.systemInfo.setEntityValidated(true);
} else {
throw new java.lang.SecurityException();
}
return isValid;
}
@Override
public void setEntityValidator(EntityValidatorHelper<Object> _validateFactory) {
this.entityValidator = _validateFactory;
}
@Override
public void setEntityAudit(int customerId, String userId, RECORD_TYPE recordType) {
System.out.println("Setting logged in user info for " + recordType);
if (entityAudit == null) {
entityAudit = new EntityAudit();
}
if (recordType == RECORD_TYPE.ADD) {
this.entityAudit.setCreatedBy(userId);
this.entityAudit.setUpdatedBy(userId);
} else {
this.entityAudit.setUpdatedBy(userId);
}
setSystemInformation(recordType);
}
@Override
public void setEntityAudit(int customerId, String userId) {
if (entityAudit == null) {
entityAudit = new EntityAudit();
}
if (getPrimaryKey() == null) {
this.entityAudit.setCreatedBy(userId);
this.entityAudit.setUpdatedBy(userId);
this.systemInfo.setActiveStatus(1);
} else {
this.entityAudit.setUpdatedBy(userId);
}
}
@JsonIgnore
public String getLoggedInUserInfo() {
String auditInfo = "";
if (this.entityAudit != null) {
auditInfo = entityAudit.toString();
}
return auditInfo;
}
@Override
@JsonIgnore
public void setSystemInformation(RECORD_TYPE recordType) {
if (systemInfo == null) {
systemInfo = new SystemInfo();
}
if (recordType == RECORD_TYPE.DELETE) {
this.systemInfo.setActiveStatus(0);
} else {
this.systemInfo.setActiveStatus(1);
}
}
@JsonIgnore
public void setSystemInformation(Integer activeStatus) {
this.systemInfo.setActiveStatus(activeStatus);
}
@JsonIgnore
public String getSystemInformation() {
String systemInfo = "";
if (this.systemInfo != null) {
systemInfo = systemInfo.toString();
}
return systemInfo;
}
@Override
@JsonIgnore
public void setSystemTxnCode(Integer transactionAccessCode) {
if (systemInfo == null) {
systemInfo = new SystemInfo();
}
this.systemInfo.setTxnAccessCode(transactionAccessCode);
}
@Override
public int compare(LoginSession object1, LoginSession object2) {
return 0;
}
public String getPrimaryDisplay() {
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append((appServerSessionId == null ? " " : appServerSessionId) + ",");
sb.append((loginTime == null ? " " : loginTime) + ",");
sb.append((lastAccessTime == null ? " " : lastAccessTime) + ",");
sb.append((logoutTime == null ? " " : logoutTime));
return sb.toString();
}
public String toString() {
return getPrimaryDisplay();
}
public int hashCode() {
if (appSessionId == null) {
return super.hashCode();
} else {
return appSessionId.hashCode();
}
}
public boolean equals(Object obj) {
try {
com.sales.app.shared.appbasicsetup.usermanagement.LoginSession other = (com.sales.app.shared.appbasicsetup.usermanagement.LoginSession) obj;
if (appSessionId == null) {
return false;
} else if (!appSessionId.equals(other.appSessionId)) {
return false;
}
} catch (java.lang.Exception ignore) {
return false;
}
return true;
}
@JsonIgnore
@Override
public boolean isEntityValidated() {
return this.systemInfo.isEntityValidated();
}
@Override
public Integer getActiveStatus() {
return this.systemInfo.getActiveStatus();
}
}
| [
"applifire@3899864709f7"
] | applifire@3899864709f7 |
4f743cfac04c8c88086966b55dd44417e70d46f7 | 23ec52180e445c39a0b357d5b3a99154ba681ed7 | /DesignPatternJava/src/main/java/BehavioralPatterns/Command/sample1/Barbecuer.java | cb5bc894a2a325c5fc01fbb1ff55252ef18e4e9a | [] | no_license | pisces312/MyJavaProjects | 1408c5f33f1f39fc3929ebe34d39b6bcd6a5d166 | 0529ba813350e710d8aaca2d89c453570b244a64 | refs/heads/master | 2021-01-18T03:59:42.190929 | 2017-12-16T15:58:13 | 2017-12-16T15:58:13 | 84,271,420 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 410 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BehavioralPatterns.Command.sample1;
/**
*接收者,实现所有命令的具体动作
* @author pisces312
*/
public class Barbecuer {
public void bakeMutton(){
System.out.println("烤羊肉");
}
public void bakeChickenWing(){
System.out.println("烤鸡翅");
}
}
| [
"lee.ni@emc.com"
] | lee.ni@emc.com |
c4fe6920ecb59a94ee3bdebaad62437f4767f13a | 39ad5947c15ec725fe2f1c62e36b3c79f4c529fa | /stamppy/stamppyProject-businessLogic/src/main/java/org/stamppyProject/businessLogic/reports/dto/SalesJson.java | d0f25d18e3ab968c97fab6e863b0f43efb0f5de2 | [] | no_license | miso4204/Grupo03 | ad9105c146a9362a7f7f571212e4ae6293eeb8e5 | 0581df697e8a826a47942ec67719b84419b73581 | refs/heads/master | 2020-06-03T10:23:33.351985 | 2015-05-12T06:02:01 | 2015-05-12T06:02:01 | 30,677,335 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 656 | java | package org.stamppyProject.businessLogic.reports.dto;
import org.stamppyProject.businessLogic.business.stamp.dto.StampJson;
public class SalesJson {
private Integer numberSales;
private StampJson stamp;
/**
* @return the numberSales
*/
public Integer getNumberSales() {
return numberSales;
}
/**
* @param numberSales the numberSales to set
*/
public void setNumberSales(Integer numberSales) {
this.numberSales = numberSales;
}
/**
* @return the stamp
*/
public StampJson getStamp() {
return stamp;
}
/**
* @param stamp the stamp to set
*/
public void setStamp(StampJson stamp) {
this.stamp = stamp;
}
}
| [
"ms.lancheros10@uniandes.edu.co"
] | ms.lancheros10@uniandes.edu.co |
1034f73f49206cb5056ade2b8441c6d0ad70bb82 | ac2aaee34222249197534266f87edabdf346b066 | /src/com/elementarynl/event/ElementaryListener.java | 3d1d0a95672945bbb8588d9a3f2e6d3662a7c4da | [
"MIT"
] | permissive | elliot5/ElementaryNL | a5514c7dd94550342773817723b4036edb572f20 | 0db6f191cfa46f23025bcb058cd3410747917ced | refs/heads/master | 2020-04-05T07:26:21.516630 | 2018-11-11T10:47:50 | 2018-11-11T10:47:50 | 156,675,602 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,680 | java | /*
*
* MIT License
*
* Copyright (c) 2018 Elliot Bewey
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.elementarynl.event;
import com.elementarynl.network.worker.NetworkWorker;
import java.net.DatagramPacket;
public class ElementaryListener {
public synchronized void onReceive(final NetworkWorker worker, final DatagramPacket packet) {}
public synchronized void onSent(final NetworkWorker worker, final OutcomeState state) {}
public synchronized void onBind(final NetworkWorker worker, final OutcomeState state) {}
public synchronized void onConnect(final NetworkWorker worker, final OutcomeState state) {}
}
| [
"elliotbewey@yahoo.co.uk"
] | elliotbewey@yahoo.co.uk |
55a3391986906bc08b8b74f13e9f98bb8c003525 | 74c6bff136291d1c1e2c63679b6e2ba69b1fc851 | /src/Windows/win1/textDemo5.java | c3391cf5900365fe306a13832e5fd14237e2c0ee | [] | no_license | aurorawill/HelloWorld | 648a9eac5e0a62adee3ca60ccc4ee4ea67fe944f | 9399f9c97fd4566ffd51bca4559cfeb3840af5a6 | refs/heads/master | 2022-11-06T15:43:37.222091 | 2020-06-19T09:51:23 | 2020-06-19T09:51:23 | 273,459,250 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 613 | java | package Windows.win1;
import javax.swing.*;
public class textDemo5 {
public static void main(String args[]){
JFrame f1=new JFrame("窗体");
JTextField t1=new JTextField();
JTextArea t2=new JTextArea();
//设置组件位置和大小,参数顺序为对应窗口的x,y坐标,对应组件的宽和高
t1.setBounds(50,50,200,30);
t2.setBounds(50,100,200,100);
f1.add(t1);
f1.add(t2);
//取消布局管理,设置窗体大小,显示窗体
f1.setLayout(null);
f1.setSize(300,300);
f1.setVisible(true);
}
}
| [
"2499587196@qq.com"
] | 2499587196@qq.com |
cd909d225369cc318ca50adbfa03eeacc60f9989 | 974980834eb79e4d333a50d4d874c1fd95d747e2 | /src/main/java/com/exam/yiyou/examadmin/repository/mapper/RoleMapper.java | 120efa0596c22d89417f70b85fcba3d396b2c428 | [
"Apache-2.0"
] | permissive | LaoKpa/exam-admin | 66d31cb6465819026579c4a2502b0b625702779d | 67576d5db9130319b0d3aa0d51861e76a78aad5a | refs/heads/master | 2023-03-15T14:37:51.803480 | 2018-11-26T15:09:55 | 2018-11-26T15:09:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 859 | java | package com.exam.yiyou.examadmin.repository.mapper;
import com.exam.yiyou.examadmin.repository.model.Role;
import com.exam.yiyou.examadmin.repository.model.RoleExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface RoleMapper {
int countByExample(RoleExample example);
int deleteByExample(RoleExample example);
int deleteByPrimaryKey(Integer id);
int insert(Role record);
int insertSelective(Role record);
List<Role> selectByExample(RoleExample example);
Role selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Role record, @Param("example") RoleExample example);
int updateByExample(@Param("record") Role record, @Param("example") RoleExample example);
int updateByPrimaryKeySelective(Role record);
int updateByPrimaryKey(Role record);
} | [
"lailesy@163.com"
] | lailesy@163.com |
f6d697f04bc756204d64a90c7777e26f6a0e481c | c056742be2f8db76303c0bd30be76b6a00fe96b7 | /lang_interface/java/com/intel/daal/algorithms/decision_forest/regression/training/TrainingMethod.java | 775572bd82a00b41d83b5e16ea58b50ebe8535fb | [
"Intel",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"MIT",
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Vika-F/daal | 232de182ea4304ac49f9637efad09b4e08545ceb | 53076ea8fa9e64edc7440f989f8e150ec21e83d5 | refs/heads/master | 2023-08-22T07:14:46.157341 | 2020-03-13T09:28:48 | 2020-03-13T09:28:48 | 224,593,020 | 1 | 0 | Apache-2.0 | 2023-09-13T09:54:30 | 2019-11-28T07:19:00 | C++ | UTF-8 | Java | false | false | 1,956 | java | /* file: TrainingMethod.java */
/*******************************************************************************
* Copyright 2014-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/**
* @defgroup decision_forest_regression_training Training
* @brief Contains classes for decision forest regression models training
* @ingroup decision_forest_regression
* @{
*/
package com.intel.daal.algorithms.decision_forest.regression.training;
/**
* <a name="DAAL-CLASS-ALGORITHMS__DECISION_FOREST__REGRESSION__TRAINING__TRAININGMETHOD"></a>
* @brief Available methods for training decision forest regression models
*/
public final class TrainingMethod {
private int _value;
/**
* Constructs the training method object using the provided value
* @param value Value corresponding to the training method object
*/
public TrainingMethod(int value) {
_value = value;
}
/**
* Returns the value corresponding to the training method object
* @return Value corresponding to the training method object
*/
public int getValue() {
return _value;
}
private static final int defaultDenseId = 0;
/** Default method. Bagging, random choice of features, variance-based impurity. */
public static final TrainingMethod defaultDense = new TrainingMethod(defaultDenseId);
}
/** @} */
| [
"nikolay.a.petrov@intel.com"
] | nikolay.a.petrov@intel.com |
2e04d511269c5ade069a92a8adb680cf6afad30c | f44f47bd8e9eea330adc225ee3d1131c47baf752 | /Project1_MovieDetailScreen/app/src/main/java/org/techtown/moviedetailscreen/CommentItemView.java | 7a942fc43c0ecbdde4fafa244b1813e08c9f51dc | [] | no_license | hanbinchoi/android_practice | 559995fb329d0cfd344ec59d606dfd2c335542be | ee825fdbb12baa8ec84041875a794428a6ac973e | refs/heads/master | 2020-06-20T04:45:27.305411 | 2020-04-17T10:09:53 | 2020-04-17T10:09:53 | 196,998,764 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,349 | java | package org.techtown.moviedetailscreen;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
public class CommentItemView extends LinearLayout {
TextView userIdText;
TextView commentText;
RatingBar ratingBar;
public CommentItemView(Context context) {
super(context);
init(context);
}
public CommentItemView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.comment_item_view,this,true);
//리니어 레이아웃을 상속받앗으므로 여기에 뷰를 받을수있는거임
userIdText = (TextView)findViewById(R.id.userID);
commentText = (TextView)findViewById(R.id.comment);
ratingBar = (RatingBar)findViewById(R.id.ratingBar);
}
public void setUserID(String userID) {
userIdText.setText(userID);
}
public void setComment(String comment) {
commentText.setText(comment);
}
public void setRating(float rating){ ratingBar.setRating(rating); }
}
| [
"wkghskak@naver.com"
] | wkghskak@naver.com |
dd76056286741269ec7c05297fe23bbaf51bd83c | 6dc826e7d84fb07584ecb0f2b34836343106fdf6 | /src/org/accela/cellmatrix/strategy/PopuEvolveStrategy.java | 5fa067a6b6a5fece573237895cff14524dbe2027 | [
"MIT"
] | permissive | accelazh/CellMatrix | 47c6c8e48c008c9d5edbcbc621c7786aca2e608c | 00cefe65164181ad1f03c40e24be6c46f5fbb542 | refs/heads/master | 2021-01-21T05:00:06.821476 | 2014-06-15T06:01:36 | 2014-06-15T06:01:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,120 | java | package org.accela.cellmatrix.strategy;
import org.accela.cellmatrix.EvolveStrategy;
import org.accela.cellmatrix.CellMatrix.NineCells;
public class PopuEvolveStrategy implements EvolveStrategy {
@Override
public int nextState(NineCells cells) {
double val = cells.cells[1][1];
double avgVal = 0;
for (int i = 0; i < cells.cells.length; i++) {
for (int j = 0; j < cells.cells[i].length; j++) {
avgVal += cells.cells[i][j];
}
}
avgVal /= 9;
if (val <= 0 && cells.countNeighborPos > 2) {
val = avgVal * 2;
}
double b = 0.6;
double a = 1 + Math.random() * b - b / 2;
a = 1;
double deathRate = (100.0 / (avgVal + 0.01) + 1.0 / 100) / 100;
deathRate *= a;
double birthRate = 10.0 / 100;
birthRate *= a;
double pressureRate = avgVal / 200000;
pressureRate *= a;
double death = deathRate * val;
double birth = birthRate * val;
double pressure = pressureRate * val;
double punish = val >= 10000 ? val : 0;
int ret = (int) (val - death + birth - pressure - punish);
ret = ret >= 0 ? ret : 0;
return ret;
}
}
| [
"AC_Icarus@163.com"
] | AC_Icarus@163.com |
88a037321c0b6d162c66e5ef63d8113c06cf222a | b111b77f2729c030ce78096ea2273691b9b63749 | /oreilly-gradle-book-examples/testing-junitforkedthreads/src/test/java/org/gradle/example/simple/TestPerson110.java | 0cd96c446df610144942eed421cb3cbdeedc4587 | [] | no_license | WeilerWebServices/Gradle | a1a55bdb0dd39240787adf9241289e52f593ccc1 | 6ab6192439f891256a10d9b60f3073cab110b2be | refs/heads/master | 2023-01-19T16:48:09.415529 | 2020-11-28T13:28:40 | 2020-11-28T13:28:40 | 256,249,773 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 518 | java | package org.gradle.example.simple;
import org.gradle.example.simple.Person;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestPerson110 {
@Test
public void testPerson() {
Person p = new Person();
p.setAge(20);
p.setName("Fird Birfle");
p.setSalary(195750.22);
assertEquals(215325.242, p.calculateBonus(), 0.01);
assertEquals("The Honorable Fird Birfle", p.becomeJudge());
assertEquals(30, p.timeWarp());
p.wasteTime();
}
}
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
dadf8c2512ae2a9060f17e52fd14ad04f10632cd | 2a5e927110cc9d35024bdc7c2d8db38705d97e23 | /src/main/java/com/louis/service/CSVServiceImpl.java | 9f92aa3d9b5c4b7682fe6d7768911b4dbbadd7af | [] | no_license | liaowei0619/economic-crime-server | 0fa1ff4618c375356fc463bc3a158154fd34ead4 | e60bec65f8729c62e0a8dd120de7a6e55441b927 | refs/heads/master | 2021-07-01T03:55:46.959952 | 2017-09-21T07:06:15 | 2017-09-21T07:06:15 | 104,311,712 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,684 | java | package com.louis.service;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.louis.config.MYJZConfig;
import com.louis.controller.CSVController;
import com.louis.entity.Csvpartbase;
import com.louis.entity.FileTb;
import com.louis.exception.CustomException;
import com.louis.mapper.CsvpartbaseMapper;
import com.louis.mapper.FileTbMapper;
import com.louis.utilTools.DateUtils;
import com.louis.utilTools.EntityToCharArray;
import com.louis.utilTools.ResourceUtils;
import com.louis.utilTools.UUIDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
@Service(CSVServiceImpl.SERVICE_NAME)
public class CSVServiceImpl implements CSVService {
private static final Logger log = LoggerFactory.getLogger(CSVController.class);
public static final String SERVICE_NAME = "com.louis.service.CSVServiceImpl";
@Autowired
private CsvpartbaseMapper csvpartbaseMapper;
@Autowired
private FileTbMapper fileTbMapper;
public FileTb exportIpMac(String filePath) {
List<Csvpartbase> allcsv = csvpartbaseMapper.selectAll();
FileTb fileTb = null;
if (!allcsv.isEmpty()) {
fileTb = new FileTb();
for (Csvpartbase csv : allcsv) {
EntityToCharArray entityToCharArray = new EntityToCharArray();
String[] csvArray = entityToCharArray.entityToArray(csv);
// 定义一个CSV路径
try {
// 创建CSV写对象 例如:CsvWriter(文件路径,分隔符,编码格式);
String fileid = UUIDUtils.getUUID();
CsvWriter csvWriter = new CsvWriter(filePath + fileid + ".csv", ',', Charset.forName("UTF-8"));
// 写表头
String[] csvHeaders = MYJZConfig.CSV_HEADERS;
csvWriter.writeRecord(csvHeaders);
// 写内容
csvWriter.writeRecord(csvArray);
csvWriter.close();
fileTb.setRealPath(filePath);
fileTb.setCreateDate(DateUtils.getDate());
fileTb.setFileName(fileid);
fileTb.setFileUrl(ResourceUtils
.getProperty(MYJZConfig.URL_PATH)
+ MYJZConfig.FILE_LOCATION + UUIDUtils.getUUID() + ".csv");
fileTb.setFileType("csv");
} catch (IOException e) {
throw new CustomException("导出失败!");
}
}
}
return fileTb;
}
public Map<String, String> importIpMac(String path, MultipartFile[] files) {
String succcess_count = "0";
String fail_count = "";
/**
* 遍历索引的文件
*/
if (files.length >= 1) {
for (MultipartFile file : files) {
if (!file.isEmpty()) {
String originalName = file.getOriginalFilename();
int dotPosition = originalName.indexOf(".");
String fileType = null;
String filename = null;
if (dotPosition != -1) {
fileType = originalName.substring(
originalName.indexOf(".") + 1, originalName.length());
filename = UUIDUtils.getUUID() + "." + fileType;
} else {
filename = UUIDUtils.getUUID();
}
/**
* 读取文件内容
*/
try {
// 用来保存数据
ArrayList<String[]> csvFileList = new ArrayList<>();
// 定义一个CSV路径
// 创建CSV读对象 例如:CsvReader(文件路径,分隔符,编码格式);
CsvReader reader = new CsvReader(path + '/' + file.getOriginalFilename(), ',', Charset.forName("UTF-8"));
// 跳过表头 如果需要表头的话,这句可以忽略
reader.readHeaders();
// 逐行读入除表头的数据
while (reader.readRecord()) {
csvFileList.add(reader.getValues());
}
reader.close();
Csvpartbase csvpartbase = new Csvpartbase();
/* 遍历读取的CSV文件 */
for (int row = 0; row < csvFileList.size(); row++) {
// 取得第row行第0列的数据
csvpartbase.setId(csvFileList.get(row)[0]);
csvpartbase.setMac(csvFileList.get(row)[1]);
csvpartbase.setIp(csvFileList.get(row)[2]);
csvpartbase.setUpip(csvFileList.get(row)[3]);
csvpartbase.setUpname(csvFileList.get(row)[4]);
csvpartbase.setUpindex(csvFileList.get(row)[5]);
csvpartbase.setModifytime(csvFileList.get(row)[6]);
int count = csvpartbaseMapper.insertSelective(csvpartbase);
if (count == 1) {
succcess_count = String.valueOf(Integer.parseInt(succcess_count) + count);
} else {
if (fail_count.isEmpty()) {
fail_count = String.valueOf(row);
} else {
fail_count = fail_count + "、" + row;
}
}
}
/**
* 保存到文件导入表中
*/
FileTb upLoadFile = new FileTb();
upLoadFile.setFileId(UUIDUtils.getUUID());
upLoadFile.setFileName(filename);
upLoadFile.setFileType(fileType);
upLoadFile.setFileSize(file.getSize());
upLoadFile.setCreateDate(new Date());
upLoadFile.setFileUrl(ResourceUtils
.getProperty(MYJZConfig.URL_PATH)
+ MYJZConfig.FILE_LOCATION + filename);
upLoadFile.setRealPath(MYJZConfig.FILE_LOCATION
+ filename);
fileTbMapper.insertSelective(upLoadFile);
} catch (IOException e) {
throw new CustomException("导入异常!");
}
}
}
}
Map<String, String> res = new HashMap<>();
res.put("success", succcess_count);
res.put("fail", fail_count);
return res;
}
public static void main(String[] args) {
List<Csvpartbase> allcsv = new ArrayList<>();
for (int i = 0; i < 2; i++) {
Csvpartbase csvpartbase = new Csvpartbase();
csvpartbase.setId("" + i);
csvpartbase.setIp("127.0.0.1");
csvpartbase.setMac("127.0.0.1");
csvpartbase.setModifytime("20170920");
csvpartbase.setUpindex("" + i);
csvpartbase.setUpname("lw" + i);
csvpartbase.setUpip("123.0.0.2");
allcsv.add(csvpartbase);
}
for (Csvpartbase csv1 : allcsv) {
/**
* 第一种方法
*/
// String[] csvstr = {csv1.getId(),csv1.getMac(),csv1.getIp(),csv1.getIp(),csv1.getUpname(),csv1.getUpindex(),csv1.getModifytime()};
/**
* 第二种方法
*/
// String[] csvstr = new String[csv1.getClass().getDeclaredFields().length];
// for (int i = 0; i < csvstr.length; i++) {
// Field[] f = csv1.getClass().getDeclaredFields();
// csvstr[i] = f[i].toString();
// }
// System.out.println(csvstr);
/**
* 第三种方法
*/
EntityToCharArray entityToCharArray = new EntityToCharArray();
String[] csvArray = entityToCharArray.entityToArray(csv1);
System.out.println(csvArray[0]);
}
}
}
| [
"1036849437@qq.com"
] | 1036849437@qq.com |
966c8120ef3f4fabccf7f2a3feba5b8d37784605 | fce534788ddb537353cf24e4b7b42eb1e23427b3 | /src/lk/ijse/dep/project/controller/TaskFormController.java | 0326afc582b757c5920446e72b7137e29ccfb2d2 | [
"MIT"
] | permissive | DilushaKumari/BakerySystem | 2f9a9ae430b8c77d64641be818d3edf70c3161da | 43105d2536bd89f4d208b72a375bf568a4dfdf81 | refs/heads/master | 2020-12-01T20:46:41.390468 | 2019-12-29T15:01:52 | 2019-12-29T15:01:52 | 230,762,207 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,297 | java | package lk.ijse.dep.project.controller;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.controls.JFXTimePicker;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import lk.ijse.dep.project.business.BOFactory;
import lk.ijse.dep.project.business.BOTypes;
import lk.ijse.dep.project.business.custom.ProductBO;
import lk.ijse.dep.project.business.custom.TaskBO;
import lk.ijse.dep.project.business.exception.AllReadyExisitsRcpIdInProductException;
import lk.ijse.dep.project.dto.ProductDTO;
import lk.ijse.dep.project.dto.TaskDTO;
import lk.ijse.dep.project.util.RecipeTM;
import lk.ijse.dep.project.util.TaskAddTM;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TaskFormController implements Initializable {
public AnchorPane taskForm;
public JFXTextField txtTaskDes;
public JFXTextField txtDate;
public JFXButton btnDelete;
public JFXComboBox<String> cmbProductId;
public JFXTextField txtProductDes;
public JFXButton btnAdd;
public JFXTextField txtExpectedQty;
public TableView<TaskAddTM> tblTask;
public JFXTextField txtTaskId;
public JFXTextField txtSearch;
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
ProductBO productBO = BOFactory.getInstance().getBO(BOTypes.PRODUCT);
TaskBO taskBO = BOFactory.getInstance().getBO(BOTypes.TASK);
@Override
public void initialize(URL location, ResourceBundle resources) {
Date curDate = new Date();
txtDate.setText(dateFormatter.format(curDate));
txtDate.setDisable(true);
btnDelete.setDisable(true);
btnAdd.setDisable(true);
loadProductId();
loadTable();
txtSearch.requestFocus();
tblTask.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("taskId"));
tblTask.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("taskDes"));
tblTask.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("productId"));
tblTask.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("expectedQty"));
cmbProductId.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
String selectedProdcutId = cmbProductId.getSelectionModel().getSelectedItem();
if (selectedProdcutId == null)
return;
try {
ProductDTO productDetails = productBO.getProductDetails(selectedProdcutId);
txtProductDes.setText(productDetails.getProductName());
btnAdd.setDisable(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
txtSearch.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
loadTable();
}
});
tblTask.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TaskAddTM>() {
@Override
public void changed(ObservableValue<? extends TaskAddTM> observable, TaskAddTM oldValue, TaskAddTM newValue) {
btnAdd.setText("Update");
TaskAddTM selectedTask = tblTask.getSelectionModel().getSelectedItem();
if (selectedTask == null) {
btnAdd.setText("Add");
return;
}
txtTaskId.setText(selectedTask.getTaskId());
txtTaskId.setDisable(true);
btnDelete.setDisable(false);
txtTaskDes.setText(selectedTask.getTaskDes());
txtExpectedQty.setText(selectedTask.getExpectedQty()+"");
cmbProductId.setValue(selectedTask.getProductId());
}
});
}
public void loadProductId() {
try {
List<String> productIds = productBO.getProductId();
ObservableList items = cmbProductId.getItems();
items.clear();
for (String productId : productIds) {
items.add(productId);
}
cmbProductId.setItems(items);
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadTable(){
ObservableList tasks = tblTask.getItems();
tasks.clear();
try {
List<TaskDTO> pendingTasksBySearch = taskBO.findTasksBySearch('%' + txtSearch.getText() + '%',"PE");
for (TaskDTO task: pendingTasksBySearch) {
tasks.add(new TaskAddTM(task.getTaskId(),task.getTaskDes(),task.getProductId(),task.getExpectQty()));
}
} catch (Exception e) {
new Alert(Alert.AlertType.ERROR, "Something went wrong, please contact DEPPO").show();
Logger.getLogger("lk.ijse.dep.project.controller").log(Level.SEVERE, "When Load pending task Table", e);
}
}
public void imgHome_OnMouseClicked(MouseEvent mouseEvent) {
try {
URL resource = this.getClass().getResource("/lk/ijse/dep/project/view/DashBoardForm.fxml");
Parent root = null;
root = FXMLLoader.load(resource);
Scene scene = new Scene(root);
Stage primaryStage = (Stage) this.taskForm.getScene().getWindow();
primaryStage.setScene(scene);
primaryStage.centerOnScreen();
} catch (IOException e) {
e.printStackTrace();
}
}
public void btnDelete_OnAction(ActionEvent actionEvent) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION,
"Are you sure whether you want to delete this task?",
ButtonType.YES, ButtonType.NO);
Optional<ButtonType> buttonType = alert.showAndWait();
if (buttonType.get() == ButtonType.YES) {
String selectedItem = txtTaskId.getText();
try {
boolean b = taskBO.deletePendingTask(selectedItem);
if(b){
new Alert(Alert.AlertType.INFORMATION,"Task is deleted Successfully...");
}
txtTaskId.clear();
txtTaskDes.clear();
txtExpectedQty.clear();
cmbProductId.getSelectionModel().clearSelection();
txtProductDes.clear();
btnAdd.setDisable(true);
btnDelete.setDisable(true);
loadTable();
} catch (AllReadyExisitsRcpIdInProductException e) {
new Alert(Alert.AlertType.INFORMATION, e.getMessage()).show();
} catch (Exception e) {
new Alert(Alert.AlertType.ERROR, "Something went wrong, please contact DEPPO").show();
Logger.getLogger("lk.ijse.dep.project.controller").log(Level.SEVERE, null, e);
}
}
}
public void imgTask_OnMouseClicked(MouseEvent mouseEvent) {
txtProductDes.clear();
txtExpectedQty.clear();
cmbProductId.getSelectionModel().clearSelection();
txtTaskDes.clear();
btnAdd.setDisable(true);
int maxId = 0;
try {
String lastTaskId = taskBO.getLastTaskId();
if (lastTaskId == null) {
maxId = 0;
} else {
maxId = Integer.parseInt(lastTaskId.replace("T", ""));
}
maxId = maxId + 1;
String id = "";
if (maxId < 10) {
id = "T00" + maxId;
} else if (maxId < 100) {
id = "T0" + maxId;
} else {
id = "T" + maxId;
}
txtTaskId.setText(id);
txtTaskId.setDisable(true);
} catch (Exception e) {
new Alert(Alert.AlertType.ERROR, "Something went wrong, please contact DEPPO").show();
Logger.getLogger("lk.ijse.dep.project.controller").log(Level.SEVERE, null, e);
}
}
public void btnAdd_OnAction(ActionEvent actionEvent) {
if (!txtTaskDes.getText().matches("^.+")) {
Alert alert = new Alert(Alert.AlertType.ERROR, "Enter Task Description");
alert.show();
txtTaskDes.requestFocus();
txtTaskDes.selectAll();
return;
}else if (!txtExpectedQty.getText().matches("(\\d+[.]\\d+|(\\d+))")) {
Alert alert = new Alert(Alert.AlertType.ERROR, "Invalid Expected Quantity...", ButtonType.OK);
alert.show();
txtExpectedQty.requestFocus();
txtExpectedQty.selectAll();
return;
}
boolean flag =false;
if (btnAdd.getText().equals("Add")){
try {
flag = taskBO.saveTask(new TaskDTO(txtTaskId.getText(), txtTaskDes.getText(), new java.sql.Date(new Date().getTime()), cmbProductId.getSelectionModel().getSelectedItem(), Double.parseDouble(txtExpectedQty.getText())));
} catch (Exception e) {
new Alert(Alert.AlertType.ERROR, "Something went wrong, please contact DEPPO").show();
Logger.getLogger("lk.ijse.dep.pos.controller").log(Level.SEVERE, "When Add", e);
}
}else {
try {
flag= taskBO.updateTask(new TaskDTO(txtTaskId.getText(), txtTaskDes.getText(), new java.sql.Date(new Date().getTime()), cmbProductId.getSelectionModel().getSelectedItem(), Double.parseDouble(txtExpectedQty.getText())));
} catch (Exception e) {
new Alert(Alert.AlertType.ERROR, "Something went wrong, please contact DEPPO").show();
Logger.getLogger("lk.ijse.dep.pos.controller").log(Level.SEVERE, "When Update", e);
}
}
String productId =cmbProductId.getSelectionModel().getSelectedItem();
if(flag){
if(btnAdd.getText().equals("Add")) {
new Alert(Alert.AlertType.INFORMATION, "Successfully Added a task...").show();
ObservableList items = tblTask.getItems();
items.add(new TaskAddTM(txtTaskId.getText(),txtTaskDes.getText(),productId,Double.parseDouble(txtExpectedQty.getText())));
tblTask.setItems(items);
}else {
new Alert(Alert.AlertType.INFORMATION, "Successfully Updated a pending task...").show();
TaskAddTM selectedTask = tblTask.getSelectionModel().getSelectedItem();
selectedTask.setTaskDes(txtTaskDes.getText());
selectedTask.setProductId(cmbProductId.getSelectionModel().getSelectedItem());
selectedTask.setExpectedQty(Double.parseDouble(txtExpectedQty.getText()));
tblTask.refresh();
}
tblTask.refresh();
txtTaskDes.clear();
txtTaskId.clear();
txtProductDes.clear();
txtExpectedQty.clear();
cmbProductId.getSelectionModel().clearSelection();
tblTask.getSelectionModel().clearSelection();
btnAdd.setDisable(true);
btnDelete.setDisable(true);
txtTaskId.setDisable(false);
txtSearch.requestFocus();
}
}
public void txtExpectedQty_OnAction(ActionEvent actionEvent) {
btnAdd_OnAction(actionEvent);
}
}
| [
"dilushakumaridt@gmail.com"
] | dilushakumaridt@gmail.com |
a4fccc59014311708ac9cfee0ff479e6f9eb94e6 | 26e13685fe469298d99c25a5b4d16d289f8073c1 | /src/main/java/de/kasperczyk/rkbudget/account/IbanValidator.java | 1661991da5a7054b018ed004d28f149fc476fc6c | [] | no_license | Kasperczyk/RKBudget | 968c39e1be1778f8e79985bbf38019123c902ff7 | 9b45034a1982a194474e77d3e3229c0aad3bf4d9 | refs/heads/master | 2020-12-03T00:22:05.058547 | 2017-08-09T15:41:02 | 2017-08-09T15:41:02 | 95,869,760 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,598 | java | package de.kasperczyk.rkbudget.account;
import de.kasperczyk.rkbudget.user.UserController;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.validator.routines.checkdigit.IBANCheckDigit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@Component
@Scope("request")
public class IbanValidator implements Validator {
private final MessageSource messageSource;
private final UserController userController;
@Autowired
public IbanValidator(MessageSource messageSource, UserController userController) {
this.messageSource = messageSource;
this.userController = userController;
}
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (!isIbanValid(value)) {
FacesMessage errorMessage = new FacesMessage(
messageSource.getMessage("account_error_invalidIban", null, userController.getLocale()));
throw new ValidatorException(errorMessage);
}
}
private boolean isIbanValid(Object value) {
String iban = StringUtils.deleteWhitespace(value.toString());
return new IBANCheckDigit().isValid(iban);
}
}
| [
"kasperczyk.rene@gmail.com"
] | kasperczyk.rene@gmail.com |
4cb73925095dc5b7cc8698aa166c4c3abc3060b8 | 9dc87d204c515b8bc514fd3e4f148f4486df52c0 | /src/test/java/com/bdt/kiradb/PersistTest.java | 5d5fe52b4b4b6f7859aeb3bf2195b89a61b1a898 | [] | no_license | mrblog/KiraDB | 8d193267c349a6d46d5b04903e749874f2e8ae0d | a817903fc6e7da4fe561f9cab7f22e563d04bc69 | refs/heads/master | 2020-04-26T03:32:43.506105 | 2018-12-03T06:14:21 | 2018-12-03T06:14:21 | 8,253,697 | 1 | 0 | null | 2013-12-18T17:19:51 | 2013-02-17T17:22:41 | Java | UTF-8 | Java | false | false | 2,711 | java | package com.bdt.kiradb;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import com.bdt.kiradb.mykdbapp.Person;
public class PersistTest {
private final static String testAccounts[] = { "332", "109", "320", "644" };
private final static String testNames[] = { "Wolpe, H.","Grumette, M.","Halpern, M.","Kenny, B. C." };
private final static String INDEX = "KiraDBPersistedIndex";
@Test
public void firstPass() throws IOException, InterruptedException, KiraException, ClassNotFoundException {
KiraDb db = new KiraDb(new File(INDEX));
for (int i = 0; i < testAccounts.length; i++) {
Person xp = new Person();
xp.setAccount(testAccounts[i]);
xp.setName(testNames[i]);
xp.setCreatedAt(new Date());
System.out.println("Writing person... " + xp.getAccount());
db.storeObject(xp);
}
List<Person> q1Results = db.executeQuery(new Person(), (String)null, null, 10, 0, null, true);
assertNotNull("PASS1 q1Results result should not be null", q1Results);
System.out.println("PASS1 Found " + q1Results.size() + " records.");
assertEquals("Incorrect number of records", q1Results.size(), testAccounts.length);
}
@Test
public void secondPass() throws IOException, KiraException, ClassNotFoundException {
KiraDb db = new KiraDb(new File(INDEX));
List<Person> q1Results = db.executeQuery(new Person(), (String)null, null, 10, 0, null, true);
assertNotNull("PASS2 q1Results result should not be null", q1Results);
System.out.println("PASS2 Found " + q1Results.size() + " records.");
assertEquals("Incorrect number of records", q1Results.size(), testAccounts.length);
for (Person p: q1Results) {
System.out.println("Account: " + p.getAccount() + " Name: " + p.getName());
}
// ensure each test account is accounted for exactly once
for (int i = 0; i < testAccounts.length; i++) {
int n = 0;
for (Person p: q1Results) {
if (p.getAccount().equals(testAccounts[i])) {
assertEquals("Duplicate match on account " + testAccounts[i], n, 0);
n++;
assertTrue("Name does not match on account " + testAccounts[i], p.getName().equals(testNames[i]));
}
}
assertEquals("No match on account " + testAccounts[i], n, 1);
}
System.out.println("Deleting index " + INDEX);
db.deleteIndex();
}
}
| [
"mrblogdotorg@gmail.com"
] | mrblogdotorg@gmail.com |
709b0052dffb4e1362f6edba615a5e1a12859160 | a41411929ebca8363ff343397e3edf45cd6095c7 | /src/SurvivalDude.java | a64d5b059903031f1ae30e6ce7af19161fde0192 | [] | no_license | Mitchthesupermitch/SurvivalDude | 0fe779eadddc63aa54264af9bcacfc0e8ebe0b55 | 1ee7d17bd297ee2286db444bb00a9fa37f26f128 | refs/heads/master | 2021-07-02T20:23:33.839111 | 2017-09-22T17:47:31 | 2017-09-22T17:47:31 | 104,502,873 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,917 | java | import java.util.Scanner;
public class SurvivalDude {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter(System.getProperty("line.separator"));
String response, name, friendName;
int a;
int deathNum = 0;
int day = 1;
do {
System.out.print("\n\nWhat is your name? ");
name = keyboard.next();
do {
System.out.println("\n\nAll right then, " + name + ", let's get started.");
keyboard.next();
System.out.println("You are on a plane. Suddenly, the plane's engine explodes.");
keyboard.next();
System.out.println("What do you do?\n\n(1) Cry \n\n(2) Grab a parchute and jump ");
a = keyboard.nextInt();
} while (a != 2 && a != 1);
if (a == 1) {
do {
// escape plane
System.out.println(
"Your crying attracts the attention of a flight attendant,\n\nwho puts a parachute on you and kicks you off the plane.");
keyboard.next();
System.out.println("You pull the cord and slowly drift onto an island.");
keyboard.next();
System.out.println("You take off the parachute and see a forest.");
keyboard.next();
System.out.println("What do you do?\n\n(1) Explore (2) Go for a swim ");
a = keyboard.nextInt();
} while (a != 1 && a != 2);
if (a == 2) {
do {
// swim my dude
System.out.println("You wade into the warm ocean water. You sure are having fun!");
keyboard.next();
System.out.println("Eventually you get tired and go back on shore.");
keyboard.next();
System.out.println("The sun is setting and you're cold.");
keyboard.next();
System.out.println("You sure are bad at planning ahead.");
keyboard.next();
System.out.println(
"What now? \n\n(1) Cover yourself with sand and go to sleep\n\n(2) Try to find shelter in the forest ");
a = keyboard.nextInt();
} while (a != 1 && a != 2);
if (a == 2) {
do {
System.out.println("You go into the forest and find a comfy rock to sleep on.");
keyboard.next();
System.out.println("You cover yourself with ferns and close your eyes.");
keyboard.next();
System.out.println("You wake up the next day. Your stomach grumbles.");
keyboard.next();
System.out.println("What do you do? \n\n(1)Sleep to conserve energy (2) Eat those weird looking berries ");
a = keyboard.nextInt();
day++;
} while (a != 1 && a != 2);
if (a == 2) {
do {
System.out.println("Those berries taste real good.");
keyboard.next();
System.out.println("Wow, you just found a food source. Good job!");
keyboard.next();
System.out.println("You are no longer hungry.");
keyboard.next();
System.out.println("What do you want to do?\n\n(1)Try to make a shelter (2)Look for more food ");
a = keyboard.nextInt();
} while (a != 1 && a != 2);
if (a == 1) {
do {
System.out.println(
"You spend the rest of the day collecting material for your house.");
keyboard.next();
System.out.println("However, it is too dark to keep building your house at night.");
keyboard.next();
System.out.println(
"What do you do?\n\n(1)Try anyway (2) Go to sleep on your cold rock again ");
a = keyboard.nextInt();
} while (a != 1 && a != 2);
if (a ==1) {
do {
System.out.println("You build the frame for your shelter.");
keyboard.next();
System.out.println("You try to lift a heavy chunk of wood.");
keyboard.next();
System.out.println("You drop it on your foot.");
keyboard.next();
System.out.println("Now your foot is hurt, bozo.");
keyboard.next();
System.out.println("What do you do?\n\n(1)Try to keep working (2) Make a splint ");
a = keyboard.nextInt();
}while (a != 1 && a != 2);
if (a == 2) {
do {
System.out.println("You succesfully splint your foot.");
keyboard.next();
System.out.println("You go to sleep in your half-finished shelter.");
keyboard.next();
System.out.println("You wake up. Your foot does not hurt as much anymore.");
keyboard.next();
System.out.println("You finish building your house.");
keyboard.next();
System.out.println("What now? \n\n(1)Eat some berries(2)Try to make a boat");
a = keyboard.nextInt();
day ++;
} while (a != 1 && a != 2);
if (a == 1) {
do {
System.out.println("Those berries taste really good.");
keyboard.next();
System.out.println("You decide you're never going to make it off the island on your own.");
keyboard.next();
System.out.println("That means you need to survive until rescuers arrive.");
keyboard.next();
System.out.println("What do you do to survive?\n\n(1)Continue making your house\n\n(2)Eat A L L the berries");
a = keyboard.nextInt();
} while (a != 1 && a != 2);
if (a == 2) {
do {
System.out.println("You eat all the Y U M M Y berries.");
keyboard.next();
System.out.println("Those berries energize and uplift you.");
keyboard.next();
System.out.println("Now that you are fully awake, what do you want to do?\n\n(1)Make some friends\n\n(2)Make weapons");
a = keyboard.nextInt();
} while (a != 1 && a != 2);
if (a == 1) {
do {
System.out.println("You explore the forest and look for some friends.");
keyboard.next();
System.out.println("You encounter a baby pig.");
keyboard.next();
System.out.println("What do you do?\n\n(1)Pet it\n\n(2)Give it some berries");
a = keyboard.nextInt();
} while (a != 1 && a != 2);
if (a == 2) {
do {
System.out.println("The pig eats all the Y U M M Y berries.");
keyboard.next();
System.out.println("The pig now follows you around.");
keyboard.next();
System.out.println("You just made a friend! What's his name?");
friendName = keyboard.next();
System.out.println("What do you want to do with "+friendName+"?\n\n(1)Train your friend to fight\n\n(2)Go play in the ocean");
a = keyboard.nextInt();
} while (a != 1 && a != 2);
if (a == 2) {
do {
System.out.println("You and "+friendName+" go into the ocean.");
keyboard.next();
System.out.println("You have fun until the sun sets.");
keyboard.next();
System.out.println("You and "+friendName+" head back to your shelter.");
keyboard.next();
System.out.println("You go to sleep with "+friendName+".");
keyboard.next();
System.out.println("You wake up the next day and eat berries with "+ friendName+".");
keyboard.next();
System.out.println("What now? \n\n(1)Spell out 'Help!' on the beach (2)Learn how to make fire");
a = keyboard.nextInt();
day++;
} while (a != 1 && a != 2);
if (a == 1) {
do {
System.out.println("You go to the beach with some rocks.");
keyboard.next();
System.out.println("You spend a couple hours arranging the rocks in the perfect position.");
keyboard.next();
System.out.println("Now people can see that you need help. Congrats!");
keyboard.next();
System.out.println("You have some time to kill before nightfall. What do you do?\n\n(1)Lay around and do nothing (2)Find something to eat other than berries");
a = keyboard.nextInt();
} while (a != 1 && a != 2);
if (a == 1) {
do {
System.out.println("You sit on the beach and relax in the sun.");
keyboard.next();
System.out.println("Eventually you get hot and crawl into the shade.");
keyboard.next();
System.out.println("You are so bored, you go to sleep early.");
keyboard.next();
System.out.println("You wake up the next day to the sound of a helicopter.");
keyboard.next();
System.out.println("A man drops down from a rope ladder and walks toward you..");
keyboard.next();
System.out.println("Who is it ?! (1) Snoop Dogg (2) The Babadook");
a = keyboard.nextInt();
} while (a != 1 && a != 2);
if (a == 1) {
System.out.println("You as Snoop Dogg if he is here to help.");
keyboard.next();
System.out.println("He replies 'Fo shizzle, go watch some televizzle.'");
keyboard.next();
System.out.println("He brings you and "+ friendName+"back to the mainland and you live happily ever after.");
keyboard.next();
}else {
System.out.println("Why would you choose the Babadook?");
keyboard.next();
System.out.println("Well guess what?");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
}else {
System.out.println("You find a new type of berry.");
keyboard.next();
System.out.println("You pop them into your mouth and fall unconscious.");
keyboard.next();
System.out.println("They were poisonous.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
}else {
System.out.println("You smack some rocks together, which creates sparks.");
keyboard.next();
System.out.println("Those sparks spread to the dead plants on the forest floor.");
keyboard.next();
System.out.println("The entire island is set on fire.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
}else {
System.out.println("You put a pointy rock in "+friendName+"'s mouth.");
keyboard.next();
System.out.println(""+friendName+" stabs you and steals your berries.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
}else {
System.out.println("As you pet the pig, a shadow falls over you.");
keyboard.next();
System.out.println("It's the pig's mom!");
keyboard.next();
System.out.println("She eats you.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
}else {
System.out.println("You need weapons to survive. You pick up some sticks and shiny rocks.");
keyboard.next();
System.out.println("The rock shines some light into the eye of a giant bird .");
keyboard.next();
System.out.println("The giant bird swoops down and eats you.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
}else {
System.out.println("You get some wood for your boat.");
System.out.println("You try to put a roof over your head.");
keyboard.next();
System.out.println("You go inside your house and survey your work.");
keyboard.next();
System.out.println("The roof collapses over your head.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
}else {
System.out.println("You get some wood for your boat.");
keyboard.next();
System.out.println("You realize that you do not know how to build a boat.");
keyboard.next();
System.out.println("You sit down and start crying.");
keyboard.next();
System.out.println("A wild boar appeared!");
keyboard.next();
System.out.println("What do you think happens? \n\n(1)You die(2) You still die, but faster");
a = keyboard.nextInt();
System.out.println("You died!\n\n");
deathNum++;
}
}else {
System.out.println("Your foot hurts, but you don't care.");
keyboard.next();
System.out.println("You raise a slab of stone over your head.");
keyboard.next();
System.out.println("Your foot gives out and you drop the rock on your head.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
} else {
System.out.println("You lay down on your rock.");
keyboard.next();
System.out.println("During the night, a giant bird grabs you.");
keyboard.next();
System.out.println("You get eaten.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
}else {
System.out.println("You find a couple of coconut trees and try to climb them.");
keyboard.next();
System.out.println("Suddenly, a coconut falls on your head.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
} else if (a == 1) {
System.out.println("You wake up a few hours later.");
keyboard.next();
System.out.println("You are so hungry you can barely move.");
keyboard.next();
System.out.println("You lay on your rock until a wild boar eats you.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
} else {
System.out.println("That sand feels nice.");
keyboard.next();
System.out.println("A giant crab apppears and eats you.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
} else if (a == 1) {
System.out.println("While you are exploring, you find a wild boar.");
keyboard.next();
System.out.println("It kills you.\n\n");
deathNum++;
}
}
else {
System.out.println("You leap out of the burning plane.");
keyboard.next();
System.out.println("Unfortunately, your parachute doesn't open.");
keyboard.next();
System.out.println("You died!\n\n");
deathNum++;
}
if (day == 1) {
System.out.print("You survived for " + day + " day.");
} else {
System.out.print("You survived for " + day + " days.");
}
if (day < 3) {
System.out.print(" That's pretty lame.");
}
if (day == 3 || day > 3 && day < 5) {
System.out.print(" That's pretty good.");
}
if (day == 5) {
System.out.print(" Congrats on surviving!");
}
if (deathNum == 1) {
System.out.print("\nYou died "+deathNum+" time!");
} else {
System.out.print("\nYou died "+deathNum+" times!");
}
} while (true);
}
}
| [
"student@FHS-R84-22328.local"
] | student@FHS-R84-22328.local |
f083572bbfb3d3270d933e2dd1baa21de08aa42d | f2b6a0486ccfbeaecea58727cfb7c1b543659fd0 | /src/main/java/com/jcomdot/simplemvc/user/sqlservice/SqlService.java | d71131f5ab3541d61e2c011147edd6d0e934f32d | [] | no_license | jcomdot/SimpleMVC | 3d38ffdeca0530ea93972b1d9379adb86b5d1e9f | 6f0362668007898448f7a3ce755ace6b836f5b24 | refs/heads/master | 2021-06-02T12:56:35.574550 | 2019-05-15T04:41:19 | 2019-05-15T04:41:19 | 17,441,723 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 149 | java | package com.jcomdot.simplemvc.user.sqlservice;
public interface SqlService {
String getSql(String key) throws SqlRetrievalFailureException;
}
| [
"Joonsong@192.168.1.105"
] | Joonsong@192.168.1.105 |
8264d1b8970416c400c0823501f16ea3dd0d7fa0 | 36e7ac4f1b6e8bb14dad67d99406393cc94a5a33 | /src/test/java/com/imgeek/algorithm/MyListTest.java | c10d4aacc24b2373e749823e9910f1ad90c4f43c | [] | no_license | thesungodess/myzone | 527f30a42bbf4d40f7210d9935a780703640b447 | 945c369caf27963d2047bb7dc35c3064bf57c9f0 | refs/heads/master | 2020-04-01T12:36:28.314176 | 2018-10-15T10:07:24 | 2018-10-15T10:07:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,076 | java | package com.imgeek.algorithm;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author :xiemin
* @date: 2018-09-19
*/
public class MyListTest {
private MyList myList;
public MyListTest() {
myList = new MyList();
}
@Before
public void create() {
int size = 10;
for (int i = 0; i < size; i++) {
Node node = new Node();
node.data = i;
myList.add(node);
}
}
@Test
public void add() {
int size = 10;
assertEquals(size, myList.size());
}
@Test
public void contains() {
Node node = new Node();
node.data = 9;
assertEquals(true, myList.contains(node));
}
@Test
public void remove() {
Node node = new Node();
node.data = 9;
node = myList.remove(node);
assertEquals(false, myList.contains(node));
}
@Test
public void get() {
int num = 5;
Node node = myList.get(5);
assertEquals(num, node.data);
}
} | [
"xiemin@farmfriend.cn"
] | xiemin@farmfriend.cn |
8f665aceb42af012e18b2faedd3a0b778f3d9ed5 | 15e3e23c8ab6f45cc19201a9cd983fbbb71d4c45 | /src/com/joilnen/GameStateType.java | 39be11815824cf84d19baaa400c6ee4ddc415796 | [] | no_license | Joilnen/bzzz | 536314240ee600265471ffdd9bbba3bfc59959e8 | 5a7ef9789b2fd552af4320ae84dc234bc38f2c97 | refs/heads/master | 2016-09-05T18:53:14.518399 | 2013-03-06T12:47:18 | 2013-03-06T12:47:18 | 8,602,443 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 151 | java | package com.joilnen;
class GameStateType {
static int IN_MENU = 0;
static int RUNNING = 1;
static int IN_PAUSE = 2;
static int GAME_OVER = 3;
}
| [
"joilnen@mygentoo.(none)"
] | joilnen@mygentoo.(none) |
b28c92d74db08ca99f35149dd838f38991267e32 | 22a76a439c9208afb100a55ab7ad794b592edbd5 | /src/project/pbo/states/LoadThread.java | 2fd2e0eebd81a7c924c467e2b499e3f5fb0d6356 | [] | no_license | Ztrohub/ProjectPBO | a451499e8a1595af481c55b606a5f75310cb7729 | e84d2ebbc0d714e85d54b81f39436b53341b63a1 | refs/heads/master | 2023-05-26T06:45:23.986864 | 2021-06-07T10:22:44 | 2021-06-07T10:22:44 | 359,666,977 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 334 | java | package project.pbo.states;
import project.pbo.gfx.Assets;
public class LoadThread implements Runnable{
private final State nextstate;
public LoadThread(State nextstate) {
this.nextstate = nextstate;
}
@Override
public void run() {
Assets.nullThisYeah();
nextstate.loadFile();
}
}
| [
"ztroidmail@gmail.com"
] | ztroidmail@gmail.com |
15ac04329b91a39d3fc3d6ff079aded689062771 | 51a2e2e01d311b5cda24dabf219d4048a33f040f | /src/main/java/com/stock/mvc/entites/CommandeClient.java | 018b956992fd44e6c69899ea6ac94dc5b6372c31 | [] | no_license | khalouaoui/Stock_Management | 40ad311a94653db4e927ff195767ab3d0d0e0a4c | 5df961dd1490a35628af2a4d7d0b3aad219423a7 | refs/heads/master | 2022-12-21T09:10:27.121034 | 2019-12-22T22:36:39 | 2019-12-22T22:36:39 | 227,933,151 | 0 | 0 | null | 2022-12-16T01:00:58 | 2019-12-13T22:35:28 | Java | UTF-8 | Java | false | false | 2,810 | java | package com.stock.mvc.entites;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
@Entity
public class CommandeClient implements Serializable{
@Id
@GeneratedValue
private Long idCommandeClient;
private String code;
@Temporal(TemporalType.TIMESTAMP)
private Date dateCommande;
@ManyToOne
@JoinColumn(name = "idClient")
private Client client;
@OneToMany(mappedBy = "commandeClient")
private List<LigneCommandeClient> ligneCommandeClients;
@Transient
private BigDecimal totalCommande;
public Long getIdCommandeClient() {
return idCommandeClient;
}
public void setIdCommandeClient(Long id) {
this.idCommandeClient = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Date getDateCommande() {
return dateCommande;
}
public void setDateCommande(Date dateCommande) {
this.dateCommande = dateCommande;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
@JsonIgnore
public List<LigneCommandeClient> getLigneCommandeClients() {
return ligneCommandeClients;
}
public void setLigneCommandeClients(List<LigneCommandeClient> ligneCommandeClients) {
this.ligneCommandeClients = ligneCommandeClients;
}
public BigDecimal getTotalCommande() {
totalCommande = BigDecimal.ZERO;
if (!ligneCommandeClients.isEmpty()) {
for (LigneCommandeClient ligneCommandeClient : ligneCommandeClients) {
if (ligneCommandeClient.getQuantite() != null && ligneCommandeClient.getPrixUnitaire() != null) {
BigDecimal totalLigne = ligneCommandeClient.getQuantite().multiply(ligneCommandeClient.getPrixUnitaire());
totalCommande = totalCommande.add(totalLigne);
}
}
}
return totalCommande;
}
@Transient
public String getLigneCommandeJson() {
if (!ligneCommandeClients.isEmpty()) {
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(ligneCommandeClients);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
}
| [
"khalouaoui_ibrahim@hotmail.fr"
] | khalouaoui_ibrahim@hotmail.fr |
6a16f81761ff354d005012df49bbbd4d19fc9573 | 864e3e11241c01c35eb0b0c0640ccc915fea4a5e | /src/test/java/com/acme/petcompanionlibrary/PetcompanionlibraryApplicationTests.java | 0b2219eb23f0033c8fcb93d65cdda50f0324043d | [] | no_license | Arix69sex/PatternBasedLibraryForPetCompanion | 1f4b3b35945dad2c6669597734d8061e993c98c5 | 9f7611bada8e1ef990d95c256a5b1578c21b99f2 | refs/heads/master | 2023-01-20T12:13:17.756518 | 2020-11-26T20:23:55 | 2020-11-26T20:23:55 | 312,457,466 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 242 | java | package com.acme.petcompanionlibrary;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class PetcompanionlibraryApplicationTests {
@Test
void contextLoads() {
}
}
| [
"arix69sex@gmail.com"
] | arix69sex@gmail.com |
cc6058891d5c16962ea2856f921433ef307cfae4 | 79e72f0720c63cc1134b007094214280af1a4976 | /Module01/src/com/seaking/bean/Users.java | 862d66a8a4d50f1d3bb4ebb07b38dc60893cda65 | [] | no_license | CharlieDwD/ProJect02 | 20bfc5cbe39be93c777de5eea36d8d932ad5acaf | 7c8434238341afa89202fbfc5e2b957eae283387 | refs/heads/master | 2020-05-16T03:55:01.009618 | 2019-04-22T10:37:58 | 2019-04-22T10:37:58 | 182,754,054 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 202 | java | package com.seaking.bean;
public class Users {
public static void main(String[] args){
//dsfjskldjfsdkljf
System.out.print("HelloWord!!");
}
public void method(){
}
}
| [
"seakingdavid@163.com"
] | seakingdavid@163.com |
fe6cdce697714528a53359bd76f1efeddb868356 | b0946aca726c5bff2206ab1c68d75f9f3f6d33e6 | /src/main/java/pl/mw/article/dao/AuthorDAO.java | 3309c890810e042c32a38abe1fd3829e46ea44ef | [] | no_license | mwiesiolek/article-app | 807b94791ba65527d85f16662554f97888b51c76 | 173b5b0e007b3e81c06a96e360f6fc8967905016 | refs/heads/master | 2021-01-10T06:55:18.137193 | 2015-10-09T17:29:20 | 2015-10-09T17:29:20 | 43,451,675 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,134 | java | package pl.mw.article.dao;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Repository;
import pl.mw.article.domain.Author;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Created by mwiesiolek on 30/09/2015.
*/
@Repository
public class AuthorDAO extends AbstractDAO<Author> {
public Set<Author> findAll(final int from, final int number) {
Criteria criteria = getSession().createCriteria(Author.class);
criteria.setFirstResult(from);
criteria.setMaxResults(number);
return new LinkedHashSet<>(criteria.list());
}
public Author find(final Long id) {
return (Author) getSession().get(Author.class, id);
}
public Set<Author> findAllWith(final Criterion criterion) {
Criteria criteria = getSession().createCriteria(Author.class);
criteria.add(criterion);
return new LinkedHashSet<>(criteria.list());
}
public Set<Author> findAllWith(final Criterion criterion, final int from, final int number) {
Criteria criteria = getSession().createCriteria(Author.class);
criteria.add(criterion);
criteria.setFirstResult(from);
criteria.setMaxResults(number);
return new LinkedHashSet<>(criteria.list());
}
public void delete(Author Author) {
getSession().delete(Author);
}
public Long size() {
return (Long) getSession().createCriteria(Author.class).setProjection(Projections.rowCount()).uniqueResult();
}
public Long size(final Criterion criterion) {
Criteria criteria = getSession().createCriteria(Author.class);
criteria.add(criterion);
return (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
}
public boolean checkIfExist(final Criterion criterion) {
Criteria criteria = getSession().createCriteria(Author.class);
criteria.add(criterion);
Long result = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
return result > 0;
}
}
| [
"maksymilian.wiesiolek@gmail.com"
] | maksymilian.wiesiolek@gmail.com |
b9218a80c5dcd6faf65b3ae2d2bf5471a8add4a4 | 926f589160f0a5188c45feaaa793a483923f5e9a | /core java/Constructor/src/Constructor/Day7/byKunalSir/A.java | 3fa6b998a1297f992bb5431656edb07e577b9cae | [] | no_license | rohankalamkar/corejava | 6016bd2e923f2cb56e0ef974801058c975455789 | 5b2a466b57d6a8fc3c9a64432400f47b52416d7d | refs/heads/master | 2023-08-21T21:07:24.355631 | 2021-10-26T12:42:21 | 2021-10-26T12:42:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 60 | java | package Constructor.Day7.byKunalSir;
public class A {
}
| [
"rohan.kalamkar7@gmail.com"
] | rohan.kalamkar7@gmail.com |
836d14914dfc91fc21430ec0a1bee3aa2dd3ebb8 | fd402e0eb0f622f01514145205b04d043e0b739e | /src/Genetico/GUI.java | 2cee36bf3d7cb6b2c2fc3b9f58898e84b841d14d | [] | no_license | BelmontIzacc/2CM1_Java | ddb26412611ea38a86421424c761d76f6775aad5 | dad695dba79b409262d7c4f5016f29cf2b54c808 | refs/heads/master | 2020-03-26T14:52:31.199843 | 2018-11-22T03:42:25 | 2018-11-22T03:42:25 | 145,009,207 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 19,737 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Genetico;
import javax.swing.ButtonModel;
/**
*
* @author izacc
*/
public class GUI extends javax.swing.JFrame {
/**
* Creates new form GUI
*/
public GUI() {
initComponents();
aleatoria.setSelected(true);
puntos.setSelected(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
seleccion = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
aleatoria = new javax.swing.JRadioButton();
torneo = new javax.swing.JRadioButton();
mejor = new javax.swing.JRadioButton();
jPanel3 = new javax.swing.JPanel();
cr = new javax.swing.JComboBox<>();
jPanel4 = new javax.swing.JPanel();
puntos = new javax.swing.JRadioButton();
jPanel5 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
poblacion = new javax.swing.JTextField();
muta = new javax.swing.JTextField();
gen = new javax.swing.JTextField();
muestra = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jPanel6 = new javax.swing.JPanel();
ress = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccion"));
seleccion.add(aleatoria);
aleatoria.setText("Aleatoria");
seleccion.add(torneo);
torneo.setText("TorneoKL");
seleccion.add(mejor);
mejor.setText("Mejor");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(aleatoria)
.addComponent(torneo)
.addComponent(mejor))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(aleatoria)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(torneo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(mejor)
.addContainerGap(18, Short.MAX_VALUE))
);
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Cruza"));
cr.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Seleccionar", "Binaria", "AND", "OR", "XNOR", "XOR", "NOT", "NAND", "NOR" }));
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(cr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(cr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Muta"));
puntos.setText("2puntos");
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(puntos)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(puntos)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("General"));
jLabel1.setText("Poblacion :");
jLabel2.setText("Prob.Muta :");
jLabel3.setText("Generaciones :");
jLabel4.setText("Muestreo :");
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(muta, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE)
.addComponent(poblacion)))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(3, 3, 3)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(muestra)
.addComponent(gen))))
.addContainerGap())
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(poblacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(muta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(gen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(muestra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jButton1.setText("Start");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultado"));
ress.setText("Resultado...");
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(ress)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(ress)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jButton1))
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
int seleccion=0;
if(this.aleatoria.isSelected()){
seleccion=1;
}else if(this.torneo.isSelected()){
seleccion=2;
}else if(this.mejor.isSelected()){
seleccion=3;
}
int muta=0;
if(this.puntos.isSelected()){
muta=1;
}
int cruza=0;
if(cr.getSelectedIndex()>0){
cruza = cr.getSelectedIndex();
}
int tamP = Integer.parseInt(this.poblacion.getText());
int gen = Integer.parseInt(this.gen.getText());
double mutaP = Double.parseDouble(this.muta.getText());
int mues = Integer.parseInt(this.muestra.getText());
GeneticoV1 g = new GeneticoV1(tamP,gen,mutaP,mues);
g.evolucionar(seleccion,muta,cruza);
ress.setText(""+g.getPobActual().getMayor().getFitness());
System.out.println();
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JRadioButton aleatoria;
private javax.swing.JComboBox<String> cr;
private javax.swing.JTextField gen;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JRadioButton mejor;
private javax.swing.JTextField muestra;
private javax.swing.JTextField muta;
private javax.swing.JTextField poblacion;
private javax.swing.JRadioButton puntos;
private javax.swing.JLabel ress;
private javax.swing.ButtonGroup seleccion;
private javax.swing.JRadioButton torneo;
// End of variables declaration//GEN-END:variables
}
| [
"jisagiizacc@gmail.com"
] | jisagiizacc@gmail.com |
3027d4d5ad6d562aebe8fefbf6bf1d064ad63c6c | 501989f313f923b069c9c1b06a507463ab946e2b | /src/com/jspgou/cms/manager/impl/AdvertiseMngImpl.java | a5d08b3171365dac256055de6fca00908d452541 | [] | no_license | xrogzu/shop | fded93f9dbc801ff983362fc10d33ad7a8c07fad | 17568c709f64323e2b0dce06f4bc3d600a8157f8 | refs/heads/master | 2021-04-12T08:48:48.082699 | 2017-07-24T06:11:52 | 2017-07-24T06:16:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,607 | java | package com.jspgou.cms.manager.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jspgou.common.hibernate3.Updater;
import com.jspgou.common.page.Pagination;
import com.jspgou.cms.dao.AdvertiseDao;
import com.jspgou.cms.entity.Advertise;
import com.jspgou.cms.manager.AdspaceMng;
import com.jspgou.cms.manager.AdvertiseMng;
/**
* This class should preserve.
* @preserve
*/
@Service
@Transactional
public class AdvertiseMngImpl implements AdvertiseMng {
@Override
@Transactional(readOnly = true)
public Pagination getPage( Integer adspaceId,
Boolean enabled, int pageNo, int pageSize) {
Pagination page = dao.getPage( adspaceId, enabled, pageNo,
pageSize);
return page;
}
@Override
@Transactional(readOnly = true)
public List<Advertise> getList(Integer adspaceId, Boolean enabled) {
return dao.getList(adspaceId, enabled);
}
@Override
@Transactional(readOnly = true)
public Advertise findById(Integer id) {
Advertise entity = dao.findById(id);
return entity;
}
@Override
public Advertise save(Advertise bean, Integer adspaceId,
Map<String, String> attr) {
bean.setAdspace(adspaceMng.findById(adspaceId));
bean.setAttr(attr);
bean.init();
dao.save(bean);
return bean;
}
@Override
public Advertise update(Advertise bean, Integer adspaceId,
Map<String, String> attr) {
Updater<Advertise> updater = new Updater<Advertise>(bean);
bean = dao.updateByUpdater(updater);
bean.setAdspace(adspaceMng.findById(adspaceId));
bean.getAttr().clear();
bean.getAttr().putAll(attr);
return bean;
}
@Override
public Advertise deleteById(Integer id) {
Advertise bean = dao.deleteById(id);
return bean;
}
@Override
public Advertise[] deleteByIds(Integer[] ids) {
Advertise[] beans = new Advertise[ids.length];
for (int i = 0, len = ids.length; i < len; i++) {
beans[i] = deleteById(ids[i]);
}
return beans;
}
@Override
public void display(Integer id) {
Advertise ad = findById(id);
if (ad != null) {
ad.setDisplayCount(ad.getDisplayCount() + 1);
}
}
@Override
public void click(Integer id) {
Advertise ad = findById(id);
if (ad != null) {
ad.setClickCount(ad.getClickCount() + 1);
}
}
private AdspaceMng adspaceMng;
private AdvertiseDao dao;
@Autowired
public void setAdspaceMng(AdspaceMng adspaceMng) {
this.adspaceMng = adspaceMng;
}
@Autowired
public void setDao(AdvertiseDao dao) {
this.dao = dao;
}
} | [
"he.tang@everydayratings.com"
] | he.tang@everydayratings.com |
55fd2f2f86c807a687e9f22318f9415a4213fc91 | 6fde206c062b464929be2a53689a3ece8165e91f | /src/Search/DepthFirstSearch/Combination.java | f8c95e9eedb1a9d857bd71c7cac9654b15e08d94 | [] | no_license | cgcn/AlgorithmStudy | 3646bc2030fbe85b1e0e22f7d75f2fe117fa38ab | fc225b97e85db2287f243f118b0325cf3dd6c235 | refs/heads/master | 2020-09-12T15:33:48.037657 | 2017-09-06T12:47:06 | 2017-09-06T12:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,386 | java | package Search.DepthFirstSearch;
import java.util.Scanner;
/**
* Created by tlh on 2016/7/2.
* 组合算法 从n个数里取出m个数组合的算法
* 用01组合法
* 首先初始化,将数组前n个元素置1,表示第一个组合为前n个数。
* 然后从左到右扫描数组元素值的“10”组合,找到第一个“10”组合后将其变为
* “01”组合,同时将其左边的所有“1”全部移动到数组的最左端。
* 当第一个“1”移动到数组的m-n的位置,即n个“1”全部移动到最右端时,就得到了最后一个组合。
*/
public class Combination {
private int n;
private int m;
private int[] src;
//零一数组
private int[] zerones;
public Combination(int m, int n, int[] src) {
this.m = m;
this.n = n;
this.src = src;
zerones = new int[n];
for (int i = 0; i < m; i++) {
zerones[i] = 1;
}
}
public void run() {
while (true) {
outputCombination();
if (!findOneZero())
break;
}
}
private void outputCombination() {
for (int i = 0; i < n; i++) {
if (zerones[i] == 1)
System.out.print(src[i] + " ");
}
System.out.println();
}
private boolean findOneZero() {
int i;
for (i = 0; i < n - 1; i++) {
if (zerones[i] == 1 && zerones[i + 1] == 0) {
//将10组合变成01
zerones[i] = 0;
zerones[i + 1] = 1;
int ones = 0;
//将前面所有的1移到最右边
for (int j = 0; j < i; j++) {
if (zerones[j] == 1) ones++;
}
for (int j = 0; j < i; j++) {
if (j < ones)
zerones[j] = 1;
else zerones[j] = 0;
}
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] src = new int[n];
for (int i = 0; i < n; i++) {
src[i] = in.nextInt();
}
Combination p = new Combination(m, n, src);
p.run();
in.close();
}
}
| [
"570495627@qq.com"
] | 570495627@qq.com |
8dd08afe3a50e4b25275030fe8ce93ff6f9c8d05 | fe7213f7ac2521249c02496bf37c6d36fc935d65 | /HomeWorks/hw4/app/src/main/java/ru/mail/park/tfshw4/MainActivity.java | 6c2338414cfea03c8a51f70c4035838b9e7c38a9 | [] | no_license | 112Nick/AndroidSchool | 64e7ed2683718ccebcd50a9965785d5b814b572f | 7893be1e6a4a97cf344eb043ea1663398b54608f | refs/heads/master | 2020-04-04T10:10:53.164196 | 2018-11-02T09:46:52 | 2018-11-02T09:46:52 | 155,845,222 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,631 | java | package ru.mail.park.tfshw4;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static Integer number = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addBtn = findViewById(R.id.add_btn);
Button deleteBtn = findViewById(R.id.delete_btn);
Button deleteAllBtn = findViewById(R.id.delete_all_btn);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
number++;
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, MyFragment.newInstance(number))
.addToBackStack(null)
.commit();
}
});
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (number != 0) {
number--;
}
getSupportFragmentManager().popBackStack();
}
});
deleteAllBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < number; i++) {
getSupportFragmentManager().popBackStack();
}
number = 0;
}
});
}
}
| [
"mrnickrus@gmail.com"
] | mrnickrus@gmail.com |
c98e053d69793863f8f3b6732df0b8a99b6b5059 | 9f8559d293595896f9d6665a67296e6a631a1174 | /app/src/main/java/app/usman/popular_movies/Top_rated.java | f13d8594796aca392697bcca3111b1e4f0e22b34 | [] | no_license | usmanjilani95/Popular-Movies-P1 | 32fe5b6f33aa3ddb6d265f48f8dee525ec50a396 | 7ba59dafd119e70df458a47dc884c61b6f19bf2e | refs/heads/master | 2021-01-01T04:35:39.489441 | 2016-06-10T14:12:29 | 2016-06-10T14:12:29 | 56,529,957 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 29,987 | java | package app.usman.popular_movies;
/**
* Created by Usman Ahmad Jilani on 10-06-2016.
*/
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.twotoasters.jazzylistview.recyclerview.JazzyRecyclerViewScrollListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class Top_rated extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private GridLayoutManager mLayoutManager;
final ArrayList<String> imglist = new ArrayList<String>();
final ArrayList<String> titlelist = new ArrayList<String>();
final ArrayList<String> back_imglist = new ArrayList<String>();
final ArrayList<String> plotlist = new ArrayList<String>();
final ArrayList<String> user_ratinglist = new ArrayList<String>();
final ArrayList<String> release_datelist = new ArrayList<String>();
ArrayList<String> genre = new ArrayList<String>();
ArrayList<Integer> popularity = new ArrayList<Integer>();
ArrayList<String> language = new ArrayList<String>();
final ArrayList<String> id_list = new ArrayList<String>();
JazzyRecyclerViewScrollListener jazzyScrollListener;
String API_KEY;
FragmentManager fm;
public Top_rated() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
fm= getFragmentManager();
mRecyclerView.setHasFixedSize(true);
API_KEY=getActivity().getResources().getString(R.string.API_KEY);
if (getResources().getConfiguration().orientation == 2) {
mLayoutManager = new GridLayoutManager(getActivity(), 3);
mRecyclerView.setLayoutManager(mLayoutManager);
String url = "https://api.themoviedb.org/3/movie/top_rated?api_key="+API_KEY;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray json = response.getJSONArray("results");
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
String movy = jsonObject.getString("poster_path");
String site = "http://image.tmdb.org/t/p/w300/" + movy;
imglist.add(site);
String title = jsonObject.getString("title");
titlelist.add(title);
String backdrop_path = jsonObject.getString("backdrop_path");
String back_img = "http://image.tmdb.org/t/p/w500/" + backdrop_path;
back_imglist.add(back_img);
String plot = jsonObject.getString("overview");
plotlist.add(plot);
String user_rating = jsonObject.getString("vote_average");
user_ratinglist.add(user_rating);
String release_date = jsonObject.getString("release_date");
release_datelist.add(release_date);
String id= jsonObject.getString("id");
id_list.add(id);
popularity.add(jsonObject.getInt("popularity"));
language.add(jsonObject.getString("original_language"));
JSONArray ja= jsonObject.getJSONArray("genre_ids");
genre.add(ja.getString(0));
}
mAdapter = new MyAdapter1(imglist);
mRecyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
isOnline();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
isOnline();
}
});
Volley.newRequestQueue(getActivity()).add(jsonRequest);
mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int current_page) {
String url = "https://api.themoviedb.org/3/movie/top_rated?page=" + current_page + "&&api_key="+API_KEY;;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray json = response.getJSONArray("results");
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
String movy = jsonObject.getString("poster_path");
String site = "http://image.tmdb.org/t/p/w300/" + movy;
imglist.add(site);
String title = jsonObject.getString("title");
titlelist.add(title);
String backdrop_path = jsonObject.getString("backdrop_path");
String back_img = "http://image.tmdb.org/t/p/w500/" + backdrop_path;
back_imglist.add(back_img);
String plot = jsonObject.getString("overview");
plotlist.add(plot);
String user_rating = jsonObject.getString("vote_average");
user_ratinglist.add(user_rating);
String release_date = jsonObject.getString("release_date");
release_datelist.add(release_date);
String id= jsonObject.getString("id");
id_list.add(id);
popularity.add(jsonObject.getInt("popularity"));
language.add(jsonObject.getString("original_language"));
JSONArray ja= jsonObject.getJSONArray("genre_ids");
genre.add(ja.getString(0));
}
mAdapter.notifyItemInserted(imglist.size() - 1);
} catch (JSONException e) {
e.printStackTrace();
isOnline();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
isOnline();
}
});
Volley.newRequestQueue(getActivity()).add(jsonRequest);
}
});
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
boolean dual_pane = getResources().getBoolean(R.bool.dual_pane);
if (dual_pane) {
Tab_description tabletDetailFragment = new Tab_description();
Bundle b1 = new Bundle();
b1.putString("title", titlelist.get(position));
b1.putString("b_img", back_imglist.get(position));
b1.putString("overview", plotlist.get(position));
b1.putString("vote", user_ratinglist.get(position));
b1.putString("r_date", release_datelist.get(position));
b1.putString("p_img", imglist.get(position));
b1.putString("id", id_list.get(position));
b1.putString("genre", genre.get(position));
b1.putInt("popularity", popularity.get(position));
b1.putString("language", language.get(position));
tabletDetailFragment.setArguments(b1);
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.details_frag, tabletDetailFragment);
ft.commit();
} else {
Intent intent = new Intent(getActivity(), Movie_description.class);
intent.putExtra("title", titlelist.get(position));
intent.putExtra("b_img", back_imglist.get(position));
intent.putExtra("overview", plotlist.get(position));
intent.putExtra("vote", user_ratinglist.get(position));
intent.putExtra("r_date", release_datelist.get(position));
intent.putExtra("p_img", imglist.get(position));
intent.putExtra("id", id_list.get(position));
intent.putExtra("genre", genre.get(position));
intent.putExtra("popularity", popularity.get(position));
intent.putExtra("language", language.get(position));
startActivity(intent);
}
}
})
);
} else if (getResources().getConfiguration().orientation == 1) {
mLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mLayoutManager);
String url = "https://api.themoviedb.org/3/movie/top_rated?api_key="+API_KEY;;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray json = response.getJSONArray("results");
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
String movy = jsonObject.getString("poster_path");
String site = "http://image.tmdb.org/t/p/w185/" + movy;
imglist.add(site);
String title = jsonObject.getString("title");
titlelist.add(title);
String backdrop_path = jsonObject.getString("backdrop_path");
String back_img = "http://image.tmdb.org/t/p/w500/" + backdrop_path;
back_imglist.add(back_img);
String plot = jsonObject.getString("overview");
plotlist.add(plot);
String user_rating = jsonObject.getString("vote_average");
user_ratinglist.add(user_rating);
String release_date = jsonObject.getString("release_date");
release_datelist.add(release_date);
String id= jsonObject.getString("id");
id_list.add(id);
popularity.add(jsonObject.getInt("popularity"));
language.add(jsonObject.getString("original_language"));
JSONArray ja= jsonObject.getJSONArray("genre_ids");
genre.add(ja.getString(0));
}
mAdapter = new MyAdapter1(imglist);
mRecyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
isOnline();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
isOnline();
}
});
Volley.newRequestQueue(getActivity()).add(jsonRequest);
mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int current_page) {
String url = "https://api.themoviedb.org/3/movie/top_rated?page=" + current_page + "&&api_key="+API_KEY;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray json = response.getJSONArray("results");
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
String movy = jsonObject.getString("poster_path");
String site = "http://image.tmdb.org/t/p/w185/" + movy;
imglist.add(site);
String title = jsonObject.getString("title");
titlelist.add(title);
String backdrop_path = jsonObject.getString("backdrop_path");
String back_img = "http://image.tmdb.org/t/p/w500/" + backdrop_path;
back_imglist.add(back_img);
String plot = jsonObject.getString("overview");
plotlist.add(plot);
String user_rating = jsonObject.getString("vote_average");
user_ratinglist.add(user_rating);
String release_date = jsonObject.getString("release_date");
release_datelist.add(release_date);
String id= jsonObject.getString("id");
id_list.add(id);
popularity.add(jsonObject.getInt("popularity"));
language.add(jsonObject.getString("original_language"));
JSONArray ja= jsonObject.getJSONArray("genre_ids");
genre.add(ja.getString(0));
}
mAdapter.notifyItemInserted(imglist.size() - 1);
} catch (JSONException e) {
e.printStackTrace();
isOnline();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
isOnline();
}
});
Volley.newRequestQueue(getActivity()).add(jsonRequest);
}
});
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
boolean dual_pane = getResources().getBoolean(R.bool.dual_pane);
if (dual_pane) {
Tab_description tabletDetailFragment = new Tab_description();
Bundle b1 = new Bundle();
b1.putString("title", titlelist.get(position));
b1.putString("b_img", back_imglist.get(position));
b1.putString("overview", plotlist.get(position));
b1.putString("vote", user_ratinglist.get(position));
b1.putString("r_date", release_datelist.get(position));
b1.putString("p_img", imglist.get(position));
b1.putString("id", id_list.get(position));
b1.putString("genre", genre.get(position));
b1.putInt("popularity", popularity.get(position));
b1.putString("language", language.get(position));
tabletDetailFragment.setArguments(b1);
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.details_frag, tabletDetailFragment);
ft.commit();
} else {
Intent intent = new Intent(getActivity(), Movie_description.class);
intent.putExtra("title", titlelist.get(position));
intent.putExtra("b_img", back_imglist.get(position));
intent.putExtra("overview", plotlist.get(position));
intent.putExtra("vote", user_ratinglist.get(position));
intent.putExtra("r_date", release_datelist.get(position));
intent.putExtra("p_img", imglist.get(position));
intent.putExtra("id", id_list.get(position));
intent.putExtra("genre", genre.get(position));
intent.putExtra("popularity", popularity.get(position));
intent.putExtra("language", language.get(position));
startActivity(intent);
}
}
})
);
}
return view;
}
public void isOnline() {
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
API_KEY=getActivity().getResources().getString(R.string.API_KEY);
if(activeNetwork==null){
Snackbar.make(mRecyclerView, "Please Connect to the Internet", Snackbar.LENGTH_LONG)
.setAction("Retry", new View.OnClickListener() {
@Override
public void onClick(View v) {
isOnline();
}
})
.setDuration(Snackbar.LENGTH_INDEFINITE)
.show();
}
else
{
imglist.clear();
titlelist.clear();
back_imglist.clear();
plotlist.clear();
user_ratinglist.clear();
release_datelist.clear();
id_list.clear();
genre.clear();
language.clear();
popularity.clear();
String url = "https://api.themoviedb.org/3/movie/top_rated?api_key="+API_KEY;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
JSONArray json = response.getJSONArray("results");
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
String movy = jsonObject.getString("poster_path");
String site = "http://image.tmdb.org/t/p/w185/" + movy;
imglist.add(site);
String title = jsonObject.getString("title");
titlelist.add(title);
String backdrop_path = jsonObject.getString("backdrop_path");
String back_img = "http://image.tmdb.org/t/p/w500/" + backdrop_path;
back_imglist.add(back_img);
String plot = jsonObject.getString("overview");
plotlist.add(plot);
String user_rating = jsonObject.getString("vote_average");
user_ratinglist.add(user_rating);
String release_date = jsonObject.getString("release_date");
release_datelist.add(release_date);
String id= jsonObject.getString("id");
id_list.add(id);
popularity.add(jsonObject.getInt("popularity"));
language.add(jsonObject.getString("original_language"));
JSONArray ja= jsonObject.getJSONArray("genre_ids");
genre.add(ja.getString(0));
}
mAdapter = new MyAdapter(imglist);
mRecyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
isOnline();
//Toast.makeText(getActivity(), "Something went wrong!!please check your connection 111", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
isOnline();
//Toast.makeText(getActivity(), "Something went wrong!!please check your connection", Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(getActivity()).add(jsonRequest);
mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int current_page) {
// do something...
String url = "https://api.themoviedb.org/3/movie/top_rated?page=" + current_page + "&&api_key="+API_KEY;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
JSONArray json = response.getJSONArray("results");
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
String movy = jsonObject.getString("poster_path");
String site = "http://image.tmdb.org/t/p/w300/" + movy;
imglist.add(site);
String title = jsonObject.getString("title");
titlelist.add(title);
String backdrop_path = jsonObject.getString("backdrop_path");
String back_img = "http://image.tmdb.org/t/p/w500/" + backdrop_path;
back_imglist.add(back_img);
String plot = jsonObject.getString("overview");
plotlist.add(plot);
String user_rating = jsonObject.getString("vote_average");
user_ratinglist.add(user_rating);
String release_date = jsonObject.getString("release_date");
release_datelist.add(release_date);
String id= jsonObject.getString("id");
id_list.add(id);
popularity.add(jsonObject.getInt("popularity"));
language.add(jsonObject.getString("original_language"));
JSONArray ja= jsonObject.getJSONArray("genre_ids");
genre.add(ja.getString(0));
}
mAdapter.notifyItemInserted(imglist.size() - 1);
} catch (JSONException e) {
e.printStackTrace();
isOnline();
//Toast.makeText(getActivity(), "Something went wrong!!please check your connection 111", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
isOnline();
//Toast.makeText(getActivity(), "Something went wrong!!please check your connection", Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(getActivity()).add(jsonRequest);
}
});
}
}
} | [
"usmanjilani95@gmail.com"
] | usmanjilani95@gmail.com |
84a0fc1ecdb687a0eca0eb540fb1c28b52068426 | 9ede3a90b1e3da090300e6b036eb234495e4df16 | /duoduophoto/src/main/java/com/laocuo/duoduophoto/util/ImageResizer.java | f4a160d439ac434b1317eef156af5bf0519ef071 | [] | no_license | laocuo/duoduophoto | 21b117019b56a30d4e91e68b93b96b98153e78d6 | 44697624d6372ff19de5149ae3084790263d84f7 | refs/heads/master | 2016-09-15T02:47:10.965437 | 2016-05-31T02:41:25 | 2016-05-31T02:41:25 | 46,961,026 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,192 | java | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.laocuo.duoduophoto.util;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.laocuo.duoduophoto.BuildConfig;
/**
* A simple subclass of {@link ImageWorker} that resizes images from resources
* given a target width and height. Useful for when the input images might be
* too large to simply load directly into memory.
*/
public class ImageResizer extends ImageWorker {
private static final String TAG = "ImageWorker";
protected int mImageWidth;
protected int mImageHeight;
/**
* Initialize providing a single target image size (used for both width and
* height);
*
* @param activity
* @param imageWidth
* @param imageHeight
*/
public ImageResizer(Activity activity, int imageWidth, int imageHeight) {
super(activity);
setImageSize(imageWidth, imageHeight);
}
/**
* Initialize providing a single target image size (used for both width and
* height);
*
* @param activity
* @param imageSize
*/
public ImageResizer(Activity activity, int imageSize) {
super(activity);
setImageSize(imageSize);
}
/**
* Set the target image width and height.
*
* @param width
* @param height
*/
public void setImageSize(int width, int height) {
mImageWidth = width;
mImageHeight = height;
}
/**
* Set the target image size (width and height will be the same).
*
* @param size
*/
public void setImageSize(int size) {
setImageSize(size, size);
}
/**
* The main processing method. This happens in a background task. In this case
* we are just sampling down the bitmap and returning it from a resource.
*
* @param resId
* @return
*/
private Bitmap processBitmap(int resId) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "processBitmap - " + resId);
}
return decodeSampledBitmapFromResource(mActivity.getResources(),
resId, mImageWidth, mImageHeight);
}
@Override
protected Bitmap processBitmap(Object data) {
// return processBitmap(Integer.parseInt(String.valueOf(data)));
return processBitmap(String.valueOf(data));
}
private Bitmap processBitmap(String filename) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "processBitmap - " + filename);
}
return decodeScaledBitmapFromFile(filename, mImageWidth, mImageHeight);
// return decodeSampledBitmapFromFile(filename, mImageWidth, mImageHeight);
}
/**
* Decode and sample down a bitmap from resources to the requested width and
* height.
*
* @param res
* The resources object containing the image data
* @param resId
* The resource id of the image data
* @param reqWidth
* The requested width of the resulting bitmap
* @param reqHeight
* The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect ratio
* and dimensions that are equal to or greater than the requested
* width and height
*/
public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
/**
* Decode and sample down a bitmap from a file to the requested width and
* height.
*
* @param filename
* The full path of the file to decode
* @param reqWidth
* The requested width of the resulting bitmap
* @param reqHeight
* The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect ratio
* and dimensions that are equal to or greater than the requested
* width and height
*/
public static synchronized Bitmap decodeSampledBitmapFromFile(
String filename, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
//add by laocuo@163.com
public static synchronized Bitmap decodeScaledBitmapFromFile(
String filename, int reqWidth, int reqHeight) {
Bitmap b = null, rb;
try {
b = decodeSampledBitmapFromFile(filename, reqWidth, reqHeight);
rb = Bitmap.createScaledBitmap(b, reqWidth, reqHeight, false);
} catch (OutOfMemoryError e) {
Log.d("zhaocheng", "OutOfMemoryError");
return null;
}
b.recycle();
return rb;
}
/**
* Calculate an inSampleSize for use in a {@link BitmapFactory.Options} object
* when decoding bitmaps using the decode* methods from {@link BitmapFactory}.
* This implementation calculates the closest inSampleSize that will result in
* the final decoded bitmap having a width and height equal to or larger than
* the requested width and height. This implementation does not ensure a power
* of 2 is returned for inSampleSize which can be faster when decoding but
* results in a larger bitmap which isn't as useful for caching purposes.
*
* @param options
* An options object with out* params already populated (run through
* a decode* method with inJustDecodeBounds==true
* @param reqWidth
* The requested width of the resulting bitmap
* @param reqHeight
* The requested height of the resulting bitmap
* @return The value to be used for inSampleSize
*/
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger
// inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down
// further.
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
}
| [
"laocuo@163.com"
] | laocuo@163.com |
39729d8c35439f1b9037f91df4addc4853c1934e | 243e9e5a1abf23a7c9c4c57ed94fd54f394d7fb7 | /app/src/main/java/com/memaro/courseroomrx/usecases/database/NoteDatabase.java | e80dd96fd469eece9d7b84f60253f215fcdb2456 | [] | no_license | amir58/CourseRoomRx | b9f6e67cda54e79fc731b93de47698dcc3ccad01 | 15bb2782ba726a40eaf0f5fefd5eea9f8102002d | refs/heads/master | 2020-12-08T13:25:11.920007 | 2020-10-21T20:22:09 | 2020-10-21T20:22:09 | 232,992,439 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 846 | java | package com.memaro.courseroomrx.usecases.database;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.memaro.courseroomrx.entities.Note;
@Database(entities = {Note.class}, version = 3)
public abstract class NoteDatabase extends RoomDatabase {
public abstract NoteDao noteDao();
private static volatile NoteDatabase INSTANCE;
public static NoteDatabase getDatabase(Context context) {
if (INSTANCE == null) {
synchronized (NoteDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context,
NoteDatabase.class, "note_database")
.build();
}
}
}
return INSTANCE;
}
}
| [
"devamir11@gmail.com"
] | devamir11@gmail.com |
37a67714873f67be3c664d35b7596f0cf02d525a | 5805647f82e4c663ddbef45692cfa9e42136d284 | /app/src/main/java/com/example/pandey/projectx/HomeScreen.java | 2635c99a7d753eed842d954562ed66b937d8cff5 | [] | no_license | sushantnitk/ProjectX | f9be8126afb46dbc8ed8d57ad018a1661b1f5efd | d41a6758be9695da8911a135a039b82613257ac6 | refs/heads/master | 2020-06-11T22:16:35.658512 | 2016-12-05T11:43:27 | 2016-12-05T11:43:27 | 75,617,588 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,271 | java | package com.example.pandey.projectx;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.pandey.projectx.Utility.AlertDialogManager;
import com.example.pandey.projectx.Utility.Session;
import org.w3c.dom.Text;
import java.util.HashMap;
/**
* Created by Pandey on 11-11-2016.
*/
public class HomeScreen extends AppCompatActivity {
AlertDialogManager alert = new AlertDialogManager();
// Session Manager Class
Session session;
// Button Logout
Button btnLogout;
TextView name,email;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
session= new Session(getApplicationContext());
name=(TextView)findViewById(R.id.lblName);
email=(TextView)findViewById(R.id.lblEmail);
btnLogout=(Button)findViewById(R.id.btnLogout);
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isUserLoggedIn(), Toast.LENGTH_LONG).show();
session.checkLogin();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// name
String sname = user.get(Session.KEY_NAME);
// email
String semail = user.get(Session.KEY_EMAIL);
// displaying user data
name.setText(Html.fromHtml("Name: <b>" + name + "</b>"));
email.setText(Html.fromHtml("Email: <b>" + email + "</b>"));
/**
* Logout button click event
* */
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Clear the session data
// This will clear all session data and
// redirect user to LoginActivity
session.logoutUser();
}
});
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
}
| [
"sushantraj232@gmail.com"
] | sushantraj232@gmail.com |
8274303e073fd32007da2cdd614d1da0ddf8134b | bdbf1261af80c48166d02d864658193983346217 | /src/main/java/br/com/grupopibb/portalrh/model/Filial.java | d3dcd7c800558001e6b2c1d46b85ecb087ed0738 | [] | no_license | Manhattan/portalrh | d5e939048777bc4d9fb617640154b0e6f879819d | 4abfb38cecbe4edc8bb3d90ddd96e2616e2983b3 | refs/heads/master | 2021-01-22T11:46:34.228676 | 2015-03-31T17:44:17 | 2015-03-31T17:44:17 | 23,804,106 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,803 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.grupopibb.portalrh.model;
import br.com.grupopibb.portalrh.model.commons.EntityInterface;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* @author administrator
*/
@Entity
@Table(name = "Filial")
@NamedQuery(name = "Filial.findByEmpresa",
query = "SELECT DISTINCT f FROM Filial f "
+ " WHERE f.empresaCod = :empresaCod")
public class Filial implements EntityInterface<Filial> {
@Id
@Column(name = "Empresa_Cod")
private String empresaCod;
/*
*/
@Id
@Column(name = "Filial_Cod")
private String codigo;
/*
*/
@Column(name = "Filial_Nome")
private String nome;
@Override
public Serializable getId() {
return empresaCod + codigo;
}
@Override
public String getLabel() {
return codigo + " - " + nome;
}
@Override
public boolean verificarId() {
return false;
}
@Override
public boolean isMarcado() {
return false;
}
@Override
public int compareTo(Filial o) {
return o.getId().toString().compareTo(o.getId().toString());
}
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + (this.empresaCod != null ? this.empresaCod.hashCode() : 0);
hash = 97 * hash + (this.codigo != null ? this.codigo.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Filial other = (Filial) obj;
if ((this.empresaCod == null) ? (other.empresaCod != null) : !this.empresaCod.equals(other.empresaCod)) {
return false;
}
if ((this.codigo == null) ? (other.codigo != null) : !this.codigo.equals(other.codigo)) {
return false;
}
return true;
}
@Override
public String toString() {
return codigo;
}
public String getEmpresaCod() {
return empresaCod;
}
public void setEmpresaCod(String empresaCod) {
this.empresaCod = empresaCod;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
| [
"tone.lima@gpdttecw0801.grupopibb.corp"
] | tone.lima@gpdttecw0801.grupopibb.corp |
70e6beb57ea461a2e4f7f5566a7f30bba50703c4 | 0a28aed656ea6ea34c5491e41843e41ba65bbc0b | /src/main/java/org/alessiodm/ringer/util/MD5Util.java | 31aad1b3f0a001fce75cc9c176255a3280bbd7ec | [
"MIT"
] | permissive | alessiodm/ringer | d88d50961d37dde992c76640501ab5a0c8706762 | 041657d3087254fd0be21bc2bc737897dc7c1755 | refs/heads/master | 2018-12-28T21:18:30.010713 | 2013-05-02T15:08:31 | 2013-05-02T15:08:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,100 | java | package org.alessiodm.ringer.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
/**
* Very simple encryption salt + MD5
*
* @param toenc String to encode
* @param salt Salt for encoding
* @return Encoded String
*/
public static String encrypt(String toenc, String salt){
if (salt != null){
toenc += salt + "!@!" + salt;
}
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
md.update(toenc.getBytes());
byte[] byteData = md.digest();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
} catch (NoSuchAlgorithmException ex) {
return null;
}
}
public static void main(String[] args){
System.out.println(MD5Util.encrypt("user3", "user3"));
}
}
| [
"alessio.dellamotta@gmail.com"
] | alessio.dellamotta@gmail.com |
4987a384a58434043da8a3e2a199bcbe8cb08ef5 | 59d801909b961ef1b3d0f0c74425749c9744c61f | /Java Design Patterns/abstract-factory/King.java | 85a69e1c1049928a17a548f8e4427b7466a4d137 | [] | no_license | SixYearsInFebruary/ReadingRecord | 2ccac81765d4b74fbdcb0015dba4b508e7f13cc6 | 1a684f91569eabf61044d74edd9ce422a5d2fe20 | refs/heads/master | 2020-05-20T15:37:43.989609 | 2015-08-23T14:29:51 | 2015-08-23T14:29:51 | 37,798,161 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 27 | java | public interface King {
} | [
"549309505@qq.com"
] | 549309505@qq.com |
5624ebc096547849bea48ddb887e12f165317b20 | d24f7eb444c64089a80cdfcde48960169fc4cf39 | /algorithms/LeetCode/src/leetcode/kthsmallest/lexico/Solution.java | 335ea8cd1af4250ddb73c5471dd93fb685f8974a | [] | no_license | soniclavier/learn | 7ffeaac70760a01aadb0324dd19083272ee3b5d2 | eb13efd2c9947f1b60eef9877668abe72909ec55 | refs/heads/master | 2020-04-03T20:07:19.332724 | 2018-10-20T06:20:26 | 2018-10-20T06:20:26 | 30,120,079 | 1 | 1 | null | 2016-09-10T21:58:35 | 2015-01-31T17:36:07 | HTML | UTF-8 | Java | false | false | 329 | java | package leetcode.kthsmallest.lexico;
/**
* Created by vviswanath on 9/21/17.
*/
public class Solution {
/*
public int findKthNumber(int n, int k) {
}*/
public static void main(String[] args) {
Solution sl = new Solution();
//System.out.println(sl.findKthNumber(1000000000, 2 - 1));
}
}
| [
"vishnu.viswanath25@gmail.com"
] | vishnu.viswanath25@gmail.com |
d36a3c40d41fc1f61d16be54b5ec6f83bf1a6fb0 | ee1637457cb85e3715f8f26a089169185db46cdf | /module_kchart/src/main/java/com/at/kchart/charting/data/PieData.java | 9a434a761c8c13c0d70ba54e636d0be1fe190d56 | [] | no_license | safe-ending/AtRouter | 5660fd003372b06ea25a2b8ca514f5269c99d646 | 51480624662b9072529ab3b8d7acfe65f5dc5b8f | refs/heads/master | 2020-05-14T15:58:32.753170 | 2019-09-03T02:56:44 | 2019-09-03T02:56:44 | 181,863,919 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,191 | java |
package com.at.kchart.charting.data;
import com.at.kchart.charting.highlight.Highlight;
import com.at.kchart.charting.interfaces.datasets.IPieDataSet;
/**
* A PieData object can only represent one DataSet. Unlike all other charts, the
* legend labels of the PieChart are created from the x-values array, and not
* from the DataSet labels. Each PieData object can only represent one
* PieDataSet (multiple PieDataSets inside a single PieChart are not possible).
*
* @author Philipp Jahoda
*/
public class PieData extends ChartData<IPieDataSet> {
public PieData() {
super();
}
public PieData(IPieDataSet dataSet) {
super(dataSet);
}
/**
* Sets the PieDataSet this data object should represent.
*
* @param dataSet
*/
public void setDataSet(IPieDataSet dataSet) {
mDataSets.clear();
mDataSets.add(dataSet);
notifyDataChanged();
}
/**
* Returns the DataSet this PieData object represents. A PieData object can
* only contain one DataSet.
*
* @return
*/
public IPieDataSet getDataSet() {
return mDataSets.get(0);
}
/**
* The PieData object can only have one DataSet. Use getDataSet() method instead.
*
* @param index
* @return
*/
@Override
public IPieDataSet getDataSetByIndex(int index) {
return index == 0 ? getDataSet() : null;
}
@Override
public IPieDataSet getDataSetByLabel(String label, boolean ignorecase) {
return ignorecase ? label.equalsIgnoreCase(mDataSets.get(0).getLabel()) ? mDataSets.get(0)
: null : label.equals(mDataSets.get(0).getLabel()) ? mDataSets.get(0) : null;
}
@Override
public Entry getEntryForHighlight(Highlight highlight) {
return getDataSet().getEntryForIndex((int) highlight.getX());
}
/**
* Returns the sum of all values in this PieData object.
*
* @return
*/
public float getYValueSum() {
float sum = 0;
for (int i = 0; i < getDataSet().getEntryCount(); i++) {
sum += getDataSet().getEntryForIndex(i).getY();
}
return sum;
}
}
| [
"592953547@qq.com"
] | 592953547@qq.com |
2475d73d3d049b837be48ff02c15c6901996a8dd | b3661355c85ee112ee5db65fd1da2ce1ca633b35 | /version2/src/by/epam/javatraining/halavin/taskone/lib/controller/command/GetIsCrossCoorPlane.java | 29813312c9dc216cf38f63add77b1fb379ba8a20 | [] | no_license | Epimedo/EpamFirstTask | 3049eacb0ef9443ad12b7b86f1ab562765d47a47 | b8c25d95d36f86833c02e788f67004e28e2a2c2e | refs/heads/master | 2020-04-10T13:56:35.921921 | 2018-12-17T07:29:14 | 2018-12-17T07:29:14 | 161,063,185 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,006 | java | package by.epam.javatraining.halavin.taskone.lib.controller.command;
import org.apache.log4j.Logger;
import by.epam.javatraining.halavin.taskone.lib.bean.impl.Shape;
import by.epam.javatraining.halavin.taskone.lib.controller.command.impl.ShapeCommand;
import by.epam.javatraining.halavin.taskone.lib.service.exception.ServiceException;
import by.epam.javatraining.halavin.taskone.lib.service.factory.ServiceFactory;
import by.epam.javatraining.halavin.taskone.lib.service.impl.MethodsForShapeService;
public class GetIsCrossCoorPlane implements ShapeCommand {
private final Logger LOG = Logger.getLogger(GetIsCrossCoorPlane.class);
@Override
public String execute(String request, Shape shape) {
String responce = null;
ServiceFactory servicefactory = ServiceFactory.getInstance();
MethodsForShapeService methods = servicefactory.getMethodsForShapeService();
try {
responce = "" + methods.isCoorPlane(shape);
} catch (ServiceException e) {
LOG.error(e);
}
return responce;
}
}
| [
"eggol@icloud.com"
] | eggol@icloud.com |
a2aa7bdf0ff3721e988233ea05c1373f73e2e38c | 7c451bd83121499809c97c6b881308115e095332 | /backend/src/main/java/com/nelioalves/services/validation/ClienteUpdate.java | 74a27918eed7d39e188ca18455bb5043b0d09b9c | [] | no_license | leonardo-teles/pedidos | 699fc2855ae9ac1c9d4024c4052c8406d681db4c | 1b34bd10a92d951be01f030f33df1567887e5ab2 | refs/heads/main | 2023-05-21T16:58:10.447207 | 2021-06-08T18:37:09 | 2021-06-08T18:37:09 | 364,030,266 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 570 | java | package com.nelioalves.services.validation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Constraint(validatedBy = ClienteUpdateValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ClienteUpdate {
String message() default "Erro de validação";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| [
"leonardo.teles.almeida@gmail.com"
] | leonardo.teles.almeida@gmail.com |
7c81530f6ea8d69412f92c1667791828356c8031 | e58a8e0fb0cfc7b9a05f43e38f1d01a4d8d8cf1f | /MazeRunner2/src/com/puttysoftware/mazerunner2/creatures/monsters/AbstractBothRandomScalingMonster.java | 7e4454d0b37cd382b987da886b8c8eed0fd5a337 | [
"Unlicense"
] | permissive | retropipes/older-java-games | 777574e222f30a1dffe7936ed08c8bfeb23a21ba | 786b0c165d800c49ab9977a34ec17286797c4589 | refs/heads/master | 2023-04-12T14:28:25.525259 | 2021-05-15T13:03:54 | 2021-05-15T13:03:54 | 235,693,016 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,648 | java | /* MazeRunnerII: An RPG
Copyright (C) 2011-2012 Eric Ahnell
Any questions should be directed to the author via email at: products@puttysoftware.com
*/
package com.puttysoftware.mazerunner2.creatures.monsters;
import com.puttysoftware.mazerunner2.creatures.StatConstants;
import com.puttysoftware.mazerunner2.creatures.party.PartyManager;
import com.puttysoftware.randomrange.RandomRange;
abstract class AbstractBothRandomScalingMonster
extends AbstractBothRandomMonster {
// Constructors
AbstractBothRandomScalingMonster() {
super();
}
@Override
public void loadMonster() {
final int newLevel = PartyManager.getParty().getPartyMeanLevel();
this.setLevel(newLevel);
this.setVitality(this.getInitialVitality());
this.setCurrentHP(this.getMaximumHP());
this.setIntelligence(this.getInitialIntelligence());
this.setCurrentMP(this.getMaximumMP());
this.setStrength(this.getInitialStrength());
this.setBlock(this.getInitialBlock());
this.setAgility(this.getInitialAgility());
this.setLuck(this.getInitialLuck());
this.setGold(this.getInitialGold());
this.setExperience((long) (this.getInitialExperience()
* this.adjustForLevelDifference()));
this.setAttacksPerRound(1);
this.setSpellsPerRound(1);
this.image = this.getInitialImage();
}
@Override
public boolean scales() {
return true;
}
private int getInitialStrength() {
final RandomRange r = new RandomRange(1,
Math.max(this.getLevel() * StatConstants.GAIN_STRENGTH, 1));
return r.generate();
}
private int getInitialBlock() {
final RandomRange r = new RandomRange(0,
this.getLevel() * StatConstants.GAIN_BLOCK);
return r.generate();
}
private long getInitialExperience() {
int minvar, maxvar;
minvar = (int) (this.getLevel()
* AbstractMonster.MINIMUM_EXPERIENCE_RANDOM_VARIANCE);
maxvar = (int) (this.getLevel()
* AbstractMonster.MAXIMUM_EXPERIENCE_RANDOM_VARIANCE);
final RandomRange r = new RandomRange(minvar, maxvar);
final long expbase = PartyManager.getParty().getPartyMaxToNextLevel();
final long factor = this.getBattlesToNextLevel();
return expbase / factor + r.generateLong();
}
private int getToughness() {
return this.getStrength() + this.getBlock() + this.getAgility()
+ this.getVitality() + this.getIntelligence() + this.getLuck();
}
private int getInitialGold() {
final int min = 0;
final int max = this.getToughness()
* AbstractMonster.GOLD_TOUGHNESS_MULTIPLIER;
final RandomRange r = new RandomRange(min, max);
return r.generate();
}
private int getInitialAgility() {
final RandomRange r = new RandomRange(1,
Math.max(this.getLevel() * StatConstants.GAIN_AGILITY, 1));
return r.generate();
}
private int getInitialVitality() {
final RandomRange r = new RandomRange(1,
Math.max(this.getLevel() * StatConstants.GAIN_VITALITY, 1));
return r.generate();
}
private int getInitialIntelligence() {
final RandomRange r = new RandomRange(0,
this.getLevel() * StatConstants.GAIN_INTELLIGENCE);
return r.generate();
}
private int getInitialLuck() {
final RandomRange r = new RandomRange(0,
this.getLevel() * StatConstants.GAIN_LUCK);
return r.generate();
}
}
| [
"eric.ahnell@puttysoftware.com"
] | eric.ahnell@puttysoftware.com |
d61486f55757de8b36db1af2321722466354383d | 077f81916b719a57435ae579628977c3ebbc1478 | /trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/taglib/ForEachTag.java | 9fbe19a266b9362e2232b9d7aa9fa3a4606c4728 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | m-y-mo/myfaces-trinidad_20165019 | e9f2da811aaa07160b8b660fa13743750c5932d4 | 43125e45e1c56fab0cc56e32d079be787209d3b4 | refs/heads/master | 2020-03-07T10:27:37.758086 | 2018-03-30T13:34:10 | 2018-03-30T13:34:10 | 127,431,966 | 0 | 1 | Apache-2.0 | 2020-02-11T14:23:38 | 2018-03-30T13:35:24 | Java | UTF-8 | Java | false | false | 16,477 | java | /*
* 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.myfaces.trinidadinternal.taglib;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.webapp.UIComponentTag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.myfaces.trinidad.logging.TrinidadLogger;
import org.apache.myfaces.trinidad.webapp.ELContextTag;
import org.apache.myfaces.trinidadinternal.el.Tokenizer;
import org.apache.myfaces.trinidadinternal.el.Tokenizer.Token;
//JSTL Core Library - <c:forEach> Tag
//===================================
//Syntax 1: Iterate over a collection of objects
//
//<c:forEach [var="varName "] items="collection"
// [varStatus="varStatusName"]
// [begin="begin"] [end="end"] [step=" step"]>
// body content
//</c:forEach>
//
//Syntax 2: Iterate a fixed number of times
//
//<c:forEach [var="varName"]
// [varStatus="varStatusName"]
// begin=" begin" end="end" [step="step"]>
// body content
//</c:forEach>
/**
*
*/
public class ForEachTag extends TagSupport implements ELContextTag
{
public void setItems(String items)
{
if (!items.startsWith("#{") ||
!items.endsWith("}"))
throw new IllegalArgumentException(_LOG.getMessage(
"MUST_BE_SIMPLE_JSF_EL_EXPRESSION"));
_items = items;
}
public void setBegin(String begin)
{
_begin = begin;
}
public void setEnd(String end)
{
_end = end;
}
public void setStep(String step)
{
_step = step;
}
public void setVar(String var)
{
if (UIComponentTag.isValueReference(var))
throw new IllegalArgumentException(_LOG.getMessage(
"VAR_CANNOT_BE_EXPRESSION"));
_var = var;
}
public void setVarStatus(String varStatus)
{
if (UIComponentTag.isValueReference(varStatus))
throw new IllegalArgumentException(_LOG.getMessage(
"VARSTATUS_CANNOT_BE_EXPRESSION"));
_varStatus = varStatus;
}
@Override
public int doStartTag() throws JspException
{
_validateAttributes();
FacesContext context = FacesContext.getCurrentInstance();
_parentELContext = (ELContextTag)
findAncestorWithClass(this, ELContextTag.class);
_currentBegin = _resolveInteger(context, _begin, 0);
int length;
if (null != _items)
{
Object items = _resolveObject(context, _items);
//pu: If items is specified and resolves to null, it is treated as an
// empty collection, i.e., no iteration is performed.
if (items == null)
{
if (_LOG.isFine())
_LOG.fine("Items expression " + _items + " resolved to null.");
return SKIP_BODY;
}
// =-=AEW <c:forEach> supports arbitrary collections; but
// JSF only supports List in its EL.
if (items instanceof List)
length = ((List) items).size();
else if (items.getClass().isArray())
length = Array.getLength(items);
else
throw new JspException(_LOG.getMessage(
"MUST_POINT_TO_LIST_OR_ARRAY"));
if (length == 0)
{
if (_LOG.isFine())
_LOG.fine("Items found at " + _items + " is empty.");
return SKIP_BODY;
}
//pu: If valid 'items' was specified, and so was 'begin', get out if size
// of collection were to be less than the begin. A mimic of c:forEach.
if (length < _currentBegin)
{
if (_LOG.isFine())
_LOG.fine("Size of 'items' is less than 'begin'");
return SKIP_BODY;
}
_currentEnd = _resolveInteger(context, _end, length - 1);
//pu: If 'end' were specified, but is beyond the size of collection, limit
// the iteration to where the collection ends. A mimic of c:forEach and
// fix for bug 4029853.
if (length < _currentEnd)
_currentEnd = length - 1;
}
else
{
_currentEnd = _resolveInteger(context, _end, 0);
}
_currentIndex = _currentBegin;
_currentStep = _resolveInteger(context, _step, 1);
//pu: Now check the valid relation between 'begin','end' and validity of 'step'
_validateRangeAndStep();
if (_currentEnd < _currentIndex)
return SKIP_BODY;
if (null != _var || null != _varStatus)
{
//pu: If items not defined (syntax 2), the return type of 'var' is an
// int according to JSTL specs, and apache impl returns index. Mimic.
_varReplacement = (null == _items)?
String.valueOf(_currentIndex):
_items.substring(2, _items.length() - 1) + "[" + _currentIndex + "]";
}
//pu: If there is no varStatus set, no point in keeping loop status
// variables updated.
if (null != _varStatus)
{
_updateLoopStatus();
_propertyReplacementMap = new HashMap<String, Object>(9, 1);
_propertyReplacementMap.put("begin", Integer.valueOf(_currentBegin));
_propertyReplacementMap.put("end", Integer.valueOf(_currentEnd));
_propertyReplacementMap.put("step", Integer.valueOf(_currentStep));
_propertyReplacementMap.put("count", Integer.valueOf(_currentCount));
_propertyReplacementMap.put("index", Integer.valueOf(_currentIndex));
_propertyReplacementMap.put("current", _varReplacement);
_propertyReplacementMap.put(
"first",
(_isFirst)? Boolean.TRUE:Boolean.FALSE);
_propertyReplacementMap.put(
"last",
(_isLast)? Boolean.TRUE:Boolean.FALSE);
}
if (_LOG.isFiner())
{
_LOG.finer("Iterating from " + _currentIndex + " to " + _currentEnd +
" by " + _currentStep);
}
return EVAL_BODY_INCLUDE;
}
@Override
public int doAfterBody()
{
_currentIndex += _currentStep;
if (null != _var || null != _varStatus)
{
//pu: If items not defined (syntax 2), the return type of 'var' is an
// int according to JSTL specs, and apache impl returns index. Mimic.
_varReplacement = (null == _items)?
String.valueOf(_currentIndex):
_items.substring(2, _items.length() - 1) + "[" + _currentIndex + "]";
}
//pu: if there is no varStatus set, no point in keeping loop status
// variables updated.
if (null != _varStatus)
{
//pu: _isFirst is not yet updated after first iteration
boolean isSecondIteration = (_isFirst)? true:false;
_updateLoopStatus();
if (isSecondIteration)
{
_propertyReplacementMap.put(
"first",
(_isFirst)? Boolean.TRUE:Boolean.FALSE);
}
if (_isLast)
{
_propertyReplacementMap.put(
"last",
(_isLast)? Boolean.TRUE:Boolean.FALSE);
}
_propertyReplacementMap.put("count", Integer.valueOf(_currentCount));
_propertyReplacementMap.put("index", Integer.valueOf(_currentIndex));
_propertyReplacementMap.put("current", _varReplacement);
}
if (_currentEnd < _currentIndex)
return SKIP_BODY;
return EVAL_BODY_AGAIN;
}
public String transformId(String id)
{
if (_parentELContext != null)
id = _parentELContext.transformId(id);
// SEPARATOR_CHAR would be nice; but JSF does not allow
// the separator char in an ID - just in client IDs.
// return id + NamingContainer.SEPARATOR_CHAR + _currentIndex;
return id + '_' + _currentIndex;
}
static String __transformExpression(
String expression,
String var,
String subst)
{
String varDot = var + ".";
Tokenizer tokens = new Tokenizer(expression);
StringBuffer buf = new StringBuffer(expression.length());
while(tokens.hasNext())
{
Token tok = tokens.next();
String exp = tok.getText();
if (tok.type == Tokenizer.VAR_TYPE)
{
if (var.equals(exp) || exp.startsWith(varDot))
{
buf.append(subst);
buf.append(exp.substring(var.length()));
continue;
}
}
buf.append(exp);
}
return buf.toString();
}
public String transformExpression(String expression)
{
if (expression != null)
{
String transformedExp = expression;
int expressionStart = expression.indexOf("#{");
if (expressionStart >= 0)
{
transformedExp = _transformExpression(expression);
if (_parentELContext != null)
transformedExp = _parentELContext.transformExpression(transformedExp);
}
if (_LOG.isFiner())
_LOG.finer("Transformed expression:{0} to:{1}",
new String[] {expression, transformedExp});
return transformedExp;
}
return null;
}
/**
* Release state.
*/
@Override
public void release()
{
super.release();
//=-=pu: Does only the properties that has setters need to be released ?
// What about variables like _propertyReplacementMap/_varReplacement etc. ?
_begin = null;
_end = null;
_end = null;
_items = null;
_step = null;
_var = null;
_varStatus = null;
}
protected ValueBinding createValueBinding(
FacesContext context,
String expression)
{
if (_parentELContext != null)
expression = _parentELContext.transformExpression(expression);
return context.getApplication().createValueBinding(expression);
}
private void _validateAttributes() throws JspTagException
{
if (null == _items)
{
if (null == _begin || null == _end)
{
throw new JspTagException(
"'begin' and 'end' should be specified if 'items' is not specified");
}
}
//pu: This is our own check - c:forEach behavior un-defined & unpredictable.
if ((_var != null) &&
_var.equals(_varStatus))
{
throw new JspTagException(
"'var' and 'varStatus' should not have same value");
}
}
private void _validateRangeAndStep() throws JspTagException
{
if (_currentBegin < 0)
throw new JspTagException("'begin' < 0");
if (_currentStep < 1)
throw new JspTagException("'step' < 1");
}
private String _transformExpression(String expression)
{
boolean doVar = (_var != null);
boolean doVarStatus = (_varStatus != null);
if (!(doVar || doVarStatus))
return expression;
StringBuffer buf = new StringBuffer(expression.length());
// ACW: see bug 3754666:
Tokenizer tokens = new Tokenizer(expression);
String varDot = _var+".";
String varStatusDot = _varStatus+".";
while(tokens.hasNext())
{
Token tok = tokens.next();
String text = tok.getText();
if (tok.type == Tokenizer.VAR_TYPE)
{
if (doVar && (_var.equals(text) || text.startsWith(varDot)))
{
text = _replaceVariableAndPropertiesInExpression(
text, _var, _varReplacement, null);
}
else if (doVarStatus && (_varStatus.equals(text) || text.startsWith(varStatusDot)))
{
text = _replaceVariableAndPropertiesInExpression(
text, _varStatus, null, _propertyReplacementMap);
}
}
buf.append(text);
}
return buf.toString();
}
/**
* Replaces all occurance of 'variable' and the property (the key in map)
* with the property replacement (value in the map).
* If propertyReplacementMap were to be null, then all the occurance of
* 'variable' will be replaced by 'variableReplacement'.
* Returns a string modified thus.
*/
private String _replaceVariableAndPropertiesInExpression(
String subExpression,
String variable,
String variableReplacement,
Map<String, Object> propertyReplacementMap)
{
int variableLength = variable.length();
//pu: Now check whether the variable is followed by any property from
// the supplied map.
if (null != propertyReplacementMap)
{
String property;
String propertyReplacement;
for(Map.Entry<String, Object> entry : propertyReplacementMap.entrySet())
{
property = entry.getKey();
String expressionAfterVar = subExpression.substring(variableLength);
if (expressionAfterVar.startsWith("."+property))
{
int propertyLength = property.length();
//pu: We found our property, but it could be followed
// by an alphanumeric in which case we ignore and move on because
// we just found it as a substring
int endOfReplacement = propertyLength + 1;
if (expressionAfterVar.length() > endOfReplacement)
{
if (Character.isLetterOrDigit(
expressionAfterVar.charAt(endOfReplacement)))
{
continue;
}
}
propertyReplacement = entry.getValue().toString();
//pu: Replace both the variable plus the property following it.
subExpression = _replaceSubString(
subExpression,
0,
variableLength + propertyLength + 1,
propertyReplacement);
//pu: If we handled atleast one property, break out from here.
break;
}
}
}
//pu: If there were no properties to be replaced, replace the variable itself
else
{
subExpression = _replaceSubString(subExpression, 0, variableLength, variableReplacement);
}
return subExpression;
}
/**
* Given the 'str', replaces a substring starting from 'beginIndex'
* of 'noOfChars' length with the string in 'replacement', returns the
* string modified thus.
*/
private String _replaceSubString(
String str,
int beginIndex,
int noOfChars,
String replacement)
{
StringBuffer buffer = new StringBuffer(str.length() +
replacement.length() -
noOfChars);
buffer.append(str.substring(0, beginIndex));
buffer.append(replacement);
buffer.append(str.substring(beginIndex + noOfChars));
return buffer.toString();
}
/**
* Update the loop status variables.
*/
private void _updateLoopStatus()
{
_currentCount = ((_currentIndex - _currentBegin)/_currentStep) + 1;
_isFirst = (_currentIndex == _currentBegin);
_isLast = (_currentIndex + _currentStep) > _currentEnd;
}
private Object _resolveObject(FacesContext context, String expression)
{
ValueBinding vb = createValueBinding(context, expression);
return vb.getValue(context);
}
private int _resolveInteger(
FacesContext context,
String expression,
int defaultValue)
{
if (expression == null)
return defaultValue;
if (UIComponentTag.isValueReference(expression))
{
Object o = _resolveObject(context, expression);
if (o instanceof Number)
return ((Number) o).intValue();
if (o == null)
return defaultValue;
expression = o.toString();
}
return Integer.parseInt(expression);
}
private int _currentBegin;
private int _currentIndex;
private int _currentEnd;
private int _currentStep;
private int _currentCount;
private boolean _isFirst;
private boolean _isLast;
private ELContextTag _parentELContext;
private String _items;
private String _begin;
private String _end;
private String _step;
private String _var;
private String _varStatus;
//pu: Map for properties referred off from 'varStatus' and their replacements
private Map<String, Object> _propertyReplacementMap;
//pu: Represents replacement for 'var' upon every iteration
private String _varReplacement;
private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(ForEachTag.class);
}
| [
"mmo@semmle.com"
] | mmo@semmle.com |
33d5a7e29b0ae5c263ce9a95f2e055ca8e888d94 | 9eb140f0dac19b4154fd3a7dc1d30161de3a1953 | /sk-gudang/src/org/radot/json/beans/PageReturPenjualanParam.java | 700fd81bba780e40b28ed92e0a32bc8e149a2951 | [] | no_license | osiris16/sk-gudang | 6bdd5e36f088cfc3540276490c44fbb27167918d | 0b55430da54b18f1c42da529a29c1dc9d4fedd88 | refs/heads/master | 2020-03-26T04:03:03.839211 | 2018-08-30T15:31:53 | 2018-08-30T15:31:53 | 144,483,433 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 343 | java | package org.radot.json.beans;
import org.radot.json.servlet.JsonParam;
import com.google.gson.annotations.Expose;
public class PageReturPenjualanParam extends JsonParam {
@Expose
private String page;
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
}
| [
"taufik@finmas.co.id"
] | taufik@finmas.co.id |
89f415a8608c58607ef4bda6e025824abb500c78 | f3452279877899e37a6dd4aa6f2c121a190cc27d | /app/src/main/java/com/ssthouse/moduo/control/util/SDCardUtil.java | 5c90bff32e60b23432e28d3edb95e3da60bb04a0 | [] | no_license | sunsetknight/Moduo | bc5772f1889a368c6b6d7492a55679fcb0c98998 | 455d7e900856e16903502bdd688b37079f5a84e0 | refs/heads/master | 2020-12-24T19:12:51.795568 | 2016-04-13T06:22:38 | 2016-04-13T06:22:38 | 56,127,892 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,152 | java | package com.ssthouse.moduo.control.util;
import android.os.Environment;
import android.os.StatFs;
import java.io.File;
/**
* Sd卡工具类
* Created by ssthouse on 2015/12/15.
*/
public class SDCardUtil {
/**
* 判断SDCard是否可用
*
* @return
*/
public static boolean isSDCardEnable() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* 获取SD卡路径
*
* @return
*/
public static String getSDCardPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator;
}
/**
* 获取SD卡的剩余容量 单位byte
*
* @return
*/
public static long getSDCardAllSize() {
if (isSDCardEnable()) {
StatFs stat = new StatFs(getSDCardPath());
// 获取空闲的数据块的数量
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
// 获取单个数据块的大小(byte)
long freeBlocks = stat.getAvailableBlocks();
return freeBlocks * availableBlocks;
}
return 0;
}
/**
* 获取指定路径所在空间的剩余可用容量字节数,单位byte
*
* @param filePath
* @return 容量字节 SDCard可用空间,内部存储可用空间
*/
public static long getFreeBytes(String filePath) {
// 如果是sd卡的下的路径,则获取sd卡可用容量
if (filePath.startsWith(getSDCardPath())) {
filePath = getSDCardPath();
} else {// 如果是内部存储的路径,则获取内存存储的可用容量
filePath = Environment.getDataDirectory().getAbsolutePath();
}
StatFs stat = new StatFs(filePath);
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
return stat.getBlockSize() * availableBlocks;
}
/**
* 获取系统存储路径
*
* @return
*/
public static String getRootDirectoryPath() {
return Environment.getRootDirectory().getAbsolutePath();
}
}
| [
"462271850@qq.com"
] | 462271850@qq.com |
28821a92e011c565e2f3dd6a2faf0011c3aaa19b | 40e4cdcad07b3bb85b484f34481c4c22833deb83 | /Spring/githubdemo/src/main/java/com/stackroute/githubdemo/service/GitServiceImpl.java | f50434ab729c3eebbe52056920144082b86f2759 | [] | no_license | rutujarishi/AngularAssignment | 7c2a9b268df451ef4211d54ac6bcc9ff8d696eab | c990e1d5f75290ff7b33a42568f95b67ede65697 | refs/heads/master | 2023-02-06T09:47:07.196802 | 2019-10-31T04:14:18 | 2019-10-31T04:14:18 | 218,029,855 | 0 | 0 | null | 2023-01-07T11:16:26 | 2019-10-28T11:20:03 | TypeScript | UTF-8 | Java | false | false | 780 | java | package com.stackroute.githubdemo.service;
import com.stackroute.githubdemo.model.Git;
import com.stackroute.githubdemo.repository.GitRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GitServiceImpl implements GitService {
private GitRepository gitRepository;
@Autowired
public GitServiceImpl(GitRepository gitRepository) {
this.gitRepository = gitRepository;
}
@Override
public boolean saveRepo(Git repo) {
gitRepository.save(repo);
return true;
}
@Override
public List<Git> getAllRepo() {
return gitRepository.findAll();
}
}
| [
"rutujarishi7@gmail.com"
] | rutujarishi7@gmail.com |
f43f0eda80ab8710e2769b957d3ddfdd10bee780 | 04335734d6813e363a0e0e7f967983ee166d17be | /parsing/src/main/java/by/kononov/parsing/factory/BuilderFactory.java | b8dcc90496ed031102dbcd36d75e5e2c379cc445 | [] | no_license | unicorn2828/epam_task4_web_xml | b1f146b52dcef253984343039146034adea157ed | f0fda3e1ca2d6ddb8b8938eac31f7bee6dcb2e8c | refs/heads/master | 2022-02-17T05:10:49.532783 | 2020-02-02T19:11:10 | 2020-02-02T19:11:10 | 237,821,661 | 0 | 0 | null | 2022-01-27T16:20:25 | 2020-02-02T19:08:42 | CSS | UTF-8 | Java | false | false | 712 | java | package by.kononov.parsing.factory;
import by.kononov.parsing.builder.GemDomBuilder;
import by.kononov.parsing.builder.GemSaxBuilder;
import by.kononov.parsing.builder.GemStaxBuilder;
import by.kononov.parsing.entity.Gems;
import by.kononov.parsing.type.BuilderType;
public class BuilderFactory{
public Gems createGemsBuilder(BuilderType parserType, String fileName) {
switch (parserType) {
case DOM:
return new GemDomBuilder().buildGems(fileName);
case SAX:
return new GemSaxBuilder().buildGems(fileName);
case STAX:
return new GemStaxBuilder().buildGems(fileName);
default:
throw new EnumConstantNotPresentException(parserType.getDeclaringClass(), parserType.name());
}
}
} | [
"260v2602gmail.com"
] | 260v2602gmail.com |
afba9385d0522a888157587418abd5a25ae1770a | 0bc20684e70d219f5deabd5010dd0b3b7e64b298 | /oxd-wf-prototype/contrib/openclinica-module/src/org/openxdata/server/module/openclinica/ws/subjectlist/EventListType.java | 93bd6c9440116577f37d769a2b648cdfbca2ccd4 | [] | no_license | mclabs/moveitserver | ee42aedfacf8bd563282378e82764e390c4b7109 | 6a49c6c8af95726f91e2826980234be25877187c | refs/heads/master | 2021-01-18T14:09:35.961082 | 2012-03-12T14:15:50 | 2012-03-12T14:15:50 | 2,011,756 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,144 | java |
package org.openxdata.server.module.openclinica.ws.subjectlist;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.AccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.openxdata.server.module.openclinica.ws.subjectlist.EventListType;
import org.openxdata.server.module.openclinica.ws.subjectlist.StudyEventType;
/**
* <p>Java class for eventListType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="eventListType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="event" type="{http://openclinica.org/ws/listbeans}studyEventType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(AccessType.FIELD)
@XmlType(name = "eventListType", propOrder = {
"event"
})
public class EventListType {
@XmlElement(namespace = "http://openclinica.org/ws/listbeans")
protected List<StudyEventType> event;
/**
* Gets the value of the event property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the event property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEvent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link StudyEventType }
*
*
*/
public List<StudyEventType> getEvent() {
if (event == null) {
event = new ArrayList<StudyEventType>();
}
return this.event;
}
}
| [
"soyfactor@gmail.com"
] | soyfactor@gmail.com |
e90b3c8f24954cb1deecb56402758638edea3113 | 98d313cf373073d65f14b4870032e16e7d5466f0 | /gradle-open-labs/example/src/main/java/se/molybden/Class13645.java | 29eab5429591223ac3c80376ea1bf13556d7656a | [] | no_license | Molybden/gradle-in-practice | 30ac1477cc248a90c50949791028bc1cb7104b28 | d7dcdecbb6d13d5b8f0ff4488740b64c3bbed5f3 | refs/heads/master | 2021-06-26T16:45:54.018388 | 2016-03-06T20:19:43 | 2016-03-06T20:19:43 | 24,554,562 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 110 | java |
public class Class13645{
public void callMe(){
System.out.println("called");
}
}
| [
"jocce.nilsson@gmail.com"
] | jocce.nilsson@gmail.com |
98f07701777202bb5b4cee282fcf3d423203c90e | 1a1e6fac497bd841bf7ccc14728fc1ab7e6acbd0 | /src/main/java/com/stark/web/RadioPlayerFactory.java | 3d05157be8caea7622b643d757dc9d35f55e2f59 | [
"MIT"
] | permissive | djagadish7/iRadioReceiver | 8a82dfc71f7ff59907e113fb7fb9c49f933a1f1c | 2905a24a2d02260ddf1f38eb36a1e0b7d0c87d4e | refs/heads/master | 2020-05-19T16:15:00.498915 | 2019-10-06T07:04:11 | 2019-10-06T07:04:11 | 185,103,569 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,105 | java | package com.stark.web;
import java.util.ArrayList;
import java.util.List;
public class RadioPlayerFactory
{
enum MEDIA_PLAYER
{
MPG123,
JAVAX
};
private static List<IRadioPlayer> m_radioPlayers = new ArrayList<>();
public static IRadioPlayer getRadioPlayer(MEDIA_PLAYER media_player)
{
if (media_player == MEDIA_PLAYER.JAVAX) {
for (IRadioPlayer player : m_radioPlayers) {
if (player instanceof JavaxRadioPlayer)
return player;
}
IRadioPlayer player = (IRadioPlayer) new JavaxRadioPlayer();
m_radioPlayers.add(player);
return player;
}
if (media_player == MEDIA_PLAYER.MPG123)
{
for (IRadioPlayer player : m_radioPlayers)
{
if (player instanceof MPG123RadioPlayer)
return player;
}
IRadioPlayer player = (IRadioPlayer) new MPG123RadioPlayer();
m_radioPlayers.add(player);
return player;
}
return null;
}
} | [
"djagadish7@gmail.com"
] | djagadish7@gmail.com |
e09c4138a52ab44c5a3ca44fcf8b2891c3296a11 | df5a2e63f6a3550af4b830af6195e0e14769141e | /src/main/java/be/ugent/mmlab/rml/model/SubjectMap.java | 0d6b00eff1ae5189ecd079d3c765e890a0a44afc | [] | no_license | andimou/RMLProcessor | a4ab69335de6e0d28bc714dbf21ce07f3693f59c | 84e4055d6feb7d395b4aea3e5905f74453e53f9a | refs/heads/master | 2021-01-19T13:53:19.748809 | 2014-01-27T22:07:55 | 2014-01-27T22:07:55 | 14,625,091 | 0 | 1 | null | 2021-12-09T19:05:23 | 2013-11-22T17:54:05 | Java | UTF-8 | Java | false | false | 1,889 | java | /*
* Copyright 2011 Antidot opensource@antidot.net
* https://github.com/antidot/db2triples
*
* DB2Triples is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* DB2Triples is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/***************************************************************************
*
* R2RML Model : SubjectMap Interface
*
* A subject map is a term map. It specifies a rule
* for generating the subjects of the RDF triples generated
* by a triples map.
*
****************************************************************************/
package be.ugent.mmlab.rml.model;
import java.util.Set;
import net.antidot.semantic.rdf.rdb2rdf.r2rml.exception.InvalidR2RMLStructureException;
import org.openrdf.model.URI;
public interface SubjectMap extends TermMap {
/**
* A subject map may have one or more class IRIs.
*/
public Set<URI> getClassIRIs();
/**
* Any subject map may have one or more associated graph maps.
*/
public Set<GraphMap> getGraphMaps();
/**
* A Term Map knows in own Triples Map container.
* In 7.7 Inverse Expressions : "Let t be the logical table
* associated with this term map" suggests this feature.
*/
public TriplesMap getOwnTriplesMap();
public void setOwnTriplesMap(TriplesMap ownTriplesMap) throws InvalidR2RMLStructureException;
}
| [
"miel.vandersande@ugent.be"
] | miel.vandersande@ugent.be |
25ea50eb0573e9eeefd341e27d10c8c0b9b66168 | 3a568be34324d54a89c25b005e58f2313d3a8275 | /cdr.core/src/main/java/com/founder/cdr/service/impl/UserManagerServiceImpl.java | 5f672e59fbccac70a363c3af4a918a92b8b25537 | [] | no_license | neil-ms/szbj-code | 9384e74481e5b4d9065a00c0becd5b73ea67ab01 | 92a8b8006b3198f2ed51daeb0f2c33e428a82edc | refs/heads/master | 2020-12-11T03:46:35.455388 | 2016-09-19T07:22:07 | 2016-09-19T07:22:07 | 68,563,282 | 0 | 0 | null | 2016-09-19T02:50:32 | 2016-09-19T02:50:32 | null | UTF-8 | Java | false | false | 25,658 | java | package com.founder.cdr.service.impl;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.founder.cdr.core.Constants;
import com.founder.cdr.dao.UserManagerDao;
import com.founder.cdr.dto.iam.UserListDto;
import com.founder.cdr.entity.CodePerson;
import com.founder.cdr.entity.CodeValue;
import com.founder.cdr.entity.MedicalVisit;
import com.founder.cdr.entity.SystemAccount;
import com.founder.cdr.entity.SystemAccountAuth;
import com.founder.cdr.entity.SystemAuth;
import com.founder.cdr.entity.SystemAuthDto;
import com.founder.cdr.service.UserManagerService;
import com.founder.cdr.util.DateUtils;
import com.founder.cdr.util.ResetPwUtil;
import com.founder.cdr.util.StringUtils;
import com.founder.fasf.core.util.daohelper.entity.EntityDao;
import com.founder.fasf.core.util.message.LocalizableUtils;
import com.founder.fasf.web.paging.PagingContext;
import com.ibm.mq.MQException;
@Component
public class UserManagerServiceImpl implements UserManagerService {
@Autowired
UserManagerDao userManagerDao;
@Autowired
EntityDao entityDao;
// @Autowired
// UserManagerMQMsgSendService userManagerMQMsgSendService;
//
// @Autowired
// SystemSettingsManagerService sysSetting;
//
// @Autowired
// SendMsgByMobileNosWebservice sendMsgByMobileNosWebservice;
//
// @Autowired
// SendEmailWebservice sendEmailWebservice;
//
// @Autowired
// PwdManagerDao pwdManagerDao;
//
private static Logger logger = LoggerFactory
.getLogger(UserManagerServiceImpl.class);
/***
* 加载部门字典
*
* @return
*/
public List<CodePerson> selectDeptDict(String name) {
return (List<CodePerson>) userManagerDao.selectDeptDict(name);
}
//
// /***
// * 加载职务字典
// *
// * @return
// */
// public List<TDictTitle> selectPostDict()
// {
// return (List<TDictTitle>) userManagerDao.selectPostDict();
// }
//
// /***
// * 加载在岗状态字典
// *
// * @return
// */
// public List<DictEmploymentStatus> selectInPostDict()
// {
// return (List<DictEmploymentStatus>) userManagerDao.selectInPostDict();
// }
//
// /***
// * 加载人员类型字典
// *
// * @return
// */
// public List<DictEmployeeType> selectPersonTypeDict()
// {
// return (List<DictEmployeeType>) userManagerDao.selectPersonTypeDict();
// }
//
// /***
// * 加载系统列表
// *
// * @return
// */
// public List<IamSysInfo> selectSysInfo()
// {
// return (List<IamSysInfo>) userManagerDao.selectSysInfo();
// }
//
/***
* 查询账户列表
*/
public List<UserListDto> userList(UserListDto userListDto,
PagingContext pageContext) {
String userid = userListDto.getSearchUserId() != null ? userListDto
.getSearchUserId() : "";
String userName = userListDto.getSearchUserName() != null ? userListDto
.getSearchUserName() : "";
String dept = userListDto.getSearchDept() != null ? userListDto
.getSearchDept() : "";
String state = userListDto.getSearchState() != null ? userListDto
.getSearchState() : "";
String authSys = userListDto.getSearchAuthSys() != null ? userListDto
.getSearchAuthSys() : "";
String postCode = userListDto.getSearchPost() != null ? userListDto
.getSearchPost() : "";
String InPost = userListDto.getSearchInPost() != null ? userListDto
.getSearchInPost() : "";
String personType = userListDto.getSearchPersonType() != null ? userListDto
.getSearchPersonType() : "";
String hidden = Constants.HIDDEN_ADMIN_ACCOUNT;
if (hidden != null && !hidden.isEmpty()) {
String[] hiddens = hidden.split("\\|");
StringBuilder news = new StringBuilder();
for (String s : hiddens) {
news.append("'" + s + "',");
}
hidden = news.substring(1, news.length() - 2);
}
return userManagerDao.selectUserList(userid, userName, dept, state,
authSys, postCode, InPost, personType, hidden, pageContext);
}
/***
* 查询账户列表
*/
public UserListDto selectUserByNo(String userNo) {
return userManagerDao.selectUserByNo(userNo);
}
/**
* 初始化个人权限
*/
public List<SystemAuthDto> selectPersonAuthList(String userNo) {
List list = new ArrayList<Object>();
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("userId", userNo);
paramMap.put("deleteFlag", "0");
// 初始化个人权限设定
List pAuthList = entityDao.selectByCondition(SystemAccountAuth.class,
paramMap);
paramMap = null;
SystemAuthDto actlAuthDto = null;
// 角色和缺省的并集
List oAuthList = userManagerDao.selectRoleAuthByUserNo(userNo);
for (int i = 0; i < pAuthList.size(); i++) {
String pAuthId = ((SystemAccountAuth) pAuthList.get(i))
.getSystemAuthId();
for (int j = 0; j < oAuthList.size(); j++) {
String oAuthId = ((SystemAuth) oAuthList.get(j))
.getSystemAuthId();
if (pAuthId.equals(oAuthId)) {
oAuthList.remove(j);
j--;
break;
}
}
}
for (int i = 0; i < pAuthList.size(); i++) {
actlAuthDto = new SystemAuthDto();
actlAuthDto.setAuthId(((SystemAccountAuth) pAuthList.get(i))
.getSystemAuthId());
list.add(actlAuthDto);
}
for (int j = 0; j < oAuthList.size(); j++) {
actlAuthDto = new SystemAuthDto();
actlAuthDto.setAuthId("o_"
+ ((SystemAuth) oAuthList.get(j)).getSystemAuthId());
list.add(actlAuthDto);
}
return list;
}
public List<SystemAuth> getDefaultAccess(int type, int area) {
List<SystemAuth> authList = null;
// 缺省权限列表
authList = userManagerDao.selectDefaultAccess(type, area);
return authList;
}
//
// /***
// * 修改账户状态 启用 或 停用
// */
// @Transactional
// public void updateStates(UserListDto userListDto, String state)
// {
// List<IamAccountInfo> accountLst = new ArrayList<IamAccountInfo>();
// String ids = userListDto.getUserIds();
// if (ids != null && !"".equals(ids))
// {
// String[] arrayId = ids.split(",");
// for (int i = 0; i < arrayId.length; i++)
// {
// IamAccountInfo entity = (IamAccountInfo) entityDao.selectById(
// IamAccountInfo.class, arrayId[i]);
// entity.setStatus(Integer.valueOf(state));
// entityDao.update(entity);
// accountLst.add(entity);
// }
// // 发送更新消息
// this.sendMQMsgForAccount(accountLst, "update", null);
// }
// }
/***
* 重置密码
*/
@Transactional
public void updatePasswd(UserListDto userListDto, int resetType, int riType) {
// 重置密码分两种,0:默认生成和用户Id相同;1:生成随机密码;
// 邮件提醒方式有四种,0:不提醒;1:短信提醒;2:邮件提醒;3:短信 + 邮件提醒;
List<SystemAccount> accountLst = new ArrayList<SystemAccount>();
String ids = userListDto.getUserIds();
if (ids != null && !"".equals(ids)) {
String[] arrayId = ids.split(",");
for (int i = 0; i < arrayId.length; i++) {
Map<String, Object> condition = new HashMap<String, Object>();
condition.put("userId", arrayId[i]);
List entity = new ArrayList<SystemAccount>();
entity = entityDao.selectByCondition(SystemAccount.class,
condition);
SystemAccount entityAccout = (SystemAccount) entity.get(0);
this.resetPasswd(entityAccout, resetType);
// accountLst.add(entity);
}
// this.sendMQMsgForAccount(accountLst, "update", null);
}
}
// /***
// * 删除用户
// */
// public void deleteUser(UserListDto userListDto)
// {
// String userNo = userListDto.getUserNo();
// if (userNo != null && !"".equals(userNo))
// {
// IamAccountInfo entity = (IamAccountInfo) entityDao.selectById(
// IamAccountInfo.class, userNo);
// entityDao.delete(entity);
// }
// }
//
// /***
// * 已启用账户列表
// *
// * @param userListDto
// * @return
// */
// public List<UserListDto> startedUserList(UserListDto userListDto,
// PagingContext pageContext)
// {
// String userid = userListDto.getSearchUserId() != null ?
// userListDto.getSearchUserId()
// : "";
// String userName = userListDto.getSearchUserName() != null ?
// userListDto.getSearchUserName()
// : "";
// String dept = userListDto.getSearchDept() != null ?
// userListDto.getSearchDept()
// : "";
// String postCode = userListDto.getSearchPost() != null ?
// userListDto.getSearchPost()
// : "";
// String InPost = userListDto.getSearchInPost() != null ?
// userListDto.getSearchInPost()
// : "";
// String personType = userListDto.getSearchPersonType() != null ?
// userListDto.getSearchPersonType()
// : "";
// return userManagerDao.selectStartedUserList(userid, userName, dept,
// postCode, InPost, personType, pageContext);
// }
//
// /***
// * 已启用的并选择了公共服务系统的账户列表
// *
// * @param userListDto
// * @return
// */
// public List<UserListDto> startedAndCommonUserList(UserListDto
// userListDto,
// PagingContext pageContext)
// {
// String userid = userListDto.getSearchUserId() != null ?
// userListDto.getSearchUserId()
// : "";
// String userName = userListDto.getSearchUserName() != null ?
// userListDto.getSearchUserName()
// : "";
// String dept = userListDto.getSearchDept() != null ?
// userListDto.getSearchDept()
// : "";
// String postCode = userListDto.getSearchPost() != null ?
// userListDto.getSearchPost()
// : "";
// String InPost = userListDto.getSearchInPost() != null ?
// userListDto.getSearchInPost()
// : "";
// String personType = userListDto.getSearchPersonType() != null ?
// userListDto.getSearchPersonType()
// : "";
// return userManagerDao.selectStartedCommonUserList(userid, userName, dept,
// postCode, InPost, personType, pageContext);
// }
//
// /***
// *
// * 查询因到期应该停用的账户列表
// *
// * @return
// */
// public List<IamAccountInfo> selectEndUsers()
// {
//
// return userManagerDao.selectEndUsers();
// }
//
// /***
// *
// * 到期账户停用
// *
// */
// public void stopUsersIfEnd()
// {
//
// List<IamAccountInfo> list = userManagerDao.selectEndUsers();
//
// System.out.println(list.size());
//
// int result = userManagerDao.updateStatusIfEnd();
//
// System.out.println(result);
//
// /***
// *
// * 此处有短信、邮件通知接口调用
// *
// */
//
// System.out.println("---------------停用账户封装成xml发送到各个系统-----------------------");
// System.out.println("---------------短信或邮件通知用户账号已停用----------------");
//
// }
//
// /***
// * 查询用户列表(权限设置)
// */
// public List<UserListDto> searchSelectedUsers(String[] userIds)
// {
// List<UserListDto> lst = new ArrayList<UserListDto>();
// if (userIds != null && userIds.length > 0)
// {
// for (int i = 0; i < userIds.length; i++)
// {
// UserListDto dto = userManagerDao.selectSetAuthUsers(userIds[i]);
// lst.add(dto);
// }
// }
// return lst;
// }
//
// /***
// * 查询账户权限
// */
// public List<String> selectUserAuthorities(String[] userIds)
// {
// List<String> lst = new ArrayList<String>();
// if (userIds != null && !"".equals(userIds))
// {
// for (int i = 0; i < userIds.length; i++)
// {
// Map<String, Object> condition = new HashMap<String, Object>();
// condition.put("userNo", userIds[i]);
// List<Object> resrs = entityDao.selectByCondition(
// IamAccountSys.class, condition);
// for (Object resr : resrs)
// {
// lst.add(((IamAccountSys) resr).getSysId());
// }
// }
// }
// return lst;
// }
//
// /***
// * 保存账户权限
// */
// @Transactional
// public int saveAccountAuthorities(TreeDto treeDto)
// {
// try
// {
// if (treeDto.getIds() != null && !"".equals(treeDto.getIds()))
// {
// String[] users = treeDto.getIds();
// Map[] datas = new HashMap[users.length];
// for (int i = 0; i < users.length; i++)
// {
// List<IamAccountSys> delLst = new ArrayList<IamAccountSys>();
// List<IamAccountSys> addLst = new ArrayList<IamAccountSys>();
//
// Map<String, Object> condition = new HashMap<String, Object>();
// condition.put("userNo", users[i]);
// List<Object> oldResrs = entityDao.selectByCondition(
// IamAccountSys.class, condition);
//
// String[] resrs = null;
// if (treeDto.getSelectIds() != null
// && !"".equals(treeDto.getSelectIds()))
// {
// resrs = treeDto.getSelectIds().split(",");
// }
// else
// {
// IamAccountInfo userDto = (IamAccountInfo) entityDao.selectById(
// IamAccountInfo.class, users[i]);
// if (userDto.getStatus() == 0)
// return ConstantsDef.OPERATION_INVALID;
// }
//
// delLst = this.returnDelAuth(oldResrs, resrs);
// addLst = this.returnAddAuth(oldResrs, resrs, users[i]);
// if (delLst != null && delLst.size() > 0)
// {
// for (IamAccountSys entity : delLst)
// {
// entityDao.delete(entity);
// if("S028".equals(entity.getSysId())){
// IamUserInfo sysUser =
// (IamUserInfo)entityDao.selectById(IamUserInfo.class, entity.getUserNo());
// entityDao.delete(sysUser);
// }
// }
// }
// if (addLst != null && addLst.size() > 0)
// {
// for (IamAccountSys entity : addLst)
// {
// entityDao.insert(entity);
// }
// }
//
// IamAccountInfo entity = (IamAccountInfo) entityDao.selectById(
// IamAccountInfo.class, users[i]);
// if (treeDto.getSelectIds() != null
// && !"".equals(treeDto.getSelectIds()))
// {
// // 账户启用
// if (entity.getStatus() != ConstantsDef.ACCOUNT_STATUS_1)
// {
// entity.setStatus(ConstantsDef.ACCOUNT_STATUS_1);
// this.resetPasswdForStartedUser(entity);
// }
// }
// Map data = new HashMap();
// data.put("userInfo", entity);
// data.put("delLst", delLst);
// data.put("addLst", addLst);
// datas[i] = data;
// }
// // 发送更新消息
// if (datas != null && datas.length > 0)
// {
// for (int i = 0; i < datas.length; i++)
// {
// List<IamAccountInfo> accountLst = new ArrayList<IamAccountInfo>();
// accountLst.add((IamAccountInfo) datas[i].get("userInfo"));
// List<IamAccountSys> delLst = (List<IamAccountSys>)
// datas[i].get("delLst");
// if (delLst != null && delLst.size() > 0)
// {
// for (IamAccountSys resr : delLst)
// {
// if (resr.getSysId().startsWith("S"))
// {
// this.sendMQMsgForAccount(accountLst,
// "delete", resr.getSysId());
// }
// }
// }
// List<IamAccountSys> addLst = (List<IamAccountSys>)
// datas[i].get("addLst");
// if (addLst != null && addLst.size() > 0)
// {
// for (IamAccountSys resr : addLst)
// {
// if (resr.getSysId().startsWith("S"))
// {
// this.sendMQMsgForAccount(accountLst,
// "insert", resr.getSysId());
// }
// }
// }
// }
// }
// }
// }
// catch (Exception e)
// {
// return ConstantsDef.OPERATION_FAILURE;
// }
// return ConstantsDef.OPERATION_SUCCESS;
// }
//
// /***
// * 返回需要删除的权限
// */
// private List<IamAccountSys> returnDelAuth(List<Object> oldResrs,
// String[] newResrs)
// {
// List<IamAccountSys> lst = new ArrayList<IamAccountSys>();
// if (oldResrs != null && oldResrs.size() > 0)
// {
// for (Object oldResr : oldResrs)
// {
// IamAccountSys entity = (IamAccountSys) oldResr;
// boolean isExists = false;
// if (newResrs != null && newResrs.length > 0)
// {
// for (int i = 0; i < newResrs.length; i++)
// {
// if (newResrs[i].equals(entity.getSysId()))
// {
// isExists = true;
// break;
// }
// }
// }
// if (!isExists)
// lst.add(entity);
// }
// }
// return lst;
// }
//
// /***
// * 返回需要添加的权限
// */
// private List<IamAccountSys> returnAddAuth(List<Object> oldResrs,
// String[] newResrs, String userNo)
// {
// List<IamAccountSys> lst = new ArrayList<IamAccountSys>();
// if (newResrs != null && newResrs.length > 0)
// {
// for (int i = 0; i < newResrs.length; i++)
// {
// boolean isExists = false;
// if (oldResrs != null && oldResrs.size() > 0)
// {
// for (Object oldResr : oldResrs)
// {
// IamAccountSys entity = (IamAccountSys) oldResr;
// if (newResrs[i].equals(entity.getSysId()))
// {
// isExists = true;
// break;
// }
// }
// }
// if (!isExists)
// {
// IamAccountSys newResr = new IamAccountSys();
// newResr.setSysId(newResrs[i]);
// newResr.setUserNo(userNo);
// lst.add(newResr);
// }
// }
// }
// return lst;
// }
// /***
// * 发送账户更新通知
// */
// public void sendMQMsgForAccount(List<IamAccountInfo> accountLst,
// String action, String targetSysCode)
// {
// DateFormat DATE_FORMAT_MSG = new SimpleDateFormat("yyyyMMddHHmmss");
// if (accountLst != null && accountLst.size() > 0)
// {
// for (IamAccountInfo entity : accountLst)
// {
// MessageHead msgHead = new MessageHead();
// msgHead.setMsgId("BS901");
// msgHead.setMsgName("账户信息服务结果数据");
// msgHead.setSourceSysCode("S028");
// msgHead.setVersion(Long.parseLong(DATE_FORMAT_MSG.format(new Date())));
// Map[] datas = this.entityToMap(entity);
// String result = null;
// if (datas != null)
// {
// if (targetSysCode == null || targetSysCode == "")
// {
// List<IamAccountSys> listSys =
// pwdManagerDao.selectVisitSys(entity.getUserNo());
// // 人员在存在可访问的系统时才发送账户信息
// if (listSys.size() > 0)
// {
// for (IamAccountSys sys : listSys)
// {
// msgHead.setTargetSysCode(sys.getSysId());
// Message msg = MessageUtils.buildMessage(
// msgHead, datas);
// System.currentTimeMillis();
// // 设置action的值,同时将mobile设值为空。
// for (int i = 0; i < msg.getBody().getRows().size(); i++)
// {
// msg.getBody().getRows().get(i).setAction(
// action);
// msg.getBody().getRows().get(i).put(
// "mobile", null);
// }
// result = MessageUtils.marshal(msg);
// try
// {
// userManagerMQMsgSendService.sendMQMessage(result);
// }
// catch (MQException e)
// {
// e.printStackTrace();
// }
//
// }
// }else{
// logger.info("该用户没有可访问的系统,不发送MQ消息!");
// }
// }
// else
// {
// msgHead.setTargetSysCode(targetSysCode);
// Message msg = MessageUtils.buildMessage(msgHead, datas);
// System.currentTimeMillis();
// // 设置action的值,同时将mobile设值为空。
// for (int i = 0; i < msg.getBody().getRows().size(); i++)
// {
// msg.getBody().getRows().get(i).setAction(action);
// msg.getBody().getRows().get(i).put("mobile", null);
// }
// result = MessageUtils.marshal(msg);
// try
// {
// userManagerMQMsgSendService.sendMQMessage(result);
// }
// catch (MQException e)
// {
// e.printStackTrace();
// }
// }
// }
// }
// }
// }
//
// private Map[] entityToMap(IamAccountInfo entity)
// {
// Map<String, Object>[] datas = new HashMap[1];
// Map<String, Object> data = new HashMap<String, Object>();
// data.put("userID", entity.getUserNo());
// data.put("userName", entity.getUserName());
// data.put("passwd", entity.getPasswd());
// data.put("sex", entity.getSex());
// data.put("email", entity.getEmail());
// data.put("mobile", "");
// data.put("deptCode", entity.getDeptCode());
// data.put("groupCd", entity.getGroupCd());
// data.put("employmentStatusCd", entity.getEmploymentStatusCd());
// data.put("employeeTypeCd", entity.getEmployeeTypeCd());
// data.put("jobCategory", entity.getJobCategory());
// Date date = new Date();
// if (entity.getServiceStartDate() != null)
// date = new Date(entity.getServiceStartDate().getTime());
// data.put("serviceStartDate", date);
// data.put("status", entity.getStatus());
// data.put("memo", entity.getMemo());
// data.put("resetPasswdFlag", entity.getResetPasswdFlag());
// datas[0] = data;
// return datas;
// }
//
// private void resetPasswdForStartedUser(IamAccountInfo entity)
// {
// String passwd = "";
// String initPasswd = "";
// int reType = sysSetting.selectPwdCreateRule();
// if (reType == 1)
// {
// initPasswd = ResetPwUtil.genRandomNum();
// }
// else
// {
// initPasswd = entity.getUserNo();
// }
// passwd = ResetPwUtil.md5(initPasswd);
// entity.setPasswd(passwd);
// entityDao.update(entity);
// StringBuilder content = new StringBuilder();
// content.append(LocalizableUtils.getLocalizedString("userStart.message",
// LocaleContextHolder.getLocale()));
// content.append(entity.getUserNo());
// content.append(LocalizableUtils.getLocalizedString(
// "userStart.password.message", LocaleContextHolder.getLocale()));
// content.append(initPasswd);
// String title = LocalizableUtils.getLocalizedString(
// "userStart.email.title", LocaleContextHolder.getLocale());
// SendMsgThread sendMsg = new SendMsgThread(entity, content.toString(),
// title, sysSetting, sendMsgByMobileNosWebservice, sendEmailWebservice);
// Thread thread = new Thread(sendMsg);
// thread.start();
// }
//
private void resetPasswd(SystemAccount entity, int resetType) {
String passwd = "";
String initPasswd = "";
int reType = resetType;
if (reType == 1) {
initPasswd = ResetPwUtil.genRandomNum();
} else {
initPasswd = entity.getUserId();
}
passwd = ResetPwUtil.md5(initPasswd);
entity.setPasswd(passwd);
entityDao.update(entity);
// StringBuilder content = new StringBuilder();
// content.append(LocalizableUtils.getLocalizedString(
// "resetPwd.system.message", LocaleContextHolder.getLocale()));
// content.append(initPasswd);
// String title = LocalizableUtils.getLocalizedString(
// "resetPwd.email.title", LocaleContextHolder.getLocale());
// SendMsgThread sendMsg = new SendMsgThread(entity, content.toString(),
// title, sysSetting, sendMsgByMobileNosWebservice,
// sendEmailWebservice);
// Thread thread = new Thread(sendMsg);
// thread.start();
}
/***
* 根据部门name获取部门code
*
* @return
*/
public List<CodePerson> selectDeptCodeByDeptName(String name) {
return (List<CodePerson>) userManagerDao.selectDeptCodeByDeptName(name);
}
// @Override
// public Map[] selectSystemReg(SystemRegisterDto systemRegisterDto,
// PagingContext pagingContext)
// {
// String searchSysID = systemRegisterDto.getSearchSysID() == null ? ""
// : systemRegisterDto.getSearchSysID();
// String searchSysNameValue = systemRegisterDto.getSearchSysName() == null
// ? ""
// : systemRegisterDto.getSearchSysName();
// String searchSysName = searchSysNameValue.trim();
// String searchCateCode = systemRegisterDto.getSearchCateCode() == null ?
// ""
// : systemRegisterDto.getSearchCateCode();
// String searchSupId = systemRegisterDto.getSearchSupId() == null ? ""
// : systemRegisterDto.getSearchSupId();
// return userManagerDao.selectSystemReg(searchSysID,searchSysName,
// searchCateCode, searchSupId, pagingContext);
// }
/***
* 加载字典
*
* @return
*/
public List<CodeValue> selectCodeDict(String dictCode) {
return (List<CodeValue>) userManagerDao.selectCodeDict(dictCode);
}
/***
* 保存个人设定权限
*
* @param userNo
* @param authList
*/
public void saveAuthList(String userNo, List<String> authList) {
// TODO Auto-generated method stub
List<Map> oList = userManagerDao.selectPersonActlAuth(userNo);
//将缺省和角色设定的权限删除,只保存个人自己设定的
for(int i=0;i<authList.size();i++){
if(authList.get(i).contains("o_")){
authList.remove(i);
i--;
}
}
for(int i=0;i<oList.size();i++){
String oAuthId = oList.get(i).get("systemAuthId").toString();
for(int j=0;j<authList.size();j++){
String nAuthId = authList.get(j);
if(oAuthId.equals(nAuthId)){
oList.remove(i);
authList.remove(j);
i--;
j--;
break;
}
}
}
// 清除个人权限
Map<String, Object> condition = new HashMap<String, Object>();
condition.put("userId", userNo);
for (Map map : oList) {
String authId = map.get("systemAuthId").toString();
condition.put("systemAuthId", authId);
condition.put("deleteFlag", "0");
SystemAccountAuth ActlUserAuth = (SystemAccountAuth) entityDao
.selectByCondition(SystemAccountAuth.class, condition).get(0);
entityDao.delete(ActlUserAuth);
}
List<Map> nList = new ArrayList<Map>();
Map map = null;
SystemAccountAuth userAuth = null;
for (String authId : authList) {
map = new HashMap();
map.put("systemAuthId", authId);
SystemAuth auth = (SystemAuth) entityDao.selectById(SystemAuth.class,
authId);
map.put("authDesc", auth.getMemo());
nList.add(map);
userAuth = new SystemAccountAuth();
userAuth.setUserId(userNo);
userAuth.setSystemAuthId(authId);
Date sysdate = DateUtils.getSystemTime();
userAuth.setCreateTime(sysdate);
userAuth.setUpdateTime(sysdate);
userAuth.setDeleteFlag("0");
userAuth.setUpdateCount(BigDecimal.ZERO);
entityDao.insert(userAuth);
userAuth = null;
}
nList = null;
map = null;
authList = null;
}
@Override
public boolean changeUserPassword(String userId, String userName,
String newPasswordMD5) {
Map<String, Object> condition = new HashMap<String, Object>();
condition.put("userId", userId);
condition.put("userName", userName);
List<Object> result = entityDao.selectByCondition(SystemAccount.class, condition);
if(result == null || result.isEmpty()){
return false;
} else {
SystemAccount sa = (SystemAccount) result.get(0);
sa.setPasswd(newPasswordMD5);
entityDao.updatePartially(sa, "passwd");
return true;
}
}
}
| [
"149516374@qq.com"
] | 149516374@qq.com |
d87d360a15aaeb0198cd2e0dc81807503dbf8c08 | 4fe9e0756f78c82be45ecb7da125685d425f2947 | /app/src/main/java/com/dedsec/materialui/helper/DragItemTouchHelper.java | 379cd0b424683018692f697211217962960f5d01 | [
"Apache-2.0"
] | permissive | vsolank2/MaterialUI-master | 65d01072c6c692f3ca77deea203c4b6c581c9c66 | 37f02920a8f2247ecb8304b1fa993f15f6b59782 | refs/heads/master | 2023-05-12T14:24:39.576661 | 2021-06-06T16:06:42 | 2021-06-06T16:06:42 | 374,404,281 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,791 | java | package com.dedsec.materialui.helper;
import android.graphics.Canvas;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
public class DragItemTouchHelper extends ItemTouchHelper.Callback {
public static final float ALPHA_FULL = 1.0f;
private final MoveHelperAdapter mAdapter;
public DragItemTouchHelper(MoveHelperAdapter adapter) {
mAdapter = adapter;
}
@Override
public boolean isLongPressDragEnabled() {
return true;
}
@Override
public boolean isItemViewSwipeEnabled() {
return false;
}
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
// Set movement flags based on the layout manager
if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
final int swipeFlags = 0;
return makeMovementFlags(dragFlags, swipeFlags);
} else {
final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
if (source.getItemViewType() != target.getItemViewType()) {
return false;
}
// Notify the adapter of the move
mAdapter.onItemMove(source.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
// Fade out the view as it is swiped out of the parent's bounds
final float alpha = ALPHA_FULL - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
viewHolder.itemView.setAlpha(alpha);
viewHolder.itemView.setTranslationX(dX);
} else {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
}
@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
// We only want the active item to change
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
if (viewHolder instanceof TouchViewHolder) {
// Let the view holder know that this item is being moved or dragged
TouchViewHolder itemViewHolder = (TouchViewHolder) viewHolder;
itemViewHolder.onItemSelected();
}
}
super.onSelectedChanged(viewHolder, actionState);
}
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
viewHolder.itemView.setAlpha(ALPHA_FULL);
if (viewHolder instanceof TouchViewHolder) {
// Tell the view holder it's time to restore the idle state
TouchViewHolder itemViewHolder = (TouchViewHolder) viewHolder;
itemViewHolder.onItemClear();
}
}
public interface MoveHelperAdapter {
boolean onItemMove(int fromPosition, int toPosition);
}
public interface TouchViewHolder {
void onItemSelected();
void onItemClear();
}
}
| [
"vipul@Vipuls-iMac.local"
] | vipul@Vipuls-iMac.local |
104b7ab6a02ced3437503afc49054758c215d04f | bba1b40129c217ca16baac1e234dcc936161f695 | /src/main/java/com/bc/mall/server/Application.java | 3f238343353a3396b4a539132d40d3e05989798f | [] | no_license | BooksCup/mall-server | e3b30906ba860f8066905a68dbedc1c801c7e2bb | 57b842463323647c0f7b4bfe510888ada3d8170e | refs/heads/master | 2023-01-29T13:23:09.915822 | 2020-12-08T06:01:23 | 2020-12-08T06:01:23 | 298,232,433 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,085 | java | package com.bc.mall.server;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
/**
* 启动类
* git test
*
* @author zhou
*/
@SpringBootApplication
@MapperScan("com.bc.mall.server.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> connector.setProperty("relaxedQueryChars", "|{}[]\\"));
return factory;
}
}
| [
"812809680@qq.com"
] | 812809680@qq.com |
c2222d075a8eb3fd24308b14745e88b6acfd6489 | 0dcd52b15cd7e16641e7d67770fc77036ae210e4 | /src/main/java/soccer/event/Shoot.java | e6e09e4a62ad38f36586f8a8b2079743150d5a66 | [] | no_license | ethien-salinas/201803-OCAJava8 | b4c94158ce96a091a38b15425141c3666cbc4bda | 26c0d72ddf1bb080370c76663eb2d58126809a16 | refs/heads/master | 2021-04-12T08:59:10.556245 | 2018-06-02T14:18:21 | 2018-06-02T14:18:21 | 126,831,694 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 706 | java | package soccer.event;
public class Shoot extends GameEvent {
// At the simplest, if successful dribbling moves towards the other teams goal
public Shoot() {
// No change in ballPoss until next event; Goal or Kickout(save)
}
public String toString() {
return "Shoots ";
}
public GameEvent[] getNextEvents() {
GameEvent theEvent[] = {new Goal(), new Kickout()};
return theEvent;
}
public boolean changePlayer() {
return false;
}
public boolean changeTeam() {
return false;
}
public void setBallPos(int currBallPos) {
//super.setBallPos(currBallPos);
super.ballPos = currBallPos;
}
}
| [
"ethien.salinas@gmail.com"
] | ethien.salinas@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.