text
stringlengths
10
2.72M
package br.ufrgs.rmpestano.intrabundle.plugin; import br.ufrgs.rmpestano.intrabundle.facet.OSGiFacet; import br.ufrgs.rmpestano.intrabundle.i18n.MessageProvider; import br.ufrgs.rmpestano.intrabundle.jasper.JasperManager; import br.ufrgs.rmpestano.intrabundle.metric.MetricsCalculation; import br.ufrgs.rmpestano.intrabundle.model.*; import br.ufrgs.rmpestano.intrabundle.model.enums.MetricName; import br.ufrgs.rmpestano.intrabundle.model.enums.MetricScore; import br.ufrgs.rmpestano.intrabundle.util.Constants; import br.ufrgs.rmpestano.intrabundle.util.MetricUtils; import org.jboss.forge.project.Project; import org.jboss.forge.resources.Resource; import org.jboss.forge.shell.Shell; import org.jboss.forge.shell.ShellColor; import org.jboss.forge.shell.ShellPrompt; import org.jboss.forge.shell.plugins.*; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * */ @Alias("osgi") @RequiresFacet(OSGiFacet.class) public class OsgiPlugin implements Plugin { @Inject Instance<OSGiProject> project; @Inject MessageProvider provider; @Inject ShellPrompt prompt; @Inject Shell shell; @Inject JasperManager jasperManager; @Inject MetricsCalculation metrics; @Inject MetricUtils metricUtils; private boolean sorted; @Command(value = "countBundles") public void countBundles(@PipeIn String in, PipeOut out) { out.println("Total number of bundles:" + getModules().size()); } @Command(value = "listBundles") public void listBundles(@PipeIn String in, PipeOut out) { for (OSGiModule osGiModule : getModules()) { out.println(osGiModule.getName()); } } @Command(value = "bundleLocations") public void bundleLocations(@PipeIn String in, PipeOut out) { for (int i=1;i<=getModules().size();i++) { out.println(i+" - "+((Project)getModules().get(i-1)).getProjectRoot().getFullyQualifiedName()); } } @Command(value = "loc", help = "count lines of code of all bundles") public void loc(@PipeIn String in, PipeOut out) { long total = 0; for (int i = 0; i < getModules().size(); i++) { long loci = getModules().get(i).getLinesOfCode(); out.println(getModules().get(i).getName() + ":" + loci); total += loci; } out.println(provider.getMessage("osgi.total-loc") + total); } @Command(value = "lot", help = "count lines of test code of all bundles") public void lot(@PipeIn String in, PipeOut out) { out.println(provider.getMessage("osgi.total-lot") + project.get().getLinesOfTestCode()); } @Command(value = "usesDeclarativeServices", help = "list modules that use declarative services") public void usesDeclarativeServices(@PipeIn String in, PipeOut out) { out.println(ShellColor.YELLOW, provider.getMessage("osgi.declarativeServices")); for (OSGiModule module : getModules()) { if (module.getUsesDeclarativeServices()) { out.println(module.getName()); } } } @Command(value = "activators", help = "list modules activator classes") public void listActivators(@PipeIn String in, PipeOut out) { out.println(ShellColor.YELLOW, provider.getMessage("osgi.listActivators")); for (OSGiModule module : getModules()) { out.println(module.getName() + ":" + (module.getActivator() != null ? module.getActivator().getFullyQualifiedName() : provider.getMessage("osgi.no-activator"))); } } @Command(value = "exportedPackages") public void listExportedPackages(@PipeIn String in, PipeOut out) { if (!allModules(provider.getMessage("packages"))) { OSGiModule choice = choiceModule(); listModuleExportedPackages(choice, out); }//execute command for all modules else { for (OSGiModule osGiModule : getModules()) { listModuleExportedPackages(osGiModule, out); } } } @Command(value = "importedPackages") public void listImportedPackages(@PipeIn String in, PipeOut out) { if (!allModules(provider.getMessage("packages"))) { OSGiModule choice = choiceModule(); listModuleImportedPackages(choice, out); }//execute command for all modules else { for (OSGiModule osGiModule : getModules()) { listModuleImportedPackages(osGiModule, out); } } } @Command(value = "requiredBundles") public void listRequiredBundles(@PipeIn String in, PipeOut out) { if (!allModules(provider.getMessage("requireBundles"))) { OSGiModule choice = choiceModule(); listModuleRequiredBundles(choice, out); }//execute command for all bundles else { for (OSGiModule osGiModule : getModules()) { listModuleRequiredBundles(osGiModule, out); } } } @Command("dependencies") public void moduleDependencies(@PipeIn String in, PipeOut out) { if (!this.allModules(provider.getMessage("dependencies"))) { OSGiModule choice = choiceModule(); this.listModuleDependencies(choice, out); }//execute command for all modules else { for (OSGiModule osGiModule : getModules()) { listModuleDependencies(osGiModule, out); } } } @Command("cycles") public void moduleCycles(@PipeIn String in, PipeOut out) { if (!this.allModules(provider.getMessage("cycles"))) { OSGiModule choice = choiceModule(); this.listModuleCycles(choice, out); }//execute command for all modules else { for (OSGiModule osGiModule : getModules()) { listModuleCycles(osGiModule, out); } } } @Command("staleReferences") public void moduleStaleReferences(@PipeIn String in, PipeOut out) { if (!this.allModules(provider.getMessage("staleReferences"))) { OSGiModule bundle = choiceModule(); List<Resource<?>> staleReferences = bundle.getStaleReferences(); if(!staleReferences.isEmpty()){ out.println(provider.getMessage("bundle.listing-stale-references")); for (Resource<?> staleReference : staleReferences) { out.println(staleReference.getFullyQualifiedName()); } } else{ out.println(provider.getMessage("bundle.noStaleReferences")); } }//execute command for all modules else { out.println(ShellColor.YELLOW, "===== " + provider.getMessage("module.staleReferences") + " ====="); for (OSGiModule module: getModules()) { if(!module.getStaleReferences().isEmpty()){ out.println(module.getName() + ":"+module.getStaleReferences().size() + " "+ provider.getMessage("metrics.staleReferences").toLowerCase()); } else{ out.println(module.getName() + ":"+provider.getMessage("bundle.noStaleReferences")); } } } } @Command("publishInterfaces") public void publishInterfaces(@PipeIn String in, PipeOut out) { out.println(ShellColor.YELLOW, provider.getMessage("osgi.publishInterfaces")); for (OSGiModule osGiModule : getModules()) { if (osGiModule.getPublishesInterfaces()) { out.println(osGiModule.getName()); } } } @Command("declaresPermissions") public void declaresPermissions(@PipeIn String in, PipeOut out) { out.println(ShellColor.YELLOW, provider.getMessage("osgi.declaresPermissions")); for (OSGiModule osGiModule : getModules()) { if (osGiModule.getDeclaresPermissions()) { out.println(osGiModule.getName()); } } } @Command(value = "bundleMetrics") public void bundleMetrics(PipeOut out) { if (!this.allModules(provider.getMessage("metrics"))) { OSGiModule bundle = choiceModule(); MetricPoints metricPoints = metrics.calculateBundleQuality(bundle); out.println(metricUtils.metricQuality(metricPoints)); out.println(provider.getMessage("bundle.listing-metrics")); for (Metric metric : metricPoints.getBundleMetrics()) { out.println(provider.getMessage(metric.getName().getValue())+":"+metric.getScore().name()); } }//execute command for all modules else { out.println(ShellColor.YELLOW, "===== " + provider.getMessage("osgi.listing-metrics") + " ====="); for (OSGiModule module: getModules()) { out.println(ShellColor.YELLOW,provider.getMessage("module.metrics",module.getName())); MetricPoints metricPoints = metrics.calculateBundleQuality(module); out.println(metricUtils.metricQuality(metricPoints)); for (Metric metric : metricPoints.getBundleMetrics()) { out.println(provider.getMessage(metric.getName().getValue())+":"+metric.getScore().name()); } } } } @Command(value = "projectMetric", help = "returns OSGi project mode and absolute metric score based on each bundle score") public void projectMetric(PipeOut out) { out.println(provider.getMessage("osgi.metric",metrics.calculateProjectModeQuality().name(), metrics.calculateProjectAbsoluteQuality().name())); } @Command(value = "projectPoints", help = "returns OSGi project mode and absolute metric score based on each bundle score") public void projecPoints(PipeOut out) { int maxPoints = project.get().getMaxPoints(); int projectPoints = metrics.getProjectQualityPonts(); double percentage = metrics.getProjectQualityPointsPercentage(); out.println(provider.getMessage("osgi.project-points",projectPoints,maxPoints,percentage)); } @Command(value = "metricQuality", help = "returns the quality of a given metric based on the project modules") public void metricQuality(PipeOut out) { MetricName metric = choiceMetric(); MetricPoints metricPoints = metrics.calculateMetricQuality(metric); out.println(metricUtils.metricQuality(metricPoints)); } @Command(help = "list bundles with the given quality", value = "findBundlesByQuality") public void findModulesByQuality(PipeOut out) { MetricScore quality = choiceQuality(); List<OSGiModule> modules = metrics.getModulesByQuality(quality); if(!modules.isEmpty()){ for (OSGiModule osGiModule : modules) { out.println(osGiModule.getName()); } } else{ out.println(provider.getMessage("osgi.scan.noBundlesFound")); } } private void listModuleImportedPackages(OSGiModule module, PipeOut out) { out.println(ShellColor.YELLOW, "===== " + provider.getMessage("module.listImported", module) + " ====="); if (module.getImportedPackages().isEmpty()) { out.println(provider.getMessage("module.noImportedPackages")); } else { for (String s : module.getImportedPackages()) { out.println(s); } } } private void listModuleExportedPackages(OSGiModule module, PipeOut out) { out.println(ShellColor.YELLOW, "===== " + provider.getMessage("module.listExported", module) + " ====="); if (module.getExportedPackages().isEmpty()) { out.println(provider.getMessage("module.noExportedPackages")); } else { for (String s : module.getExportedPackages()) { out.println(s); } } } private void listModuleRequiredBundles(OSGiModule module, PipeOut out) { out.println(ShellColor.YELLOW, "===== " + provider.getMessage("module.listRequiredBundles", module) + " ====="); if (module.getRequiredBundles().isEmpty()) { out.println(provider.getMessage("module.noRequiredBundles")); } else { for (String s : module.getRequiredBundles()) { out.println(s); } } } private void listModuleDependencies(OSGiModule choice, PipeOut out) { out.println(ShellColor.YELLOW, "===== " + provider.getMessage("module.dependencies", choice) + " ====="); if (project.get().getModulesDependencies().get(choice).isEmpty()) { out.println(provider.getMessage("module.noDependency")); } else { for (OSGiModule m : project.get().getModulesDependencies().get(choice)) { out.println(m.getName()); } } } private void listModuleCycles(OSGiModule choice, PipeOut out) { out.println(ShellColor.YELLOW, "===== " + provider.getMessage("module.cycles", choice) + " ====="); if (project.get().getModuleCyclicDependenciesMap().get(choice).isEmpty()) { out.println(provider.getMessage("module.noCycle")); } else { for (ModuleCycle m : project.get().getModuleCyclicDependenciesMap().get(choice)) { out.println(m.toString()); } } } private OSGiModule choiceModule() { return prompt.promptChoiceTyped(provider.getMessage("module.choice"), getModules()); } private MetricScore choiceQuality() { return prompt.promptChoiceTyped(provider.getMessage("quality.choice"), Arrays.asList(MetricScore.values())); } private MetricName choiceMetric() { return prompt.promptChoiceTyped(provider.getMessage("metrics.choice"), Arrays.asList(MetricName.values())); } private boolean allModules(String allWhat) { return prompt.promptBoolean(provider.getMessage("module.all", allWhat)); } public List<OSGiModule> getModules() { if(!sorted){ Collections.sort(project.get().getModules()); sorted = true; } return project.get().getModules(); } @Command(help = "Generate a report containing information about all bundles of the project") public void report() { jasperManager.reportFromProject(project.get(),Constants.REPORT.GENERAL); } @Command(value = "metricReport", help = "Generate a report containing bundle metric information of all bundles of the project") public void metricReport() { jasperManager.reportFromProject(project.get(), Constants.REPORT.METRICS); } }
package com.nic.projectproposal.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.springframework.web.multipart.MultipartFile; /** * PpOutsourcingOfTheProjectActivities generated by hbm2java */ @Entity @Table(name = "pp_outsourcing_of_the_project_activities", schema = "public") public class PpOutsourcingOfTheProjectActivities implements java.io.Serializable { private int projectOutsourcingPaId; private Integer projectProposalId; private String applicantPiaProcess; private String activityToBeOutsourced; private String nameOfTheOutsourcingPartner; private String legalStatus; private String bankName; private String state; private String district; private String bankBranch; private String ifscCode; private String micr; private String nameAsPerBankAccount; private String bankAccountNumber; private String financialYear; private String turnOver; private String netWorth; private String houseAddress; private String areaAddress; private String townCity; private String stateUt; private String block; private String village; private String postOffice; private String phone; private String street; private String landmark; private String policeStation; private String districtPartTwo; private String gramPanchayat; private String pin; private String emailId; private String mobileNumber; private String roleId; private String createdBy; private String modifiedBy; private Date createdDate; private Date modifiedDate; /* file upload start **/ private MultipartFile mouasoutsourcepartner; private MultipartFile registrationcertficate; private MultipartFile bankstatement; private MultipartFile checkleaf; private MultipartFile balancesheet; private MultipartFile employeelist; @Transient public MultipartFile getMouasoutsourcepartner() { return mouasoutsourcepartner; } public void setMouasoutsourcepartner(MultipartFile mouasoutsourcepartner) { this.mouasoutsourcepartner = mouasoutsourcepartner; } @Transient public MultipartFile getRegistrationcertficate() { return registrationcertficate; } public void setRegistrationcertficate(MultipartFile registrationcertficate) { this.registrationcertficate = registrationcertficate; } @Transient public MultipartFile getBankstatement() { return bankstatement; } public void setBankstatement(MultipartFile bankstatement) { this.bankstatement = bankstatement; } @Transient public MultipartFile getCheckleaf() { return checkleaf; } public void setCheckleaf(MultipartFile checkleaf) { this.checkleaf = checkleaf; } @Transient public MultipartFile getBalancesheet() { return balancesheet; } public void setBalancesheet(MultipartFile balancesheet) { this.balancesheet = balancesheet; } @Transient public MultipartFile getEmployeelist() { return employeelist; } public void setEmployeelist(MultipartFile employeelist) { this.employeelist = employeelist; } /* file upload end **/ public PpOutsourcingOfTheProjectActivities() { } public PpOutsourcingOfTheProjectActivities(int projectOutsourcingPaId) { this.projectOutsourcingPaId = projectOutsourcingPaId; } public PpOutsourcingOfTheProjectActivities(int projectOutsourcingPaId, Integer projectProposalId, String applicantPiaProcess, String activityToBeOutsourced, String nameOfTheOutsourcingPartner, String legalStatus, String bankName, String state, String district, String bankBranch, String ifscCode, String micr, String nameAsPerBankAccount, String bankAccountNumber, String financialYear, String turnOver, String netWorth, String houseAddress, String areaAddress, String townCity, String stateUt, String block, String village, String postOffice, String phone, String street, String landmark, String policeStation, String districtPartTwo, String gramPanchayat, String pin, String emailId, String mobileNumber, String roleId, String createdBy, String modifiedBy, Date createdDate, Date modifiedDate) { this.projectOutsourcingPaId = projectOutsourcingPaId; this.projectProposalId = projectProposalId; this.applicantPiaProcess = applicantPiaProcess; this.activityToBeOutsourced = activityToBeOutsourced; this.nameOfTheOutsourcingPartner = nameOfTheOutsourcingPartner; this.legalStatus = legalStatus; this.bankName = bankName; this.state = state; this.district = district; this.bankBranch = bankBranch; this.ifscCode = ifscCode; this.micr = micr; this.nameAsPerBankAccount = nameAsPerBankAccount; this.bankAccountNumber = bankAccountNumber; this.financialYear = financialYear; this.turnOver = turnOver; this.netWorth = netWorth; this.houseAddress = houseAddress; this.areaAddress = areaAddress; this.townCity = townCity; this.stateUt = stateUt; this.block = block; this.village = village; this.postOffice = postOffice; this.phone = phone; this.street = street; this.landmark = landmark; this.policeStation = policeStation; this.districtPartTwo = districtPartTwo; this.gramPanchayat = gramPanchayat; this.pin = pin; this.emailId = emailId; this.mobileNumber = mobileNumber; this.roleId = roleId; this.createdBy = createdBy; this.modifiedBy = modifiedBy; this.createdDate = createdDate; this.modifiedDate = modifiedDate; } @Id @Column(name="project_outsourcing_pa_id") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="pp_outsourcing_of_the_project_act_project_outsourcing_pa_id_seq") @SequenceGenerator(name="pp_outsourcing_of_the_project_act_project_outsourcing_pa_id_seq", sequenceName="pp_outsourcing_of_the_project_act_project_outsourcing_pa_id_seq", allocationSize=1) public int getProjectOutsourcingPaId() { return this.projectOutsourcingPaId; } public void setProjectOutsourcingPaId(int projectOutsourcingPaId) { this.projectOutsourcingPaId = projectOutsourcingPaId; } @Column(name = "project_proposal_id") public Integer getProjectProposalId() { return this.projectProposalId; } public void setProjectProposalId(Integer projectProposalId) { this.projectProposalId = projectProposalId; } @Column(name = "applicant_pia_process") public String getApplicantPiaProcess() { return this.applicantPiaProcess; } public void setApplicantPiaProcess(String applicantPiaProcess) { this.applicantPiaProcess = applicantPiaProcess; } @Column(name = "activity_to_be_outsourced") public String getActivityToBeOutsourced() { return this.activityToBeOutsourced; } public void setActivityToBeOutsourced(String activityToBeOutsourced) { this.activityToBeOutsourced = activityToBeOutsourced; } @Column(name = "name_of_the_outsourcing_partner") public String getNameOfTheOutsourcingPartner() { return this.nameOfTheOutsourcingPartner; } public void setNameOfTheOutsourcingPartner(String nameOfTheOutsourcingPartner) { this.nameOfTheOutsourcingPartner = nameOfTheOutsourcingPartner; } @Column(name = "legal_status") public String getLegalStatus() { return this.legalStatus; } public void setLegalStatus(String legalStatus) { this.legalStatus = legalStatus; } @Column(name = "bank_name") public String getBankName() { return this.bankName; } public void setBankName(String bankName) { this.bankName = bankName; } @Column(name = "state") public String getState() { return this.state; } public void setState(String state) { this.state = state; } @Column(name = "district") public String getDistrict() { return this.district; } public void setDistrict(String district) { this.district = district; } @Column(name = "bank_branch") public String getBankBranch() { return this.bankBranch; } public void setBankBranch(String bankBranch) { this.bankBranch = bankBranch; } @Column(name = "ifsc_code") public String getIfscCode() { return this.ifscCode; } public void setIfscCode(String ifscCode) { this.ifscCode = ifscCode; } @Column(name = "micr") public String getMicr() { return this.micr; } public void setMicr(String micr) { this.micr = micr; } @Column(name = "name_as_per_bank_account") public String getNameAsPerBankAccount() { return this.nameAsPerBankAccount; } public void setNameAsPerBankAccount(String nameAsPerBankAccount) { this.nameAsPerBankAccount = nameAsPerBankAccount; } @Column(name = "bank_account_number") public String getBankAccountNumber() { return this.bankAccountNumber; } public void setBankAccountNumber(String bankAccountNumber) { this.bankAccountNumber = bankAccountNumber; } @Column(name = "financial_year") public String getFinancialYear() { return this.financialYear; } public void setFinancialYear(String financialYear) { this.financialYear = financialYear; } @Column(name = "turn_over") public String getTurnOver() { return this.turnOver; } public void setTurnOver(String turnOver) { this.turnOver = turnOver; } @Column(name = "net_worth") public String getNetWorth() { return this.netWorth; } public void setNetWorth(String netWorth) { this.netWorth = netWorth; } @Column(name = "house_address") public String getHouseAddress() { return this.houseAddress; } public void setHouseAddress(String houseAddress) { this.houseAddress = houseAddress; } @Column(name = "area_address") public String getAreaAddress() { return this.areaAddress; } public void setAreaAddress(String areaAddress) { this.areaAddress = areaAddress; } @Column(name = "town_city") public String getTownCity() { return this.townCity; } public void setTownCity(String townCity) { this.townCity = townCity; } @Column(name = "state_ut") public String getStateUt() { return this.stateUt; } public void setStateUt(String stateUt) { this.stateUt = stateUt; } @Column(name = "block") public String getBlock() { return this.block; } public void setBlock(String block) { this.block = block; } @Column(name = "village") public String getVillage() { return this.village; } public void setVillage(String village) { this.village = village; } @Column(name = "post_office") public String getPostOffice() { return this.postOffice; } public void setPostOffice(String postOffice) { this.postOffice = postOffice; } @Column(name = "phone") public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; } @Column(name = "street") public String getStreet() { return this.street; } public void setStreet(String street) { this.street = street; } @Column(name = "landmark") public String getLandmark() { return this.landmark; } public void setLandmark(String landmark) { this.landmark = landmark; } @Column(name = "police_station") public String getPoliceStation() { return this.policeStation; } public void setPoliceStation(String policeStation) { this.policeStation = policeStation; } @Column(name = "district_part_two") public String getDistrictPartTwo() { return this.districtPartTwo; } public void setDistrictPartTwo(String districtPartTwo) { this.districtPartTwo = districtPartTwo; } @Column(name = "gram_panchayat") public String getGramPanchayat() { return this.gramPanchayat; } public void setGramPanchayat(String gramPanchayat) { this.gramPanchayat = gramPanchayat; } @Column(name = "pin") public String getPin() { return this.pin; } public void setPin(String pin) { this.pin = pin; } @Column(name = "email_id") public String getEmailId() { return this.emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } @Column(name = "mobile_number") public String getMobileNumber() { return this.mobileNumber; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } @Column(name = "role_id") public String getRoleId() { return this.roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } @Column(name = "created_by") public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } @Column(name = "modified_by") public String getModifiedBy() { return this.modifiedBy; } public void setModifiedBy(String modifiedBy) { this.modifiedBy = modifiedBy; } @Temporal(TemporalType.DATE) @Column(name = "created_date", length = 13) public Date getCreatedDate() { return this.createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } @Temporal(TemporalType.DATE) @Column(name = "modified_date", length = 13) public Date getModifiedDate() { return this.modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } }
/* * 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 com.printcalculator.enums; /** * * @author LiH */ public enum Price { A4SingleSide_BLACK("0.15"), A4SingleSide_COLOUR("0.25"), A4DoubleSide_BLACK("0.10"), A4DoubleSide_COLOUR("0.20"); Price(String cost) { this.cost = cost; } private final String cost; public String getCost() { return this.cost; } }
/* * This file is part of LeagueLib. * LeagueLib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LeagueLib 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 LeagueLib. If not, see <http://www.gnu.org/licenses/>. */ package com.lolRiver.achimala.leaguelib.connection; import com.lolRiver.achimala.leaguelib.errors.LeagueException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LeagueAccountQueue { private ArrayList<LeagueAccount> _internalQueue = new ArrayList<LeagueAccount>(); private LeagueServer _server; private int _index = 0; /** * Adds an account to the queue. * (Thread-safe) */ public synchronized void addAccount(LeagueAccount account) throws LeagueException { if (!account.isConnected()) account.connect(); _internalQueue.add(account); } /** * Gets the next account off the queue that is connected. * Returns null if no connected accounts are available. * Unlike traditional queues, not destructive. */ public synchronized LeagueAccount nextAccount() { if (_internalQueue.size() == 0) return null; for (int i = 0; i < _internalQueue.size(); i++) { _index = (_index + 1) % _internalQueue.size(); LeagueAccount account = _internalQueue.get(_index); if (account.isConnected()) return account; } // no accounts are connected return null; } /** * Returns a list view of all the accounts in the queue. */ public List<LeagueAccount> getAllAccounts() { return _internalQueue; } /** * Iterates through accounts in the queues and connects any that are disconnected. * In a Play! app or similar, don't call this as it connects each account synchronously * Instead, iterate over getAllAccounts() and call connect() on each account in a worker thread * and have your scheduler connect them in parallel. */ public synchronized Map<LeagueAccount, LeagueException> connectAll() { Map<LeagueAccount, LeagueException> exceptions = new HashMap<LeagueAccount, LeagueException>(); for (LeagueAccount account : _internalQueue) { try { if (!account.isConnected()) account.connect(); } catch (LeagueException ex) { exceptions.put(account, ex); } } return exceptions.size() > 0 ? exceptions : null; } /** * Returns true iff there exists an account that is connected. */ public synchronized boolean isAnyAccountConnected() { for (LeagueAccount account : _internalQueue) { if (account.isConnected()) return true; } return false; } /** * Returns true iff every account is connected. */ public synchronized boolean isEveryAccountConnected() { for (LeagueAccount account : _internalQueue) { if (!account.isConnected()) return false; } return true; } }
package com.tencent.mm.plugin.appbrand.appusage; import com.tencent.mm.ab.b; import com.tencent.mm.ab.l; import com.tencent.mm.ab.v.a; import com.tencent.mm.protocal.c.aks; import com.tencent.mm.sdk.platformtools.x; class e$1 implements a { final /* synthetic */ e flm; e$1(e eVar) { this.flm = eVar; } public final int a(int i, int i2, String str, b bVar, l lVar) { if (i == 0 && i2 == 0 && bVar != null && bVar.dIE.dIL != null && (bVar.dIE.dIL instanceof aks)) { e.a(this.flm, (aks) bVar.dIE.dIL); } else { x.e("MicroMsg.AppBrandLauncherListWAGameLogic", "doRequest() cgi return errType %d, errCode %d, errMsg %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str}); e.a(this.flm, null); } return 0; } }
/* * Minesweeper Project * by Group3 : Arnaud BABOL, Guillaume SIMMONEAU */ package Model; import View.View; import java.util.LinkedList; /** * * @author simonneau */ public abstract class Model { /** * */ protected LinkedList<View> views; /** * */ public abstract void notifyViews(); /** * * @return */ @Override public abstract Model clone(); /** * * @param view */ public void addView(View view){ this.views.add(view); } }
package org.bokontep.wavesynth; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; public class WaveTableEdit extends View { private SynthEngine engine = null; private int w = 0; private int h = 0; private WaveDisplay[] waveDisplays = null; private WaveDisplay drawDisplay = null; int selectedIndex = -1; int displayWaveHeight = 0; int displayWaveItemWidth = 0; public WaveTableEdit(Context context, AttributeSet attrs,SynthEngine engine) { super(context, attrs); setFocusable(true); setFocusableInTouchMode(true); waveDisplays = new WaveDisplay[16]; setSynthEngine(engine); for(int i=0;i<waveDisplays.length;i++) { waveDisplays[i] = new WaveDisplay(this.getContext(),attrs); waveDisplays[i].setData(engine.getWavetable(i)); } } public void setSynthEngine(SynthEngine engine) { this.engine = engine; } public SynthEngine getSynthEngine() { return this.engine; } @Override protected void onDraw(Canvas canvas) { } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); this.w = w; this.h = h; displayWaveHeight = h/4; displayWaveItemWidth = w/(waveDisplays.length+2); for(int i=0;i<waveDisplays.length;i++) { waveDisplays[i].setLayoutParams(new WindowManager.LayoutParams(displayWaveHeight,displayWaveItemWidth)); } } }
package controlador; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.ExecutionListener; import persistencia.UsuariosAgesic; public class ElegirUsuarios implements ExecutionListener{ public void notify(DelegateExecution execution) { EntityManagerFactory emf = Persistence .createEntityManagerFactory("EmployeePU"); EntityManager em = emf.createEntityManager(); Query q=em.createNamedQuery("UsuariosAgesic.findAll"); List<UsuariosAgesic> usuarios= q.getResultList(); String usrs=""; int i = 0; String integrante1=""; String integrante2= ""; String integrante3= ""; if(execution.getVariable("integrante1") instanceof Long) { integrante1= ((Long) execution.getVariable("integrante1")).toString(); }else if(execution.getVariable("integrante1") instanceof Integer) { integrante1= ((Integer) execution.getVariable("integrante1")).toString(); }else if(execution.getVariable("integrante1") instanceof String) { integrante1= (String) execution.getVariable("integrante1"); } if(execution.getVariable("integrante2") instanceof Long) { integrante2= ((Long) execution.getVariable("integrante2")).toString(); }else if(execution.getVariable("integrante2") instanceof Integer) { integrante2= ((Integer) execution.getVariable("integrante2")).toString(); }else if(execution.getVariable("integrante2") instanceof String) { integrante2= (String) execution.getVariable("integrante2"); } if(execution.getVariable("integrante3") instanceof Long) { integrante3= ((Long) execution.getVariable("integrante3")).toString(); }else if(execution.getVariable("integrante3") instanceof Integer) { integrante3= ((Integer) execution.getVariable("integrante3")).toString(); }else if(execution.getVariable("integrante3") instanceof String) { integrante3= (String) execution.getVariable("integrante3"); } for (UsuariosAgesic usuariosAgesic : usuarios) { if(Integer.toString(i).compareTo(integrante1)==0) execution.setVariable("integrante1", usuariosAgesic.getId().getUsr()); if(Integer.toString(i).compareTo(integrante2)==0) execution.setVariable("integrante2", usuariosAgesic.getId().getUsr()); if(Integer.toString(i).compareTo(integrante3)==0) execution.setVariable("integrante3", usuariosAgesic.getId().getUsr()); i++; } execution.setVariable("usuarios", usrs); } }
package chapter07; import java.util.Scanner; public class Exercise07_25 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter the values a,b,c: "); double[] array = new double[3]; array[0] = input.nextDouble(); array[1] = input.nextDouble(); array[2] = input.nextDouble(); double[] roots = new double[2]; solveQuadratic(array, roots); } public static int solveQuadratic(double[] eqn, double[] roots) { double discriminant = Math.pow(eqn[1], 2) - (4 * eqn[0] * eqn[2]); if (discriminant > 0) { System.out.println("Number of reel roots: 2"); System.out.println("Root one: " + ((-eqn[1] + Math.sqrt(discriminant)) / (2 * eqn[0]))); System.out.println("Root two: " + ((-eqn[1] - Math.sqrt(discriminant)) / (2 * eqn[0]))); return 2; } else if (discriminant == 0) { System.out.println("Number of reel roots: 1"); System.out.println(((-eqn[1] + Math.sqrt(discriminant))) / (2 * eqn[0])); return 1; } else { System.out.println("There is no reel roots"); return 0; } } }
package com.tencent.mm.plugin.card.b; import android.content.IntentFilter; import android.location.LocationManager; import com.tencent.map.geolocation.TencentLocationListener; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.plugin.card.a.g; import com.tencent.mm.plugin.card.base.b; import com.tencent.mm.plugin.card.model.ai; import com.tencent.mm.protocal.c.iu; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.al; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.base.h; public final class i implements e { public volatile float cXm = -85.0f; public volatile float cXn = -1000.0f; String htC; private b htQ; public MMActivity hub; public volatile boolean huc = false; private volatile boolean hud = false; public Object hue = new Object(); private boolean huf = false; boolean hug = false; private boolean huh = false; iu hui; private b huj; public a huk; private int hul = 60; private long hum = 0; private long hun = 0; private long huo = 10000; public al hup = new al(new 1(this), false); public final void a(MMActivity mMActivity, String str, b bVar, float f, float f2) { int i; boolean z; this.huc = true; this.hub = mMActivity; this.htC = str; this.htQ = bVar; this.cXm = f; this.cXn = f2; this.huf = bVar.awm().rop; this.hug = bVar.awn().rns; this.hui = bVar.awm().roq; if (bVar.awm().roq == null) { i = 60; } else { i = bVar.awm().roq.rjZ; } this.hul = i; if (bVar.awm().roq == null || bi.oW(bVar.awm().roq.name)) { z = false; } else { z = true; } this.huh = z; x.i("MicroMsg.CardLbsOrBluetooth", "init cardId:%s, needLocation:%b, isLocationAuth:%b needBluetooth:%b reportTime:%d", new Object[]{str, Boolean.valueOf(this.huf), Boolean.valueOf(this.hug), Boolean.valueOf(this.huh), Integer.valueOf(this.hul)}); if (this.huf && !this.hug) { String str2 = bi.oW(this.htQ.awm().ror) ? this.htQ.awm().title : this.htQ.awm().ror; h.a(this.hub, this.hub.getString(g.card_report_location_confirm, new Object[]{str2}), this.hub.getString(g.app_tip), new 2(this), new 3(this)); } if (this.huh) { x.i("MicroMsg.CardLbsOrBluetooth", "initBluetoothHelper blueToothInfo.name:%s", new Object[]{this.hui.name}); this.huk = new a(this, (byte) 0); a aVar = this.huk; x.i("MicroMsg.CardLbsOrBluetooth", "init bluetoothStateListener"); aVar.fKZ = new 2(aVar); ad.getContext().registerReceiver(aVar.fKZ, new IntentFilter("android.bluetooth.adapter.action.STATE_CHANGED")); } start(); xP(); } public final void start() { if (awQ()) { x.i("MicroMsg.CardLbsOrBluetooth", "start"); if (this.huc) { if (this.huf) { LocationManager locationManager = (LocationManager) ad.getContext().getSystemService("location"); if (locationManager != null) { boolean isProviderEnabled = locationManager.isProviderEnabled(TencentLocationListener.GPS); boolean isProviderEnabled2 = locationManager.isProviderEnabled("network"); x.i("MicroMsg.CardLbsOrBluetooth", "isGPSEnable:%b isNetworkEnable:%b", new Object[]{Boolean.valueOf(isProviderEnabled), Boolean.valueOf(isProviderEnabled2)}); } } if (this.huk != null && this.huh) { this.huk.awS(); } awN(); com.tencent.mm.kernel.g.Eh().dpP.a(2574, this); return; } x.e("MicroMsg.CardLbsOrBluetooth", "isInit:%b", new Object[]{Boolean.valueOf(this.huc)}); } } public final void awN() { awO(); if (this.hul > 0) { long j = (long) (this.hul * 1000); this.hup.J(j, j); x.i("MicroMsg.CardLbsOrBluetooth", "start ReportTimer!"); return; } x.e("MicroMsg.CardLbsOrBluetooth", "not to start ReportTimer!"); } public final void awO() { x.i("MicroMsg.CardLbsOrBluetooth", "stop ReportTimer!"); if (!this.hup.ciq()) { this.hup.SO(); } } public final void xP() { if (!awQ()) { x.i("MicroMsg.CardLbsOrBluetooth", "[report]not need report"); } else if (this.hud) { x.i("MicroMsg.CardLbsOrBluetooth", "isReporting, return"); } else { boolean z; boolean awP; this.hud = true; if (this.huh) { if (this.huk == null) { x.e("MicroMsg.CardLbsOrBluetooth", "[needReportBluetooth]bluetoothHelper is null, return"); } else if (!this.huk.awR().byN.equals("") && System.currentTimeMillis() - this.hum >= this.huo) { z = true; awP = awP(); x.i("MicroMsg.CardLbsOrBluetooth", "report needLocation:%b, isLocationAuth:%b, isBluetoothEnable:%b, needReportBluetooth:%b needReportGps:%b", new Object[]{Boolean.valueOf(this.huf), Boolean.valueOf(this.hug), Boolean.valueOf(this.huk.hus), Boolean.valueOf(z), Boolean.valueOf(awP)}); b awR; if (!z && awP) { awR = this.huk.awR(); x.i("MicroMsg.CardLbsOrBluetooth", "reportBluetoothAndGps deviceInfo:%s", new Object[]{awR}); x.d("MicroMsg.CardLbsOrBluetooth", "reportBluetoothAndGps lbsLongitude:%f, lbsLatitude:%f", new Object[]{Float.valueOf(this.cXn), Float.valueOf(this.cXm)}); a(this.htC, awR.huy, this.cXn, this.cXm, awR.bMF, this.huk.hus, this.hug); this.hun = System.currentTimeMillis(); this.hum = System.currentTimeMillis(); this.huk.reset(); this.huj = awR; return; } else if (z) { awR = this.huk.awR(); x.i("MicroMsg.CardLbsOrBluetooth", "reportBluetooth deviceInfo:%s", new Object[]{awR}); a(this.htC, awR.huy, -1000.0f, -85.0f, awR.bMF, this.huk.hus, this.hug); this.hum = System.currentTimeMillis(); this.huk.reset(); this.huj = awR; } else if (awP) { x.i("MicroMsg.CardLbsOrBluetooth", "reportgps"); x.d("MicroMsg.CardLbsOrBluetooth", "reportgps lbsLongitude:%f, lbsLatitude:%f", new Object[]{Float.valueOf(this.cXn), Float.valueOf(this.cXm)}); a(this.htC, new byte[0], this.cXn, this.cXm, 0, false, this.hug); this.hun = System.currentTimeMillis(); } else { x.e("MicroMsg.CardLbsOrBluetooth", "not report"); this.hud = false; } } } z = false; awP = awP(); x.i("MicroMsg.CardLbsOrBluetooth", "report needLocation:%b, isLocationAuth:%b, isBluetoothEnable:%b, needReportBluetooth:%b needReportGps:%b", new Object[]{Boolean.valueOf(this.huf), Boolean.valueOf(this.hug), Boolean.valueOf(this.huk.hus), Boolean.valueOf(z), Boolean.valueOf(awP)}); if (!z) { } if (z) { awR = this.huk.awR(); x.i("MicroMsg.CardLbsOrBluetooth", "reportBluetooth deviceInfo:%s", new Object[]{awR}); a(this.htC, awR.huy, -1000.0f, -85.0f, awR.bMF, this.huk.hus, this.hug); this.hum = System.currentTimeMillis(); this.huk.reset(); this.huj = awR; } else if (awP) { x.i("MicroMsg.CardLbsOrBluetooth", "reportgps"); x.d("MicroMsg.CardLbsOrBluetooth", "reportgps lbsLongitude:%f, lbsLatitude:%f", new Object[]{Float.valueOf(this.cXn), Float.valueOf(this.cXm)}); a(this.htC, new byte[0], this.cXn, this.cXm, 0, false, this.hug); this.hun = System.currentTimeMillis(); } else { x.e("MicroMsg.CardLbsOrBluetooth", "not report"); this.hud = false; } } } private boolean awP() { boolean z = true; synchronized (this.hue) { boolean z2; if (System.currentTimeMillis() - this.hun >= this.huo) { z2 = true; } else { z2 = false; } boolean z3; if (Float.compare(this.cXm, -85.0f) == 0 || Float.compare(this.cXn, -1000.0f) == 0) { z3 = false; } else { z3 = true; } if (!(this.hug && this.huf && z3 && z2)) { z = false; } } return z; } static void a(String str, byte[] bArr, float f, float f2, int i, boolean z, boolean z2) { com.tencent.mm.kernel.g.Eh().dpP.a(new ai(str, bArr, f, f2, (float) i, z, z2), 0); } public final void a(int i, int i2, String str, l lVar) { x.i("MicroMsg.CardLbsOrBluetooth", "report success, onSceneEnd errType:%d, errCode:%d, errMsg:%s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str}); this.hud = false; } public final boolean awQ() { return this.huf || this.huh; } }
package com.graphql.test.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.graphql.test.model.User; import com.graphql.test.schema.QueryResolver; @RestController @RequestMapping("api/rest/users") public class UserResource { @Autowired private QueryResolver query; @GetMapping("/{id}") @ResponseBody public User getUser(@PathVariable("id") Integer id) { return query.user(id); } }
package data; import entityparts.EntityPart; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class Entity implements Serializable { private final UUID ID = UUID.randomUUID(); private UUID parentId; public UUID getParentId() { return parentId; } public void setParentId(UUID parentId) { this.parentId = parentId; } public Map<Class, EntityPart> getParts() { return parts; } public void setParts(Map<Class, EntityPart> parts) { this.parts = parts; } private float[] shapeX = new float[4]; private float[] shapeY = new float[4]; private float radius; private float[] colour; private Map<Class, EntityPart> parts; private String sprite; private String spawnSound; private boolean isSpawnSoundLoaded; private boolean IsLoaded; private boolean isUsingBoxCollision = true; public boolean isIsUsingBoxCollision() { return isUsingBoxCollision; } public void setIsUsingBoxCollision(boolean isUsingBoxCollision) { this.isUsingBoxCollision = isUsingBoxCollision; } private boolean isSpawned; public boolean isIsSpawnSoundLoaded() { return isSpawnSoundLoaded; } public void setIsSpawnSoundLoaded(boolean isSpawnSoundLoaded) { this.isSpawnSoundLoaded = isSpawnSoundLoaded; } public boolean isIsSpawned() { return isSpawned; } public void setIsSpawned(boolean isSpawned) { this.isSpawned = isSpawned; } public String getSpawnSound() { return spawnSound; } public void setSpawnSound(String spawnSound) { this.spawnSound = spawnSound; } public String getSprite() { return sprite; } public void setSprite(String sprite) { this.sprite = sprite; } public boolean getIsLoaded() { return IsLoaded; } public void setIsLoaded(boolean IsLoaded) { this.IsLoaded = IsLoaded; } public Entity() { parts = new ConcurrentHashMap<>(); } public void add(EntityPart part) { parts.put(part.getClass(), part); } public void remove(Class partClass) { parts.remove(partClass); } public <E extends EntityPart> E getPart(Class partClass) { return (E) parts.get(partClass); } public void setRadius(float r) { this.radius = r; } public float getRadius() { return radius; } public String getID() { return ID.toString(); } public float[] getShapeX() { return shapeX; } public void setShapeX(float[] shapeX) { this.shapeX = shapeX; } public float[] getShapeY() { return shapeY; } public void setShapeY(float[] shapeY) { this.shapeY = shapeY; } public float[] getColour() { return this.colour; } public void setColour(float[] c) { this.colour = c; } }
package com.yinghai.a24divine_user.module.login; import android.Manifest; import android.content.Context; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.telephony.TelephonyManager; import com.example.fansonlib.utils.MyPermissionHelper; import com.example.fansonlib.utils.SharePreferenceHelper; import com.example.fansonlib.utils.ShowToast; import com.yinghai.a24divine_user.R; import com.yinghai.a24divine_user.base.MyBaseActivity; import com.yinghai.a24divine_user.callback.IBackFragmentListener; import com.yinghai.a24divine_user.constant.ConFragment; import com.yinghai.a24divine_user.constant.ConstantPreference; import com.yinghai.a24divine_user.manager.MyFragmentManager; import com.yinghai.a24divine_user.module.login.bind.BindFragment; import com.yinghai.a24divine_user.module.login.phone.LoginFragment; import com.yinghai.a24divine_user.module.login.findpassword.FindPasswordFragment; import com.yinghai.a24divine_user.module.login.setpassword.SetPasswordFragment; import com.yinghai.a24divine_user.module.login.state.LoginStateManager; import com.yinghai.a24divine_user.module.main.MainActivity; import com.yinghai.a24divine_user.utils.LogUtils; import com.yinghai.a24divine_user.utils.MyStatusBarUtil; /** * @author Created by:fanson * Created on:2017/10/25 15:42 * Description:登录Activity */ public class LoginActivity extends MyBaseActivity implements IBackFragmentListener { private static final String TAG = LoginActivity.class.getSimpleName(); private LoginFragment mLoginFragment; private ChooseLoginFragment mChooseLoginFragment; private MyPermissionHelper mPermissionHelper; private BindFragment mBindFragment; private FindPasswordFragment mFindPasswordFragment; private SetPasswordFragment mSetPasswordFragment; @Override protected int getContentView() { return R.layout.activity_login; } @Override protected void initView() { super.initView(); LogUtils.d(TAG, "initView"); if (SharePreferenceHelper.getBoolean(ConstantPreference.B_USER_LOGIN, false) && LoginStateManager.getInstance().getState()) { startMyActivity(MainActivity.class); } else { SharePreferenceHelper.clear(); checkPermission(); initChooseLoginFragment(); } } @Override protected void setStatus() { MyStatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null); } private void initChooseLoginFragment() { if (mChooseLoginFragment == null) { mChooseLoginFragment = new ChooseLoginFragment(); } MyFragmentManager.replaceFragment(getSupportFragmentManager(), R.id.login_fl_main, mChooseLoginFragment); } private void initPhoneLoginFragment() { if (mLoginFragment == null) { mLoginFragment = new LoginFragment(); } MyFragmentManager.switchFragment(getSupportFragmentManager(), R.id.login_fl_main, getCurrentFragment(), mLoginFragment); } private void initBindFragment(int thirdId) { mBindFragment = BindFragment.newInstance(thirdId); MyFragmentManager.switchFragment(getSupportFragmentManager(),R.id.login_fl_main, getCurrentFragment(), mBindFragment); } /** * 找回密码 */ private void initFindPasswordFragment() { mFindPasswordFragment = FindPasswordFragment.newInstance(FindPasswordFragment.TYPE_FIND_PASSWORD); MyFragmentManager.switchFragment(getSupportFragmentManager(),R.id.login_fl_main, mLoginFragment, mFindPasswordFragment); } private void initSetPasswordFragment() { mSetPasswordFragment = new SetPasswordFragment(); MyFragmentManager.switchFragment(getSupportFragmentManager(),R.id.login_fl_main, getCurrentFragment(), mSetPasswordFragment); } @Override protected void initData() { } @Override protected void listenEvent() { } @Override public void onFragment(Object object) { super.onFragment(object); switch ((int) object) { case ConFragment.OPEN_PHONE_LOGIN: initPhoneLoginFragment(); break; // 找回密码 case ConFragment.FIND_PASSWORD: initFindPasswordFragment(); break; // 设置密码 case ConFragment.SET_PASSWORD: initSetPasswordFragment(); break; // 找回密码成功 case ConFragment.FIND_PASSWORD_SUCCESS: mLoginFragment = new LoginFragment(); switchFragment(R.id.login_fl_main, getCurrentFragment(), mLoginFragment); break; case ConFragment.SET_PASSWORD_FRAGMENT_BACK: initPhoneLoginFragment(); break; case ConFragment.Login_FRAGMENT_BACK: onBackPressed(); break; case ConFragment.FIND_PASSWORD_FRAGMENT_BACK: initPhoneLoginFragment(); break; default: break; } } @Override public void currentFragmentBack(Fragment fragment) { mCurrentFragmentList.add(fragment); } public void checkPermission() { if (Build.VERSION.SDK_INT < 23) { getDeviceId(); return; } if (!MyPermissionHelper.hasPermissions(this, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_SMS)) { mPermissionHelper = new MyPermissionHelper(this); mPermissionHelper.requestPermissions(getString(R.string.phone_permission_request), new MyPermissionHelper.PermissionListener() { @Override public void doAfterGrand(String... permission) { getDeviceId(); } @Override public void doAfterDenied(String... permission) { ShowToast.Long(getString(R.string.phone_permission_no_agress)); checkPermission(); } }, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_SMS); } else { getDeviceId(); } } private void getDeviceId() { String strIMEI = ((TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId(); SharePreferenceHelper.putString(ConstantPreference.S_DEVICE_ID, strIMEI); SharePreferenceHelper.apply(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { mPermissionHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults); } @Override public void onMultiFragment(Object... object) { super.onMultiFragment(object); switch ((Integer) object[0]) { case ConFragment.OPEN_BIND_VIEW: initBindFragment((Integer) object[1]); break; default: break; } } @Override public void onBackPressed() { if (!MyFragmentManager.handlerBackPress(getSupportFragmentManager())){ finish(); } } @Override protected void onDestroy() { super.onDestroy(); if (mCurrentFragmentList != null) { mCurrentFragmentList.clear(); mCurrentFragmentList = null; } mBindFragment = null; mChooseLoginFragment = null; mLoginFragment = null; mFindPasswordFragment = null; mSetPasswordFragment = null; } }
package edu.kit.pse.osip.core.io.networking; /** * Class for saving connection and networking details. * * @author Maximilian Schwarzmann * @version 1.0 */ public class RemoteMachine { /** * Saves the hostname. */ private String hostname; /** * Saves the port. */ private int port; /** * Constructor of RemoteMachine. * * @param hostname host name of the RemoteMachine. * @param port the port of the RemoteMachine. */ public RemoteMachine(String hostname, int port) { this.hostname = hostname; this.port = port; } /** * Getter method of the hostname. * * @return hostname of RemoteMachine. */ public final String getHostname() { return hostname; } /** * Getter method of port. * * @return port of RemoteMachine. */ public final int getPort() { return port; } }
package com.example.matthewtimmons.guessthatsong.Managers; import android.content.Context; import android.content.SharedPreferences; import android.widget.Toast; import com.example.matthewtimmons.guessthatsong.Models.Level; import com.example.matthewtimmons.guessthatsong.R; import java.util.ArrayList; import java.util.List; import java.util.Map; public class LevelSaveDataManager { public static List<Level> allLevelsData; public static void instantiateLevelsWithSaveData(Context context) { List<Level> allLevels = new ArrayList<Level>(); SharedPreferences sharedPreferences = SharedPreferencesManager.getSharedPreferences(context); Map<String, Object> val = (Map<String, Object>) sharedPreferences.getAll(); allLevels.add(new Level("cyfmh", "Can You Feel My Heart", "Bring Me The Horizon", R.raw.can_you_feel_my_heart_5, R.raw.can_you_feel_my_heart_3, R.raw.can_you_feel_my_heart_1, (Boolean) val.get("cyfmh"))); allLevels.add(new Level("drown", "Drown", "Bring Me The Horizon", R.raw.drown_5, R.raw.drown_3, R.raw.drown_1, (Boolean) val.get("2"))); allLevels.add(new Level("february", "February", "A Thorn For Every Heart", R.raw.february_5, R.raw.february_3, R.raw.february_1, (Boolean) val.get("3"))); allLevels.add(new Level("helena", "Helena", "My Chemical Romance", R.raw.helena_5, R.raw.helena_3, R.raw.helena_1, (Boolean) val.get("4"))); allLevels.add(new Level("ino", "I'm Not Okay", "My Chemical Romance", R.raw.im_not_okay_5, R.raw.im_not_okay_3, R.raw.im_not_okay_1, (Boolean) val.get("5"))); allLevelsData = allLevels; } }
/* Violet - A program for editing UML diagrams. Copyright (C) 2007 Cay S. Horstmann (http://horstmann.com) Alexandre de Pellegrin (http://alexdp.free.fr); This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.horstmann.violet.framework.file.chooser; import java.io.IOException; import java.util.ArrayList; import javax.jnlp.FileContents; import javax.jnlp.FileOpenService; import javax.jnlp.FileSaveService; import javax.jnlp.ServiceManager; import javax.jnlp.UnavailableServiceException; import com.horstmann.violet.framework.file.IFile; import com.horstmann.violet.framework.file.naming.ExtensionFilter; import com.horstmann.violet.framework.file.naming.FileNamingService; import com.horstmann.violet.framework.file.persistence.IFileReader; import com.horstmann.violet.framework.file.persistence.IFileWriter; import com.horstmann.violet.framework.file.persistence.JNLPFileReader; import com.horstmann.violet.framework.file.persistence.JNLPFileWriter; import com.horstmann.violet.framework.injection.bean.ManiocFramework.BeanInjector; import com.horstmann.violet.framework.injection.bean.ManiocFramework.InjectedBean; import com.horstmann.violet.framework.injection.bean.ManiocFramework.ManagedBean; /** * This class provides a FileService for Java Web Start. Note that file saving is strange under Web Start. You first save the data, * and the dialog is only displayed when the output stream is closed. Therefore, the file name is not available until after the file * has been written. */ @ManagedBean(registeredManually=true) public class JNLPFileChooserService implements IFileChooserService { /** * Default constructor * * @param namingService */ public JNLPFileChooserService() { BeanInjector.getInjector().inject(this); try { openService = (FileOpenService) ServiceManager.lookup("javax.jnlp.FileOpenService"); saveService = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService"); } catch (UnavailableServiceException ex) { ex.printStackTrace(); } } /* * (non-Javadoc) * * @see com.horstmann.violet.framework.file.chooser.IFileChooserService#isWebStart() */ public boolean isWebStart() { return true; } @Override public IFileReader getFileReader(IFile file) throws IOException { String currentDirectory = file.getDirectory(); String filename = file.getFilename(); ExtensionFilter[] filters = this.fileNamingService.getFileFilters(); ArrayList<String> fileExtensions = new ArrayList<String>(); for (ExtensionFilter aFilter : filters) { String aFilterExtension = aFilter.getExtension(); if (filename.endsWith(aFilterExtension)) { fileExtensions.add(aFilterExtension); } } String[] fileExtensionsStrings = (String[]) fileExtensions.toArray(new String[fileExtensions.size()]); final FileContents contents = openService.openFileDialog(currentDirectory, fileExtensionsStrings); return new JNLPFileReader(contents); } @Override public IFileReader chooseAndGetFileReader(ExtensionFilter... filters) throws IOException { String currentDirectory = "."; ArrayList<String> fileExtensions = new ArrayList<String>(); //ExtensionFilter[] filters = this.fileNamingService.getFileFilters(); for (int i = 0; i < filters.length; i++) { ExtensionFilter aFilter = filters[i]; String filterExtension = aFilter.getExtension(); fileExtensions.add(filterExtension); } String[] fileExtensionsStrings = (String[]) fileExtensions.toArray(new String[fileExtensions.size()]); final FileContents contents = openService.openFileDialog(currentDirectory, fileExtensionsStrings); return new JNLPFileReader(contents); } @Override public IFileWriter getFileWriter(IFile file) throws IOException { String defaultDirectory = file.getDirectory(); ArrayList<String> fileExtensions = new ArrayList<String>(); ExtensionFilter[] filters = this.fileNamingService.getFileFilters(); for (int i = 0; i < filters.length; i++) { ExtensionFilter aFilter = filters[i]; String filterExtension = aFilter.getExtension(); fileExtensions.add(filterExtension); } String[] fileExtensionsStrings = (String[]) fileExtensions.toArray(new String[fileExtensions.size()]); FileContents contents = saveService.saveAsFileDialog(defaultDirectory, fileExtensionsStrings, null); if (contents == null) { return null; } return new JNLPFileWriter(contents); } @Override public IFileWriter chooseAndGetFileWriter(final ExtensionFilter... filters) throws IOException { String defaultDirectory = "."; ArrayList<String> fileExtensions = new ArrayList<String>(); for (int i = 0; i < filters.length; i++) { ExtensionFilter aFilter = filters[i]; String filterExtension = aFilter.getExtension(); fileExtensions.add(filterExtension); } String[] fileExtensionsStrings = (String[]) fileExtensions.toArray(new String[fileExtensions.size()]); FileContents contents = saveService.saveAsFileDialog(defaultDirectory, fileExtensionsStrings, null); if (contents == null) { return null; } return new JNLPFileWriter(contents); } /** * JNLP service */ private FileOpenService openService; /** * JNLP service */ private FileSaveService saveService; /** * Handle file names */ @InjectedBean private FileNamingService fileNamingService; }
package javapt; import java.text.DecimalFormat; public final class RenderTask implements Runnable { public RenderTask(final Camera camera, final Scene scene, final int samples, final ImageBuffer imageBuffer, final int line) { this.camera = camera; this.scene = scene; this.samples = samples; this.imageBuffer = imageBuffer; this.line = line; this.r = new java.util.Random(this.line); this.df = new DecimalFormat("#0.0"); } @Override public final void run() { for (int x = 0; x < camera.getImageWidth(); ++x) { for (int s = 0; s < samples; ++s) { final Vec2 pixelSample = new Vec2(x + r.nextDouble(), line + r.nextDouble()); final Ray ray = camera.getRay(pixelSample); imageBuffer.setPixel(x, line, Vec3.add(imageBuffer.getPixel(x, line), traceRay(ray, 0))); } imageBuffer.setPixel(x, line, Vec3.div(imageBuffer.getPixel(x, line), samples)); } synchronized (System.out) { System.out.print("Progress: " + df.format(((double) (line + 1) / camera.getImageHeight()) * 100.0) + "%\r"); } } public final Vec3 traceRay(final Ray ray, final int depth) { IntersectionRecord intRec = new IntersectionRecord(); if (!scene.intersect(ray, intRec) || (depth > 10)) return new Vec3(); final Vec3 emission = scene.getPrimitives().get(intRec.id).getMaterial().getEmission(); final ONB onb = new ONB(Vec3.normalize(intRec.normal)); final Vec3 localWo = Mat3x3.mul(onb.getWorldToLocalMatrix(), Vec3.mul(ray.getDirection(), -1.0)); Vec3 localWi = new Vec3(); final Vec3 partREValue = scene.getPrimitives().get(intRec.id).getMaterial().getBSDF().evalPartRE(localWo, localWi, r); final Vec3 worldWi = Mat3x3.mul(onb.getLocalToWorldMatrix(), localWi); final Ray newRay = new Ray(Vec3.add(intRec.position, Vec3.mul(worldWi, 1e-5)), worldWi); return Vec3.add(emission, Vec3.mul(partREValue, traceRay(newRay, depth + 1))); } private final Camera camera; private final Scene scene; private final int samples; private final ImageBuffer imageBuffer; private final int line; private final java.util.Random r; private final DecimalFormat df; }
/* * 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 data.db; import data.core.api.ApiData; import data.core.api.ApiDatabase; import java.util.HashMap; /** * * @author Ryno */ public class DBAssessment extends ApiDatabase{ //-------------------------------------------------------------------------- //properties //-------------------------------------------------------------------------- public DBAssessment(){ key = "asm_id"; table = "assessment"; fields = new HashMap <> (); fields.put("asm_id", new Object[]{"id", "null", ApiData.INT}); fields.put("asm_date", new Object[]{"date added", "null", ApiData.DATETIME}); fields.put("asm_ref_class", new Object[]{"class", "null", ApiData.INT}); fields.put("asm_name", new Object[]{"name", "", ApiData.STRING}); fields.put("asm_term", new Object[]{"term", "", ApiData.STRING}); fields.put("asm_column_count", new Object[]{"type", "0", ApiData.INT}); } //-------------------------------------------------------------------------- }
/* * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with SAP Hybris. */ package com.cnk.travelogix.sapintegrations.facade; import de.hybris.platform.servicelayer.dto.converter.Converter; import org.apache.log4j.Logger; import com.cnk.travelogix.contract.provisioning.data.ContractOperationResponseData; import com.cnk.travelogix.contract.provisioning.data.MaintainChargingContractRequestData; import com.cnk.travelogix.custom.chargeable.itemcharging.ChargeableItemChargeRequest; import com.cnk.travelogix.custom.chargeable.itemcharging.ChargeableItemChargeResponse; import com.cnk.travelogix.custom.contract.provisioning.ContractOperationResponse; import com.cnk.travelogix.custom.contract.provisioning.MaintainChargingContractRequest; import com.cnk.travelogix.custom.mappingtable.maintain.MaintainMappingTableRequest; import com.cnk.travelogix.custom.mappingtable.maintain.MaintainMappingTableRowRequest; import com.cnk.travelogix.custom.mappingtable.maintain.MappingTableOperationResponse; import com.cnk.travelogix.custom.mappingtable.maintain.MappingTableRowOperationResponse; import com.cnk.travelogix.custom.subscribe.account.ExternalAccountMaintainRequest; import com.cnk.travelogix.custom.subscribe.account.ExternalAccountOperationResponse; import com.cnk.travelogix.custom.subscribe.account.SubscriberAccountCancelRequest; import com.cnk.travelogix.custom.subscribe.account.SubscriberAccountMaintainRequest; import com.cnk.travelogix.custom.subscribe.account.SubscriberAccountOperationResponse; import com.cnk.travelogix.sapintegrations.chargeable.itemcharging.data.ChargeableItemChargeRequestData; import com.cnk.travelogix.sapintegrations.chargeable.itemcharging.data.ChargeableItemChargeResponseData; import com.cnk.travelogix.sapintegrations.exception.ServiceNotSupportedException; import com.cnk.travelogix.sapintegrations.factory.SAPWebServicesFactory; import com.cnk.travelogix.sapintegrations.mappingtable.maintain.data.MaintainMappingTableRequestData; import com.cnk.travelogix.sapintegrations.mappingtable.maintain.data.MappingTableOperationResponseData; import com.cnk.travelogix.sapintegrations.processor.ContractProvisioningProcessor; import com.cnk.travelogix.sapintegrations.processor.ExternalAccMaintainRequestProcessor; import com.cnk.travelogix.sapintegrations.processor.ItemChargingProcessor; import com.cnk.travelogix.sapintegrations.processor.MaintainMappingTableRequestProcessor; import com.cnk.travelogix.sapintegrations.processor.MappingTableRowMaintainRequestProcessor; import com.cnk.travelogix.sapintegrations.processor.SubscriberAccMaintainRequestProcessor; import com.cnk.travelogix.sapintegrations.processor.SubscriberAccountCancelProcessor; import com.cnk.travelogix.sapintegrations.subscribe.account.data.ExternalAccount; import com.cnk.travelogix.sapintegrations.subscribe.account.data.ExternalAccountMaintainData; import com.cnk.travelogix.sapintegrations.subscribe.account.data.ExternalAccountOperationResponseData; import com.cnk.travelogix.sapintegrations.subscribe.account.data.ResponseStatus; import com.cnk.travelogix.sapintegrations.subscribe.account.data.SubscriberAccountMaintainData; import com.cnk.travelogix.sapintegrations.subscribe.account.data.SubscriberAccountOperationResponseData; /** * */ public class DefaultCCServicesFacade implements CCServicesFacade { private final Logger LOG = Logger.getLogger(getClass()); private SAPWebServicesFactory sapWebServicesFactory; private Converter<SubscriberAccountMaintainData, SubscriberAccountMaintainRequest> subscriberAccMaintaintRequestDataConverter; private Converter<SubscriberAccountOperationResponse, SubscriberAccountOperationResponseData> subscriberAccMaintaintResponseDataConverter; private Converter<ExternalAccountMaintainData, ExternalAccountMaintainRequest> externalAccMaintaintRequestDataConverter; private Converter<ExternalAccountOperationResponse, ExternalAccountOperationResponseData> externalAccMaintaintResponseDataConverter; private Converter<MaintainMappingTableRequestData, MaintainMappingTableRowRequest> mappingTableRowMaintainRequestDataConverter; private Converter<MappingTableRowOperationResponse, MappingTableOperationResponseData> mappingTableRowMaintainResponseDataConverter; private Converter<MaintainMappingTableRequestData, MaintainMappingTableRequest> maintainMappingTableRequestDataConverter; private Converter<MappingTableOperationResponse, MappingTableOperationResponseData> maintainMappingTableResponseDataConverter; private Converter<MaintainChargingContractRequestData, MaintainChargingContractRequest> contractProvisioningRequestConverter; private Converter<ContractOperationResponse, ContractOperationResponseData> contractProvisioningResponseConverter; private Converter<ChargeableItemChargeRequestData, ChargeableItemChargeRequest> itemChargingRequestConverter; private Converter<ChargeableItemChargeResponse, ChargeableItemChargeResponseData> itemChargingResponseConverter; /** * @return the mappingTableRowMaintainRequestDataConverter */ public Converter<MaintainMappingTableRequestData, MaintainMappingTableRowRequest> getMappingTableRowMaintainRequestDataConverter() { return mappingTableRowMaintainRequestDataConverter; } /** * @param mappingTableRowMaintainRequestDataConverter * the mappingTableRowMaintainRequestDataConverter to set */ public void setMappingTableRowMaintainRequestDataConverter( final Converter<MaintainMappingTableRequestData, MaintainMappingTableRowRequest> mappingTableRowMaintainRequestDataConverter) { this.mappingTableRowMaintainRequestDataConverter = mappingTableRowMaintainRequestDataConverter; } /** * @return the mappingTableRowMaintainResponseDataConverter */ public Converter<MappingTableRowOperationResponse, MappingTableOperationResponseData> getMappingTableRowMaintainResponseDataConverter() { return mappingTableRowMaintainResponseDataConverter; } /** * @param mappingTableRowMaintainResponseDataConverter * the mappingTableRowMaintainResponseDataConverter to set */ public void setMappingTableRowMaintainResponseDataConverter( final Converter<MappingTableRowOperationResponse, MappingTableOperationResponseData> mappingTableRowMaintainResponseDataConverter) { this.mappingTableRowMaintainResponseDataConverter = mappingTableRowMaintainResponseDataConverter; } /** * @return the sapWebServicesFactory */ public SAPWebServicesFactory getSapWebServicesFactory() { return sapWebServicesFactory; } /** * @param sapWebServicesFactory * the sapWebServicesFactory to set */ public void setSapWebServicesFactory(final SAPWebServicesFactory sapWebServicesFactory) { this.sapWebServicesFactory = sapWebServicesFactory; } /** * @return the subscriberAccMaintaintRequestDataConverter */ public Converter<SubscriberAccountMaintainData, SubscriberAccountMaintainRequest> getSubscriberAccMaintaintRequestDataConverter() { return subscriberAccMaintaintRequestDataConverter; } /** * @param subscriberAccMaintaintRequestDataConverter * the subscriberAccMaintaintRequestDataConverter to set */ public void setSubscriberAccMaintaintRequestDataConverter( final Converter<SubscriberAccountMaintainData, SubscriberAccountMaintainRequest> subscriberAccMaintaintRequestDataConverter) { this.subscriberAccMaintaintRequestDataConverter = subscriberAccMaintaintRequestDataConverter; } /** * @return the subscriberAccMaintaintResponseDataConverter */ public Converter<SubscriberAccountOperationResponse, SubscriberAccountOperationResponseData> getSubscriberAccMaintaintResponseDataConverter() { return subscriberAccMaintaintResponseDataConverter; } /** * @param subscriberAccMaintaintResponseDataConverter * the subscriberAccMaintaintResponseDataConverter to set */ public void setSubscriberAccMaintaintResponseDataConverter( final Converter<SubscriberAccountOperationResponse, SubscriberAccountOperationResponseData> subscriberAccMaintaintResponseDataConverter) { this.subscriberAccMaintaintResponseDataConverter = subscriberAccMaintaintResponseDataConverter; } /** * @return the externalAccMaintaintRequestDataConverter */ public Converter<ExternalAccountMaintainData, ExternalAccountMaintainRequest> getExternalAccMaintaintRequestDataConverter() { return externalAccMaintaintRequestDataConverter; } /** * @param externalAccMaintaintRequestDataConverter * the externalAccMaintaintRequestDataConverter to set */ public void setExternalAccMaintaintRequestDataConverter( final Converter<ExternalAccountMaintainData, ExternalAccountMaintainRequest> externalAccMaintaintRequestDataConverter) { this.externalAccMaintaintRequestDataConverter = externalAccMaintaintRequestDataConverter; } /** * @return the externalAccMaintaintResponseDataConverter */ public Converter<ExternalAccountOperationResponse, ExternalAccountOperationResponseData> getExternalAccMaintaintResponseDataConverter() { return externalAccMaintaintResponseDataConverter; } /** * @param externalAccMaintaintResponseDataConverter * the externalAccMaintaintResponseDataConverter to set */ public void setExternalAccMaintaintResponseDataConverter( final Converter<ExternalAccountOperationResponse, ExternalAccountOperationResponseData> externalAccMaintaintResponseDataConverter) { this.externalAccMaintaintResponseDataConverter = externalAccMaintaintResponseDataConverter; } @Override public SubscriberAccountOperationResponseData subscribeAccMaintain(final SubscriberAccountMaintainData request) { SubscriberAccountOperationResponseData subscriberAccountOperationResponseData = null; try { LOG.info("Creating Subscriber Account"); final SubscriberAccountMaintainRequest subAccMaintainRequest = getSubscriberAccMaintaintRequestDataConverter() .convert(request); final SubscriberAccMaintainRequestProcessor processor = getSapWebServicesFactory() .createSAPWebService(SubscriberAccMaintainRequestProcessor.class); final SubscriberAccountOperationResponse subAccOpResponse = processor.processRequest(subAccMaintainRequest); subscriberAccountOperationResponseData = getSubscriberAccMaintaintResponseDataConverter().convert(subAccOpResponse); if (!ResponseStatus.ERROR.equals(subscriberAccountOperationResponseData.getStatus())) { LOG.info("Subscriber Account Created Successfully So Creating External Account "); final ExternalAccountMaintainData externalAccountMaintainData = new ExternalAccountMaintainData(); final ExternalAccount externalAccount = new ExternalAccount(); externalAccount.setCurrencyCode(request.getSubscriberAccount().getCurrencyCode()); externalAccount.setDescription(request.getSubscriberAccount().getDescription()); externalAccount.setId(request.getSubscriberAccount().getId()); externalAccount.setSubscriberAccountId(request.getSubscriberAccount().getId()); externalAccountMaintainData.setExternalAccount(externalAccount); final ExternalAccountOperationResponseData externalAccountOperationResponseDate = externalAccMaintain( externalAccountMaintainData); if (ResponseStatus.ERROR.equals(externalAccountOperationResponseDate.getStatus())) { LOG.info("Creating External Account Failed So Canceling Subscriber Account"); subscriberAccountOperationResponseData.setStatus(externalAccountOperationResponseDate.getStatus()); // Cancel Subscriber Account final com.cnk.travelogix.sapintegrations.subscribe.account.data.SubscriberAccountCancelRequest subscriberAccountCancelRequestData = new com.cnk.travelogix.sapintegrations.subscribe.account.data.SubscriberAccountCancelRequest(); subscriberAccountCancelRequestData .setSubscriberAccountId(subscriberAccountOperationResponseData.getSubscriberAccountId()); final SubscriberAccountOperationResponseData cancelResponse = canceSubscriberAccount( subscriberAccountCancelRequestData); if (ResponseStatus.ERROR.equals(cancelResponse.getStatus())) { subscriberAccountOperationResponseData.setStatus(cancelResponse.getStatus()); } } } } catch (final Exception e) { LOG.error(e.getMessage(), e); } return subscriberAccountOperationResponseData; } @Override public SubscriberAccountOperationResponseData canceSubscriberAccount( final com.cnk.travelogix.sapintegrations.subscribe.account.data.SubscriberAccountCancelRequest cancelRequestData) { SubscriberAccountOperationResponse cancelResponse = null; try { final SubscriberAccountCancelRequest cancelRequest = new SubscriberAccountCancelRequest(); cancelRequest.setSubscriberAccountId(cancelRequestData.getSubscriberAccountId()); final SubscriberAccountCancelProcessor processor = getSapWebServicesFactory() .createSAPWebService(SubscriberAccountCancelProcessor.class); cancelResponse = processor.processRequest(cancelRequest); return getSubscriberAccMaintaintResponseDataConverter().convert(cancelResponse); } catch (final ServiceNotSupportedException e) { LOG.error(e.getMessage(), e); } return null; } public ExternalAccountOperationResponseData externalAccMaintain(final ExternalAccountMaintainData request) { try { final ExternalAccountMaintainRequest extAccMaintainRequest = getExternalAccMaintaintRequestDataConverter() .convert(request); final ExternalAccMaintainRequestProcessor processor = getSapWebServicesFactory() .createSAPWebService(ExternalAccMaintainRequestProcessor.class); final ExternalAccountOperationResponse extAccOpResponse = processor.processRequest(extAccMaintainRequest); return getExternalAccMaintaintResponseDataConverter().convert(extAccOpResponse); } catch (final Exception e) { LOG.error(e.getMessage(), e); } return null; } /** * This method is called to Create Table & Insert records. * * Send * */ @Override public MappingTableOperationResponseData createMappingTableMaintain(final MaintainMappingTableRequestData request) { try { final MaintainMappingTableRequest maintainMappingTableRequest = getMaintainMappingTableRequestDataConverter() .convert(request); final String operation = request.getOperation(); if ("CREATE_INSERT".equalsIgnoreCase(operation)) { final MaintainMappingTableRequestProcessor processor = getSapWebServicesFactory() .createSAPWebService(MaintainMappingTableRequestProcessor.class); final MappingTableOperationResponse response = processor.processRequest(maintainMappingTableRequest); return getMaintainMappingTableResponseDataConverter().convert(response); } else if ("INSERT_UPDATE".equalsIgnoreCase(operation)) { final MaintainMappingTableRowRequest mapTbleRowRequest = getMappingTableRowMaintainRequestDataConverter() .convert(request); final MappingTableRowMaintainRequestProcessor processor = getSapWebServicesFactory() .createSAPWebService(MappingTableRowMaintainRequestProcessor.class); final MappingTableRowOperationResponse response = processor.processRequest(mapTbleRowRequest); return getMappingTableRowMaintainResponseDataConverter().convert(response); } } catch (final Exception e) { LOG.error(e.getMessage(), e); } return null; } @Override public ContractOperationResponseData contractProvisioning(final MaintainChargingContractRequestData request) { try { final MaintainChargingContractRequest contractRequest = getContractProvisioningRequestConverter().convert(request); final ContractProvisioningProcessor processor = getSapWebServicesFactory() .createSAPWebService(ContractProvisioningProcessor.class); final ContractOperationResponse response = processor.processRequest(contractRequest); return getContractProvisioningResponseConverter().convert(response); } catch (final Exception e) { LOG.error(e.getMessage(), e); } return null; } /** * @return the maintainMappingTableRequestDataConverter */ public Converter<MaintainMappingTableRequestData, MaintainMappingTableRequest> getMaintainMappingTableRequestDataConverter() { return maintainMappingTableRequestDataConverter; } /** * @param maintainMappingTableRequestDataConverter * the maintainMappingTableRequestDataConverter to set */ public void setMaintainMappingTableRequestDataConverter( final Converter<MaintainMappingTableRequestData, MaintainMappingTableRequest> maintainMappingTableRequestDataConverter) { this.maintainMappingTableRequestDataConverter = maintainMappingTableRequestDataConverter; } /** * @return the maintainMappingTableResponseDataConverter */ public Converter<MappingTableOperationResponse, MappingTableOperationResponseData> getMaintainMappingTableResponseDataConverter() { return maintainMappingTableResponseDataConverter; } /** * @param maintainMappingTableResponseDataConverter * the maintainMappingTableResponseDataConverter to set */ public void setMaintainMappingTableResponseDataConverter( final Converter<MappingTableOperationResponse, MappingTableOperationResponseData> maintainMappingTableResponseDataConverter) { this.maintainMappingTableResponseDataConverter = maintainMappingTableResponseDataConverter; } /** * @return the contractProvisioningResponseConverter */ public Converter<ContractOperationResponse, ContractOperationResponseData> getContractProvisioningResponseConverter() { return contractProvisioningResponseConverter; } /** * @param contractProvisioningResponseConverter * the contractProvisioningResponseConverter to set */ public void setContractProvisioningResponseConverter( final Converter<ContractOperationResponse, ContractOperationResponseData> contractProvisioningResponseConverter) { this.contractProvisioningResponseConverter = contractProvisioningResponseConverter; } /** * @return the contractProvisioningRequestConverter */ public Converter<MaintainChargingContractRequestData, MaintainChargingContractRequest> getContractProvisioningRequestConverter() { return contractProvisioningRequestConverter; } /** * @param contractProvisioningRequestConverter * the contractProvisioningRequestConverter to set */ public void setContractProvisioningRequestConverter( final Converter<MaintainChargingContractRequestData, MaintainChargingContractRequest> contractProvisioningRequestConverter) { this.contractProvisioningRequestConverter = contractProvisioningRequestConverter; } /** * @return the itemChargingRequestConverter */ public Converter<ChargeableItemChargeRequestData, ChargeableItemChargeRequest> getItemChargingRequestConverter() { return itemChargingRequestConverter; } /** * @param itemChargingRequestConverter * the itemChargingRequestConverter to set */ public void setItemChargingRequestConverter( final Converter<ChargeableItemChargeRequestData, ChargeableItemChargeRequest> itemChargingRequestConverter) { this.itemChargingRequestConverter = itemChargingRequestConverter; } /** * @return the itemChargingResponseConverter */ public Converter<ChargeableItemChargeResponse, ChargeableItemChargeResponseData> getItemChargingResponseConverter() { return itemChargingResponseConverter; } /** * @param itemChargingResponseConverter * the itemChargingResponseConverter to set */ public void setItemChargingResponseConverter( final Converter<ChargeableItemChargeResponse, ChargeableItemChargeResponseData> itemChargingResponseConverter) { this.itemChargingResponseConverter = itemChargingResponseConverter; } @Override public ChargeableItemChargeResponseData itemCharging(final ChargeableItemChargeRequestData request) { try { final ChargeableItemChargeRequest requestData = getItemChargingRequestConverter().convert(request); final ItemChargingProcessor itemChargingProcessor = getSapWebServicesFactory() .createSAPWebService(ItemChargingProcessor.class); final ChargeableItemChargeResponse itemChargeResponse = itemChargingProcessor.processRequest(requestData); return getItemChargingResponseConverter().convert(itemChargeResponse); } catch (final Exception e) { LOG.error(e); } return null; } }
package com.james; import com.james.controller.ProductdatailsController; import com.james.controller.VehicleController; import com.james.pojo.Vehicle; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration public class testVehicle { @Resource private VehicleController vehicleController; @Resource private ProductdatailsController productdatailsController; @Test public void sqwe(){ //全部商品 List<Vehicle> add = vehicleController.add(); System.out.println(add); } //商品详情 @Test public void stes(){ String aa="宝马7系"; System.out.println(productdatailsController.product(aa)); } //新增商品 @Test public void stes1(){ } }
/* * 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 com.luv2code.springdemo; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * * @author obarretopalacio */ public class AnnotationBeanScopeDemoApp { /** * @param args the command line arguments */ public static void main(String[] args) { // read spring config file ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //retrieve bean from spring container Coach alphaCoach = context.getBean("tennisCoach", Coach.class); Coach theCoach = context.getBean("tennisCoach", Coach.class); //verify is same object boolean result = (alphaCoach == theCoach); System.out.println("Pointing to the same objects: "+ result); System.out.println("Memory location fot the thecoach: "+ theCoach); System.out.println("Memory location fot the alphacoach: "+ alphaCoach); //close the context context.close(); } }
package org.alienideology.jcord.internal.gateway; /** * OPCode - OP Code sent by Discord GateWay server. * @author AlienIdeology */ public enum OPCode { DISPATCH (0), HEARTBEAT (1), IDENTIFY (2), STATUS_UPDATE (3), VOICE_STATE_UPDATE (4), VOICE_SERVER_PING (5), RESUME (6), RECONNECT (7), REQUEST_GUILD_MEMBERS (8), INVALID_SESSION (9), HELLO (10), HEARTBEAT_ACK (11), GUILD_SYNC (12), UNKNOWN (-1); public int key; OPCode(int key) { this.key = key; } public static OPCode getByKey(int key) { for (OPCode op : values()) { if (op.key == key) return op; } return UNKNOWN; } }
package com.rsm.yuri.projecttaxilivre.map.models; /** * Created by yuri_ on 03/02/2018. */ public class GroupAreas { private Area mainArea, areaVerticalSide, areaHorizontalSide, areaDiagonal; public Area getMainArea() { return mainArea; } public void setMainArea(Area mainArea) { this.mainArea = mainArea; } public Area getAreaVerticalSide() { return areaVerticalSide; } public void setAreaVerticalSide(Area areaVerticalSide) { this.areaVerticalSide = areaVerticalSide; } public Area getAreaHorizontalSide() { return areaHorizontalSide; } public void setAreaHorizontalSide(Area areaHorizontalSide) { this.areaHorizontalSide = areaHorizontalSide; } public Area getAreaDiagonal() { return areaDiagonal; } public void setAreaDiagonal(Area areaDiagonal) { this.areaDiagonal = areaDiagonal; } }
package vc.lang.types; import vc.lang.impl.EvaluationContext; import vc.lang.runtime.ExecException; public abstract class Token { public abstract void eval(EvaluationContext context) throws ExecException; public abstract boolean sameValue(Token other); public abstract byte[] getSymbol(); public final boolean sameType(Token other) { return getClass() == other.getClass(); } }
package day01; public class SystemOut { public static void main(String[] args) { /* * 코드실행 단축키 - Ctrl + f11 * sysout이라고 적고 Ctrl + space를 누르면 println() 이 자동 생성됩니다. * 되돌리기 Ctrl + z * 정렬 Ctrl + a, Ctrl + i * 코드를 옮길때 alt + 방향키 * 이름을 동시에 변경하고 싶을때 alt + shift + r * */ //1. 개행(줄바꿈)을 포함하는 println() System.out.println("안녕하세요"); System.out.println("반가워요"); //2. 개행(줄바꿈)이 없는 print() System.out.print("줄바꿈이 없음..."); System.out.print("코드를 가로로 출력할 때 사용합니다\n"); /* * \n 줄바꿈 * \t 8칸 탭 정렬 * %s 문자열을 입력받음 * %d 정수를 입력받음 * %f 실수를 입력받음 * %c 문자를 입력받음 */ //3. 형식지정 출력문 printf() System.out.printf("안녕하세요. 제 이름은 %s 이고 오늘 날짜는 %d월 %d일 입니다\n","홍길동",8,20); System.out.printf("파이값은 %.2" + "f 입니다",3.14); } }
package biblioteca.negocio.dao; import java.util.ArrayList; import biblioteca.negocio.basica.Autor; public interface AutorDAO { /** * Insere um registro no BD * @param a Objeto contendo todos os dados * @throws ConexaoException * @throws DAOException */ public void incluir(Autor a)throws ConexaoException,DAOException; /** * Apaga um registro da tabela produto * @param id Identificacao (PK) do registro * @throws ConexaoException * @throws DAOException */ public void excluirAutor(Integer id)throws ConexaoException,DAOException; /** * Atualiza TODOS os campos de um registro * @param a Obejto contendo todos os campos * @throws ConexaoException * @throws DAOException */ public void alterarAutor(Autor a)throws ConexaoException,DAOException; /** * Lista todos os registros da tabela produto * @return um ArrayList com todos os dados * @throws ConexaoException * @throws DAOException */ public ArrayList<Autor> listar()throws ConexaoException,DAOException; /** * Retorna o objeto com os dados da tabela * @param id Chave primaria * @return * @throws ConexaoException * @throws DAOException */ public Autor get(Integer id)throws ConexaoException,DAOException; /** * Faz uma busca pelo valor dogitado no campo NOME * @param nome Texto contendo o nome a ser procurado * @return * @throws ConexaoException * @throws DAOException */ public Autor consultar(String nome)throws ConexaoException,DAOException; public ArrayList pesquisaTabelaAutor(String nome) throws ConexaoException, DAOException; public ArrayList listarTabelaAutor() throws ConexaoException, DAOException; }
package Tickets; /** * Enumeration for the number of bits of a system * @author Andress Alkhawand - Hubert Whan Tong * */ public enum Bits { THIRTY_TWO(32), SIXTY_FOUR(64); private int bits; //associates the bit number with the enum //for easier conversion when needed: //ex: SIXTY_FOUR.getBits() returns 64. /** * Constructor provided so that each enum has * an underlying integer with the bits * @param bits The integer version of the bits enum value */ Bits(int bits) { this.bits = bits; } /** * Gets the associated integer version of the bits * @return The integer bit value (so 32 instead of THIRTY_TWO) */ int getBits() { return bits; } /** * Returns a version of the enum that can be used * for nicer printing. * @return a A string with a version of the enum that can be used * for nicer printing */ @Override public String toString() { return ("" + bits); } }
package codewarsestd; public class ZeroTrueOrFalse { //https://www.codewars.com/kata/is-it-negative-zero-0/train/java public static boolean isNegativeZero(float n) { if (new Float(n).equals(-0.0f)) { return true; } else { return false; } } public static void main(String[] args) { System.out.println(isNegativeZero(-0f)); System.out.println(isNegativeZero(-5f)); System.out.println(isNegativeZero(-4f)); System.out.println(isNegativeZero(-3f)); System.out.println(isNegativeZero(-2f)); System.out.println(isNegativeZero(-1f)); System.out.println(isNegativeZero(0f)); System.out.println(isNegativeZero(1f)); System.out.println(isNegativeZero(2f)); System.out.println(isNegativeZero(3f)); System.out.println(isNegativeZero(4f)); System.out.println(isNegativeZero(5f)); } }
package com.stem.entity; import java.util.ArrayList; import java.util.List; public class TigerPayExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public TigerPayExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andOpenidIsNull() { addCriterion("openid is null"); return (Criteria) this; } public Criteria andOpenidIsNotNull() { addCriterion("openid is not null"); return (Criteria) this; } public Criteria andOpenidEqualTo(String value) { addCriterion("openid =", value, "openid"); return (Criteria) this; } public Criteria andOpenidNotEqualTo(String value) { addCriterion("openid <>", value, "openid"); return (Criteria) this; } public Criteria andOpenidGreaterThan(String value) { addCriterion("openid >", value, "openid"); return (Criteria) this; } public Criteria andOpenidGreaterThanOrEqualTo(String value) { addCriterion("openid >=", value, "openid"); return (Criteria) this; } public Criteria andOpenidLessThan(String value) { addCriterion("openid <", value, "openid"); return (Criteria) this; } public Criteria andOpenidLessThanOrEqualTo(String value) { addCriterion("openid <=", value, "openid"); return (Criteria) this; } public Criteria andOpenidLike(String value) { addCriterion("openid like", value, "openid"); return (Criteria) this; } public Criteria andOpenidNotLike(String value) { addCriterion("openid not like", value, "openid"); return (Criteria) this; } public Criteria andOpenidIn(List<String> values) { addCriterion("openid in", values, "openid"); return (Criteria) this; } public Criteria andOpenidNotIn(List<String> values) { addCriterion("openid not in", values, "openid"); return (Criteria) this; } public Criteria andOpenidBetween(String value1, String value2) { addCriterion("openid between", value1, value2, "openid"); return (Criteria) this; } public Criteria andOpenidNotBetween(String value1, String value2) { addCriterion("openid not between", value1, value2, "openid"); return (Criteria) this; } public Criteria andTradeIdIsNull() { addCriterion("trade_id is null"); return (Criteria) this; } public Criteria andTradeIdIsNotNull() { addCriterion("trade_id is not null"); return (Criteria) this; } public Criteria andTradeIdEqualTo(String value) { addCriterion("trade_id =", value, "tradeId"); return (Criteria) this; } public Criteria andTradeIdNotEqualTo(String value) { addCriterion("trade_id <>", value, "tradeId"); return (Criteria) this; } public Criteria andTradeIdGreaterThan(String value) { addCriterion("trade_id >", value, "tradeId"); return (Criteria) this; } public Criteria andTradeIdGreaterThanOrEqualTo(String value) { addCriterion("trade_id >=", value, "tradeId"); return (Criteria) this; } public Criteria andTradeIdLessThan(String value) { addCriterion("trade_id <", value, "tradeId"); return (Criteria) this; } public Criteria andTradeIdLessThanOrEqualTo(String value) { addCriterion("trade_id <=", value, "tradeId"); return (Criteria) this; } public Criteria andTradeIdLike(String value) { addCriterion("trade_id like", value, "tradeId"); return (Criteria) this; } public Criteria andTradeIdNotLike(String value) { addCriterion("trade_id not like", value, "tradeId"); return (Criteria) this; } public Criteria andTradeIdIn(List<String> values) { addCriterion("trade_id in", values, "tradeId"); return (Criteria) this; } public Criteria andTradeIdNotIn(List<String> values) { addCriterion("trade_id not in", values, "tradeId"); return (Criteria) this; } public Criteria andTradeIdBetween(String value1, String value2) { addCriterion("trade_id between", value1, value2, "tradeId"); return (Criteria) this; } public Criteria andTradeIdNotBetween(String value1, String value2) { addCriterion("trade_id not between", value1, value2, "tradeId"); return (Criteria) this; } public Criteria andPayStatusIsNull() { addCriterion("pay_status is null"); return (Criteria) this; } public Criteria andPayStatusIsNotNull() { addCriterion("pay_status is not null"); return (Criteria) this; } public Criteria andPayStatusEqualTo(Integer value) { addCriterion("pay_status =", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusNotEqualTo(Integer value) { addCriterion("pay_status <>", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusGreaterThan(Integer value) { addCriterion("pay_status >", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusGreaterThanOrEqualTo(Integer value) { addCriterion("pay_status >=", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusLessThan(Integer value) { addCriterion("pay_status <", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusLessThanOrEqualTo(Integer value) { addCriterion("pay_status <=", value, "payStatus"); return (Criteria) this; } public Criteria andPayStatusIn(List<Integer> values) { addCriterion("pay_status in", values, "payStatus"); return (Criteria) this; } public Criteria andPayStatusNotIn(List<Integer> values) { addCriterion("pay_status not in", values, "payStatus"); return (Criteria) this; } public Criteria andPayStatusBetween(Integer value1, Integer value2) { addCriterion("pay_status between", value1, value2, "payStatus"); return (Criteria) this; } public Criteria andPayStatusNotBetween(Integer value1, Integer value2) { addCriterion("pay_status not between", value1, value2, "payStatus"); return (Criteria) this; } public Criteria andPayMoneyIsNull() { addCriterion("pay_money is null"); return (Criteria) this; } public Criteria andPayMoneyIsNotNull() { addCriterion("pay_money is not null"); return (Criteria) this; } public Criteria andPayMoneyEqualTo(Integer value) { addCriterion("pay_money =", value, "payMoney"); return (Criteria) this; } public Criteria andPayMoneyNotEqualTo(Integer value) { addCriterion("pay_money <>", value, "payMoney"); return (Criteria) this; } public Criteria andPayMoneyGreaterThan(Integer value) { addCriterion("pay_money >", value, "payMoney"); return (Criteria) this; } public Criteria andPayMoneyGreaterThanOrEqualTo(Integer value) { addCriterion("pay_money >=", value, "payMoney"); return (Criteria) this; } public Criteria andPayMoneyLessThan(Integer value) { addCriterion("pay_money <", value, "payMoney"); return (Criteria) this; } public Criteria andPayMoneyLessThanOrEqualTo(Integer value) { addCriterion("pay_money <=", value, "payMoney"); return (Criteria) this; } public Criteria andPayMoneyIn(List<Integer> values) { addCriterion("pay_money in", values, "payMoney"); return (Criteria) this; } public Criteria andPayMoneyNotIn(List<Integer> values) { addCriterion("pay_money not in", values, "payMoney"); return (Criteria) this; } public Criteria andPayMoneyBetween(Integer value1, Integer value2) { addCriterion("pay_money between", value1, value2, "payMoney"); return (Criteria) this; } public Criteria andPayMoneyNotBetween(Integer value1, Integer value2) { addCriterion("pay_money not between", value1, value2, "payMoney"); return (Criteria) this; } public Criteria andPayTimeIsNull() { addCriterion("pay_time is null"); return (Criteria) this; } public Criteria andPayTimeIsNotNull() { addCriterion("pay_time is not null"); return (Criteria) this; } public Criteria andPayTimeEqualTo(String value) { addCriterion("pay_time =", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeNotEqualTo(String value) { addCriterion("pay_time <>", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeGreaterThan(String value) { addCriterion("pay_time >", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeGreaterThanOrEqualTo(String value) { addCriterion("pay_time >=", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeLessThan(String value) { addCriterion("pay_time <", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeLessThanOrEqualTo(String value) { addCriterion("pay_time <=", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeLike(String value) { addCriterion("pay_time like", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeNotLike(String value) { addCriterion("pay_time not like", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeIn(List<String> values) { addCriterion("pay_time in", values, "payTime"); return (Criteria) this; } public Criteria andPayTimeNotIn(List<String> values) { addCriterion("pay_time not in", values, "payTime"); return (Criteria) this; } public Criteria andPayTimeBetween(String value1, String value2) { addCriterion("pay_time between", value1, value2, "payTime"); return (Criteria) this; } public Criteria andPayTimeNotBetween(String value1, String value2) { addCriterion("pay_time not between", value1, value2, "payTime"); return (Criteria) this; } public Criteria andProductNameIsNull() { addCriterion("product_name is null"); return (Criteria) this; } public Criteria andProductNameIsNotNull() { addCriterion("product_name is not null"); return (Criteria) this; } public Criteria andProductNameEqualTo(String value) { addCriterion("product_name =", value, "productName"); return (Criteria) this; } public Criteria andProductNameNotEqualTo(String value) { addCriterion("product_name <>", value, "productName"); return (Criteria) this; } public Criteria andProductNameGreaterThan(String value) { addCriterion("product_name >", value, "productName"); return (Criteria) this; } public Criteria andProductNameGreaterThanOrEqualTo(String value) { addCriterion("product_name >=", value, "productName"); return (Criteria) this; } public Criteria andProductNameLessThan(String value) { addCriterion("product_name <", value, "productName"); return (Criteria) this; } public Criteria andProductNameLessThanOrEqualTo(String value) { addCriterion("product_name <=", value, "productName"); return (Criteria) this; } public Criteria andProductNameLike(String value) { addCriterion("product_name like", value, "productName"); return (Criteria) this; } public Criteria andProductNameNotLike(String value) { addCriterion("product_name not like", value, "productName"); return (Criteria) this; } public Criteria andProductNameIn(List<String> values) { addCriterion("product_name in", values, "productName"); return (Criteria) this; } public Criteria andProductNameNotIn(List<String> values) { addCriterion("product_name not in", values, "productName"); return (Criteria) this; } public Criteria andProductNameBetween(String value1, String value2) { addCriterion("product_name between", value1, value2, "productName"); return (Criteria) this; } public Criteria andProductNameNotBetween(String value1, String value2) { addCriterion("product_name not between", value1, value2, "productName"); return (Criteria) this; } public Criteria andOrderIdIsNull() { addCriterion("order_id is null"); return (Criteria) this; } public Criteria andOrderIdIsNotNull() { addCriterion("order_id is not null"); return (Criteria) this; } public Criteria andOrderIdEqualTo(String value) { addCriterion("order_id =", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdNotEqualTo(String value) { addCriterion("order_id <>", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdGreaterThan(String value) { addCriterion("order_id >", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdGreaterThanOrEqualTo(String value) { addCriterion("order_id >=", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdLessThan(String value) { addCriterion("order_id <", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdLessThanOrEqualTo(String value) { addCriterion("order_id <=", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdLike(String value) { addCriterion("order_id like", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdNotLike(String value) { addCriterion("order_id not like", value, "orderId"); return (Criteria) this; } public Criteria andOrderIdIn(List<String> values) { addCriterion("order_id in", values, "orderId"); return (Criteria) this; } public Criteria andOrderIdNotIn(List<String> values) { addCriterion("order_id not in", values, "orderId"); return (Criteria) this; } public Criteria andOrderIdBetween(String value1, String value2) { addCriterion("order_id between", value1, value2, "orderId"); return (Criteria) this; } public Criteria andOrderIdNotBetween(String value1, String value2) { addCriterion("order_id not between", value1, value2, "orderId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.core.woucampus.woucampus; /** * Original content from: * George Mathew * http://wptrafficanalyzer.in/blog/route-between-two-locations-with-waypoints-in-google-map-android-api-v2/ * */ public interface Parser { public Route parse(); }
package com.raremile.taglib.common; /** * Interface that defines all the constants used by the application * @author akshyap * */ public interface CommonConstants { public static final String DB_NAME = "dbName"; public static final String DB_HOST = "host"; public static final String DB_PORT = "port"; public static final String DB_USER= "user"; public static final String DB_PASSWORD = "password"; public static final String NAME= "akshay"; }
package com.fundwit.sys.shikra.database; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; @Service public class MysqlDatabaseManagerImpl implements DatabaseManager{ private static final String KEY_DEFAULT_CREATE_DATABASE_STATEMENT = "DEFAULT_CREATE_DATABASE_STATEMENT"; private static final String KEY_DEFAULT_CREATE_USER_STATEMENT = "DEFAULT_CREATE_USER_STATEMENT"; private static final String KEY_DEFAULT_GRANT_STATEMENT= "DEFAULT_GRANT_STATEMENT"; private static final Map<String, String> sqlMap; static { sqlMap = new HashMap<>(); sqlMap.put(KEY_DEFAULT_CREATE_DATABASE_STATEMENT+"_MYSQL", "CREATE SCHEMA IF NOT EXISTS %s DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"); sqlMap.put(KEY_DEFAULT_CREATE_USER_STATEMENT+"_MYSQL", "CREATE USER IF NOT EXISTS '%s'@'%%' IDENTIFIED BY '%s';"); sqlMap.put(KEY_DEFAULT_GRANT_STATEMENT+"_MYSQL", "GRANT ALL ON %s.* TO '%s'@'%%'; FLUSH PRIVILEGES;"); sqlMap.put(KEY_DEFAULT_CREATE_DATABASE_STATEMENT+"_H2", "CREATE SCHEMA IF NOT EXISTS %s ;"); sqlMap.put(KEY_DEFAULT_CREATE_USER_STATEMENT+"_H2", "CREATE USER IF NOT EXISTS %s PASSWORD '%s';"); sqlMap.put(KEY_DEFAULT_GRANT_STATEMENT+"_H2", "GRANT ALL ON SCHEMA %s TO %s;"); } @Override public void initializeDatabase(DataSourceProperties properties) { String url = properties.getUrl(); String databaseName; String baseUrl; String jdbcBaseUrl; String databaseType = url.substring(5, url.indexOf(':',6)).toUpperCase(); if(url.startsWith("jdbc:mysql:")) { int idx1 = url.lastIndexOf("/"); int idx2 = url.indexOf("?"); if(idx2==-1){ idx2 = url.length(); } databaseName = url.substring(idx1+1, idx2); baseUrl = url.substring(0, idx1); String parameter = url.substring(idx2); // include ? prefix jdbcBaseUrl = baseUrl+"/"+parameter; } else if(url.startsWith("jdbc:h2:mem:")) { int idx1 = url.lastIndexOf(":"); int idx2 = url.indexOf(";"); if(idx2==-1) { idx2 = url.length(); } databaseName = url.substring(idx1+1, idx2); // baseUrl = url.substring(0, idx1); // String parameter = url.substring(idx2); // include ? prefix jdbcBaseUrl = url; }else{ throw new RuntimeException("not supported jdbc url: "+url); } Connection conn = null; try { String username = !StringUtils.isEmpty(properties.getSchemaUsername()) ? properties.getSchemaUsername() : properties.getUsername(); String password = !StringUtils.isEmpty(properties.getSchemaPassword()) ? properties.getSchemaPassword() : properties.getPassword(); DriverManager.setLoginTimeout(2); conn = DriverManager.getConnection(jdbcBaseUrl, username, password); if(conn == null) { throw new RuntimeException("failed to get database connection for initialize"); } this.execute(String.format(sqlMap.get(KEY_DEFAULT_CREATE_DATABASE_STATEMENT+"_"+databaseType), databaseName), conn); if(properties.getUsername()!=null && properties.getSchemaUsername()!=null && !properties.getUsername().equals(properties.getSchemaUsername())) { this.execute(String.format(sqlMap.get(KEY_DEFAULT_CREATE_USER_STATEMENT+"_"+databaseType), properties.getUsername(), properties.getPassword()), conn); this.execute(String.format(sqlMap.get(KEY_DEFAULT_GRANT_STATEMENT+"_"+databaseType), databaseName, properties.getUsername()), conn); } } catch (SQLException e) { throw new RuntimeException(e); }finally { try { if(conn!=null && !conn.isClosed()) { conn.close(); } } catch (SQLException e) { throw new RuntimeException(e); } } } // @Override // public void execute(String statement, DataSource dataSource) { // DatabaseUtils.execute(statement, dataSource); // } @Override public void execute(String statement, Connection dataSource) { DatabaseUtils.execute(statement, dataSource); } }
package com.goodhealth.provider.eurake.controller; public class ShutDown { public static void main(String[] args) { String url ="http://127.0.0.1:9090/shutdown"; //该url必须要使用dopost方式来发送 // HttpUtil.doPost(url); } }
package com.springboot.demo.service.Imp; import com.springboot.demo.dao.UserDao; import com.springboot.demo.entity.User; import com.springboot.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service(value = "userService") public class UserServiceImp implements UserService { @Resource private UserDao userDao; @Override public int save(User user) { return userDao.save(user); } @Override public User findById(int id) { return userDao.findById(id); } @Override public void deleteUserById(int id) { userDao.deleteUserById(id); } @Override public List<User> findAll() { return userDao.findAll(); } }
package ru.mrequ.core; public interface Condition<T> { boolean check(T t); }
import java.util.ArrayList; import java.util.Scanner; public class Kaup { private ArrayList<KaupVO> voList = new ArrayList<KaupVO>(); private Scanner scanner = new Scanner(System.in); private ArrayList<String> voKaupList = new ArrayList<String>(); public void doService(){ String cmd = "y"; float weight = 0.0f, height = 0.0f; do{ System.out.print("키를 입력해주세요 :"); height = scanner.nextFloat(); System.out.print("몸무게를 입력해주세요 :"); weight = scanner.nextFloat(); KaupVO vo = new KaupVO(); vo.setHeight(height); vo.setWeight(weight); voKaupList.add(vo.getKaup()); voList.add(vo); System.out.println("입력을 멈추시려면 n 을 눌러주세요 : "); cmd = scanner.next(); }while(!cmd.equalsIgnoreCase("n")); } public void listUserHeightAndWeight(){ System.out.println("---------------------------------"); System.out.println("\t\t리스트"); System.out.println("---------------------------------"); for(int i=0; i<voList.size(); i++){ KaupVO vo = voList.get(i); System.out.println("[" + (i+1) + "]번째 유저의 키와 몸무게.."); System.out.println("키 : " + vo.getHeight()); System.out.println("몸무게 : " + vo.getWeight()); System.out.println(); } System.out.println(); System.out.println(); listKaup(); } private void listKaup(){ System.out.println("------------------------------"); System.out.println("\t\tKAUP 지수입니다"); System.out.println("------------------------------"); for(int i=0; i<voList.size(); i++){ System.out.println((i+1) + "번 째 유저의 Kaup 지수.."); System.out.println(voKaupList.get(i)); System.out.println(); } } public static void main(String[] args) { Kaup kaup = new Kaup(); kaup.doService(); kaup.listUserHeightAndWeight(); System.out.println("프로그램을 종료합니당.."); } } class KaupVO{ private float height; private float weight; private int idx; private String msg; public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getKaup(){ setIdxAndMsg(); return "[키=" + getHeight() + "cm, 몸무게=" + getWeight() + "kg, 카우프지수=" + idx + ", scanner=" + getMsg() + "]"; } private void setIdxAndMsg(){ idx = (int)((weight / (height * height)) * 10000); if(idx > 30) msg = "비만"; else if (idx > 24) msg = "과체중"; else if (idx > 20) msg = "정상"; else if (idx > 15) msg = "저체중"; else if (idx > 13) msg = "마름"; else if (idx > 10) msg = "영양실조"; else msg = "소모증"; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } }
package MyFirstApp.Util; import MyFirstApp.AppMessages.Root; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository @Transactional public class RootDaoImpl implements RootDAO { @Autowired private SessionFactory sessionFactory; @Override @Transactional(readOnly = false) public void insertPerson(Root root) { Session session = sessionFactory.openSession(); session.save(root); } }
package org.kazminov.myttssample.org.kazminov.tts; import android.content.Context; import android.media.AudioManager; import android.os.Handler; import android.speech.tts.TextToSpeech; import android.speech.tts.UtteranceProgressListener; import android.support.annotation.MainThread; import android.util.Log; import android.widget.Toast; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Locale; /** * Created by olkazmin on 24.09.17. */ public class TTSPlayer { public static final String LOG_TAG = "TTSPlayer"; private final Context mContext; private Handler mHandler = new Handler(); private TextToSpeech mTTS; private final int STATE_DEFAULT = 0; private final int STATE_INITIALIZING = 1; private final int STATE_READY = 2; private final int STATE_PLAYING = 3; private final int STATE_ERROR = 4; private int mState = STATE_DEFAULT; private Deque<String> mQueue = new LinkedList<>(); private int mStreamType = AudioManager.STREAM_SYSTEM; private float mVolume = -1f; private TSSPlayerListener myListener; public interface TSSPlayerListener { void onUtterancePlaybackFinished(String utterance); void onError(); void onInitializing(); void onUtterancePlaybackStarted(String utterance); } public TTSPlayer(Context context) { mContext = context; } @MainThread public void play(String text) { log("play: state=%d, %s", mState, text); if (mState == STATE_ERROR) { onError(); return; } if (mState == STATE_DEFAULT) { mQueue.push(text); init(); return; } if (mState == STATE_INITIALIZING || mState == STATE_PLAYING) { mQueue.push(text); return; } mQueue.push(text); playNext(); } private void onError() { if (myListener != null) { myListener.onError(); } } public void setStreamType(int streamType) { this.mStreamType = streamType; } public void setVolume(float volume) { this.mVolume = volume; } private void init() { log("init"); setState(STATE_INITIALIZING); mTTS = new TextToSpeech(mContext, new TextToSpeech.OnInitListener() { @Override public void onInit(int i) { initLanguage(); } }); } private void initLanguage() { Locale locale = // Locale.ENGLISH Locale.getDefault() ; int result = mTTS.setLanguage(locale); //int result = mTTS.setLanguage(Locale.getDefault()); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Toast.makeText(mContext, "TTS is not supported for your language", Toast.LENGTH_SHORT).show(); mTTS.shutdown(); mTTS = null; setState(STATE_ERROR); return; } onInitFinished(); } private void onInitFinished() { log("onInitFinished"); setState(STATE_READY); playNext(); } private void playNext() { log("playNext: queue size=%d", mQueue.size()); if (mQueue.isEmpty()) { setState(STATE_READY); return; } setState(STATE_PLAYING); String utterance = mQueue.poll(); log("playNext: %s", utterance); /**TextToSpeech.Engine. * * KEY_PARAM_STREAM * KEY_PARAM_UTTERANCE_ID * KEY_PARAM_VOLUME * * * AudioManager * * STREAM_NOTIFICATION * STREAM_MUSIC */ mTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() { @Override public void onStart(final String s) { log("onStart: %s", s); onPlaybackStarted(s); } @Override public void onDone(final String s) { log("onDone: %s", s); mHandler.post(new Runnable() { @Override public void run() { onPlaybackFinished(s); playNext(); } }); } @Override public void onError(String s) { log("onError: %s", s); TTSPlayer.this.onError(); mHandler.post(new Runnable() { @Override public void run() { playNext(); } }); } }); HashMap<String, String> params = new HashMap(); params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utterance); if (mVolume != -1f) { params.put(TextToSpeech.Engine.KEY_PARAM_VOLUME, Float.toString(mVolume)); } if (mStreamType != -1) { params.put(TextToSpeech.Engine.KEY_PARAM_STREAM, Integer.toString(mStreamType)); } onInitializing(); mTTS.speak(utterance, TextToSpeech.QUEUE_FLUSH, params); } private void onPlaybackStarted(String utterance) { if (myListener != null) { myListener.onUtterancePlaybackStarted(utterance); } } private void onPlaybackFinished(String utterance) { if (myListener != null) { myListener.onUtterancePlaybackFinished(utterance); } } public void destroy() { log("destroy"); if (mTTS == null) { return; } mTTS.stop(); mTTS.shutdown(); mTTS = null; setState(STATE_DEFAULT); } private void setState(int state) { log("setState: current=%d, new=%d", mState, state); if (state == mState) { return; } mState = state; switch (mState) { case STATE_INITIALIZING: onInitializing(); break; case STATE_ERROR: onError(); break; } } private void onInitializing() { if (myListener != null) { myListener.onInitializing(); } } private void log(String message, Object... args) { Log.v(LOG_TAG, String.format(message, args)); } public void setMyListener(TSSPlayerListener myListener) { this.myListener = myListener; } }
package views; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import java.sql.ResultSet; import java.sql.SQLException; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Text; import models.Database; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; public class AddVoiture extends Dialog { protected boolean result; protected Shell shell; private String email; private Text modele; private Text immat; Combo comboMarques; /** * Create the dialog. * @param parent * @param style */ public AddVoiture(Shell parent, String email) { super(parent, SWT.DIALOG_TRIM); setText("Nouvelle voiture"); this.email = email; } /** * Open the dialog. * @return the result */ public boolean open() { createContents(); shell.open(); shell.layout(); Display display = getParent().getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return result; } /** * Create contents of the dialog. */ private void createContents() { shell = new Shell(getParent(), getStyle()); shell.setSize(179, 242); shell.setText(getText()); Label lblMarque = new Label(shell, SWT.NONE); lblMarque.setBounds(10, 10, 55, 15); lblMarque.setText("Marque :"); comboMarques = new Combo(shell, SWT.NONE); comboMarques.setBounds(10, 31, 150, 23); addMarques(); Label lblModle = new Label(shell, SWT.NONE); lblModle.setBounds(10, 60, 55, 15); lblModle.setText("Modèle :"); modele = new Text(shell, SWT.BORDER); modele.setBounds(10, 81, 150, 23); Label lblImmatriculation = new Label(shell, SWT.NONE); lblImmatriculation.setBounds(10, 110, 150, 15); lblImmatriculation.setText("Immatriculation :"); immat = new Text(shell, SWT.BORDER); immat.setBounds(10, 131, 150, 23); Button btnAjouter = new Button(shell, SWT.NONE); btnAjouter.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (comboMarques.getSelectionIndex() != -1) { Database.getInstance().addVoiture(immat.getText(), comboMarques.getText(), modele.getText(), email); result = true; shell.close(); } else { InfoDialog info = new InfoDialog(shell, "Vous devez sélectionner une marque"); info.open(); } } }); btnAjouter.setBounds(85, 172, 75, 25); btnAjouter.setText("Ajouter"); } private void addMarques() { ResultSet rs = Database.getInstance().getMarques(); try { while (rs.next()) { String a = rs.getString("marque"); comboMarques.add(a); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.maintain.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.BitmapDrawable; import android.util.AttributeSet; import android.widget.ImageView; import com.ifeiyang.bijia.R; public class BorderCircleImage extends ImageView { private Context mContext; private int mw; private int mh; private int a; private int r; private int bDefaultColor = 0xFFFFFFFF; private int bThickness; private int bOutColor; private int bInColor; public BorderCircleImage(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; setCustomAttributes(attrs); } private void setCustomAttributes(AttributeSet attrs) { TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.RoundedImageView); bThickness = a.getDimensionPixelSize(R.styleable.RoundedImageView_border_thickness, 0); bOutColor = a.getColor(R.styleable.RoundedImageView_border_outside_color, bDefaultColor); bInColor = a.getColor(R.styleable.RoundedImageView_border_inside_color, bDefaultColor); bThickness = 2; a.recycle(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { mw = w; mh = h; a = w < h ? w : h; r = a / 2; } @Override protected void onDraw(Canvas canvas) { Bitmap b = ((BitmapDrawable) getDrawable()).getBitmap(); if (b == null) { return; } drawBorder(canvas); drawBitmap(canvas, b); } private void drawBitmap(Canvas canvas, Bitmap b) { Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true); Bitmap circleImage = getCircleImage(bitmap); canvas.drawBitmap(circleImage, 0, 0, null); } private void drawBorder(Canvas canvas) { Paint paint = new Paint(); paint.setAntiAlias(true); paint.setFilterBitmap(true); paint.setDither(true); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(bThickness); paint.setColor(bOutColor); canvas.drawCircle(r, r, r - bThickness / 2, paint); paint.setColor(bInColor); canvas.drawCircle(r, r, r - bThickness * 3 / 2, paint); } private Bitmap getCircleImage(Bitmap bitmap) { Bitmap output = Bitmap.createBitmap(a, a, Config.ARGB_8888); Canvas canvas = new Canvas(output); canvas.drawARGB(0, 0, 0, 0); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setFilterBitmap(true); paint.setDither(true); bitmap = getCenterBitmap(bitmap); bitmap = Bitmap.createScaledBitmap(bitmap, a - bThickness * 2, a - bThickness * 2, true); canvas.drawCircle(r, r, r - bThickness * 2, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, 0 + bThickness * 2, 0 + bThickness * 2, paint); return output; } private Bitmap getCenterBitmap(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int abs = Math.abs((width - height) / 2); if (width > height) { return Bitmap.createBitmap(bitmap, abs, 0, height, height); } else if (width < height) { return Bitmap.createBitmap(bitmap, 0, abs, width, width); } else { return bitmap; } } }
package com.huhurezmarius.worldmap.repository; import com.huhurezmarius.worldmap.model.NamedZone; import com.huhurezmarius.worldmap.response.NamedZonesResponse; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface NamedZoneRepository extends JpaRepository<NamedZone, Long> { @Query("select new com.toptal.timezones.response.NamedZonesResponse(nz.id,nz.name,tz.zoneName,tz.gmt) from NamedZone nz\n" + "left join Timezone tz on nz.timezone.id=tz.id\n" + "where nz.user.id = :user_id") List<NamedZonesResponse> findByUserId(Long user_id); Optional<NamedZone> findByName(String name); Optional<NamedZone> findByNameAndUserId(String name,Long userId); }
package com.mundo.data; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; /** * SpringTest * * @author maodh * @since 02/05/2018 */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ApplicationTest.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) public class SpringTest { @Resource private ApplicationContext applicationContext; @Test public void spring() { Assert.assertNotNull(applicationContext); } }
package artbot.com.sistemainspector.adapter; import android.app.Activity; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import artbot.com.sistemainspector.R; import artbot.com.sistemainspector.model.Horas; import artbot.com.sistemainspector.model.Report; public class HorasAdapter extends RecyclerView.Adapter<HorasAdapter.HorasViewHolder>{ private ArrayList<Horas> reports2; private int resource2; private Activity activity; public HorasAdapter(ArrayList<Horas>reports2,int resource2,Activity activity){ this.reports2 = reports2; this.resource2 = resource2; this.activity = activity; } @NonNull @Override public HorasViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(resource2, viewGroup,false); return new HorasViewHolder(view); } @Override public void onBindViewHolder(@NonNull HorasViewHolder horasViewHolder, int i) { Horas horas = reports2.get(i); horasViewHolder.txtfecha.setText(horas.getFecha()); horasViewHolder.txtdesde.setText(horas.getDesde()); horasViewHolder.txthasta.setText(horas.getHasta()); } @Override public int getItemCount() { return reports2.size(); } public class HorasViewHolder extends RecyclerView.ViewHolder { private TextView txtfecha; private TextView txtdesde; private TextView txthasta; public HorasViewHolder(@NonNull View itemView) { super(itemView); txtfecha = (TextView) itemView.findViewById(R.id.text_fecha); txtdesde = (TextView) itemView.findViewById(R.id.text_desde); txthasta = (TextView) itemView.findViewById(R.id.text_hasta); } } }
package br.com.tomioka.vendashortalicas; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class VendasHortalicasApplication { public static void main(String[] args) { SpringApplication.run(VendasHortalicasApplication.class, args); } }
package q0437_binaryTree_Recursion; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class PathSum3 { /** 给定一个二叉树,它的每个结点都存放着一个整数值。 找出路径和等于给定数值的路径总数。 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。 示例: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 返回 3。和等于 8 的路径有: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11 */ public int pathSum(TreeNode root, int sum) { if(root == null) return 0; return paths(root, sum)+pathSum(root.left, sum)+pathSum(root.right, sum); } public int paths(TreeNode root, int sum){ if(root == null) return 0; int res = 0; if(root.val == sum){ res += 1; } // res += paths(root.left, sum-root.val); // res += paths(root.right, sum-root.val); if(root.left != null){ res += paths(root.left, sum-root.val); } if(root.right != null){ res += paths(root.right, sum-root.val); } return res; } }
package model.dao; import java.util.List; import model.entidades.Vendedor; public interface VendedorDao { void insertVendedor(Vendedor vendedor); void updateVendedor(Vendedor vendedor); void deletarVendedorPeloId(Integer id); Vendedor localizarVendedorPeloId(Integer id); List<Vendedor> listarTodosOsVendedores(); List<Vendedor> listarPorDepartamento(Integer departamentoId); }
package com.tencent.mm.ui.tools; import android.app.Activity; import android.os.IBinder; import android.os.Looper; import android.support.v4.app.FragmentActivity; import android.support.v4.view.m; import android.support.v4.view.m.e; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.w.a.d; import com.tencent.mm.w.a.g; import com.tencent.mm.w.a.j; import com.tencent.mm.w.a.k; import java.util.ArrayList; public class o { final String TAG; ag dvh; MenuItem iZG; private boolean uBA; public int uBB; private int uBC; a uBD; boolean uBq; public boolean uBr; private boolean uBs; private boolean uBt; boolean uBu; public e uBv; public b uBw; private com.tencent.mm.ui.tools.SearchViewNotRealTimeHelper.a uBx; private boolean uBy; private ArrayList<String> uBz; public interface a { void collapseActionView(); void czR(); } public interface b { void WW(); void WX(); void WY(); void WZ(); boolean pj(String str); void pk(String str); } public o() { this.uBq = false; this.uBr = false; this.uBs = false; this.uBt = true; this.uBu = true; this.iZG = null; this.dvh = new ag(Looper.getMainLooper()); this.uBv = null; this.uBy = true; this.uBB = k.app_empty_string; this.uBC = 0; this.uBy = true; this.uBq = false; this.TAG = "MicroMsg.SearchViewHelper-" + String.valueOf(System.currentTimeMillis()); } public o(byte b) { this.uBq = false; this.uBr = false; this.uBs = false; this.uBt = true; this.uBu = true; this.iZG = null; this.dvh = new ag(Looper.getMainLooper()); this.uBv = null; this.uBy = true; this.uBB = k.app_empty_string; this.uBC = 0; this.uBy = true; this.uBq = true; this.TAG = "MicroMsg.SearchViewHelper-" + String.valueOf(System.currentTimeMillis()); } public final String getSearchContent() { if (this.uBv != null) { return this.uBv.getSearchContent(); } return ""; } public final void setSearchContent(String str) { if (this.uBv != null) { this.uBv.setSearchContent(str); } } public final void setHint(CharSequence charSequence) { if (this.uBv != null) { this.uBv.setHint(charSequence); } } public final void clearFocus() { if (this.uBv != null) { this.uBv.czt(); } } public boolean Un() { return false; } public void Uo() { } public void Up() { } public final void a(final FragmentActivity fragmentActivity, Menu menu) { x.v(this.TAG, "on create options menu"); if (fragmentActivity == null) { x.w(this.TAG, "on add search menu, activity is null"); return; } if (this.uBv == null) { if (this.uBy) { this.uBv = new ActionBarSearchView(fragmentActivity); } else { this.uBv = new SearchViewNotRealTimeHelper(fragmentActivity); this.uBv.setNotRealCallBack(this.uBx); } this.uBv.setAutoMatchKeywords(this.uBA); this.uBv.setKeywords(this.uBz); } this.uBv.setCallBack(new com.tencent.mm.ui.tools.ActionBarSearchView.b() { public final void bad() { if (o.this.uBr) { o.this.Uo(); } else { x.v(o.this.TAG, "onVoiceSearchRequired, but not in searching"); } } public final void bac() { if (o.this.uBw != null) { o.this.uBw.WZ(); } } public final void FW(String str) { if (!o.this.uBr) { x.v(o.this.TAG, "onSearchTextChange %s, but not in searching", str); } else if (o.this.uBw != null) { o.this.uBw.pk(str); } } public final void WY() { if (o.this.uBw != null) { o.this.uBw.WY(); } } }); this.uBv.ms(Un()); this.uBv.setOnEditorActionListener(new OnEditorActionListener() { public final boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { if (3 != i || o.this.uBw == null) { return false; } return o.this.uBw.pj(o.this.getSearchContent()); } }); if (this.uBC != 0) { this.uBv.setSearchTipIcon(this.uBC); } this.iZG = menu.add(0, g.menu_search, 0, this.uBB); this.iZG.setEnabled(this.uBt); int i = j.actionbar_icon_dark_search; if (ad.getContext().getSharedPreferences(ad.chY() + "_redesign", 4).getBoolean("dark_actionbar", false)) { i = j.actionbar_icon_light_search; } this.iZG.setIcon(i); m.a(this.iZG, (View) this.uBv); if (this.uBq) { m.a(this.iZG, 9); } else { m.a(this.iZG, 2); } if (this.uBq) { m.a(this.iZG, new e() { public final boolean onMenuItemActionExpand(MenuItem menuItem) { o.this.a(fragmentActivity, false); return true; } public final boolean onMenuItemActionCollapse(MenuItem menuItem) { o.this.b(fragmentActivity, false); return true; } }); } else { this.uBD = new a() { public final void czR() { o.this.a(fragmentActivity, true); } public final void collapseActionView() { o.this.b(fragmentActivity, true); } }; } this.uBv.setBackClickCallback(new com.tencent.mm.ui.tools.ActionBarSearchView.a() { public final void bae() { if (o.this.uBq) { if (o.this.iZG != null) { m.c(o.this.iZG); } } else if (o.this.uBD != null) { o.this.uBD.collapseActionView(); } } }); } public void a(Activity activity, Menu menu) { x.v(this.TAG, "on prepare options menu, searchViewExpand %B, triggerExpand %B, canExpand %B", Boolean.valueOf(this.uBr), Boolean.valueOf(this.uBs), Boolean.valueOf(this.uBt)); if (activity == null) { x.w(this.TAG, "on hanle status fail, activity is null"); return; } this.iZG = menu.findItem(g.menu_search); if (this.iZG == null) { x.w(this.TAG, "can not find search menu, error"); return; } this.iZG.setOnMenuItemClickListener(new OnMenuItemClickListener() { public final boolean onMenuItemClick(MenuItem menuItem) { return false; } }); b(activity, menu); } private void b(final Activity activity, Menu menu) { if (!this.uBt) { return; } if (this.uBr || this.uBs) { this.uBs = false; if (activity instanceof MMActivity) { ((MMActivity) activity).lF(ad.getContext().getResources().getColor(d.normal_actionbar_color)); } if (menu != null) { for (int i = 0; i < menu.size(); i++) { MenuItem item = menu.getItem(i); if (item.getItemId() != g.menu_search) { item.setVisible(false); } } } this.dvh.postDelayed(new Runnable() { public final void run() { if (o.this.iZG == null) { x.w(o.this.TAG, "on post expand search menu, but item is null"); return; } x.i(o.this.TAG, "try to expand action view, searchViewExpand %B", Boolean.valueOf(o.this.uBr)); if (o.this.uBq) { if (!o.this.uBr) { m.b(o.this.iZG); } } else if (o.this.uBD != null) { o.this.uBD.czR(); } final View a = m.a(o.this.iZG); if (a != null && o.this.uBr) { a.findViewById(g.edittext).requestFocus(); if (o.this.uBu) { o.this.dvh.postDelayed(new Runnable() { public final void run() { ((InputMethodManager) activity.getSystemService("input_method")).showSoftInput(a.findViewById(g.edittext), 0); } }, 128); } } } }, 128); } } public boolean onKeyDown(int i, KeyEvent keyEvent) { x.v(this.TAG, "on key down, key code %d, expand %B", Integer.valueOf(i), Boolean.valueOf(this.uBr)); if (4 != i || !this.uBr) { return false; } czQ(); return true; } public final void mv(boolean z) { boolean z2 = false; String str = this.TAG; String str2 = "do expand, expanded[%B], search menu item null[%B]"; Object[] objArr = new Object[2]; objArr[0] = Boolean.valueOf(this.uBr); if (this.iZG == null) { z2 = true; } objArr[1] = Boolean.valueOf(z2); x.d(str, str2, objArr); if (!this.uBr) { if (this.uBt) { this.uBu = z; if (this.iZG != null) { this.dvh.post(new Runnable() { public final void run() { if (o.this.iZG == null) { x.w(o.this.TAG, "post do expand search menu, but search menu item is null"); } else if (o.this.uBq) { m.b(o.this.iZG); } else if (o.this.uBD != null) { o.this.uBD.czR(); } } }); return; } else { this.uBs = true; return; } } x.w(this.TAG, "can not expand now"); } } public final void czQ() { x.d(this.TAG, "do collapse"); if (this.uBr && this.iZG != null) { if (this.uBq) { m.c(this.iZG); } else if (this.uBD != null) { this.uBD.collapseActionView(); } } } public final boolean czu() { if (this.uBv != null) { return this.uBv.czu(); } return false; } public final boolean czv() { if (this.uBv != null) { return this.uBv.czv(); } return false; } public final void a(final FragmentActivity fragmentActivity, final boolean z) { x.d(this.TAG, "doNewExpand, searchViewExpand " + this.uBr); if (!this.uBr) { this.uBr = true; b((Activity) fragmentActivity, null); this.dvh.post(new Runnable() { public final void run() { if (fragmentActivity == null || fragmentActivity.isFinishing()) { x.w(o.this.TAG, "want to expand search view, but activity status error"); } else if (z) { fragmentActivity.supportInvalidateOptionsMenu(); } } }); if (this.uBw != null) { this.uBw.WX(); } } } public final void b(final FragmentActivity fragmentActivity, final boolean z) { x.d(this.TAG, "doNewCollapse, searchViewExpand " + this.uBr); if (this.uBr) { this.uBr = false; Up(); if (this.uBv != null) { this.uBv.mt(false); } this.dvh.post(new Runnable() { public final void run() { if (fragmentActivity == null || fragmentActivity.isFinishing()) { x.w(o.this.TAG, "want to collapse search view, but activity status error"); } else if (z) { fragmentActivity.supportInvalidateOptionsMenu(); } } }); if (this.uBw != null) { this.dvh.post(new Runnable() { public final void run() { if (o.this.uBw != null) { o.this.uBw.WW(); } } }); } } this.dvh.post(new Runnable() { public final void run() { if (o.this.iZG == null) { x.w(o.this.TAG, "want to collapse search view, but search menu item is null"); return; } if (!(fragmentActivity == null || fragmentActivity.isFinishing())) { FragmentActivity fragmentActivity = fragmentActivity; InputMethodManager inputMethodManager = (InputMethodManager) fragmentActivity.getSystemService("input_method"); if (inputMethodManager != null) { View currentFocus = fragmentActivity.getCurrentFocus(); if (currentFocus != null) { IBinder windowToken = currentFocus.getWindowToken(); if (windowToken != null) { inputMethodManager.hideSoftInputFromWindow(windowToken, 0); } } } } View a = m.a(o.this.iZG); if (a != null) { a.findViewById(g.edittext).clearFocus(); } } }); } }
package net.plazmix.core.api.spigot.inventory.paginator; /** * @author MasterCapeXD */ public enum PaginatorType { GLOBAL, PERSONAL, NONE }
package loops; import java.util.Scanner; public class primenum { public void prime(){ int i,n,m,flag=0; Scanner pr = new Scanner(System.in); System.out.println("Please enter n value:-"); n =pr.nextInt(); m = n/2; if(n==0 || n==1){ System.out.println(n+ " is not a prime number"); }else{ for(i=2;i<=m;i++) { if (n%i == 0) { System.out.println(n+ " is not a prime number"); // flag = 1; break; } } if (flag == 0) { System.out.println(n+ " is a prime number"); } } } }
package com.yixin.web.aop; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Maps; import com.yixin.common.utils.InvokeResult; import com.yixin.common.utils.JsonObjectUtils; import com.yixin.dsc.common.exception.BzException; import com.yixin.dsc.util.DateUtil; import com.yixin.web.anocation.InterfaceMonitor; import com.yixin.web.common.enums.TimeConsumeLevel; import com.yixin.web.dto.monitor.InterfaceMonitorInfoDto; import com.yixin.web.service.monitor.MonitorService; import org.apache.commons.lang3.exception.ExceptionUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.assertj.core.util.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.net.InetAddress; import java.util.Date; import java.util.List; import java.util.Map; /** * @description: * @date: 2018-10-08 14:04 */ @Aspect @Component public class InterfaceMonitorAop { private Logger logger = LoggerFactory.getLogger(getClass()); @Resource private MonitorService monitorService; /** * 配置切入点 */ @Pointcut("@annotation(com.yixin.web.anocation.InterfaceMonitor)") public void executeService() { } /** * 配置环绕通知 */ @Around(value = "@annotation(interfaceMonitor)") public Object aroundExec(ProceedingJoinPoint pjp, InterfaceMonitor interfaceMonitor) throws Throwable { Date startTime = new Date(); InterfaceMonitorInfoDto monitorInfo = new InterfaceMonitorInfoDto(); monitorInfo.setType("interface"); //目标方法执行前数据收集 collectBeforeInfo(interfaceMonitor, pjp, monitorInfo, startTime); Object result = null; InvokeResult invokeResult = new InvokeResult<>(); try { //目标方法执行 result = pjp.proceed(); //结果中的异常数据收集 collectResultErrorInfo(result, monitorInfo); } catch (BzException e) { //打印接口异常信息 printLog(e.getMessage(), monitorInfo, e); result = invokeResult.failure(e.getMessage()); //目标方法执行异常数据收集 collectErrorInfo(e, monitorInfo); } catch (Throwable e) { String errorMsg = interfaceMonitor.errorMsg(); //打印接口异常信息 printLog(errorMsg, monitorInfo, e); result = invokeResult.failure(errorMsg); //目标方法执行异常数据收集 collectErrorInfo(e, monitorInfo); } finally { //目标方法执行后数据收集 collectAfterInfo(result, monitorInfo, startTime); logger.info(JsonObjectUtils.objectToJson(monitorInfo)); //记录 monitor info、检查异常和耗时问题 monitorService.interfaceMonitor(monitorInfo); } //返回 return result; } /** * 执行前数据收集 * * @param interfaceMonitor * @param pjp * @param monitorInfo * @param startTime */ private void collectBeforeInfo(InterfaceMonitor interfaceMonitor, ProceedingJoinPoint pjp, InterfaceMonitorInfoDto monitorInfo, Date startTime) { try { //接口配置的耗时 level TimeConsumeLevel timeConsumeLevel = interfaceMonitor.timeConsume(); monitorInfo.setTimeConsumeLevel(timeConsumeLevel.getValue()); //服务器ip String ip = InetAddress.getLocalHost().getHostAddress(); monitorInfo.setServerHost(ip); //类名 Class clazz = pjp.getTarget().getClass(); String className = clazz.getName(); monitorInfo.setClassName(className); //方法名 String methodName = pjp.getSignature().getName(); monitorInfo.setMethodName(methodName); //开始时间 String startTimeStr = DateUtil.dateToString(startTime, DateUtil.DEFAULT_TIMESTAMP_FORMAT); monitorInfo.setStartTime(startTimeStr); //参数 Object[] args = pjp.getArgs(); if (args != null && args.length > 0) { monitorInfo.setArgs(JsonObjectUtils.objectToJson(args)); } List<Map<String, String>> keyParameters = getKeyParams(interfaceMonitor, args); monitorInfo.setKeyParameters(keyParameters); String keyParamtersStr = extractKeyParamters(keyParameters); monitorInfo.setKeyParametersStr(keyParamtersStr); } catch (Exception e) { logger.error("interface monitor AOP before 异常", e); monitorInfo.setBeforeError(e.getMessage()); } } /** * 异常信息收集 * * @param e * @param monitorInfo */ private void collectErrorInfo(Throwable e, InterfaceMonitorInfoDto monitorInfo) { try { //是否有异常 monitorInfo.setHasError(true); //异常message monitorInfo.setMessage(e.getMessage()); //异常堆栈 monitorInfo.seteStackTrace(ExceptionUtils.getStackTrace(e)); } catch (Exception e1) { monitorInfo.setExceptionError(e.getMessage()); } } /** * 返回结果中的异常收集 * * @param result * @param monitorInfo */ private void collectResultErrorInfo(Object result, InterfaceMonitorInfoDto monitorInfo) { try { if (result instanceof InvokeResult) { InvokeResult invokeResult = (InvokeResult) result; boolean hasError = invokeResult.isHasErrors(); if (hasError) { monitorInfo.setHasError(hasError); monitorInfo.setMessage(invokeResult.getErrorMessage()); } } } catch (Exception e) { monitorInfo.setExceptionError(e.getMessage()); } } /** * 方法执行后数据收集 * * @param result * @param monitorInfo * @param startTime */ private void collectAfterInfo(Object result, InterfaceMonitorInfoDto monitorInfo, Date startTime) { try { //返回结果 monitorInfo.setResult(JsonObjectUtils.objectToJson(result)); //结束时间 Date endTime = new Date(); monitorInfo.setEndTime(DateUtil.dateToString(endTime, DateUtil.DEFAULT_TIMESTAMP_FORMAT)); //接口耗时 /ms monitorInfo.setTimeConsumed(endTime.getTime() - startTime.getTime()); } catch (Exception e) { logger.error("interface monitor AOP after 异常", e); monitorInfo.setAfterError(e.getMessage()); } } private List<Map<String, String>> getKeyParams(InterfaceMonitor interfaceMonitor, Object[] args) { try { String[] keyParam = interfaceMonitor.keyParam(); if (keyParam == null || keyParam.length <= 0) { return null; } List<Map<String, String>> keyParams = Lists.newArrayList(); for (String item : keyParam) { try { String[] paramConf = item.split("::"); String paramName = paramConf[0]; String paramValue = parseParam(paramConf[1], args); Map<String, String> param = Maps.newHashMap(); param.put(paramName, paramValue); keyParams.add(param); } catch (Exception e) { logger.error("parse param error"); } } return keyParams; } catch (Exception e) { logger.error("get key parameters error"); return null; } } private String parseParam(String paramPosition, Object[] args) { String[] keys = paramPosition.split("_"); boolean firstLevel = keys.length == 1; int argPosition = Integer.parseInt(keys[0]); Object arg = args[argPosition]; if (firstLevel) { return arg.toString(); } JSONObject jsonObject = parseJSONObject(arg); Object propValue = null; if (jsonObject != null) { for (int i = 1; i < keys.length; i++) { String prop = keys[i]; propValue = jsonObject.get(prop); jsonObject = parseJSONObject(propValue); } return propValue.toString(); } else { return null; } } private JSONObject parseJSONObject(Object arg) { if (arg instanceof String) { try { return JSON.parseObject((String) arg); } catch (Exception e) { return null; } } else { return JSON.parseObject(JSON.toJSONString(arg)); } } private String extractKeyParamters(List<Map<String, String>> parameters) { if (parameters == null || parameters.size() <= 0) { return ""; } StringBuilder sb = new StringBuilder(""); for (Map<String, String> item : parameters) { for (Map.Entry<String, String> entry : item.entrySet()) { sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); } sb.append("&"); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } private void printLog(String errorMsg, InterfaceMonitorInfoDto monitorInfo, Throwable exception) { StringBuilder sb = new StringBuilder(""); // sb.append("接口,"); sb.append(monitorInfo.getClassName()); sb.append("/"); sb.append(monitorInfo.getMethodName()); sb.append(","); sb.append(errorMsg); sb.append(","); sb.append(monitorInfo.getKeyParametersStr()); logger.error(sb.toString(), exception); } }
package com.example.lenovo.medleybranch; public class Customer_Bill { String billID; String CarID; String billDate; String nextDate; String meterReading; public Customer_Bill() { } public Customer_Bill(String billID, String carID, String billDate, String nextDate, String meterReading) { this.billID = billID; CarID = carID; this.billDate = billDate; this.nextDate = nextDate; this.meterReading = meterReading; } public String getBillID() { return billID; } public void setBillID(String billID) { this.billID = billID; } public String getCarID() { return CarID; } public void setCarID(String carID) { CarID = carID; } public String getBillDate() { return billDate; } public void setBillDate(String billDate) { this.billDate = billDate; } public String getNextDate() { return nextDate; } public void setNextDate(String nextDate) { this.nextDate = nextDate; } public String getMeterReading() { return meterReading; } public void setMeterReading(String meterReading) { this.meterReading = meterReading; } }
package com.example.tagebuch.model.dao; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.example.tagebuch.model.pojo.Pensamiento; import java.util.List; @Dao public interface PensamientoRoomDAO { @Query("SELECT * FROM pensamientos") List<Pensamiento> getAll(); @Query("SELECT * FROM pensamientos WHERE fecha = :fecha LIMIT 1") Pensamiento obtenerPorFecha(String fecha); @Insert void insertar(Pensamiento pensamiento); @Delete void eliminar(Pensamiento pensamiento); @Update void actualizar(Pensamiento pensamiento); }
package constantes; public enum Carta { ///ENUM OURO,ESPADAS,PAUS,COPAS // CONSTANTES }
package com.saaolheart.mumbai.masters.invoice; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface InvoiceTypeMasterRepo extends JpaRepository<InvoiceTypeMaster,Long>{ }
package com.youtalkwesign.service; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.transaction.Transactional; import org.apache.commons.io.IOUtils; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.youtalkwesign.model.Heart; import com.youtalkwesign.model.Video; import com.youtalkwesign.repository.HeartRepository; @Service @Transactional public class HeartedService { @Autowired HeartRepository repo; public boolean hasHeart(String username, String v) { Heart heart = repo.findOneByUsernameAndVideoId(username, v); return heart != null; } public List<Video> getHeartedVideos(String username) { // initialize result List<Video> result = new ArrayList<Video>(); List<Heart> hearts = repo.findByUsername(username); for (Heart heart : hearts) { Video video = new Video(); video.setId(heart.getVideoId()); video.setTitle(getTitleQuietly(heart.getVideoId())); video.setThumbnailImageUrl("https://i.ytimg.com/vi/" + heart.getVideoId() + "/maxresdefault.jpg"); result.add(video); } return result; } private static String getTitleQuietly(String videoId) { try { if (videoId != null) { URL embededURL = new URL("http://www.youtube.com/oembed?url=" + "http://www.youtube.com/watch?v=" + videoId + "&format=json" ); return new JSONObject(IOUtils.toString(embededURL, "UTF-8")).getString("title"); } } catch (Exception e) { e.printStackTrace(); } return null; } public void unheart(String username, String videoId) { repo.deleteByUsernameAndVideoId(username, videoId); } }
package me.alven.checker.util; import java.util.Arrays; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Check { public static String PlFirstAlias() { if(FileManager.getConfig().getStringList("Main.Aliases").isEmpty()) return "acheck"; return FileManager.getConfig().getStringList("Main.Aliases").get(0); } public static String PlDescrip() { if(FileManager.getConfig().getString("Main.PlDescr").isEmpty()) return "Check Player"; return FileManager.getConfig().getString("Main.PlDescr"); } public static List<String> PlAliases() { if(FileManager.getConfig().getStringList("Main.Aliases").isEmpty()) return Arrays.asList(""); return FileManager.getConfig().getStringList("Main.Aliases"); } public static String TimeBanCommander(String path, CommandSender adm, Player cheat, String time) { return FileManager.getConfig().getString(path).replaceAll("%ADM%", adm.getName()).replaceAll("%PLAYER%", cheat.getName()).replaceAll("%TIME%", time); } public static String BanCommander(String path, CommandSender adm, Player cheat) { return FileManager.getConfig().getString(path).replaceAll("%ADM%", adm.getName()).replaceAll("%PLAYER%", cheat.getName() .replaceAll("%TIME%", "")); } public static String BanCommanderl(String path, Player cheat) { Player adm = Bukkit.getPlayer(FileManager.getChecking().getString(cheat.getName()+".admin")); return FileManager.getConfig().getString(path).replaceAll("%ADM%", adm.getName()).replaceAll("%PLAYER%", cheat.getName() .replaceAll("%TIME%", "")); } public static boolean hasPerms(CommandSender sender, String path) { if(sender.isOp()) return true; if(sender.hasPermission(FileManager.getConfig().getString(path))) return true; return false; } }
package banyuan.day07.package02; /** * @author 陈浩 * @date Created on 2019/10/30 * 制作一个销售首饰的公司类。 * 属性: * 一个保存员工的数组。 * 方法: * 1, 添加一个员工。 * 2, 通过员工的名字来删除员工。 * 3, 通过员工的名字来显示员工的工资。 * 4, 输出所有员工的工资和。 */ public class Compay { String[] Person = new String[10]; public Compay() { } public static void add() { } public Compay(String[] person) { Person = person; } public static void delete(String name) { } public static void search(String name) { } public static void payTheTotal() { double a = new XiaoShiGong().makeMoney(10, 200) + new XiaoShiGong().makeMoney(10, 230) + new XiaoShouYuanGong().makeMoney(5000, 4000) + new XiaoShouYuanGong().makeMoney(200000, 4000) + new PuTongYuanGong().makeMoney(205, 4000); double b = new GongRen().makeMoney(30, 50); System.out.println(a); System.out.println(b); System.out.println(a + b); } public String[] getPerson() { return Person; } public void setPerson(String[] person) { Person = person; } }
package com.example.vohonglam.miniproject; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.app.Activity; import android.view.View; public class Gift3 extends Activity { private MediaPlayer player; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gift_3); player = MediaPlayer.create(this, R.raw.a); player.start(); } public void Clickreturn3 (View view) { player.stop(); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } }
import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; //import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class BaseTest { protected WebDriver driver; protected String baseUrl; protected WebDriverWait wait; @Before public void baseSetUp() throws Exception { driver = new ChromeDriver(); baseUrl = "http://sureprep-frontend-coding-challenge.s3-website-us-east-1.amazonaws.com"; wait = new WebDriverWait(driver, 5); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.manage().deleteAllCookies(); driver.get(baseUrl); // String pageLoaded = ((JavascriptExecutor)driver).executeScript("return document.readyState").toString(); // System.out.println("Home Page load is "+ pageLoaded); } @After public void baseTearDown() throws Exception { // Thread.sleep(3000); // delay for visual debug purposes right before quit driver.quit(); } }
package com.yuyutx.stack; import java.util.Stack; /** * @author jun * @date 2020-11-10 06:21 * @description * * 使用一个栈实现另一个栈的排序,从顶到底从大到小 * * 思路 * 1.只要新建的栈里的元素是从从大到小的入栈,然后再弹出到原来的空栈,那原来的栈从顶到底就是从大到小排列 * 2.当原来的待排序的栈不为空时,弹出栈顶元素,当新建的辅助栈不为空,而且栈顶元素小于弹出值时,将辅助栈元素弹出压入待排序战。 * 3.待排序栈不为空时,弹出的元素一直压入辅助栈 */ public class MySortStack { public void sortStackByStack(Stack<Integer> stack){ Stack<Integer> popStack = new Stack<>(); while(!stack.isEmpty()){ int cur = stack.pop(); while(!popStack.isEmpty()&&popStack.peek()<cur){ stack.push(popStack.pop()); } popStack.push(cur); } while (!popStack.isEmpty()){ stack.push(popStack.pop()); } } public static void main(String[] args) { MySortStack mySortStack = new MySortStack(); Stack<Integer> stack = new Stack<>(); stack.push(3); stack.push(1); stack.push(2); stack.push(4); System.out.println(stack); mySortStack.sortStackByStack(stack); System.out.println(stack); } }
package com.dil.firstproj; import java.util.Locale; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.dil.firstproj.controller.NavigationController; import com.dil.firstproj.service.NewsService; public class NavigationControllerTest { @InjectMocks private NavigationController controller; @Mock private NewsService service; private MockMvc mockMvc; private Locale locale; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); locale = LocaleContextHolder.getLocale(); } @Test public void getIndexPage_whenServiceReturnsEmpty_thenReturn() throws Exception { Mockito.when(service.getHomePage()).thenReturn(""); mockMvc.perform(MockMvcRequestBuilders.get("/home").locale(locale)) .andExpect(MockMvcResultMatchers.view().name("index")); } }
package com.ssp; import org.junit.jupiter.api.Test; import java.util.*; public class Solution { }
package pe.egcc.cursoapp.service.implementacion; import java.util.ArrayList; import java.util.List; import pe.egcc.cursoapp.dto.ProductoDto; import pe.egcc.cursoapp.service.contrato.CursoService; public class CursoServiceImpl implements CursoService { @Override public String[] getListaCategoria() { return DataStore.arregloCategoria; } @Override public int registrarProducto(ProductoDto dto) { //--- DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //Date date = new Date(); //System.out.println(dateFormat.format(date)); //calculamos el nr de incidencia int numProd = DataStore.productos.size() + 1; dto.setNum(numProd); //calcularPromedio(dto); DataStore.productos.add(dto); return 1; } /* private void calcularPromedio(AlumnoDto dto) { // Proceso int pr = (dto.getNota1() + dto.getNota2() + dto.getNota3()) /3; boolean aprobado = (pr >= 13); // Registrar resultado dto.setAprobado(aprobado); dto.setPromedio(pr); } */ @Override public List<ProductoDto> getProductos(String categoria) { List<ProductoDto> lista2 = new ArrayList<>(); for (ProductoDto dto : DataStore.productos) { if (dto.getCategoria().equals(categoria)) { lista2.add(dto); } } return lista2; } @Override public List<ProductoDto> getAllProductos() { List<ProductoDto> lista2 = new ArrayList<>(); for (ProductoDto dto : DataStore.productos) { lista2.add(dto); } return lista2; } }
package com.example.remi.bluetoothspike; import android.bluetooth.BluetoothDevice; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by remi on 07/03/2017. */ public class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.ViewHolder> { private List<BluetoothDevice> mDevices = new ArrayList<>(); private DeviceViewHolderClick mDeviceViewHolderClick; public static interface DeviceViewHolderClick { void onDevice(BluetoothDevice device); } public static class ViewHolder extends RecyclerView.ViewHolder { public TextView mTextViewName; public TextView mTextViewIdentifier; public ViewHolder(View v) { super(v); mTextViewName = (TextView) v.findViewById(R.id.text_view_name); mTextViewIdentifier = (TextView) v.findViewById(R.id.text_view_identifier); } public void BindView(final BluetoothDevice device, final DeviceViewHolderClick deviceViewHolderClick) { String name = device.getName(); mTextViewName.setText(name); mTextViewIdentifier.setText(device.getAddress()); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deviceViewHolderClick.onDevice(device); } }); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.device_recycle_view, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { BluetoothDevice device = mDevices.get(position); holder.BindView(device, mDeviceViewHolderClick); } @Override public int getItemCount() { return mDevices.size(); } public void setmDevices(List<BluetoothDevice> mDevices) { this.mDevices = mDevices; notifyDataSetChanged(); } public DeviceAdapter(DeviceViewHolderClick mDeviceViewHolderClick) { this.mDeviceViewHolderClick = mDeviceViewHolderClick; } }
package lt.kaunascoding.web.model.mysql.classes; import lt.kaunascoding.web.model.mysql.interfaces.ITable; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; public class User implements ITable{ private int id; private String nickname; private String password; private String name; private String email; private String level; private Date regDate; private Timestamp lastLoginDate; public User() { } public User(ResultSet eilute){ try { id = eilute.getInt("id"); nickname = eilute.getString("nickname"); password = eilute.getString("password"); name = eilute.getString("name"); email = eilute.getString("email"); level = eilute.getString("level"); regDate = eilute.getDate("reg_date"); lastLoginDate = eilute.getTimestamp("last_login_date"); } catch (SQLException e) { e.printStackTrace(); } } public User(int id, String nickname, String password, String name, String email, String level, Date regDate, Timestamp lastLoginDate) { this.id = id; this.nickname = nickname; this.password = password; this.name = name; this.email = email; this.level = level; this.regDate = regDate; this.lastLoginDate = lastLoginDate; } //region Getters and Setter public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public Date getRegDate() { return regDate; } public void setRegDate(Date regDate) { this.regDate = regDate; } public Timestamp getLastLoginDate() { return lastLoginDate; } public void setLastLoginDate(Timestamp lastLoginDate) { this.lastLoginDate = lastLoginDate; } //endregion public String tableRows() { StringBuilder table = new StringBuilder(); table.append("(id,nickname,password,name,email,level,reg_date,last_login_date)"); return table.toString(); } public String toTable() { StringBuilder table = new StringBuilder(); table.append("("); table.append("NULL,"); table.append("\"" + nickname + "\""+","); table.append("\"" + password + "\""+","); table.append("\"" + name + "\""+","); table.append("\"" + email + "\""+","); table.append("\"" + level + "\""+","); table.append("\"" + regDate.toString() + "\""+","); table.append("\"" + lastLoginDate.toString() + "\""); table.append(")"); return table.toString(); } }
package presentacion.controlador.command.CommandFactura; import negocio.factorias.FactorySA; import negocio.factura.SAFactura; import negocio.lineadefactura.TLineaDeFactura; import presentacion.contexto.Contexto; import presentacion.controlador.command.Command; import presentacion.eventos.EventosFactura; /** * The Class EliminarLibroFactura. */ public class EliminarLibroFactura implements Command { /* * (non-Javadoc) * * @see presentacion.controlador.command.Command#execute(java.lang.Object) */ @Override public Contexto execute(final Object objeto) { final TLineaDeFactura tLineaDeFactura = (TLineaDeFactura) objeto; final SAFactura sa = FactorySA.getInstance().createSAFactura(); String mensaje; Contexto contexto; try { sa.eliminarLibroDeFactura(tLineaDeFactura); mensaje = "Factura modificada correctamente. Su ID es: " + tLineaDeFactura.getId() + ". "; contexto = new Contexto(EventosFactura.ELIMINAR_LIBRO_FACTURA_OK, mensaje); } catch (final Exception e) { mensaje = e.getMessage(); contexto = new Contexto(EventosFactura.ELIMINAR_LIBRO_FACTURA_KO, mensaje); } return contexto; } }
/** * original(c) zhuoyan company * projectName: java-design-pattern * fileName: MementoTest.java * packageName: cn.zy.pattern.memento * date: 2018-12-26 22:00 * history: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package cn.zy.pattern.memento; import cn.zy.pattern.memento.high.HighChessman; import cn.zy.pattern.memento.high.HighMemento; import cn.zy.pattern.memento.high.HighMementoCareker; import cn.zy.pattern.memento.simple.Chessman; import cn.zy.pattern.memento.simple.MementoCareker; import cn.zy.pattern.memento.simple.SimpleMemento; import com.alibaba.fastjson.JSON; import org.junit.Test; /** * @version: V1.0 * @author: ending * @className: MementoTest * @packageName: cn.zy.pattern.memento * @description: 备忘录测试类 * @data: 2018-12-26 22:00 **/ public class MementoTest { @Test public void simpleTest(){ MementoCareker mementoCareker = new MementoCareker(); Chessman chessman = new Chessman(); chessman.setName("马"); chessman.setX(1); chessman.setY(2); SimpleMemento simpleMemento = chessman.getMemento(); mementoCareker.setSimpleMemento(simpleMemento); System.out.println(JSON.toJSONString(chessman)); chessman.setY(7); System.out.println(JSON.toJSONString(chessman)); /** 悔棋 */ chessman.restore(mementoCareker.getSimpleMemento()); System.out.println(JSON.toJSONString(chessman)); } @Test public void high(){ int index = 0; HighMementoCareker highMementoCareker = new HighMementoCareker(); HighChessman chessman = new HighChessman(); chessman.setName("马"); chessman.setX(1); chessman.setY(2); HighMemento memento = chessman.getMemento(); highMementoCareker.setHighMemento(index++ , memento); System.out.println("当前位置" + JSON.toJSONString(chessman.getMemento())); System.out.println(JSON.toJSONString(highMementoCareker.getHighMementoList())); chessman.setX(2); memento = chessman.getMemento(); highMementoCareker.setHighMemento(index++, memento); System.out.println("当前位置" + JSON.toJSONString(chessman.getMemento())); System.out.println(JSON.toJSONString(highMementoCareker.getHighMementoList())); chessman.setX(3); memento = chessman.getMemento(); highMementoCareker.setHighMemento(index++, memento); System.out.println("当前位置" + JSON.toJSONString(chessman.getMemento())); System.out.println(JSON.toJSONString(highMementoCareker.getHighMementoList())); /** 悔棋 */ HighMemento highMemento = highMementoCareker.getHighMemento(--index - 1); chessman.restore(highMemento); System.out.println("当前位置" + JSON.toJSONString(chessman)); System.out.println(JSON.toJSONString(highMementoCareker.getHighMementoList())); highMemento = highMementoCareker.getHighMemento(--index - 1); chessman.restore(highMemento); System.out.println("当前位置" + JSON.toJSONString(chessman)); System.out.println(JSON.toJSONString(highMementoCareker.getHighMementoList())); /** 撤销悔棋 */ highMemento = highMementoCareker.getHighMemento(index++); chessman.restore(highMemento); System.out.println("当前位置" + JSON.toJSONString(chessman)); System.out.println(JSON.toJSONString(highMementoCareker.getHighMementoList())); highMemento = highMementoCareker.getHighMemento(index++); chessman.restore(highMemento); System.out.println("当前位置" + JSON.toJSONString(chessman)); System.out.println(JSON.toJSONString(highMementoCareker.getHighMementoList())); } }
package com.qw.springboot.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping("/index") public String index() { return "admin/index"; } @RequestMapping("/") public String example() { return "index1"; } @RequestMapping("/404") public String test404() { return ""; } @RequestMapping("/test01") public String test01() { return "webM"; } @RequestMapping("/login") public String test02() { return "admin/login"; } @RequestMapping("/rbac-admin") public String test03() { return "admin/rbac-admin"; } @RequestMapping("/rbac-user-list") public String test04() { return "admin/rbac-user-list"; } @RequestMapping("/welcome") public String test05() { return "admin/welcome"; } @RequestMapping("/system") public String test06() { return "admin/system"; } @RequestMapping("/admin-info") public String test07() { return "admin/admin-info"; } @RequestMapping("/position-add") public String test08() { return "admin/position-add"; } @RequestMapping("/position-list") public String test09() { return "admin/position-list"; } @RequestMapping("/position-edit") public String test10() { return "admin/position-edit"; } @RequestMapping("/infor-list") public String test11() { return "admin/infor-list"; } @RequestMapping("/infor-edit") public String test12() { return "admin/infor-edit"; } @RequestMapping("/product-add") public String test13() { return "admin/product-add"; } @RequestMapping("/product-list") public String test14() { return "admin/product-list"; } @RequestMapping("/product-edit") public String test15(){ return "admin/product-edit"; } @RequestMapping("/order-form") public String test16(){ return "admin/order-form"; } @RequestMapping("/order-edit") public String test17(){ return "admin/order-edit"; } @RequestMapping("/article-detail") public String test18() { return "admin/article-detail"; } @RequestMapping("/article-list") public String test19() { return "admin/article-list"; } @RequestMapping("/article-edit") public String test20(){ return "admin/article-edit"; } @RequestMapping("/article-add") public String test22(){ return "admin/article-add"; } }
package model.impl; import java.util.List; import java.util.Vector; import model.AccessPoint; import model.AccessPointNetwork; import model.GridPoint; import model.Level; import model.Plan; import model.SensorNode; public class AccessPointNetworkImpl implements AccessPointNetwork { //private Vector<AccessPoint> accessPoints; private Vector<Vector<AccessPoint>> levelaps;//Vector of vector of accesspoints (one vector per level) /** * Constructs and initializes an AccessPointNetwork with no AccessPoints, but with the correct number of levels */ public AccessPointNetworkImpl(Plan plan) { int maxlevelno=-1; for(Level l:plan.getLevels()) if(l.getNumber()>maxlevelno) maxlevelno=l.getNumber(); //System.out.println("nieuw apn, maxlevel= "+maxlevelno); this.levelaps = new Vector<Vector<AccessPoint>>(); for (int i=0;i<maxlevelno+1;i++) levelaps.add(new Vector<AccessPoint>()); //System.out.println("APnetwerk gecre�erd met "+levelaps.size()+" levels."); } public AccessPointNetworkImpl() { this.levelaps = new Vector<Vector<AccessPoint>>(); } /** * Constructs and initializes an AccessPointNetwork with the given AccessPoints. * @param accessPoints */ public AccessPointNetworkImpl(Vector<Vector<AccessPoint>> accessPoints) { this.levelaps = accessPoints; } public Vector<Vector<AccessPoint>> getAccessPoints(){ return levelaps; } /*public Vector<AccessPoint> getAccessPoints(int levelnumber){ Vector<AccessPoint> levelaps= new Vector<AccessPoint>(); for(AccessPoint a:this.getAccessPoints()) if(a.getLevel().getNumber()==levelnumber) levelaps.add(a); return levelaps; }*/ public Vector<AccessPoint> getAccessPoints(int levelnumber){ //System.out.println(levelaps.size());//number of vectors(levels) //System.out.println(levelaps.firstElement().size());//number APS on level0 return levelaps.elementAt(levelnumber); } /*public void setAccessPoints(Vector<AccessPoint> accessPoints) { this.accessPoints = accessPoints; } */ public int getTotalSize(){ int size=0; for(Vector<AccessPoint> levelaps:getAccessPoints()) size=size+levelaps.size(); return size; } public void removeAllAccessPoints(){ int aantallevels=levelaps.size(); for(int i=0;i<aantallevels;i++){ levelaps.elementAt(i).removeAllElements();//elk level heeft weer een lege vector met APs, aantal levels blijft intact } } public void addAccessPoint(AccessPoint ap){ int levelno=ap.getLevel().getNumber(); /*int currentmaxlevelno=levelaps.size()-1; if(currentmaxlevelno<levelno){ //we have to add levels for(int i=0;i<levelno-currentmaxlevelno;i++) levelaps.add(new Vector<AccessPoint>()); } Vector<AccessPoint> acpsonlevel=levelaps.elementAt(levelno); acpsonlevel.addElement(ap);*/ //System.out.println("aantal levels erin in apnimpl "+this.getAccessPoints().size()); // System.out.println("number of level: "+levelno); // System.out.println(ap.getCoordinates().x+", "+ap.getCoordinates().y); // System.out.println(levelaps.size()); levelaps.elementAt(levelno).addElement(ap); } public boolean farEnough4E(double x,double y,int dist){ for(AccessPoint ap:this.getAccessPoints(0)) { if(ap.distance(new GridPointImpl(x,y))<dist) return false; } return true; } public boolean refineGridLocationsAroundAPs(int grid_size, List<GridPoint[]>gridPointstemp) { //verfijn gridpointresolutie rond het AP, voor exposureberekening (Refine grid point resolution around the AP, for exposure calculation) //System.out.println("aantal levels met aps "+levelaps.size()); //System.out.println("ap op L0 "+levelaps.elementAt(0).firstElement()); for(int i=0;i<levelaps.size();i++) for(AccessPoint app:levelaps.elementAt(i)) if(!app.getRadios().firstElement().getType().equalsIgnoreCase("sensor"))//only refine for non-sinks if(!app.refineGridLocations_v2_aroundAPs(grid_size, gridPointstemp)) return false; return true; } public SensorNode getApWithID(int ID) { for(int i=0;i<levelaps.size();i++){ for(AccessPoint a:levelaps.elementAt(i)){ for(TransTxRadioImpl rad:a.getRadios()){ if(((SensorNode)rad).getNodeID()==ID) return (SensorNode) rad; } } } return null; } }
package com.ethercamp.starter.Solidity; import java.io.IOException; import java.util.HashMap; public class SolcCompilerJniWrapper implements ISolcCompiler { static { System.loadLibrary("solidity"); } public native byte[] compileNative();//???? @Override public void setSource(String src) { } @Override public HashMap<String, byte[]> compile() throws IOException { return null; } @Override public HashMap<String, String> getAbi() throws IOException { return null; } @Override public String getAst() throws IOException { return null; } @Override public String getAsm() throws IOException { return null; } @Override public String getOpCodes() throws IOException { return null; } @Override public String getHashes() throws IOException { return null; } }
package SvgPac; import java.awt.geom.Point2D; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; public class SvgPointArray extends ArrayList<Point2D.Float> { private static final long serialVersionUID = -7118936325657358855L; public SvgPointArray() { super(); } public void read(BufferedReader br) throws IOException { int i = 0; while (true) { System.out.printf("\tpoint[%d]=", i); String s = br.readLine(); if (s.isEmpty() || s.equals("*")) break; String[] xy = s.split(","); add(new Point2D.Float( Float.parseFloat(xy[0]), Float.parseFloat(xy[1]))); i++; } } public void save(DataOutputStream stream) throws IOException { stream.writeInt(size()); if (size() <= 0) return; for (Point2D.Float p: this) { stream.writeFloat(p.x); stream.writeFloat(p.y); } } public void load(DataInputStream stream) throws IOException { clear(); int count = stream.readInt(); if (count <= 0) return; for (int i = 0; i < count; i++) { add(new Point2D.Float(stream.readFloat(), stream.readFloat())); } } public void getPoints(int[] xp, int[] yp) { final int s = size(); Point2D.Float p; for (int i = 0; i < s; i++) { p = get(i); xp[i] = Math.round(p.x); yp[i] = Math.round(p.y); } } public String toString() { StringBuilder sb = new StringBuilder(); int count = size(); if (count > 0) { for (int i = 0; i < count; i++) { Point2D.Float p = get(i); sb.append(SvgHelper.floatToString(p.x) + "," + SvgHelper.floatToString(p.y) + " "); } } return sb.toString(); } }
package com.mideas.rpg.v2.hud.auction.old; public enum AuctionFrameTab { BROWSE, BIDS, AUCTIONS, ; }
public class Kodu1{ public static double[] arvudeks(String[] andmed){ double[] arvud=new double[andmed.length]; for(int i=0; i<2; i++){ arvud[i]=Double.parseDouble(andmed[i]); } return arvud; } public static double hüpotenuus(double[] arvud){ double hüpotenuus=0; for(double arv: arvud){ hüpotenuus = Math.sqrt((arvud[0]*arvud[0]) + (arvud[1]*arvud[1])); } return hüpotenuus; } public static double pindala(double[] kaatetid){ double pindala = kaatetid[0]*kaatetid[1] / 2; return pindala; } public static double ümbermõõt(double[] küljed){ double ümbermõõt = küljed[0] + küljed[1] + küljed[2]; return ümbermõõt; } public static void main(String[] arg){ for(int i=0; i<2; i++){ if (i==0) { System.out.println(i+1+"." +" kaatet: "+arg[i]); } if (i==1) { System.out.println(i+1+"." +" kaatet: "+arg[i]); } } double[] a=arvudeks(arg); double[] b=new double[3]; b[0] = a[0]; b[1] = a[1]; b[2] = hüpotenuus(a); double ümbermõõt = b[0]+b[1]+b[2]; //System.out.println("Hüpotenuus: "+ hüpotenuus(a)); System.out.printf("Hüpotenuus: %.2f %n", hüpotenuus(a)); System.out.printf("Kolmnurga pindala on: %.2f %n", pindala(a)); System.out.printf("Kolmnurga ümbermõõt on: %.2f %n", ümbermõõt); } }
package com.bitbus.fantasyprep.player; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Entity @Getter @Setter @EqualsAndHashCode(exclude = {"player", "pointProjections"}) @ToString(exclude = {"player", "pointProjections"}) public class PlayerProjection { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int projectionId; @OneToOne @JoinColumn(name = "player_id") private Player player; private double passingYards; private double passingTds; private double interceptions; private double rushingYards; private double rushingTds; private double receptions; private double receivingYards; private double receivingTds; @OneToMany(mappedBy = "projection") private List<PlayerProjectedPoints> pointProjections; }
package com.zihui.cwoa.processone.service; import com.zihui.cwoa.financial.pojo.RoleAllUser; import com.zihui.cwoa.processone.dao.HumanMapper; import com.zihui.cwoa.system.pojo.sys_users; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @CacheConfig(cacheNames = {"HumanServiceCache"}) @Service("HumanService") public class HumanService { @Autowired private HumanMapper humanMapper; /** * 查询请假出差记录 * @return 查询结果 */ public Map<String,Object> queryLeaveByVo(int size,String userId, String project, String leaveYear, String leaveMonth, int page, int limit){ List<Map<String,Object>> queryLeaveByVo = humanMapper.queryLeaveByVo(userId,project,leaveYear,leaveMonth,page,limit); Map<String,Object> map =new HashMap<>(); map.put("code",0); map.put("msg","请求成功"); map.put("count",size); map.put("data",queryLeaveByVo); return map; } /** * 查询请假出差记录条数 * @return 查询结果 */ public Integer countLeaveByVo(String userId, String project, String leaveYear, String leaveMonth){ return humanMapper.countLeaveByVo(userId,project,leaveYear,leaveMonth); } /** * 查询用户的出差请假记录详情 * @return 查询结果 */ public List<Map<String,Object>> queryLeaveDetail(String userId, String project, String leaveYear, String leaveMonth){ return humanMapper.queryLeaveDetail(userId,project,leaveYear,leaveMonth); } /** * 查询所有角色及该角色下的所有用户 */ @Cacheable(key="'userQueryRoleAllUser'") public Map<String,Object> queryRoleAllUser(){ List<RoleAllUser> roleAllUsers = humanMapper.queryRoleAllUser(); List<Map<String,Object>> dataList=new ArrayList<>(); Map<String,Object> dataMap=new HashMap<>(); for (RoleAllUser role: roleAllUsers) { Map<String,Object> map=new HashMap<>(); map.put("name",role.getRole_name()); map.put("type","optgroup"); dataList.add(map); for(sys_users user:role.getList()){ Map<String,Object> map2=new HashMap<>(); map2.put("name",user.getUserName()); map2.put("value",user.getUserId()); dataList.add(map2); } } dataMap.put("data", dataList); dataMap.put("code", 0); dataMap.put("msg", "未知错误"); return dataMap; } /** * 根据父ID查询菜单名称数组 */ public List<String> queryMenuByParentId(String userId,String parentId){ return humanMapper.queryMenuByParentId(userId,parentId); } /** * 查询角色用以下拉框选择 */ @Cacheable(key="'roleQueryRoleSelectChw'") public List<Map<String,Object>> queryRoleSelect(){ return humanMapper.queryRoleSelect(); } /** * 查询所有角色及该角色下的所有用户 */ @Cacheable(key="'userChwRoleUser'") public List<RoleAllUser> roleUser(){ return humanMapper.queryRoleAllUser(); } /** * 查询用户部门 */ public String selectDepartmentById(String userId){ return humanMapper.selectDepartmentById(userId); } /** * 查询用户姓名及部门 */ @Cacheable(key="'userQueryNameDepartment'") public List<Map<String,Object>> queryNameDepartment(){ return humanMapper.queryNameDepartment(); } }
package com.lec.ex01_store; //2호점: 김치찌개-5,000 부대찌개-5,000 비빔밥-5,000 순대국-5,000 공기밥-무료 public class StoreNum2 implements HeadQuarterStore { private String name; public StoreNum2(String name) { this.name = name; } //override-재정의; 부모클래스의 메소드를 재정의 //overload 중복정의; 매개변수의 수나 타입으로 같은 이름의 함수를 중복 정의 @Override public void kimchi() { System.out.println("김치찌개 5,000원"); } @Override public void bude() { System.out.println("부대찌개 5,000원"); } @Override public void bibib() { System.out.println("비빔밥 5,000원"); } @Override public void sunde() { System.out.println("순대찌개 5,000원"); } @Override public void bab() { System.out.println("공기밥0원.무료"); } public String getName() { return name; } }
package testcase; import converter.ConverterDateTimestamp; import converter.ConverterDateTimestamp2; import es.utils.mapper.Mapper; import es.utils.mapper.exception.MappingException; import es.utils.mapper.exception.MappingNotFoundException; import from.ConverterFrom; import from.From; import from.FromWithConverter; import org.junit.jupiter.api.Test; import to.ConverterTo; import to.To; import to.ToWithConverter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.sql.Timestamp; import java.util.Date; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; public class ConverterTest { @Test public void shouldApplyConverterIfPresent() throws MappingNotFoundException, MappingException { Mapper mapper = new Mapper(); mapper.add(From.class, To.class); mapper.build(); From from = new From(); To to = mapper.map(from); assertThat(to.getTimestamp1()).isNull(); assertThat(to.getTimestamp2()).isEqualTo(Timestamp.valueOf("2019-07-07 08:45:36")); assertThat(to.getTimestamp3()).isEqualTo(Timestamp.valueOf("2019-07-07 08:45:36")); } @Test public void shouldThrowExceptioForNoEmptyConstructorOrMapperConverter() throws MappingNotFoundException, MappingException, IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream originalOut = System.out; System.setOut(new PrintStream(out)); Mapper mapper = new Mapper(); mapper.add(FromWithConverter.class, ToWithConverter.class); mapper.build(); FromWithConverter from = new FromWithConverter(); ToWithConverter to = mapper.map(from); String outString = out.toString(); out.flush(); out.close(); System.setOut(originalOut); assertThat(to.getName()).isNull(); assertThat(outString).contains("WARNING - The converter for "+ConverterDateTimestamp2.class+" does not have a empty public contructor or a constructor accepting a Mapper instance; the converter is ignored."+System.lineSeparator()); } @Test public void shouldThrowExceptioForNoEmptyConstructorConverter() throws MappingNotFoundException, MappingException, IOException { Mapper mapper = new Mapper(); mapper.add(ConverterFrom.class, ConverterTo.class); mapper.add(Date.class, Timestamp.class, d->new Timestamp(d.getTime())); mapper.build(); ConverterFrom from = new ConverterFrom(); ConverterTo to = mapper.map(from); assertThat(to.getTimeStamp()).isNotNull(); assertThat(to.getTimeStamp().toInstant().toEpochMilli()).isEqualTo(from.getDate().getTime()); } @Test public void shouldApplyConverterInBuilder() throws MappingNotFoundException, MappingException { Mapper mapper = new Mapper(); mapper.addForClass(From.class,To.class).addMapping() .<Date>from("data4").transform(ConverterDateTimestamp.class).to("data4") .create(); mapper.build(); From from = new From(); To to = mapper.map(from); assertThat(to.getTimestamp1()).isNull(); assertThat(to.getTimestamp2()).isEqualTo(Timestamp.valueOf("2019-07-07 08:45:36")); assertThat(to.getTimestamp3()).isEqualTo(Timestamp.valueOf("2019-07-07 08:45:36")); assertThat(to.getTimestamp4()).isEqualTo(Timestamp.valueOf("2019-07-07 08:45:36")); } @Test public void shouldApplyConverterInBuilder2() throws MappingNotFoundException, MappingException { Mapper mapper = new Mapper(); mapper.addForClass(From.class, To.class).addMapping() .<Date>from("data4").transform(d->d).transform(ConverterDateTimestamp.class).to("data4") .create(); mapper.build(); From from = new From(); To to = mapper.map(from); assertThat(to.getTimestamp1()).isNull(); assertThat(to.getTimestamp2()).isEqualTo(Timestamp.valueOf("2019-07-07 08:45:36")); assertThat(to.getTimestamp3()).isEqualTo(Timestamp.valueOf("2019-07-07 08:45:36")); assertThat(to.getTimestamp4()).isEqualTo(Timestamp.valueOf("2019-07-07 08:45:36")); } @Test public void shouldThrowMappingExceptionInConverterInBuilder() throws MappingNotFoundException, MappingException { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream originalOut = System.out; System.setOut(new PrintStream(out)); Mapper mapper = new Mapper(); MappingException exception = assertThrows(MappingException.class, ()-> mapper.addForClass(From.class, To.class).addMapping() .<Date>from("data4").transform(ConverterDateTimestamp2.class).to("data4") .create()); System.setOut(originalOut); assertThat(exception.getMessage()).isEqualTo("Converter of "+ConverterDateTimestamp2.class+" cannot be instantiate."); } @Test public void shouldThrowMappingExceptionInConverterInBuilder2() throws MappingNotFoundException, MappingException { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream originalOut = System.out; System.setOut(new PrintStream(out)); Mapper mapper = new Mapper(); MappingException exception = assertThrows(MappingException.class, ()-> mapper.addForClass(From.class, To.class).addMapping() .<Date>from("data4").transform(d->d).transform(ConverterDateTimestamp2.class).to("data4") .create()); mapper.build(); System.setOut(originalOut); assertThat(exception.getMessage()).isEqualTo("Converter of "+ConverterDateTimestamp2.class+" cannot be instantiate."); } }
package com.example.mjunior.fiapimoveis.modelo; import java.io.Serializable; public class Imovel implements Serializable{ private Long id; private String contato; private String endereco; private String tipo; private Double nota; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getContato() { return contato; } public void setContato(String contato) { this.contato = contato; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public Double getNota() { return nota; } public void setNota(Double nota) { this.nota = nota; } @Override public String toString() { return getEndereco() + " nota: " + getNota(); } }
/* * 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 Tank_Game.GameFiles; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.io.BufferedReader; import java.io.FileReader; /** * * @author jrettinghouse */ public class Walls { BufferedImage wallTexture, wallTexture2; BufferedReader r; private int [][] walls; private int mapWidth, mapHeight; public Walls(String path) { try { wallTexture = ImageIO.read(Walls.class.getResource("/Tank_Wars_Resourses/Wall1.gif")); // load image wallTexture2 = ImageIO.read(Walls.class.getResource("/Tank_Wars_Resourses/Wall2.gif")); // load image r = new BufferedReader(new FileReader(path)); // load txt file what will create walls mapWidth = Integer.parseInt(r.readLine()); // first line read from walls.txt is width mapHeight = Integer.parseInt(r.readLine()); // second line read is height walls = new int[mapHeight][mapWidth]; System.out.println(mapHeight); System.out.println(mapWidth); for (int row = 0; row < mapHeight; row++){ String line = r.readLine(); String[] tokens = line.split("\\s+"); // delimits by whitespace " " for (int col = 0; col < mapWidth; col++){ // x,y coordinate for the walls that will be drawn will be represented by 1's adn 2's walls[row][col] = Integer.parseInt(tokens[col]); } } } catch (Exception e) { System.out.println(e); } } public void draw(Graphics2D g) { for (int x = 0; x < mapWidth; x++ ) { for (int y = 0; y < mapHeight; y++) { int wallHere = walls[x][y]; if (wallHere == 1) { g.drawImage(wallTexture, y*wallTexture.getHeight(), x*wallTexture.getWidth(), null); } if (wallHere == 2) { g.drawImage(wallTexture2, y*wallTexture.getHeight(), x*wallTexture.getWidth(), null); } } } } public void breakWallAt (int x, int y) { walls[x][y] = 0; } public void respawnWallAt (int x, int y) { walls[x][y] = 2; } public int[][] getWalls(){ return walls; } public int getPictureWidth(){ return wallTexture.getWidth(); } public int getPictureHieght(){ return wallTexture.getHeight(); } public int getMapHeight() { return mapHeight; } public int getMapWidth() { return mapWidth; } }
package cn.canlnac.onlinecourse.domain.interactor; import javax.inject.Inject; import cn.canlnac.onlinecourse.domain.executor.PostExecutionThread; import cn.canlnac.onlinecourse.domain.executor.ThreadExecutor; import cn.canlnac.onlinecourse.domain.repository.CommentRepository; import rx.Observable; /** * 获取指定评论使用用例. */ public class GetCommentUseCase extends UseCase { private final int commentId; private final CommentRepository commentRepository; @Inject public GetCommentUseCase( int commentId, CommentRepository commentRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread ) { super(threadExecutor, postExecutionThread); this.commentId = commentId; this.commentRepository = commentRepository; } @Override protected Observable buildUseCaseObservable() { return this.commentRepository.getComment(commentId); } }
package com.example.covid_19.Screen; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.example.covid_19.BerandaActivity; import com.example.covid_19.MainActivity; import com.example.covid_19.R; import com.example.covid_19.adaptercovid; import com.example.covid_19.model.CountriesItem; import com.example.covid_19.model.Global; import com.example.covid_19.model.Response; import com.example.covid_19.retrofit.RetrofitCOnfig; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; public class GlobalCovid extends AppCompatActivity { Global dunia=new Global(); List<CountriesItem>indo=new ArrayList<>(); String id; String date; CardView carddunia,cardindo; TextView txtkonfbaru,txttotalkonf,txtbarusembh,txttotalsembuh,txttotalkematian,txtkematianbaru,datedunia,dateindo; TextView indokonfbaru,indototkon,indototsembuh,indobarusembuh,indokematianbaru,indototalkematian; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_global_covid); //inisaialisasi dunia carddunia=findViewById(R.id.id_card_dunia); txtkonfbaru=findViewById(R.id.id_konfirmasi_baru_dunia); txttotalkonf=findViewById(R.id.id_total_konfirmasi_dunia); txttotalkematian=findViewById(R.id.id_total_kematian_dunia); txtbarusembh=findViewById(R.id.id_baru_Sembuuh_dunia); txttotalsembuh=findViewById(R.id.id_total_sembuh_dunia); txtkematianbaru=findViewById(R.id.id_kematian_baru_dunia); datedunia=findViewById(R.id.id_tanggal); dateindo=findViewById(R.id.id_tanggal_dunia); //inisialisasi indo indokonfbaru=findViewById(R.id.id_konfirmasi_baru_indo); indototkon=findViewById(R.id.id_total_konfirmasi_indo); indototsembuh=findViewById(R.id.id_total_sembuh_indo); indobarusembuh=findViewById(R.id.id_baru_Sembuuh_indo); indokematianbaru=findViewById(R.id.id_kematian_baru_indo); indototalkematian=findViewById(R.id.id_total_kematian_indo); //txtkonfbaru.setText(String.valueOf(dataglobal.get(3))); carddunia.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(GlobalCovid.this, MainActivity.class)); } }); getDataOnline(); getIDindo(); } private void getIDindo(){ } private void getDataOnline(){ final ProgressDialog progress=new ProgressDialog(GlobalCovid.this); progress.setMessage("Tunggu Sebentar..."); progress.show(); Call<Response> request= RetrofitCOnfig.getApiservice().ambildata(""); request.enqueue(new Callback<Response>() { @Override public void onResponse(Call<Response> call, retrofit2.Response<Response> response) { if (response.isSuccessful()){ dunia= response.body().getGlobal(); date=response.body().getDate(); indo=response.body().getCountries(); //ini untuk dunia String konfirmasibarudunia= String.valueOf(dunia.getNewConfirmed()); String totkonfirmasidunia= String.valueOf(dunia.getTotalConfirmed()); String totkematiandunia= String.valueOf(dunia.getTotalDeaths()); String barusembuhdunia= String.valueOf(dunia.getNewRecovered()); String totalsembuhdunia= String.valueOf(dunia.getTotalRecovered()); String kematianbaruduna= String.valueOf(dunia.getNewDeaths()); //ini untuk indonesia String konfbaruindo= String.valueOf(indo.get(77).getNewConfirmed()); String totalkonindo= String.valueOf(indo.get(77).getTotalConfirmed()); String totsembuhindo= String.valueOf(indo.get(77).getTotalRecovered()); String barusembuhindo= String.valueOf(indo.get(77).getNewRecovered()); String barumatiindo= String.valueOf(indo.get(77).getNewDeaths()); String totalkematianindo= String.valueOf(indo.get(77).getTotalDeaths()); String dateindonya= String.valueOf(indo.get(77).getDate()); //set untuk dunia txtkonfbaru.setText(konfirmasibarudunia); txttotalkonf.setText(totkonfirmasidunia); txttotalkematian.setText(totkematiandunia); txtbarusembh.setText(barusembuhdunia); txttotalsembuh.setText(totalsembuhdunia); txtkematianbaru.setText(kematianbaruduna); datedunia.setText(date.toLowerCase()); //set untuk indonesia indokonfbaru.setText(konfbaruindo); indototkon.setText(totalkonindo); indototsembuh.setText(totsembuhindo); indobarusembuh.setText(barusembuhindo); indokematianbaru.setText(barumatiindo); indototalkematian.setText(totalkematianindo); dateindo.setText(dateindonya.toLowerCase()); progress.dismiss(); }else { Toast.makeText(GlobalCovid.this, "Gagal Memuat", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Response> call, Throwable t) { Toast.makeText(GlobalCovid.this, "Ada kesalahan "+t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }
package com.sinotao.util.spring; import javax.servlet.ServletContext; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.web.context.ServletContextAware; /** * * 功能描述: 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext. * * @version 1.0.0 * @author tonglei */ public class SpringContextHolder implements ApplicationContextAware, ServletContextAware { private static ApplicationContext applicationContext; private static ServletContext servletContext; /** * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量. */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext; // NOSONAR } /** * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * 清除applicationContext静态变量. */ public static void cleanApplicationContext() { applicationContext = null; } private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder"); } } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ public static <T> T getBean(Class<T> clazz) { checkApplicationContext(); return applicationContext.getBean(clazz); } /** * 实现ServletContextAware接口的context注入函数, 将其存入静态变量. */ public void setServletContext(ServletContext servletContext) { SpringContextHolder.servletContext = servletContext; } /** * 取得存储在静态变量中的servletContext. */ public static ServletContext getServletContext() { checkServletContext(); return servletContext; } /** * 清除servletContext静态变量. */ public static void cleanServletContext() { servletContext = null; } private static void checkServletContext() { if (servletContext == null) { throw new IllegalStateException("servletContext未注入,请在servletContext.xml中定义SpringContextHolder"); } } public static String getAppAbsolutPath(){ return servletContext.getRealPath("/"); } }
package Controlador; import Modelo.Personal; import Modelo.PersonalDAO; import Modelo.Usuario; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import java.time.LocalDate; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Controlador extends HttpServlet { PersonalDAO dao = new PersonalDAO(); Usuario usu = new Usuario(); Personal per = new Personal(); protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Personal p = new Personal(); String acceso = ""; String action = request.getParameter("accion"); int id; id = Integer.parseInt(request.getParameter("id")); dao.eliminar(id); String nom = "Jonatan de Abreu"; String pas = "Admin"; request.setAttribute("nom", nom); request.setAttribute("pas", pas); List lista = dao.listar(); request.setAttribute("personal", lista); acceso = "recursos/vistas/Vistaadmin.jsp"; RequestDispatcher vista = request.getRequestDispatcher(acceso); vista.forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Personal p = new Personal(); String acceso = ""; String action = request.getParameter("accion"); if (action.equalsIgnoreCase("agregar")) { String nom = request.getParameter("txtnombre"); String dire = request.getParameter("txtdireccion"); String tlf = request.getParameter("txttlf"); String fecha = request.getParameter("txtfecha"); String cargo = request.getParameter("txtcargo"); String z_i = request.getParameter("txtz_i"); p.setNombre(nom); p.setDireccion(dire); p.setTlf(tlf); p.setFecha(fecha); p.setCargo(cargo); p.setZ_i(z_i); dao.add(p); String nomb = "Jonatan de Abreu"; String pas = "Admin"; request.setAttribute("nom", nomb); request.setAttribute("pas", pas); List lista = dao.listar(); request.setAttribute("personal", lista); acceso = "recursos/vistas/Vistaadmin.jsp"; } else if (action.equalsIgnoreCase("eliminar")) { int id; id = Integer.parseInt(request.getParameter("id")); dao.eliminar(id); acceso = "recursos/vistas/Vistaadmin.jsp"; } else if (action.equalsIgnoreCase("add")) { acceso = "recursos/vistas/Add.jsp"; } else if (action.equalsIgnoreCase("animales")) { acceso = "recursos/vistas/Animales.jsp"; } else if (action.equalsIgnoreCase("itinerarios")) { acceso = "recursos/vistas/Itinerarios.jsp"; } else if (action.equalsIgnoreCase("zona")) { acceso = "recursos/vistas/Zonas.jsp"; } else if (action.equalsIgnoreCase("atras")) { String nom = "Jonatan de Abreu"; String pas = "Admin"; request.setAttribute("nom", nom); request.setAttribute("pas", pas); List lista = dao.listar(); request.setAttribute("personal", lista); acceso = "recursos/vistas/Vistaadmin.jsp"; } else if (action.equalsIgnoreCase("vistae")) { acceso = "recursos/vistas/Vistaempleado.jsp"; } else if (action.equalsIgnoreCase("mapa")) { acceso = "recursos/vistas/Mapa.jsp"; } else if (action.equalsIgnoreCase("login")) { acceso = "recursos/vistas/Login.jsp"; } else if (action.equalsIgnoreCase("index")) { acceso = "index.jsp"; } else if (action.equalsIgnoreCase("salir")) { acceso = "recursos/vistas/Login.jsp"; } else if (action.equals("ingresar")) { String nom = request.getParameter("txtnombre"); String pas = request.getParameter("txtpas"); int r = 0; usu.setNom(nom); usu.setPass(pas); r = dao.validar(usu); if (r == 1 && usu.getPass().equals("Admin")) { request.setAttribute("nom", nom); request.setAttribute("pas", pas); List lista = dao.listar(); request.setAttribute("personal", lista); request.getRequestDispatcher("recursos/vistas/Vistaadmin.jsp").forward(request, response); } else if (r == 1) { request.setAttribute("nom", nom); request.setAttribute("pas", pas); List lista = dao.listar(); request.setAttribute("personal", lista); request.getRequestDispatcher("recursos/vistas/Vistaempleado.jsp").forward(request, response); } else { request.getRequestDispatcher("recursos/vistas/ErrorLog.jsp").forward(request, response); } } RequestDispatcher vista = request.getRequestDispatcher(acceso); vista.forward(request, response); } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package com.jy.Rabbit; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component @RabbitListener(queues = "q_hi") public class Recevier { @RabbitHandler public void RecevierHi(Object o){ System.out.println(o.toString()); } }
/******************************************************************************* * Copyright (C) 2013, 2014, International Business Machines Corporation * All Rights Reserved *******************************************************************************/ package com.ibm.streamsx.jms.exceptions; /** * This class is used for throwing exceptions * which comes during connection creation or * sending/receiving JMS Messages. * */ public class ConnectionException extends Exception { /** * */ private static final long serialVersionUID = 1L; public ConnectionException(String message) { super(message); } }
package com.toggleable.morgan.jeremyslist.ui; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.toggleable.morgan.jeremyslist.R; import com.toggleable.morgan.jeremyslist.fragments.RestaurantMapFragment; public class ResultsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Fragment fragment = null; Class fragmentClass = null; switch(item.getItemId()) { case R.id.action_settings: //show settings options break; case R.id.action_user_location_map: fragmentClass = RestaurantMapFragment.class; Log.i("fragmentClass: ", fragmentClass.toString()); break; default: //users action not recognized. Invoke super class to handle it fragmentClass = RestaurantMapFragment.class; } try { fragment = (Fragment) fragmentClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.activity_results_fragment, fragment).commit(); return true; } }
package edu.spring.springbootyaml.service; import edu.spring.springbootyaml.config.ApplicationVersion; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @Service public class PrintInfoService { private final String version; private final String buildNumber; private final String anyOtherInfo; public PrintInfoService( // Сюда подставится объект свойств, т.к. ApplicationVersion - @Component ApplicationVersion applicationVersion, // А можно и так получать @Value("${any.another.property}") String anyOtherInfo ) { this.version = applicationVersion.getVersion(); this.buildNumber = applicationVersion.getBuildNumber(); this.anyOtherInfo = anyOtherInfo; } public void printInfo() { System.out.println("version: " + version); System.out.println("buildNumber: " + buildNumber); System.out.println("any info: " + anyOtherInfo); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package com.hybris.backoffice.excel.importing; import static org.assertj.core.api.Assertions.assertThat; import de.hybris.platform.catalog.model.CatalogModel; import de.hybris.platform.core.model.product.ProductModel; import java.util.HashMap; import java.util.Map; import org.junit.Test; import com.hybris.backoffice.excel.data.Impex; import com.hybris.backoffice.excel.data.ImpexForType; import com.hybris.backoffice.excel.data.ImpexHeaderValue; public class DefaultImpexConverterTest { private final DefaultImpexConverter defaultImpexConverter = new DefaultImpexConverter(); @Test public void shouldEscapeValueWhenItContainsNewLineN() { // given final String value = "First line\nSecond line"; // when final String escapedValue = defaultImpexConverter.getValue(value); // then assertThat(escapedValue).isEqualTo("\"First line\nSecond line\""); } @Test public void shouldEscapeValueWhenItContainsNewLineRN() { // given final String value = "First line\r\nSecond line"; // when final String escapedValue = defaultImpexConverter.getValue(value); // then assertThat(escapedValue).isEqualTo("\"First line\r\nSecond line\""); } @Test public void shouldEscapeValueWhenItContainsSemicolon() { // given final String value = "First line;Second line"; // when final String escapedValue = defaultImpexConverter.getValue(value); // then assertThat(escapedValue).isEqualTo("\"First line;Second line\""); } @Test public void shouldNotEscapeValueWhenItContainsBoolean() { // given final Boolean value = Boolean.TRUE; // when final String escapedValue = defaultImpexConverter.getValue(value); // then assertThat(escapedValue).isEqualTo(value.toString()); } @Test public void shouldNotEscapeValueWhenItContainsNumber() { // given final Double value = 3.14; // when final String escapedValue = defaultImpexConverter.getValue(value); // then assertThat(escapedValue).isEqualTo(value.toString()); } @Test public void shouldNotEscapeValueWhenItContainsStringWithoutSpecialCharacters() { // given final String value = "First line and second line"; // when final String escapedValue = defaultImpexConverter.getValue(value); // then assertThat(escapedValue).isEqualTo(value); } @Test public void shouldPrepareHeaderWithoutSpecialAttributes() { // given final ImpexHeaderValue impexHeaderValue = new ImpexHeaderValue(ProductModel.CODE, false); // when final String headerAttribute = defaultImpexConverter.prepareHeaderAttribute(impexHeaderValue); // then assertThat(headerAttribute).isEqualTo(String.format("%s", ProductModel.CODE)); } @Test public void shouldPrepareHeaderWithUniqueAttribute() { // given final ImpexHeaderValue impexHeaderValue = new ImpexHeaderValue(ProductModel.CODE, true); // when final String headerAttribute = defaultImpexConverter.prepareHeaderAttribute(impexHeaderValue); // then assertThat(headerAttribute).isEqualTo(String.format("%s[unique=true]", ProductModel.CODE)); } @Test public void shouldPrepareHeaderWithLangAttribute() { // given final ImpexHeaderValue impexHeaderValue = new ImpexHeaderValue(ProductModel.CODE, false, "en"); // when final String headerAttribute = defaultImpexConverter.prepareHeaderAttribute(impexHeaderValue); // then assertThat(headerAttribute).isEqualTo(String.format("%s[lang=en]", ProductModel.CODE)); } @Test public void shouldPrepareHeaderWithUniqueAndLangAttributes() { // given final ImpexHeaderValue impexHeaderValue = new ImpexHeaderValue(ProductModel.CODE, true, "en"); // when final String headerAttribute = defaultImpexConverter.prepareHeaderAttribute(impexHeaderValue); // then assertThat(headerAttribute).isEqualTo(String.format("%s[unique=true,lang=en]", ProductModel.CODE)); } @Test public void shouldPrepareHeaderWithDateAttribute() { // given final ImpexHeaderValue impexHeaderValue = new ImpexHeaderValue(ProductModel.CODE, false, "", "M/d/yy h:mm a"); // when final String headerAttribute = defaultImpexConverter.prepareHeaderAttribute(impexHeaderValue); // then assertThat(headerAttribute).isEqualTo(String.format("%s[dateformat=M/d/yy h:mm a]", ProductModel.CODE)); } @Test public void shouldPrepareImpexHeader() { // given final ImpexForType impexForType = new ImpexForType(ProductModel._TYPECODE); impexForType.putValue(0, new ImpexHeaderValue(ProductModel.CODE, true), ""); impexForType.putValue(0, new ImpexHeaderValue(ProductModel.NAME, false, "en"), ""); // when final String impexHeader = defaultImpexConverter.prepareImpexHeader(impexForType); // then assertThat(impexHeader).isEqualTo("INSERT_UPDATE Product;code[unique=true];name[lang=en];\n"); } @Test public void shouldReturnTrueWhenAllUniqueValuesAreNotEmpty() { // given final Map<ImpexHeaderValue, Object> row = new HashMap<>(); row.put(new ImpexHeaderValue(ProductModel.CODE, true), "notEmptyValue"); row.put(new ImpexHeaderValue(ProductModel.NAME, false), "notEmptyValue"); row.put(new ImpexHeaderValue(ProductModel.DELIVERYTIME, false), null); row.put(new ImpexHeaderValue(ProductModel.DETAIL, false), ""); row.put(new ImpexHeaderValue(ProductModel.CATALOGVERSION, true), "notEmptyValue"); // when final boolean result = defaultImpexConverter.areUniqueAttributesPopulated(row); // then assertThat(result).isTrue(); } @Test public void shouldReturnFalseWhenNotAllUniqueValuesAreNotEmpty() { // given final Map<ImpexHeaderValue, Object> row = new HashMap<>(); row.put(new ImpexHeaderValue(ProductModel.CODE, true), "notEmptyValue"); row.put(new ImpexHeaderValue(ProductModel.NAME, false), "notEmptyValue"); row.put(new ImpexHeaderValue(ProductModel.DELIVERYTIME, false), null); row.put(new ImpexHeaderValue(ProductModel.DETAIL, false), ""); row.put(new ImpexHeaderValue(ProductModel.CATALOGVERSION, true), ""); // when final boolean result = defaultImpexConverter.areUniqueAttributesPopulated(row); // then assertThat(result).isFalse(); } @Test public void shouldGeneratedSingleLineForImpexScript() { // given final ImpexForType impexForType = new ImpexForType(ProductModel._TYPECODE); impexForType.putValue(0, new ImpexHeaderValue(ProductModel.CODE, true), "ProductCode"); impexForType.putValue(0, new ImpexHeaderValue(ProductModel.NAME, false, "en"), "ProductName"); // when final String singleRow = defaultImpexConverter.prepareImpexRows(impexForType); // then assertThat(singleRow).isEqualTo(";ProductCode;ProductName;"); } @Test public void shouldGeneratedMultiLineForImpexScript() { // given final ImpexForType impexForType = new ImpexForType(ProductModel._TYPECODE); impexForType.putValue(0, new ImpexHeaderValue(ProductModel.CODE, true), "First product code"); impexForType.putValue(0, new ImpexHeaderValue(ProductModel.NAME, false, "en"), "First product name"); impexForType.putValue(1, new ImpexHeaderValue(ProductModel.CODE, true), "Second product code"); impexForType.putValue(1, new ImpexHeaderValue(ProductModel.NAME, false, "en"), "Second product name"); // when final String singleRow = defaultImpexConverter.prepareImpexRows(impexForType); // then assertThat(singleRow).isEqualTo(";First product code;First product name;\n;Second product code;Second product name;"); } @Test public void shouldGeneratedMultiLineForImpexScriptWithEmptyNotUniqueValues() { // given final ImpexForType impexForType = new ImpexForType(ProductModel._TYPECODE); impexForType.putValue(0, new ImpexHeaderValue(ProductModel.CODE, true), "First product code"); impexForType.putValue(0, new ImpexHeaderValue(ProductModel.NAME, false, "en"), "First product name"); impexForType.putValue(1, new ImpexHeaderValue(ProductModel.CODE, true), "Second product code"); impexForType.putValue(1, new ImpexHeaderValue(ProductModel.NAME, false, "en"), ""); // when final String singleRow = defaultImpexConverter.prepareImpexRows(impexForType); // then assertThat(singleRow).isEqualTo(";First product code;First product name;\n;Second product code;;"); } @Test public void shouldGeneratedMultiLineForImpexScriptOnlyWithLinesWhichHaveAllUniqueValues() { // given final ImpexForType impexForType = new ImpexForType(ProductModel._TYPECODE); impexForType.putValue(0, new ImpexHeaderValue(ProductModel.CODE, true), "First product code"); impexForType.putValue(0, new ImpexHeaderValue(ProductModel.NAME, false, "en"), "First product name"); impexForType.putValue(1, new ImpexHeaderValue(ProductModel.CODE, true), ""); impexForType.putValue(1, new ImpexHeaderValue(ProductModel.NAME, false, "en"), ""); impexForType.putValue(1, new ImpexHeaderValue(ProductModel.CODE, true), "Third product code"); impexForType.putValue(1, new ImpexHeaderValue(ProductModel.NAME, false, "en"), "Third product name"); // when final String singleRow = defaultImpexConverter.prepareImpexRows(impexForType); // then assertThat(singleRow).isEqualTo(";First product code;First product name;\n;Third product code;Third product name;"); } @Test public void shouldGenerateWholeImpexScriptForSingleTypeCode() { // given final Impex impex = new Impex(); final ImpexForType impexForProduct = impex.findUpdates(ProductModel._TYPECODE); impexForProduct.putValue(0, new ImpexHeaderValue(ProductModel.CODE, true), "First product code"); impexForProduct.putValue(0, new ImpexHeaderValue(ProductModel.NAME, false, "en"), "First product name"); impexForProduct.putValue(1, new ImpexHeaderValue(ProductModel.CODE, true), "Second product code"); impexForProduct.putValue(1, new ImpexHeaderValue(ProductModel.NAME, false, "en"), "Second product name"); // when final String generatedImpex = defaultImpexConverter.convert(impex); // then assertThat(generatedImpex) .isEqualTo( "INSERT_UPDATE Product;code[unique=true];name[lang=en];\n;First product code;First product name;\n;Second product code;Second product name;\n\n"); } @Test public void shouldGenerateWholeImpexScriptForManyTypeCodes() { // given final Impex impex = new Impex(); final ImpexForType impexForProduct = impex.findUpdates(ProductModel._TYPECODE); impexForProduct.putValue(0, new ImpexHeaderValue(ProductModel.CODE, true), "First product code"); impexForProduct.putValue(0, new ImpexHeaderValue(ProductModel.NAME, false, "en"), "First product name"); impexForProduct.putValue(1, new ImpexHeaderValue(ProductModel.CODE, true), "Second product code"); impexForProduct.putValue(1, new ImpexHeaderValue(ProductModel.NAME, false, "en"), "Second product name"); final ImpexForType impexForCatalog = impex.findUpdates(CatalogModel._TYPECODE); impexForCatalog.putValue(0, new ImpexHeaderValue(CatalogModel.ID, true), "Clothing"); // when final String generatedImpex = defaultImpexConverter.convert(impex); // then assertThat(generatedImpex) .isEqualTo( "INSERT_UPDATE Catalog;id[unique=true];\n;Clothing;\n\nINSERT_UPDATE Product;code[unique=true];name[lang=en];\n;First product code;First product name;\n;Second product code;Second product name;\n\n"); } }
package algorithm.APSS.stakQueueDequeue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; /** * 입력을 고려하지 못했다. * 처음 입력이 ),},] 일 경우도 생각해야 한다. */ public class Brackets2 { static boolean isCorrect(String str) { Stack<Character> st = new Stack<>(); for (char s : str.toCharArray()) { switch (s) { case ')': if (!st.isEmpty() && st.peek() == '(') st.pop(); else return false; break; case '}': if (!st.isEmpty() && st.peek() == '{') st.pop(); else return false; break; case ']': if (!st.isEmpty() && st.peek() == '[') st.pop(); else return false; break; default: st.push(s); } } return st.isEmpty(); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int TC = Integer.parseInt(br.readLine().trim()); for (int tc = 0; tc < TC; tc++) { String str = br.readLine().trim(); System.out.println(isCorrect(str) ? "YES" : "NO"); } } }
package com.jack.jkbase.config; import java.util.Properties; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.crypto.hash.Md5Hash; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver; @Configuration public class ShiroConfig { private static String ALGORITHM_NAME=Md5Hash.ALGORITHM_NAME; private static int HashIterations = 1; @Bean public ShiroFilterChainDefinition shiroFilterChainDefinition() { DefaultShiroFilterChainDefinition chain = new DefaultShiroFilterChainDefinition(); //哪些请求可以匿名访问 chain.addPathDefinition("/signOut.do", "logout"); chain.addPathDefinition("/**/*.html", "anon"); chain.addPathDefinition("/mylogin.do", "anon"); chain.addPathDefinition("/error", "anon"); //除了以上的请求外,其它请求都需要登录 chain.addPathDefinition("/", "authc"); chain.addPathDefinition("/**/*.do", "authc"); chain.addPathDefinition("/**/*.page", "authc"); return chain; } @Bean(name="simpleMappingExceptionResolver") public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() { SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver(); Properties mappings = new Properties(); mappings.setProperty("DatabaseException", "databaseError");//数据库异常处理 mappings.setProperty("UnauthorizedException","403"); r.setExceptionMappings(mappings); // None by default r.setDefaultErrorView("moduleClosed"); // No default r.setExceptionAttribute("ex"); // Default is "exception" //r.setWarnLogCategory("example.MvcLogger"); // No default return r; } @Bean public HashedCredentialsMatcher hashedCredentialsMatcher(){ HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(ALGORITHM_NAME); hashedCredentialsMatcher.setHashIterations(HashIterations); return hashedCredentialsMatcher; } @Bean public DefaultWebSecurityManager securityManager(){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(myShiroRealm()); securityManager.setSessionManager(sessionManager()); return securityManager; } @Bean public MyShiroRealm myShiroRealm(){ MyShiroRealm r = new MyShiroRealm(); r.setCredentialsMatcher(hashedCredentialsMatcher()); return r; } @Bean public DefaultWebSessionManager sessionManager() { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); //设置url重新setSessionIdUrlRewritingEnabled值为false sessionManager.setSessionIdUrlRewritingEnabled(false); return sessionManager; } /** * * @param pwd * @param salt * @return */ public static String hashUserPwd(String pwd,String salt){ return new SimpleHash(ALGORITHM_NAME,pwd,null,HashIterations).toHex(); } /* public static void main(String[] args) { String salt = "9e77501e-725f-4d69-812e-56b0c2186f11"; System.out.println(ByteSource.Util.bytes(salt)); System.out.println(hashUserPwd("654321888",salt)); //b4f92a719c98cd13a50a117092f04250809a303ce0d63d5861b37e59d02d4b90 }*/ }
package com.espendwise.manta.web.tags; import java.io.Serializable; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTagSupport; import javax.servlet.jsp.tagext.TagSupport; import org.apache.log4j.Logger; import com.espendwise.manta.util.Utility; import com.espendwise.manta.web.util.AppI18nUtil; public class TabTag extends TagSupport { private static final Logger logger = Logger.getLogger(TabTag.class); protected static final String LAST_CELL = "tab-last-cell"; protected static final String FIRST_CELL = "tab-first-cell"; protected static final String LAST_ROW = "tab-last-row"; protected static final String ACTIVE = "tab-active"; protected static final String INACTIVE = "tab-inactive"; protected static final String EMPTY = ""; protected static final String SPACE = " "; protected static final String NEXT_LINE = "\n"; protected static final String PX = "px"; protected static final String CLEAR = "<div class=\"clear\"></div>"; protected static final String END_OF_LINE = "<div class=\"endline\" style=\"height:%1$s\"></div>" + ""; protected static final String TAB = "<div class=\"tab %1$s\">\n" + " <span class=\"content %2$s\">\n" + " <div class=\"left\"></div>\n" + " <div class=\"center\"><table style=\"width:1px;height:25px \"><tr><td style=\"vertical-align: middle;white-space: nowrap\"><a href=\"%4$s\">%3$s</a></td></tr></table></div>\n" + " <div class=\"right\"></div>\n" + " </span>\n" + " <div class=\"space\">%5$s</div>\n" + " </div>"; private String requestedPath; private String tabPath; private Tabs tabs; @Override public int doStartTag() throws JspException { logger.debug("doStartTag()=> requestedPath: "+requestedPath); this.tabs = new Tabs(); return BodyTagSupport.EVAL_PAGE; } @Override public int doEndTag() throws JspException { StringBuilder sb = new StringBuilder(); try { String basePath = getBasePath(); logger.debug("doEndTag()()=> basePath: "+basePath); for (int rowIndex = 0; rowIndex < tabs.size(); rowIndex++) { TabRow row = tabs.get(rowIndex); for (int cellIndex = 0; cellIndex < row.size(); cellIndex++) { TabCell cell = row.get(cellIndex); String active = getRequestedPath().startsWith(cell.getPath()) ? TabTag.ACTIVE : TabTag.INACTIVE; String lastRow = rowIndex == tabs.size() - 1 ? TabTag.LAST_ROW : TabTag.EMPTY; String lastCell = cellIndex == row.size() - 1 ? TabTag.LAST_CELL : TabTag.EMPTY ; String firstCell = cellIndex == 0? TabTag.FIRST_CELL : TabTag.EMPTY ; String message = AppI18nUtil.getMessage(cell.getName()); String s = TabTag.NEXT_LINE; String link = null; if (cell.isRenderLink()) { link = basePath + cell.getHref(); } else { link = ""; } s += String.format(TabTag.TAB, firstCell + TabTag.SPACE + lastRow + TabTag.SPACE + lastCell , active, message, link, rowIndex != tabs.size() - 1 && cellIndex == row.size() - 1 ? String.format(END_OF_LINE, ((tabs.size() - 1 - rowIndex) * 25) + PX) : TabTag.SPACE ); sb.append(s); } sb.append(TabTag.NEXT_LINE); sb.append(TabTag.CLEAR); } pageContext.getOut().write(sb.toString()); } catch (Exception e) { logger.error("doEndTag()=> " + e.getMessage(), e); throw new JspException(e.getMessage()); } return TagSupport.EVAL_PAGE; } public String getRequestedPath() { return requestedPath; } public void setRequestedPath(String requestedPath) { this.requestedPath = requestedPath; } @Override public void release() { super.release(); this.requestedPath = null; this.tabs = null; } public void addRow() { tabs.add(new TabRow()); } public void addCell(String name, String path, String href, boolean renderLink) { tabs.get(tabs.size()-1).add(new TabCell(name, path, href, renderLink)); } public Tabs getTabs() { return tabs; } private String getBasePath() throws Exception { String tabPath = getTabPath(); String pattern = tabPath.replace("*", "\\d{1,}"); String path = (String) pageContext.getRequest().getAttribute("javax.servlet.forward.request_uri"); if (Utility.isSet(path)) { Pattern p = Pattern.compile(pattern); Matcher matcher = p.matcher(path); if (matcher.find()) { return matcher.group(); } } return "#"; } private class Tabs extends ArrayList<TabRow> {} private class TabRow extends ArrayList<TabCell> {} private class TabCell implements Serializable { private String href; private String name; private String path; private boolean renderLink; public TabCell(String name, String path, String href, boolean renderLink) { this.name = name; this.path = path; this.href = href; this.renderLink = renderLink; } public String getPath() { return path; } public String getName() { return name; } public String getHref() { return href; } public boolean isRenderLink() { return renderLink; } } public String getTabPath() { return tabPath; } public void setTabPath(String tabPath) { this.tabPath = tabPath; } }
package com.example.iutassistant.NewActivities; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.example.iutassistant.R; public class New_Attendence_Teacher extends AppCompatActivity implements View.OnClickListener { CardView takeAttendence, attendenceList, details; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new__attendence__teacher); takeAttendence = findViewById(R.id.takeAttendenceId); attendenceList = findViewById(R.id.attendenceListId); details = findViewById(R.id.studentDetailsId); takeAttendence.setOnClickListener(this); attendenceList.setOnClickListener(this); details.setOnClickListener(this); } public void onClick(View view) { if(view.getId() == R.id.takeAttendenceId){ Intent intent = new Intent(getApplicationContext(),New_Take_Attendence.class); startActivity(intent); } else if(view.getId() == R.id.attendenceListId){ Intent intent = new Intent(getApplicationContext(),New_AttendenceList.class); startActivity(intent); } else if(view.getId() == R.id.studentDetailsId){ Intent intent = new Intent(getApplicationContext(),New_Attendence_Details.class); startActivity(intent); } } }
package com.example.myapplication.app; import android.Manifest; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v4.content.ContextCompat; import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionManager; import com.google.gson.Gson; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class AppComponent { private static final String PREFERENCES_NAME = "SmsGatewayPreferences"; private static final Gson GSON = new Gson(); public static class Permission { public static boolean canSendSms(Context context) { return ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED; } public static boolean canReadPhoneState(Context context) { return ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED; } // @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1) // public static void ddd(Context context){ // List<SubscriptionInfo> availableSimCards = getAvailableSimCards(context); // for (SubscriptionInfo subscriptionInfo : availableSimCards) { // String SimCarrierName = subscriptionInfo.getCarrierName().toString().trim(); // String SimDisplayName = subscriptionInfo.getDisplayName().toString().trim(); // String SimSerialNo = subscriptionInfo.getIccId().trim(); // int subscriptionId = subscriptionInfo.getSubscriptionId(); // String number = subscriptionInfo.getNumber(); // } // SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, 0); // String simId = settings.getString("SimSerialNo", null); // // SharedPreferences.Editor editor = settings.edit(); // editor.putStringSet("SimSerialNo", null); // } // // @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1) // public static Integer getSimSubscriptionIdByIccId(Context context, String iccId){ // List<SubscriptionInfo> availableSimCards = getAvailableSimCards(context); // for (SubscriptionInfo subscriptionInfo : availableSimCards) { //// String SimCarrierName = subscriptionInfo.getCarrierName().toString().trim(); //// String SimDisplayName = subscriptionInfo.getDisplayName().toString().trim(); //// int subscriptionId = subscriptionInfo.getSubscriptionId(); //// String number = subscriptionInfo.getNumber(); // String simSerialNo = subscriptionInfo.getIccId().trim(); // if(simSerialNo.equals(iccId)){ // return subscriptionInfo.getSubscriptionId(); // } // } // return null; // } } public static class Config { @SuppressLint("MissingPermission") @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1) public static List<SubscriptionInfo> getAvailableSimCards(Context context) { SubscriptionManager subscripManager = SubscriptionManager.from(context); return subscripManager.getActiveSubscriptionInfoList(); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1) public static List<String> getSimCardOptionByNumberList(Context context) { List<String> simCardOptionByNumberList = new ArrayList<>(); List<SubscriptionInfo> availableSimCards = getAvailableSimCards(context); for (SubscriptionInfo subscriptionInfo : availableSimCards) { // String SimDisplayName = subscriptionInfo.getDisplayName().toString().trim(); String number = subscriptionInfo.getNumber(); StringBuilder option = new StringBuilder() .append(number); // .append(SimDisplayName != null && SimDisplayName.length() > 0 ? " | " : "") // .append(SimDisplayName); simCardOptionByNumberList.add(option.toString()); } return simCardOptionByNumberList; } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1) public static List<String> getSimCardOptionByPositionList(Context context) { List<String> simCardOptionByNumberList = new ArrayList<>(); List<SubscriptionInfo> availableSimCards = getAvailableSimCards(context); for (SubscriptionInfo subscriptionInfo : availableSimCards) { int slotIndex = subscriptionInfo.getSimSlotIndex(); StringBuilder option = new StringBuilder() .append("SIM") .append(" ") .append(slotIndex + 1); simCardOptionByNumberList.add(option.toString()); } return simCardOptionByNumberList; } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1) public static Integer getPreferenceSubscriptionId(Context context) { int position = Preferences.getSimCardBy(context); if(position == 1){ //NUMBER List<SubscriptionInfo> availableSimCards = getAvailableSimCards(context); for (SubscriptionInfo subscriptionInfoTemp : availableSimCards) { String number = subscriptionInfoTemp.getNumber(); if(number.equals(Preferences.getSimCardOption(context))) { return subscriptionInfoTemp.getSubscriptionId(); } } } else if(position == 2){ //POSITION List<SubscriptionInfo> availableSimCards = getAvailableSimCards(context); for (SubscriptionInfo subscriptionInfoTemp : availableSimCards) { String number = new StringBuilder() .append("SIM") .append(" ") .append(subscriptionInfoTemp.getSimSlotIndex() + 1).toString(); if(number.equals(Preferences.getSimCardOption(context))){ return subscriptionInfoTemp.getSubscriptionId(); } } } return null; } } public static class Preferences { private static String IS_AUTO_STARTUP_KEY = "AUTO_STARTUP"; private static String SIM_CARD_BY_KEY = "SIM_CARD_BY"; private static String SIM_CARD_OPTION_KEY = "SIM_CARD_OPTION"; private static String FETCH_URL_KEY = "FETCH_URL"; private static String SENT_STATUS_URL_KEY = "SENT_STATUS_URL"; private static String DELIVERED_STATUS_URL_KEY = "DELIVERED_STATUS_URL"; private static String MESSAGE_LOG_URL_KEY = "MESSAGE_LOG_URL"; private static String INTERVAL_FETCH_REQUEST_KEY = "INTERVAL_FETCH_REQUEST"; public static boolean isAutoStartup(Context context){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); return settings.getBoolean(IS_AUTO_STARTUP_KEY, false); } public static void autoStartup(Context context, boolean value){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(IS_AUTO_STARTUP_KEY, value); editor.apply(); } public static int getSimCardBy(Context context){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); return settings.getInt(SIM_CARD_BY_KEY, 0); } public static void setSimCardBy(Context context, int value){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putInt(SIM_CARD_BY_KEY, value); editor.apply(); } public static String getSimCardOption(Context context){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); return settings.getString(SIM_CARD_OPTION_KEY, null); } public static void setSimCardOption(Context context, String value){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(SIM_CARD_OPTION_KEY, value); editor.commit(); } public static String getFetchUrl(Context context){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); return settings.getString(FETCH_URL_KEY, null); } public static void setFetchUrl(Context context, String value){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(FETCH_URL_KEY, value); editor.commit(); } public static String getSentStatusUrl(Context context){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); return settings.getString(SENT_STATUS_URL_KEY, null); } public static void setSentStatusUrl(Context context, String value){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(SENT_STATUS_URL_KEY, value); editor.commit(); } public static String getDeliveredStatusUrl(Context context){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); return settings.getString(DELIVERED_STATUS_URL_KEY, null); } public static void setDeliveredStatusUrl(Context context, String value){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(DELIVERED_STATUS_URL_KEY, value); editor.commit(); } public static String getMessageLogUrl(Context context){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); return settings.getString(MESSAGE_LOG_URL_KEY, null); } public static void setMessageLogUrl(Context context, String value){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(MESSAGE_LOG_URL_KEY, value); editor.commit(); } public static int getIntervalFetchRequest(Context context){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); return settings.getInt(INTERVAL_FETCH_REQUEST_KEY, 30); } public static void setIntervalFetchRequest(Context context, int value){ SharedPreferences settings = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putInt(INTERVAL_FETCH_REQUEST_KEY, value); editor.apply(); } } public static class Utils { public static <T> T getObjectFromJson(String input, Type type){ // Type type = new TypeToken<String>(){}.getType(); return GSON.fromJson(input, type); } } public static class Service { public static void start(Context context){ Intent appService = new Intent(context, AppService.class); context.startService(appService); } public static void stop(Context context){ Intent appService = new Intent(context, AppService.class); context.stopService(appService); } public static boolean isRunning(Context context, Class<?> claszz) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo serviceInfo : activityManager.getRunningServices(Integer.MAX_VALUE)) { if (serviceInfo.service.getClassName().equals(claszz.getName())) { return true; } } return false; } } }
/** **************************************************************************** * Copyright (c) The Spray Project. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Spray Dev Team - initial API and implementation **************************************************************************** */ package org.eclipselabs.spray.shapes.ui.quickfix; import java.util.List; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.resource.IEObjectDescription; import org.eclipse.xtext.resource.IResourceDescription; import org.eclipse.xtext.resource.IResourceDescriptions; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.ui.editor.model.IXtextDocument; import org.eclipse.xtext.util.concurrent.IUnitOfWork; import org.eclipse.xtext.validation.Issue; import org.eclipse.xtext.xbase.lib.IteratorExtensions; import org.eclipselabs.spray.styles.Gradient; import org.eclipselabs.spray.styles.GradientLayout; import org.eclipselabs.spray.styles.Style; import org.eclipselabs.spray.styles.StyleContainer; import org.eclipselabs.spray.styles.StyleLayout; import org.eclipselabs.spray.styles.StylesFactory; import org.eclipselabs.spray.styles.StylesPackage; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; public abstract class AbstractStyleDSLModificationJob extends IUnitOfWork.Void<XtextResource> { public enum ModificationJobType implements LinkingQuickfixModificationJob { STYLE, GRADIENT; public AbstractStyleDSLModificationJob create(final IXtextDocument shapeXtextDocument, final Issue issue) { AbstractStyleDSLModificationJob job = null; if (this == ModificationJobType.STYLE) { job = new StyleModificationJob(shapeXtextDocument, issue); } else if (this == ModificationJobType.GRADIENT) { job = new GradientModificationJob(shapeXtextDocument, issue); } return job; } @Override public URI getDSLURI(IResourceDescriptions dscriptions, URI uriToProblem) { final String spraySegment = uriToProblem.trimFragment().lastSegment(); final String lastSegment = spraySegment.substring(0, spraySegment.length() - ".shape".length()) + ".style"; final String uriToShapeFile = uriToProblem.trimFragment() .trimSegments(1) .appendSegment(lastSegment).toString(); List<IResourceDescription> filteredDescs = IteratorExtensions .toList(Iterables.filter( dscriptions.getAllResourceDescriptions(), new Predicate<IResourceDescription>() { public boolean apply(IResourceDescription desc) { return desc.getURI().trimFragment().toString() .equals(uriToShapeFile); } }).iterator()); URI uri = null; if (filteredDescs.size() > 0) { uri = filteredDescs.get(0).getURI(); List<IEObjectDescription> containers = IteratorExtensions .toList(filteredDescs .get(0) .getExportedObjectsByType( StylesPackage.Literals.STYLE_CONTAINER_ELEMENT) .iterator()); if (containers.size() > 0) { uri = containers.get(0).getEObjectURI(); } else { // no quick fix, when there is a [shape-filename].shape but with // empty content uri = null; } } else { // no quick fix, when there is no [shape-filename].shape resource uri = null; } return uri; } } private IXtextDocument shapeXtextDocument; private Issue issue; protected EObject newElement; protected AbstractStyleDSLModificationJob(final IXtextDocument shapeXtextDocument, final Issue issue) { AbstractStyleDSLModificationJob.this.shapeXtextDocument = shapeXtextDocument; AbstractStyleDSLModificationJob.this.issue = issue; } @Override public void process(XtextResource styleResource) throws Exception { StyleContainer styleContainer = null; for (EObject eo : styleResource.getContents()) { if (eo instanceof StyleContainer) { styleContainer = (StyleContainer) eo; break; } } if (styleContainer != null) { String elementName = shapeXtextDocument.get(issue.getOffset(), issue.getLength()); newElement = createNewElement(styleContainer, elementName); } } protected abstract EObject createNewElement(StyleContainer styleContainer, String elementName); private static class StyleModificationJob extends AbstractStyleDSLModificationJob { StyleModificationJob(IXtextDocument sprayXtextDocument, Issue issue) { super(sprayXtextDocument, issue); } @Override protected EObject createNewElement(StyleContainer styleContainer, String styleName) { Style style = StylesFactory.eINSTANCE.createStyle(); style.setName(styleName); StyleLayout styleLayout = StylesFactory.eINSTANCE.createStyleLayout(); style.setLayout(styleLayout); styleContainer.getStyleContainerElement().add(style); return style; } } private static class GradientModificationJob extends AbstractStyleDSLModificationJob { GradientModificationJob(IXtextDocument sprayXtextDocument, Issue issue) { super(sprayXtextDocument, issue); } @Override protected EObject createNewElement(StyleContainer styleContainer, String gradientName) { Gradient gradient = StylesFactory.eINSTANCE.createGradient(); gradient.setName(gradientName); GradientLayout gradientLayout = StylesFactory.eINSTANCE.createGradientLayout(); gradient.setLayout(gradientLayout); styleContainer.getStyleContainerElement().add(gradient); return gradient; } } public EObject getNewElement() { return newElement; } }
package com.stringprograms; public class StringLogicQuestion { public static void main(String[] args) { // TODO Auto-generated method stub String str = "a,b,c,d,+,-,*"; str=str.replaceAll(",", ""); String s1 = str.replaceAll("[^a-z]", ""); System.out.println(s1); String s2 = str.replaceAll("[a-z]", ""); System.out.println(s2); String rep = ""; int k=1,i=0,j=0; while(k<=s1.length()+s2.length()) { if(k%2!=0) { while(i<s1.length()) { rep = rep+s1.charAt(i); break; } i++; } else { while(j<s2.length()) { rep = rep+s2.charAt(j); break; } j++; } k++; } System.out.println(rep); } }
package org.training.controller.commands.authorization; import org.training.constants.URIConstants; import org.training.controller.commands.Command; import org.training.model.entities.User; import org.training.service.UserService; import org.training.service.impl.UserServiceImpl; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.ResourceBundle; import static org.training.constants.PageConstants.VIEW_SIGNIN_JSP; /** * Created by nicko on 1/26/2017. */ public class SignInCommand implements Command { @Override public String execute(HttpServletRequest request, HttpServletResponse response) { String login = request.getParameter("login"); String password = request.getParameter("password"); if(!isInputValid(login,password)){ request.setAttribute("error",ResourceBundle.getBundle("messages").getString("invalidInputError")); return VIEW_SIGNIN_JSP; } UserService userService = UserServiceImpl.getInstance(); User existingUser = userService.login(login, password); if (existingUser != null) { HttpSession session = request.getSession(); session.setAttribute("id", existingUser.getId()); session.setAttribute("login", existingUser.getLogin()); session.setAttribute("role", existingUser.getRole().toString()); session.setAttribute("balance", existingUser.getBalance()); return URIConstants.INDEX; } request.setAttribute("error", ResourceBundle.getBundle("messages").getString("userExistError")); return VIEW_SIGNIN_JSP; } private Boolean isInputValid(String login, String password) { return !(login.isEmpty() || password.isEmpty()); } }
package com.tencent.mm.plugin.appbrand.ui; import android.content.Intent; import android.view.MenuItem; import com.tencent.mm.plugin.appbrand.jsapi.op_report.AppBrandOpReportLogic.AppBrandOnOpReportStartEvent; import com.tencent.mm.plugin.appbrand.n; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.n.d; import java.util.Locale; class AppBrandProfileUI$4 implements d { final /* synthetic */ AppBrandProfileUI gvm; AppBrandProfileUI$4(AppBrandProfileUI appBrandProfileUI) { this.gvm = appBrandProfileUI; } public final void onMMMenuItemSelected(MenuItem menuItem, int i) { switch (menuItem.getItemId()) { case 1: if (AppBrandProfileUI.b(this.gvm) == null) { x.e("MicroMsg.AppBrandProfileUI", "wxaExposedParams is null"); return; } Intent intent = new Intent(); String a = n.a(AppBrandProfileUI.b(this.gvm)); x.i("MicroMsg.AppBrandProfileUI", "wxaExposedParams:%s", new Object[]{AppBrandProfileUI.b(this.gvm).toString()}); x.v("MicroMsg.AppBrandProfileUI", "KRawUrl " + a); intent.putExtra("rawUrl", a); intent.putExtra("forceHideShare", true); com.tencent.mm.bg.d.b(this.gvm, "webview", ".ui.tools.WebViewUI", intent); AppBrandProfileUI.a(this.gvm, 7, 1); if (AppBrandProfileUI.b(this.gvm).bJu == 3) { AppBrandOnOpReportStartEvent.tV(AppBrandProfileUI.d(this.gvm).appId); return; } return; case 2: com.tencent.mm.bg.d.b(this.gvm, "appbrand", ".ui.AppBrandAuthorizeUI", new Intent(this.gvm, AppBrandAuthorizeUI.class).putExtra("key_username", AppBrandProfileUI.e(this.gvm))); AppBrandProfileUI.a(this.gvm, 10, 1); return; case 3: com.tencent.mm.bg.d.b(this.gvm, "webview", ".ui.tools.WebViewUI", new Intent().putExtra("rawUrl", String.format(Locale.US, "https://mp.weixin.qq.com/mp/wapreportwxadevlog?action=get_page&appid=%s#wechat_redirect", new Object[]{AppBrandProfileUI.b(this.gvm).appId})).putExtra("forceHideShare", true)); return; default: return; } } }
package com.apprisingsoftware.xmasrogue.io; import com.apprisingsoftware.util.ArrayUtil; import com.apprisingsoftware.xmasrogue.util.Coord; import java.awt.Color; import java.util.Collection; import java.util.Collections; public final class LabelScreen implements AsciiScreen { public enum Alignment { LEFT, RIGHT, CENTER } private final int width; private final Color bgColor; private final Alignment align; private Message message; private boolean hasBeenUpdated; public LabelScreen(int width, Color bgColor, Alignment alignment) { this.width = width; this.bgColor = bgColor; this.align = alignment; hasBeenUpdated = true; } public void postMessage(Message message) { if (message.getText().length() > width) throw new IllegalArgumentException(String.format("\"%s\" is too long of a message (more than %d characters)", message.getText(), width)); this.message = message; hasBeenUpdated = true; } @Override public AsciiTile getTile(int x, int y) { int mx; switch (align) { case LEFT: mx = x; break; case RIGHT: mx = x - (width - message.getText().length()); break; case CENTER: mx = Math.floorDiv(2 * x + message.getText().length() - width, 2); break; default: throw new AssertionError(); } if (mx >= 0 && mx < message.getText().length()) { return new AsciiTile(message.getText().charAt(mx), message.getActiveColor(), bgColor); } else { return new AsciiTile(' ', Color.BLACK, bgColor); } } @Override public boolean isTransparent(int x, int y) { return !inBounds(x, y); } @Override public Collection<Coord> getUpdatedTiles() { if (hasBeenUpdated) { hasBeenUpdated = false; return ArrayUtil.cartesianProduct(width, 1, (x, y) -> new Coord(x, y)); } else return Collections.emptyList(); } @Override public int getWidth() { return width; } @Override public int getHeight() { return 1; } }
import java.util.ArrayList; /* * 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. */ /** * Program written by Joseph Straceski. * @author Joseph Straceski * Contact at web: <https://github.com/Crepox> * e-mail: IpwndU360@gmail.com */ public class Container { ArrayList<Container> children = new ArrayList<Container>(); ArrayList<Line> lines = new ArrayList<Line>(); ArrayList<Vector3f> points = new ArrayList<Vector3f>(); Vector3f rot = new Vector3f(); Vector3f position = new Vector3f(); }
package com.hk.movie.feign; import com.hk.config.UserFeignConfiguration; import com.hk.user.vo.UserVo; import feign.Param; import feign.RequestLine; import org.springframework.cloud.netflix.feign.FeignClient; /** * @author huangkai * @date 2018-6-4 20:25 */ @FeignClient(value = "user-service", configuration = UserFeignConfiguration.class) public interface UserFeignClient { /** * 使用 Feign * * @param id * @return */ @RequestLine("GET /user/{id}") UserVo getById(@Param("id") Long id); /** * 使用 POST 请求,如果是复杂对象,服务调用者需要使用 @RequqstBody 来接收 * * @param userVo * @return */ @RequestLine("POST /user/save") UserVo saveUser(UserVo userVo); /** * 复杂对象必须使用 POST调用,此方法使用GET,会报错 * * @param userVo * @return */ @RequestLine("GET /user/get") UserVo getUser(UserVo userVo); }