text
stringlengths 10
2.72M
|
|---|
package de.jmda.app.xstaffr.client.fx.edit.candidate;
import java.util.HashSet;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import de.jmda.app.xstaffr.client.fx.XStaffrServiceProviderJPASE;
import de.jmda.app.xstaffr.common.domain.Candidate;
import de.jmda.app.xstaffr.common.service.XStaffrService;
import de.jmda.core.cdi.event.ActionOnEvent;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.HBox;
public class CandidateEditorController implements CandidateEditorService
{
private enum Mode { SELECT, EDIT, NEW };
private final static Logger LOGGER = LogManager.getLogger(CandidateEditorController.class);
@FXML private TableView<CandidateTableWrapper> tblVw;
@FXML private HBox hbx;
@FXML private Button btnRemove;
@FXML private TextField txtFldFilter;
@FXML private TitledPane ttldPnDetails;
@FXML private TextField txtFldFirstName;
@FXML private TextField txtFldLastName;
@FXML private TextField txtFldUniqueName;
@FXML private TextArea txtAreaNotes;
@FXML private Button btnEdit;
@FXML private Button btnUpdate;
@FXML private Button btnNew;
@FXML private Button btnCreate;
@FXML private Button btnCancel;
private XStaffrService xStaffrService;
private ObservableList<CandidateTableWrapper> tableWrappers;
private FilteredList<CandidateTableWrapper> tableWrappersFiltered;
private ObjectProperty<Mode> mode = new SimpleObjectProperty<>();
private ObjectProperty<Candidate> selected = new SimpleObjectProperty<>();
@FXML private void initialize()
{
LOGGER.debug("initialising");
xStaffrService = XStaffrServiceProviderJPASE.instance().provide();
selected.addListener((obs, old, newValue) -> onSelectedChanged(newValue));
mode.addListener((obs, old, newValue) -> onModeChanged(newValue));
mode.set(Mode.SELECT);
ttldPnDetails.setExpanded(true);
initTable();
initTableControlBar();
initDetails();
reload();
}
private void initTable()
{
TableColumn<CandidateTableWrapper, String> tcLastName = new TableColumn<>("last name");
tcLastName.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getLastName()));
TableColumn<CandidateTableWrapper, String> tcFirstName = new TableColumn<>("first name");
tcFirstName.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getFirstName()));
TableColumn<CandidateTableWrapper, String> tcUniqueName = new TableColumn<>("unique name");
tcUniqueName.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getUniqueName()));
tblVw.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
tblVw
.getSelectionModel()
.selectedItemProperty().addListener((obs, old, newValue) -> onTableSelectionChanged(newValue));
tblVw.getColumns().add(tcLastName);
tblVw.getColumns().add(tcFirstName);
tblVw.getColumns().add(tcUniqueName);
}
private void initTableControlBar()
{
btnRemove.setOnAction(e -> onBtnRemove());
txtFldFilter.textProperty().addListener((obs, old, newValue) -> onFilterTextChanged(newValue));
}
private void initDetails()
{
ttldPnDetails.setExpanded(true);
btnEdit.setOnAction(e -> onBtnEdit());
btnUpdate.setOnAction(e -> onBtnUpdate());
btnNew.setOnAction(e -> onBtnNew());
btnCreate.setOnAction(e -> onBtnCreate());
btnCancel.setOnAction(e -> onBtnCancel());
}
private Set<CandidateTableWrapper> toTableWrappers(Set<Candidate> candidates)
{
Set<CandidateTableWrapper> result = new HashSet<>();
candidates.forEach(candidate -> result.add(new CandidateTableWrapper(candidate)));
return result;
}
private Set<Candidate> tableWrappersToSet()
{
Set<Candidate> result = new HashSet<>();
tableWrappers.forEach(tableWrapper -> result.add(tableWrapper.getCandidate()));
return result;
}
@Override public void reload()
{
tableWrappers = FXCollections.observableArrayList(toTableWrappers(xStaffrService.candidates()));
// wrap observable list in a filtered list, display all initially
tableWrappersFiltered = new FilteredList<>(tableWrappers, p -> true);
// wrap filtered list in a sorted list
SortedList<CandidateTableWrapper> sortedList = new SortedList<>(tableWrappersFiltered);
// sort the list in the same way the table is sorted (click on headers)
sortedList.comparatorProperty().bind(tblVw.comparatorProperty());
tblVw.setItems(sortedList);
}
private void onTableSelectionChanged(CandidateTableWrapper newValue)
{
if (newValue == null)
{
selected.set(null);
}
else
{
selected.set(newValue.getCandidate());
}
btnEdit.setDisable(selected.get() == null);
}
private void onSelectedChanged(Candidate newValue)
{
if (newValue == null)
{
clearDetails();
}
else
{
updateDetails(newValue);
}
}
private void onModeChanged(Mode newValue)
{
if (newValue == Mode.SELECT)
{
setDetailsReadOnly(true);
tblVw.setDisable(false);
hbx.setDisable(false); // enable remove button and filter
btnEdit.setDisable(selected.get() == null);
btnUpdate.setDisable(true);
btnNew.setDisable(false);
btnCreate.setDisable(true);
btnCancel.setDisable(true);
}
else if (newValue == Mode.EDIT)
{
setDetailsReadOnly(false);
tblVw.setDisable(true);
hbx.setDisable(true); // disable remove button and filter
txtFldFilter.setText("");
txtFldFirstName.requestFocus();
btnEdit.setDisable(true);
btnUpdate.setDisable(false);
btnNew.setDisable(true);
btnCreate.setDisable(true);
btnCancel.setDisable(false);
}
else if (newValue == Mode.NEW)
{
clearDetails();
setDetailsReadOnly(false);
tblVw.setDisable(true);
hbx.setDisable(true); // disable remove button and filter
txtFldFilter.setText("");
txtFldFirstName.requestFocus();
btnEdit.setDisable(true);
btnUpdate.setDisable(true);
btnNew.setDisable(true);
btnCreate.setDisable(false);
btnCancel.setDisable(false);
}
}
private void onFilterTextChanged(String filterExpression)
{
tableWrappersFiltered.setPredicate(candidateTableWrapper -> applyFilterFor(candidateTableWrapper, filterExpression));
}
private void onBtnRemove()
{
CandidateTableWrapper selectedItem = tblVw.getSelectionModel().getSelectedItem();
if (selectedItem == null) return;
// remove candidate in db
xStaffrService.deleteCandidate(selectedItem.getCandidate());
tableWrappers.remove(selectedItem);
ActionOnEvent.fire(new CandidatesChanged(this, tableWrappersToSet()));
}
private void onBtnEdit() { mode.set(Mode.EDIT); }
private void onBtnUpdate()
{
Candidate candidate = selected.get();
if (candidate == null) return;
candidate.setFirstName(txtFldFirstName.getText());
candidate.setLastName(txtFldLastName.getText());
candidate.setUniqueName(txtFldUniqueName.getText());
candidate.setText(txtAreaNotes.getText());
// update candidate in db
xStaffrService.updateCandidate(candidate);
// update candidate in table
tblVw.refresh();
ActionOnEvent.fire(new CandidatesChanged(this, tableWrappersToSet()));
mode.set(Mode.SELECT);
}
private void onBtnNew() { mode.set(Mode.NEW); }
private void onBtnCreate()
{
Candidate candidate = new Candidate(txtFldLastName.getText(), txtFldFirstName.getText(), txtFldUniqueName.getText());
candidate.setText(txtAreaNotes.getText());
xStaffrService.persistCandidate(candidate);
CandidateTableWrapper candidateTableWrapper = new CandidateTableWrapper(candidate);
tableWrappers.add(candidateTableWrapper);
ActionOnEvent.fire(new CandidatesChanged(this, tableWrappersToSet()));
tblVw.getSelectionModel().select(candidateTableWrapper);
mode.set(Mode.SELECT);
}
private void onBtnCancel()
{
updateDetails(selected.get());
setDetailsReadOnly(true);
tblVw.setDisable(false);
mode.set(Mode.SELECT);
}
private void clearDetails()
{
txtFldFirstName.setText("");
txtFldLastName.setText("");
txtFldUniqueName.setText("");
txtAreaNotes.setText("");
}
private void setDetailsReadOnly(boolean flag)
{
txtFldFirstName.setEditable(!flag);
txtFldLastName.setEditable(!flag);
txtFldUniqueName.setEditable(!flag);
txtAreaNotes.setEditable(!flag);
}
private void updateDetails(Candidate newValue)
{
txtFldFirstName.setText(newValue.getFirstName());
txtFldLastName.setText(newValue.getLastName());
txtFldUniqueName.setText(newValue.getUniqueName());
txtAreaNotes.setText(newValue.getText());
}
private boolean applyFilterFor(CandidateTableWrapper candidateTableWrapper, String filterExpression)
{
// if filterExpression is empty all candidates match
if (filterExpression == null || filterExpression.isEmpty()) return true;
String lowerCaseFilterExpression = filterExpression.toLowerCase();
// check first name
if (candidateTableWrapper.getCandidate().getFirstName().toLowerCase().contains(lowerCaseFilterExpression)) return true;
// check last name
else if (candidateTableWrapper.getCandidate().getLastName().toLowerCase().contains(lowerCaseFilterExpression)) return true;
// candidate does not match
return false;
}
}
|
/*
* 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.beweb.lunel.programmation.exosEnVrac.algo;
/**
*
* @author lowas
*/
public class Exercice14 {
public static void launch(){
System.out.println("Exo 14 : (Blague) ");
}
}
|
package com.jovhengshuapps.aquainfinity;
import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import com.ericalarcon.basicframework.Templates.BFMenu;
import com.ericalarcon.basicframework.Templates.BFMenuItem;
import com.ericalarcon.basicframework.Templates.NavigationActivity;
public class MainActivity extends NavigationActivity {
@Override
public Fragment firstFragment() {
//return the first fragment that will be shown
//jump to the TabsFragment of ListFragment sections
//of this document to see how to do it
//(or you can create your own simple Fragment, of course)
BFMenu menu1 = new BFMenu();
// menu1.addItem(new BFMenuItem("View Customer Details",
// R.mipmap.dummy_file_icon,
// BFMenuItem.BFMenuItemType.SHOW_AS_MENUITEM,
// new BFMenuItem.BFMenuItemListener() {
// @Override
// public void onClick() {
//
// }
// }));
// menu1.addItem(new BFMenuItem("Take New Order",
// R.mipmap.dummy_file_icon,
// BFMenuItem.BFMenuItemType.SHOW_AS_MENUITEM,
// new BFMenuItem.BFMenuItemListener() {
// @Override
// public void onClick() {
//
// }
// }));
// menu1.addItem(new BFMenuItem("View Transaction History",
// R.mipmap.dummy_file_icon,
// BFMenuItem.BFMenuItemType.SHOW_AS_MENUITEM,
// new BFMenuItem.BFMenuItemListener() {
// @Override
// public void onClick() {
//
// }
// }));
this.addActionBarMenu(menu1);
return new ScanCustomerPageFragment(this);
}
@Override
public Boolean showBackButtonInFirstFragment() {
//show back button already in the first Fragment
//set to True if this activity is called by another Activity
//the back button will then pop back to the previous Activity
return false;
}
@Override
public Boolean showMasterDetailLayoutInTablets() {
//set to false if you don't want a master-detail layout in tablets
return false;
}
}
|
package m.imtsoft.todayspilates.domain.user;
import java.util.List;
import java.util.Map;
public interface UserMapper {
List getUser();
List loginUser(Map<String, Object> parameter);
User getUserInfo(Map<String, Object> parameter);
List existUserInStor(Map<String, Object> parameter);
}
|
package com.tencent.mm.ui.chatting.gallery;
import com.tencent.mm.ui.chatting.gallery.ImageGalleryUI.19;
class ImageGalleryUI$19$2 implements Runnable {
final /* synthetic */ 19 tWr;
ImageGalleryUI$19$2(19 19) {
this.tWr = 19;
}
public final void run() {
this.tWr.tWn.finish();
this.tWr.tWn.overridePendingTransition(0, 0);
}
}
|
package inheritance.access;
public class AccountTest {
public static void main(String[] args) {
SavingAccount myAccount = new SavingAccount("°¹Î°æ",233111,0.33);
myAccount.deposit(400000);
myAccount.withdraw(30000);
myAccount.checkBalance();
System.out.println(myAccount.name);
System.out.println(myAccount.open);
System.out.println(myAccount.number);
// System.out.println(myAccount.Balance);
}
}
|
///*
// * [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.operations.order.converters.populator;
//
//import de.hybris.platform.commercefacades.user.data.CountryData;
//import de.hybris.platform.converters.Populator;
//import de.hybris.platform.core.model.c2l.CountryModel;
//import de.hybris.platform.servicelayer.dto.converter.ConversionException;
//
//import org.springframework.core.convert.converter.Converter;
//import org.springframework.util.Assert;
//
////import com.cnk.travelogix.common.core.cart.data.SectorData;
//import com.cnk.travelogix.common.facades.product.data.flight.AirportData;
//import com.cnk.travelogix.masterdata.core.iata.model.AirportModel;
//import com.cnk.travelogix.product.common.core.model.SectorModel;
//
//
///**
// * This populator is used for populate Sector model data into Sector DTO
// *
// * @author C5244543 (Shivraj)
// */
//public class SectorPopulator implements Populator<SectorModel, SectorData>
//{
// private Converter<AirportModel, AirportData> airportConverter;
// private Converter<CountryModel, CountryData> countryConverter;
//
// @Override
// public void populate(final SectorModel source, final SectorData target) throws ConversionException
// {
// Assert.notNull(source, "Parameter source cannot be null.");
// Assert.notNull(target, "Parameter target cannot be null.");
// if(source.getFromCountry()!=null)
// {
// target.setFromCountry(countryConverter.convert(source.getFromCountry()));
// }
// if(source.getFromCity()!=null)
// {
// target.setFromCity(airportConverter.convert(source.getFromCity()));
// }
// if(source.getToCountry()!=null)
// {
// target.setToCountry(countryConverter.convert(source.getToCountry()));
// }
// if(source.getToCity()!=null)
// {
// target.setToCity(airportConverter.convert(source.getToCity()));
// }
//
// }
//
// /**
// * @return the airportConverter
// */
// public Converter<AirportModel, AirportData> getAirportConverter()
// {
// return airportConverter;
// }
//
// /**
// * @param airportConverter
// * the airportConverter to set
// */
// public void setAirportConverter(final Converter<AirportModel, AirportData> airportConverter)
// {
// this.airportConverter = airportConverter;
// }
//
// /**
// * @return the countryConverter
// */
// public Converter<CountryModel, CountryData> getCountryConverter()
// {
// return countryConverter;
// }
//
// /**
// * @param countryConverter
// * the countryConverter to set
// */
// public void setCountryConverter(final Converter<CountryModel, CountryData> countryConverter)
// {
// this.countryConverter = countryConverter;
// }
//
//}
|
package kz.kbtu.study.course;
import kz.kbtu.study.throwable.CreditOverflow;
import java.util.List;
public interface ManagingCourses {
List<Course> getCourses();
void addCourse(Course course) throws CreditOverflow;
}
|
package com.example.l03.projektpaszport;
import java.io.Serializable;
import java.sql.Time;
/**
* Created by Bartek on 2016-10-24.
*/
public class Lekarstwo implements Serializable{
private Integer id_lekarstwo;
private String godzina;
private String ilosc;
private String sposob_zazycia;
private String zdjecie;
Lekarstwo(
Integer id_lekarstwo,
String godzina,
String ilosc,
String sposob_zazycia,
String zdjecie
){
this.id_lekarstwo = id_lekarstwo;
this.godzina = godzina;
this. ilosc = ilosc;
this. sposob_zazycia = sposob_zazycia;
this. zdjecie = zdjecie;
}
public Integer getId_lekarstwo() {
return id_lekarstwo;
}
public void setId_lekarstwo(Integer id_lekarstwo) {
this.id_lekarstwo = id_lekarstwo;
}
public String getGodzina() {
return godzina;
}
public void setGodzina(String godzina) {
this.godzina = godzina;
}
public String getIlosc() {
return ilosc;
}
public void setIlosc(String ilosc) {
this.ilosc = ilosc;
}
public String getSposob_zazycia() {
return sposob_zazycia;
}
public void setSposob_zazycia(String sposob_zazycia) {
this.sposob_zazycia = sposob_zazycia;
}
public String getZdjecie() {
return zdjecie;
}
public void setZdjecie(String zdjecie) {
this.zdjecie = zdjecie;
}
public Lekarstwo returnObj(){
return this;
}
}
|
package com.lxy.basic;
import java.util.Scanner;
/**
* @author menglanyingfei
* @date 2017-3-7
* ?
*/
public class Main24_SimulationOfArray {
private static int v1;
private static int v2;
private static int t;
private static int s;
private static int l;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
v1 = sc.nextInt();
v2 = sc.nextInt();
t = sc.nextInt();
s = sc.nextInt();
l = sc.nextInt();
sc.close();
run(0, 0, 0, 0);
}
/**
*
* @param times 经过的秒数
* @param rl 兔子经过的距离
* @param tl 乌龟经过的距离
* @param sLeft 兔子休息剩余时间
*/
public static void run(int times, int rl, int tl, int sLeft){
if(sLeft == 0){
if(rl - tl >= t){
sLeft = s-1; //这一秒直接用掉,告诉下一次还剩多少秒
}else{
rl += v1;
}
}else{
//兔子这一秒需要休息
sLeft--;
}
tl += v2;
times++; //这一秒用掉
if(rl == l && tl == l){
System.out.println("D");
System.out.println(times);
return;
}
if(rl == l && tl != l){
System.out.println("R");
System.out.println(times);
return;
}
if(tl == l&& rl != l){
System.out.println("T");
System.out.println(times);
return;
}
run(times, rl, tl, sLeft);
}
}
|
package com.gauro.rabbitmqproducer.producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/**
* @author Chandra
*/
@Service
@Slf4j
public class FixedRateProducer {
private final RabbitTemplate rabbitTemplate;
private static int i=0;
public FixedRateProducer(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
@Scheduled(fixedRate = 500)
public void sendMessage(){
i++;
log.info("Fixed Rate "+i);
rabbitTemplate.convertAndSend("course.fixedrate"," Fixed Rate :"+i);
}
}
|
package chapter13.Exercise13_19;
import java.math.BigInteger;
public class Rational extends Number implements Comparable<Rational> {
private BigInteger numerator;
private BigInteger denominator;
public Rational() {
this(0, 1);
}
public Rational(long numerator, long denominator) {
this(new BigInteger(numerator + ""), new BigInteger(denominator + ""));
}
public Rational(BigInteger numerator, BigInteger denominator) {
BigInteger gcd = gcd(numerator, denominator);
this.numerator = new BigInteger(numerator.divide(gcd).multiply(
(denominator.compareTo(BigInteger.ZERO) > 0) ? BigInteger.ONE : new BigInteger(-1 + "")) + "");
this.denominator = new BigInteger(denominator.abs().divide(gcd) + "");
}
private static BigInteger gcd(BigInteger n, BigInteger d) {
BigInteger n1 = n.abs();
BigInteger n2 = d.abs();
BigInteger gcd = BigInteger.ONE;
for (BigInteger k = BigInteger.ONE; k.compareTo(n1) <= 0 && k.compareTo(n2) <= 0; k = k.add(BigInteger.ONE)) {
if (n1.mod(k).equals(BigInteger.ZERO) && n2.mod(k).equals(BigInteger.ZERO))
gcd = k;
}
return gcd;
}
public BigInteger getNumerator() {
return numerator;
}
public BigInteger getDenominator() {
return denominator;
}
public Rational add(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator())
.add(denominator.multiply(secondRational.getNumerator()));
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
public Rational subtract(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator())
.subtract(denominator.multiply(secondRational.getNumerator()));
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
public Rational multiply(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getNumerator());
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
public Rational divide(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator());
BigInteger d = denominator.multiply(secondRational.getNumerator());
return new Rational(n, d);
}
@Override
public String toString() {
if (denominator.equals(BigInteger.ONE))
return numerator.toString() + "";
else
return numerator + "/" + denominator;
}
@Override
public boolean equals(Object other) {
if ((this.subtract((Rational) (other))).getNumerator().equals(BigInteger.ZERO))
return true;
else
return false;
}
@Override
public int intValue() {
return (int) doubleValue();
}
@Override
public float floatValue() {
return (float) doubleValue();
}
@Override
public double doubleValue() {
return numerator.doubleValue() / denominator.doubleValue();
}
@Override
public long longValue() {
return (long) doubleValue();
}
@Override
public int compareTo(Rational o) {
if (this.subtract(o).getNumerator().compareTo(BigInteger.ZERO) > 0)
return 1;
else if (this.subtract(o).getNumerator().compareTo(BigInteger.ZERO) < 0)
return -1;
else
return 0;
}
}
|
/*
* 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 gui.panels;
import glbank.Account;
import glbank.database.ConnectionProvider;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
* @author Martin
*/
public class TransactionPanel extends javax.swing.JPanel {
private int idc;
private int idemp;
/**
* Creates new form TransactionPanel
*/
public TransactionPanel(int idc, int idemp) {
initComponents();
this.idc = idc;
this.idemp = idemp;
initForm();
}
private void initForm() {
showListOfSourceAccount();
}
private void showListOfSourceAccount() {
comboSourceAccount.removeAllItems();
List<Account> clientAccounts = new ConnectionProvider().getClientAccounts(idc);
if (!clientAccounts.isEmpty()) {
for (Account account : clientAccounts) {
comboSourceAccount.addItem("" + account.getIdacc());
}
}
}
private float getInputAmount() {
float value;
try {
value = Float.parseFloat(txtSourceAmount.getText());
} catch (NumberFormatException ex) {
value = 0;
}
return value = (float) Math.round(value * 100) / 100;
}
private boolean checkGLDestinationAccount() {
List<Long> allAccountNumbers = new ConnectionProvider().getAllAccountNumbers();
long destinationAcc;
try {
destinationAcc = Long.parseLong(txtDestinationAcc.getText());
} catch (NumberFormatException ex) {
return false;
}
for (long accNum : allAccountNumbers) {
if (destinationAcc == accNum) {
return true;
}
}
return false;
}
private boolean checkDestinationAccountFormat() {
String destinationAcc = txtDestinationAcc.getText();
if (destinationAcc.length() >= 8 && destinationAcc.length() <= 10) {
try {
long temp = Long.parseLong(destinationAcc);
} catch (NumberFormatException ex) {
return false;
}
return true;
}
return false;
}
private int getDestBank() {
String selectedBank = (String) comboBankCode.getSelectedItem();
switch (selectedBank) {
case "GLbank":
return 2701;
case "TatraBanka":
return 1100;
case "mBank":
return 8360;
default:
return 2701;
}
}
private boolean isEveryFieldFilled() {
if (!"".equals(txtDestinationAcc.getText().trim()) && !"".equals(txtSourceAmount.getText().trim())) {
return true;
}
return false;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
btnSubmitTransaction = new javax.swing.JButton();
txtSourceAmount = new javax.swing.JTextField();
txtDestinationAcc = new javax.swing.JTextField();
comboBankCode = new javax.swing.JComboBox<>();
comboSourceAccount = new javax.swing.JComboBox<>();
jLabel5 = new javax.swing.JLabel();
txtDescription = new javax.swing.JTextField();
jLabel1.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel1.setText("Amount :");
jLabel2.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel2.setText("Source account :");
jLabel3.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel3.setText("Destination account :");
jLabel4.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel4.setText("Bank :");
btnSubmitTransaction.setText("Submit");
btnSubmitTransaction.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSubmitTransactionActionPerformed(evt);
}
});
comboBankCode.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "GLbank", "TatraBanka", "mBank" }));
jLabel5.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
jLabel5.setText("Description :");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(jLabel5))
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(comboBankCode, javax.swing.GroupLayout.Alignment.LEADING, 0, 290, Short.MAX_VALUE)
.addComponent(txtDestinationAcc, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)
.addComponent(txtDescription, javax.swing.GroupLayout.Alignment.LEADING)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtSourceAmount)
.addComponent(comboSourceAccount, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 125, Short.MAX_VALUE)
.addComponent(btnSubmitTransaction, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(comboSourceAccount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtSourceAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtDestinationAcc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(comboBankCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(btnSubmitTransaction, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(62, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void btnSubmitTransactionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitTransactionActionPerformed
if (isEveryFieldFilled()) {
long srcacc;
long destacc;
float amount;
try {
srcacc = Long.parseLong((String) comboSourceAccount.getSelectedItem());
destacc = Long.parseLong(txtDestinationAcc.getText());
amount = Math.abs(Float.parseFloat(txtSourceAmount.getText()));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Check your fields!");
return;
}
if (amount > new ConnectionProvider().getAccountBalance(srcacc)) {
JOptionPane.showMessageDialog(this, "Not enough money on source account!");
return;
}
int srcbank = 2701;
int destbank = getDestBank();
String description = txtDescription.getText();
if (comboBankCode.getSelectedIndex() == 0) {
if (checkGLDestinationAccount() && checkDestinationAccountFormat()) {
System.out.println("btn submit performed");
new ConnectionProvider().performBankTransaction(srcacc, destacc,
srcbank, destbank, amount, idemp, description);
JOptionPane.showMessageDialog(this, "Transaction performed!");
} else {
JOptionPane.showMessageDialog(this, "Bad format of destination account");
}
} else {
if (checkDestinationAccountFormat()) {
new ConnectionProvider().performBankTransaction(srcacc, destacc,
srcbank, destbank, amount, idemp, description);
JOptionPane.showMessageDialog(this, "Transaction performed!");
} else {
JOptionPane.showMessageDialog(this, "Bad format of destination account");
}
}
}
}//GEN-LAST:event_btnSubmitTransactionActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnSubmitTransaction;
private javax.swing.JComboBox<String> comboBankCode;
private javax.swing.JComboBox<String> comboSourceAccount;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField txtDescription;
private javax.swing.JTextField txtDestinationAcc;
private javax.swing.JTextField txtSourceAmount;
// End of variables declaration//GEN-END:variables
}
|
package com.example.vezbepredtest001.dialog;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AboutDialog extends AlertDialog.Builder {
public AboutDialog(Context context) {
super(context);
setTitle("About");
setMessage("App for actors");
setCancelable(false);
setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
}
public AlertDialog prepareDialog(){
AlertDialog dialog = create();
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
}
|
package com.example.zealience.oneiromancy.util;
import android.content.Context;
import android.os.Bundle;
import com.example.zealience.oneiromancy.constant.KeyConstant;
import com.example.zealience.oneiromancy.constant.UrlConstant;
import com.example.zealience.oneiromancy.ui.activity.WebViewActivity;
/**
* @user steven
* @createDate 2019/3/6 18:06
* @description 页面跳转配置文件
*/
public class PageJumpUtil {
public static void jumpToAppointpage(Context context, String functionUrl,
String pageTitle) {
jumpToAppointpage(context, functionUrl, pageTitle, null);
}
/**
* @param context
* @param functionUrl
* @param pageTitle
*/
public static void jumpToAppointpage(final Context context, String functionUrl,
String pageTitle, Bundle bundle) {
if (functionUrl == null || functionUrl.length() <= 0) {
return;
}
if (functionUrl.startsWith("http")) {
if (bundle == null) {
bundle = new Bundle();
}
bundle.putString(KeyConstant.URL_KEY, functionUrl);
WebViewActivity.startActivity(context, bundle);
} else if (functionUrl.startsWith("app")) {
}
}
}
|
package backjoon.sortion;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Word implements Comparable{
private String word;
public Word(String word){
this.word = word;
}
public String getWord(){return word;}
public void setWord(){this.word = word;}
@Override
public int compareTo(Object o) {
Word w = (Word)o;
int result = word.length() - w.word.length();
return (result != 0) ? result : word.compareTo(w.word);
}
}
public class Backjoon1181 {
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
int n = Integer.parseInt(br.readLine());
List<Word> list = new ArrayList<Word>();
for(int i = 0 ; i < n; i++){
list.add(new Word(br.readLine()));
}
Collections.sort(list);
for(int i = 0 ; i < n - 1; i++){
if(list.get(i).getWord().equals(list.get(i + 1).getWord())) {
list.remove(i-- + 1);
n--;
}
}
for(Word w : list){
bw.write(w.getWord() + "\n");
}
bw.close();
br.close();
}
}
|
package cc.before30.fpij.types;
import java.util.Objects;
/**
* User: before30
* Date: 2017. 9. 8.
* Time: PM 5:32
*/
@FunctionalInterface
public interface Consumer4<T1, T2, T3, T4> {
void accept(T1 t1, T2 t2, T3 t3, T4 t4);
default Consumer3<T2, T3, T4> curried(final T1 t1) {
return (t2, t3, t4) -> accept(t1, t2, t3, t4);
}
default Consumer4<T1, T2, T3, T4> andThen(Consumer4<? super T1, ? super T2, ? super T3, ? super T4> after) {
Objects.requireNonNull(after);
return (t1, t2, t3, t4) -> {
accept(t1, t2, t3, t4);
after.accept(t1, t2, t3, t4);
};
}
}
|
package emp.application.model;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.envers.Audited;
@Entity
//@Audited
@Table(name = "AUTHORITY")
public class Authority implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "authoritySeq", sequenceName = "AUTHORITY_SEQ")
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator =
// "authoritySeq")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "AUTHORITY_ID", unique = true, nullable = false)
private int id;
@Column(name = "AUTHORITY_NAME")
private String name;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "PORTAL_USER_AUTHORITY", joinColumns = { //
@JoinColumn(name = "AUTHORITY_AUTHORITY_ID", referencedColumnName = "AUTHORITY_ID") }, //
inverseJoinColumns = { @JoinColumn(name = "PORTAL_USER_USER_ID", referencedColumnName = "USER_ID") })
private Set<User> users;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
|
/**
*
*/
package org.rebioma.client;
import java.util.Map;
/**
* Interface d'ecoute d'une recherche d'occurence.
*
* @author Mikajy
*
*/
public interface OccurrenceSearchListener {
public static final String SEARCH_TYPE_PROPERTY_KEY = "searchType";
public static final String SEARCH_TYPE_VALUE_PROPERTY_KEY = "searchTypeValue";
public static final String RESULT_FILTER_PROPERTY_KEY = "resultFilter";
public static final String RESULT_FILTER_VALUE_KEY = "resultFilter_value";
public static final String ERROR_QUERY_KEY = "errorQuery";
public static final String ERROR_QUERY_VALUE_KEY = "errorquery_value";
public static final String SHARED_KEY = "shared";
public static final String SHARED_VALUE_KEY = "shared_value";
/**
* quand une recherche d'occurrence est lancée.
* @param searchFilter - chaque element de cette collection est un paramètre à {@link OccurrenceQuery#addSearchFilter(String)}}
*/
public void searchQuery(OccurrenceQuery query, Map<String, Object> propertyMap);
}
|
package control;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.MemberDAO;
import model.MemberBean;
@WebServlet("/NowLoginMember.do")
public class NowLoginMember extends HttpServlet {
private static final long serialVersionUID = 1L;
public NowLoginMember() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doNowLoginMember(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doNowLoginMember(request, response);
}
protected void doNowLoginMember(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//━━━━━━━━━━━━━━━━로그인시간체크━━━━━━━━━━━━━━━━━━━┓
HttpSession lastl = request.getSession(); //┃
String lastle = (String)lastl.getAttribute("email"); //┃
Date lastlt = new Date(); //┃
SimpleDateFormat lastlty = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //┃
String lastld = lastlty.format(lastlt); //┃
MemberDAO lastldao = new MemberDAO(); //┃
lastldao.sessionTime(lastle, lastld); //┃
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
String nowserver = request.getParameter("nowserver");
String land = "";
if (nowserver.equals("1")) {
land = "울산%";
} else if (nowserver.equals("2")) {
land = "부산%";
} else if (nowserver.equals("3")) {
land = "경상남도%";
} else if (nowserver.equals("4")) {
land = "경상북도%";
} else if (nowserver.equals("5")) {
land = "충청남도%";
} else if (nowserver.equals("6")) {
land = "충청북도%";
} else if (nowserver.equals("7")) {
land = "강원도%";
} else if (nowserver.equals("8")) {
land = "경기도%";
} else if (nowserver.equals("9")) {
land = "대구%";
} else if (nowserver.equals("10")) {
land = "인천%";
} else if (nowserver.equals("11")) {
land = "광주%";
} else if (nowserver.equals("12")) {
land = "대전%";
} else if (nowserver.equals("13")) {
land = "제주도%";
} else if (nowserver.equals("14")) {
land = "서울%";
} else if (nowserver.equals("15")) {
land = "세종%";
} else if (nowserver.equals("16")) {
land = "전라남도%";
} else if (nowserver.equals("17")) {
land = "전라북도%";
} else {
land = "%";
}
// 몇 분 전까지 로그인 사람을 구할 것 인가
int lastLogin = 59;
// 세션 성별
HttpSession session = request.getSession();
String gender = "";
if (((String)session.getAttribute("gender")).equals("남자")) {
gender = "여자";
} else {
gender = "남자";
}
// 사람들 불러오기
MemberDAO dao = new MemberDAO();
MemberDAO dpo = new MemberDAO();
// 로그인 중인 플레티넘 회원수 세기
MemberDAO dco = new MemberDAO();
int platinumCount = dco.platinumCountLogin(land, gender, lastLogin);
// 페이지에 들어갈 플레티넘 회원 수
int full = platinumCount / 3; // 플레티넘이 3명 꽉찬 페이지
int fullNext = full + 1; // 플레티넘이 꽉 안찬 페이지 ( noFull명 )
int noFull = platinumCount%3; // fullNext 페이지에 들어갈 플레티넘 회원수
// 전체 게시물 수
int count = 0;
// 페이지 넘버 값
String pageNum = request.getParameter("pageNum");
if (pageNum == null) {
pageNum = "1";
}
// 넘버값 정수처리
int currentPage = Integer.parseInt(pageNum);
// 한 페이지에 보여질 플레티넘 회원의 수
int oneLinePageSize = 3;
int oneLineStartRow = (currentPage - 1) * oneLinePageSize;
int oneLineEndRow = oneLinePageSize;
// 한 페이지에 보여질 일반 회원의 수
int twoLinePageSize = 12;
int twoLineStartRow = (currentPage - 1) * twoLinePageSize;
int twoLineEndRow = twoLinePageSize;
// 지금 페이지에 들어 갈 회원 종류 정리
// 3명 꽉 찬 페이지 일때
if ( currentPage <= full ) {
// 기본 환경으로 적용
// 꽉 차지 않는 페이지 일때
} else if ( currentPage == fullNext ) {
oneLineEndRow = noFull;
twoLineEndRow = twoLinePageSize + (( 3 - noFull ) * 2 );
// 플레티넘이 없는 페이지 일때
} else {
oneLinePageSize = 0;
oneLineStartRow = 0;
oneLineEndRow = 0;
twoLinePageSize = 18;
twoLineStartRow = ((currentPage - 1) * twoLinePageSize) - (platinumCount * 2 );
twoLineEndRow = twoLinePageSize;
}
// 총 이성 회원 수
count = dao.getAllMemberLogin(land, gender, lastLogin);
// age 나이로 고칠것
Date today = new Date();
SimpleDateFormat dayTime = new SimpleDateFormat("yyyy");
String nowyear = dayTime.format(today);
// 입력된 수만큼 회원들 불러오기
Vector<MemberBean> vp = dpo.getPlatinumLogin(land, gender, oneLineStartRow, oneLineEndRow, nowyear, lastLogin);
Vector<MemberBean> va = dpo.getMemberNormalLogin(land, gender, twoLineStartRow, twoLineEndRow, nowyear, lastLogin);
//request 객체에 담아서 전달
request.setAttribute("vp", vp);
request.setAttribute("va", va);
request.setAttribute("nowserver", nowserver);
request.setAttribute("platinumCount", platinumCount);
request.setAttribute("count", count);
request.setAttribute("oneLinePageSize", oneLinePageSize);
request.setAttribute("twoLinePageSize", twoLinePageSize);
request.setAttribute("currentPage", currentPage);
request.setAttribute("gender", gender);
RequestDispatcher dis = request.getRequestDispatcher("/mannam/nowLoginMember.jsp?nowserver="+nowserver);
dis.forward(request, response);
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
final class c$ab extends g {
c$ab() {
super("chooseMedia", "chooseMedia", 254, true);
}
}
|
package com.formssi.frms.system.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.formssi.frms.common.domain.Tree;
import com.formssi.frms.common.utils.BuildTree;
import com.formssi.frms.common.utils.MD5Utils;
import com.formssi.frms.system.dao.DeptDao;
import com.formssi.frms.system.dao.UserDao;
import com.formssi.frms.system.dao.UserRoleDao;
import com.formssi.frms.system.domain.SysDept;
import com.formssi.frms.system.domain.SysUser;
import com.formssi.frms.system.domain.SysUserRole;
import com.formssi.frms.system.service.UserService;
import com.formssi.frms.system.vo.UserVO;
@Transactional
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userMapper;
@Autowired
UserRoleDao userRoleMapper;
@Autowired
DeptDao deptMapper;
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
@Override
public SysUser get(Long id) {
List<Long> roleIds = userRoleMapper.listRoleId(id);
SysUser user = userMapper.get(id);
user.setDeptName(deptMapper.get(user.getDeptId()).getName());
user.setRoleIds(roleIds);
return user;
}
@Override
public List<SysUser> list(Map<String, Object> map) {
return userMapper.list(map);
}
@Override
public int count(Map<String, Object> map) {
return userMapper.count(map);
}
@Transactional
@Override
public int save(SysUser user) {
int count = userMapper.save(user);
Long userId = user.getUserId();
List<Long> roles = user.getRoleIds();
userRoleMapper.removeByUserId(userId);
List<SysUserRole> list = new ArrayList<>();
for (Long roleId : roles) {
SysUserRole ur = new SysUserRole();
ur.setUserId(userId);
ur.setRoleId(roleId);
list.add(ur);
}
if (list.size() > 0) {
userRoleMapper.batchSave(list);
}
return count;
}
@Override
public int update(SysUser user) {
int r = userMapper.update(user);
Long userId = user.getUserId();
List<Long> roles = user.getRoleIds();
userRoleMapper.removeByUserId(userId);
List<SysUserRole> list = new ArrayList<>();
for (Long roleId : roles) {
SysUserRole ur = new SysUserRole();
ur.setUserId(userId);
ur.setRoleId(roleId);
list.add(ur);
}
if (list.size() > 0) {
userRoleMapper.batchSave(list);
}
return r;
}
@Override
public int remove(Long userId) {
userRoleMapper.removeByUserId(userId);
return userMapper.remove(userId);
}
@Override
public boolean exit(Map<String, Object> params) {
boolean exit;
exit = userMapper.list(params).size() > 0;
return exit;
}
@Override
public Set<String> listRoles(Long userId) {
return null;
}
@Override
public int resetPwd(UserVO userVO,SysUser SysUser) throws Exception {
if(Objects.equals(userVO.getSysUser().getUserId(),SysUser.getUserId())){
if(Objects.equals(MD5Utils.encrypt(SysUser.getUsername(),userVO.getPwdOld()),SysUser.getPassword())){
SysUser.setPassword(MD5Utils.encrypt(SysUser.getUsername(),userVO.getPwdNew()));
return userMapper.update(SysUser);
}else{
throw new Exception("输入的旧密码有误!");
}
}else{
throw new Exception("你修改的不是你登录的账号!");
}
}
@Override
public int adminResetPwd(UserVO userVO) throws Exception {
SysUser SysUser =get(userVO.getSysUser().getUserId());
if("admin".equals(SysUser.getUsername())){
throw new Exception("超级管理员的账号不允许直接重置!");
}
SysUser.setPassword(MD5Utils.encrypt(SysUser.getUsername(), userVO.getPwdNew()));
return userMapper.update(SysUser);
}
@Transactional
@Override
public int batchremove(Long[] userIds) {
int count = userMapper.batchRemove(userIds);
userRoleMapper.batchRemoveByUserId(userIds);
return count;
}
@Override
public Tree<SysDept> getTree() {
List<Tree<SysDept>> trees = new ArrayList<Tree<SysDept>>();
List<SysDept> depts = deptMapper.list(new HashMap<String, Object>(16));
Long[] pDepts = deptMapper.listParentDept();
Long[] uDepts = userMapper.listAllDept();
Long[] allDepts = (Long[]) ArrayUtils.addAll(pDepts, uDepts);
for (SysDept dept : depts) {
if (!ArrayUtils.contains(allDepts, dept.getDeptId())) {
continue;
}
Tree<SysDept> tree = new Tree<SysDept>();
tree.setId(dept.getDeptId().toString());
tree.setParentId(dept.getParentId().toString());
tree.setText(dept.getName());
Map<String, Object> state = new HashMap<>(16);
state.put("opened", true);
state.put("mType", "dept");
tree.setState(state);
trees.add(tree);
}
List<SysUser> users = userMapper.list(new HashMap<String, Object>(16));
for (SysUser user : users) {
Tree<SysDept> tree = new Tree<SysDept>();
tree.setId(user.getUserId().toString());
tree.setParentId(user.getDeptId().toString());
tree.setText(user.getName());
Map<String, Object> state = new HashMap<>(16);
state.put("opened", true);
state.put("mType", "user");
tree.setState(state);
trees.add(tree);
}
// 默认顶级菜单为0,根据数据库实际情况调整
Tree<SysDept> t = BuildTree.build(trees);
return t;
}
@Override
public int updatePersonal(SysUser SysUser) {
return userMapper.update(SysUser);
}
@Override
public Map<String, Object> updatePersonalImg(MultipartFile file, String avatar_data, Long userId) throws Exception {
return null;
}
}
|
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class TopNWordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable>
{
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws
IOException,InterruptedException
{
/*Initial count will be 0 for a keyword*/
int total = 0;
for(IntWritable value : values)
{
/*Getting previous value and add new value in count*/
total+=value.get();
}
context.write(key, new IntWritable(total));
}
}
|
package com.medplus.departmentinfo.service.impl;
import java.util.List;
import com.medplus.departmentinfo.beans.DepartmentBean;
import com.medplus.departmentinfo.beans.EmployeeBean;
import com.medplus.departmentinfo.dao.DepartmentDAO;
import com.medplus.departmentinfo.dao.impl.DepartmentDAOImpl;
import com.medplus.departmentinfo.service.DepartmentService;
public class DepartmentServiceImpl implements DepartmentService {
DepartmentDAO dao = new DepartmentDAOImpl();
@Override
public List<DepartmentBean> getALLDepartment() {
List<DepartmentBean> deptList = null;
deptList = dao.getALLDepartment();
return deptList;
}
@Override
public String updateDepartment(DepartmentBean departmentBean) {
String status = "updation failed !!";
int rows = dao.updateDepartment(departmentBean);
if (rows > 0)
status = "updated successfully !!";
return status;
}
@Override
public String addDepartment(DepartmentBean departmentBean) {
String status = "registration failed !!";
int rows = dao.addDepartment(departmentBean);
if (rows > 0)
status = "registered successfully !!";
return status;
}
@Override
public DepartmentBean getDepartmentByID(int deptNo) {
DepartmentBean departmentBean = null;
departmentBean = dao.getDepartmentByID(deptNo);
return departmentBean;
}
@Override
public List<EmployeeBean> getALLEmployeeByDeptNo(int deptNo) {
List<EmployeeBean> emplist = null;
emplist = dao.getALLEmployeeByDeptNo(deptNo);
return emplist;
}
}
|
package com.library.bexam.form;
import java.util.List;
/**
* 教材章节实体
* @author caoqian
* @date 20181219
*/
public class NodeBookForm {
private int nodeId;
private String nodeName;
private int parentId;
private List<NodeBookForm> nodeList;
private int textBookId;
private String createTime;
public NodeBookForm() {
}
public NodeBookForm(int nodeId, String nodeName, int parentId, String createTime) {
this.nodeId = nodeId;
this.nodeName = nodeName;
this.parentId = parentId;
this.createTime = createTime;
}
public int getNodeId() {
return nodeId;
}
public void setNodeId(int nodeId) {
this.nodeId = nodeId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public List<NodeBookForm> getNodeList() {
return nodeList;
}
public void setNodeList(List<NodeBookForm> nodeList) {
this.nodeList = nodeList;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public int getTextBookId() {
return textBookId;
}
public void setTextBookId(int textBookId) {
this.textBookId = textBookId;
}
}
|
package com.carlosdv93.vetta.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.carlosdv93.vetta.model.Telefone;
@Repository
public interface TelefoneRepository extends CrudRepository<Telefone, Long>{
}
|
package Jugs.PlayStudio;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class psDataAnalyis
{
public String filepath = "/home/jugs/Downloads/psTransactions.txt";
public ArrayList<String> records = new ArrayList<>();
public HashSet<String> userID = new HashSet<>();
public HashMap<String, ArrayList<String> > userBasedRecord = new HashMap<String, ArrayList<String>>();
public List<Transaction> transactionList = new ArrayList<>();
public static void main(String[] args) throws Exception
{
psDataAnalyis psData = new psDataAnalyis();
psData.userDatabase();
}
private void userDatabase() throws Exception {
File file = new File(filepath);
BufferedReader br = new BufferedReader(new FileReader(file));
br.readLine();
String line;
while ((line = br.readLine()) != null)
{
try
{
String[] recStr = line.split("\t");
userID.add(recStr[0]);
// transactionList.add(new Transaction(recStr[0], formatter(recStr[1]), formatter(recStr[2]), Integer.parseInt(recStr[3]), Float.parseFloat(recStr[4]),
// Float.parseFloat(recStr[5]), Float.parseFloat(recStr[6]), Long.parseLong(recStr[7]), Long.parseLong(recStr[8]),
// Long.parseLong(recStr[9]), Long.parseLong(recStr[10]),Boolean.parseBoolean(recStr[11]), Long.parseLong(recStr[12]),recStr[13]));
records.add(line);
}
catch (Exception e)
{
System.out.println("Not an ID");
}
}
/*
* Solution To Question 1
* */
HashMap<String, ArrayList<String>> moneytizersByDate = getRecordsByDate(records);
System.out.println("Total Monetizer on '11/16/2017' : " + moneytizersByDate.size());
HashMap<String, String> monitisedDateRange = moneytizerMonytizeOnDateRange(records, moneytizersByDate);
System.out.println("Total Monetizer Moneitised in Between '11/17/2017' and '11/23/2017' who were monetizer in '11/16/2017' : " + monitisedDateRange.size());
/*
* Solution To Question 2 -> a and b
* */
analysisABgameTest(records);
/*
* Solution To Question 3 -> a , b and c
* */
newGameFeature(records);
/*
* Solution To Question 4 -> a and b [Clustering Algorithm]
* */
clusteringAlgorithm(records);
}
private void clusteringAlgorithm(ArrayList<String> records) throws Exception
{
KMeansAlgorithm kmeans = new KMeansAlgorithm();
kmeans.readFile(records);
}
private void newGameFeature(ArrayList<String> records) throws Exception
{
Date featureDate = new SimpleDateFormat("MM/dd/yyyy").parse("01/18/2018");
float before = 0;
float after = 0;
for (String rec : records)
{
String[] strSplit = rec.split(",");
Date cmpDate = new SimpleDateFormat("MM/dd/yyyy").parse(strSplit[1]);
if (cmpDate.compareTo(featureDate) >= 0)
{
after += Float.parseFloat(strSplit[3]);
}
else
{
before += Float.parseFloat(strSplit[3]);
}
}
System.out.println(before);
System.out.println(after);
}
private void analysisABgameTest(ArrayList<String> records) throws ParseException
{
float amountSpendA = (float) 0.0;
float amountSpendB = (float) 0.0;
long timeSpendA = 0;
long timeSpendB = 0;
long nosOfTransactionA = 0;
long nosOfTransactionB = 0;
Date fromDate = new SimpleDateFormat("MM/dd/yyyy").parse("12/09/2017");
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse("12/19/2017");
for (String rec : records)
{
String[] recArray = rec.split(",");
Date cmdDate = new SimpleDateFormat("MM/dd/yyyy").parse(recArray[1]);
if (cmdDate.compareTo(fromDate) >= 0 && cmdDate.compareTo(toDate) <= 0)
{
if (recArray[13].equals("A"))
{
amountSpendA += Float.parseFloat(recArray[4]);
timeSpendA += Long.parseLong(recArray[12]);
nosOfTransactionA += Long.parseLong(recArray[3]);
}
else if (recArray[13].equals("B"))
{
amountSpendB += Float.parseFloat(recArray[4]);
timeSpendB += Long.parseLong(recArray[12]);
nosOfTransactionB += Long.parseLong(recArray[3]);
// System.out.println(amountSpendB);
}
}
}
System.out.println("Total Amount Spend on Game A (in USD) :" + amountSpendA);
System.out.println("Total Amount Spend on Game A (in USD) : " + amountSpendB);
System.out.println("Total Time Spend on Game A (in hrs): " +(timeSpendA/60)/60);
System.out.println("Total Time Spend on Game B (in hrs): " + timeSpendB/60/60);
System.out.println("Total Transactions in Game A : " + nosOfTransactionA);
System.out.println("Total Transactions in Game B : " + nosOfTransactionB);
}
private HashMap<String, String> moneytizerMonytizeOnDateRange(ArrayList<String> records, HashMap<String, ArrayList<String>> moneytizers) throws ParseException
{
HashMap<String, String> monetizerMontized = new HashMap<>();
Date fromDate = new SimpleDateFormat("MM/dd/yyyy").parse("11/17/2017");
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse("11/23/2017");
for (String rec : records)
{
Date cmpDate = new SimpleDateFormat("MM/dd/yyyy").parse(rec.split(",")[1]);
if (cmpDate.compareTo(fromDate) >= 0 && cmpDate.compareTo(toDate) <= 0)
{
for (Map.Entry pair : moneytizers.entrySet())
{
if (pair.getKey().equals(rec.split(",")[0]) && Float.parseFloat(rec.split(",")[4]) > 0)
{
monetizerMontized.put(rec.split(",")[0] , rec);
}
}
}
}
return monetizerMontized;
}
private HashMap<String, ArrayList<String>> getRecordsByDate(ArrayList<String> records)
{
HashMap<String, ArrayList<String> > result = new HashMap<>();
for (String rec : records)
{
if ((rec.split(",")[1]).equals("11/16/2017"))
{
if (result.containsKey(rec.split(",")[0]))
{
ArrayList<String> value = result.get(rec.split(",")[0]);
value.add(rec);
result.put(rec.split(",")[0], value);
}
else
{
ArrayList<String> value = new ArrayList<>();
value.add(rec);
result.put(rec.split(",")[0], value);
}
}
}
return result;
}
private Date formatter(String dateInString) throws ParseException
{
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy");
if (dateInString.equals(""))
{
date = formatter.parse("01/01/1900");
}
else
{
date = formatter.parse(dateInString);
}
return date;
}
}
|
package wjtoth.cyclicstablematching;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Matching implements Comparable<Matching> {
// number of genders
private final int NUMBER_OF_GROUPS;
// number of agents per gender
private final int NUMBER_OF_AGENTS;
// Store matching
ArrayList<int[]> matching;
// string which represents matching
private String hash;
// number of non-empty matches
private int size;
// partners indexed by group,index
private int[][] partnerOf;
public Matching(int numberOfGroups, int numberOfAgents) {
NUMBER_OF_GROUPS = numberOfGroups;
NUMBER_OF_AGENTS = numberOfAgents;
matching = new ArrayList<int[]>(numberOfGroups);
size = -1;
}
/**
* Converts list of permutations to a matching
*
* @param permutationProduct
* list of size NUMBER_OF_GROUPS where each int[] is a
* permutation of [0,..., NUMBER_OF_AGENTS - 1]
*/
public void setMatchingFromPermutations(ArrayList<int[]> permutationProduct) {
for (int i = 0; i < NUMBER_OF_AGENTS; ++i) {
int[] match = new int[NUMBER_OF_GROUPS];
for (int j = 0; j < NUMBER_OF_GROUPS; ++j) {
match[j] = permutationProduct.get(j)[i];
}
try {
matching.set(i, match);
} catch (IndexOutOfBoundsException e) {
matching.add(i, match);
}
}
sortAndHash();
}
/**
* Arranges matching tuples in lex order, precomputes partners
* and Computes hash string
*/
private void sortAndHash() {
Collections.sort(matching, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1.length != o2.length) {
return o1.length - o2.length;
}
for (int i = 0; i < o1.length; ++i) {
if (o1[i] != o2[i]) {
return o1[i] - o2[i];
}
}
return 0;
}
});
precomputePartners();
StringBuffer sb = new StringBuffer();
for (int[] match : matching) {
for (int agent : match) {
sb.append(agent);
}
}
hash = sb.toString();
}
//stores partners in memory for quick access
private void precomputePartners() {
partnerOf = new int[NUMBER_OF_GROUPS][NUMBER_OF_AGENTS];
for(int i = 0; i<NUMBER_OF_GROUPS; ++i) {
for(int j = 0; j<NUMBER_OF_AGENTS; ++j) {
partnerOf[i][j] = -1;
}
}
for(int[] match : matching) {
for(int i = 0; i<match.length; ++i) {
int partner = match[(i+1)%match.length];
partnerOf[i][match[i]] = partner;
}
}
}
/**
* sets matching from matching
*
* @param matching
* NUMBER_OF_AGENTS tuples of sizes NUMBER_OF_GROUPS int[]'s
* should have disjoint intersection
*/
public void setMatching(ArrayList<int[]> matching) {
this.matching = matching;
sortAndHash();
}
/**
* returns index of partner that agent in group has preference over
*
* @param group
* index of gender agent belongs to
* @param agent
* index of agent
* @return
*/
public int getPartner(int group, int agent) {
return partnerOf[group][agent];
}
/**
*
* @return list of tuples representing matching
*/
public ArrayList<int[]> getMatching() {
return matching;
}
/**
* Pretty prints matching
*/
public String toString() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("---------\n");
for (int i = 0; i < matching.size(); ++i) {
int[] orderedMatch = matching.get(i);
stringBuffer.append("(");
for (int j = 0; j < orderedMatch.length; ++j) {
stringBuffer.append(orderedMatch[j] + " ");
}
stringBuffer.append(")\n");
}
stringBuffer.append("---------");
return stringBuffer.toString();
}
/**
* Standard Getters
*/
public int getNUMBER_OF_GROUPS() {
return NUMBER_OF_GROUPS;
}
public int getNUMBER_OF_AGENTS() {
return NUMBER_OF_AGENTS;
}
public String getHash() {
return hash;
}
/**
* Matchings are compared lexicographically via hash strings, hence the need
* to sort.
*/
public int compareTo(Matching perfectMatching) {
return hash.compareTo(perfectMatching.getHash());
}
@Override
public boolean equals(Object obj) {
if (obj.getClass() != getClass()) {
return false;
}
Matching perfectMatching = (Matching) obj;
return hash.equals(perfectMatching.getHash());
}
@Override
public int hashCode() {
if (hash == null) {
return 0;
}
return hash.hashCode();
}
/**
* @return true iff matching is proper
*/
public boolean validate() {
for (int[] match : matching) {
for (int i = 0; i < match.length; ++i) {
boolean isMatched = match[i] >= 0;
boolean nextIsMatched = match[(i + 1) % match.length] >= 0;
if ((isMatched && !nextIsMatched) || (!isMatched && nextIsMatched)) {
return false;
}
}
}
return true;
}
/**
*
* @param permutation
* a NUMBER_OF_AGENTS size permutation
* @return matching with additional gender taken by appending permutation
*/
public Matching extend(int[] permutation) {
if (permutation.length != NUMBER_OF_AGENTS) {
System.out.println("Cannot extend with given permutation: " + Arrays.toString(permutation));
return null;
}
ArrayList<int[]> extendedMatching = new ArrayList<int[]>();
int k = 0;
for (int[] match : matching) {
int[] extendedMatch = new int[match.length + 1];
for (int i = 0; i < match.length; ++i) {
extendedMatch[i] = match[i];
}
extendedMatch[match.length] = permutation[k];
extendedMatching.add(extendedMatch);
++k;
}
Matching retval = new Matching(getNUMBER_OF_GROUPS() + 1, getNUMBER_OF_AGENTS());
retval.setMatching(extendedMatching);
return retval;
}
/**
*
* @param group
* index of gender
* @param agent
* index of agent in gender
* @return true iff agent has a partner in this matching
*/
public boolean isMatchedInGroup(int group, int agent) {
if(agent >= NUMBER_OF_AGENTS) {
return false;
}
return partnerOf[group][agent] >= 0;
}
public int size() {
if (size == -1) {
int count = 0;
for (int[] match : matching) {
boolean nonNegative = true;
for (int i = 0; i < match.length; ++i) {
if (match[i] == -1) {
nonNegative = false;
break;
}
}
if (nonNegative) {
++count;
}
}
size = count;
}
return size;
}
public boolean isInternallyBlocked(PreferenceSystem preferenceSystem) {
for (int a = 0; a < preferenceSystem.numberOfAgents; ++a) {
if (isMatchedInGroup(0, a)) {
int partnerOfA = getPartner(0, a);
for (int i = 0; i < preferenceSystem.ranks[0][a][partnerOfA]; ++i) {
int b = preferenceSystem.preferences[0][a][i];
if (isMatchedInGroup(1, b)) {
int partnerOfB = getPartner(1, b);
for (int j = 0; j < preferenceSystem.ranks[1][b][partnerOfB]; ++j) {
int c = preferenceSystem.preferences[1][b][j];
if (isMatchedInGroup(2, c)) {
int partnerOfC = getPartner(2, c);
if (preferenceSystem.prefers(2, c, a, partnerOfC)) {
return true;
}
}
}
}
}
}
}
return false;
}
public List<List<Integer>> firstOrderDissatisfied(PreferenceSystem preferenceSystem) {
int n = preferenceSystem.numberOfGroups;
List<List<Integer>> potentialBlocks = new ArrayList<List<Integer>>(n);
for (int i = 0; i < n; ++i) {
List<Integer> groupBlocks = new LinkedList<Integer>();
for (int v = 0; v < preferenceSystem.numberOfAgents; ++v) {
if (isMatchedInGroup((i - 1 + n) % n, v)) {
int partnerOfV = getPartner((i - 1 + n) % n, v);
for (int j = 0; j < preferenceSystem.ranks[(i - 1 + n) % n][v][partnerOfV]; ++j) {
int u = preferenceSystem.preferences[(i - 1 + n) % n][v][j];
groupBlocks.add(u);
}
}
}
potentialBlocks.add(i, groupBlocks);
}
return potentialBlocks;
}
public Matching append(int[] tuple) {
matching.add(tuple);
sortAndHash();
return this;
}
public Matching validSubmatching(PreferenceSystem preferenceSystem) {
return validSubmatching(preferenceSystem, 0);
}
public Matching validSubmatching(PreferenceSystem preferenceSystem, int group) {
int n = preferenceSystem.numberOfGroups;
Matching retval = new Matching(NUMBER_OF_GROUPS, NUMBER_OF_AGENTS);
for (int[] tuple : matching) {
boolean validFlag = true;
for (int i = 0; i < tuple.length; ++i) {
int agent = tuple[i];
int partner = tuple[(i + 1) % tuple.length];
if (partner == -1
|| preferenceSystem.ranks[(i + group) % n][agent][partner] >= preferenceSystem.numberOfAgents) {
validFlag = false;
}
}
if (validFlag) {
retval.append(tuple);
}
}
return retval;
}
public boolean isInternallyBlocked(PreferenceSystem preferenceSystem, int group, int[] triple) {
for (int a = 0; a < preferenceSystem.numberOfAgents; ++a) {
if(group == 0 && triple[group] == a) {
continue;
}
if (isMatchedInGroup(0, a,triple)) {
int partnerOfA = getPartner(0, a,triple);
for (int i = 0; i < preferenceSystem.ranks[0][a][partnerOfA]; ++i) {
int b = preferenceSystem.preferences[0][a][i];
if(group == 1 && triple[group] == b) {
continue;
}
if (isMatchedInGroup(1, b,triple)) {
int partnerOfB = getPartner(1, b,triple);
for (int j = 0; j < preferenceSystem.ranks[1][b][partnerOfB]; ++j) {
int c = preferenceSystem.preferences[1][b][j];
if(group == 2 && triple[group] == c) {
continue;
}
if (isMatchedInGroup(2, c,triple)) {
int partnerOfC = getPartner(2, c,triple);
if (preferenceSystem.prefers(2, c, a, partnerOfC)) {
return true;
}
}
}
}
}
}
}
return false;
}
private int getPartner(int group, int agent, int[] triple) {
if(triple[group] == agent) {
return triple[(group+1)%triple.length];
}
return getPartner(group, agent);
}
public boolean isMatchedInGroup(int group, int agent, int[] triple) {
if(triple[group] == agent) {
return true;
}
return isMatchedInGroup(group,agent);
}
public List<List<Integer>> firstOrderDissatisfied(PreferenceSystem preferenceSystem, int group, int[] triple) {
int n = preferenceSystem.numberOfGroups;
List<List<Integer>> potentialBlocks = new ArrayList<List<Integer>>(n);
for (int i = 0; i < n; ++i) {
List<Integer> groupBlocks = new LinkedList<Integer>();
for (int v = 0; v < preferenceSystem.numberOfAgents; ++v) {
if (isMatchedInGroup((i - 1 + n) % n, v,triple)) {
int partnerOfV = getPartner((i - 1 + n) % n, v,triple);
for (int j = 0; j < preferenceSystem.ranks[(i - 1 + n) % n][v][partnerOfV]; ++j) {
int u = preferenceSystem.preferences[(i - 1 + n) % n][v][j];
if(u != preferenceSystem.numberOfAgents) {
groupBlocks.add(u);
}
}
}
}
potentialBlocks.add(i, groupBlocks);
}
return potentialBlocks;
}
}
|
package boj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class BOJ_2146_다리만들기 {
private static int N;
private static int iNum;
private static int bridge;
private static int[][] map;
private static int[][] dir= {{-1,0},{1,0},{0,-1},{0,1}};
private static boolean[][] visited;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N =Integer.parseInt(br.readLine());
map = new int[N][N];
visited = new boolean[N][N];
for (int r = 0; r < N; r++) {
st = new StringTokenizer(br.readLine());
for (int c = 0; c < N; c++) {
map[r][c] = Integer.parseInt(st.nextToken());
}
}
iNum=1;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
if(!visited[r][c] && map[r][c] == 1) { // 각 섬을 각각 다른 숫자로 채운다. dfs로 구현
iNum++; // ex) 1번째 섬은 2로 채워져있고 2번째섬은 3으로 채워져있고 ...
dfs(new Pair(r,c,0)); // 이유는 섬을 구분하기 위해서
}
}
}
bridge = Integer.MAX_VALUE;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
if(map[r][c] > 0) {
for (int i = 0; i < N; i++) {
Arrays.fill(visited[i], false);
}
bfs(new Pair(r,c,0)); // bfs로 각 위치마다 다른섬을 만나는 최소 다리를 찾는다.
}
}
}
System.out.println(bridge);
}
public static void bfs(Pair p){
Queue<Pair> queue = new LinkedList<>();
queue.offer(p);
visited[p.x][p.y] = true;
while(!queue.isEmpty()) {
Pair tmp = queue.poll();
if(map[tmp.x][tmp.y]!=0 && map[tmp.x][tmp.y]!=map[p.x][p.y]) { // 만약 다른섬에 도착했다면?
bridge = Math.min(bridge, tmp.c-1); // 시작위치에서의 최소 다리 길이는 구했다. 끝
return;
}
for (int i = 0; i < dir.length; i++) {
int a = tmp.x + dir[i][0];
int b = tmp.y + dir[i][1];
if(a>=0 && b>=0 && a<N && b< N && !visited[a][b] && map[a][b]!=map[p.x][p.y]){ // 자신의 섬을 제외하고 이동
int c = tmp.c +1;
queue.offer(new Pair(a,b,c));
visited[a][b] = true;
}
}
}
}
public static void dfs(Pair p) {
map[p.x][p.y] = iNum;
for (int i = 0; i < dir.length; i++) {
int a = p.x + dir[i][0];
int b = p.y + dir[i][1];
if(a>=0 && b>=0 && a<N && b< N && !visited[a][b] && map[a][b] == 1) {
visited[p.x][p.y] =true;
dfs(new Pair(a,b,0));
visited[a][b] =false;
}
}
}
public static class Pair{
int x;
int y;
int c; // 현재 거리
public Pair(int x, int y, int c) {
this.x = x;
this.y = y;
this.c = c;
}
}
}
|
package GUI;
import DataStructures.GraphicData;
import DataStructures.NodeData;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class IDestWindow {
//Controller declaration
private Controller controller = new Controller();
//Graphic nodes declarations
private GridPane gridPane = new GridPane();
private Button button = new Button("Agregar");
private ChoiceBox<String> placeBox = new ChoiceBox<>();
private Group root = new Group(gridPane);
public void start(TextField field, GraphicData graphicData, String exc1, String exc2) throws Exception {
//Basic settings
controller.fillBoxesExcept(placeBox, graphicData, exc1, exc2);
gridPane.setPadding(new Insets(10, 10, 10, 10)); //margins around the whole grid
Stage primaryStage = new Stage();
gridPane.setPadding(new Insets(10, 10, 10, 10)); //margins around the whole grid
gridPane.add(new Label("Destino:"),0,0);
gridPane.add(placeBox,1,0);
HBox buttonBox = new HBox(button);
buttonBox.setAlignment(Pos.CENTER);
gridPane.add(buttonBox,0,2,2,2);
//Adding node to the metadata file
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
String text = field.getText();
if(text.length() != 0) {
text += "," + placeBox.getValue();
field.setText(text);
}
else{
text+=placeBox.getValue();
field.setText(text);
}
primaryStage.close();
}
});
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
|
package com.supconit.kqfx.web.util;
import java.util.Collection;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MsgPushUtil {
private transient static final Logger logger = LoggerFactory
.getLogger(MsgPushUtil.class);
/**
* 将信息推送到前台,然后前台同DWR框架调用信息
* @param msg
*/
public static void send(final String msg){
Runnable run = new Runnable() {
private ScriptBuffer bf = new ScriptBuffer();
@Override
public void run() {
// TODO Auto-generated method stub
//设置需要调用的JS和参数
bf.appendCall("show", msg);
//得到所有的ScriptSession
Collection<ScriptSession> sessions = Browser.getTargetSessions();
//遍历所有的session
for(ScriptSession session : sessions){
session.addScript(bf);
}
}
};
try {
//执行推送
Browser.withAllSessions(run);
} catch (Exception e) {
logger.info("无页面推送:"+e.toString());
e.printStackTrace();
}
}
}
|
package com.jingb.application.ninegag.foldablelayout;
import android.content.res.Resources;
import android.content.res.TypedArray;
import com.jingb.application.R;
/**
* Created by jingb on 16/3/19.
*/
public class Painting {
int imageId;
public Painting(int imageId) {
this.imageId = imageId;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public static Painting[] getAllPaintings(Resources res) {
TypedArray images = res.obtainTypedArray(R.array.paintings_images);
int size = 5;
Painting[] paintings = new Painting[size];
for (int i = 0; i < size; i++) {
final int imageId = images.getResourceId(i, -1);
paintings[i] = new Painting(imageId);
}
images.recycle();
return paintings;
}
}
|
package br.com.opensig.comercial.server.acao;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Document;
import br.com.opensig.comercial.client.servico.ComercialException;
import br.com.opensig.comercial.server.ComercialServiceImpl;
import br.com.opensig.comercial.shared.modelo.ComCompra;
import br.com.opensig.comercial.shared.modelo.ComCompraProduto;
import br.com.opensig.core.client.controlador.filtro.ECompara;
import br.com.opensig.core.client.controlador.filtro.EJuncao;
import br.com.opensig.core.client.controlador.filtro.FiltroNumero;
import br.com.opensig.core.client.controlador.filtro.FiltroObjeto;
import br.com.opensig.core.client.controlador.filtro.FiltroTexto;
import br.com.opensig.core.client.controlador.filtro.GrupoFiltro;
import br.com.opensig.core.client.controlador.filtro.IFiltro;
import br.com.opensig.core.client.servico.CoreService;
import br.com.opensig.core.client.servico.OpenSigException;
import br.com.opensig.core.server.UtilServer;
import br.com.opensig.core.server.importar.IImportacao;
import br.com.opensig.core.shared.modelo.Autenticacao;
import br.com.opensig.core.shared.modelo.Lista;
import br.com.opensig.core.shared.modelo.sistema.SisExpImp;
import br.com.opensig.empresa.server.EmpresaServiceImpl;
import br.com.opensig.empresa.shared.modelo.EmpContato;
import br.com.opensig.empresa.shared.modelo.EmpContatoTipo;
import br.com.opensig.empresa.shared.modelo.EmpEmpresa;
import br.com.opensig.empresa.shared.modelo.EmpEndereco;
import br.com.opensig.empresa.shared.modelo.EmpEnderecoTipo;
import br.com.opensig.empresa.shared.modelo.EmpEntidade;
import br.com.opensig.empresa.shared.modelo.EmpEstado;
import br.com.opensig.empresa.shared.modelo.EmpFornecedor;
import br.com.opensig.empresa.shared.modelo.EmpMunicipio;
import br.com.opensig.financeiro.shared.modelo.FinConta;
import br.com.opensig.financeiro.shared.modelo.FinForma;
import br.com.opensig.financeiro.shared.modelo.FinPagamento;
import br.com.opensig.financeiro.shared.modelo.FinPagar;
import br.com.opensig.fiscal.shared.modelo.FisNotaEntrada;
import br.com.opensig.nfe.TEnderEmi;
import br.com.opensig.nfe.TNFe;
import br.com.opensig.nfe.TNFe.InfNFe.Cobr.Dup;
import br.com.opensig.nfe.TNFe.InfNFe.Det;
import br.com.opensig.nfe.TNFe.InfNFe.Det.Imposto.ICMS;
import br.com.opensig.nfe.TNFe.InfNFe.Det.Prod;
import br.com.opensig.nfe.TNFe.InfNFe.Emit;
import br.com.opensig.nfe.TNFe.InfNFe.Ide;
import br.com.opensig.nfe.TNFe.InfNFe.Total.ICMSTot;
import br.com.opensig.produto.shared.modelo.ProdEmbalagem;
import br.com.opensig.produto.shared.modelo.ProdIpi;
import br.com.opensig.produto.shared.modelo.ProdOrigem;
import br.com.opensig.produto.shared.modelo.ProdProduto;
import br.com.opensig.produto.shared.modelo.ProdTipo;
import br.com.opensig.produto.shared.modelo.ProdTributacao;
public class ImportarNfe implements IImportacao<ComCompra> {
private CoreService servico;
private ComCompra compra;
private List<ComCompraProduto> comProdutos;
private List<ProdTributacao> tributacao;
private List<ProdIpi> ipis;
private List<ProdEmbalagem> embalagem;
private EmpEmpresa empresa;
private EmpFornecedor fornecedor;
private TNFe nfe;
private Autenticacao auth;
public ImportarNfe() {
}
@Override
public Map<String, List<ComCompra>> setArquivo(Autenticacao auth, Map<String, byte[]> arquivos, SisExpImp modo) throws OpenSigException {
this.servico = new ComercialServiceImpl(auth);
this.fornecedor = new EmpFornecedor();
this.auth = auth;
String xml = "";
for (byte[] valor : arquivos.values()) {
xml = new String(valor);
break;
}
// valida se é NFe
try {
// pega a NFe
int I = xml.indexOf("<infNFe");
int F = xml.indexOf("</NFe>") + 6;
String texto = "<NFe xmlns=\"http://www.portalfiscal.inf.br/nfe\">" + xml.substring(I, F);
nfe = UtilServer.xmlToObj(texto, "br.com.opensig.nfe");
} catch (Exception e) {
throw new ComercialException("Não é uma NFe válida!");
}
// valida se tem protocolo
try {
Document doc = UtilServer.getXml(xml);
UtilServer.getValorTag(doc.getDocumentElement(), "nProt", true);
} catch (Exception e) {
throw new ComercialException("Não tem o protocolo da Sefaz!");
}
// valida a empresa
validarEmpresa();
// valida a compra
validarCompra();
// valida o fornecedor
validarFornecedor();
// valida os produtos
validarProduto();
// coloca a nota
FisNotaEntrada nota = new FisNotaEntrada();
nota.setFisNotaEntradaXml(xml);
compra.setFisNotaEntrada(nota);
compra.setComCompraNfe(true);
Map<String, List<ComCompra>> resp = new HashMap<String, List<ComCompra>>();
List<ComCompra> lista = new ArrayList<ComCompra>();
lista.add(getCompra());
resp.put("ok", lista);
return resp;
}
private void validarEmpresa() throws OpenSigException {
if (nfe.getInfNFe().getDest().getCNPJ().equals(auth.getEmpresa()[5].replaceAll("\\W", ""))) {
EmpEntidade ent = new EmpEntidade(Integer.valueOf(auth.getEmpresa()[1]));
ent.setEmpEntidadeNome1(auth.getEmpresa()[2]);
ent.setEmpEntidadeNome2(auth.getEmpresa()[3]);
ent.setEmpEntidadePessoa(auth.getEmpresa()[4]);
ent.setEmpEntidadeDocumento1(auth.getEmpresa()[5]);
ent.setEmpEntidadeDocumento2(auth.getEmpresa()[6]);
ent.setEmpEntidadeObservacao("");
empresa = new EmpEmpresa(Integer.valueOf(auth.getEmpresa()[0]));
empresa.setEmpEntidade(ent);
} else {
throw new ComercialException("O destinatário não é a empresa logada!");
}
}
private void validarCompra() throws OpenSigException {
Ide ide = nfe.getInfNFe().getIde();
ICMSTot tot = nfe.getInfNFe().getTotal().getICMSTot();
// tenta achar a compra
FiltroObjeto fo = new FiltroObjeto("empEmpresa", ECompara.IGUAL, empresa);
FiltroTexto ft = new FiltroTexto("empFornecedor.empEntidade.empEntidadeDocumento1", ECompara.IGUAL, nfe.getInfNFe().getEmit().getCNPJ());
FiltroNumero fn = new FiltroNumero("comCompraNumero", ECompara.IGUAL, ide.getNNF());
GrupoFiltro gf = new GrupoFiltro(EJuncao.E, new IFiltro[] { fo, ft, fn });
compra = new ComCompra();
compra = (ComCompra) servico.selecionar(compra, gf, false);
if (compra != null) {
throw new ComercialException("A compra já existe!");
} else {
// recupera os demais campos do xml
Date dtData = null;
try {
dtData = new SimpleDateFormat("yyyy-MM-dd").parse(ide.getDEmi());
} catch (ParseException e) {
UtilServer.LOG.debug("Data invalida.");
throw new ComercialException(auth.getConf().get("errInvalido") + " -> dEmi");
}
compra = new ComCompra();
compra.setEmpEstado(getEstado(ide.getCUF()));
compra.setComCompraEmissao(dtData);
compra.setComCompraRecebimento(new Date());
compra.setComCompraSerie(Integer.valueOf(ide.getSerie()));
compra.setComCompraNumero(Integer.valueOf(ide.getNNF()));
compra.setComCompraIcmsBase(Double.valueOf(tot.getVBC()));
compra.setComCompraIcmssubBase(Double.valueOf(tot.getVBCST()));
compra.setComCompraIcmsValor(Double.valueOf(tot.getVICMS()));
compra.setComCompraIcmssubValor(Double.valueOf(tot.getVST()));
compra.setComCompraValorFrete(Double.valueOf(tot.getVFrete()));
compra.setComCompraValorSeguro(Double.valueOf(tot.getVSeg()));
compra.setComCompraValorDesconto(Double.valueOf(tot.getVDesc()));
compra.setComCompraValorIpi(Double.valueOf(tot.getVIPI()));
compra.setComCompraValorOutros(Double.valueOf(tot.getVOutro()));
compra.setComCompraValorProduto(Double.valueOf(tot.getVProd()));
compra.setComCompraValorNota(Double.valueOf(tot.getVNF()));
compra.setComCompraPaga(nfe.getInfNFe().getCobr() != null);
compra.setFinPagar(getPagar());
compra.setComCompraObservacao("");
}
}
private EmpEstado getEstado(String ibge) throws OpenSigException {
FiltroNumero fn = new FiltroNumero("empEstadoIbge", ECompara.IGUAL, ibge);
EmpEstado est = (EmpEstado) servico.selecionar(new EmpEstado(), fn, true);
return est;
}
private FinPagar getPagar() throws OpenSigException {
// pagar
FinPagar pagar = new FinPagar();
List<FinPagamento> pagamentos = new ArrayList<FinPagamento>();
pagar.setFinConta(new FinConta(Integer.valueOf(auth.getConf().get("conta.padrao"))));
pagar.setFinPagamentos(pagamentos);
pagar.setFinPagarObservacao("");
// acha a forma de pagamento boleto
FiltroTexto ft = new FiltroTexto("finFormaDescricao", ECompara.IGUAL, auth.getConf().get("txtBoleto"));
FinForma forma = (FinForma) servico.selecionar(new FinForma(), ft, false);
// caso nao encontre coloca a primeira
if (forma == null) {
forma = new FinForma(1);
forma.setFinFormaDescricao(auth.getConf().get("txtDinheiro"));
}
if (nfe.getInfNFe().getCobr() != null) {
List<Dup> duplicatas = nfe.getInfNFe().getCobr().getDup();
int par = 1;
for (Dup dup : duplicatas) {
// data
Date dtData = null;
try {
dtData = new SimpleDateFormat("yyyy-MM-dd").parse(dup.getDVenc());
} catch (ParseException e) {
dtData = new Date();
}
// parcela
String parcela = par < 10 ? "0" + par : "" + par;
parcela += duplicatas.size() < 10 ? "/0" + duplicatas.size() : "/" + duplicatas.size();
// pagamentos
FinPagamento pag = new FinPagamento();
pag.setFinForma(forma);
pag.setFinPagamentoDocumento(dup.getNDup());
pag.setFinPagamentoValor(Double.valueOf(dup.getVDup()));
pag.setFinPagamentoParcela(parcela);
pag.setFinPagamentoCadastro(new Date());
pag.setFinPagamentoVencimento(dtData);
pag.setFinPagar(pagar);
pag.setFinPagamentoStatus(auth.getConf().get("txtAberto"));
pag.setFinPagamentoObservacao("");
pagamentos.add(pag);
par++;
}
}
return pagar;
}
private void validarFornecedor() throws OpenSigException {
// recupera o cnpj
fornecedor = getFornecedor(nfe.getInfNFe().getEmit().getCNPJ());
// caso seje um novo
if (fornecedor.getEmpFornecedorId() == 0) {
EmpresaServiceImpl<EmpFornecedor> servico = new EmpresaServiceImpl<EmpFornecedor>(auth);
servico.salvar(fornecedor);
}
fornecedor.anularDependencia();
}
private EmpFornecedor getFornecedor(String cnpj) throws OpenSigException {
try {
cnpj = UtilServer.formataTexto(cnpj, "##.###.###/####-##");
FiltroTexto ft = new FiltroTexto("empEntidade.empEntidadeDocumento1", ECompara.IGUAL, cnpj);
fornecedor = (EmpFornecedor) servico.selecionar(fornecedor, ft, false);
} catch (Exception e) {
fornecedor = null;
}
if (fornecedor == null) {
Emit emit = nfe.getInfNFe().getEmit();
TEnderEmi ende = emit.getEnderEmit();
// seta fornecedor
EmpEntidade enti = new EmpEntidade();
enti.setEmpEntidadeNome1(emit.getXNome());
String fantasia = emit.getXFant() != null ? emit.getXFant() : emit.getXNome();
if (fantasia.length() > 15) {
fantasia = fantasia.substring(0, 15);
}
enti.setEmpEntidadeNome2(fantasia);
enti.setEmpEntidadeDocumento1(cnpj);
enti.setEmpEntidadeDocumento2(emit.getIE());
enti.setEmpEntidadeAtivo(true);
enti.setEmpEntidadePessoa(auth.getConf().get("txtJuridica"));
enti.setEmpEntidadeObservacao("");
// seta o endereco
EmpEndereco endereco = new EmpEndereco();
endereco.setEmpEnderecoTipo(new EmpEnderecoTipo(Integer.valueOf(auth.getConf().get("nfe.tipoendecom"))));
endereco.setEmpEnderecoLogradouro(ende.getXLgr());
endereco.setEmpEnderecoNumero(Integer.valueOf(ende.getNro().replaceAll("\\D", "")));
endereco.setEmpEnderecoComplemento(ende.getXCpl() != null ? ende.getXCpl() : "");
endereco.setEmpEnderecoBairro(ende.getXBairro());
FiltroNumero fn = new FiltroNumero("empMunicipioIbge", ECompara.IGUAL, ende.getCMun());
EmpMunicipio empM = (EmpMunicipio) servico.selecionar(new EmpMunicipio(), fn, false);
endereco.setEmpMunicipio(empM);
String cep = ende.getCEP() != null ? ende.getCEP().substring(0, 5) + "-" + ende.getCEP().substring(5) : "00000-000";
endereco.setEmpEnderecoCep(cep);
List<EmpEndereco> ends = new ArrayList<EmpEndereco>();
ends.add(endereco);
enti.setEmpEnderecos(ends);
// seta o contato telefone
String fone = ende.getFone() != null ? ende.getFone().substring(0, 2) + " " + ende.getFone().substring(2, 6) + "-" + ende.getFone().substring(6) : "0000-0000";
EmpContato contato = new EmpContato();
contato.setEmpContatoTipo(new EmpContatoTipo(Integer.valueOf(auth.getConf().get("nfe.tipoconttel"))));
contato.setEmpContatoDescricao(fone);
contato.setEmpContatoPessoa("");
List<EmpContato> conts = new ArrayList<EmpContato>();
conts.add(contato);
enti.setEmpContatos(conts);
fornecedor = new EmpFornecedor();
fornecedor.setEmpEntidade(enti);
}
return fornecedor;
}
private void validarProduto() throws OpenSigException {
// pega os tributados
Lista<ProdTributacao> tributo = servico.selecionar(new ProdTributacao(), 0, 0, null, false);
tributacao = tributo.getLista();
// pega os ipis
Lista<ProdIpi> tributoIpi = servico.selecionar(new ProdIpi(), 0, 0, null, false);
ipis = tributoIpi.getLista();
// pega as embalagens
Lista<ProdEmbalagem> emb = servico.selecionar(new ProdEmbalagem(), 0, 0, null, false);
embalagem = emb.getLista();
// seta os tipos
comProdutos = new ArrayList<ComCompraProduto>();
for (Det det : nfe.getInfNFe().getDet()) {
MyIcms myicms = getIcms(det.getImposto().getICMS());
String ipi = "";
String pIpi = "";
try {
ipi = det.getImposto().getIPI().getIPITrib().getCST();
pIpi = det.getImposto().getIPI().getIPITrib().getPIPI();
if (pIpi == null) {
pIpi = "0.00";
}
} catch (Exception e) {
ipi = "99";
pIpi = "0.00";
}
// setando o produto da compra
ComCompraProduto comProd = new ComCompraProduto();
ProdProduto prod = getProduto(det.getProd(), myicms, ipi);
comProd.setProdProduto(prod);
comProd.setProdEmbalagem(prod.getProdEmbalagem());
int cfop = Integer.valueOf(det.getProd().getCFOP());
comProd.setComCompraProdutoCfop(cfop >= 5000 ? cfop - 4000 : cfop);
comProd.setComCompraProdutoIcms(Double.valueOf(myicms.getAliquota()));
comProd.setComCompraProdutoIpi(Double.valueOf(pIpi));
comProd.setComCompraProdutoQuantidade(Double.valueOf(det.getProd().getQCom()));
comProd.setComCompraProdutoValor(Double.valueOf(det.getProd().getVUnCom()));
comProd.setComCompraProdutoTotal(Double.valueOf(det.getProd().getVProd()));
comProd.setComCompraProdutoPreco(prod.getProdProdutoPreco());
comProd.setComCompra(compra);
comProdutos.add(comProd);
}
}
private MyIcms getIcms(ICMS icms) {
MyIcms myicms = new MyIcms();
// normal
if (icms.getICMS00() != null) {
myicms.setAliquota(icms.getICMS00().getPICMS());
myicms.setCst(icms.getICMS00().getCST());
myicms.setOrigem(icms.getICMS00().getOrig());
} else if (icms.getICMS10() != null) {
myicms.setAliquota(icms.getICMS10().getPICMS());
myicms.setCst(icms.getICMS10().getCST());
myicms.setOrigem(icms.getICMS10().getOrig());
} else if (icms.getICMS20() != null) {
myicms.setAliquota(icms.getICMS20().getPICMS());
myicms.setCst(icms.getICMS20().getCST());
myicms.setOrigem(icms.getICMS20().getOrig());
} else if (icms.getICMS30() != null) {
myicms.setAliquota("0");
myicms.setCst(icms.getICMS30().getCST());
myicms.setOrigem(icms.getICMS30().getOrig());
} else if (icms.getICMS40() != null) {
myicms.setAliquota("0");
myicms.setCst(icms.getICMS40().getCST());
myicms.setOrigem(icms.getICMS40().getOrig());
} else if (icms.getICMS51() != null) {
myicms.setAliquota(icms.getICMS51().getPICMS());
myicms.setCst(icms.getICMS51().getCST());
myicms.setOrigem(icms.getICMS51().getOrig());
} else if (icms.getICMS60() != null) {
myicms.setAliquota("0");
myicms.setCst(icms.getICMS60().getCST());
myicms.setOrigem(icms.getICMS60().getOrig());
} else if (icms.getICMS70() != null) {
myicms.setAliquota(icms.getICMS70().getPICMS());
myicms.setCst(icms.getICMS70().getCST());
myicms.setOrigem(icms.getICMS70().getOrig());
} else if (icms.getICMS90() != null) {
myicms.setAliquota(icms.getICMS90().getPICMS());
myicms.setCst(icms.getICMS90().getCST());
myicms.setOrigem(icms.getICMS90().getOrig());
// simples
} else if (icms.getICMSSN101() != null) {
myicms.setAliquota("0");
myicms.setCst(icms.getICMSSN101().getCSOSN());
myicms.setOrigem(icms.getICMSSN101().getOrig());
} else if (icms.getICMSSN102() != null) {
myicms.setAliquota("0");
myicms.setCst(icms.getICMSSN102().getCSOSN());
myicms.setOrigem(icms.getICMSSN102().getOrig());
} else if (icms.getICMSSN201() != null) {
myicms.setAliquota("0");
myicms.setCst(icms.getICMSSN201().getCSOSN());
myicms.setOrigem(icms.getICMSSN201().getOrig());
} else if (icms.getICMSSN202() != null) {
myicms.setAliquota("0");
myicms.setCst(icms.getICMSSN202().getCSOSN());
myicms.setOrigem(icms.getICMSSN202().getOrig());
} else if (icms.getICMSSN500() != null) {
myicms.setAliquota("0");
myicms.setCst(icms.getICMSSN500().getCSOSN());
myicms.setOrigem(icms.getICMSSN500().getOrig());
} else if (icms.getICMSSN900() != null) {
myicms.setAliquota("0");
myicms.setCst(icms.getICMSSN900().getCSOSN());
myicms.setOrigem(icms.getICMSSN900().getOrig());
}
return myicms;
}
private ProdProduto getProduto(Prod prod, MyIcms icms, String ipi) throws OpenSigException {
String ean = prod.getCEAN();
// barra
GrupoFiltro grupoBarra = new GrupoFiltro();
FiltroTexto ft1 = new FiltroTexto("prodProdutoBarra", ECompara.IGUAL, ean);
grupoBarra.add(ft1, EJuncao.OU);
// barra do preco
FiltroTexto ft2 = new FiltroTexto("prodPrecoBarra", ECompara.IGUAL, ean);
ft2.setCampoPrefixo("t2.");
grupoBarra.add(ft2, EJuncao.OU);
// busca
ProdProduto produto = new ProdProduto();
Lista<ProdProduto> lista = servico.selecionar(produto, 0, 1, grupoBarra, false);
// verifica se achou
if (lista.getTotal() == 1) {
produto = lista.getLista().get(0);
produto.anularDependencia();
produto.setProdEmbalagem(getEmbalagem(prod.getUCom()));
produto.setProdTipo(new ProdTipo(1));
produto.setProdIpi(getIpi(ipi));
produto.setProdOrigem(new ProdOrigem(Integer.valueOf(icms.getOrigem()) + 1));
produto.setEmpFornecedor(fornecedor);
produto.setEmpFabricante(fornecedor);
produto.setProdTributacao(getTributacao(icms.getCst()));
// caso nao acha cria um novo para confirmar
} else {
produto.setProdProdutoNcm(prod.getNCM());
produto.setProdProdutoBarra(ean);
produto.setProdProdutoReferencia(prod.getCProd());
produto.setProdProdutoDescricao(prod.getXProd());
produto.setProdEmbalagem(new ProdEmbalagem(1));
produto.setProdTipo(new ProdTipo(1));
produto.setProdProdutoVolume(1);
produto.setProdOrigem(new ProdOrigem(Integer.valueOf(icms.getOrigem()) + 1));
produto.setEmpFornecedor(fornecedor);
produto.setEmpFabricante(fornecedor);
produto.setProdTributacao(getTributacao(icms.getCst()));
produto.setProdIpi(getIpi(ipi));
produto.setProdProdutoAtivo(true);
produto.setProdProdutoCategoria(auth.getConf().get("categoria.padrao") + "::");
produto.setProdProdutoCadastrado(new Date());
produto.setProdProdutoCusto(Double.valueOf(prod.getVUnCom()));
produto.setProdProdutoPreco(0.00);
produto.setProdProdutoObservacao("");
}
return produto;
}
private ProdEmbalagem getEmbalagem(String nome) {
// se nao achar colocar a padrao UND
ProdEmbalagem resp = new ProdEmbalagem(1);
// percorre as embalagens
for (ProdEmbalagem emb : embalagem) {
if (emb.getProdEmbalagemNome().equalsIgnoreCase(nome)) {
resp = emb;
break;
}
}
return resp;
}
private ProdTributacao getTributacao(String cst) {
// se nao achar colocar a padrao 00
ProdTributacao resp = null;
// percorre as tributacoes
for (ProdTributacao trib : tributacao) {
if (cst.length() == 2 && trib.getProdTributacaoCst().equals(cst)) {
resp = trib;
break;
} else if (cst.length() == 3 && trib.getProdTributacaoCson().equals(cst)) {
resp = trib;
break;
} else if (trib.getProdTributacaoCst().equals("00")) {
resp = trib;
}
}
return resp;
}
private ProdIpi getIpi(String cst) {
// se nao achar colocar a padrao 00
ProdIpi resp = new ProdIpi(1);
// percorre as tributacoes
for (ProdIpi ipi : ipis) {
if (ipi.getProdIpiCstSaida().equals(cst)) {
resp = ipi;
break;
}
}
return resp;
}
public ComCompra getCompra() {
compra.setEmpEmpresa(empresa);
compra.setEmpFornecedor(fornecedor);
compra.setComCompraProdutos(comProdutos);
compra.getFinPagar().setEmpEmpresa(empresa);
compra.getFinPagar().setEmpEntidade(fornecedor.getEmpEntidade());
return compra;
}
private class MyIcms {
private String aliquota;
private String origem;
private String cst;
public MyIcms() {
}
public String getAliquota() {
return aliquota;
}
public void setAliquota(String aliquota) {
this.aliquota = aliquota;
}
public String getOrigem() {
return origem;
}
public void setOrigem(String origem) {
this.origem = origem;
}
public String getCst() {
return cst;
}
public void setCst(String cst) {
this.cst = cst;
}
}
}
|
/**
* Klass som hanterar kunder. Varje kund har sina konton i en arraylist.
*
* @author Lukas Skog Andersen, luksok-8
*/
package luksok8;
import java.io.Serializable;
import java.util.ArrayList;
@SuppressWarnings("serial")
public class Customer implements Serializable {
private String surName;
private String firstName;
private String personalIdentityNo;
ArrayList<Account> accounts = new ArrayList<Account>();
/**
* Konstruktor
* @param firstName kundens förnamn
* @param surName kundens efternamn
* @param personalIdentityNo kundens personnummer
*/
public Customer(String firstName, String surName, String personalIdentityNo) {
this.surName = surName;
this.firstName = firstName;
this.personalIdentityNo = personalIdentityNo;
}
/**
* Ändrar kundens efternamn
*
* @param newSurName nytt efternamn
*/
public void setSurName(String newSurName) {
surName = newSurName;
}
/**
* Ändrar kundens förnamn
*
* @param newFirstName nytt förnamn
*/
public void setFirstName(String newFirstName) {
firstName = newFirstName;
}
/**
* Hämtar personnummer
*
* @return Sträng med kundens personnummer
*/
public String getPersonalId() {
return personalIdentityNo;
}
/**
* Hämtar en sträng med personlig info
*
* @return Sträng med personlig information om kunden
*/
public String getPersonalInfo() {
return firstName + " " + surName + " " + personalIdentityNo;
}
/**
* Hämtar en ArrayList med info om alla konton
*
* @param interestYesNo int, 1 för ränta, 0 om inte
* @return ArrayList med kundens alla konton
*/
public ArrayList<String> getAccountInfo(int interestYesNo) {
ArrayList<String> accountInfo = new ArrayList<String>();
for (int i = 0; i < accounts.size(); i++) {
Account konto = accounts.get(i);
if (interestYesNo == 1) {
double interest = Math.round(accounts.get(i).getInterest());
accountInfo.add(konto.toString() + " " + Double.toString(interest));
} else {
accountInfo.add(konto.toString());
}
}
return accountInfo;
}
/**
* Tar bort ett konto
*
* @param accountId kontonumret som ska tas bort
* @return boolean, true om kontot tas bort
*/
public boolean deleteAccount(int accountId) {
int accIndex = accountIndex(accountId);
if (!(accIndex == -1)) {
accounts.remove(accIndex);
return true;
}
return false;
}
/**
* Skapar ett sparkonto
*
* @return int med det nya kontonumret
*/
public int createSavingsAccount() {
SavingsAccount newAccount = new SavingsAccount();
accounts.add(newAccount);
return accounts.get(accounts.size() - 1).getAccountNo();
}
/**
* Skapar ett kreditkonto
*
* @return int med det nya kontonumret
*/
public int createCreditAccount() {
CreditAccount newAccount = new CreditAccount();
accounts.add(newAccount);
return accounts.get(accounts.size() - 1).getAccountNo();
}
/**
* Hämtar info om ett specifikt konto
*
* @param accountId Sökt kontonummer
* @param interestYesNo int = 1 för ränta, 0 annars
* @return Sträng med info om kontot
*/
public String oneAccountInfo(int accountId, int interestYesNo) {
int index = accountIndex(accountId);
if (!(index == -1)) {
if (interestYesNo == 1) {
double interest = accounts.get(index).getInterest();
return accounts.get(index).toString() + " " + interest;
} else {
return accounts.get(index).toString();
}
} else {
return "";
}
}
/**
* Kollar om ett visst kontonummer finns hos kund
*
* @param accountId Sökt kontonummer
* @return Boolean, true om kontot finns hos kund
*/
public Boolean lookForAccount(int accountId) {
int accIndex = accountIndex(accountId);
if (!(accIndex == -1)) {
return true;
}
return false;
}
/**
* Kollar vilket index ett visst konto har hos en kund
*
* @param accountId Sökt kontonummer
* @return int med det index som kontot har, -1 om det inte tillhör kund
*/
public int accountIndex(int accountId) {
int accNo = 0;
for (int i = 0; i < accounts.size(); i++) {
accNo = accounts.get(i).getAccountNo();
if (accNo == accountId) {
return i;
}
}
return -1;
}
/**
* Hanterar en insättning
*
* @param accountId Önskat kontonummer
* @param amount Insättningssumma
* @return boolean, true om insättning lyckas
*/
public boolean deposit(int accountId, double amount) {
int accIndex = accountIndex(accountId);
if (!(accIndex == -1)) {
accounts.get(accIndex).deposit(amount);
return true;
} else {
return false;
}
}
/**
* Hanterar ett uttag
*
* @param accountId Önskat kontonummer
* @param amount Uttagssumma
* @return boolean, true om uttag lyckas
*/
public boolean withdraw(int accountId, double amount) {
int accIndex = accountIndex(accountId);
if (!(accIndex == -1)) {
if (accounts.get(accIndex).withdraw(amount)) {
return true;
}
}
return false;
}
/**
* Metod som hämtar kontonummer till konto på givet index.
* @param index det index som sökta kontot har
* @return det sökta kontonumret
*/
public int getAccountNo(int index) {
return accounts.get(index).getAccountNo();
}
public void saveCustomer() {
for(int i = 0; i < accounts.size(); i++ ) {
}
}
}
|
import org.testng.annotations.Test;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class TestNG {
public WebDriver driver;
public WebElement searchbox;
public WebElement searchbutton;
public WebElement linktext;
// locate id of google searchbox
@Test
public void searchbox() {
searchbox = driver.findElement(By.id("lst-ib"));
// enter "selenium" in the searchbox
searchbox.sendKeys("Selenium");
// Find search button ID
searchbutton = driver.findElement(By.name("btnK"));
// select search button
searchbutton.submit();
// Wait for link
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='rso']/div[1]/div/div[1]/div/h3/a")));
// Find link for selenium
linktext = driver.findElement(By.xpath("//*[@id='rso']/div[1]/div/div[1]/div/h3/a"));
// Select Selenium link
linktext.click();
// Select Download tab on Selenium page
driver.findElement(By.cssSelector("#menu_download > a")).click();
// Select Javadoc ink
driver.findElement(
By.cssSelector("#mainContent > table:nth-child(13) > tbody > tr:nth-child(1) > td:nth-child(6) > a"))
.click();
// Switch to frame containing Selenium package
driver.switchTo().frame("packageListFrame");
// Select Selenium package
driver.findElement(By.xpath("/html/body/div[2]/ul/li[5]/a")).click();
// switch to default frame
driver.switchTo().defaultContent();
// Switch to frame containing webdriver
driver.switchTo().frame("packageFrame");
// Select Webdriver interface
driver.findElement(By.cssSelector("body > div > ul:nth-child(2) > li:nth-child(10) > a > span")).click();
// take a screenshot
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
// now copy the screenshot to desired location using copyFile method
// this will create a different file name each time using the
// currentTime
FileUtils.copyFile(srcFile,
new File("C:\\Selenium Screenshots\\" + System.currentTimeMillis() + " testing.png"));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(srcFile.getAbsolutePath());
// switch to default frame
driver.switchTo().defaultContent();
// view the page source and save to a file
String pagesourcevalue = driver.getPageSource();
try {
File f = new File("c:\\Selenium Screenshots\\PageSource" + System.currentTimeMillis() + ".txt");
FileWriter writer = new FileWriter(f);
writer.write(pagesourcevalue);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver",
"U:\\git\\automation-testing\\resources\\webDrivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.com");
driver.manage().window().maximize();
}
@AfterTest
public void afterTest() {
System.out.println(" I am done");
driver.close();
}
}
|
package com.github.w4o.sa.controller;
import com.github.w4o.sa.commons.CommonResult;
import com.github.w4o.sa.dto.CreateRoleParam;
import com.github.w4o.sa.dto.UpdateRoleParam;
import com.github.w4o.sa.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author frank
* @date 2019-05-17
*/
@RestController
@RequestMapping("/role")
@Api(tags = "系统管理-角色管理")
public class RoleController {
private final RoleService roleService;
@Autowired
public RoleController(RoleService roleService) {
this.roleService = roleService;
}
/**
* 角色列表
*/
@ApiOperation("获取角色列表")
@GetMapping
public CommonResult list(@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "page", defaultValue = "1") Integer page,
@RequestParam(value = "size", defaultValue = "5") Integer size) {
return new CommonResult().okPage(roleService.list(name, page, size));
}
/**
* 创建角色
*/
@ApiOperation("创建角色")
@PostMapping
public CommonResult create(@RequestBody CreateRoleParam createRoleParam) {
return new CommonResult().ok(roleService.create(createRoleParam));
}
/**
* 更新角色信息
*/
@ApiOperation("更新角色信息")
@PutMapping("/{id}")
public CommonResult update(@PathVariable(value = "id") Integer id,
@RequestBody UpdateRoleParam updateRoleParam) {
return new CommonResult().ok(roleService.updateById(id, updateRoleParam));
}
/**
* 删除角色信息
*/
@ApiOperation("删除角色信息")
@DeleteMapping("/{id}")
public CommonResult delete(@PathVariable(value = "id") Integer id) {
return new CommonResult().ok(roleService.deleteById(id));
}
/**
* 获取权限和当前角色分配的权限
*
* @param id 角色id
*/
@ApiOperation("获取所有权限和当前角色分配的权限")
@GetMapping("/{id}/permissions")
public CommonResult permissions(@PathVariable(value = "id") Integer id) {
return new CommonResult().ok(roleService.getPermissions(id));
}
/**
* 更新角色权限
*
* @param id 角色id
*/
@ApiOperation("更新角色权限")
@PutMapping("/{id}/permissions")
public CommonResult updatePermissions(@PathVariable(value = "id") Integer id,
@RequestBody Integer[] permissions) {
roleService.updatePermissions(id, permissions);
return new CommonResult().ok();
}
}
|
package com.elasticsearch.elasticsearch.model;
import java.util.List;
public class UserDto {
private String username;
private String password;
private String firstName;
private String lastName;
private long salary;
private int age;
private String email;
/**
* Roles are being eagerly loaded here because
* they are a fairly small collection of items for this example.
*/
private List<Role> roles;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
package net.learn2develop.moviedata_finaltask10.dialogs;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import net.learn2develop.moviedata_finaltask10.R;
public class DialogAbout extends AlertDialog.Builder {
public DialogAbout(Context context) {
super(context);
setTitle(context.getString(R.string.About));
setMessage(context.getString(R.string.created_by) + " Kisker");
setPositiveButton(context.getString(R.string.Ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
public AlertDialog prepareDialog() {
AlertDialog dialog = create();
dialog.setCanceledOnTouchOutside(true);
return dialog;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Service;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author Hoang Minh
*/
public interface LoanType {
public ResultSet getAllLoanType() throws SQLException;
public ResultSet getLoanTypeByID(int ID) throws SQLException;
public boolean DelLoanType(int ID) throws SQLException;
public boolean InsertLoanType(String TypeName, float InterestRate, String Des) throws SQLException;
public boolean changeLoanType(int ID, String TypeName, float InterestRate, String Des) throws SQLException;
public int countLoanDetailByLoanTypeID(int ID) throws SQLException;
}
|
package structuralPatterns.proxyPattern;
public class Gamer implements IGamer{
@Override
public void play() {
System.out.println("gamer play");
}
@Override
public void shoot() {
System.out.println("gamer shoot");
}
}
|
package persistenza.dao;
import business.assistenza.Ticket;
import exceptions.DatabaseException;
import exceptions.TicketNotFoundException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import persistenza.DatabaseConnection;
/** DAO per il salvataggio persistente di un Ticket. */
public class TicketDao {
/**
* Salva il Ticket sul persistenza.
*
* @param t Il Ticket da salvare
* @throws DatabaseException Errore nel salvataggio del Ticket
*/
public static void save(Ticket t) throws DatabaseException {
try {
PreparedStatement prep =
DatabaseConnection.getInstance().getCon().prepareStatement(Query.newTicket);
prep.setString(1, t.getNomeCognome());
prep.setString(2, t.getCf());
prep.setString(3, t.getIndirizzo());
prep.setLong(4, t.getNumTel());
prep.setString(5, t.getTipo());
prep.setString(6, t.getNomeProdotto());
prep.setLong(7, t.getCodiceProdotto());
prep.setString(8, t.getNumeroDiSerie());
prep.setLong(9, t.getCodiceScontrino());
prep.setString(10, t.getDataScontrino());
prep.setString(11, t.getProblema());
prep.setString(12, t.getDataApertura());
prep.setString(13, t.getStato());
prep.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw new DatabaseException("Errore nel salvataggio del Ticket");
}
}
/**
* Salva le informazioni di un Ticket nel persistenza.
*
* @param apertura data di apertura del Ticket
* @param cf Codice Fiscale del Cliente
* @param serie Numero di Serie del Prodotto
* @return il Ticket cercato
* @throws TicketNotFoundException Ticket non trovato
* @throws DatabaseException Errore del Database
*/
public static Ticket getTicket(String apertura, String cf, String serie)
throws TicketNotFoundException, DatabaseException {
try {
PreparedStatement prep =
DatabaseConnection.getInstance().getCon().prepareStatement(Query.getTicket);
prep.setString(1, apertura + "%");
prep.setString(2, cf);
prep.setString(3, serie);
ResultSet res = prep.executeQuery();
if (!res.next()) {
throw new TicketNotFoundException("Ticket non trovato. Controllare i campi");
} else {
Ticket t = new Ticket();
t.setNomeCognome(res.getString("NOME_CLIENTE"));
t.setCf(res.getString("CODICE_FISCALE"));
t.setIndirizzo(res.getString("INDIRIZZO"));
t.setTipo(res.getString("TIPO"));
t.setNomeProdotto(res.getString("NOME_PRODOTTO"));
t.setNumeroDiSerie(res.getString("NUMERO_DI_SERIE"));
t.setNumTel(res.getLong("NUM_TEL"));
t.setCodiceScontrino(res.getInt("SCONTRINO"));
t.setDataApertura(res.getString("DATA_APERTURA"));
t.setCodiceProdotto(res.getLong("PRODOTTO"));
t.setStato(res.getString("STATO"));
return t;
}
} catch (SQLException e) {
e.printStackTrace();
throw new DatabaseException("Errore nella ricerca del Ticket");
}
}
}
|
package domain;
import datasource.daos.AfspeellijstTrackDAO;
import datasource.daos.TrackDAO;
import domain.datamappers.TrackDataMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
class AfspeellijstTest {
private static final int ID = 1;
private Afspeellijst afspeellijstUnderTest;
private TrackDAO mockedTrackDAO;
private AfspeellijstTrackDAO mockedAfspeellijstTrackDAO;
private TrackDataMapper mockedTrackDataMapper;
@BeforeEach
void setUp() {
afspeellijstUnderTest = new Afspeellijst();
this.mockedTrackDAO = mock(TrackDAO.class);
this.mockedAfspeellijstTrackDAO = mock(AfspeellijstTrackDAO.class);
this.mockedTrackDataMapper = mock(TrackDataMapper.class);
this.afspeellijstUnderTest.setTrackDataMapper(mockedTrackDataMapper);
this.afspeellijstUnderTest.setTrackDAO(mockedTrackDAO);
this.afspeellijstUnderTest.setAfspeellijstTrackDAO(mockedAfspeellijstTrackDAO);
}
@Test
void testBerekenAfspeellijstRoeptSelectAan() {
// Arrange
var tracks = new ArrayList<Track>();
var afspeelduur = 10;
tracks.add(new Lied(ID, "a", afspeelduur, true, "a", "a"));
tracks.add(new Lied(ID, "b", afspeelduur, true, "a", "a"));
// Act
int actual = afspeellijstUnderTest.berekenAfspeellijstLengte(ID);
// Assert
verify(mockedAfspeellijstTrackDAO).select(ID, false);
}
@Test
void testBerekenAfspeellijstLengteOfLengteKlopt() {
// Arrange
var tracks = new ArrayList<Track>();
var afspeelduur = 10;
tracks.add(new Lied(ID, "a", afspeelduur, true, "a", "a"));
tracks.add(new Lied(ID, "b", afspeelduur, true, "a", "a"));
when(mockedTrackDataMapper.mapResultSetToListDomain(mockedAfspeellijstTrackDAO.select(ID, false))).thenReturn(tracks);
// Act
int actual = afspeellijstUnderTest.berekenAfspeellijstLengte(ID);
// Assert
assertEquals(afspeelduur * 2, actual);
}
@Test
void testVoegTracksToeCallsAfspeellijstTrackDAOIInsert() {
// Arrange
var track = new Lied(ID, "a", 1, true, "a", "a");
var afspeellijst = new Afspeellijst();
afspeellijst.setId(ID);
// Act
afspeellijstUnderTest.voegTrackToe(track, afspeellijst);
// Assert
verify(mockedAfspeellijstTrackDAO).insert(afspeellijst.getId(), track.getId());
}
@Test
void testVerwijderTrackRoeptDeleteAan() {
// Arrange
// Act
afspeellijstUnderTest.verwijderTrack(ID, ID);
// Assert
verify(mockedAfspeellijstTrackDAO).delete(ID,ID);
}
@Test
void testOpenTracksVoorAfspeellijstRoeptSelectAanBijFalse() {
// Arrange
// Act
afspeellijstUnderTest.openTracksAfspeellijst(ID, false);
// Assert
verify(mockedAfspeellijstTrackDAO).select(ID, false);
}
@Test
void testOpenTracksVoorAfspeellijstRoeptSelectAanBijTrue() {
// Arrange
// Act
afspeellijstUnderTest.openTracksAfspeellijst(ID, true);
// Assert
verify(mockedAfspeellijstTrackDAO).select(ID, true);
}
}
|
/**
* The MIT License
* Copyright © 2020 Stephen Dankbar
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.sdankbar.qml.graph;
import java.awt.geom.Point2D;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.lang3.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sdankbar.qml.JQMLModelFactory;
import com.github.sdankbar.qml.JVariant;
import com.github.sdankbar.qml.graph.parsing.EdgeDefinition;
import com.github.sdankbar.qml.graph.parsing.GraphVizParser;
import com.github.sdankbar.qml.models.AbstractJQMLMapModel.PutMode;
import com.github.sdankbar.qml.models.list.JQMLListModel;
import com.github.sdankbar.qml.models.singleton.JQMLSingletonModel;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
/**
* Model for sending Graph Vertex and Edge layout and user defined information
* to QML for drawing. Creates 3 models that send data to QML.
*
* <prefix>_graph - Contains information about the entire graph. Valid keys are
* in the GraphKey Enum.
*
* <prefix>_vertices - Contains information about a vertex in the graph. Valid
* keys are in the VertexKey Enum plus any user defined keys.
*
*
* <prefix>_edges - Contains information about an edge in the graph. Valid keys
* are in the EdgeKey Enum.
*
* @param <K> User define key/role type. toString() of type must return valid
* QML identifiers.
*/
public class GraphModel<K> {
private static final JVariant ZERO_VARIANT = new JVariant(0);
private static final JVariant ONE_VARIANT = new JVariant(1);
private static final Logger log = LoggerFactory.getLogger(GraphModel.class);
private static final ExecutorService LAYOUT_EXEC = Executors.newSingleThreadExecutor();
/**
* Create a new GraphModel using an Enum as the user define role type.
*
* @param modelPrefix The prefix prepended to the 3 QML models this class
* creates (_graph, _vertices, and _edges).
* @param factory Factory for creating the models.
* @param keyClass Class of an Enum type that contains the user defined
* roles.
* @param dpi Dots per inch on the display that will display this
* GraphModel's graph. Used for converting between inches
* (used by GraphViz) and pixels.
* @return The new GraphModel.
*/
public static <T extends Enum<T>> GraphModel<T> create(final String modelPrefix, final JQMLModelFactory factory,
final Class<T> keyClass, final double dpi) {
final ImmutableSet<String> userKeys = EnumSet.allOf(keyClass).stream().map(Enum::name)
.collect(ImmutableSet.toImmutableSet());
return new GraphModel<>(modelPrefix, factory, userKeys, dpi);
}
/**
* Create a new GraphModel using a Set of keys.
*
* @param modelPrefix The prefix prepended to the 3 QML models this class
* creates (_graph, _vertices, and _edges).
* @param factory Factory for creating the models.
* @param keySet Set of all valid keys/roles for sending user defined data
* to QML.
* @param dpi Dots per inch on the display that will display this
* GraphModel's graph. Used for converting between inches
* (used by GraphViz) and pixels.
* @return The new GraphModel.
*/
public static <T> GraphModel<T> create(final String modelPrefix, final JQMLModelFactory factory,
final ImmutableSet<T> keySet, final double dpi) {
final ImmutableSet<String> stringKeySet = keySet.stream().map(Object::toString)
.collect(ImmutableSet.toImmutableSet());
return new GraphModel<>(modelPrefix, factory, stringKeySet, dpi);
}
private static String getIDAsGraphVizIDString(final long uuid) {
final String oct = Long.toOctalString(uuid);
// '0' == 48, map to 65 = 'A'
// '7' == 55, map to 72 = 'H'
return oct.chars().map(c -> (char) (c + 17))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
}
private static String runGraphViz(final String graphDef) {
final ProcessBuilder builder = new ProcessBuilder();
// dot command
// plain output format
// invert y coordinates, (0, 0) is top left.
if (SystemUtils.IS_OS_WINDOWS) {
builder.command("dot.exe", "-Tplain", "-y");
} else {
builder.command("dot", "-Tplain", "-y");
}
try {
final Process p = builder.start();
try (final BufferedWriter w = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()))) {
w.write(graphDef);
w.flush();
}
final BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
final StringBuilder plainFormat = new StringBuilder();
String line;
while ((line = input.readLine()) != null) {
plainFormat.append(line);
plainFormat.append(System.lineSeparator());
}
return plainFormat.toString();
} catch (final IOException e) {
log.error("Failed to run \"dot\" utility. Check that it is installed and on the PATH.", e);
throw new IllegalStateException("Failed to run \"dot\" utility", e);
}
}
private long nextUUID = 1;
private final JQMLSingletonModel<GraphKey> singletonModel;
private final JQMLListModel<String> vertexModel;
private final JQMLListModel<EdgeKey> edgeModel;
private final List<Vertex<K>> vertices = new ArrayList<>();
private final double dpi;
private GraphModel(final String modelPrefix, final JQMLModelFactory factory, final ImmutableSet<String> userKeys,
final double dpi) {
Objects.requireNonNull(modelPrefix, "modelPrefix is null");
Objects.requireNonNull(factory, "factory is null");
this.dpi = dpi;
singletonModel = factory.createSingletonModel(modelPrefix + "_graph", GraphKey.class, PutMode.RETURN_NULL);
singletonModel.put(GraphKey.width, new JVariant(dpi));
singletonModel.put(GraphKey.height, new JVariant(dpi));
final ImmutableSet<String> builtInKeys = EnumSet.allOf(VertexKey.class).stream().map(VertexKey::name)
.collect(ImmutableSet.toImmutableSet());
final Set<String> keys = new HashSet<>();
keys.addAll(builtInKeys);
keys.addAll(userKeys);
vertexModel = factory.createListModel(modelPrefix + "_vertices", keys, PutMode.RETURN_NULL);
edgeModel = factory.createListModel(modelPrefix + "_edges", EdgeKey.class, PutMode.RETURN_NULL);
}
private void applyGraphVizOutput(final GraphVizParser parser) {
singletonModel.put(GraphKey.width, new JVariant(parser.getGraphWidthInches() * dpi));
singletonModel.put(GraphKey.height, new JVariant(parser.getGraphHeightInches() * dpi));
for (final Vertex<K> b : vertices) {
b.apply(parser.getNode(b.getUUID()), dpi);
}
// Add edges
edgeModel.clear();
for (final Vertex<K> b : vertices) {
final List<EdgeDefinition> edges = parser.getEdges(b.getUUID());
for (final EdgeDefinition e : edges) {
final ImmutableList<Point2D> polyline = e.getPolyLine();
final ImmutableMap.Builder<EdgeKey, JVariant> builder = ImmutableMap.builder();
builder.put(EdgeKey.polyline, new JVariant(polyline));
builder.put(EdgeKey.head_id, new JVariant(e.getHeadUUID()));
builder.put(EdgeKey.tail_id, new JVariant(e.getTailUUID()));
edgeModel.add(builder.build());
}
}
}
/**
* Remove all vertices from the graph.
*/
public void clear() {
vertexModel.clear();
edgeModel.clear();
for (final Vertex<K> v : vertices) {
v.invalidate();
}
vertices.clear();
}
/**
* @param widthInches Width of the new Vertex in inches.
* @param heightInches Height of the new Vertex in inches.
* @return Newly created Vertex in this graph.
*/
public Vertex<K> createVertex(final double widthInches, final double heightInches) {
final ImmutableMap.Builder<String, JVariant> builder = ImmutableMap.builder();
final String uuid = getIDAsGraphVizIDString(++nextUUID);
builder.put(VertexKey.id.toString(), new JVariant(uuid));
builder.put(VertexKey.x.toString(), ZERO_VARIANT);
builder.put(VertexKey.y.toString(), ZERO_VARIANT);
builder.put(VertexKey.width.toString(), ONE_VARIANT);
builder.put(VertexKey.height.toString(), ONE_VARIANT);
final Map<String, JVariant> map = vertexModel.add(builder.build());
final Vertex<K> v = new Vertex<>(uuid, widthInches, heightInches, this, map);
vertices.add(v);
return v;
}
/**
* @param widthInches Width of the new Vertex in inches.
* @param heightInches Height of the new Vertex in inches.
* @param initialData Data to initially populate the Vertex with
* @return Newly created Vertex in this graph.
*/
public Vertex<K> createVertex(final double widthInches, final double heightInches,
final ImmutableMap<K, JVariant> initialData) {
Objects.requireNonNull(initialData, "initialData is null");
final ImmutableMap.Builder<String, JVariant> builder = ImmutableMap.builder();
final String uuid = getIDAsGraphVizIDString(++nextUUID);
builder.put(VertexKey.id.toString(), new JVariant(uuid));
builder.put(VertexKey.x.toString(), ZERO_VARIANT);
builder.put(VertexKey.y.toString(), ZERO_VARIANT);
builder.put(VertexKey.width.toString(), ONE_VARIANT);
builder.put(VertexKey.height.toString(), ONE_VARIANT);
for (final Entry<K, JVariant> entry : initialData.entrySet()) {
builder.put(entry.getKey().toString(), entry.getValue());
}
final Map<String, JVariant> map = vertexModel.add(builder.build());
final Vertex<K> v = new Vertex<>(uuid, widthInches, heightInches, this, map);
vertices.add(v);
return v;
}
private String getGraphVizDOTFormat() {
final StringBuilder builder = new StringBuilder(vertices.size() * 64);
final String newLine = System.lineSeparator();
builder.append("digraph {");
builder.append(newLine);
for (final Vertex<K> v : vertices) {
v.addGraphVizNodeDefinition(builder);
builder.append(newLine);
v.addGraphVizEdgeDefinition(builder);
builder.append(newLine);
}
builder.append("}");
return builder.toString();
}
/**
* Lays out the graph, sending the updated layout data to QML. Must be called
* after changing the structure of the graph in order for those changes to be
* applied. Call blocks until data is updated.
*/
public void layoutGraph() {
final String graphVizFormat = getGraphVizDOTFormat();
final GraphVizParser parser = new GraphVizParser(runGraphViz(graphVizFormat), dpi);
applyGraphVizOutput(parser);
}
/**
* Lays out the graph, sending the updated layout data to QML. Must be called
* after changing the structure of the graph in order for those changes to be
* applied. Call returns immediately and data is updated on the provided
* executor. Provide executor must be the QML Thread executor.
*
* @param qmlThreadExecutor The QML Thread executor. Used to update the models
* once the layout is complete.
* @return CompletableFuture that completes once the models are updated.
*/
public CompletableFuture<Void> layoutGraphAsync(final ExecutorService qmlThreadExecutor) {
Objects.requireNonNull(qmlThreadExecutor, "qmlTheadExecutor is null");
final String graphVizFormat = getGraphVizDOTFormat();
final CompletableFuture<GraphVizParser> future = CompletableFuture
.supplyAsync(() -> new GraphVizParser(runGraphViz(graphVizFormat), dpi), LAYOUT_EXEC);
return future.thenAcceptAsync(parser -> applyGraphVizOutput(parser), qmlThreadExecutor);
}
/**
* @param removed Vertex to remove.
* @return True if the vertex was removed;
*/
public boolean removeVertex(final Vertex<K> removed) {
Objects.requireNonNull(removed, "removed is null");
Preconditions.checkArgument(this == removed.getOwningGraph(),
"Attempted to remove Vertex not owned by this GraphModel");
// Remove the item from the JQmlListModel
for (int i = 0; i < vertexModel.size(); ++i) {
if (vertexModel.get(i) == removed.getOwningGraph()) {
vertexModel.remove(i);
break;
}
}
if (vertices.remove(removed)) {
removed.invalidate();
return true;
} else {
return false;
}
}
}
|
package com.codegym.emailvalidate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EmailvalidateApplication {
public static void main(String[] args) {
SpringApplication.run(EmailvalidateApplication.class, args);
}
}
|
package com.tencent.mm.plugin.webview.stub;
import com.tencent.mm.g.a.mu;
import com.tencent.mm.plugin.webview.ui.tools.WebViewStubCallbackWrapper;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.x;
class WebViewStubService$2 extends c<mu> {
final /* synthetic */ WebViewStubService pUR;
WebViewStubService$2(WebViewStubService webViewStubService) {
this.pUR = webViewStubService;
this.sFo = mu.class.getName().hashCode();
}
private boolean a(mu muVar) {
if ((muVar instanceof mu) && (WebViewStubService.i(this.pUR) == null || WebViewStubService.i(this.pUR).containsKey(muVar.bXK.filePath))) {
if (WebViewStubService.i(this.pUR) != null) {
WebViewStubService.i(this.pUR).remove(muVar.bXK.filePath);
}
x.d("MicroMsg.WebViewStubService", "result: " + muVar.bXK.result);
try {
for (WebViewStubCallbackWrapper webViewStubCallbackWrapper : WebViewStubService.h(this.pUR)) {
webViewStubCallbackWrapper.pXx.e(muVar.bXK.filePath, muVar.bXK.result, muVar.bXK.bJr, muVar.bXK.bJs);
}
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.WebViewStubService", e, "", new Object[0]);
}
}
return false;
}
}
|
package javatpoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by acedric on 14/02/2017.
*/
public class Operation {
int data = 50;
void change(Operation op){
op.data=op.data+100;
}
public static void main(String[] args) {
// Operation op = new Operation();
// System.out.println(op.data);
// op.change(op);
// System.out.println(op.data);
//
// ArrayList<String> al = new ArrayList();
// al.add("arnaud");
// al.add("arnaud1");
// al.add("arnaud2");
// al.add("arnaud3");
//
//
// Iterator<String> iterator = al.iterator();
// while (iterator.hasNext()){
// System.out.println(iterator.next());
// }
Employee employee1 = new Employee(1,"arnaud","catford");
Employee employee2 = new Employee(2,"daryl","Lewisham");
Employee employee3 = new Employee(3,"fabrice","clayton");
ArrayList<Employee> emp = new ArrayList();
emp.add(employee1);
emp.add(employee2);
emp.add(employee3);
Iterator itr = emp.iterator();
while (itr.hasNext()){
Employee epl = (Employee) itr.next();
System.out.println(epl.getEmployeeId() +" "+ epl.getEmployeeName() +" "+epl.getEmployeeAddress());
// System.out.println(itr.next());
}
Map<Integer,String> hm = new HashMap();
hm.put(1,"arnaud");
hm.put(2,"cedric");
hm.put(3,"daryl");
hm.put(1,"arnaud");
for (Map.Entry m:hm.entrySet()) {
System.out.println(m.getKey()+" : "+ m.getValue());
}
}
}
class Employee{
private int employeeId;
private String employeeName;
private String employeeAddress;
public Employee(int employeeId, String employeeName, String employeeAddress) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.employeeAddress = employeeAddress;
}
public int getEmployeeId() {
return employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public String getEmployeeAddress() {
return employeeAddress;
}
}
|
package com.zhouyi.business.controller;
import com.zhouyi.business.core.model.LedenCollectIris;
import com.zhouyi.business.core.model.Response;
import com.zhouyi.business.core.service.BaseService;
import com.zhouyi.business.core.service.LedenCollectIrisService;
import com.zhouyi.business.core.vo.LedenCollectIrisVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 杜承旭
* @ClassNmae: LedenCollectIrisController
* @Description: TODO
* @date 2019/9/3 9:39
* @Version 1.0
**/
@RestController
@RequestMapping(value = "/api/iris")
public class LedenCollectIrisController {
@Autowired
private BaseService<LedenCollectIris, LedenCollectIrisVo> baseService;
@Autowired
private LedenCollectIrisService ledenCollectIrisService;
/**
*根据人员编号查询虹膜信息
*/
@RequestMapping(value = "/get/{id}")
public Response selectIrisByPersonCode(@PathVariable String id){
return ledenCollectIrisService.selectIrisByPersonCode(id);
}
}
|
package com.oobootcamp;
public class Car {
private String number;
public Car(int number) {
this.number = String.valueOf(number);
}
public Car(String number) {
this.number = number;
}
public String getNumber() {
return number;
}
}
|
package ru.brainworkout.braingym.strup_test;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import ru.brainworkout.braingym.MainActivity;
import ru.brainworkout.braingym.R;
public class StrupActivityOptions_ver1 extends AppCompatActivity {
private SharedPreferences mSettings;
private String mStrupLang;
private int mStrupMaxTime;
private int mStrupExampleTime;
private String mStrupExampleType;
private int mStrupVer1FontSizeChange;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_strup_options_ver1);
getPreferencesFromFile();
setPreferencesOnScreen();
}
public void buttonStrupOptionsVer1Save_onClick(View view) {
//MainActivity.APP_PREFERENCES;
// int resID = getResources().getIdentifier(ButtonID, "id", getPackageName());
//Button but = (Button) findViewById(resID);
SharedPreferences.Editor editor = mSettings.edit();
editor.putString(MainActivity.APP_PREFERENCES_STRUP_LANGUAGE, mStrupLang);
editor.putInt(MainActivity.APP_PREFERENCES_STRUP_VER1_TEST_TIME, mStrupMaxTime);
editor.putInt(MainActivity.APP_PREFERENCES_STRUP_VER1_EXAMPLE_TIME, mStrupExampleTime);
editor.putString(MainActivity.APP_PREFERENCES_STRUP_VER1_EXAMPLE_TYPE, mStrupExampleType);
int sizeID = getResources().getIdentifier("evStrupVer1OptionsFontSizeChange", "id", getPackageName());
EditText txtSize = (EditText) findViewById(sizeID);
if (txtSize != null) {
mStrupVer1FontSizeChange= Integer.parseInt((txtSize.getText().toString().equals("")?"0":txtSize.getText().toString()));
}
editor.putInt(MainActivity.APP_PREFERENCES_STRUP_VER1_FONT_SIZE_CHANGE, mStrupVer1FontSizeChange);
editor.apply();
this.finish();
}
public void buttonHome_onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void buttonStrupOptionsVer1Cancel_onClick(View view) {
this.finish();
}
private void getPreferencesFromFile() {
mSettings = getSharedPreferences(MainActivity.APP_PREFERENCES, Context.MODE_PRIVATE);
if (mSettings.contains(MainActivity.APP_PREFERENCES_STRUP_VER1_FONT_SIZE_CHANGE)) {
// Получаем язык из настроек
mStrupVer1FontSizeChange = mSettings.getInt(MainActivity.APP_PREFERENCES_STRUP_VER1_FONT_SIZE_CHANGE, 0);
} else {
mStrupVer1FontSizeChange = 0;
}
if (mSettings.contains(MainActivity.APP_PREFERENCES_STRUP_VER1_TEST_TIME)) {
mStrupMaxTime = mSettings.getInt(MainActivity.APP_PREFERENCES_STRUP_VER1_TEST_TIME, 60);
} else {
mStrupMaxTime = 60;
}
if (mSettings.contains(MainActivity.APP_PREFERENCES_STRUP_VER1_EXAMPLE_TIME)) {
mStrupExampleTime = mSettings.getInt(MainActivity.APP_PREFERENCES_STRUP_VER1_EXAMPLE_TIME, 0);
} else {
mStrupExampleTime = 0;
}
if (mSettings.contains(MainActivity.APP_PREFERENCES_STRUP_VER1_EXAMPLE_TYPE)) {
mStrupExampleType = mSettings.getString(MainActivity.APP_PREFERENCES_STRUP_VER1_EXAMPLE_TYPE, "RANDOM");
} else {
mStrupExampleType = "RANDOM";
}
if (mSettings.contains(MainActivity.APP_PREFERENCES_STRUP_LANGUAGE)) {
// Получаем язык из настроек
mStrupLang = mSettings.getString(MainActivity.APP_PREFERENCES_STRUP_LANGUAGE, "Ru");
} else {
mStrupLang = "Ru";
}
}
private void setPreferencesOnScreen() {
int sizeID = getResources().getIdentifier("evStrupVer1OptionsFontSizeChange", "id", getPackageName());
EditText txtSize = (EditText) findViewById(sizeID);
if (txtSize != null) {
txtSize.setText(String.valueOf(mStrupVer1FontSizeChange));
}
int sizeLabelID = getResources().getIdentifier("tvStrupVer1FontSizeLabel", "id", getPackageName());
TextView tvSizeLabel = (TextView) findViewById(sizeLabelID);
int mStrupVer1TextSize = getIntent().getIntExtra("mStrupVer1TextSize", 0);
if (tvSizeLabel != null) {
tvSizeLabel.setText("Изменение шрифта ("+String.valueOf(mStrupVer1TextSize)+"+/-sp):");
}
int maxtimeID = getResources().getIdentifier("rbStrupVer1MaxTime" + mStrupMaxTime, "id", getPackageName());
RadioButton butTime = (RadioButton) findViewById(maxtimeID);
if (butTime != null) {
butTime.setChecked(true);
}
RadioGroup radiogroupMaxTime = (RadioGroup) findViewById(R.id.rgStrupVer1MaxTime);
if (radiogroupMaxTime != null) {
radiogroupMaxTime.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case -1:
break;
case R.id.rbStrupVer1MaxTime60:
mStrupMaxTime = 60;
break;
case R.id.rbStrupVer1MaxTime120:
mStrupMaxTime = 120;
break;
default:
break;
}
}
});
}
int extimeID = getResources().getIdentifier("rbStrupVer1ExTime" + mStrupExampleTime, "id", getPackageName());
RadioButton exTime = (RadioButton) findViewById(extimeID);
if (exTime != null) {
exTime.setChecked(true);
}
RadioGroup radiogroupExTime = (RadioGroup) findViewById(R.id.rgStrupVer1ExTime);
if (radiogroupExTime != null) {
radiogroupExTime.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case -1:
break;
case R.id.rbStrupVer1ExTime0:
mStrupExampleTime = 0;
break;
case R.id.rbStrupVer1ExTime5:
mStrupExampleTime = 5;
break;
case R.id.rbStrupVer1ExTime10:
mStrupExampleTime = 10;
break;
default:
break;
}
}
});
}
int extypeID = getResources().getIdentifier("rbStrupVer1ExType" + mStrupExampleType, "id", getPackageName());
RadioButton exType = (RadioButton) findViewById(extypeID);
if (exType != null) {
exType.setChecked(true);
}
RadioGroup radiogroupExType = (RadioGroup) findViewById(R.id.rgStrupVer1ExType);
if (radiogroupExType != null) {
radiogroupExType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case -1:
break;
case R.id.rbStrupVer1ExTypeRANDOM:
mStrupExampleType = "RANDOM";
break;
case R.id.rbStrupVer1ExTypeCOLOR:
mStrupExampleType = "COLOR";
break;
case R.id.rbStrupVer1ExTypeWORD:
mStrupExampleType = "WORD";
break;
default:
break;
}
}
});
}
//Установим настройки в зависимости от сохраненного языка
int langID = getResources().getIdentifier("rbStrupVer1Lang" + mStrupLang, "id", getPackageName());
RadioButton butLang = (RadioButton) findViewById(langID);
if (butLang != null) {
butLang.setChecked(true);
}
//
RadioGroup radiogroupLang = (RadioGroup) findViewById(R.id.rgStrupVer1Lang);
if (radiogroupLang != null) {
radiogroupLang.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case -1:
break;
case R.id.rbStrupVer1LangRu:
mStrupLang = "Ru";
break;
case R.id.rbStrupVer1LangEn:
mStrupLang = "En";
break;
default:
break;
}
}
});
}
}
}
|
package ru.carlson.roof;
public enum roofBlock {
air("ВОЗДУХ"),
edge("КРАЙ"),
pipe("ТРУБА"),
roof("КРЫША");
private final String nameOfBlock;
private roofBlock(String name){
nameOfBlock = name;
}
public String getNameOfBlock(){
return nameOfBlock;
}
}
|
public class PoeDameron extends Character implements Pilot{
public PoeDameron(){
super("Poe Dameron","Light Side","Resistance",true);
}
public boolean pilot(){
return true;
}
}
|
/**
* This is a constant class which stores the constant value required to display
* English equivalent output of given Currency value written on a check.
*
* @author jayawant.chavan
*
*/
public interface CheckWriterConstant {
String NUMBER_LIMIT = "000000000000000";
String TRILLION = " trillion ";
String BILLION = " billion ";
String MILLION = " million ";
String THOUSAND = " thousand ";
String HUNDRED = " hundred";
String DOLLARS = " dollars only";
String DOLLARS_AND = " dollars and ";
String CENT = "/100";
String SLASH_DELIMETER = "/";
String SPACE_ADJUST = "\\s{2,}";
char DOT = '.';
char FORWARD_SLASH = '/';
String ZERO = "zero";
// Static array which hold the tens value in the form of word
String[] TENSVALUENAMES = { "", " ten", " twenty", " thirty", " forty", " fifty", " sixty", " seventy", " eighty",
" ninety" };
// Static array which hold the number value in the form of word
String[] NUMBERVALUENAMES = { "", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine",
" ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen",
" nineteen" };
}
|
package com.esc.fms.controller.file;
import com.esc.fms.common.constant.Constants;
import com.esc.fms.entity.FileListElement;
import com.esc.fms.service.base.FtpService;
import com.esc.fms.service.file.FileManageService;
import com.esc.fms.service.file.FileService;
import org.apache.commons.io.IOExceptionWithCause;
import org.apache.commons.io.output.StringBuilderWriter;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileEntryParserImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Created by tangjie on 2017/4/23.
*/
@Controller
@RequestMapping("/filemanage")
public class FileManageController {
private static final Logger logger = LoggerFactory.getLogger(FileManageController.class);
@Autowired
private FileService fileService;
@Autowired
private FtpService ftpService;
@Autowired
private FileManageService fileManageService;
@RequestMapping("/view.do")
public ModelAndView goToFileUploadPage() {
return new ModelAndView("file/fileManage");
}
@RequestMapping("/getFileList.do")
@ResponseBody
public ModelMap getFileList(@RequestParam(value = "fileName", required = false) String fileName,
@RequestParam(value = "fileType", required = false) Integer fileType,
@RequestParam(value = "folderName", required = false) String folderName,
@RequestParam(value = "creator", required = false) String creator,
@RequestParam(value = "updator", required = false) String updator,
@RequestParam(value = "page") int pageIndex,
@RequestParam(value = "rows") int pageSize) {
int offset = (pageIndex - 1) * pageSize;
ModelMap result = new ModelMap();
result.put("total", fileService.getCountByConditions(fileName, fileType, folderName, creator, updator));
result.put("rows", fileService.getFileListByConditions(fileName, fileType, folderName, creator, updator, offset, pageSize));
return result;
}
@RequestMapping("/getFileProperties")
@ResponseBody
public ModelMap getFileProperties(@RequestParam("FileID") Integer fileID) {
ModelMap result = fileService.getFileProperties(fileID);
return result;
}
@RequestMapping("/resetProperty")
@ResponseBody
public ModelMap resetProperty(@RequestParam("fileID") Integer fileID,
@RequestParam("shareType") String shareType,
@RequestParam("oldOpRights") List<String> oldOpRights,
@RequestParam("newOpRights") List<String> newOpRights,
@RequestParam(value = "oldSharedStaffs", required = false) List<String> oldSharedStaffs,
@RequestParam(value = "newSharedStaffs", required = false) List<String> newSharedStaffs) {
ModelMap result = new ModelMap();
String success = "fail";
String msg = "";
try {
fileService.resetProperty(fileID, shareType, oldOpRights, newOpRights, oldSharedStaffs, newSharedStaffs);
success = "success";
msg = "重设文件属性成功!";
} catch (Exception e) {
logger.warn("重设文件属性失败, 文件编号:[{}]", fileID);
msg = "重设文件属性失败!";
}
result.addAttribute("success", success);
result.put("msg", msg);
return result;
}
@RequestMapping("/fileDelete.do")
@ResponseBody
public ModelMap fileReplace(@RequestParam("FileIDs") List<Integer> fileIDs,HttpServletRequest request){
ModelMap result = new ModelMap();
String msg = "";
String userName = request.getSession().getAttribute("userName").toString();
Boolean executeResult = false;
try{
executeResult = fileManageService.fileDelete(fileIDs,userName);
}catch (IOException e){
executeResult = false;
e.printStackTrace();
}
result.put("success",executeResult);
if(executeResult == true){
result.put("msg","文件删除成功!");
}else{
result.put("msg","文件删除失败!");
}
return result;
}
@RequestMapping(value = "/fileReplace.do",method = RequestMethod.POST)
@ResponseBody
public ModelMap fileReplace(@RequestParam("replaceFileID") Integer fileID,@RequestParam MultipartFile sourceFiles, HttpServletRequest request){
ModelMap result = new ModelMap();
logger.debug("fileId:[{}],sourceFilesName:[{}]",fileID,sourceFiles.getOriginalFilename());
if(null != sourceFiles){
String userName = request.getSession().getAttribute("userName").toString();
Boolean executeResult = false;
try{
executeResult = fileManageService.fileReplace(fileID,sourceFiles,userName);
}catch (IOException e){
executeResult = false;
e.printStackTrace();
}
result.put("success",executeResult);
if(executeResult == true){
result.put("msg","文件替换成功!");
}else{
result.put("msg","文件替换失败!");
}
}else{
result.put("success",false);
result.put("msg","上传文件为空!");
}
return result;
}
@RequestMapping("/fileDownload")
public void fileDownload(@RequestParam("fileUrls") List<String> fileUrls, HttpServletResponse response){
FTPClient ftpClient = null;
ZipOutputStream zipOut = null;
byte[] buf = new byte[4096];
try{
response.setCharacterEncoding("utf-8");
response.setContentType("application/x-zip-compressed");
response.setHeader("Content-Disposition", "inline;fileName=" + new String("下载文件".getBytes("gb2312"),"ISO8859-1") + ".zip");
ftpClient = ftpService.getFtpClient();
zipOut = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream(),4096));
for(String fileUrl : fileUrls){
logger.debug("file Download ... fileUrl:[{}]",fileUrl);
String[] paths = fileUrl.split("/");
for(int i=0;i<paths.length-1;i++){
String path = new String(paths[i].getBytes(ftpClient.getControlEncoding()), Constants.SERVER_CHARSET);
if(!ftpClient.changeWorkingDirectory(path)){
throw new IOException("为文件路径[" + fileUrl + "]切换目录[" + path + "]时,失败!");
}
}
String fileName = paths[paths.length-1];
logger.debug("文件名:[{}]",fileName);
ZipEntry entry = new ZipEntry(fileName);
zipOut.putNextEntry(entry);
logger.debug("Current working directory : [{}]",ftpClient.printWorkingDirectory() );
logger.debug("ftp is connected :[{}]",ftpClient.isConnected());
InputStream bis = ftpClient.retrieveFileStream(fileName);
if(null != bis){
int readLen = -1;
while((readLen = bis.read(buf,0,4096)) != -1){
zipOut.write(buf,0,readLen);
}
bis.close();
if(!ftpClient.completePendingCommand()){
throw new IOException("执行completePendingCommand命令失败!");
}
}else{
throw new IOException("获取文件" + fileName + "的输入流失败,replyCode :[" + ftpClient.getReplyCode() + "]");
}
for(int i =0; i < paths.length -1;i++){
if(!ftpClient.changeToParentDirectory()){
throw new IOException("切换到父目录失败!");
}
}
}
}catch (IOException e){
logger.error(e.getMessage());
e.printStackTrace();
}finally {
if(null != zipOut){
try{
zipOut.close();
}catch (IOException e){
logger.error(e.getMessage());
e.printStackTrace();
}
}
try{
ftpService.closeFtpConnection(ftpClient);
}catch (IOException e){
logger.error(e.getMessage());
e.printStackTrace();
}
}
}
@RequestMapping("/fileOpen")
public void fileOpen(@RequestParam("fileUrl") String fileUrl, HttpServletResponse response){
FTPClient ftpClient = null;
BufferedOutputStream out = null;
try{
ftpClient = ftpService.getFtpClient();
logger.debug("fileUrl : [{}]",fileUrl);
String[] paths = fileUrl.split("/");
for(int i=0;i<paths.length-1;i++){
String path = new String(paths[i].getBytes(ftpClient.getControlEncoding()), Constants.SERVER_CHARSET);
if(!ftpClient.changeWorkingDirectory(path)){
StringBuilder msg = new StringBuilder();
msg.append("切换目录[").append(path).append("]失败!");
throw new IOException(msg.toString());
}
}
String fileName = paths[paths.length-1];
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "inline;fileName=" + fileName);
out = new BufferedOutputStream(response.getOutputStream(),4096);
if(!ftpClient.retrieveFile(fileName,out))
{
throw new IOException("下载文件" + fileName + "失败!");
}
}catch (IOException e){
logger.error(e.getMessage());
e.printStackTrace();
}finally {
try{
ftpService.closeFtpConnection(ftpClient);
}catch (IOException e){
logger.error(e.getMessage());
e.printStackTrace();
}
if(null != out){
try{
out.close();
}catch (IOException e){
logger.error(e.getMessage());
e.printStackTrace();
}
}
}
}
}
|
package br.ufla.lemaf.ti.lemaf4j.common.errors;
import br.ufla.lemaf.ti.lemaf4j.common.messaging.ErrorType;
/**
* Representa os erros de Email.
*
* @author Highlander Paiva
* @since 1.0
*/
public enum EmailError implements ErrorType {
EMAIL_INVALIDO, MULTIPLOS_EMAILS
}
|
package com.ntconsult.devtest.entities;
/**
* Sale entity.
*
* @author Marcos Freitas Nunes <marcosn@gmail.com>
*/
public class Sale {
private long id;
private float amount;
private String seller;
/**
* Default constructor.
*/
public Sale() {
amount = 0F;
}
/**
* The array must to have 4 attributes and be in this format: {ignorable, SaleId,[ItemId-ItemQuantity-ItemPrice,
* ItemId...], SellerName}.
*
* Example: {"003","10","[1-10-100,2-30-2.50,3-40-3.10]","Diego"}
*
* @param array
* @return
*/
public static Sale fromArray(String[] array) {
Sale sale = new Sale();
sale.setId(Long.parseLong(array[1]));
sale.setSeller(array[3]);
//Removes the first and last character that should be "[" and "]"
String itemsStr = array[2].substring(1, array[2].length() - 1);
String[] items = itemsStr.split(",");
for (String itemStr : items) {
//split the items and then get a array with attibutes (Item ID-Item Quantity-Item Price).
String[] itemAttr = itemStr.split("-");
//get the item's price and add to amount.
sale.addAmount(Float.parseFloat(itemAttr[2]));
}
return sale;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSeller() {
return seller;
}
public void setSeller(String seller) {
this.seller = seller;
}
/**
* Adds the price to the sale
*
* @param price
*/
public void addAmount(Float price) {
this.amount += price;
}
/**
* Return the sum of price all itens.
*
* @return
*/
public float getAmount() {
return this.amount;
}
}
|
package com.woowtodo.repositories.roleRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.woowtodo.entities.WoowRole;
public interface RoleRepository extends JpaRepository<WoowRole, Integer>,CustomRoleRepository{
}
|
package pixel.bus.service;
import pixel.bus.gui.GameFrame;
import pixel.bus.model.GameData;
import pixel.bus.model.enu.GameSpeedEnum;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by vanley on 15/06/2017.
*/
public class GameEngineService implements ActionListener {
private Timer timer;
public static int tick = 0;
private GameData gameData;
public GameEngineService(GameData gameData) {
this.gameData = gameData;
tick = gameData.getTick();
timer = new Timer(gameData.getGameSpeed().getSpeed(), this);
}
public void speed(GameSpeedEnum speedEnum){
if (!timer.isRunning()) {
unPause();
}
if(GameSpeedEnum.PAUSE.equals(speedEnum)){
pause();
} else {
gameData.setGameSpeed(speedEnum);
timer.setDelay(speedEnum.getSpeed());
}
}
public void unPause(){
timer.start();
}
public void pause(){
timer.stop();
}
@Override
public void actionPerformed(ActionEvent e) {
tick++;
GameLoaderFactory.getInstance().getInstance(StationService.class).queuePassengers();
GameLoaderFactory.getInstance().getInstance(GameFrame.class).updateInfo();
}
}
|
package org.fao.unredd.api.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.fao.unredd.api.json.LayerUpdateRepresentation;
import org.fao.unredd.api.model.LayerUpdates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Path("/layerupdates/{updateId}")
public class LayerUpdateResource extends AbstractLayerBasedResource {
@Autowired
private LayerUpdates layerUpdates;
@GET
@Produces(MediaType.APPLICATION_JSON)
public LayerUpdateRepresentation asJSON(
@PathParam("updateId") String updateId) {
try {
return layerUpdates.getLayerUpdate(updateId).getJSON();
} catch (IllegalArgumentException e) {
throw new NotFoundException("No update with the ID: " + updateId);
}
}
}
|
package nl.jtosti.hermes.user;
import nl.jtosti.hermes.company.exception.CompanyNotFoundException;
import nl.jtosti.hermes.user.exception.UserNotFoundException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.when;
@ExtendWith(SpringExtension.class)
@DisplayName("User Service")
@Tag("services")
class UserServiceTest {
@Autowired
private UserServiceInterface userService;
@MockBean
private UserRepository userRepository;
@Test
@DisplayName("Get user with valid email")
void shouldReturnUser_whenGetUserWithEmail() {
User user = new User("Alex", "Jones", "alex.jones@alex.com", "");
when(userRepository.findByEmail(user.getEmail())).thenReturn(Optional.of(user));
User found = userService.getUserByEmail(user.getEmail());
assertThat(found).isEqualTo(user);
}
@Test
@DisplayName("Get all users")
void shouldReturnUsers_whenGetAllUsers() {
User user = new User("Alex", "Jones", "alex.jones@alex.com", "");
User user1 = new User("Jay", "Jones", "jay.jones@jay.com", "");
given(userRepository.findAllByOrderByIdAsc()).willReturn(Arrays.asList(user, user1));
List<User> found = userService.getAllUsers();
assertThat(found).hasSize(2);
assertThat(found.get(0)).isEqualTo(user);
assertThat(found.get(1)).isEqualTo(user1);
}
@Test
@DisplayName("Add user")
void shouldReturnNewUser_whenAddingUser() {
User user = new User("Alex", "Jones", "alex.jones@alex.com", "");
when(userRepository.save(any(User.class))).thenReturn(user);
User newUser = userService.save(user);
assertThat(newUser.getEmail()).isEqualTo(user.getEmail());
}
@Test
@DisplayName("User exists")
void shouldReturnTrue_whenEmailExists() {
User user = new User("Alex", "Jones", "alex.jones@alex.com", "");
when(userRepository.findByEmail(user.getEmail())).thenReturn(Optional.of(user));
assertThat(userService.exists(user.getEmail())).isTrue();
}
@Test
@DisplayName("User doesn't exist")
void shouldReturnFalse_whenEmailDoesNotExist() {
assertThat(userService.exists("alex.jones@alex.com")).isFalse();
}
@Test
@DisplayName("Get single user")
void shouldReturnUser_whenGetSingleUser() {
User user = new User("Alex", "Jones", "alex.jones@alex.com", "");
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
assertThat(userService.getUserById(1L).getEmail()).isEqualTo(user.getEmail());
}
@Test
@DisplayName("Get invalid user throws exception")
void shouldThrowException_whenGetUserWithInvalidId() {
try {
userService.getUserById(2L);
// Making sure the test actually fails if it returned something
assertThat(true).isFalse();
} catch (UserNotFoundException ex) {
assertThat(ex.getMessage()).isEqualTo("Could not find user 2");
}
}
@Test
@DisplayName("Update invalid user throws exception")
void shouldThrowException_whenUpdateUserWithInvalidId() {
User user = new User("Alex", "Jones", "alex.jones@alex.com", "");
user.setId(2L);
try {
userService.updateUser(user);
// Making sure the test actually fails if it returned something
assertThat(true).isFalse();
} catch (UserNotFoundException ex) {
assertThat(ex.getMessage()).isEqualTo("Could not find user 2");
}
}
@Test
@DisplayName("Update user")
void shouldReturnUpdatedUser_whenUpdateUser() {
User user = new User("Alex", "Jones", "alex.jones@alex.com", "");
User user1 = new User("Jay", "Jones", "jay.jones@jay.com", "");
user.setId(1L);
user1.setId(1L);
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
when(userRepository.save(user1)).thenReturn(user1);
assertThat(userService.updateUser(user1)).isEqualTo(user1);
}
@Test
@DisplayName("Get unknown email")
void shouldThrowUserNotFoundException_whenGetUnknownEmail() {
try {
userService.getUserByEmail("Jane.jones@alex.com");
assertThat(true).isFalse();
} catch (UserNotFoundException ex) {
assertThat(ex.getMessage()).isEqualTo("Could not find user linked to Jane.jones@alex.com");
}
}
@Test
@DisplayName("Delete user")
void shouldDoNothing_whenDeleteUser() {
userService.deleteUser(1L);
assertThat(true).isTrue();
}
@Test
@DisplayName("Get list of users by company")
void shouldReturnListOfUsers_whenGetListOfCompanyUsers() {
User user = new User("Alex", "Jones", "alex.jones@alex.com", "");
User user1 = new User("Jay", "Jones", "jay.jones@jay.com", "");
given(userRepository.findUsersByCompanyId(1L)).willReturn(Arrays.asList(user, user1));
List<User> found = userService.getAllUsersByCompanyId(1L);
assertThat(found).hasSize(2);
assertThat(found.get(0)).isEqualTo(user);
assertThat(found.get(1)).isEqualTo(user1);
}
@Test
@DisplayName("Get list of users by unknown company ID")
void shouldThrowCompanyNotFoundException_whenGetListOfCompanyUsersFromUnknownId() {
given(userRepository.findUsersByCompanyId(1L)).willReturn(new ArrayList<>());
try {
userService.getAllUsersByCompanyId(1L);
} catch (CompanyNotFoundException e) {
assertThat(e.getMessage()).isEqualTo("Could not find company 1");
}
}
@TestConfiguration
static class UserServiceTestContextConfiguration {
@Autowired
private UserRepository userRepository;
@Bean
public UserServiceInterface userServiceInterface() {
return new UserService(userRepository);
}
}
}
|
package com.example.iutassistant.Model;
public interface IModel {
}
|
package temp;
import com.google.gson.Gson;
import tools.FileIO;
import tools.Request;
import tools.Respond;
import tools.Unit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by troy on 11.11.2016.
*
*/
public class GetUnitsFromDB {
public static void main(String[] args) throws InterruptedException {
long sleepTime = 10 * 60000;
while (true) {
try (//BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Socket socket = new Socket("localhost", 7779);
BufferedReader readerSocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream())) {
// String line = reader.readLine();
// String line = "post /units/temp1/?timeOut=1000&setting=300";
// String line = "get /units/temp1/?globalTimeOut=100&setting=200";
// String line = "get /units/";
// String line = "get /units/temp1/";
// String line1 = "get /units/temp1/?until=2016-11-11 00:00:00&since=2016-11-20 23:59:59";
Request request = new Request();
request.setMethod("get");
request.setPath("units/temp1");
String line = new Gson().toJson(request);
request.setParameters("since", "2016-12-01 00:00:00");
request.setParameters("until", "2016-12-20 23:59:59");
String line1 = new Gson().toJson(request);
FileIO fileIO = new FileIO("C:\\Users\\troy\\Desktop\\data.txt");
if (!fileIO.exists()){
writer.println(line1);
writer.flush();
String answer = readerSocket.readLine();
System.out.println(answer);
Respond respond = new Gson().fromJson(answer, Respond.class);
Unit[] units = new Gson().fromJson(respond.getData(), Unit[].class);
String[] data = new String[units.length];
for (int i = 0; i < units.length; i++) {
data[i] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(units[i].getDate()) + "=" + units[i].getValue();
data[i] = data[i].replace(".", ",");
}
//
fileIO.writeToFile(data, false);
} else {
writer.println(line);
writer.flush();
String answer = readerSocket.readLine();
if (!answer.contains("\"status\":\"ZERO_RESULTS\"")){
Respond respond = new Gson().fromJson(answer, Respond.class);
Unit unit = new Gson().fromJson(respond.getData(), Unit.class);
String[] data = new String[1];
data[0] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(unit.getDate()) + "=" + unit.getValue();
data[0] = data[0].replace(".", ",");
fileIO.writeToFile(data, true);
}
}
System.out.println("Last transaction: " + new Date().toString());
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(sleepTime);
}
}
}
|
package com.santhosh;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class statusPageApplication {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(statusPageApplication.class, args);
}
}
|
package com.anexa.livechat.service.api.odoo;
import com.anexa.livechat.dto.waboxapp.WaBoxAppRequestDto;
public interface OdooLiveChatService {
void sendMessageToOdoo(int channel, String db, String user, String pwd, WaBoxAppRequestDto request);
}
|
package com.tencent.mm.plugin.game.gamewebview.jsapi.biz;
import android.content.Intent;
import com.samsung.android.sdk.look.smartclip.SlookSmartClipMetaTag;
import com.tencent.mm.g.a.pz;
import com.tencent.mm.model.s;
import com.tencent.mm.plugin.game.gamewebview.jsapi.a;
import com.tencent.mm.plugin.game.gamewebview.model.h;
import com.tencent.mm.plugin.game.gamewebview.ui.GameWebViewUI;
import com.tencent.mm.plugin.game.gamewebview.ui.d;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import org.json.JSONObject;
public final class ay extends a {
public static final int CTRL_BYTE = 4;
public static final String NAME = "shareTimeline";
public final void a(d dVar, JSONObject jSONObject, int i) {
x.i("MicroMsg.GameJsApiSendAppMessage", "invoke");
GameWebViewUI pageActivity = dVar.getPageActivity();
if (jSONObject == null) {
x.e("MicroMsg.GameJsApiSendAppMessage", "sendAppMessage fail, appmsg is null");
dVar.E(i, a.f("share_timeline:fail_null_params", null));
return;
}
String optString = jSONObject.optString("link");
if (bi.oW(optString)) {
x.e("MicroMsg.GameJsApiSendAppMessage", "link is null");
dVar.E(i, a.f("share_timeline:fail_invalid_params", null));
return;
}
int i2;
h.a(dVar, jSONObject);
String optString2 = jSONObject.optString("desc");
if (optString2 != null) {
if (optString2.startsWith("http://")) {
optString2.substring(7);
} else if (optString2.startsWith("https://")) {
optString2.substring(8);
}
}
int i3 = 1;
String str = "";
int i4 = 0;
if (this.jGp != null) {
this.jGp.setClassLoader(getClass().getClassLoader());
i3 = this.jGp.getInt("snsWebSource", 1);
str = this.jGp.getString("jsapi_args_appid");
i4 = bi.getInt(this.jGp.getString("urlAttribute"), 0);
this.jGp.remove("urlAttribute");
}
int i5 = i3;
if (bi.oW(str)) {
str = jSONObject.optString("appid");
}
String optString3 = jSONObject.optString("img_width");
String optString4 = jSONObject.optString("img_height");
x.i("MicroMsg.GameJsApiSendAppMessage", "doTimeline, rawUrl:[%s], shareUrl:[%s]", new Object[]{optString, dVar.Dp(optString)});
String optString5 = jSONObject.optString("type");
String optString6 = jSONObject.optString(SlookSmartClipMetaTag.TAG_TYPE_TITLE);
String optString7 = jSONObject.optString("img_url");
String optString8 = jSONObject.optString("src_username");
String optString9 = jSONObject.optString("src_displayname");
i3 = -1;
try {
i3 = Integer.valueOf(optString3).intValue();
Integer.valueOf(optString4);
i2 = i3;
} catch (Exception e) {
i2 = i3;
}
Intent intent = new Intent();
intent.putExtra("Ksnsupload_width", i2);
intent.putExtra("Ksnsupload_height", i2);
intent.putExtra("Ksnsupload_link", r11);
intent.putExtra("Ksnsupload_title", optString6);
intent.putExtra("Ksnsupload_imgurl", optString7);
intent.putExtra("Ksnsupload_contentattribute", i4);
if (s.hf(optString8)) {
intent.putExtra("src_username", optString8);
intent.putExtra("src_displayname", optString9);
}
intent.putExtra("Ksnsupload_source", i5);
intent.putExtra("Ksnsupload_type", 1);
if (!bi.oW(optString5) && optString5.equals("music")) {
intent.putExtra("ksnsis_music", true);
}
if (!bi.oW(optString5) && optString5.equals("video")) {
intent.putExtra("ksnsis_video", true);
}
if (str != null && str.length() > 0) {
intent.putExtra("Ksnsupload_appid", str);
}
str = "MicroMsg.GameJsApiSendAppMessage";
String str2 = "doTimeline, init intent, jsapiArgs == null ? %b";
Object[] objArr = new Object[1];
objArr[0] = Boolean.valueOf(this.jGp == null);
x.i(str, str2, objArr);
if (this.jGp != null) {
optString2 = this.jGp.getString("K_sns_thumb_url");
str = this.jGp.getString("K_sns_raw_url");
str2 = bi.aG(this.jGp.getString("KSnsStrId"), "");
optString3 = bi.aG(this.jGp.getString("KSnsLocalId"), "");
intent.putExtra("key_snsad_statextstr", this.jGp.getString("key_snsad_statextstr"));
x.i("MicroMsg.GameJsApiSendAppMessage", "currentUrl %s contentUrl %s thumbUrl %s", new Object[]{optString, str, optString2});
if (!(str == null || optString == null || !str.equals(optString))) {
intent.putExtra("KlinkThumb_url", optString2);
}
intent.putExtra("KSnsStrId", str2);
intent.putExtra("KSnsLocalId", optString3);
if (str2 != null && this.jGp.getBoolean("KFromTimeline", false)) {
pz pzVar = new pz();
pzVar.caF.bSZ = str2;
pzVar.caF.bKW = optString3;
com.tencent.mm.sdk.b.a.sFg.m(pzVar);
}
}
intent.putExtra("ShareUrlOriginal", dVar.getRawUrl());
intent.putExtra("ShareUrlOpen", dVar.getCurrentURL());
intent.putExtra("JsAppId", dVar.getCacheAppId());
intent.putExtra("need_result", true);
x.i("MicroMsg.GameJsApiSendAppMessage", "doTimeline, start activity");
pageActivity.geJ = new 1(this, dVar, i);
com.tencent.mm.bg.d.a(pageActivity, "sns", ".ui.SnsUploadUI", intent, 2, false);
}
}
|
package com.xm.base.clazz;
/**
* Created by xm on 2017/3/22.
*/
public class ProImplement implements ProInterface {
@Override
public void doSomething() {
System.out.println("doSomething");
}
@Override
public void somethingElse(String arg) {
System.out.println("somethingElse :"+arg);
}
}
|
/*
* Copyright 2014 - 2016 Blazebit.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blazebit.persistence.pagination.web.model;
import javax.faces.context.FacesContext;
import java.util.*;
import com.blazebit.persistence.KeysetPage;
import com.blazebit.persistence.PagedList;
import com.blazebit.persistence.PaginatedCriteriaBuilder;
import com.blazebit.persistence.pagination.web.view.IdHolderView;
import com.blazebit.persistence.view.EntityViewSetting;
import com.blazebit.persistence.view.Sorter;
import com.blazebit.persistence.view.Sorters;
import com.blazebit.reflection.ReflectionUtils;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortMeta;
import org.primefaces.model.SortOrder;
/**
* @author Moritz Becker (moritz.becker@gmx.at)
* @since 1.2
*/
public abstract class AbstractLazyDataModel<T extends IdHolderView<?>> extends LazyDataModel<T> {
protected final Class<T> viewClass;
private KeysetPage keysetPage;
// Request caching
private transient PagedList<T> entityData;
private transient Object requestContext;
private List<SortMeta> oldSortMeta = Collections.emptyList();
@SuppressWarnings("unchecked")
public AbstractLazyDataModel() {
this.viewClass = (Class<T>) ReflectionUtils.resolveTypeVariable(getClass(), AbstractLazyDataModel.class.getTypeParameters()[0]);
}
@Override
@SuppressWarnings("unchecked")
public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
// Notice that sort functions will only work with multisort enabled on
// the datatable
final PagedList<T> list;
if (sortField == null) {
list = load(first, pageSize, Collections.EMPTY_LIST, filters);
} else {
list = load(first, pageSize, Arrays.asList(new SortMeta(null, sortField, sortOrder, null)), filters);
}
return list;
}
@Override
public PagedList<T> load(int first, int pageSize, List<SortMeta> multiSortMeta, Map<String, Object> filters) {
Object currentRequestContext = FacesContext.getCurrentInstance();
// prevent duplicate data fetching from the database within the same request
if (requestContext == currentRequestContext && entityData != null && entityData.getMaxResults() == pageSize && multiSortMeta.isEmpty() && filters.isEmpty()) {
return entityData;
}
requestContext = currentRequestContext;
if(hasSortingChanged(multiSortMeta)){
// we have to reset the keyset if the sorting changes
keysetPage = null;
}
oldSortMeta = new ArrayList<>(multiSortMeta);
entityData = getEntityData(first, pageSize, multiSortMeta, filters);
setRowCount((int) entityData.getTotalSize());
keysetPage = entityData.getKeysetPage();
return entityData;
}
protected PagedList<T> getEntityData(int startRow, int rowsPerPage, List<SortMeta> multiSortMeta, Map<String, Object> filterMap) {
return getEntityData(createSettings(viewClass, startRow, rowsPerPage, multiSortMeta, filterMap));
}
/**
* Implement this method to create a database query using the supplied entity view settings.
*
* @param setting the entity view settings that should be used for the query
* @return the query results
*/
protected abstract PagedList<T> getEntityData(EntityViewSetting<T, PaginatedCriteriaBuilder<T>> setting);
/**
* This method creates entity view settings according to the current state of pagination, filtering and sorting in
* the datatable.
*
* This implementation transparently uses keyset pagination if possible.
*
* @param modelClass entity view class
* @param startRow page start row
* @param rowsPerPage page size
* @param multiSortMeta current sort metadata
* @param filterMap current filter settings
* @return
*/
protected EntityViewSetting<T, PaginatedCriteriaBuilder<T>> createSettings(Class<T> modelClass, int startRow, int rowsPerPage, List<SortMeta> multiSortMeta, Map<String, Object> filterMap) {
EntityViewSetting<T, PaginatedCriteriaBuilder<T>> setting = EntityViewSetting.create(modelClass, startRow, rowsPerPage);
setting.withKeysetPage(keysetPage);
applyFilters(setting, filterMap);
applySorters(setting, multiSortMeta);
return setting;
}
protected void applyFilters(EntityViewSetting<?, ?> setting, Map<String, Object> filterMap) {
for (Map.Entry<String, Object> entry : filterMap.entrySet()) {
String attributeName = getAttributeName(entry.getKey());
Object filterValue = entry.getValue();
String filterString;
if (filterValue == null) {
filterString = null;
} else if (filterValue instanceof String) {
filterString = filterValue.toString();
} else {
throw new IllegalArgumentException("Unsupported filter value [" + filterValue + "], only strings are supported!");
}
setting.addAttributeFilter(attributeName, filterString);
}
}
protected void applySorters(EntityViewSetting<?, ?> setting, List<SortMeta> multiSortMeta) {
if (multiSortMeta != null && !multiSortMeta.isEmpty()) {
for (SortMeta meta : multiSortMeta) {
if (meta.getSortOrder() == SortOrder.UNSORTED) {
continue;
}
String attributeName = getAttributeName(meta.getSortField());
Sorter sorter = meta.getSortOrder() == SortOrder.ASCENDING ? Sorters.ascending() : Sorters.descending();
setting.addAttributeSorter(attributeName, sorter);
}
}
}
/**
* Maps the filter field supplied by the datatable definition to a entity view property name.
*
* @param expression the filter field expression from the datatable definition
* @return the entity view property name
*/
protected String getAttributeName(String expression) {
return expression;
}
private boolean hasSortingChanged(List<SortMeta> newSortMeta) {
if (newSortMeta.size() != oldSortMeta.size()) {
return true;
} else {
for (int i = 0; i < newSortMeta.size(); i++) {
if (!equals(newSortMeta.get(i), oldSortMeta.get(i))) {
return true;
}
}
}
return false;
}
private boolean equals(SortMeta sort1, SortMeta sort2) {
return Objects.equals(sort1.getSortField(), sort2.getSortField()) &&
Objects.equals(sort1.getSortFunction(), sort2.getSortFunction()) &&
Objects.equals(sort1.getSortOrder(), sort2.getSortOrder());
}
}
|
package com.hyb.mall.service;
import com.github.pagehelper.PageInfo;
import com.hyb.mall.model.request.CreateOrderReq;
import com.hyb.mall.model.request.OrderVO;
import com.hyb.mall.model.vo.CartVO;
import java.util.List;
/**
* 描述:订单service
*/
public interface OrderSrvice {
String create(CreateOrderReq createOrderReq);
//查询订单详情
OrderVO detail(String orderNo);
PageInfo listForCustomer(Integer pageNum, Integer pageSize);
void cancel(String orderNo);
PageInfo listForAdmin(Integer pageNum, Integer pageSize);
String qrcode(String orderNo);
void pay(String orderNo);
void delivered(String orderNo);
void finish(String orderNo);
}
|
package tests;
import model.*;
import java.util.List;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestBishop {
Board board = Board.getBoard();
@Test
public void test1_blockedMove() {
// Blocked bishop
int row = 0; int col = 5;
List<Integer> moves = board.getValidMoves(row, col);
assert moves.size() == 0;
// Free bishop
col = 2;
moves = board.getValidMoves(row, col);
assert moves.size() == 2*5;
assert board.movePiece(6, 6, 4, 6); // moving pawn to block free bishop
moves = board.getValidMoves(row, col);
assert moves.size() == 2*4;
}
@Test
public void test2_capture() {
int row = 0; int col = 2;
assert board.movePiece(row, col, 4, 6);
assert board.wasLastMoved(4, 6);
}
}
|
package com.heroesApi.utils.controlErrores;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.heroesApi.utils.controlErrores.exception.DataNotFoundException;
@SuppressWarnings({"unchecked","rawtypes"})
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(DataNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(DataNotFoundException ex, WebRequest request) {
List<String> detalles = new ArrayList<>();
detalles.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Datos no encontrados", detalles);
detalles.forEach(str -> log.error(str));
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<String> detalles = new ArrayList<>();
for(ObjectError error : ex.getBindingResult().getAllErrors()) {
detalles.add(error.getDefaultMessage());
}
ErrorResponse error = new ErrorResponse("Validation Failed", detalles);
detalles.forEach(str -> log.error(str));
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
}
}
|
package com.cy.pj.sys.dao;
import java.util.List;
//import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import com.cy.pj.common.vo.Node;
import com.cy.pj.sys.bo.SysMenu;
@Mapper
public interface SysMenuDao {
/**
* 查询菜单表中所有的菜单记录
* 一行菜单记录映射为一个map对象(key为字段名,值为字段对应值)
* @return
*/
List<SysMenu> findObjects();
/**
*
* @param id
* @return
*/
int getChildCount(Integer id);
int deletObject(Integer id);
List<Node> findZtreeMenuNodes();
int insertObject(SysMenu entity);
int updateObject(SysMenu entity);
List<String> findPermissionByIds(List<Integer> ids);
}
|
package gov.virginia.dmas.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import gov.virginia.dmas.entity.ReportProblemEntity;
public interface ReportProblemRepository extends JpaRepository<ReportProblemEntity, Long>{
}
|
package models;
public class RunTask1 {
public static void main(String[] args) {
Services[] services = new Services[3];
services[0] = new Villa("01", "Villa", 58, 500, 3, "year", "A", "ok", 24, 5);
services[1] = new House("02", "House", 36, 300, 2, "month", "B", "ok", 2);
services[2] = new Room("03", "Room", 58, 100, 1, "date", "massage", 1, 20);
System.out.println(services[0].showInfor());
System.out.println("---------------");
System.out.println(services[1].showInfor());
System.out.println("---------------");
System.out.println(services[2].showInfor());
}
}
|
package com.example.proiectdam_serbansorinaalexandra.UI;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.proiectdam_serbansorinaalexandra.Data.Landmark;
import com.example.proiectdam_serbansorinaalexandra.Data.LandmarkAdapter;
import com.example.proiectdam_serbansorinaalexandra.Data.User;
import com.example.proiectdam_serbansorinaalexandra.Database.DatabaseInstance;
import com.example.proiectdam_serbansorinaalexandra.R;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class UserLandmarksActivity extends AppCompatActivity {
private ListView lvVisitedLandmarks;
private List<Landmark> landmarks = new ArrayList<>();
private DatabaseInstance database;
private String username;
private LandmarkAdapter adapter;
private Button btnSaveToTxt;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_landmarks);
username = getIntent().getStringExtra("username");
database = DatabaseInstance.getInstance(this);
lvVisitedLandmarks = findViewById(R.id.lv_visited_landmarks);
User currentU = database.getUserDAO().getUser(username);
landmarks = database.getLandmarkDAO().selectedLandmarks(currentU.id);
adapter = new LandmarkAdapter(this,R.layout.adapter_landmark, landmarks);
lvVisitedLandmarks.setAdapter(adapter);
btnSaveToTxt = findViewById(R.id.btn_save_to_txt);
btnSaveToTxt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String space = "\n";
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = openFileOutput("Landmarks.txt", MODE_PRIVATE);
for(int i = 0; i < landmarks.size(); i++) {
fileOutputStream.write(landmarks.get(i).toString().getBytes());
fileOutputStream.write(space.getBytes());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(UserLandmarksActivity.this, "Saved to .txt", Toast.LENGTH_LONG).show();
}
});
}
}
|
package com.example.benchmark.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@AllArgsConstructor
@Data
public class Version {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Size(max = 1024)
private String txt;
private LocalDateTime created;
public Version() {
created = LocalDateTime.now();
}
@ManyToOne
@JoinColumn(name = "fk_query", nullable = false)
private Query query;
@OneToMany(mappedBy = "version", orphanRemoval = true)
private List<Run> runs;
}
|
package lando.systems.ld36.ai.states;
import lando.systems.ld36.entities.GameObject;
/**
* Created by dsgraham on 8/28/16.
*/
public abstract class State {
GameObject owner;
public State(GameObject owner){
this.owner = owner;
}
public abstract void update(float dt);
public abstract void onEnter();
public abstract void onExit();
}
|
package com.bancofuturo.workflow.sla;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* User: sergio <br/>
* Date: 12/18/20 <br/>
* Time: 6:19 PM <br/>
*
* @author Sergio Cadena
*/
public class SuccessfulySLADelegate implements JavaDelegate {
Logger logger = Logger.getLogger(SuccessfulySLADelegate.class.getName());
@Override
public void execute(DelegateExecution delegateExecution) throws Exception {
logger.log(Level.WARNING, "*************************************************************************************************************");
logger.log(Level.INFO, "El proveedor cumple con los SLA adecuadamente");
logger.log(Level.WARNING, "*************************************************************************************************************");
}
}
|
package com.cisco.jwt_spring_boot.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.CONFLICT)
public class ResourceAlreadyExistsException extends RuntimeException {
public ResourceAlreadyExistsException(String msg){
super(msg);
}
}
|
package f_sixthexp;
/*
*
* @程序名: PrintMatrix.java
* @编程人: 陈若楠 (学号: 1512480434)
* @编程日期: 2017-10-08
* @修改日期: 2017-10-08
*
*/
import java.util.Scanner;
/**
* 编写程序打印如下图所示的n*n方阵
* n = 5
* 1 1 1 1 1
* 1 2 2 2 1
* 1 2 3 2 1
* 1 2 2 2 1
* 1 1 1 1 1
* <p>
* n = 6
* 1 1 1 1 1 1
* 1 2 2 2 2 1
* 1 2 3 3 2 1
* 1 2 3 3 2 1
* 1 2 2 2 2 1
* 1 1 1 1 1 1
* <p>
* n = 7
* 1 1 1 1 1 1 1
* 1 2 2 2 2 2 1
* 1 2 3 3 3 2 1
* 1 2 3 4 3 2 1
* 1 2 3 3 3 2 1
* 1 2 2 2 2 2 1
* 1 1 1 1 1 1 1
*/
public class PrintMatrix {
public static void main(String[] args) {
System.out.println("请输入一个数表示矩阵的长");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.close();
int[][] matrix = new int[n + 1][n + 1];
for (int i = 1; i <= (n + 1) / 2; i++) {
for (int j = 1; j <= (n + 1) / 2; j++) {
if (j > i) {
matrix[i][j] = i;
} else {
matrix[i][j] = j;
}
matrix[i][n - j + 1] = matrix[i][j];
matrix[n - i + 1][j] = matrix[i][j];
matrix[n - i + 1][n - j + 1] = matrix[i][j];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
|
package practice08;
public class Klass {
private int klass = 0;
private Student leader;
public Klass(int _klass) {
this.klass = _klass;
}
public int getNumber() {
return klass;
}
public String getDisplayName() {
return "Class "+klass;
}
public void assignLeader(Student student) {
this.leader = student;
}
public Student getLeader() {
return leader;
}
}
|
package com.snewworld.listsample.viewholder;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.snewworld.listsample.R;
/**
* Created by sNewWorld on 2017-04-28.
*/
public class FlexibleImageViewHolder extends RecyclerView.ViewHolder {
private ImageView img;
public FlexibleImageViewHolder(final View parent, ImageView img) {
super(parent);
this.img = img;
}
public static FlexibleImageViewHolder newInstance(View parent) {
ImageView img = (ImageView) parent.findViewById(R.id.img);
return new FlexibleImageViewHolder(parent, img);
}
public void setImage(Drawable drawable){
img.setImageDrawable(drawable);
ViewGroup.LayoutParams lp = img.getLayoutParams();
if (lp instanceof FlexboxLayoutManager.LayoutParams) {
FlexboxLayoutManager.LayoutParams flexboxLp = (FlexboxLayoutManager.LayoutParams) lp;
flexboxLp.setFlexGrow(1.0f);
}
}
}
|
package moe.cnkirito.krpc.remoting;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author daofeng.xjf
* @date 2019/1/10
*/
public class NettyServer implements Server {
private final static Logger LOGGER = LoggerFactory.getLogger(NettyServer.class);
private static EventLoopGroup workerGroup = new NioEventLoopGroup();
private int port;
public NettyServer(int port) {
this.port = port;
}
public void start() {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new KrpcServerInitializer())
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.SO_KEEPALIVE, false);
try {
Channel channel = bootstrap.bind(port).sync().channel();
LOGGER.info("server start at localhost:{}", port);
channel.closeFuture().sync();
} catch (InterruptedException e) {
LOGGER.error("server closed cause by interrupted exception", e);
}
}
}
|
package com.example.custom.widget;
import com.example.custom.R;
import com.example.custom.util.Utils;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.support.v4.view.PagerTabStrip;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
public class CustomPagerTab extends PagerTabStrip {
private final static String TAG = "CustomPagerTab";
private int textColor = Color.BLACK; // 文本颜色
private int textSize = 15; // 文本大小
public CustomPagerTab(Context context) {
super(context);
}
public CustomPagerTab(Context context, AttributeSet attrs) {
super(context, attrs);
if (attrs != null) {
// 根据CustomPagerTab的属性定义,从布局文件中获取属性数组描述
TypedArray attrArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomPagerTab);
// 根据属性描述定义,获取布局文件中的文本颜色
textColor = attrArray.getColor(R.styleable.CustomPagerTab_textColor, textColor);
// 根据属性描述定义,获取布局文件中的文本大小
// getDimension得到的是px值,需要转换为sp值
textSize = Utils.px2sp(context, attrArray.getDimension(R.styleable.CustomPagerTab_textSize, textSize));
int customBackground = attrArray.getResourceId(R.styleable.CustomPagerTab_customBackground, 0);
int customOrientation = attrArray.getInt(R.styleable.CustomPagerTab_customOrientation, 0);
int customGravity = attrArray.getInt(R.styleable.CustomPagerTab_customGravity, 0);
Log.d(TAG, "textColor=" + textColor + ", textSize=" + textSize);
Log.d(TAG, "customBackground=" + customBackground + ", customOrientation=" + customOrientation + ", customGravity=" + customGravity);
// 回收属性数组描述
attrArray.recycle();
}
}
// //PagerTabStrip没有三个参数的构造函数
// public CustomPagerTab(Context context, AttributeSet attrs, int defStyleAttr) {
// }
@Override
protected void onDraw(Canvas canvas) { // 绘制函数
setTextColor(textColor); // 设置标题文字的文本颜色
setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize); // 设置标题文字的文本大小
super.onDraw(canvas);
}
}
|
package factorioMain;
import org.newdawn.slick.GameContainer;
public class ScienceManager {
public ScienceManager() {
// TODO Auto-generated constructor stub
}
public void loadScience(AssetManager asset, ScienceHUD SH, GameContainer container) {
//LOGISTICS I SCIENCE
asset.LogisticsI = new Science(asset.logisticsI, "LogisticsI");
asset.LogisticsI.addContent(asset.ConveyorII);
asset.LogisticsI.addContent(asset.longinserter);
Craft clogisticsI = new Craft(asset);
clogisticsI.AddRequiredItems(new ItemSlot(asset.RedPotion,10));
asset.LogisticsI.setCraft(clogisticsI);
SH.addScience(asset.LogisticsI, container);
//FRAME TECH SCIENCE
asset.FrameTech = new Science(asset.frametech, "Frame Tech I");
asset.FrameTech.addContent(asset.framemaker);
asset.FrameTech.addContent(asset.GreenPotionMaker);
asset.FrameTech.addContent(asset.MonitorMaker);
Craft cFrame = new Craft(asset);
cFrame.AddRequiredItems(new ItemSlot(asset.RedPotion,20));
asset.FrameTech.setCraft(cFrame);
SH.addScience(asset.FrameTech, container);
//ASSIMILATION DES TECHNOLOGIES DEPENDANTES
asset.LogisticsI.addUnlockedScience(asset.FrameTech);
}
}
|
package com.example.doosan.demo.controller;
import com.example.doosan.demo.service.DoosanDemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping(value = "/view")
public class DoosanDemoController {
@Autowired
private DoosanDemoService doosanDemoService;
@GetMapping("/hello")
public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="World") String name) {
model.addAttribute("name", name);
return "hello";
}
@GetMapping("/demo")
public String dooit(Model model) {
List<Map<String, Object>> devices = doosanDemoService.getDevices();
model.addAttribute("devices", devices);
return "demo";
}
}
|
package com.rockwellcollins.atc.limp.utils;
/*
* This class is used to test SimplifyExpressions.
*/
import com.rockwellcollins.atc.LimpInjectorUtil;
import com.rockwellcollins.atc.limp.ArrayAccessExpr;
import com.rockwellcollins.atc.limp.ArrayUpdateExpr;
import com.rockwellcollins.atc.limp.Expr;
import com.rockwellcollins.atc.limp.IdExpr;
import com.rockwellcollins.atc.limp.IntegerLiteralExpr;
import com.rockwellcollins.atc.limp.IntegerWildCardExpr;
public class SimplifyExpressionsDriver {
public static void main(String[] args) throws Exception {
LimpInjectorUtil.doStandaloneSetup();
//aue = b [ index := arg]
//Example 1
ArrayAccessExpr Bindex = LimpConstructors.makeArrayAccessExpr("B", "index");
IdExpr arg = LimpConstructors.makeIntegerIdExpr("arg");
ArrayUpdateExpr aue = LimpConstructors.makeArrayUpdateExpr(Bindex, arg);
IntegerLiteralExpr ile = LimpConstructors.makeIntegerLiteralExpr(3);
ArrayAccessExpr aae = LimpConstructors.makeArrayAccessExpr(aue, ile);
System.out.println("Before simplification: " + SerializerUtil.EObjectToString(aae));
Expr simplifiedExpr1 = SimplifyExpressions.simplifyExpression(aae);
System.out.println("After simplification: " + SerializerUtil.EObjectToString(simplifiedExpr1));
//Example 2
IntegerWildCardExpr wildCard = LimpConstructors.makeIntegerWildCardExpr();
ArrayAccessExpr aae2 = LimpConstructors.makeArrayAccessExpr(aue, wildCard);
System.out.println("\n" + "Before simplification: " + SerializerUtil.EObjectToString(aae2));
Expr simplifiedExpr2 = SimplifyExpressions.simplifyExpression(aae2);
System.out.println("After simplification: " + SerializerUtil.EObjectToString(simplifiedExpr2));
//Example 3
ArrayAccessExpr BindexWild = LimpConstructors.makeArrayAccessExpr("B", wildCard);
ArrayUpdateExpr aue3 = LimpConstructors.makeArrayUpdateExpr(BindexWild, arg);
ArrayAccessExpr aae3 = LimpConstructors.makeArrayAccessExpr(aue3, ile);
System.out.println("\n" + "Before simplification: " + SerializerUtil.EObjectToString(aae3));
Expr simplifiedExpr3 = SimplifyExpressions.simplifyExpression(aae3);
System.out.println("After simplification: " + SerializerUtil.EObjectToString(simplifiedExpr3));
//Example 4
IntegerLiteralExpr ile8 = LimpConstructors.makeIntegerLiteralExpr(8);
ArrayUpdateExpr aueOuter = LimpConstructors.makeArrayUpdateExpr(aae, ile8);
ArrayAccessExpr aae4 = LimpConstructors.makeArrayAccessExpr(aueOuter, wildCard);
System.out.println("\n" + "Before simplification: " + SerializerUtil.EObjectToString(aae4));
Expr simplifiedExpr4 = SimplifyExpressions.simplifyExpression(aae4);
System.out.println("After simplification: " + SerializerUtil.EObjectToString(simplifiedExpr4));
}
}
|
/**
*
*/
package fl.sabal.source.interfacePC.Windows;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import fl.sabal.source.interfacePC.Codes.Event.lettersToUppsercase;
import fl.sabal.source.interfacePC.Codes.Event.notDigit;
import fl.sabal.source.interfacePC.Codes.Event.notLetters;
import fl.sabal.source.interfacePC.Codes.ControllerLogin;
import fl.sabal.source.interfacePC.Codes.DataBases.MySQL;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.SwingConstants;
/**
* @author FL-AndruAnnohomy
*
*/
@SuppressWarnings("serial")
public class WindowLogin extends JFrame {
private JPanel contentPane;
public JTextField userField;
public JPasswordField passwordField;
private JButton btnAccept;
private JButton btnCancel;
public MySQL mysql;
/**
* Create the frame.
*/
public WindowLogin(MySQL mysql) {
this.mysql = mysql;
setBounds(100, 100, 270, 225);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblTESCo = new JLabel("TESCo");
lblTESCo.setBounds(171, 63, 46, 14);
contentPane.add(lblTESCo);
JLabel lblSABAL = new JLabel("SABAL");
lblSABAL.setFont(new Font("Tahoma", Font.BOLD, 60));
lblSABAL.setBounds(26, 11, 199, 52);
contentPane.add(lblSABAL);
JLabel lblUser = new JLabel("Usuario: ");
lblUser.setHorizontalAlignment(SwingConstants.CENTER);
lblUser.setFont(new Font("Arial", Font.BOLD, 14));
lblUser.setBounds(20, 92, 92, 14);
contentPane.add(lblUser);
JLabel lblPassword = new JLabel("Contrase\u00F1a: ");
lblPassword.setHorizontalAlignment(SwingConstants.CENTER);
lblPassword.setFont(new Font("Arial", Font.BOLD, 14));
lblPassword.setBounds(20, 125, 92, 14);
contentPane.add(lblPassword);
userField = new JTextField();
userField.setFont(new Font("Arial", Font.BOLD, 14));
userField.setBounds(110, 88, 133, 26);
contentPane.add(userField);
userField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Arial", Font.BOLD, 14));
passwordField.setBounds(110, 119, 133, 26);
contentPane.add(passwordField);
btnCancel = new JButton("Cancelar");
btnCancel.setFont(new Font("Arial", Font.BOLD, 14));
btnCancel.setBounds(26, 157, 101, 23);
contentPane.add(btnCancel);
btnAccept = new JButton("Aceptar");
btnAccept.setFont(new Font("Arial", Font.BOLD, 14));
btnAccept.setBounds(132, 157, 101, 23);
contentPane.add(btnAccept);
}
/**
* @param event
*/
public void controller(ControllerLogin event) {
btnCancel.addActionListener(event);
btnCancel.setActionCommand("DISPOSE");
btnAccept.addActionListener(event);
btnAccept.setActionCommand("ACCEPT");
userField.addKeyListener(new lettersToUppsercase());
userField.addKeyListener(new notDigit());
passwordField.addKeyListener(new notLetters());
}
}
|
package com.diozero.util;
/*-
* #%L
* Organisation: diozero
* Project: diozero - Core
* Filename: UsbInfo.java
*
* This file is part of the diozero project. More information about this project
* can be found at https://www.diozero.com/.
* %%
* Copyright (C) 2016 - 2023 diozero
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.Optional;
import org.tinylog.Logger;
public class UsbInfo {
private static final String USB_ID_DATABASE_PROP = "diozero.usb.ids";
private static final String DEFAULT_USB_ID_DATABASE = "/var/lib/usbutils/usb.ids";
private static final String USB_ID_DATABASE;
static {
USB_ID_DATABASE = PropertyUtil.getProperty(USB_ID_DATABASE_PROP, DEFAULT_USB_ID_DATABASE);
}
public static Optional<String[]> resolve(String vendorId, String productId) {
String vendor_name = null;
String product_name = null;
try {
Iterator<String> it = Files.lines(Paths.get(USB_ID_DATABASE)).filter(line -> !line.startsWith("#"))
.filter(line -> !line.isBlank()).iterator();
while (it.hasNext()) {
String line = it.next();
if (line.startsWith("C ")) {
break;
}
if (line.startsWith(vendorId)) {
vendor_name = line.substring(vendorId.length()).trim();
// Now search for the product name
while (it.hasNext()) {
line = it.next();
if (!line.startsWith("\t")) {
break;
}
if (line.trim().startsWith(productId)) {
product_name = line.trim().substring(productId.length()).trim();
break;
}
}
break;
}
}
} catch (IOException e) {
Logger.error(e);
}
if (vendor_name == null) {
return Optional.empty();
}
return Optional.of(new String[] { vendor_name, product_name });
}
}
|
package org.codeshifts.spring.batch.reader.csv.person.enums;
import org.codeshifts.spring.batch.reader.csv.person.PersonReader;
import org.codeshifts.spring.batch.reader.csv.person.PersonReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.stereotype.Component;
/**
* A first attempt to remove the constants by enums. Better general usable solution is the {@link de.ecube.spring.batch.reader.csv.person.accessor.PersonAccessorReader}
* Created by werner.diwischek on 07.05.17.
*/
@Component
@StepScope
@Deprecated
public class PersonReaderWithEnums extends PersonReader<PersonEnumBuilder> {
private static final Logger LOG = LoggerFactory.getLogger(PersonReaderWithEnums.class);
public PersonReaderWithEnums() {
super();
setLineMapper(new PersonLineMapper());
}
private class PersonLineMapper extends DefaultLineMapper<PersonEnumBuilder> {
public PersonLineMapper() {
setLineTokenizer(PersonEnumBuilder.createLineTokenizer(","));
setFieldSetMapper(new PersonFieldSetMapper());
}
}
private class PersonFieldSetMapper implements FieldSetMapper<PersonEnumBuilder> {
@Override
public PersonEnumBuilder mapFieldSet(final FieldSet fieldSet) {
return new PersonEnumBuilder(fieldSet);
}
}
}
|
package com.hallowizer.displaySlot.apiLoader.visitInstruction;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.MethodVisitor;
import com.hallowizer.displaySlot.apiLoader.ProcrastinatingAnnotationVisitor;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public final class MethodVisitParameterAnnotationInstruction implements VisitInstruction<MethodVisitor> {
private final ProcrastinatingAnnotationVisitor av;
private final int parameter;
private final String descriptor;
private final boolean visible;
@Override
public void execute(MethodVisitor mv) {
AnnotationVisitor notProcrastinating = mv.visitParameterAnnotation(parameter, descriptor, visible);
av.stopProcrastinating(notProcrastinating);
}
}
|
package View;
import java.util.TimerTask;
import javax.swing.JTextField;
public class TimerOperation {
java.util.Timer m_Timer;
PlayWindow m_Window;
JTextField m_timerTextField = new JTextField();
static int m_Time;
public TimerOperation(PlayWindow i_Window)
{
m_Time = PlayWindow.s_TimerTime;
m_Window = i_Window;
m_Timer = Controller.TimerSingleton.GetInstance();
m_timerTextField.setBounds(363, 21, 168, 20);
m_timerTextField.setColumns(10);
m_timerTextField.setEditable(false);
m_Timer.schedule(new TimerTask() {
@Override
public void run() {
m_timerTextField.setText("00 : " + m_Time);
m_Time--;
if(m_Time == 0) {
View.PlayWindow.s_CurrQuestion = Controller.GameManagement.ChangeQuestion();
PlayWindow.ChangeQuestionOnScreen(m_Window);
ResetTime();
}
}
}, 1000,1000);
}
public JTextField GetTextField() {
return m_timerTextField;
}
public static void ResetTime() {
m_Time = PlayWindow.s_TimerTime;
}
}
|
package alcChallenge.com;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private SQLiteOpenHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new MyOpenHelper(MainActivity.this);
Button about = (Button) findViewById(R.id.button_about);
Button profile = (Button) findViewById(R.id.button_my_profile);
about.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, AboutActivity.class));
}
});
profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, ProfileActivity.class));
}
});
}
}
|
package com.example.riteshkumarsingh.mvpdaggerrxtemplate.core;
/**
* Created by riteshkumarsingh on 23/08/17.
*/
public interface BasePresenter {
void onStart();
void onStop();
}
|
package com.mybatis.service.redis;
/**
* Created by yunkai on 2017/11/27.
*/
public interface JedisServiceI {
/**
* 设置key,value
*
* @param key
* @param value
*/
public void setKeyValue(String key, String value);
/**
* nx 设置key,value
*
* @param key
* @param value
*/
public void setNxKeyValue(String key, String value);
/**
* 根据key值获取value
*
* @param key
* @return
*/
public String getValue(String key);
/**
* 递减key对应的value
*
* @param key
*/
public void decrKey(String key);
/**
* sadd SET集合
*
* @param key
* @param value
* @return
*/
public Long sadd(String key, String value);
/**
* lpush List集合
* @param key
* @param value
* @return
*/
public Long lpush(String key, String value);
/**
* lpop 移除List第一个元素并获取该值
* @param key
*/
public String lpop(String key);
/**
* sismember
*
* @param key
* @param member
*/
public void sismember(String key, String member);
}
|
package dto;
import java.io.Serializable;
// Data Transfer Object
public class MovieDTO implements Serializable {
private int id;
private String name;
private String heroName;
private double avgrating;
public MovieDTO() {
super();
// TODO Auto-generated constructor stub
}
public MovieDTO(String name, String heroName, double avgrating) {
super();
this.name = name;
this.heroName = heroName;
this.avgrating = avgrating;
}
public MovieDTO(int id, String name, String heroName, double avgrating) {
super();
this.id = id;
this.name = name;
this.heroName = heroName;
this.avgrating = avgrating;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeroName() {
return heroName;
}
public void setHeroName(String heroName) {
this.heroName = heroName;
}
public double getAvgrating() {
return avgrating;
}
public void setAvgrating(double avgrating) {
this.avgrating = avgrating;
}
@Override
public String toString() {
return "MovieDTO [id=" + id + ", name=" + name + ", heroName=" + heroName + ", avgrating=" + avgrating + "]";
}
}
|
package com.wipe.zc.journey.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.wipe.zc.journey.R;
public class RefreshListView extends ListView {
private int headerHeight;
private int downY = -1;
private int headerState = PULLDOWN_STATE;
private static final int PULLDOWN_STATE = 0;
private static final int RELESE_STATE = 1;
private static final int REFRESH_STATE = 2;
private ProgressBar pb_cuslv_header;
private View header_view;
private OnRefreshListener listener;
public RefreshListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initHeader(context);
initAnimation();
}
public RefreshListView(Context context, AttributeSet attrs) {
super(context, attrs);
initHeader(context);
initAnimation();
}
public RefreshListView(Context context) {
super(context);
initHeader(context);
initAnimation();
}
/**
* 初始化头布局
*
* @param context 上下文
*/
public void initHeader(Context context) {
header_view = View.inflate(context, R.layout.item_lv_header, null);
// 隐藏头布局
// 1.测量头布局高度
header_view.measure(0, 0);
headerHeight = header_view.getMeasuredHeight();
header_view.setPadding(0, -headerHeight, 0, 0);
// 隐藏ProgressBar
pb_cuslv_header = (ProgressBar) header_view.findViewById(R.id.pb_lv_header);
pb_cuslv_header.setVisibility(View.INVISIBLE);
this.addHeaderView(header_view);
}
/**
* 初始化动画
*/
public void initAnimation() {
RotateAnimation ra_up = new RotateAnimation(
0, -180,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
ra_up.setFillAfter(true);
ra_up.setDuration(500);
RotateAnimation ra_down = new RotateAnimation(
-180, -360,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
ra_down.setFillAfter(true);
ra_down.setDuration(500);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
downY = (int) ev.getY();
break;
case MotionEvent.ACTION_MOVE:
// 判断:当处在ViewPager处在第一行,并且是从上往下滑,处理事件,改变状态
if (getFirstVisiblePosition() != 0) {
break;
}
if(headerState == REFRESH_STATE){
break;
}
if (downY == -1) {
downY = (int) ev.getY();
}
// 获取移动中的Y坐标
int moveY = (int) ev.getY();
int offsetY = moveY - downY;
if (offsetY > 0) { // 从上往下移动
int headerPadding = offsetY - headerHeight;
// 判断头布局状态
if (headerPadding < 0 && headerState != PULLDOWN_STATE) {
headerState = PULLDOWN_STATE;
switchState(headerState);
} else if (headerPadding > 0 && headerState != RELESE_STATE) {
headerState = RELESE_STATE;
switchState(headerState);
}
header_view.setPadding(0, headerPadding, 0, 0);
return true;
}
break;
case MotionEvent.ACTION_UP: // 抬起
if (headerState == PULLDOWN_STATE) {
header_view.setPadding(0, -headerHeight, 0, 0);
} else if (headerState == RELESE_STATE) {
headerState = REFRESH_STATE;
header_view.setPadding(0, 0, 0, 0);
switchState(headerState);
if (listener != null) {
listener.refreshing();
}
}
break;
default:
break;
}
return super.onTouchEvent(ev);
}
/**
* 根据状态处理
*
* @param headerState HeaderView状态
*/
private void switchState(int headerState) {
if (headerState == RELESE_STATE) {
}
if (headerState == PULLDOWN_STATE) {
}
if (headerState == REFRESH_STATE) {
pb_cuslv_header.setVisibility(View.VISIBLE);
}
}
/**
* 向外提供恢复头布局方法
*/
public void reviewHeader() {
// 隐藏标题栏
header_view.setPadding(0, -headerHeight, 0, 0);
pb_cuslv_header.setVisibility(View.INVISIBLE);
headerState = PULLDOWN_STATE;
}
public void setOnRefreshListener(OnRefreshListener listener) {
this.listener = listener;
}
public interface OnRefreshListener {
void refreshing();
}
}
|
package ua.training.controller.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import ua.training.model.dao.impl.Constants;
import ua.training.model.entity.Test;
import ua.training.model.enums.TestCategory;
import ua.training.model.enums.TestDifficulty;
public class StartTestEditCommand implements Command {
private static final String DEFAULT = "default";
@Override
public String execute(HttpServletRequest request) {
HttpSession session = request.getSession();
Test test = (Test) session.getAttribute(Constants.TEST);
String newDescription = request.getParameter(Constants.DESCRIPTION);
String newTime = request.getParameter(Constants.TIME);
String newDifficulty = request.getParameter(Constants.DIFFICULTY);
String newCategory = request.getParameter(Constants.CATEGORY);
if (newDescription != null) {
test.setDescription(newDescription);
}
if (newTime != null) {
test.setTime(Integer.parseInt(newTime));
}
if (!newDifficulty.contains(DEFAULT)) {
test.setDifficulty(TestDifficulty.valueOf(newDifficulty.toUpperCase()));
}
if (!newCategory.contains(DEFAULT)) {
test.setCategory(TestCategory.valueOf(newCategory.toUpperCase()));
}
session.setAttribute("test", test);
if (0 < test.getSize()) {
session.setAttribute(Constants.INDEX, 1);
session.setAttribute(Constants.QUESTION, test.getQuestions().get(0));
return "/admin/edit-question.jsp";
}
return "/serv/finish-test-edit";
}
}
|
package com.diozero.animation;
/*
* #%L
* Organisation: diozero
* Project: diozero - Core
* Filename: Animation.java
*
* This file is part of the diozero project. More information about this project
* can be found at https://www.diozero.com/.
* %%
* Copyright (C) 2016 - 2023 diozero
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.tinylog.Logger;
import com.diozero.animation.easing.EasingFunction;
import com.diozero.animation.easing.Linear;
import com.diozero.api.function.Action;
import com.diozero.api.function.FloatConsumer;
import com.diozero.util.DiozeroScheduler;
/**
* The Animation class constructs objects that represent a single Animation. An
* Animation consists of a target and an array of segments. A target is the
* device or list of devices that are being animated. A segment is a short
* modular animation sequence (i.e. sit, stand, walk, etc). Segments are
* synchronous and run first-in, first-out.
*/
public class Animation implements Runnable {
private static final int DEFAULT_FPS = 60;
private Collection<FloatConsumer> targets;
/**
* An easing function from ease-component to apply to the playback head on the
* timeline. See {@link com.diozero.api.easing.Easing Easing} docs for a list of
* available easing functions (default: "linear")
*/
private EasingFunction easing;
/**
* When true, segment will loop until animation.next() or animation.stop() is
* called (default: false)
*/
private boolean loop;
/**
* Controls the speed of the playback head and scales the calculated duration of
* this and all subsequent segments until it is changed by another segment or a
* call to the speed() method (default: 1.0)
*/
private float speed;
/**
* fps: The maximum frames per second for the segment (default: 60)
*/
private int fps;
private int periodMs;
/**
* function to execute when segment is started (default: none)
*/
private Action onStart;
/**
* function to execute when animation is stopped (default: none)
*/
private Action onStop;
/**
* function to execute when segment is completed (default: none)
*/
private Action onSegmentComplete;
/**
* function to execute when segment loops (default: none)
*/
private Action onLoop;
private ScheduledFuture<?> future;
private int runSegment;
private int runStep;
private LinkedList<AnimationInstance> animationInstances;
private AnimationInstance currentAnimationInstance;
public Animation(FloatConsumer target, int fps, EasingFunction easing, float speed) {
this(Arrays.asList(target), fps, easing, speed, false);
}
public Animation(FloatConsumer target, int fps, EasingFunction easing, float speed, boolean loop) {
this(Arrays.asList(target), fps, easing, speed, loop);
}
public Animation(Collection<FloatConsumer> targets, int fps, EasingFunction easing, float speed) {
this(targets, fps, easing, speed, false);
}
public Animation(Collection<FloatConsumer> targets, int fps, EasingFunction easing, float speed, boolean loop) {
animationInstances = new LinkedList<>();
this.targets = targets;
if (fps <= 0) {
fps = DEFAULT_FPS;
}
this.fps = fps;
periodMs = 1000 / fps;
// Default to Linear
if (easing == null) {
easing = Linear::ease;
}
this.easing = easing;
this.speed = speed;
this.loop = loop;
}
public int getFps() {
return fps;
}
public boolean getLoop() {
return loop;
}
public void setLoop(boolean loop) {
this.loop = loop;
}
/**
* Play the animation. Animation's are set to play by default and this only
* needs to be called if the animation has been paused or a segment's speed
* property was set to 0.
*
* @return Future instance for the background animation thread
*/
public ScheduledFuture<?> play() {
currentAnimationInstance = animationInstances.removeFirst();
runSegment = 0;
runStep = 0;
future = DiozeroScheduler.getNonDaemonInstance().scheduleAtFixedRate(this, 0, periodMs, TimeUnit.MILLISECONDS);
if (onStart != null) {
onStart.action();
}
return future;
}
/**
* Immediately stop the animation and flush the segment queue.
*/
public synchronized void stop() {
if (future != null) {
future.cancel(true);
future = null;
if (onStop != null) {
onStop.action();
}
}
}
/**
* Get the current speed
*
* @return current speed factor
*/
public float getSpeed() {
return speed;
}
public int getPeriodMs() {
return periodMs;
}
public EasingFunction getEasingFunction() {
return easing;
}
public Collection<FloatConsumer> getTargets() {
return targets;
}
/**
* Add a segment to the animation's queue.
*
* @param durationMillis Time in milliseconds for the entire animation
* @param cuePoints List of relative time points at which to change to the
* next segment
* @param keyFrames List of segment values for target
*/
public void enqueue(int durationMillis, float[] cuePoints, List<AnimationInstance.KeyFrame[]> keyFrames) {
enqueue(new AnimationInstance(durationMillis, cuePoints, keyFrames));
}
public void enqueue(AnimationInstance animationInstance) {
animationInstance.prepare(this);
animationInstances.add(animationInstance);
}
@Override
public void run() {
List<List<float[]>> segment_values = currentAnimationInstance.getSegmentValues();
float[] tgt_values = segment_values.get(runSegment).get(runStep);
int index = 0;
for (FloatConsumer target : targets) {
target.accept(tgt_values[index++]);
}
runStep++;
if (runStep == segment_values.get(runSegment).size()) {
runStep = 0;
runSegment++;
Logger.info("New segment {}, segmentValues.size() {}", Integer.valueOf(runSegment),
Integer.valueOf(segment_values.size()));
if (onSegmentComplete != null) {
onSegmentComplete.action();
}
if (runSegment == segment_values.size()) {
runSegment = 0;
// Any more animation instances?
if (animationInstances.size() > 0) {
currentAnimationInstance = animationInstances.removeFirst();
} else {
Logger.info("Finished");
if (loop) {
if (onLoop != null) {
onLoop.action();
}
} else {
future.cancel(false);
future = null;
if (onStop != null) {
onStop.action();
}
}
}
}
}
}
}
|
package test;
//导入关于栈的类
import java.util.Stack;
public class Test7 {
/**
* 用栈判断是否为回文
* @param str 判断的字符串
* @return true/false
*/
public static boolean TurnString(String str){
//如果为空,扔出错误
if (str.length()==0){
throw new IndexOutOfBoundsException ("非法字符串");
}
//如果只有一个字母,返回true
if (str.length()==1){
return true;
}
//新建栈1和2
Stack<String> stack1 = new Stack<>();
Stack<String> stack2 = new Stack<>();
//获得循环次数
double n;
if (str.length()%2==0){
n = str.length()/2+0.5;
}else{
n = (str.length()+1)/2;
}
//将字符串中前半字符按正序放入栈1
for (int i = 1 ; i < n ; i++){
stack1.add(String.valueOf(str.charAt(i-1)));
}
//将字符串中后半个字符按倒序放入栈2
for (int i = str.length() ; i > n ; i--){
stack2.add(String.valueOf(str.charAt(i-1)));
}
//循环出栈比较每一个字符
for (int i = 1 ; i<=stack1.size() ; i++){
//如果不相同,返回false
if (!(stack1.pop()).equals(stack2.pop())){
return false;
}
}
//如果相同,返回true
return true;
}
public static void main(String[] args){
String str1 = "";
String str2 = "a";
String str3 = "asd";
String str4 = "asdsa";
String str5 = "as";
String str6 = "assa";
//System.out.println(TurnString(str1));
System.out.println(TurnString(str2));
System.out.println(TurnString(str3));
System.out.println(TurnString(str4));
System.out.println(TurnString(str5));
System.out.println(TurnString(str6));
}
}
|
package br.com.sdad.services;
import br.com.sdad.EnviarEmail;
import br.com.sdad.daos.InfoVitalDAO;
import br.com.sdad.daos.UsuarioDAO;
import br.com.sdad.entidades.informacoes.BatimentoCardiaco;
import br.com.sdad.entidades.informacoes.Parametros;
import br.com.sdad.entidades.informacoes.Queda;
import br.com.sdad.mqtt.MqttPublishSubscribeUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.persistence.EntityNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
// Classe responsável por processar os tópicos recebidos pelo MQTT
@Component
public class ProcessaTopicoService {
public static final String TOPICO_ATUALIZAR_FREQUENCIA = "atualizarFrequencia";
public static final String TOPICO_DETECTAR_QUEDA = "quedaAlerta";
private static final String MSG_QUEDA_TITULO = "Queda detectada";
private static final String MSG_QUEDA_DETECTADA = "Uma possível queda foi detectada às <hora>.";
@Autowired
private InfoVitalDAO infoVitalDAO0;
@Autowired
private UsuarioDAO usuarioDAO0;
@Autowired
private MqttPublishSubscribeUtils mqtt0;
@Autowired
private EnviarEmail enviarEmail0;
private static InfoVitalDAO infoVitalDAO;
private static UsuarioDAO usuarioDAO;
private static MqttPublishSubscribeUtils mqtt;
private static EnviarEmail enviarEmail;
@PostConstruct
private void initStatic() {
infoVitalDAO = this.infoVitalDAO0;
usuarioDAO = this.usuarioDAO0;
mqtt = this.mqtt0;
enviarEmail = this.enviarEmail0;
}
public static void processaTopico(String topico, String mensagem) {
switch (topico) {
case TOPICO_ATUALIZAR_FREQUENCIA:
String jsonBatimentos = mensagem;
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonRoot = objectMapper.readTree(jsonBatimentos);
JsonNode jsonNodeIdSdad = jsonRoot.get("idDispositivo");
JsonNode jsonNodeBatimentos = jsonRoot.get("batimentos");
String idDispositivo = jsonNodeIdSdad.asText();
String stBatimentos = jsonNodeBatimentos.asText();
if(StringUtils.isNumeric(stBatimentos) && StringUtils.isNotBlank(idDispositivo)){
// Buscar id do usuário na base
int idUsuario = usuarioDAO.getIdUsuarioFromIdDispositivo(idDispositivo);
int batimentos = Integer.parseInt(stBatimentos);
BatimentoCardiaco batimentoCardiaco = new BatimentoCardiaco();
batimentoCardiaco.setIdUsuario(7);
batimentoCardiaco.setDataHora(new Timestamp(System.currentTimeMillis()));
batimentoCardiaco.setBatimentos(batimentos);
infoVitalDAO.inserirBatimentos(batimentoCardiaco);
}
} catch (IOException e){
// TODO Corrigir exception
// Do nothing
System.out.println("Erro parser json batimentos");
} catch (EntityNotFoundException enf){
String msg = "O usuário do dispositivo de ID [] não foi encontrado";
System.out.println(msg);
}
break;
case TOPICO_DETECTAR_QUEDA:
String jsonQueda = mensagem;
Timestamp hora = new Timestamp(System.currentTimeMillis());
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonRoot = objectMapper.readTree(jsonQueda);
JsonNode jsonNodeIdSdad = jsonRoot.get("idDispositivo");
JsonNode jsonNodeQueda = jsonRoot.get("queda");
String idDispositivo = jsonNodeIdSdad.asText();
boolean quedaDetectada = jsonNodeQueda.asBoolean();
if(quedaDetectada){
String email = usuarioDAO.getEmailFromIdDispositivo(idDispositivo);
String msgQueda = MSG_QUEDA_DETECTADA.replace("<hora>", hora.toString());
// Enviar email
enviarEmail.setEmailDestinatario(email);
enviarEmail.setAssunto(MSG_QUEDA_TITULO);
enviarEmail.setMsg(msgQueda);
enviarEmail.enviarGmail();
int idUsuario = usuarioDAO.getIdUsuarioFromIdDispositivo(idDispositivo);
Queda queda = new Queda();
queda.setDataHora(hora);
queda.setIdUsuario(idUsuario);
queda.definirQueda(true);
infoVitalDAO.inserirQueda(queda);
}
} catch (Exception e) {
System.out.println(e.toString());
}
break;
default:
break;
}
}
/*public static void atualizarParametros(int tempMin,
int tempMax,
int bpmMin,
int bpmMax){
try {
ObjectMapper objectMapper = new ObjectMapper();
// lógica criar json
String json = "";
if (!mqtt.status()) {
mqtt.conectar();
}
mqtt.enviarInfo("atualizarParametros", json);
} /*catch (IOException ioe){
System.out.println(ioe.toString());
}
catch (MqttException e) {
e.printStackTrace();
}
}*/
public static void atualizarParametros(String idDispositivo, Parametros parametros) {
String json = "{\"idDispositivo\" : \"" + idDispositivo + "\"," +
"\"temperatura\" : { \"limite_temp_alta\" : \"" + parametros.getTempMax()+ "\", \"limite_temp_baixa\" : \""+ parametros.getTempMin() + "\" }" +
"\"batimentos\" : { \"limite_bpm_max\" : \"" + parametros.getBpmMax() + "\", \"limite_bpm_min\" : \"" + parametros.getBpmMin() + "\"} }";
try {
if (!mqtt.status()) {
mqtt.conectar();
}
mqtt.enviarInfo("atualizarParametros", json);
} catch (Exception e){
System.out.println(e.toString());
}
}
}
|
/*
* 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 controllers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.User;
/**
*
* @author Lrandom
*/
public class UserController {
public void index(HttpServletRequest request, HttpServletResponse response){
User user = new User();
request.setAttribute("users", user.getList());
ArrayList<User.UserBean> userBeans = user.getList();
try {
// response.getWriter().write(userBeans.get(0).getUsername());
// for (User.UserBean userBean : userBeans) {
// res
// response.getWriter().write(userBean.getUsername());
// }
request.getRequestDispatcher("WEB-INF/users/index.jsp")
.forward(request, response);
//response.getWriter().print("Tes");
} catch (Exception ex) {
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.