text
stringlengths 10
2.72M
|
|---|
package com.hcl.dmu.clientprocess.dao;
import java.util.List;
import com.hcl.dmu.clientprocess.vo.StreamEntityVo;
import com.hcl.dmu.clientprocess.vo.SubStreamEntityVo;
public interface StreamDao {
List<StreamEntityVo> getAllStreamDetails();
List<SubStreamEntityVo> getAllSubStreamDetails(String streamName);
}
|
package com.stackroute;
import java.util.*;
public class StudentMarks {
public static void main(String args[]) {
List<Integer> stuGrades = new ArrayList<Integer>();
int number_Of_Students;
int grades;
Scanner input = new Scanner(System.in);
ClassData(980, new int[]{434,898080});
number_Of_Students = input.nextInt();
try {
for (int i = 0; i < number_Of_Students; i++) {
grades = input.nextInt();
if (grades > 0 && grades <= 100) {
stuGrades.add(grades);
}
else
throw new Exception();
}
} catch (Exception e){
System.out.println("enter grades between 0 & 100");
}
}
public static boolean ClassData(int number, int[] stuGrades){
return false;
}
}
|
package com.hqhcn.android.service.impl;
import com.hqh.android.dao.CodeMapper;
import com.hqh.android.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Service
public class CodeServiceImpl implements CodeService {
@Autowired
private CodeMapper mapper;
@Override
public Map<String, Map<String, String>> loadCode() {
Map<String, Map<String, String>> frmCode_map = new HashMap<String, Map<String, String>>();
List list = mapper.loadCodeMap();
for (Object obj : list) {
Map<String, Object> map = (Map<String, Object>) obj;
String xtlb = map.get("XTLB").toString();
String dmlb = map.get("DMLB").toString();
String dmz = map.get("DMZ").toString().trim();
String dmsm1 = map.get("DMSM1").toString();
if (null == frmCode_map.get(xtlb + "_" + dmlb)) {
Map<String, String> codeMap = new LinkedHashMap<String, String>();
codeMap.put(dmz, dmsm1);
frmCode_map.put(xtlb + "_" + dmlb, codeMap);
} else {
frmCode_map.get(xtlb + "_" + dmlb).put(dmz, dmsm1);
}
}
return frmCode_map;
}
}
|
/*
* 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 vista.lugaresDespripcion;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author Alan
*/
public class ChuquisacaVirgerGuadalupe extends JFrame {
private JPanel pnlImgIzq,pnlImgDer,pnlDescrp,pnlNombL;
private JLabel lblNombreLug,lblDescrp,lblUbic;
private JLabel lblImgn1,lblImgn2,lblImgn3,lblImgn4,lblImgn5;
private BorderLayout layPrinc;
private BoxLayout layCentro;
private GridLayout layIzq,layDer;
private FlowLayout layNomb;
//este main debe ser borrado esta de pruba
public ChuquisacaVirgerGuadalupe() throws HeadlessException {
setTitle("agencia De viajes (nombre agencia)");
setSize(1080,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
iniciar();
setLocationRelativeTo(null);
setVisible(true);
}
private void iniciar(){
iniciarPanels();
integrImgs();
integrInfo();
editColorEtiquets();
}
private void iniciarPanels(){
pnlNombL=new JPanel();
pnlImgIzq=new JPanel();
pnlDescrp=new JPanel();
pnlImgDer=new JPanel();
iniciarLayouts();
integLayouts();
editColor();
//se creo un espacio para que no se vea la tan junto a las imagenes
pnlDescrp.add(Box.createRigidArea (new Dimension(10, 0)));
//se integran todos los paneles en el jFrame
add(pnlNombL,BorderLayout.NORTH);
add(pnlImgIzq,BorderLayout.WEST);
add(pnlDescrp,BorderLayout.CENTER);
add(pnlImgDer,BorderLayout.EAST);
}
private void iniciarLayouts(){
layPrinc=new BorderLayout();
layNomb=new FlowLayout();
layIzq=new GridLayout(3, 1, 10, 5);
layCentro=new BoxLayout(pnlDescrp,BoxLayout.Y_AXIS);
layDer=new GridLayout(3, 1, 10,5);
}
private void integLayouts(){
setLayout(layPrinc);
pnlNombL.setLayout(layNomb);
pnlImgIzq.setLayout(layIzq);
pnlDescrp.setLayout(layCentro);
pnlImgDer.setLayout(layDer);
}
private void editColor(){
pnlNombL.setBackground(new Color(32, 112, 193));
pnlImgIzq.setBackground(new Color(32, 112, 193));
pnlDescrp.setBackground(new Color(32, 112, 193));
pnlImgDer.setBackground(new Color(32, 112, 193));
}
private void integrImgs(){
lblImgn1=new JLabel(new ImageIcon(getClass().getResource("/vista/LugaresTuristicos/Chuquisaca/CapillaVirgenGuadalupe/imagen1.jpg")));
lblImgn2=new JLabel(new ImageIcon(getClass().getResource("/vista/LugaresTuristicos/Chuquisaca/CapillaVirgenGuadalupe/imagen2.jpg")));
lblImgn3=new JLabel(new ImageIcon(getClass().getResource("/vista/LugaresTuristicos/Chuquisaca/CapillaVirgenGuadalupe/imagen3.jpg")));
lblImgn4=new JLabel(new ImageIcon(getClass().getResource("/vista/LugaresTuristicos/Chuquisaca/CapillaVirgenGuadalupe/imagen4.jpg")));
lblImgn5=new JLabel(new ImageIcon(getClass().getResource("/vista/LugaresTuristicos/Chuquisaca/CapillaVirgenGuadalupe/imagen5.jpg")));
pnlImgIzq.add(lblImgn1);
pnlImgIzq.add(lblImgn2);
pnlImgDer.add(lblImgn3);
pnlImgDer.add(lblImgn4);
pnlImgDer.add(lblImgn5);
}
private void integrInfo(){
lblNombreLug=new JLabel("Capilla de la Virgen de Guadalupe");
lblUbic=new JLabel("<html>Contáctanos:<p> Av. Ayacucho entre Colombia y Ecuador <p>+591 62615493 <p>4 4446666 <p> Cochabamba-Bolivia<html>");
lblDescrp=new JLabel("<html>La imagen mas querida para muchos denominado como la patrona de Chuquisaca o Sucre, una hermosa imagen con una infinita cantidad de incrustaciones de joyas de inapreciable valor. En 1748 el lienzo se reforzo con una plancha de maciza de oro y plata, representado el manto de la Virgen dejando la pintura original en el rostro de la virgen y el niño.<html><p>"
+ "<p><html>La historia nos relata que una trade encontraron una mula extraviada con una extraña carga en su lomo, se trabata de un enorme cajon que el animal cuidaba celosamente sin dejarse atrapar. Cuando se postraba a descansar, esta se encondia entra las plantas y luego salia sin descuidar jamas su carga, la gente intento atrapar a dicho animal pensando que llevaba consigo era un tesoro, finalmente con ayuda de autoridades y la iglesia el animal fue atrapado descubriendo en su cargo siendo una sorpresa para todos una hermosa imagen de la virgen de rostro moreno y un niño en sus mano: era la Virgen de Guadalupe.<p><html>"
+"<html><p>Desde entonces, se celebra en su honor una gran fiesta el 8 de septiembre, con entradas folkloricas de conjuntos, dando otro atractivo mas colorido y de gran interes para enriquezer nuestro turismo nacional, durante la fiesta dicha imagen recorre la ciudad mostrandose a la poblacion en general a paso lento mas que todo en la Plaza 25 de Mayo .<p><html>"
+"<html><p>Nuestro paquete ofrece diferentes actividades que se encuentra formuladas en este con diferentes atractivos para las familias que se dirigen a dicha zona, considerar que se realizaran diferentes caminatas durante nuestro tour, aquellas personas que llegasen a sufrir problemas fisicos abstenerse.<p><html>"
+"<html><p><p><html>");
pnlNombL.add(lblNombreLug);
pnlImgIzq.add(lblUbic);
pnlDescrp.add(lblDescrp);
}
private void editColorEtiquets(){
lblDescrp.setForeground(Color.WHITE);
lblUbic.setForeground(Color.WHITE);
lblNombreLug.setForeground(Color.WHITE);
//se cambian tamaños
lblDescrp.setFont(new Font("arial", Font.PLAIN, 18));
lblUbic.setFont(new Font("arial", Font.PLAIN, 14));
lblNombreLug.setFont(new Font("arial", Font.BOLD, 20));
}
}
|
package LeetCode.LinkedList;
public class RemoveDuplicates {
public ListNode deleteDuplicates(ListNode head) {
ListNode temp = head;
while(temp != null) {
if(temp.next != null && temp.next.val == temp.val) {
temp.next = temp.next.next;
} else {
temp = temp.next;
}
}
return head;
}
public static void main(String[] args){
ListNode head = new ListNode(1, new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(3)))));
RemoveDuplicates r = new RemoveDuplicates();
ListNode res = r.deleteDuplicates(head);
while (res != null){
System.out.print(res.val);
System.out.print('\t');
res = res.next;
}
}
}
|
package edu.sit.view.controllers;
import edu.sit.bancodedados.conexao.ConexaoException;
import edu.sit.bancodedados.dao.FornecedorDao;
import edu.sit.erro.visualizacao.EErroVisualizacao;
import edu.sit.erro.visualizacao.VisualizacaoException;
import edu.sit.erros.dao.DaoException;
import edu.sit.model.Fornecedor;
public class FornecedorView {
public static boolean visualizar() throws VisualizacaoException {
try {
System.out.println("\n**** LISTA DE FORNECEDOR ****\n");
System.out.println(String.format("%-15s", "Código") + String.format("%-20s", "Nome") + "CNPJ");
for (Fornecedor fornecedor : new FornecedorDao().consultaTodos()) {
System.out.println(String.format("%-15s", "[" + fornecedor.getId() + "]")
+ String.format("%-20s", fornecedor.getNome()) + String.format("%-10s", fornecedor.getCNPJ()));
}
return true;
} catch (DaoException | ConexaoException e) {
System.out.println(e.getMessage());
throw new VisualizacaoException(EErroVisualizacao.ERRO_BUSCA_FORNECEDORES);
}
}
public static void exibeFornecedor(Fornecedor fornecedor) {
System.out.println("************* DADOS DO CLIENTE***************");
System.out.println("Nome\t" + fornecedor.getNome());
System.out.println("CNPJ\t" + fornecedor.getCNPJ());
System.out.println("Email\t" + fornecedor.getContato().getEmail() + "--------- Telefone\t"
+ fornecedor.getContato().getTelefone());
System.out.println("Pessoa responsável\t" + fornecedor.getPessoaResponsavel());
}
}
|
public class circle implements Shape {
private double radius;
public circle(double radius) {
this.radius = radius;
}
@Override
public double calcArea() {
return Math.PI * radius * radius;
}
@Override
public void printDetails() {
}
}
|
/*
* UniTime 3.2 - 3.5 (University Timetabling Application)
* Copyright (C) 2008 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.model;
import java.util.Set;
import java.util.TreeSet;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.unitime.timetable.model.base.BaseRoles;
import org.unitime.timetable.model.dao.RolesDAO;
import org.unitime.timetable.security.rights.HasRights;
import org.unitime.timetable.security.rights.Right;
/**
* @author Tomas Muller
*/
public class Roles extends BaseRoles implements HasRights, Comparable<Roles> {
/**
*
*/
private static final long serialVersionUID = 3256722879445154100L;
/*[CONSTRUCTOR MARKER BEGIN]*/
public Roles () {
super();
}
/**
* Constructor for primary key
*/
public Roles (java.lang.Long roleId) {
super(roleId);
}
/*[CONSTRUCTOR MARKER END]*/
public static final String ROLE_STUDENT = "Student";
public static final String ROLE_INSTRUCTOR = "Instructor";
public static final String ROLE_NONE = "No Role";
public static final String ROLE_ANONYMOUS = "Anonymous";
public static String USER_ROLES_ATTR_NAME = "userRoles";
public static String ROLES_ATTR_NAME = "rolesList";
public static Roles getRole(String roleRef, org.hibernate.Session hibSession) {
return (Roles)hibSession.createQuery(
"from Roles where reference = :reference")
.setString("reference", roleRef).setCacheable(true).uniqueResult();
}
@Override
public boolean hasRight(Right right) {
return getRights().contains(right.name());
}
public Long getUniqueId() { return getRoleId(); }
public boolean isUsed() {
return ((Number)RolesDAO.getInstance().getSession().createQuery(
"select count(m) from ManagerRole m where m.role.roleId = :roleId")
.setLong("roleId", getRoleId()).uniqueResult()).intValue() > 0;
}
public static Set<Roles> findAll(boolean managerOnly) {
return findAll(managerOnly, RolesDAO.getInstance().getSession());
}
public static Set<Roles> findAll(boolean managerOnly, org.hibernate.Session hibSession) {
Criteria criteria = hibSession.createCriteria(Roles.class);
if (managerOnly)
criteria = criteria.add(Restrictions.eq("manager", Boolean.TRUE));
return new TreeSet<Roles>(criteria.setCacheable(true).list());
}
public static Set<Roles> findAllInstructorRoles() {
return findAllInstructorRoles(RolesDAO.getInstance().getSession());
}
public static Set<Roles> findAllInstructorRoles(org.hibernate.Session hibSession) {
return new TreeSet<Roles>(hibSession.createCriteria(Roles.class).add(Restrictions.eq("instructor", Boolean.TRUE)).setCacheable(true).list());
}
@Override
public int compareTo(Roles o) {
if (isManager() != o.isManager())
return (isManager() ? 1 : -1);
if (getRights().size() != o.getRights().size())
return (getRights().size() < o.getRights().size() ? -1 : 1);
return getAbbv().compareToIgnoreCase(o.getAbbv());
}
}
|
package com.yt;
public class Yellow implements Color {
@Override
public void bepaint(String shape) {
System.out.println(shape+"黄色");
}
}
|
package com.paritytrading.parity.client.event;
import com.paritytrading.parity.net.poe.POE;
public class Error {
public static final String HEADER = "" +
"Order ID Reason\n" +
"---------------- ------------------";
private String orderId;
private byte reason;
public Error(Event.OrderRejected event) {
orderId = event.orderId;
reason = event.reason;
}
private String describe(byte reason) {
switch (reason) {
case POE.ORDER_REJECT_REASON_UNKNOWN_INSTRUMENT:
return "Unknown instrument";
case POE.ORDER_REJECT_REASON_INVALID_PRICE:
return "Invalid price";
case POE.ORDER_REJECT_REASON_INVALID_QUANTITY:
return "Invalid quantity";
default:
return "<unknown>";
}
}
public String format() {
return String.format("%16s %-18s", orderId, describe(reason));
}
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.qtplaf.library.ai.learning.genetic;
import java.util.List;
/**
* Utilities to score.
*
* @author Miquel Sas
*/
public class ScoreUtils {
/**
* Scored networks comparator.
*/
public static class Comparator implements java.util.Comparator<Genome> {
/** Minimize. */
private boolean minimize;
/**
* Constructor.
*
* @param minimize Minimize flag.
*/
public Comparator(boolean minimize) {
super();
this.minimize = minimize;
}
/**
* Do compare.
*
* @param g1 First genome.
* @param g2 Second genome.
*/
@Override
public int compare(Genome g1, Genome g2) {
return ScoreUtils.compare(g1.getScore(), g2.getScore(), minimize);
}
}
/**
* Compare two scores. Returns a negative integer, zero or a positive integer as the first score is better, equal to
* or worst than the second score.
*
* @param score1 The first score.
* @param score2 The second score.
* @param minimize A boolean that indicates if scores should be minimized.
* @return A comparison integer.
*/
public static int compare(double score1, double score2, boolean minimize) {
if (minimize) {
if (score1 < score2) {
return -1;
}
if (score1 > score2) {
return 1;
}
} else {
if (score1 > score2) {
return -1;
}
if (score1 < score2) {
return 1;
}
}
return 0;
}
/**
* Return the winner (best) of the list.
*
* @param genomes The list of genomes.
* @param minimize A boolean that indicates if scores should be minimized.
* @return The winner or best genome.
*/
public static Genome getWinner(List<Genome> genomes, boolean minimize) {
Genome winner = null;
for (Genome member : genomes) {
if (winner == null) {
winner = member;
}
if (compare(winner.getScore(), member.getScore(), minimize) > 0) {
winner = member;
}
}
return winner;
}
/**
* Return the looser (worst) of the list.
*
* @param genomes The list of genomes.
* @param minimize A boolean that indicates if scores should be minimized.
* @return The loser or worst genome.
*/
public static Genome getLooser(List<Genome> genomes, boolean minimize) {
Genome looser = null;
for (Genome member : genomes) {
if (looser == null) {
looser = member;
}
if (compare(looser.getScore(), member.getScore(), minimize) < 0) {
looser = member;
}
}
return looser;
}
}
|
package com.yinghai.a24divine_user.module.login.state;
import android.app.Activity;
/**
* @author Created by:fanson
* Created Time: 2017/11/23 11:08
* Describe:(状态模式)用户在登录后的情况下操作,返回true方可进行操作
*/
public class LoginState implements UserState{
@Override
public boolean onBookDivine(Activity activity) {
return true;
}
@Override
public boolean onCollect(Activity activity) {
return true;
}
@Override
public boolean onComment(Activity activity) {
return true;
}
@Override
public boolean onShopping(Activity activity) {
return true;
}
@Override
public boolean onMe(Activity activity) {
return true;
}
@Override
public boolean onLookUserInfo(Activity activity) {
return true;
}
}
|
package interviewTasks_Saim;
import java.util.Arrays;
public class SumOfElementsCloseToZero {
public static void main(String[] args) {
int [] num ={1,8,0,2,6,8,5,8,0,1,2,0};
getSumOfTwoClosestToZeroElements(num);
}
public static void getSumOfTwoClosestToZeroElements(int[] a){
int [] b = new int[2];
int z= 0;
for (int i =0 ;i < a.length; i++){
for(int j = i + 1 ; j < a.length; j ++){
int sum= a[i] + a[j];
if(z == 0 );
z = sum;
if(Math.abs(sum) > 0 && Math.abs(sum) < Math.abs(z)){
z = sum;
b[0] = a [i];
b[1] = a [j];
}
}
}
// System.out.println(a[]);
}
}
|
package com.example.waterbilling;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLDataException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.waterbilling.Sync.dailySync;
import calculations.Bill_calculation_Fault;
import calculations.Bill_caluculations;
import database.sqldataclass;
import Read.Write.File.Printfile;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Layout;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint({ "NewApi", "SimpleDateFormat" })
public class Ds_Corrected_Bill extends Activity {
private TextView consCode;
private TextView name;
private TextView fromDate;
private TextView toDate;
private TextView creds;
private EditText cumUnits;
private EditText avgUnits;
private EditText minUnits;
private EditText curRdg;
private EditText prevRdg;
private EditText unitsBld;
private TextView addlUnits;
private EditText wtrCharges;
private EditText swgCharges;
private EditText mtrRent;
private EditText sunCharges;
private EditText arrs;
private EditText cat;
private EditText fixDate;
private EditText mtrSize;
private EditText mtrNum;
private EditText monthlyRent;
private TextView total;
private Button print;
private Button calc;
private Button mtrRepl;
private Spinner fault;
private String faultVal;
public ArrayList<String> billedCons;
private ArrayList<String> faultsList=new ArrayList<String>();
private ArrayList<String> faultsdescp=new ArrayList<String>();
private ArrayList<String> consOutList=new ArrayList<String>();
private ArrayList<String> records = new ArrayList<String>();
private static ArrayList<EditText> editList = new ArrayList<EditText>();
private String selecteditem;
private String wtrRate;
private String swgRate;
private String mtrRate;
private String sunRate;
private String arrsRate;
private int wtrChargesVal;
private int mtrRentVal;
private int swgChargesVal;
private int sunVal;
private int arrsVal;
private int posVal;
private Integer currentreading ;
private Integer prevreading;
sqldataclass getread = new sqldataclass(Ds_Corrected_Bill.this);
public Bill_caluculations cal= new Bill_caluculations(Ds_Corrected_Bill.this);
public Bill_calculation_Fault calf = new Bill_calculation_Fault(Ds_Corrected_Bill.this);
public Boolean correctDate= false;
public Boolean correctionFlag= true;
public Date wrongDate = null;
public float watrChrg=0;
public String consId;
public boolean wt = false;
public String values;
public boolean BTConnected=true;
public boolean hasText=false;
Printfile pf = new Printfile(Ds_Corrected_Bill.this);
ArrayList<String> Printdata = new ArrayList<String>();
public boolean wf, textChanged=false, visChk=false;
TableLayout tl;
String dtFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(dtFormat, Locale.US);
sqldataclass entry;
String username,Location,role;
boolean bf,upFlag=false;
File file;
//String upurl = "http://www.imaginepanajiexpo.com/slides/Uploadfile.php"; Commented on 24-7-14
String upurl = "http://www.cybercadtechnologies.com/admin/Uploadfile.php"; //Added on 24-7-14
String upSetTimeurl = "http://www.cybercadtechnologies.com/admin/app/SetUploadTime.php"; //Added on 7-8-14
String filename; //Added on 8-7-14
//String upurl = "http://10.0.2.2/waterbill/Uploadfile.php";
//String upurl = "http://www.websitedevelopmentindia.org/tempr/Uploadfile.php";
boolean extra = false; //Added on 19-9-14
String dateInstall;
sqldataclass dq=new sqldataclass(Ds_Corrected_Bill.this);
String appCheckUrl = "http://www.cybercadtechnologies.com/admin/app/appUpdate.php"; //Added on 13-3-15
String appUpdateUrl = "http://www.cybercadtechnologies.com/admin/app/BillMaster.apk"; //Added on 23-3-15
String dailySyncUrl = "http://www.cybercadtechnologies.com/admin/app/dailySync.php"; //Added on 18-4-15
String checkUploadUrl = "http://www.cybercadtechnologies.com/admin/app/chcekUpload.php";
String appUpdateAvailable = null;
sqldataclass dc = new sqldataclass(Ds_Corrected_Bill.this);
//-----------added on 24-3-15--------//
ProgressBar pb;
Dialog dialog;
int downloadedSize = 0;
int totalSize = 0;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
//----------------------------------//
/////////////////////////////// Edited By Ryan 17-1-14 ///////////////////////////////
public static final String PREF_FILE_NAME = "PrefFile";
public String SharedPerfCookieVal="";
public SharedPreferences preferences;
///////////////////////////////////// End ///////////////////////////////////
String ConsToalCount; //Added on 19-8-14
Cursor syncData = null; // Added on 22-4-15
JSONObject jsnobj;
//JSONArray arr = new JSONArray();
boolean dsy=false;
dailySync dsync = new dailySync();
int dsCount=0;
//---------------------------23-4-15-------------------------//
// This is some change made to test gitHub..booYEAH!!!
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ds_corrected_bill);
calc=(Button) findViewById(R.id.calculate);
calc.setEnabled(false);
mtrRepl=(Button) findViewById(R.id.mtrRepl);
print=(Button) findViewById(R.id.print);
consCode=(TextView) findViewById(R.id.consCode);
name=(TextView) findViewById(R.id.name);
cat=(EditText) findViewById(R.id.category);
fromDate=(TextView) findViewById(R.id.fromDate);
toDate=(TextView) findViewById(R.id.toDate);
cumUnits=(EditText) findViewById(R.id.cumUnits);
avgUnits=(EditText) findViewById(R.id.avgUnits);
minUnits=(EditText) findViewById(R.id.minUnits);
curRdg=(EditText) findViewById(R.id.curRead);
prevRdg=(EditText) findViewById(R.id.prevRead);
unitsBld=(EditText) findViewById(R.id.unitsBill);
addlUnits=(TextView) findViewById(R.id.adlUnits);
wtrCharges=(EditText) findViewById(R.id.wtrCharges);
swgCharges=(EditText) findViewById(R.id.swgCharges);
mtrRent=(EditText) findViewById(R.id.mtrRent);
sunCharges=(EditText) findViewById(R.id.sunCharges);
arrs=(EditText) findViewById(R.id.arrs_credits);
creds=(TextView) findViewById(R.id.credits);
total=(TextView) findViewById(R.id.total);
fault=(Spinner) findViewById(R.id.fault);
mtrSize=(EditText) findViewById(R.id.mtrSize);
fixDate=(EditText) findViewById(R.id.fixDate);
monthlyRent=(EditText) findViewById(R.id.monthlyRent);
mtrNum=(EditText) findViewById(R.id.mtrNum);
addEditList();
for(int i=0;i<editList.size()-6;i++){
editList.get(i).setOnFocusChangeListener(focusListener);
}
Bundle extras=getIntent().getExtras();
if(extras!=null)
{
billedCons=extras.getStringArrayList("BilledCons");
}
//saving fetched details in cons_in Table
getread.write_to_cons_in(billedCons);
consOutList.add(billedCons.get(39)); //0 consId
consOutList.add(billedCons.get(2)); // 1 issueDt
consOutList.add(billedCons.get(11)); //2 Cycle_Period
consOutList.add(billedCons.get(12)); //3 Last_Payment_Date
consOutList.add(billedCons.get(31)); //4 Meter_Rent1
consOutList.add(billedCons.get(43)); //5 Average_Units
consOutList.add(billedCons.get(60)); //6 Cumulative_Units1
consOutList.add(billedCons.get(25)); //7 Current_Reading
consOutList.add(billedCons.get(27)); //8 Units_Billed
consOutList.add(billedCons.get(28)); //9 Additional_Units
consOutList.add(billedCons.get(17)); //10 Lpcd
consOutList.add(billedCons.get(23)); //11 Bill_Base
consOutList.add(billedCons.get(24)); //12 Fault1
consOutList.add(billedCons.get(57)); //13 fault_Date1
consOutList.add(billedCons.get(50)); //14 Reading_rpt_count
consOutList.add(billedCons.get(29)); //15 Water_Charges
consOutList.add(billedCons.get(30)); //16 Sewage_Charge
consOutList.add(billedCons.get(34)); //17 Total_Bill_Amt
consOutList.add(billedCons.get(58)); //18 Conn_Status_out
consOutList.add(billedCons.get(59)); //19 Conn_Date_out
consOutList.add(billedCons.get(3)); //20 Time
consOutList.add(billedCons.get(36)); //21 Carry_Fwd
consOutList.add(billedCons.get(56)); //22 conscode3
//saving fetched details in cons_out Table
getread.write_to_cons_out(consOutList);
faultVal = billedCons.get(24).trim();
Load_Spinner_Data();
if(faultVal.equals("G")){
fault.setSelection(1);
}
else if(faultVal.equals("A")){
fault.setSelection(2);
}
else if(faultVal.equals("L")){
fault.setSelection(3);
}
else if(faultVal.equals("C")){
fault.setSelection(4);
}
else if(faultVal.equals("N")){
fault.setSelection(5);
}
else if(faultVal.equals("D")){
fault.setSelection(6);
}
else if(faultVal.equals("M")){
fault.setSelection(7);
}
else if(faultVal.equals("R")){
fault.setSelection(8);
}
else if(faultVal.equals("I")){
fault.setSelection(9);
}
consCode.setText(billedCons.get(40));
name.setText(billedCons.get(5));
cat.setText(billedCons.get(15));
fromDate.setText(billedCons.get(9));
toDate.setText(billedCons.get(10));
cumUnits.setText(billedCons.get(45)); //cons_in table cumUnits
//fixDate.setText(billedCons.get(19));
//mtrSize.setText(billedCons.get(20));
avgUnits.setText(billedCons.get(43)); //cons_in table avgUnits
minUnits.setText(billedCons.get(22));
creds.setText(billedCons.get(36));
curRdg.setText(billedCons.get(25));
prevRdg.setText(billedCons.get(26));
unitsBld.setText(billedCons.get(27));
addlUnits.setText(billedCons.get(28));
wtrCharges.setText(billedCons.get(29));
swgCharges.setText(billedCons.get(30));
mtrRent.setText(billedCons.get(31));
sunCharges.setText(billedCons.get(32));
arrs.setText(billedCons.get(33));
total.setText(billedCons.get(34));
if(faultVal.equals("--")) {
curRdg.setFocusableInTouchMode(true);
curRdg.setFocusable(true);
curRdg.setEnabled(true);
}
else {
curRdg.setEnabled(false);
curRdg.setFocusable(false);
}
fault.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
selecteditem=parent.getSelectedItem().toString();
posVal=fault.getSelectedItemPosition();
if(position==0) {
curRdg.setFocusableInTouchMode(true);
curRdg.setFocusable(true);
curRdg.setEnabled(true);
}
else {
curRdg.setEnabled(false);
curRdg.setFocusable(false);
curRdg.setText("0");
}
calc.setEnabled(true);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
wtrCharges.addTextChangedListener(inputValuesListener);
swgCharges.addTextChangedListener(inputValuesListener);
mtrRent.addTextChangedListener(inputValuesListener);
sunCharges.addTextChangedListener(inputValuesListener);
arrs.addTextChangedListener(inputValuesListener);
mtrRepl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tl=(TableLayout) findViewById(R.id.mrLayout);
//tl.setVisibility(v.getVisibility() == View.INVISIBLE ? View.VISIBLE: View.INVISIBLE);
if(visChk==false){
tl.setVisibility(View.VISIBLE);
visChk=true;
}
else{
tl.setVisibility(View.GONE);
visChk=false;
}
fixDate.setText(billedCons.get(19));
mtrSize.setText(billedCons.get(20));
monthlyRent.setText(billedCons.get(42));
mtrNum.setText(billedCons.get(18));
//DatePickerDialog to change meter fixed date
final Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(sdf.parse(billedCons.get(19)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
// TODO Auto-generated method stub
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
fixDate.setText(sdf.format(calendar.getTime()));
}
};
fixDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(Ds_Corrected_Bill.this, date,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
fixDate.addTextChangedListener(textWatcher);
mtrSize.addTextChangedListener(textWatcher);
monthlyRent.addTextChangedListener(textWatcher);
mtrNum.addTextChangedListener(textWatcher);
}
});
calc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
faultValidation();
if(hasText){
// update billedCons array with the editText values
// insert into the cons_in table
boolean validCat = getread.fetchCategory(cat.getText().toString().trim());
if(validCat)
{
if(visChk && textChanged){
billedCons.set(19, fixDate.getText().toString().trim());
billedCons.set(20, mtrSize.getText().toString().trim());
billedCons.set(42, monthlyRent.getText().toString().trim());
billedCons.set(18, mtrNum.getText().toString().trim());
billedCons.set(35, "R".toString());
}
billedCons.set(15, cat.getText().toString().trim());
//billedCons.set(19, fixDate.getText().toString());
//billedCons.set(20, mtrSize.getText().toString());
billedCons.set(43, avgUnits.getText().toString().trim());
billedCons.set(22, minUnits.getText().toString().trim());
billedCons.set(26, prevRdg.getText().toString().trim());
billedCons.set(45, cumUnits.getText().toString());
sqldataclass consInTable = new sqldataclass(Ds_Corrected_Bill.this);
consInTable.write_to_cons_in(billedCons);
String str2 = selecteditem;
System.out.print(str2);
String str = "Normal";
if (selecteditem.equalsIgnoreCase(str))
{ //check if the status is normal
billedCons.set(24, "");//fault normal
billedCons.set(57, "");//fault date null
values = billedCons.get(56);
records= getread.getreadingsame(values);
currentreading = Integer.parseInt(curRdg.getText().toString().trim());
prevreading= Integer.parseInt(records.get(22)); //obtains the previous reading
if(currentreading.equals(prevreading)) // if the readings are equal
{
Toast.makeText(Ds_Corrected_Bill.this, "meter not k ", Toast.LENGTH_LONG).show();
AlertDialog.Builder at2 = new AlertDialog.Builder(Ds_Corrected_Bill.this);
at2.setTitle("Confirmation");
at2.setCancelable(false);
at2.setMessage("same reading " + records.get(27) + " time.\n Is meter Faulty"); //same reading nth tym
at2.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
//commented on 24-2-15// calf.calfaultmodA(values, "M"); //meter not working
/*--------------------------------Added on 24-2-15 ----------------------------*/
correctDate=calf.calfaultmodA(values, "M"); //meter not working
/*-----------------------------------------------------------------------------*/
//---------------Added on 02-3-15 to check the watercharges > 5000----------------//
watrChrg = calf.getWaterCharges();
//------------------------------------------------------------------------------//
calf.setrptcount(); //increment count
Float watercharge =calf.write_to_textfile() ; //write to text file
boolean r=calf.write_to_db(); //write to db
if(r) //if db write successful
{
/*----------------------Added on 16-2-15--------------------------------*/
if(watercharge<0)
{
Toast.makeText(Ds_Corrected_Bill.this, "Charges are 0.0", Toast.LENGTH_LONG).show();
}
else
//----------------------------------------------------------------------//
Toast.makeText(Ds_Corrected_Bill.this, "Charges are"+watercharge, Toast.LENGTH_LONG).show();
updateTextview();
}
else
{
Toast.makeText(Ds_Corrected_Bill.this, "Write to database failed try again", Toast.LENGTH_LONG).show();
}
}
});
//---------------------------------------------------------------------------------//
at2.setNegativeButton("No", new DialogInterface.OnClickListener() { //meter not faulty
@Override
public void onClick(DialogInterface arg0, int arg1) {
records.add(currentreading.toString());
records.add(prevreading.toString());
records.add(billedCons.get(10)); //Issue Date
try
{
correctDate=cal.calmoduleA(records);//get the the no of units used and the average num of units
}
catch (Exception e) {
wt = true;
}
watrChrg = cal.getWaterCharges();
continueWrite2Db();
updateTextview();
}
}) ;
AlertDialog alertdialog=at2.create();
//show the alertdialog
alertdialog.show();
Toast.makeText(Ds_Corrected_Bill.this, records.get(25), Toast.LENGTH_LONG).show();
}
else if(currentreading.intValue()<prevreading.intValue()) //if the current reading less then previous reading
{
AlertDialog.Builder at3 = new AlertDialog.Builder(Ds_Corrected_Bill.this);
at3.setTitle("Confirmation");
at3.setCancelable(false);
at3.setMessage(" Less then previous reading \n Is meter faulty ?");
at3.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
correctDate=calf.calfaultmodA(values, "R");
watrChrg = calf.getWaterCharges();
Float watercharge =calf.write_to_textfile() ; //write to text file
boolean r=calf.write_to_db(); //write to db
if(r) //if db write successful
{
if(watercharge<0)
{
Toast.makeText(Ds_Corrected_Bill.this, "Charges are 0.0", Toast.LENGTH_LONG).show();
}
else
//----------------------------------------------------------------------//
Toast.makeText(Ds_Corrected_Bill.this, "Charges are"+watercharge, Toast.LENGTH_LONG).show();
updateTextview();
}
else
{
Toast.makeText(Ds_Corrected_Bill.this, "Write to database failed try again", Toast.LENGTH_LONG).show();
}
}
});
at3.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// this check for the 9999999 logic
AlertDialog.Builder at4 = new AlertDialog.Builder(Ds_Corrected_Bill.this);
at4.setTitle("Confirmation");
at4.setCancelable(false);
at4.setMessage(" Calculate by 9999999 Logic?");
at4.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// passing parameters to the calculate function
records.add(currentreading.toString());
records.add(prevreading.toString());
records.add(billedCons.get(10)); //Issue Date
try // try catch added on 20-4-15
{
correctDate=cal.calmoduleA(records);//get the the no of units used and the average num of units
}
catch (Exception e) {
//showNoWatchrgMsg();
//finish();
wt = true;
}
watrChrg = cal.getWaterCharges();
continueWrite2Db();
updateTextview();
}
});
at4.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertdialog=at4.create();
//show the alertdialog
alertdialog.show();
}
}) ;
AlertDialog alertdialog=at3.create();
//show the alertdialog
alertdialog.show();
}
else
{
Toast.makeText(Ds_Corrected_Bill.this, "meter k ", Toast.LENGTH_SHORT).show();
records.add(currentreading.toString());
records.add(prevreading.toString());
records.add(billedCons.get(10)); //Issue Date
try // try catch added on 20-4-15
{
correctDate=cal.calmoduleA(records);//get the the no of units used and the average num of units
}
catch (Exception e) {
//showNoWatchrgMsg();
//finish();
e.printStackTrace();
wt = true;
}
watrChrg = cal.getWaterCharges();
continueWrite2Db();
}
}
else
{
String faultCode = faultsList.get(fault.getSelectedItemPosition());
values = billedCons.get(56);
calf.setIssueDate(billedCons.get(10));
correctDate=calf.calfaultmodA(values,faultCode);
if(!correctDate)
{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
String date1 = format1.format(date);
AlertDialog.Builder at12 = new AlertDialog.Builder(Ds_Corrected_Bill.this);
at12.setTitle("Wrong Device Date");
at12.setMessage("The issue date is "+date1+" Please set todays date");
at12.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alrt = at12.create();
alrt.show();
}
else
{
watrChrg = calf.getWaterCharges();
Float watercharge =calf.write_to_textfile() ;
boolean r=calf.write_to_db(); //write to db
if(r) //if db write succesfull
{
/*----------------------Added on 16-2-15--------------------------------*/
if(watercharge<0)
{
Toast.makeText(Ds_Corrected_Bill.this, "Charges are 0.0", Toast.LENGTH_LONG).show();
}
else
//----------------------------------------------------------------------//
Toast.makeText(Ds_Corrected_Bill.this, "Charges are"+watercharge, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(Ds_Corrected_Bill.this, "Write to database failed try again", Toast.LENGTH_LONG).show();
}
}
}
//displaying calculated values in textViews
updateTextview();
}
else{
Toast.makeText(getApplicationContext(), "Invalid category", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getApplicationContext(), "Enter appropriate values", Toast.LENGTH_SHORT).show();
}
}
});
print.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
faultValidation();
if(hasText){
//updating sundry and arrears in billedCons for cons_in table
billedCons.set(32, sunCharges.getText().toString().trim());
billedCons.set(33, arrs.getText().toString().trim());
ArrayList<String> consOutDetails=new ArrayList<String>();
consOutDetails=consOutList;
int bldUnitsVal=Integer.parseInt(unitsBld.getText().toString().trim());
int wCh=Integer.parseInt(wtrCharges.getText().toString().trim());
consOutDetails.set(4, mtrRent.getText().toString().trim());//4
consOutDetails.set(7,curRdg.getText().toString().trim());//7
if(bldUnitsVal==0){
Toast.makeText(getApplicationContext(), "Units Billed cannot be 0", Toast.LENGTH_SHORT).show();
}
else{
consOutDetails.set(8,Integer.toString(bldUnitsVal));//8
}
consOutDetails.set(11,"C");//11
if(wCh==0){
Toast.makeText(getApplicationContext(), "Water charges cannot be 0", Toast.LENGTH_SHORT).show();
}
else{
consOutDetails.set(15,Integer.toString(wCh));//15
}
consOutDetails.set(16, swgCharges.getText().toString());//16
consOutDetails.set(17, total.getText().toString());//17
consOutDetails.set(21, creds.getText().toString());//21
boolean wtConsOut = getread.write_to_cons_out(consOutDetails);
if(wtConsOut)
{
boolean wtConsIn = getread.write_to_cons_in(billedCons);
if(!wtConsIn)
{
Toast.makeText(getApplicationContext(),"Error while updating consIn" , Toast.LENGTH_SHORT).show();
}
else
{
Printdata=getread.print_duplicate(billedCons.get(56));
Printdata.set(41, "CORRECTED BILL");
pf.setCorrFlag(true);
wf = pf.print_file_write(Printdata);
switchscreen();
}
}
else
{
Toast.makeText(getApplicationContext(),"Error while updating consOut" , Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),"Enter appropriate values" , Toast.LENGTH_SHORT).show();
}
}
});
}
private TextWatcher inputValuesListener=new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
try {
inputValues();
} catch (ParseException e) {
e.printStackTrace();
}
}
};
private TextWatcher textWatcher=new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
textChanged=true;
calc.setEnabled(true);
}
};
//validation to not accept null values in edit text.
public static boolean hasValidText(ArrayList<EditText> editList2){
for(EditText view:editList){
String etVal=view.getText().toString();
view.setError(null);
if(etVal.length()==0 || etVal.isEmpty()) {
view.setError("value cannot be empty");
return false;
}
}
return true;
}
public void addEditList(){
editList.add(cumUnits);
editList.add(avgUnits);
editList.add(minUnits);
editList.add(prevRdg);
editList.add(curRdg);
editList.add(cat);
editList.add(arrs);
editList.add(mtrRent);
editList.add(unitsBld);
editList.add(wtrCharges);
editList.add(swgCharges);
editList.add(sunCharges);
}
public void faultValidation(){
editList.clear();
addEditList();
if(!(faultVal.equals("--")) && !(posVal==0)){
editList.remove(4);
hasText=hasValidText(editList);
}
else {
hasText = hasValidText(editList);
}
}
//checking focus on edit texts to enable "calculate" button.
private OnFocusChangeListener focusListener = new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
{
calc.setEnabled(true);
}
else
{
calc.setEnabled(false);
}
}
};
//Real time calculation of total amount
public void inputValues() throws ParseException{
wtrRate=wtrCharges.getText().toString();
swgRate=swgCharges.getText().toString();
mtrRate=mtrRent.getText().toString();
sunRate=sunCharges.getText().toString();
arrsRate=arrs.getText().toString();
if(wtrRate.length()>0){
wtrChargesVal=Integer.parseInt(wtrRate);
}
if(swgRate.length()>0){
swgChargesVal=Integer.parseInt(swgRate);
}
if(mtrRent.length()>0){
mtrRentVal=Integer.parseInt(mtrRate);
}
if(sunRate.length()>0){
sunVal=Integer.parseInt(sunRate);
}
if(arrsRate.length()>0 && !(arrsRate.equals("-"))){
arrsVal=Integer.parseInt(arrsRate);
creds.setText("0");
}
else if(arrsRate.length()>0 && arrsRate.equals("-")){
arrsVal=NumberFormat.getInstance().parse(arrsRate).intValue();
int totalVal=wtrChargesVal+swgChargesVal+mtrRentVal+sunVal-arrsVal;
if(totalVal<0) {
total.setText("0");
creds.setText(Integer.toString(totalVal));
}
else {
total.setText(Integer.toString(totalVal));
}
}
int totalAmt=calcTotal();
if(totalAmt<0) {
total.setText("0");
creds.setText(Integer.toString(totalAmt));
}
else{
total.setText(Integer.toString(totalAmt));
}
}
public int calcTotal(){
int totalValue=wtrChargesVal+swgChargesVal+mtrRentVal+sunVal+arrsVal;
return totalValue;
}
public void Load_Spinner_Data() {
sqldataclass spindata = new sqldataclass(Ds_Corrected_Bill.this);
List<String> labels;
try {
labels = spindata.getspinnerdata();
for(int i=1;i<=labels.size();i++)
{
faultsList.add(labels.get(i));
i++;
}
for(int i=0;i<labels.size();i++)
{
faultsdescp.add(labels.get(i));
i++;
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_item, faultsdescp);
dataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
fault.setAdapter(dataAdapter);
} catch (SQLDataException e) {
System.out.print("Sql error");
} catch (SQLException e) {
System.out.print("sql error");
} catch (Exception e) {
System.out.println("I am an excpetion");
e.printStackTrace();
}
}
public void continueWrite2Db() {
Float watercharge =cal.write_to_textfile() ;
boolean b= cal.write_to_db();
if(b) //if db write succesfull
{
//----------------------Added on 16-2-15--------------------------------//
if(watercharge<0)
{
Toast.makeText(Ds_Corrected_Bill.this, "Charges are 0.0", Toast.LENGTH_LONG).show();
}
else
//----------------------------------------------------------------------//
Toast.makeText(Ds_Corrected_Bill.this, "Charges are"+watercharge, Toast.LENGTH_LONG).show();
// switchscreen();
}
else
{
Toast.makeText(Ds_Corrected_Bill.this, "Write to database failed try again", Toast.LENGTH_LONG).show();
}
Toast.makeText(Ds_Corrected_Bill.this, watercharge.toString(),Toast.LENGTH_LONG).show();
}
public void switchscreen()
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(BTConnected)
{
System.out.println("The bluetooth activity flag is true");
Intent intent = new Intent(getApplicationContext(),BTPrinterDemo.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT|Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("consid", consId); //Added on 6-3-15
intent.putExtra("corrFlag", true);
startActivityForResult(intent, 100);
}
else
{
System.out.println("The bluetooth activity flag is false");
BTConnected=true;
Intent intent_name = new Intent();
intent_name.setClass(getApplicationContext(),BTPrinterDemo.class);
intent_name.putExtra("consid", consId); //Added on 6-3-15
intent_name.putExtra("corrFlag", true);
startActivityForResult(intent_name, 100);
}
}
},2500);
}
public void updateTextview()
{
consOutList=getread.getConsOutRecord(billedCons.get(39));
unitsBld.setText(consOutList.get(8));
addlUnits.setText(consOutList.get(9));
//cumUnits.setText(consOutList.get(6));
wtrCharges.setText(consOutList.get(15));
swgCharges.setText(consOutList.get(16));
mtrRent.setText(consOutList.get(4));
creds.setText(consOutList.get(21));
total.setText(consOutList.get(17));
}
private class dailySync extends AsyncTask<Void, Void, Void> // read file
{
ProgressDialog progressDialog;
boolean b;
@Override
protected Void doInBackground(Void... arg0)
{
// TODO Auto-generated method stub
dsy = false;
syncData = dq.getDailySyn();
if(syncData!=null)
{
try
{
syncData.moveToFirst();
dsCount = syncData.getCount();
JSONArray arr = new JSONArray(); //Added on 4-5-15
//-------------------Added on 16-6-15--------------//
String mrname = dc.fetch_meter_reader_name().toString();
//------------------------------------------------//
for(int i=0;i<dsCount;i++) //Added on 4-5-15
//while(syncData.moveToNext())
{
jsnobj = new JSONObject();
//-------------------------------------Cons_In data-----------------------------//
jsnobj.put("billnum", syncData.getString(syncData.getColumnIndex("Bill_Num")));
jsnobj.put("consid", syncData.getString(syncData.getColumnIndex("Cons_Id")));
jsnobj.put("division", syncData.getString(syncData.getColumnIndex("Division")));
jsnobj.put("subdivision", syncData.getString(syncData.getColumnIndex("Sub_Division")));
jsnobj.put("conscode", syncData.getString(syncData.getColumnIndex("Cons_Code")));
jsnobj.put("noofusers", syncData.getString(syncData.getColumnIndex("No_Of_Users")));
jsnobj.put("name", syncData.getString(syncData.getColumnIndex("Name")));
jsnobj.put("add1", syncData.getString(syncData.getColumnIndex("Add1")));
jsnobj.put("add2", syncData.getString(syncData.getColumnIndex("Add2")));
jsnobj.put("add3", syncData.getString(syncData.getColumnIndex("Add3")));
jsnobj.put("fromdate", syncData.getString(syncData.getColumnIndex("From_Date")));
jsnobj.put("meternum", syncData.getString(syncData.getColumnIndex("Meter_Num")));
jsnobj.put("meterfixdate", syncData.getString(syncData.getColumnIndex("Meter_Fix_Date")));
jsnobj.put("catcode", syncData.getString(syncData.getColumnIndex("Cat_Code")));
jsnobj.put("metersize", syncData.getString(syncData.getColumnIndex("Meter_size")));
jsnobj.put("meterrent", syncData.getString(syncData.getColumnIndex("Meter_Rent")));
jsnobj.put("minunits", syncData.getString(syncData.getColumnIndex("Minimum_Units")));
jsnobj.put("avgunits", syncData.getString(syncData.getColumnIndex("Average_Units1")));
jsnobj.put("connstatus", syncData.getString(syncData.getColumnIndex("Connection_Status")));
jsnobj.put("connstatusdt", syncData.getString(syncData.getColumnIndex("Conn_Status_Date")));
//jsnobj.put("", syncData.getString(syncData.getColumnIndex("Meter_Rent")));
jsnobj.put("secdep", syncData.getString(syncData.getColumnIndex("Security_Deposit")));
jsnobj.put("cumm", syncData.getString(syncData.getColumnIndex("Cumulative_Units")));
jsnobj.put("prevread", syncData.getString(syncData.getColumnIndex("Previous_Reading")));
jsnobj.put("prevcycun", syncData.getString(syncData.getColumnIndex("Prev_Cycl_Units")));
jsnobj.put("prevcycdys", syncData.getString(syncData.getColumnIndex("Prev_Cycl_Days")));
jsnobj.put("fault", syncData.getString(syncData.getColumnIndex("Fault")));
jsnobj.put("faultdate", syncData.getString(syncData.getColumnIndex("Fault_Date")));
jsnobj.put("readrptcnt", syncData.getString(syncData.getColumnIndex("Reading_Rpt_Count")));
jsnobj.put("sundry", syncData.getString(syncData.getColumnIndex("Sundry_Charges")));
jsnobj.put("arrear", syncData.getString(syncData.getColumnIndex("Arrear_Credit")));
jsnobj.put("sewage", syncData.getString(syncData.getColumnIndex("Sewage_bit")));
jsnobj.put("compflag", syncData.getString(syncData.getColumnIndex("comp_flag")));
jsnobj.put("barcode", syncData.getString(syncData.getColumnIndex("barcode")));
jsnobj.put("code1", syncData.getString(syncData.getColumnIndex("code_split1")));
jsnobj.put("code2", syncData.getString(syncData.getColumnIndex("code_split2_zone")));
jsnobj.put("code3", syncData.getString(syncData.getColumnIndex("code_split3_cons_code")));
//------------------------------------------------------------------------------------------//
//------------------------------------Cons_out data--------------------------------------//
// jsnobj.put("consid", syncData.getString(syncData.getColumnIndex("Consumer_Id")));
jsnobj.put("issuedate", syncData.getString(syncData.getColumnIndex("Issue_Date")));
jsnobj.put("cycprd", syncData.getString(syncData.getColumnIndex("Cycle_Period")));
jsnobj.put("lastpaydt", syncData.getString(syncData.getColumnIndex("Last_Payment_Dat")));
jsnobj.put("meterrent1", syncData.getString(syncData.getColumnIndex("Meter_Rent1")));
jsnobj.put("avgunits1", syncData.getString(syncData.getColumnIndex("Average_Units")));
jsnobj.put("cumm1", syncData.getString(syncData.getColumnIndex("Cumulative_Units1")));
jsnobj.put("currread", syncData.getString(syncData.getColumnIndex("Current_Reading")));
jsnobj.put("unitsbill", syncData.getString(syncData.getColumnIndex("Units_Billed")));
jsnobj.put("adduni", syncData.getString(syncData.getColumnIndex("Additional_Units")));
jsnobj.put("lpcd", syncData.getString(syncData.getColumnIndex("Lpcd")));
jsnobj.put("billbase", syncData.getString(syncData.getColumnIndex("Bill_Base")));
jsnobj.put("fault1", syncData.getString(syncData.getColumnIndex("Fault1")));
jsnobj.put("faultdate1", syncData.getString(syncData.getColumnIndex("Fault_Date1")));
jsnobj.put("readrptcnt1", syncData.getString(syncData.getColumnIndex("Reading_rpt_count1")));
jsnobj.put("waterchrg", syncData.getString(syncData.getColumnIndex("Water_Charges")));
jsnobj.put("sewagechrg", syncData.getString(syncData.getColumnIndex("Sewage_Charge")));
jsnobj.put("totbillamt", syncData.getString(syncData.getColumnIndex("Total_Bill_Amt")));
jsnobj.put("connstatout", syncData.getString(syncData.getColumnIndex("Conn_Status_Out")));
jsnobj.put("conndateout", syncData.getString(syncData.getColumnIndex("Conn_Date_out")));
jsnobj.put("billtime", syncData.getString(syncData.getColumnIndex("Bill_Time")));
jsnobj.put("carryfwd", syncData.getString(syncData.getColumnIndex("Carry_Foward")));
jsnobj.put("mrName", mrname);
//jsnobj.put("", syncData.getString(syncData.getColumnIndex("code_split3_cons_code")));
//------------------------------------------------------------------------------------------//
arr.put(jsnobj);
if(!syncData.isLast()) //Added on 4-5-15
syncData.moveToNext(); //Added on 4-5-15
}
//------------------------Commented on 29-4-15 --------------------//
jsnobj = new JSONObject();
jsnobj.put("data", arr);
String st = jsnobj.toString();
//--------------------------------------------------------------//
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(dailySyncUrl); //Added on 18-4-15
/*Commented on 2-7-15
httppost.setHeader("json", jsnobj.toString()); //Added on 27-4-15
httppost.getParams().setParameter("jsonpost",arr);// Added on 27-4-15
*/
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("jsdata",st));
//nameValuePairs.add(new BasicNameValuePair("consid","1234"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("SENCIDE", "Execute HTTP Post Request to update File Uploaded Time");
// httpclient.execute(httppost);
HttpResponse httpresponse = httpclient.execute(httppost);
String str = inputStreamToString(httpresponse.getEntity().getContent()).toString();
// Toast.makeText(getApplicationContext(), "json is" +str, Toast.LENGTH_LONG).show();
if(str.equals("Done"))
dsy = true;
else
dsy = false;
}
catch (Exception e) {
e.printStackTrace();
dsy=false;
}
}
if(dsy)
{
syncData.moveToFirst();
ArrayList<String> considlst = new ArrayList<String>();
ArrayList<String> corrConsidlst = new ArrayList<String>();
for(int i=0;i<dsCount;i++) //Added on 4-5-15
{
considlst.add(syncData.getString(syncData.getColumnIndex("Cons_Id")).trim());
if(syncData.getString(syncData.getColumnIndex("Bill_Base")).equals("C"))
corrConsidlst.add(syncData.getString(syncData.getColumnIndex("Cons_Id")).trim());
if(!syncData.isAfterLast())
syncData.moveToNext();
}
dq.setSyncFlag(considlst); //commenetd on 12-5-15
dq.clearCorrRows(corrConsidlst); //addeed on 23-12-15
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
progressDialog.dismiss();
if(dsy)
{
Toast.makeText(Ds_Corrected_Bill.this, "Sync Successful", Toast.LENGTH_SHORT).show();
}
//--------------Added on 14-5-15----------------//
else if(syncData==null)
{
Toast.makeText(Ds_Corrected_Bill.this, "No Data To Sync", Toast.LENGTH_SHORT).show();
}
//---------------------------------------------//
else
{
Toast.makeText(Ds_Corrected_Bill.this, "Syncing Failed. Please Check Network And Try Again", Toast.LENGTH_LONG).show();
}
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(Ds_Corrected_Bill.this, "", "Please Wait Syncing Data",true);
super.onPreExecute();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
String corrSyncStatus = data.getStringExtra("corrSync");
if(corrSyncStatus.equals("true"))
new dailySync().execute();
}
}
/* if(data.getExtras().containsKey("corrSync"))
{
String corrSyncStatus = data.getStringExtra("corrSync");
if(corrSyncStatus.equals("true"))
new dailySync().execute();
}
*/
}
}
|
package leecode.dfs;
/*
判断二叉树对称,两个指针,分别走左子树和右子树(这儿处理根是否有两个子树节点的情况),
走的方向相反,判断树是否完全相同,即调用相同的树的方法,只是走的方向不同
*/
public class 对称二叉树_101 {
public boolean isSymmetric(TreeNode root) {
if(root==null){
return true;
}
//注释掉这个叶子节点也可以 issame里面有相同的逻辑
if((root.left==null)&&(root.right==null)){
return true;
}
//注释掉这个也可以!! issame里面有相同的逻辑
if((root.left==null&&root.right!=null)||(root.left!=null&&root.right==null)){
return false;
}
return issame(root.left,root.right);
}
public boolean issame(TreeNode tree1,TreeNode tree2){
if(tree1==null&&tree2==null){
return true;
}
if((tree1==null&&tree2!=null)||(tree1!=null&&tree2==null)){
return false;
}
if(tree1.val==tree2.val){
return issame(tree1.left,tree2.right)&&issame(tree1.right,tree2.left);
}else {
return false;
}
}
}
|
// 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 edu.iu.dsc.tws.examples.batch.sort;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.iu.dsc.tws.common.config.Config;
import edu.iu.dsc.tws.comms.api.DataFlowOperation;
import edu.iu.dsc.tws.comms.api.MessageType;
import edu.iu.dsc.tws.comms.dfw.io.KeyedContent;
public class RecordSource implements Runnable {
private static final Logger LOG = Logger.getLogger(RecordSource.class.getName());
private DataFlowOperation operation;
private static final int MAX_CHARS = 5;
private int noOfWords;
private int noOfDestinations;
private int taskId;
private List<Integer> destinations;
private int executor;
private RecordGenerator recordGenerator;
private List<Integer> partitioning;
private Map<Integer, Integer> totalSends = new HashMap<>();
public RecordSource(Config config, DataFlowOperation operation,
List<Integer> dests, int tIndex,
int noOfRecords, int range, int totalTasks) {
this.operation = operation;
this.noOfWords = noOfRecords;
this.destinations = dests;
this.taskId = tIndex;
this.noOfDestinations = destinations.size();
this.executor = operation.getTaskPlan().getThisExecutor();
this.recordGenerator = new RecordGenerator(range);
this.partitioning = new ArrayList<>();
int perTask = range / totalTasks;
int sum = 0;
for (int i = 0; i < totalTasks; i++) {
partitioning.add(sum);
sum += perTask;
}
for (Integer d : dests) {
totalSends.put(d, 0);
}
}
@Override
public void run() {
for (int i = 0; i < noOfWords; i++) {
Record word = recordGenerator.next();
int destIndex = 0;
int val = word.getKey();
for (int j = 0; j < partitioning.size() - 1; j++) {
if (val > partitioning.get(j) && val <= partitioning.get(j + 1)) {
destIndex = j;
}
}
int dest = destinations.get(destIndex);
int flags = 0;
// if (i >= (noOfWords - noOfDestinations)) {
// flags = MessageFlags.FLAGS_LAST;
// }
int total = totalSends.get(dest);
total += 1;
totalSends.put(dest, total);
// LOG.log(Level.INFO, String.format("%d Sending message to %d %d", executor, taskId, dest));
// lets try to process if send doesn't succeed
while (!operation.send(taskId, new KeyedContent(word.getKey(), word.getData(),
MessageType.INTEGER, MessageType.BYTE), flags, dest)) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
LOG.log(Level.INFO, String.format("%d total sends %s", executor, totalSends));
operation.finish(taskId);
}
}
|
package accessories.winds;
import accessories.Accessory;
public class Bow extends Accessory {
private String material;
public Bow(String partName, String brand, String partFor, String type, double buyingPrice, double sellingPrice, String material) {
super(partName, brand, partFor, type, buyingPrice, sellingPrice);
this.material = material;
}
public String getMaterial() {
return this.material;
}
}
|
package com.app.main.dto;
import java.io.Serializable;
import javax.persistence.CascadeType;
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.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
@Entity
public class Artist implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
private String artistEmailID;
private String artistName;
private long artistPhoneNumber;
private String artistGenre;
// private String artistAvailDays;
// private float artistfees;
private String artistCertification;
private String artistExperience;
private String artistAddress;
private String artistPassword;
private String artistDob;
private String prefWorkHours;
private String artistPicture;
public Artist(String artistEmailID, String artistName, long artistPhoneNumber, String artistGenre,
String artistAvailDays, float artistfees, String artistCertification, String artistExperience,
String artistAddress, String artistPassword, String artistDob, String prefWorkHours, String artistPicture) {
super();
this.artistEmailID = artistEmailID;
this.artistName = artistName;
this.artistPhoneNumber = artistPhoneNumber;
this.artistGenre = artistGenre;
this.artistCertification = artistCertification;
this.artistExperience = artistExperience;
this.artistAddress = artistAddress;
this.artistPassword = artistPassword;
this.artistDob = artistDob;
this.prefWorkHours = prefWorkHours;
this.artistPicture = artistPicture;
}
public Artist() {
super();
}
/*
* @OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,mappedBy
* ="artistEmail") private Order1 order;
*/
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getArtistEmailID() {
return artistEmailID;
}
public void setArtistEmailID(String artistEmailID) {
this.artistEmailID = artistEmailID;
}
public long getArtistPhoneNumber() {
return artistPhoneNumber;
}
public void setArtistPhoneNumber(long artistPhoneNumber) {
this.artistPhoneNumber = artistPhoneNumber;
}
public String getArtistGenre() {
return artistGenre;
}
public void setArtistGenre(String artistGenre) {
this.artistGenre = artistGenre;
}
public String getArtistCertification() {
return artistCertification;
}
public void setArtistCertification(String artistCertification) {
this.artistCertification = artistCertification;
}
public String getArtistExperience() {
return artistExperience;
}
public void setArtistExperience(String artistExperience) {
this.artistExperience = artistExperience;
}
public String getArtistAddress() {
return artistAddress;
}
public void setArtistAddress(String artistAddress) {
this.artistAddress = artistAddress;
}
public String getArtistDob() {
return artistDob;
}
public void setArtistDob(String artistDob) {
this.artistDob = artistDob;
}
public String getPrefWorkHours() {
return prefWorkHours;
}
public void setPrefWorkHours(String prefWorkHours) {
this.prefWorkHours = prefWorkHours;
}
public String getArtistPassword() {
return artistPassword;
}
public void setArtistPassword(String artistPassword) {
this.artistPassword = artistPassword;
}
public String getArtistName() {
return artistName;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getArtistPicture() {
return artistPicture;
}
public void setArtistPicture(String artistPicture) {
this.artistPicture = artistPicture;
}
@Override
public String toString() {
return "Artist [artistEmailID=" + artistEmailID + ", artistName=" + artistName + ", artistPhoneNumber="
+ artistPhoneNumber + ", artistGenre=" + artistGenre +
" artistCertification=" + artistCertification + ", artistExperience="
+ artistExperience + ", artistAddress=" + artistAddress + ", artistPassword=" + artistPassword
+ ", artistDob=" + artistDob + ", prefWorkHours=" + prefWorkHours + ", artistPicture=" + artistPicture
+ "]";
}
}
|
package com.hit.neuruimall.service.impl;
import com.hit.neuruimall.service.IImgService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Service
public class ImgServiceImpl implements IImgService {
@Value("${imgPath}")
private String imgPath;
@Override
public List<String> getImgUrl() {
List<String> imgNames = new ArrayList<>();
File file = new File(imgPath);
File[] itemFile = file.listFiles();
for (File file1 : itemFile) {
imgNames.add("http://localhost:8888/" +file1.getName());
}
return imgNames;
}
@Override
public void uploadImg(MultipartFile multipartFile) throws IOException {
File dist = new File(imgPath + multipartFile.getOriginalFilename());
multipartFile.transferTo(dist);
}
}
|
package com.test.webmagic.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class Result {
private String url;
private String table;
}
|
public class Message {
private String id;
private String name;
private String role;
private String salary;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString(){
return "\nID="+getId()+"::::Name"+getName();
}
}
|
package com.sda.javagdy5.hiddennumbers;
import java.util.Arrays;
public class HiddenNumbers {
public int calculate(String text) {
String[] split = text.split("[^-?0-9]+|-[^0-9]|-$");
//String[] split = text.split("-?[0-9]");
return Arrays.stream(split)
.filter(s -> !s.isEmpty())
.mapToInt(Integer::parseInt)
.sum();
}
}
|
package com.epam.talentland.balance.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.epam.talentland.balance.entity.BalanceEntity;
import com.epam.talentland.balance.exceptions.UserException;
import com.epam.talentland.balance.repository.BalanceRepository;
import com.epam.talentland.balance.util.Util;
@Service
public class BalanceService {
@Autowired
private BalanceRepository balanceRepository;
public List<BalanceEntity> getLastThreeMonths(String id) throws UserException{
String dateNow = Util.getNowDateYYYmmDDMonthaddSub(1);
String dateNowMinus3Months = Util.getNowDateYYYmmDDMonthaddSub(-3);
List<BalanceEntity> balanceInThreeMonths = balanceRepository.getLastThreeMonths(id,dateNowMinus3Months,dateNow);
if(null == balanceInThreeMonths || balanceInThreeMonths.isEmpty()) {
throw new UserException("id-" + id);
}
return balanceInThreeMonths;
}
}
|
package com.tencent.mm.plugin.webview.ui.tools.jsapi;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.webview.model.r;
class g$15 implements OnCancelListener {
final /* synthetic */ g qiK;
final /* synthetic */ r qiZ;
g$15(g gVar, r rVar) {
this.qiK = gVar;
this.qiZ = rVar;
}
public final void onCancel(DialogInterface dialogInterface) {
au.DF().c(this.qiZ);
}
}
|
package fr.cg95.cvq.service.request.school;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.service.request.IRequestService;
import fr.cg95.cvq.service.request.annotation.IsRequest;
/**
* @author Jean-Sébastien Bour (jsb@zenexity.fr)
*/
public interface IStudyGrantRequestService extends IRequestService {
/**
* Set the Edemande ID of this request
*/
void setEdemandeId(@IsRequest final Long requestId, final String edemandeId)
throws CvqException;
/**
* Set the Edemande ID of the account holder of this request
*/
void setAccountHolderEdemandeId(@IsRequest final Long requestId, final String accountHolderEdemandeId)
throws CvqException;
}
|
/*******************************************************************************
* Besiege
* by Kyle Dhillon
* Source Code available under a read-only license. Do not copy, modify, or distribute.
******************************************************************************/
package kyle.game.besiege.panels;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import kyle.game.besiege.Assets;
import kyle.game.besiege.Crest;
import kyle.game.besiege.CrestDraw;
import kyle.game.besiege.army.Army;
import kyle.game.besiege.location.Location;
import kyle.game.besiege.location.Village;
import kyle.game.besiege.party.Party;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;
public class PanelLocation extends Panel {
private final float MINI_PAD = 5;
private final float DESC_HEIGHT = 300;
private SidePanel sidePanel;
public Location location;
private TopTable topTable;
private LabelStyle ls;
private LabelStyle lsMed;
private LabelStyle lsG;
private boolean playerIn;
private PanelHire panelHire;
private boolean playerTouched;
private boolean playerWaiting;
private boolean playerBesieging;
SoldierTable garrisonSoldierTable;
private HashMap<Party, SoldierTable> garrisonedTables = new HashMap<Party, SoldierTable>();
public PanelLocation(SidePanel panel, Location location) {
this.sidePanel = panel;
this.location = location;
this.addParentPanel(panel);
this.playerTouched = false;
LabelStyle lsBig = new LabelStyle();
lsBig.font = Assets.pixel22;
lsMed = new LabelStyle();
lsMed.font = Assets.pixel18;
ls = new LabelStyle();
ls.font = Assets.pixel16;
lsG = new LabelStyle();
lsG.font = Assets.pixel16;
lsG.fontColor = Color.GRAY;
topTable = new TopTable();
topTable.updateTitle(location.getName(), new InputListener() {
public boolean touchDown(InputEvent event, float x,
float y, int pointer, int button) {
return true;
}
public void touchUp(InputEvent event, float x, float y,
int pointer, int button) {
centerCamera();
}
});
topTable.addSubtitle("locationtype", location.getTypeStr(), null);
topTable.addSubtitle("factionname", location.getFactionName(), new InputListener() {
public boolean touchDown(InputEvent event, float x,
float y, int pointer, int button) {
return true;
}
public void touchUp(InputEvent event, float x, float y,
int pointer, int button) {
setActiveFaction();
}
});
topTable.addBigLabel("Garrison", "Garrison:");
topTable.addSmallLabel("Pop", "Pop:");
topTable.addSmallLabel("Wealth", "Wealth:");
topTable.row();
//stats.debug();
topTable.padLeft(MINI_PAD);
this.addTopTable(topTable);
garrisonSoldierTable = new SoldierTable(this, location.getParty());
addSoldierTable(garrisonSoldierTable);
updateSoldierTables();
playerIn = false;
// this.hireMode = false;
location.needsUpdate = true;
System.out.println("just created new panellocation");
this.setButton(4, "Back");
}
@Override
public void act(float delta) {
// hostile player touches
if (location.hostilePlayerTouched && !playerTouched && !location.isRuin()) {
if (location.underSiege()) {
if (location.isVillage())
setButton(1, "Continue Raid");
else setButton(1, "Resume Siege");
} else if (!location.underSiege()) {
if (location.isVillage()) {
if (!((Village) location).raided())
setButton(1, "Raid");
}
else setButton(1, "Besiege");
}
setButton(2, "Withdraw");
setButton(3, null);
setButton(4, null);
playerTouched = true;
}
// hostile player leaves
else if (!location.hostilePlayerTouched && playerTouched && !location.playerBesieging) {
setButton(1, null);
setButton(2, null);
setButton(3, null);
setButton(4, "Back");
sidePanel.setHardStay(false);
sidePanel.setDefault();
// Player just left, reset the buttons
playerTouched = false;
} else if (location.playerBesieging && !playerBesieging) {
// turn on siegeOrRaid panel
setButton(1, "Charge!");
setButton(2, "Wait");
setButton(3, null);
setButton(4, "Withdraw");
playerBesieging = true;
// System.out.println("siegeOrRaid panel on");
} else if (!location.playerBesieging && playerBesieging) {
// turn off siegeOrRaid panel
setButton(1, null);
setButton(2, null);
setButton(3, null);
setButton(4, "Back");
playerBesieging = false;
// System.out.println("siegeOrRaid panel off");
}
// friendly player touches
else if (location.playerIn && !playerIn) {
setButton(1, "Rest");
if (location.toHire != null ) // && location.toHire.getHealthySize() > 0
setButton(2, "Hire");
playerIn = true;
if (this.panelHire == null && !this.location.isRuin())
this.panelHire = new PanelHire(sidePanel, location);
if (location.getKingdom().getPlayer().getPanelCaptives() != null) {
// this.panelHire = new PanelHire(panel, location);
setButton(3, "Captives");
}
}
// friendly player leaves
else if (!location.playerIn && playerIn) {
System.out.println("friendly player leavin, setting buttons to null");
setButton(1, null);
setButton(2, null);
setButton(3, null);
playerIn = false;
}
// if hostile player is waiting at a siegeOrRaid
else if (location.playerBesieging && playerBesieging) {
// start wait
if (location.playerWaiting && playerWaiting) {
setButton(1, null);
setButton(2, null);
setButton(3, null);
setButton(4, "Stop");
playerWaiting = false;
// System.out.println("setting to null");
}
// stop wait
else if (!location.playerWaiting && !playerWaiting) {
setButton(1, "Charge!");
setButton(2, "Wait");
setButton(3, null);
setButton(4, "Withdraw");
playerWaiting = true;
// System.out.println("setting to rest");
}
}
// if friendly player is inside
else if (location.playerIn && playerIn) {
// System.out.println("player inside location");
//start Wait
if (location.playerWaiting && playerWaiting) {
setButton(1, null);
setButton(4, "Stop");
playerWaiting = false;
}
//stop Wait
else if (!location.playerWaiting && !playerWaiting) {
setButton(1, "Rest");
setButton(4, "Back");
playerWaiting = true;
}
}
// else if (location.underSiege() && location.getKingdom().getPlayer().isInSiege() && location.getKingdom().getPlayer().getSiege().location == location) {
if (!location.ruin) {
String garrStr = getParty().getHealthySize() + "";
int totalGarr = 0;
for (Army a : location.getGarrisoned()) {
// don't show passive armies in garrison
if (a.passive) continue;
// garrStr += "+" + a.getParty().getHealthySize();
totalGarr += a.getParty().getHealthySize();
}
// if (totalGarr > 0) garrStr += "+" + totalGarr;
if (totalGarr > 0)
garrStr = totalGarr + location.garrison.getHealthySize() + " (" + garrStr + "+" + totalGarr + ")";
topTable.update("Garrison", garrStr);
topTable.update("Pop", (int) location.getPop() + "");
topTable.update("Wealth", "" + location.getWealth());
} else {
String garrStr = "";
int totalGarr = 0;
for (Army a : location.getGarrisoned()) {
// garrStr += "+" + a.getParty().getHealthySize();
// don't show passive armies in garrison
if (a.passive) continue;
totalGarr += a.getParty().getHealthySize();
}
// if (totalGarr > 0) garrStr += "+" + totalGarr;
if (totalGarr > 0) garrStr = totalGarr + " (" + garrStr + "+" + totalGarr + ")";
topTable.update("Garrison", garrStr);
topTable.update("Pop", (int) location.getPop() + "");
topTable.update("Wealth", "0");
}
if (location.underSiege())
topTable.update("factionname", "Under Siege!", null);
else {
if (location.type != Location.LocationType.RUIN && location.getKingdom().getPlayer().isAtWar(location))
topTable.update("factionname", location.getFactionName() + " (at war)", null);
else topTable.update("factionname", location.getFactionName(), null);
}
// Update all parties.
if (location.needsUpdate) {
garrisonedTables.get(location.getParty()).update();
// if (Math.random() < 0.3f)
topTable.update("locationtype", location.getTypeStr(), null);
location.needsUpdate = false;
}
if (garrisonedTables.size() != location.getGarrisonedAndGarrison().size) {
System.out.println("updating soldier tables for location: " + location.getName());
updateSoldierTables();
}
Set<Party> parties = garrisonedTables.keySet();
for (Party p : parties) {
if (p == null) continue;
if (p.updated) {
garrisonedTables.get(p).update();
p.updated = false;
}
}
super.act(delta);
}
// TODO This should rn keep around sts for parties that have left the garrison.
private void updateSoldierTables() {
System.out.println("updating soldier tables");
Collection<SoldierTable> c = garrisonedTables.values();
c.remove(garrisonSoldierTable);
this.clearSoldierTables(c);
garrisonedTables.clear();
garrisonedTables.put(location.getParty(), garrisonSoldierTable);
for (Army a : location.getGarrisoned()) {
if (a.passive) continue;
SoldierTable st = new SoldierTable(this, a.getParty());
addSoldierTable(st);
// topTable.add(st).colspan(4).top().padTop(MINI_PAD).expandY();
// topTable.row();
garrisonedTables.put(a.getParty(), st);
}
}
public Party getParty() {
return this.location.getParty();
}
public void setActiveFaction() {
sidePanel.setActiveFaction(location.getFaction());
}
private void centerCamera() {
Camera camera = sidePanel.getKingdom().getMapScreen().getCamera();
// camera.translate(new Vector2(location.getCenterX()-camera.position.x, location.getCenterY()-camera.position.y));
camera.translate(new Vector3(location.getCenterX()-camera.position.x, location.getCenterY()-camera.position.y, 0));
}
@Override
public void resize() { // problem with getting scroll bar to appear...
// Set<Party> set = new HashSet<>(garrisonedTables.keySet());
// // p may be null (for ruins)
// for (Party p : set) {
// SoldierTable soldierTable = garrisonedTables.get(p);
// garrisonedTables.remove(p);
//
// Cell cell = topTable.getCell(soldierTable);
//// cell.height(sidePanel.getHeight() - DESC_HEIGHT).setWidget(null);
// soldierTable = new SoldierTable(this, p);
//// soldierTable.setHeight(sidePanel.getHeight() - DESC_HEIGHT);
// cell.setWidget(soldierTable);
// garrisonedTables.put(p, soldierTable);
// soldierTable.update();
// // may be unnecessary
//// p.updated = true;
// }
location.needsUpdate = true;
super.resize();
}
@Override
public void button1() {
if (this.getButton(1).isVisible()) {
if (playerIn) {
location.startWait();
}
else if (playerBesieging && !location.playerWaiting) {
BottomPanel.log("charge!");
// TODO temp fix
if (location.getSiege() == null) {
playerBesieging = false;
return;
}
location.getSiege().attack();
System.out.println("ATTACKING ");
}
else { // besiege/raid
sidePanel.setHardStay(false);
if (!location.underSiege()) {
if (location.isVillage()) {
sidePanel.getKingdom().getPlayer().raid((Village) location);
}
else {
BottomPanel.log("Besieging " + location.getName());
sidePanel.getKingdom().getPlayer().besiege(location);
}
}
else {
// if (location.isVillage()) {
// sidePanel.getKingdom().getPlayer().raid((Village) location);
// }
// else {
BottomPanel.log("Resuming siegeOrRaid of" + location.getName());
location.getSiege().add(sidePanel.getKingdom().getPlayer());
// }
}
}
}
}
@Override
public void button2() {
if (this.getButton(2).isVisible()) {
if (playerIn) {
sidePanel.setActive(this.panelHire);
}
else if (playerBesieging) {
BottomPanel.log("waiting");
location.startWait();
}
else {
sidePanel.setHardStay(false);
sidePanel.setDefault();
}
}
}
@Override
public void button3() {
if (this.getButton(3).isVisible()) {
if (playerIn) {
location.getKingdom().getPlayer().getPanelCaptives().updateSoldierTable();
sidePanel.setActive(location.getKingdom().getPlayer().getPanelCaptives());
} else throw new AssertionError();
}
}
@Override
public void button4() {
if (location.playerWaiting) {
location.stopWait();
sidePanel.setHardStay(true);
}
else if (playerBesieging) {
location.getKingdom().getPlayer().leaveSiege();
BottomPanel.log("Withdraw!");
}
else {
sidePanel.setDefault();
}
}
@Override
public Crest getCrest() {
if (location.isRuin()) return null;
if (location.getFaction() == null) return CrestDraw.defaultCrest;
return location.getFaction().crest;
}
}
|
package com.huawei.esdk.csdemo.enums;
public enum ContinuousPresenceMode {
CP_NONE("CP_None"),
CP_1_1("CP_1_1"),
CP_2_1("CP_2_1"),
CP_2_2("CP_2_2"),
CP_2_3("CP_2_3"),
CP_3_1("CP_3_1"),
CP_3_2("CP_3_2"),
CP_3_3("CP_3_3"),
CP_3_4("CP_3_4"),
CP_3_5("CP_3_5"),
CP_3_6("CP_3_6"),
CP_4_1("CP_4_1"),
CP_4_2("CP_4_2"),
CP_4_3("CP_4_3"),
CP_4_4("CP_4_4"),
CP_4_5("CP_4_5"),
CP_4_6("CP_4_6"),
CP_5_1("CP_5_1"),
CP_5_2("CP_5_2"),
CP_5_3("CP_5_3"),
CP_5_4("CP_5_4"),
CP_6_1("CP_6_1"),
CP_6_2("CP_6_2"),
CP_6_3("CP_6_3"),
CP_6_4("CP_6_4"),
CP_6_5("CP_6_5"),
CP_7_1("CP_7_1"),
CP_7_2("CP_7_2"),
CP_7_3("CP_7_3"),
CP_7_4("CP_7_4"),
CP_7_5("CP_7_5"),
CP_8_1("CP_8_1"),
CP_8_2("CP_8_2"),
CP_8_3("CP_8_3"),
CP_8_4("CP_8_4"),
CP_9_1("CP_9_1"),
CP_10_1("CP_10_1"),
CP_10_2("CP_10_2"),
CP_10_3("CP_10_3"),
CP_10_4("CP_10_4"),
CP_10_5("CP_10_5"),
CP_10_6("CP_10_6"),
CP_13_1("CP_13_1"),
CP_13_2("CP_13_2"),
CP_13_3("CP_13_3"),
CP_13_4("CP_13_4"),
CP_13_5("CP_13_5"),
CP_16_1("CP_16_1"),
CP_20_1("CP_20_1"),
CP_24_1("CP_24_1");
private final String value;
ContinuousPresenceMode(String v) {
value = v;
}
public String value() {
return value;
}
public static ContinuousPresenceMode fromValue(String v) {
for (ContinuousPresenceMode c: ContinuousPresenceMode.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
public static Integer getIndex(String v) {
int i = 0;
for (ContinuousPresenceMode c: ContinuousPresenceMode.values()) {
if (c.value.equals(v)) {
return i;
}
i++;
}
throw new IllegalArgumentException(v);
}
}
|
package org.zacharylavallee.object;
public class NameBuilder {
private String firstName;
private String middleName;
private String lastName;
private NamePrefix prefix;
private String suffix;
public NameBuilder() {
}
public NameBuilder withFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public NameBuilder withMiddleName(String middleName) {
this.middleName = middleName;
return this;
}
public NameBuilder withLastName(String lastName) {
this.lastName = lastName;
return this;
}
public NameBuilder withPrefix(NamePrefix prefix) {
this.prefix = prefix;
return this;
}
public NameBuilder withSuffix(String suffix) {
this.suffix = suffix;
return this;
}
public Name build() {
Name name = new Name();
name.setFirstName(firstName);
name.setMiddleName(middleName);
name.setLastName(lastName);
name.setPrefix(prefix);
name.setSuffix(suffix);
return name;
}
}
|
package com.teketik.test.mockinbean.test;
import com.teketik.test.mockinbean.test.components.MockableComponent1;
import com.teketik.test.mockinbean.test.components.MockableComponent2;
import com.teketik.test.mockinbean.test.components.TestComponent1;
import com.teketik.test.mockinbean.test.components.TestComponent2;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.AbstractTestExecutionListener;
@TestExecutionListeners(
value = { MockInBeanBaseTest.TestExecutionListener.class }
)
abstract class MockInBeanBaseTest extends BaseTest {
static class TestExecutionListener extends AbstractTestExecutionListener {
private static MockableComponent1 mockableComponent1firstTest;
private static MockableComponent2 mockableComponent2firstTest;
private static boolean multiTestChecked;
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
final MockInBeanBaseTest baseTest = (MockInBeanBaseTest) testContext.getTestInstance();
if (mockableComponent1firstTest == null && mockableComponent2firstTest == null) {
mockableComponent1firstTest = baseTest.getMockableComponent1();
mockableComponent2firstTest = baseTest.getMockableComponent2();
} else {
Assertions.assertNotSame(baseTest.getMockableComponent1(), mockableComponent1firstTest);
Assertions.assertNotSame(baseTest.getMockableComponent2(), mockableComponent2firstTest);
multiTestChecked = true;
}
}
@Override
public void afterTestClass(TestContext testContext) throws Exception {
Assertions.assertTrue(multiTestChecked);
}
}
@Autowired
protected TestComponent1 testComponent1;
@Autowired
protected TestComponent2 testComponent2;
@Test
public void emptyTestForMockRecreationVerification() {
}
abstract MockableComponent1 getMockableComponent1();
abstract MockableComponent2 getMockableComponent2();
}
|
/**
* Spring Data JPA repositories.
*/
package back.repository;
|
/**
* Print out total number of babies born, as well as for each gender, in a given CSV file of baby name data.
*
* @author Duke Software Team
*/
import edu.duke.*;
import org.apache.commons.csv.*;
import java.io.*;
public class BabyBirths {
int COL_NAME = 0;
int COL_GENDER = 1;
int COL_NUM_BORN = 2;
String PATH_NAMES_BY_YEAR = "C:/Users/Mathurshan/Desktop/School Assignments/Coursera/Java/Solving Problems with Software/week 4 - baby names project/us_babynames_by_year/";
public void printInfo() {
FileResource fr = new FileResource();
for (CSVRecord rec : fr.getCSVParser(false)) {
int num_born = Integer.parseInt(rec.get(COL_NUM_BORN));
if (num_born <= 100) {
System.out.println("Name " + rec.get(COL_NAME) +
" Gender " + rec.get(COL_GENDER) +
" Num Born " + rec.get(COL_NUM_BORN));
}
}
}
public void totalBirths(int year) {
FileResource fr = new FileResource(PATH_NAMES_BY_YEAR + "yob" + year + ".csv");
int total_boys = 0;
int total_girls = 0;
int num_boys_names = 0;
int num_girls_names = 0;
for (CSVRecord rec : fr.getCSVParser(false)) {
int num_born = Integer.parseInt(rec.get(COL_NUM_BORN));
if (rec.get(COL_GENDER).equals("M")) {
total_boys += num_born;
num_boys_names++;
}
else {
total_girls += num_born;
num_girls_names++;
}
}
System.out.println("num females: " + total_girls + " num female names: " + num_girls_names);
System.out.println("total males: " + total_boys + " num male names: " + num_boys_names);
System.out.println("total births: " + (total_boys + total_girls) + " total names: " + (num_boys_names + num_girls_names));
}
public int getRank(int year, String name, String gender) {
FileResource fr = new FileResource(PATH_NAMES_BY_YEAR + "yob" + year + ".csv");
int rank = -1;
int cur_col = 1;
for (CSVRecord rec : fr.getCSVParser(false)) {
if (rec.get(COL_GENDER).equals(gender)) {
if (rec.get(COL_NAME).equals(name)) {
rank = cur_col;
}
cur_col++;
}
}
System.out.println("rank of " + name + ": " + rank);
return rank;
}
public String getName(int year, int rank, String gender) {
FileResource fr = new FileResource(PATH_NAMES_BY_YEAR + "yob" + year + ".csv");
int cur_col = 1;
String name = "NO NAME";
for (CSVRecord rec : fr.getCSVParser(false)) {
if (rec.get(COL_GENDER).equals(gender)) {
if (cur_col == rank) {
name = rec.get(COL_NAME);
}
cur_col++;
}
}
System.out.println("name of rank " + rank + ": " + name);
return name;
}
public void whatIsNameInYear(String name, int year, int new_year, String gender) {
int rank = getRank(year, name, gender);
String new_name = getName(new_year, rank, gender);
System.out.println(name + " in " + year + " => " + new_name + " in " + new_year);
}
public int yearOfHighestRank(String name, String gender) {
DirectoryResource dr = new DirectoryResource();
int year_of_best_rank = -1;
int cur_rank = Integer.MAX_VALUE;
int file_year = -1;
int file_rank = -1;
for (File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
file_year = Integer.parseInt(f.getName().substring(3,7));
file_rank = getRank(file_year, name, gender);
if (file_rank < cur_rank) {
year_of_best_rank = file_year;
cur_rank = file_rank;
}
}
return year_of_best_rank;
}
public float getAverageRank(String name, String gender) {
DirectoryResource dr = new DirectoryResource();
int num_files = 0;
float total_rank = 0;
int file_year = -1;
for (File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
file_year = Integer.parseInt(f.getName().substring(3,7));
total_rank += getRank(file_year, name, gender);
num_files++;
}
return (total_rank / num_files);
}
public int getTotalBirthsRankedHigher(int year, String name, String gender) {
FileResource fr = new FileResource(PATH_NAMES_BY_YEAR + "yob" + year + ".csv");
int cur_col = 1;
int total_births = 0;
int rank = getRank(year, name, gender);
for (CSVRecord rec : fr.getCSVParser(false)) {
if (rec.get(COL_GENDER).equals(gender)) {
if (cur_col < rank) {
total_births += Integer.parseInt(rec.get(COL_NUM_BORN));
}
cur_col++;
}
}
return total_births;
}
}
|
package com.tkb.elearning.service.impl;
import java.util.List;
import com.tkb.elearning.dao.JoinNoticeDao;
import com.tkb.elearning.model.JoinNotice;
import com.tkb.elearning.service.JoinNoticeService;
public class JoinNoticeServiceImpl implements JoinNoticeService{
private JoinNoticeDao joinNoticeDao;
/**
* 加入會員須知清單(分頁)
* @param pageCount
* @param pageStart
* @param joinNotice
* @return List<JoinNotice>
* **/
public List<JoinNotice> getList(int pageCount, int pageStart, JoinNotice joinNotice){
return joinNoticeDao.getList(pageCount, pageStart, joinNotice);
}
/**
* 取得加入會員須知筆數
* @param joinNotice
* @return AllAssociation
* **/
public Integer getCount(JoinNotice joinNotice){
return joinNoticeDao.getCount(joinNotice);
}
/**
* 取得單筆加入會員須知
* @param joinNotice
* @return AllAssociation
* */
public JoinNotice getData(JoinNotice joinNotice){
return joinNoticeDao.getData(joinNotice);
}
/**
* 新增加入會員須知
* @param joinNotice
* */
public void add(JoinNotice joinNotice){
joinNoticeDao.add(joinNotice);
}
/**
* 修改加入會員須知
* @param joinNotice
* */
public void update(JoinNotice joinNotice){
joinNoticeDao.update(joinNotice);
}
/**
* 刪除加入會員須知
* @param id
* */
public void delete(Integer id){
joinNoticeDao.delete(id);
}
public void setJoinNoticeDao(JoinNoticeDao joinNoticeDao){
this.joinNoticeDao = joinNoticeDao;
}
}
|
final class Station {
private char stationName;
Station() {
}
Station(final char stationName) {
this.stationName = stationName;
}
private char getStationName() {
return stationName;
}
void setStationName(final char stationName) {
this.stationName = stationName;
}
@Override
public boolean equals(final Object o) {
if (o instanceof Station) {
Station stationtoCompare = (Station) o;
return (this.stationName == stationtoCompare.getStationName());
} else {
return false;
}
}
@Override
public int hashCode() {
return ((Character) this.stationName).hashCode();
}
}
|
package eg.edu.guc.parkei.park.rides;
import java.util.ArrayList;
import eg.edu.guc.parkei.amusers.Amuser;
import eg.edu.guc.parkei.amusers.Baby;
import eg.edu.guc.parkei.exceptions.CannotBoardException;
import eg.edu.guc.parkei.exceptions.OutOfOrderException;
import eg.edu.guc.parkei.exceptions.UnsuitableAgeCategoryException;
import eg.edu.guc.parkei.utilities.Effect;
import eg.edu.guc.parkei.utilities.Ticket;
public class WaterRide extends FunRide {
public WaterRide() {
super();
}
public WaterRide(String name, int duration, int batchSize) {
super(name, duration, batchSize);
}
public boolean eligibleToRide(Amuser amuser) throws CannotBoardException,
OutOfOrderException {
if (this.inMaintenance()) {
throw new OutOfOrderException("Sorry");
}
if (amuser instanceof Baby) {
throw new UnsuitableAgeCategoryException(" Sorry ");
} else {
return true;
}
}
public ArrayList<Effect> affects(Amuser amuser) {
ArrayList<Effect> affects = new ArrayList<Effect>();
if (amuser.getTicket() == Ticket.Mini) {
if (amuser.getAge() > 4 && amuser.getAge() < 14) {
affects.add(Effect.Wet);
affects.add(Effect.Thrilled);
} else {
affects.add(Effect.Wet);
affects.add(Effect.Angry);
}
}
if (amuser.getTicket() == Ticket.Maxi) {
affects.add(Effect.Wet);
affects.add(Effect.Happy);
}
return affects;
}
}
|
package de.jmda.gen.java.impl;
import javax.validation.constraints.NotNull;
import de.jmda.gen.java.DeclaredFieldGenerator;
import de.jmda.gen.java.DeclaredInstanceFieldGenerator;
import de.jmda.gen.java.InstanceFieldGenerator;
public class DefaultInstanceFieldGenerator
extends AbstractFieldGenerator
implements InstanceFieldGenerator
{
private DeclaredInstanceFieldGenerator generator;
public DefaultInstanceFieldGenerator()
{
this(null);
}
public DefaultInstanceFieldGenerator(DeclaredInstanceFieldGenerator generator)
{
super(notNull(generator));
setDeclaredFieldGenerator(getDeclaredFieldGenerator());
}
@Override
public DeclaredFieldGenerator getDeclaredFieldGenerator()
{
return generator;
}
/**
* @param generator
* @throws IllegalArgumentException if <code>generator</code> is not an
* instance of {@link DeclaredInstanceFieldGenerator}
*/
@Override
public void setDeclaredFieldGenerator(DeclaredFieldGenerator generator)
{
if (generator instanceof DeclaredInstanceFieldGenerator)
{
this.generator = (DeclaredInstanceFieldGenerator) generator;
}
else
{
throw new IllegalArgumentException(
"generator has to be an instance of " +
DeclaredInstanceFieldGenerator.class.getName());
}
super.setDeclaredFieldGenerator(this.generator);
}
@Override
public DeclaredInstanceFieldGenerator getDeclaredInstanceFieldGenerator()
{
return generator;
}
@Override
public void setDeclaredInstanceFieldGenerator(
DeclaredInstanceFieldGenerator generator)
{
setDeclaredFieldGenerator(generator);
}
@NotNull
private static DeclaredFieldGenerator notNull(
DeclaredInstanceFieldGenerator generator)
{
if (generator == null)
{
generator = new DefaultDeclaredInstanceFieldGenerator();
}
return generator;
}
}
|
/*
* 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 network;
/**
*
* @author gauthier
*/
public enum ServerRequest {
INIT_HOME,
IDENTIFICATION_OK,
IDENTIFICATION_FAILED,
ALL_GROUP_RESPONSE,
MAJ_MESSAGES,
NEW_USER_RESPONSE,
ALL_GROUP_FOR_TICKET_RESPONSE,
}
|
package sevenkyu.money;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class MoneyTest {
Money money;
@BeforeEach
void init() {
money = new Money();
}
@Test
void givenPrincipalIsSmallerThanDesired_calculateYears_shouldReturnWithZero() {
// given
int principal = 1000;
double interest = 0.10;
double tax = 0;
int desired = 1000;
int expectedYears = 0;
// when
int output = money.calculateYears(principal, interest, tax, desired);
// then
assertThat(output).isEqualTo(expectedYears);
}
@Test
void givenNoTax_calculateYears_shouldReturnWithNeededYears() {
// given
int principal = 1000;
double interest = 0.10;
double tax = 0;
int desired = 1100;
int expectedYears = 1;
// when
int output = money.calculateYears(principal, interest, tax, desired);
// then
assertThat(output).isEqualTo(expectedYears);
}
@Test
void givenNoTax_calculateYears_shouldReturnWithNeededYearsRoundedUp() {
// given
int principal = 1000;
double interest = 0.10;
double tax = 0;
int desired = 1180;
int expectedYears = 2;
// when
int output = money.calculateYears(principal, interest, tax, desired);
// then
assertThat(output).isEqualTo(expectedYears);
}
@Test
void givenTaxExists_calculateYears_shouldTaxAcquiredMoneyPerYear() {
// given
int principal = 1000;
double interest = 0.05;
double tax = 0.18;
int desired = 1100;
int expectedYears = 3;
// when
int output = money.calculateYears(principal, interest, tax, desired);
// then
assertThat(output).isEqualTo(expectedYears);
}
@Test
void givenTaxExists_calculateYears_shouldTaxAcquiredMoneyOnly() {
// given
int principal = 1000;
double interest = 0.01625;
double tax = 0.18;
int desired = 1200;
int expectedYears = 14;
// when
int output = money.calculateYears(principal, interest, tax, desired);
// then
assertThat(output).isEqualTo(expectedYears);
}
}
|
package com.other.updown.utils;
import com.fasterxml.jackson.core.JsonGenerationException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.springframework.cglib.beans.BeanMap;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* 对象操作工具类
*
* @author huangyujie
* @since 2019/4/23 10:32
*/
public class ObjectUtil {
/**
* 将对象装换为map
*
* @param bean
* @return
*/
public static <T> Map<String, Object> beanToMap(T bean) {
Map<String, Object> map = new HashMap<String, Object>();
if (bean != null) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
map.put(key + "", beanMap.get(key));
}
}
return map;
}
/**
* 将map装换为javabean对象
*
* @param map
* @param bean
* @return
*/
public static <T> T mapToBean(Map<String, Object> map, T bean) {
BeanMap beanMap = BeanMap.create(bean);
beanMap.putAll(map);
return bean;
}
/**
* 方法说明:map转化为对象
*
* @param map
* @param t
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static <T> T mapToObject(Map<String, Object> map, Class<T> t) throws InstantiationException, IllegalAccessException, InvocationTargetException {
T instance = t.newInstance();
//注册日期格式化器 start
DateConverter converter = new DateConverter();
converter.setPattern("yyyy-MM-dd HH:mm");
ConvertUtils.register(converter, Date.class);
//注册日期格式化器 end
BeanUtils.populate(instance, map);
return instance;
}
/**
* 将List<T>转换为List<Map<String, Object>>
*
* @param objList
* @return
* @throws JsonGenerationException
* @throws IOException
*/
public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
if (objList != null && objList.size() > 0) {
Map<String, Object> map = null;
T bean = null;
for (int i = 0, size = objList.size(); i < size; i++) {
bean = objList.get(i);
map = beanToMap(bean);
list.add(map);
}
}
return list;
}
/**
* 将List<Map<String,Object>>转换为List<T>
*
* @param maps
* @param clazz
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps,
Class<T> clazz) throws InstantiationException,
IllegalAccessException, InvocationTargetException {
List<T> list = new ArrayList<T>();
if (maps != null && maps.size() > 0) {
Map<String, Object> map = null;
T bean = null;
for (int i = 0, size = maps.size(); i < size; i++) {
map = maps.get(i);
bean = mapToObject(map,clazz);
list.add(bean);
}
}
return list;
}
}
|
package lesson12;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Exercises3 {
public static void main(String[] args) {
var startDay = getDay();
var endDay = getDay();
var result = count(startDay, endDay);
System.out.println("Chênh lệch giữa " + startDay + " và " + endDay + " là: " + result + " ngày");
}
/**
* phương thức tính số ngày cách nhau của ngày đầu và ngày cuối
* @param startDay ngày đầu
* @param endDay ngày cuối
* @return trả về số ngày cần tính
*/
private static long count(String startDay, String endDay) {
var format = "dd/MM/yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
try {
var date1 = dateFormat.parse(startDay); //định dạng ngày đầu
var date2 = dateFormat.parse(endDay); //định dạng ngày cuối
var time1 = date1.getTime(); //thời gian ngày đầu (tính bằng ms)
var time2 = date2.getTime(); //thời gian ngày cuối (tính bằng ms)
var res = Math.abs(time2 - time1) / (24 * 60 * 60 * 1000);
return res;
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
private static String getDay() {
var input = new Scanner(System.in);
System.out.println("Nhập ngày, tháng, năm theo định dạng dd/MM/yyyy: ");
var day = input.nextLine();
if (day.length() == 10) { //độ dài của đoạn string dd/MM/yyyy
return day;
}
return "01/01/2021";
}
}
|
package services;
import models.Flight;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import javax.persistence.criteria.*;
import java.util.List;
public class FlightService {
private static SessionFactory sessionFactory = ServiceHolder.getSessionFactory();
private static Session session = ServiceHolder.getSession();
public static void init()
{
}
public static boolean flightExistsByInfo(String origin, String destination, String flight_date)
{
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Flight> query = builder.createQuery(Flight.class);
Root<Flight> root = query.from(Flight.class);
query.select(root).where(
builder.and(
builder.equal(root.get("origin"), origin),
builder.equal(root.get("destination"),destination),
builder.equal(root.get("flight_date"),flight_date)));
List<Flight> flightList = session.createQuery(query).getResultList();
//if the flightlist is not empty, then the flight already exists - false would return true for this boolean
//if it is empty, then the flight does not exist - true would return false for this boolean
return !flightList.isEmpty();
}
public static Flight getFlightById(int flight_id)
{
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Flight> query = builder.createQuery(Flight.class);
Root<Flight> root = query.from(Flight.class);
query.select(root).where(builder.equal(root.get("flight_id"), flight_id));
List<Flight> flightList = session.createQuery(query).getResultList();
return flightList.get(0);
}
public static void saveNewFlight(Flight newFlight)
{
session.save(newFlight);
}
public static int availableSeats(int id)
{
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Flight> query = builder.createQuery(Flight.class);
Root<Flight> root = query.from(Flight.class);
query.select(root).where(builder.equal(root.get("flight_id"),id));
List<Flight> flightList = session.createQuery(query).getResultList();
int availableSeats = 0;
for(Flight flight : flightList)
{
availableSeats = flight.getNum_seats();
}
return availableSeats;
}
public static void updateNumSeats(Flight flight)
{
//update the num_seats for Flight subtracting the number booked on a ticket
session.update(flight);
}
public static List<Flight> availableFlights() {
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Flight> query = builder.createQuery(Flight.class);
Root<Flight> root = query.from(Flight.class);
query.orderBy(builder.asc(root.get("origin")));
return session.createQuery(query).getResultList();
}
public static void initiateTakeoff(Flight flight)
{
flight.setTake_off_status(true);
session.beginTransaction();
session.update(flight);
session.getTransaction().commit();
}
public static void deleteFlight(Flight flight)
{
session.beginTransaction();
session.delete(flight);
session.getTransaction().commit();
}
}
|
package com.spring.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="sme_sf_fieldview_lender")
public class SalesForceLenderDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "rid")
private Long rid;
private String CreatedById;
private String CreatedDate;
private String Id;
private String IsDeleted;
private String LastActivityDate;
private String LastModifiedById;
private String LastModifiedDate;
private String LastReferencedDate;
private String LastViewedDate;
private String Name;
private String OwnerId;
private String SystemModstamp;
public Long getRid() {
return rid;
}
public void setRid(Long rid) {
this.rid = rid;
}
public String getCreatedById() {
return CreatedById;
}
public void setCreatedById(String createdById) {
CreatedById = createdById;
}
public String getCreatedDate() {
return CreatedDate;
}
public void setCreatedDate(String createdDate) {
CreatedDate = createdDate;
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getIsDeleted() {
return IsDeleted;
}
public void setIsDeleted(String isDeleted) {
IsDeleted = isDeleted;
}
public String getLastActivityDate() {
return LastActivityDate;
}
public void setLastActivityDate(String lastActivityDate) {
LastActivityDate = lastActivityDate;
}
public String getLastModifiedById() {
return LastModifiedById;
}
public void setLastModifiedById(String lastModifiedById) {
LastModifiedById = lastModifiedById;
}
public String getLastModifiedDate() {
return LastModifiedDate;
}
public void setLastModifiedDate(String lastModifiedDate) {
LastModifiedDate = lastModifiedDate;
}
public String getLastReferencedDate() {
return LastReferencedDate;
}
public void setLastReferencedDate(String lastReferencedDate) {
LastReferencedDate = lastReferencedDate;
}
public String getLastViewedDate() {
return LastViewedDate;
}
public void setLastViewedDate(String lastViewedDate) {
LastViewedDate = lastViewedDate;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getOwnerId() {
return OwnerId;
}
public void setOwnerId(String ownerId) {
OwnerId = ownerId;
}
public String getSystemModstamp() {
return SystemModstamp;
}
public void setSystemModstamp(String systemModstamp) {
SystemModstamp = systemModstamp;
}
}
|
package cn.yhd.entity;
public class UserFunctionAuthKey {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_function_auth.function_code
*
* @mbggenerated
*/
private Byte functionCode;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_function_auth.user_id
*
* @mbggenerated
*/
private Long userId;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_function_auth.function_code
*
* @return the value of user_function_auth.function_code
*
* @mbggenerated
*/
public Byte getFunctionCode() {
return functionCode;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_function_auth.function_code
*
* @param functionCode the value for user_function_auth.function_code
*
* @mbggenerated
*/
public void setFunctionCode(Byte functionCode) {
this.functionCode = functionCode;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_function_auth.user_id
*
* @return the value of user_function_auth.user_id
*
* @mbggenerated
*/
public Long getUserId() {
return userId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_function_auth.user_id
*
* @param userId the value for user_function_auth.user_id
*
* @mbggenerated
*/
public void setUserId(Long userId) {
this.userId = userId;
}
}
|
package com.forsrc.cxf.server.restful.book.service.impl;
import com.forsrc.cxf.server.restful.base.service.impl.BaseCxfServiceImpl;
import com.forsrc.cxf.server.restful.book.service.BookService;
import com.forsrc.pojo.Book;
import com.forsrc.springmvc.restful.user.service.impl.UserServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* The type Book cxf service.
*/
@Service(value = "bookCxfService")
@Transactional
public class BookCxfServiceImpl extends BaseCxfServiceImpl<Book, Long> implements BookService {
}
|
import javax.faces.bean.ManagedBean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.event.ActionEvent;
import javax.sql.rowset.CachedRowSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
/*
* 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.
*/
/**
*
* @author osman
*/
@ManagedBean(name="prices")
public class Prices {
public String update(){
return "editPrice2.xhtml";
}
//Show prices
private List<PriceType> list = new ArrayList<PriceType>();
Connection connection=null;
PreparedStatement ps=null;
DataSource dataSource;
public Prices(){
try{
Context ctx=new InitialContext();
dataSource=(DataSource)ctx.lookup("jdbc/Otopark");
}catch(Exception e){
e.printStackTrace();
}
}
public List<PriceType> priceTable(){
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
connection=DriverManager.getConnection("jdbc:derby://localhost:1527/Otopark","APP","APP");
ps=connection.prepareStatement("SELECT * FROM price");
ResultSet resultSet=ps.executeQuery();
list.clear();
while(resultSet.next()){
PriceType prices=new PriceType();
prices.setCarType(resultSet.getString("CARTYPE"));
prices.setCost0_2(resultSet.getInt("TIME0_2"));
prices.setCost2_4(resultSet.getInt("TIME2_4"));
prices.setCost4_6(resultSet.getInt("TIME4_6"));
prices.setCost6_8(resultSet.getInt("TIME6_8"));
prices.setCost8_12(resultSet.getInt("TIME8_12"));
prices.setCost12_24(resultSet.getInt("TIME12_24"));
prices.setCostDay(resultSet.getInt("DAILY"));
prices.setCostMounth(resultSet.getInt("MOUNTH"));
list.add(prices);
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
}
|
package co.aospa.mandy.view.recyclerview;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by willi on 16.04.17.
*/
public abstract class Item {
public abstract void onBind(View view);
public abstract View onCreateView(LayoutInflater inflater, ViewGroup parent);
}
|
import java.util.ArrayList;
import java.util.HashMap;
public class Entity {
private String name;
private int size;
private ArrayList<Tweet> tweet_list;
private HashMap<Long,Double> sigmaMap;
public Entity(String clusterName) {
this.name = clusterName;
this.size = 0;
this.tweet_list = new ArrayList<Tweet>();
this.sigmaMap = new HashMap<Long,Double>();
}
public String getName() {
return name;
}
public ArrayList<Tweet> getTweets(){
return tweet_list;
}
public void setSigmaMap(){
this.sigmaMap = null;
}
public HashMap<Long,Double> getSigmaMap(){
return this.sigmaMap;
}
public void addTweet(Tweet newTweet) {
tweet_list.add(newTweet);
size = size + 1;
}
public void calculateSigma(Long minTime, Long maxTime,Long timeStep) {
Long stepEnd = minTime + timeStep;
ArrayList<Integer> stepAmounts = new ArrayList<Integer>();
while(minTime < maxTime) {
int count = 0;
for(int i = 0; i < tweet_list.size(); i++) {
if(tweet_list.get(i).getTimestamp() > minTime) {
if(tweet_list.get(i).getTimestamp() < stepEnd) {
count = count + 1;
}
}
}
stepAmounts.add(count);
minTime = stepEnd;
stepEnd = stepEnd + timeStep;
}
double sum = 0.0;
for(int j = 0; j < stepAmounts.size(); j++) {
sum = sum + stepAmounts.get(j);
}
double mean = sum/stepAmounts.size();
double sumSq = 0.0;
for(int k = 0; k < stepAmounts.size(); k ++) {
sumSq = Math.pow((stepAmounts.get(k) - mean),2);
}
double sd = Math.sqrt(sumSq/(stepAmounts.size() - 1));
double sigma = Math.ceil(mean + (3*sd));
sigmaMap.put(timeStep, sigma);
}
}
|
package com.michalkowol.cars;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "cars")
class CarEntity {
@Id
private Integer id;
private String name;
}
|
package utils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class ConfigFileReader {
private Properties properties;
private final String propertyFilePath= "C:\\Users\\akumar\\Himanshu\\src\\main\\resources\\configuration.properties";
public ConfigFileReader(){
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(propertyFilePath));
properties = new Properties();
try {
properties.load(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Configuration.properties not found at " + propertyFilePath);
}
}
public String getChromeDriverPath(){
String ChromeDriverPath = properties.getProperty("ChromeDriverPath");
if(ChromeDriverPath!= null) return ChromeDriverPath;
else throw new RuntimeException("driverPath not specified in the Configuration.properties file.");
}
public String getLoginPageUrl() {
String LoginPageUrl = properties.getProperty("LoginPageUrl");
if(LoginPageUrl != null) return LoginPageUrl;
else throw new RuntimeException(" LoginPage url not specified in the Configuration.properties file.");
}
public String getInputSheetPath() {
String InputSheetPath = properties.getProperty("InputSheetPath");
if(InputSheetPath != null) return InputSheetPath;
else throw new RuntimeException("InputSheet.xls not specified in the Configuration.properties file.");
}
public String getBrowserType() {
String BrowserType = properties.getProperty("BrowserType");
if(BrowserType != null) return BrowserType;
else throw new RuntimeException("BrowserType not specified in the Configuration.properties file.");
}
public String getRegisterPageUrl() {
String RegisterPageUrl = properties.getProperty("RegisterPageUrl");
if(RegisterPageUrl != null) return RegisterPageUrl;
else throw new RuntimeException("RegisterPageUrl not specified in the Configuration.properties file.");
}
public String getHomePageUrl() {
String HomePageUrl = properties.getProperty("HomePageUrl");
if(HomePageUrl != null) return HomePageUrl;
else throw new RuntimeException("HomePageUrl not specified in the Configuration.properties file.");
}
public String getWindowTiltleOfLoginOrRegistrationPage() {
String WindowTitleLoginOrRegistrationPage = properties.getProperty("WindowTitleLoginOrRegistrationPage");
if(WindowTitleLoginOrRegistrationPage != null) return WindowTitleLoginOrRegistrationPage;
else throw new RuntimeException("WindowTitleLoginOrRegistrationPageHomePageUrl not specified in the Configuration.properties file.");
}
public String getWindowTiltleOfHomePage() {
String WindowTitleHomePage = properties.getProperty("WindowTitleHomePage");
if(WindowTitleHomePage != null) return WindowTitleHomePage;
else throw new RuntimeException("WindowTitleHomePage not specified in the Configuration.properties file.");
}
}
|
/*
* @Author : fengzhi
* @date : 2019 - 02 - 14 13 : 26
* @Description : 把数字翻译成字符串 50min
*/
package problem46;
public class Solution1 {
// 那就加油吧! 不要逃避问题,逃避不过去的。 fengzhi,愿你如心有猛虎细嗅蔷薇。
public int getTranslationCount(int number) {
if (number < 0)
return 0;
String s = String.valueOf(number);
int length = s.length();
int count;
if (length == 1)
return 1;
int[] counts = new int[length];
// 代表初始值,即只有一个数字时,仅有一种可能
counts[length - 1] = 1;
for (int i = length - 2; i >= 0; i --) {
count = counts[i + 1];
// 使得两位数存在
if (i < length - 1) {
int num = ( s.charAt(i) - '0' ) * 10 + s.charAt(i + 1) - '0';
if (num <= 25 & num >= 10) {
if (i < length - 2)
count += counts[i + 2];
else
count += 1;
}
}
counts[i] = count;
}
return counts[0];
}
public static void main(String[] args) {
Solution1 solution1 = new Solution1();
System.out.println(solution1.getTranslationCount(25));
System.out.println(solution1.getTranslationCount(26));
System.out.println(solution1.getTranslationCount(0));
System.out.println(solution1.getTranslationCount(-1));
}
}
|
import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int ans=1;
for(int i=0;i<str.length();i++){
if(str.charAt(i)==' '){
ans++;
}
}
if(str.charAt(0)==' '){
ans--;
}
if(str.charAt(str.length()-1)==' '){
ans--;
}
System.out.println(ans);
}
}
|
package br.unisal.dao;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import br.unisal.interfaces.DAOInterface;
import br.unisal.model.Filme;
import br.unisal.util.DbUtil;
public class FilmeDAO extends GenericDAO implements DAOInterface<Filme> {
private static FilmeDAO INSTANCE;
private FilmeDAO() {
}
public static FilmeDAO getInstance() {
if (INSTANCE == null) {
INSTANCE = new FilmeDAO();
}
return INSTANCE;
}
public void delete(Long id) throws ClassNotFoundException, SQLException, IOException {
String sql = "delete from filme where id = ?";
PreparedStatement ps = null;
try {
ps = getConnectionPool().prepareStatement(sql);
ps.setLong(1, id);
ps.execute();
} finally {
DbUtil.getInstance().closeQuietly(ps);
}
}
public void update(Filme t) throws ClassNotFoundException, SQLException, IOException {
String sql = "update filme set nome = ?, descricao = ?, imagem_pq = ? where id = ?";
PreparedStatement ps = null;
try {
ps = getConnectionPool().prepareStatement(sql);
ps.setString(1, t.getNome());
ps.setString(2, t.getDescricao());
ps.setString(3, t.getImagem());
ps.setLong(4, t.getId());
ps.execute();
} finally {
DbUtil.getInstance().closeQuietly(ps);
}
}
public void insert(Filme t) throws ClassNotFoundException, SQLException, IOException {
String sql = "insert into filme (nome, uuid, descricao, imagem_pq) values (?,?,?,?)";
PreparedStatement ps = null;
try {
ps = getConnectionPool().prepareStatement(sql);
ps.setString(1, t.getNome());
ps.setString(2, t.getUuid());
ps.setString(3, t.getDescricao());
ps.setString(4, t.getImagem());
ps.execute();
} finally {
DbUtil.getInstance().closeQuietly(ps);
}
}
public List<Filme> findAll() throws ClassNotFoundException, SQLException, IOException {
String sql = "select id, nome, uuid, descricao, imagem_pq from filme order by id desc";
List<Filme> filmes = new ArrayList<>();
List<Object[]> objects = executaSqlSemParametro(getConnectionPool(), sql);
if (objects != null) {
for (Object[] os : objects) {
filmes.add(castObjectToModel(os));
}
}
return filmes;
}
public Filme findById(Long id) throws ClassNotFoundException, SQLException, IOException {
String sql = "select id, nome, uuid, descricao, imagem_pq from filme where id = ?";
Filme filme = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = getConnectionPool().prepareStatement(sql);
ps.setLong(1, id);
rs = ps.executeQuery();
while (rs.next()) {
filme = new Filme();
filme.setId(rs.getLong(1));
filme.setNome(rs.getString(2));
filme.setUuid(rs.getString(3));
filme.setDescricao(rs.getString(4));
filme.setImagem(rs.getString(5));
}
} finally {
DbUtil.getInstance().closeQuietly(ps, rs);
}
return filme;
}
private Filme castObjectToModel(Object[] obj) {
Filme filme = new Filme();
filme.setId((Long) obj[0]);
filme.setNome((String) obj[1]);
filme.setUuid((String) obj[2]);
filme.setDescricao((String) obj[3]);
filme.setImagem((String) obj[4]);
return filme;
}
}
|
package model;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
/**
* This class represents a graphical Tile in the game.
* If you use it, you should EXTEND it or ADD MORE PROPERTIES
*/
public class Tile {
private BufferedImage image; // Graphical representation of this tile
private String fileName; // Filename should match the ImageIcon used
public Tile(BufferedImage image, String fileName) {
this.image = image;
this.fileName = fileName;
}
public BufferedImage getImage() {
return image;
}
public String getFileName() {
return fileName;
}
@Override
public String toString() {
return "[" + fileName + "]";
}
}
|
package com.charith.codility.sorting.NumberOfDiscIntersections;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void solution() {
Assertions.assertEquals(11, Solution.solution(new int[]{1, 5, 2, 1, 4, 0}));
}
}
|
package kiteshoolalgorithms.search;
public class BinarySearch2 {
private static int[] list = new int[] {1,2,3,4,5,6,7,8,9};
public static void main(String[] args) {
if (binarySearch(list,7)){
System.out.println("array consist 7");
}
if (!binarySearch(list,14)){
System.out.println("array isn't consist 14");
}
}
private static boolean binarySearch(final int[] array, final int search){
int first = 0;
int last = array.length-1;
int middle = (first + last) / 2;
while(first <= last) {
if(array[middle] < search){
first = middle+1;
}
else if (array[middle] == search){
return true;
} else {
last = middle - 1;
}
middle = (first + last)/2;
}
return false;
}
}
|
package com.appsquadz.hostelutility;
import com.code_base_update.beans.DashBoardBean;
import com.code_base_update.view.IBaseView;
import java.util.ArrayList;
public interface IODashboardView extends IBaseView {
void onDataLoaded(ArrayList<DashBoardBean> list);
void onProfileImageLoaded();
}
|
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Doubled {
public static void main(String[] args) {
// Create a method that decrypts the duplicated-chars.txt
System.out.println(decryptFunction());
//decryptFunction();
}
protected static List<String> decryptFunction(){
List<String> lines = new ArrayList<>();
List<String> theDecryptedList = new ArrayList<>();
Path filePath = Paths.get("duplicated-chars.txt");
try {
lines = Files.readAllLines(filePath);
} catch (NoSuchFileException e) {
System.out.println("No such file");
} catch (IOException e) {
System.out.println("Unable to read the file");
} catch (Exception e) {
System.out.println("Something went wrong");
}
for (String line: lines) {
//2 új character alapú listák kreáltam, hogy ezekbe először a szétszedett charactereket tároljam,
//majd a másikba a már duplikálódás mentes karaktereket tegyem bele, illetve egy üres stringet
//amibe majd a karaktereket töltöm vissza
List<Character> theDuplicatedChars = new ArrayList<>();
List<Character> theDecryptedChars = new ArrayList<>();
String charsBackToString = "";
//itt szedem szét karakterekre a sorokat egy foreach-el
for (char c: line.toCharArray()) {
theDuplicatedChars.add(c);
}
//
for (int i = 0; i < theDuplicatedChars.size(); i++) {
if (i > 1) {
theDuplicatedChars.remove(i - 1);
}
theDecryptedChars.add(theDuplicatedChars.get(i));
}
for (int i = 1; i < theDecryptedChars.size() ; i++) {
charsBackToString +=theDecryptedChars.get(i);
}
theDecryptedList.add(charsBackToString);
}
return theDecryptedList;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.organization.interceptor;
import de.hybris.platform.commerceservices.model.OrgUnitModel;
import de.hybris.platform.commerceservices.organization.services.OrgUnitService;
import de.hybris.platform.servicelayer.i18n.L10NService;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import de.hybris.platform.servicelayer.interceptor.ValidateInterceptor;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.user.UserService;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Required;
/**
* This interceptor validates:
* <ul>
* <li>1. Restrain orgUnit from being in more than one orgUnit group (eg 1 parent).</li>
* <li>2. Do not allow to activate units whose parents have be disabled.</li>
* </ul>
*
*/
public class OrgUnitModelValidateInterceptor implements ValidateInterceptor
{
private static final String ERROR_ORGUNIT_NO_MULTIPLE_PARENT = "error.orgunit.no.multiple.parent";
private static final String ERROR_ORGUNIT_ENABLE_ORGUNITPARENT_DISABLED = "error.orgunit.enable.orgunitparent.disabled";
private OrgUnitService orgUnitService;
private ModelService modelService;
private UserService userService;
private L10NService l10NService;
@Override
public void onValidate(final Object model, final InterceptorContext ctx) throws InterceptorException
{
if (model instanceof OrgUnitModel)
{
final OrgUnitModel unit = (OrgUnitModel) model;
// Restrain orgUnit from being in more than one orgUnit group (e.g 1 parent).
if (unit.getGroups() != null)
{
// Filter groups by OrgUnit type
final Set<OrgUnitModel> groups = unit.getGroups().stream().filter(grp -> grp.getItemtype().equals(unit.getItemtype()))
.filter(grp -> grp instanceof OrgUnitModel).map(grp -> (OrgUnitModel) grp).collect(Collectors.toSet());
if (groups.size() > 1)
{
throw new InterceptorException(getL10NService().getLocalizedString(ERROR_ORGUNIT_NO_MULTIPLE_PARENT, new Object[]
{ unit.getClass().getSimpleName() }));
}
final OrgUnitModel parentUnit = groups.stream().findFirst().orElse(null);
// Do not allow to activate units whose parents have be disabled.
if (unit.getActive().booleanValue() && parentUnit != null && !parentUnit.getActive().booleanValue())
{
throw new InterceptorException(
getL10NService().getLocalizedString(ERROR_ORGUNIT_ENABLE_ORGUNITPARENT_DISABLED, new Object[]
{ unit.getClass().getSimpleName(), unit.getUid(), parentUnit.getUid() }));
}
}
}
}
protected OrgUnitService getOrgUnitService()
{
return orgUnitService;
}
@Required
public void setOrgUnitService(final OrgUnitService orgUnitService)
{
this.orgUnitService = orgUnitService;
}
protected ModelService getModelService()
{
return modelService;
}
@Required
public void setModelService(final ModelService modelService)
{
this.modelService = modelService;
}
@Required
public void setUserService(final UserService userService)
{
this.userService = userService;
}
protected UserService getUserService()
{
return userService;
}
@Required
public void setL10NService(final L10NService l10NService)
{
this.l10NService = l10NService;
}
protected L10NService getL10NService()
{
return l10NService;
}
}
|
package kr.co.jboard2.service;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import kr.co.jboard2.dao.ArticleDao;
import kr.co.jboard2.vo.ArticleVO;
import kr.co.jboard2.vo.MemberVO;
public class ViewService implements CommonService {
@Override
public String requestProc(HttpServletRequest req, HttpServletResponse resp) {
//세션 사용정보 가져오기
HttpSession sess = req.getSession();
MemberVO mv = (MemberVO) sess.getAttribute("sessMember");
// 로그인을 하지 않고 List 페이지를 요청할 경우
if(mv == null){
return "redirect:/JBoard2/user/login.do?success=101";
}
// 전송 데이터 수신
String seq = req.getParameter("seq");
// Dao 객체 가져오기
ArticleDao dao = ArticleDao.getInstance();
// 글 가져오기
ArticleVO article = dao.selectArticle(seq);
// 해당 글 조회수 업데이트
dao.updateArticleHit(seq);
// 댓글 가져오기
List<ArticleVO> comments = dao.selectComments(seq);
req.setAttribute("article", article);
req.setAttribute("comments", comments);
return "/view.jsp";
}
}
|
package com.tencent.mm.plugin.welab.ui;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.welab.b;
import com.tencent.mm.plugin.welab.e;
import com.tencent.mm.sdk.platformtools.x;
class WelabAppInfoUI$3 implements OnClickListener {
final /* synthetic */ WelabAppInfoUI qng;
WelabAppInfoUI$3(WelabAppInfoUI welabAppInfoUI) {
this.qng = welabAppInfoUI;
}
public final void onClick(View view) {
x.i("WelabAppInfoUI", "open func " + WelabAppInfoUI.b(this.qng));
b bYI = b.bYI();
WelabAppInfoUI welabAppInfoUI = this.qng;
String b = WelabAppInfoUI.b(this.qng);
com.tencent.mm.plugin.welab.a.a.b bVar = (com.tencent.mm.plugin.welab.a.a.b) bYI.qmN.get(b);
if (bVar != null) {
x.i("WelabMgr", "use custome opener to open " + b);
bVar.e(welabAppInfoUI, b);
} else {
x.i("WelabMgr", "use default opener open " + b);
if (bYI.RT(b).field_Type != 2) {
x.e("WelabMgr", "can not find opener for " + b);
} else if (bYI.qmO != null) {
bYI.qmO.e(welabAppInfoUI, b);
} else {
x.e("WelabMgr", "defaultWeAppOpener is null!");
}
}
e.n(WelabAppInfoUI.b(this.qng), 7, WelabAppInfoUI.c(this.qng));
}
}
|
package com.jackie.classbook.service.write.impl;
import com.alibaba.fastjson.JSON;
import com.jackie.classbook.common.ClassbookCodeEnum;
import com.jackie.classbook.common.ClassbookException;
import com.jackie.classbook.common.TeacherTypeEnum;
import com.jackie.classbook.dao.*;
import com.jackie.classbook.dto.request.BaseIdReqDTO;
import com.jackie.classbook.dto.request.MateExportReqDTO;
import com.jackie.classbook.dto.response.*;
import com.jackie.classbook.entity.*;
import com.jackie.classbook.entity.Class;
import com.jackie.classbook.entity.module.MateClassMapperFactory;
import com.jackie.classbook.entity.module.MateFactory;
import com.jackie.classbook.entity.module.SchoolFactory;
import com.jackie.classbook.entity.module.TeacherFactory;
import com.jackie.classbook.process.AbstractService;
import com.jackie.classbook.process.Context;
import com.jackie.classbook.service.write.ExportService;
import com.jackie.classbook.util.ExcelUtil;
import com.jackie.classbook.util.ExportContentUtil;
import com.jackie.classbook.util.ListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* Description:
*
* @author xujj
* @date 2018/12/3
*/
@Service
public class ExportServiceImpl extends AbstractService implements ExportService {
@Autowired
private MateClassMapperDao mateClassMapperDao;
@Autowired
private TeacherClassMapperDao teacherClassMapperDao;
@Autowired
private ClassDao classDao;
@Autowired
private MateDao mateDao;
@Autowired
private SchoolDao schoolDao;
@Autowired
private AccountDao accountDao;
@Autowired
private TeacherDao teacherDao;
@Autowired
private AccountClassMapperDao accountClassMapperDao;
@Override
public Context<BaseIdReqDTO, Void> exportClass(BaseIdReqDTO reqDTO) {
MateClassMapper mateClassMapper = new MateClassMapper();
mateClassMapper.setAccountId(reqDTO.getId());
List<MateClassMapper> list = mateClassMapperDao.queryClassListByAccountId(mateClassMapper);
if (ListUtil.isEmpty(list)){
throw new ClassbookException(ClassbookCodeEnum.NO_RECORD);
}
Map<String, String> map = new HashMap<>();
for (MateClassMapper clazz : list){
Class c = classDao.queryById(clazz.getClassId());
map.put(clazz.getClassId() + "", c.getYear() + "");
TeacherClassMapper teacherClassMapper = new TeacherClassMapper();
teacherClassMapper.setClassId(clazz.getClassId());
teacherClassMapper.setTeacherType(TeacherTypeEnum.CLASSTEACHER.getKey());//班主任
List<TeacherClassMapper> classTeacher = teacherClassMapperDao.queryListByClassIdAndType(teacherClassMapper);
teacherClassMapper.setTeacherType(TeacherTypeEnum.SUBJECTSTEACHER.getKey());//任课老师
List<TeacherClassMapper> subjectTeacher = teacherClassMapperDao.queryListByClassIdAndType(teacherClassMapper);
if (classTeacher != null && classTeacher.size() > 0){
map.put(clazz.getClassId() + "-classTeacher", classTeacher.get(0).getTeacherName());
}
if (subjectTeacher != null && subjectTeacher.size() > 0){
String subTeacher = null;
for (int i = 0; i < subjectTeacher.size(); i ++){
if (i > 0){
subTeacher += ",";
}
subTeacher += subjectTeacher.get(i).getTeacherName();
}
map.put(clazz.getClassId() + "-subjectTeacher", subTeacher);
}
}
List<ClassExportRespDTO> exportList = MateClassMapperFactory.getClassExportRespDTO(list, map);
Context<BaseIdReqDTO, Void> context = new Context<>();
String[] title= {"序号","校名","届","班级","班主任","任课老师"};
ExportRespDTO exportRespDTO = new ExportRespDTO();
exportRespDTO.setFileName("班级信息");
exportRespDTO.setTitle(title);
exportRespDTO.setContent(ExportContentUtil.getContetn(exportList, title.length));
try {
ExcelUtil.export(exportRespDTO);
} catch (Exception e){
throw new ClassbookException("", e.getMessage());
}
return context;
}
@Override
public Context<MateExportReqDTO, Void> exportMate(MateExportReqDTO reqDTO) {
MateClassMapper mateClassMapper = new MateClassMapper();
mateClassMapper.setAccountId(reqDTO.getAccountId());
mateClassMapper.setSchoolId(reqDTO.getSchoolId());
mateClassMapper.setClassId(reqDTO.getClassId());
List<MateClassMapper> list = mateClassMapperDao.queryListByAccountIdAndSchoolIdClassId(mateClassMapper);
if (ListUtil.isEmpty(list)){
throw new ClassbookException(ClassbookCodeEnum.NO_RECORD);
}
List<Long> idList = new ArrayList<>();
for (MateClassMapper mate : list){
idList.add(mate.getMateId());
}
List<Mate> mateList = mateDao.queryMatesByIdList(idList);
Map<Long, Mate> mateMap = new HashMap<>();
if (ListUtil.isNotEmpty(mateList)){
for (Mate mate : mateList){
mateMap.put(mate.getId(), mate);
}
}
List<MateExportRespDTO> exportList = MateFactory.getMateExportRespDTO(list, mateMap);
Context<MateExportReqDTO, Void> context = new Context<>();
String fileName = "";
if (reqDTO.getSchoolId() != null){
School school = schoolDao.querySchoolById(reqDTO.getSchoolId());
if (school == null){
throw new ClassbookException(ClassbookCodeEnum.NO_RECORD);
}
fileName += school.getSchoolName();
}
if (reqDTO.getClassId() != null){
Class clazz = classDao.queryById(reqDTO.getClassId());
if (clazz == null){
throw new ClassbookException(ClassbookCodeEnum.NO_RECORD);
}
fileName += clazz.getClassName();
}
String[] title= {"序号","校名","班级","姓名","类型","手机","QQ","邮箱","民族","年龄","性别","省","城市",
"县/区","镇/街道","村","居住城市","印象"};
ExportRespDTO exportRespDTO = new ExportRespDTO();
exportRespDTO.setFileName(fileName + "同学信息");
exportRespDTO.setTitle(title);
exportRespDTO.setContent(ExportContentUtil.getContetn(exportList, title.length));
try {
ExcelUtil.export(exportRespDTO);
} catch (Exception e){
throw new ClassbookException("", e.getMessage());
}
return context;
}
@Override
public Context<BaseIdReqDTO, Void> exportSchool(BaseIdReqDTO reqDTO) {
Account account = accountDao.queryAccountById(reqDTO.getId());
if (account == null){
throw new ClassbookException(ClassbookCodeEnum.ACCOUNT_NOT_EXIST);
}
List<Long> idList = getAccountSchoolIdList(account);
List<School> schoolList = schoolDao.querySchoolByIdList(idList);
List<SchoolExportRespDTO> exportList = SchoolFactory.getSchoolExportRespDTO(schoolList);
Context<BaseIdReqDTO, Void> context = new Context<>();
String[] title= {"序号","校名","类型","省","城市","县/区","校训"};
ExportRespDTO exportRespDTO = new ExportRespDTO();
exportRespDTO.setFileName("学校信息");
exportRespDTO.setTitle(title);
exportRespDTO.setContent(ExportContentUtil.getContetn(exportList, title.length));
try {
ExcelUtil.export(exportRespDTO);
} catch (Exception e){
throw new ClassbookException("", e.getMessage());
}
return context;
}
@Override
public Context<MateExportReqDTO, Void> exportTeacher(MateExportReqDTO reqDTO) {
List<TeacherExportRespDTO> exportList = new ArrayList<>();
List<Long> idList = new ArrayList<>();
String schoolName = null;
String className = null;
if (reqDTO.getClassId() != null){
TeacherClassMapper teacherClassMapper = new TeacherClassMapper();
teacherClassMapper.setClassId(reqDTO.getClassId());
List<TeacherClassMapper> teacherClassMapperList = teacherClassMapperDao.queryListByClassIdAndType(teacherClassMapper);
if (ListUtil.isNotEmpty(teacherClassMapperList)) {
for (TeacherClassMapper teacher : teacherClassMapperList) {
idList.add(teacher.getTeacherId());
}
}
Class clazz = classDao.queryById(reqDTO.getClassId());
schoolName = schoolDao.querySchoolById(clazz.getSchoolId()).getSchoolName();
className = clazz.getClassName();
} else {
AccountClassMapper accountClassMapper = new AccountClassMapper();
accountClassMapper.setAccountId(reqDTO.getAccountId());
if (reqDTO.getSchoolId() != null) {
accountClassMapper.setSchoolId(reqDTO.getSchoolId());
schoolName = schoolDao.querySchoolById(reqDTO.getSchoolId()).getSchoolName();
}
List<AccountClassMapper> classList = accountClassMapperDao.queryList(accountClassMapper);
if (ListUtil.isEmpty(classList)){
throw new ClassbookException(ClassbookCodeEnum.NO_RECORD);
}
List<Long> classIdList = new ArrayList<>();
for (AccountClassMapper accountClass : classList){
classIdList.add(accountClass.getClassId());
}
List<TeacherClassMapper> teacherClassMapperList = teacherClassMapperDao.queryListByClassIdList(classIdList);
if (ListUtil.isEmpty(teacherClassMapperList)){
throw new ClassbookException(ClassbookCodeEnum.NO_RECORD);
}
for (TeacherClassMapper teacherClassMapper : teacherClassMapperList){
idList.add(teacherClassMapper.getTeacherId());
}
}
List<Teacher> teacherList = teacherDao.queryByIdList(idList);
exportList = TeacherFactory.getTeacherExportRespDTO(teacherList);
Context<MateExportReqDTO, Void> context = new Context<>();
String fileName = "";
if (!StringUtils.isEmpty(schoolName)){
fileName += schoolName;
}
if (!StringUtils.isEmpty(className)){
fileName += className;
}
String[] title= {"序号","校名","姓名","性别","手机","邮箱","所教科目"};
ExportRespDTO exportRespDTO = new ExportRespDTO();
exportRespDTO.setFileName(fileName + "教师信息");
exportRespDTO.setTitle(title);
exportRespDTO.setContent(ExportContentUtil.getContetn(exportList, title.length));
try {
ExcelUtil.export(exportRespDTO);
} catch (Exception e){
throw new ClassbookException("", e.getMessage());
}
return context;
}
/**
* 获取用户学校
* @param account
* @return
*/
public List<Long> getAccountSchoolIdList(Account account){
List<Long> idList = new ArrayList<>();
if (account.getPrimarySchoolId() != null){
idList.add(account.getPrimarySchoolId());
}
if (account.getJuniorSchoolId() != null){
idList.add(account.getJuniorSchoolId());
}
if (account.getSeniorSchoolId() != null){
idList.add(account.getSeniorSchoolId());
}
if (account.getUniversityId() != null){
idList.add(account.getUniversityId());
}
return idList;
}
}
|
package com.tencent.c.f;
public final class h {
private static boolean vkL;
private static g vkM;
static {
vkL = false;
vkM = new k();
vkL = false;
vkM = new k();
}
public static void k(Throwable th) {
cD(th);
}
public static void cD(Object obj) {
if (obj == null) {
return;
}
if (obj instanceof Exception) {
new StringBuilder().append(obj);
} else {
obj.toString();
}
}
public static void cE(Object obj) {
if (obj == null) {
return;
}
if (obj instanceof Exception) {
new StringBuilder().append(obj);
} else {
obj.toString();
}
}
public static void i(String str) {
cF(str);
}
public static void d(String str) {
cF(str);
}
public static void cF(Object obj) {
if (obj != null) {
obj.toString();
}
}
}
|
package com.enat.sharemanagement.agenda;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AgendaSummary {
private long agendaId;
private String title;
private long yes;
private long no;
private long silent;
}
|
public class Person {
// attribute
protected String surName;
protected String firstName;
protected String secondName;
// constructor
public Person(String surName, String firstName, String secondName) {
super();
this.surName = surName;
this.firstName = firstName;
this.secondName = secondName;
}
public Person(String surName, String firstName) {
super();
this.surName = surName;
this.firstName = firstName;
}
//property
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public void show() {
// System.out.println((firstName+secondName+surName).trim());
System.out.println(this.surName + this.firstName + (this.secondName != null ? this.secondName : ""));
}
//show
public String toString() {
return "Person [surName=" + surName + ", firstName=" + firstName + ", secondName=" + secondName + "]";
}
}
|
package com.somethinglurks.jbargain.scraper.node.post.poll;
import com.somethinglurks.jbargain.api.node.meta.Author;
import com.somethinglurks.jbargain.api.node.meta.Vote;
import com.somethinglurks.jbargain.api.node.post.poll.PollOption;
import com.somethinglurks.jbargain.scraper.node.meta.AuthorElementAdapter;
import com.somethinglurks.jbargain.scraper.util.date.StringToDate;
import com.somethinglurks.jbargain.scraper.util.integer.StringToInteger;
import org.jsoup.nodes.Element;
import java.util.Date;
public class ScraperPollOption implements PollOption {
private Element element;
private String nodeId;
private boolean hidden;
private Author author;
private Date date;
public ScraperPollOption(Element element, String nodeId, boolean hidden) {
this.element = element;
this.nodeId = nodeId;
this.hidden = hidden;
// Set author and date if item was suggested by another user
if (element.select("div.suggest").size() == 1) {
author = new AuthorElementAdapter(element.selectFirst("div.suggest"));
date = StringToDate.parsePostDate(element.select("div.suggest a").text(), true);
} else {
author = null;
date = null;
}
}
@Override
public String getNodeId() {
return nodeId;
}
@Override
public String getDescription() {
return element.select("span.polltext").text();
}
@Override
public Author getAuthor() {
return author;
}
@Override
public Date getPostDate() {
return date;
}
@Override
public boolean isScoreHidden() {
return hidden;
}
@Override
public int getScore() {
if (isScoreHidden()) {
return 0;
} else {
return StringToInteger.parseSelector(element, "div.n-vote > span > span");
}
}
@Override
public Vote getUserVote() {
if (element.select("div.n-vote").hasClass("voteup")) {
return Vote.POSITIVE;
} else {
return null;
}
}
@Override
public String getId() {
return element.attr("data-oid");
}
}
|
package April;
public class Method_Calculation {
public static void main(String[] args) {
System.out.println("result of addition is ->>> " +add(4,5));
System.out.println("result of subtruction is ->>> " +minus(10,5));
System.out.println("result of multiplication is ->>> " +multiply(4,5));
System.out.println("result of division is ->>> " +divide(45,5));
}
public static double add(double num1,double num2){
double result = num1 + num2;
return result;
}
public static double minus(double num1,double num2){
double result = num1 - num2;
return result;
}
public static double multiply (double num1,double num2){
double result = num1 * num2 ;
return result;
}
public static double divide (double num1, double num2){
double result = num1 / num2;
return result;
}
}
|
package com.sporsimdi.model.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.sporsimdi.model.base.ExtendedModel;
import com.sporsimdi.model.type.OrganizasyonTipi;
@Table
@Entity
public class Organizasyon extends ExtendedModel {
private static final long serialVersionUID = 8986161490957095179L;
@Enumerated(EnumType.STRING)
private OrganizasyonTipi organizasyonTipi;
private String adi;
@Temporal(TemporalType.TIMESTAMP)
private Date tarihBaslangic;
@Temporal(TemporalType.TIMESTAMP)
private Date tarihBitis;
@ManyToOne(fetch = FetchType.LAZY)
private Isletme isletme;
@OneToMany(mappedBy = "organizasyon", fetch = FetchType.LAZY)
private List<OrgTesis> orgTesisListesi = new ArrayList<OrgTesis>();
public Isletme getIsletme() {
return isletme;
}
public void setIsletme(Isletme isletme) {
this.isletme = isletme;
}
public Date getTarihBaslangic() {
return tarihBaslangic;
}
public void setTarihBaslangic(Date tarihBaslangic) {
this.tarihBaslangic = tarihBaslangic;
}
public Date getTarihBitis() {
return tarihBitis;
}
public void setTarihBitis(Date tarihBitis) {
this.tarihBitis = tarihBitis;
}
public OrganizasyonTipi getOrganizasyonTipi() {
return organizasyonTipi;
}
public void setOrganizasyonTipi(OrganizasyonTipi organizasyonTipi) {
this.organizasyonTipi = organizasyonTipi;
}
public String getAdi() {
return adi;
}
public void setAdi(String adi) {
this.adi = adi;
}
public List<OrgTesis> getOrgTesisListesi() {
return orgTesisListesi;
}
public void setOrgTesisListesi(List<OrgTesis> orgTesisListesi) {
this.orgTesisListesi = orgTesisListesi;
}
@Override
public String toString() {
return "Organizasyon [" + adi + "]";
}
}
|
public class Driver {
public static void main(String[] args)
{
Node station1 = new Node("San Francisco", null, null);
}
}
|
public class Cat
{
private double originWeight;
private double weight;
private double minWeight;
private double maxWeight;
private double feedAmount=0;
private boolean liveStatus;
private static final int NUMBER_OF_EYES = 2;
private static final double MINIMUM_WEIGHT = 1000.0;
private static final double MAXIMUM_WEIGHT = 9000.0;
private CatColor catColor;
private String name;
private static int count;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCatColor(CatColor catColor) {
this.catColor = catColor;
}
public CatColor getCatColor() {
return catColor;
}
public double getFeedAmount() {
return feedAmount;
}
public boolean isLiveStatus(){
if (getWeight()<maxWeight && getWeight()>minWeight){
liveStatus = true;
}else {
liveStatus = false;
}
return liveStatus;
}
public Cat()
{
count = getCount()+1;
weight = 1500.0 + 3000.0 * Math.random();
originWeight = weight;
minWeight = 1000.0;
maxWeight = 9000.0;
}
public Cat(double weight)
{
this();
this.weight = weight;
originWeight = weight;
}
public void meow(){
if (isLiveStatus()){
weight = weight - 1;
if (!isLiveStatus()){
count--;
}
} if (!isLiveStatus()){
// Cat.count = count-1;
System.out.println("Кошка мертва и не может мяукнуть");
}
}
public void feed(Double amount){
if (isLiveStatus()){
feedAmount +=amount;
weight = weight + amount;
if (!isLiveStatus()){
count--;
}
} if (!isLiveStatus()){
// Cat.count = count-1;
System.out.println(" нельзя покормить, так как кошка мертва");}
}
public void drink(Double amount)
{
if (isLiveStatus()){
weight = weight + amount;
if (!isLiveStatus()){
count--;
}
} if (!isLiveStatus()){
// Cat.count = count-1;
System.out.println(" нельзя напоить, так как кошка мертва");
}
}
public void pee(){
if (isLiveStatus()){weight = weight - 150;
System.out.println("Pee pee ka ka");
if (!isLiveStatus()){
count--;
}
} if (!isLiveStatus()){
System.out.println(" нельзя отправить в туалет, так как кошка мертва");
}
}
public Double getWeight()
{
return weight;
}
public String getStatus()
{
if(weight < minWeight) {
return "Dead";
}
else if(weight > maxWeight) {
return "Exploded";
}
else if(weight > originWeight) {
return "Sleeping";
}
else {
return "Playing";
}
}
/**
* метод для копирования
*/
public Cat copyCat(){
Cat nameCat = new Cat();
nameCat.weight = weight;
nameCat.setName(name);
nameCat.setCatColor(catColor);
return nameCat;
}
public static int getCount() {
return count;
}
}
|
package run.test.api;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.testng.Assert;
public class TestAuspostApi {
private static RequestSpecification requestSpec;
@BeforeClass
public void testApiSetup()
{
RequestSpecBuilder builder = new RequestSpecBuilder();
String key="7f4e5bc4-ed30-4543-a1bf-a1a26522d889";
builder.addHeader("AUTH-KEY", key);
requestSpec = builder.build();
System.out.println("Api test before class");
}
@Test(groups="API")
@Parameters({ "url_api","from_postcode","to_postcode",
"length","width","height","weight","service_code_regular"})
public void test_calculate_total_delivery_price_with_regual_api(
String url_api,String fp,String tp,
String length,String width, String height,
String weight,String scr)
{
System.out.println("Calculate total delivery price with regular");
RestAssured.basePath=url_api+
"/postage/parcel/domestic/calculate.json?"
+"from_postcode="+fp
+ "&to_postcode="+tp
+ "&length="+length
+ "&width="+width
+ "&height="+height
+ "&weight="+weight
+ "&service_code="+scr;
Response res =
given().spec(requestSpec).log().all()
.contentType(ContentType.JSON)
.when()
.get(RestAssured.basePath)
.then()
.statusCode(200)
.statusLine("HTTP/1.1 200 OK")
.extract().response();
String responseBody = res.asString();
Assert.assertTrue(responseBody.contains("postage_result"));
JsonObject jsonObject = new JsonParser().parse(responseBody).getAsJsonObject();
Assert.assertTrue(jsonObject.isJsonObject());
jsonObject = new JsonParser().parse(jsonObject.get("postage_result").toString()).getAsJsonObject();
Assert.assertTrue(jsonObject.get("total_cost").getAsString().equals("26.90"));
System.out.println("regular cost=>"+jsonObject.get("costs"));
}
@Test(groups="API")
@Parameters({ "url_api","from_postcode","to_postcode",
"length","width","height","weight","service_code_express"})
public void test_calculate_total_delivery_price_with_express_api(String url_api,String fp,String tp,
String length,String width, String height,
String weight,String sce)
{
System.out.println("Calculate total delivery price with express");
RestAssured.basePath=url_api+
"/postage/parcel/domestic/calculate.json?"
+"from_postcode="+fp
+ "&to_postcode="+tp
+ "&length="+length
+ "&width="+width
+ "&height="+height
+ "&weight="+weight
+ "&service_code="+sce;
Response res =
given().spec(requestSpec).log().all()
.contentType(ContentType.JSON)
.when()
.get(RestAssured.basePath)
.then()
.statusCode(200)
.statusLine("HTTP/1.1 200 OK")
.extract().response();
String responseBody = res.asString();
Assert.assertTrue(responseBody.contains("postage_result"));
JsonObject jsonObject = new JsonParser().parse(responseBody).getAsJsonObject();
Assert.assertTrue(jsonObject.isJsonObject());
jsonObject = new JsonParser().parse(jsonObject.get("postage_result").toString()).getAsJsonObject();
Assert.assertTrue(jsonObject.get("total_cost").getAsString().equals("59.70"));
System.out.println("express cost=>"+jsonObject.get("costs"));
}
}
|
package com.shop.errors;
/**
* The general class representing all possible exceptions thrown by Shop.
* Could be extended if needed.
*/
public class ShopException extends Exception {
//TODO: can add additional data if needed
//private String message;
public ShopException(String message) {
super(message);
}
public String getDetailMessage() {
return super.getMessage();
}
}
|
/*
* 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 ejemplointerfaz;
/**
*
* @author Administrador
*/
public class Hospital {
public void mostrarEnfermo(Feliz F){
F.Decirporque();
}
public void mostrarEstornudo(Enfermo E){
E.Estornudar();
}
}
|
/**
*
*/
package c;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import m.SomeDataClass;
import v.Panel1;
import v.Panel2;
import v.Panel3;
import v.Panel4;
import v.Panel5;
/**
* Class description
*
* @author Samuel
*
*/
public class MainGUI {
private JFrame window = new JFrame("SEG Agile Project");
private JPanel topBar; // topmost bar of application
private JPanel contentPane; // panel that holds each of our JPanels, i.e. the content
private JPanel bottomBar; // bottommost bar of application, holds button, textarea
private JButton newPeopleButton;
private JButton newTaskButton;
private JButton dashBoardButton;
private JLabel bottomText;
private JButton refreshButton;
private ArrayList<JPanel> ContentPanels;
private int panelIndex = 0;
private MainButtonController buttonController;
private Panel1 firstPanel;
private Panel3 thirdPanel;
private Panel2 secondPanel;
private Panel4 fourthPanel;
private Panel5 displayPanel;
private JButton helpButton;
/**
* Constructor method for MainGUI. Creates an object of someData.
* This method also sets up MainGUI's user interface.
*
*/
public MainGUI() {
SomeDataClass someData = new SomeDataClass();
//Create panels
firstPanel = new Panel1(someData, this);
secondPanel = new Panel2(someData, this);
thirdPanel = new Panel3(someData, this);
fourthPanel = new Panel4(someData, this);
displayPanel = new Panel5(someData, this);
//peoplePanel = new Panel6(someData, this);
ContentPanels = new ArrayList();
ContentPanels.add(firstPanel);
ContentPanels.add(secondPanel);
ContentPanels.add(thirdPanel);
ContentPanels.add(fourthPanel);
ContentPanels.add(displayPanel);
createWindow();
//Create tabs
topBar = new JPanel();
topBar.setLayout(new FlowLayout(FlowLayout.CENTER));
window.add(topBar, BorderLayout.NORTH);
buttonController = new MainButtonController(this, someData, secondPanel, thirdPanel);
dashBoardButton = new JButton("Dashboard");
topBar.add(dashBoardButton, BorderLayout.WEST);
dashBoardButton.setName("dashboard");
dashBoardButton.addActionListener(buttonController);
dashBoardButton.setEnabled(false);
newTaskButton = new JButton("New Task");
topBar.add(newTaskButton, BorderLayout.WEST);
newTaskButton.setName("new task");
newTaskButton.addActionListener(buttonController);
newPeopleButton = new JButton("Add People");
topBar.add(newPeopleButton, BorderLayout.WEST);
newPeopleButton.setName("add people");
newPeopleButton.addActionListener(buttonController);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
window.add(contentPane, BorderLayout.CENTER);
//Create bottom toolbar
bottomBar = new JPanel();
bottomBar.setLayout(new BorderLayout());
window.add(bottomBar, BorderLayout.SOUTH);
//Bottom toolbar message
bottomText = new JLabel("SEG AGILE PROJECT TEAM JAY", SwingConstants.CENTER);
bottomBar.add(bottomText, BorderLayout.CENTER);
//bottom toolbar help button
helpButton = new JButton("Help");
bottomBar.add(helpButton, BorderLayout.EAST);
helpButton.setName("help");
helpButton.addActionListener(buttonController);
contentPane.add(firstPanel);
render();
}
/**
*This creates the window accordingly to our tastes
*/
public void createWindow(){
window.setSize(1000, 800);
window.setPreferredSize(new Dimension(1000, 800));
window.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
*Allows us to see our frame
*/
public void render(){
window.pack();
window.setVisible(true);
}
/**
* This method allows us to enter the dashboard by setting the according panel index and sets some other buttons to
* As we should not be able to access them while being on the Dahsboard
*/
public void enterDashboard() {
contentPane.remove(ContentPanels.get(panelIndex));
panelIndex = 0;
contentPane.repaint();
contentPane.add(ContentPanels.get(panelIndex));
contentPane.repaint();
window.setVisible(true);
dashBoardButton.setEnabled(false);
newTaskButton.setEnabled(true);
newPeopleButton.setEnabled(true);
}
/**
* This method allows us to enter the Task panel by setting the according panel index and sets some other buttons to
* As we should not be able to access them while being on the Task panel
*/
public void enterNewTask() {
contentPane.remove(ContentPanels.get(panelIndex));
panelIndex = 1;
//contentPane.revalidate();
contentPane.repaint();
contentPane.add(ContentPanels.get(panelIndex));
contentPane.repaint();
window.setVisible(true);
dashBoardButton.setEnabled(true);
newTaskButton.setEnabled(false);
newPeopleButton.setEnabled(true);
}
/**
* This method allows us to enter the People panel by setting the according panel index and sets some other buttons to
* As we should not be able to access them while being on the People panel
*/
public void enterAddPeople() {
contentPane.remove(ContentPanels.get(panelIndex));
panelIndex = 2;
contentPane.repaint();
contentPane.add(ContentPanels.get(panelIndex));
contentPane.repaint();
window.setVisible(true);
dashBoardButton.setEnabled(true);
newTaskButton.setEnabled(true);
newPeopleButton.setEnabled(false);
}
public void enterOther() {
contentPane.remove(ContentPanels.get(panelIndex));
panelIndex = 3;
contentPane.repaint();
contentPane.add(ContentPanels.get(panelIndex));
contentPane.repaint();
window.setVisible(true);
dashBoardButton.setEnabled(true);
newTaskButton.setEnabled(true);
newPeopleButton.setEnabled(true);
}
/**
* This method allows us to display the Manager/planning panel by setting the according panel index and sets some other buttons to
* As we should not be able to access them while being on the Manager panel
*/
public void enterDisplayMgrs() {
contentPane.remove(ContentPanels.get(panelIndex));
panelIndex = 4;
contentPane.repaint();
contentPane.add(ContentPanels.get(panelIndex));
contentPane.repaint();
window.setVisible(true);
dashBoardButton.setEnabled(true);
newTaskButton.setEnabled(true);
newPeopleButton.setEnabled(true);
}
/**
* Sets size of JFrame window, based on passed parameters x and y.
*
* @param x
* @param y
*/
public void setSize(int x, int y) {
window.setSize(x, y);
}
/**
* Sets whether or not JFrame window is resizable, based on boolean passed parameter x.
*
* @param x
*/
public void setResizeable(boolean x) {
window.setResizable(x);
}
/**
* This is an accessor method for firstPanel.
*
* @return firstPanel, (instance of Panel1, extends JPanel).
*/
public Panel1 getPanel1() {
return firstPanel;
}
}
|
package com.baomidou.mybatisplus.samples.quickstart.service;
import com.baomidou.mybatisplus.samples.quickstart.domain.UserDynamic;
/**
* @author wangqinag
* @version 1.0
* @date 2020/6/15 16:39
*/
public interface UserDynamicService {
/**
* 插入动态详情
* @param userDynamic
*/
void addUserDynamic(UserDynamic userDynamic);
}
|
package Lesson1.Fish;
import Lesson1.Interfaces.Swimming;
public class GoldenFish extends Fishes implements Swimming {
public static int fishCount = 0;
public GoldenFish(String name) {
super(name);
}
/* @Override
public void swimm() {
System.out.println("GoldenFish is swimming");
}*/
}
|
package yincheng.gggithub;
import android.app.Application;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import yincheng.gggithub.helper.TypefaceHelper;
/**
* Created by yincheng on 2018/5/25/16:09.
* github:luoyincheng
*/
public class App extends Application {
private static App instance;
public static App getInstance() {
return instance;
}
@Override public void onCreate() {
super.onCreate();
instance = this;
Logger.addLogAdapter(new AndroidLogAdapter());
TypefaceHelper.generateTypeface(this);
}
}
|
/**
* @program: integral_mobile_parent
* @description: 汇总单人月积分插件加分情况
* @author: 14_赵芬
* @create: 2019-09-15 13:45
**/
package com.tfjybj.integral.model;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@NoArgsConstructor
/*
*汇总月积分插件加分情况-赵芬-2019年9月15日13:47:16
*/
public class MonthPluginSumModel {
//用户id
private String userId;
//用户的月积分汇总(代表:净收入,总收入,总支出)
private int SumIntegral;
}
|
package Algorithms;
// http://www.geeksforgeeks.org/dynamic-programming-set-5-edit-distance/
public class EditMiniDP {
static int min(int x, int y, int z) {
return x < y ? (x < z ? x : z) : (y < z ? y : z);
}
static int editDistDP(String str1, String str2, int m, int n) {
int[][] dp = new int[m + 1][n + 1];
for(int i = 0; i <=m; i++) {
for(int j = 0; j <=n; j++) {
if(i == 0)
dp[i][j] = j;
else if(j == 0)
dp[i][j] = i;
else if(str1.charAt(i - 1) == str2.charAt(j - 1))
dp[i][j] = dp[i - 1][j - 1];
else
dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]);
}
}
for(int i = 0; i <= m; i++) {
for(int j = 0; j <= n; j++)
System.out.print(dp[i][j] + " ");
System.out.println();
}
return dp[m][n];
}
public static void main(String[] args) {
String str1 = "mtuday";
String str2 = "saturday";
int op = editDistDP(str1, str2, str1.length(), str2.length());
System.out.println(op);
}
}
|
package JavaSE.OO.duoxianchen;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/*
* 关于定时器应用
* 作用:每隔一段固定的时间执行一段代码
*/
public class TimerTest {
public static void main(String[] args) throws ParseException {
//创建定时器
Timer t=new Timer();
//指定定时任务
t.schedule(new LogTimerTask(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").parse("2020-02-22 16:48:00 000"),10*1000);
}
}
//指定任务
class LogTimerTask extends TimerTask{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date()));
}
}
|
package project.requestDetailsWebapp.service;
public interface RequestDetailsService {
}
|
package com.habiture;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import utils.Utils;
/**
* Created by GawinHsu on 4/20/15.
*/
public class StubQueryGroups extends StubLoginSuccessfully {
private class StubConnection extends MockNetworkConnection {
private InputStream in = null;
@Override
public InputStream getInputStream() {
String packet = "{\n" +
" \"groups\": [\n" +
" {\n" +
" \"goal\": 3, \n" +
" \"url\": \"http://140.124.144.121/Habiture/profile/11145559_786919498044885_2254052047058669334_n.jpg\", \n" +
" \"swear\": \"running\", \n" +
" \"frequency\": 7, \n" +
" \"do_it_time\": 12, \n" +
" \"id\": 189, \n" +
" \"icon\": 0\n" +
" }\n" +
" ]\n" +
"}";
InputStream in = new ByteArrayInputStream(packet.getBytes());
return in;
}
@Override
public void close() {
Utils.closeIO(in);
}
}
@Override
public NetworkConnection openGetGroupsConnection(int uid) {
return new StubConnection();
}
}
|
package petsanctuaryamok;
public interface OilAllSynthetics {
public void oilAllSynthetics();
}
|
package BPTree;
import java.util.concurrent.ThreadLocalRandom;
public class BPTree<Key extends Comparable, Value> {
//https://en.wikibooks.org/wiki/Algorithm_Implementation/Trees/B%2B_tree
//корень дерева
private Node root;
//кол-во строк в блоке
private final int rows_block;
//высота дерева
private int height = 1;
//кол-во строк в индексе
private int cnt = 0;
public BPTree(int n) {
rows_block = n;
root = new LNode();
//первый блок и последний
root.last = true;
} //BPTree
public void insert(Key key, Value value) {
Split result = root.insert(key, value);
if (result != null) {
//разделяем корень на 2 части
//создаем новый корень с сылками на лево и право
INode _root = new INode();
_root.num = 1;
_root.keys[0] = result.key;
_root.children[0] = result.left;
_root.children[1] = result.right;
//уровень текущей ветки = высота предыдущей + 1
_root.level = result.level + 1;
root = _root;
//повышаем счетчик высоты дерева
height++;
}
} //insert
//index scan
public Value indexScan(Key key) {
Node node = root;
//спускаемся по внутренним веткам, пока не дойдем до листа
while (node instanceof BPTree.INode) {
INode inner = (INode) node;
int idx = inner.getLoc(key);
node = inner.children[idx];
}
//спустились до листа
LNode leaf = (LNode) node;
int idx = leaf.getLoc(key);
//нашли ключ элемента в блоке
//если последний элемент, то дополнительно проверим значение
if (idx < leaf.num && leaf.keys[idx].equals(key)) {
return leaf.values[idx];
} else {
return null;
}
} //indexScan
//index min scan
public Value getMin() {
Node node = root;
//спускаемся по внутренним веткам налево, пока не дойдем до листа
while (node instanceof BPTree.INode) {
INode inner = (INode) node;
node = inner.children[0];
}
if( node.num == 0 ) return null;
//спустились до листа
LNode leaf = (LNode) node;
return leaf.values[0];
} //getMin
//index max scan
public Value getMax() {
Node node = root;
//спускаемся по внутренним веткам направо, пока не дойдем до листа
while (node instanceof BPTree.INode) {
INode inner = (INode) node;
node = inner.children [inner.num];
}
if( node.num == 0 ) return null;
//спустились до листа
LNode leaf = (LNode) node;
return leaf.values[leaf.num - 1];
} //getMax
//index range scan - поиск по диапазону
public Value[] rangeScan(Key from_key, Key to_key) {
Node node = root;
//спускаемся по внутренним веткам, пока не дойдем до листа
while (node instanceof BPTree.INode) {
INode inner = (INode) node;
int idx = inner.getLoc(from_key);
node = inner.children[idx];
}
//спустились до листа
LNode leaf = (LNode) node;
int idx = leaf.getLoc(from_key);
//нашли ключ элемента в блоке
if (idx < leaf.num && leaf.keys[idx].compareTo(from_key) >= 0) {
Value[] arr = (Value[]) new Object[cnt];
//двигаемся вправо, пока не найдем правую границу
int cnt_arr = 0;
do {
//стартуем с найденного элемента
for(int i = idx; i < leaf.num; i++) {
if(leaf.keys[i].compareTo(to_key) > 0) {
//возвращаем только нужное число элементов
Value[] _arr = (Value[]) new Object[cnt_arr];
System.arraycopy(arr, 0, _arr, 0, cnt_arr);
arr = null;
return _arr;
}
arr[cnt_arr] = leaf.values[i];
cnt_arr++;
}
//последующие блоки читаем с 0
idx = 0;
leaf = leaf.next;
} while(leaf != null);
Value[] _arr = (Value[]) new Object[cnt_arr];
System.arraycopy(arr, 0, _arr, 0, cnt_arr);
arr = null;
return _arr;
}
return null;
} //rangeScan
//index full scan
public Value[] fullScan() {
Node node = root;
//спускаемся по внутренним веткам направо, пока не дойдем до листа
while (node instanceof BPTree.INode) {
INode inner = (INode) node;
node = inner.children [0];
}
if( node.num == 0 ) return null;
Value[] arr = (Value[]) new Object[cnt];
//спустились до листа
LNode leaf = (LNode) node;
//последовательно идем по листам слева направо
int cnt_arr = 0;
do {
System.arraycopy(leaf.values, 0, arr, cnt_arr, leaf.num);
cnt_arr = cnt_arr + leaf.num;
leaf = leaf.next;
} while(leaf != null);
return arr;
} //fullScan
//blevel - высота дерева -1
public int getBLevel() {
return height - 1;
} //getBLevel
public int getCnt() {
return cnt;
} //getCnt
//фактор кластеризации
//идеально = число строк / число строк в блоке
//плохо = число строк
public int getClusterFactor() {
int cluster_factor = 0;
int prev_block = 0;
int cur_block = 0;
Object arr[] = new Integer[cnt];
arr = fullScan();
for(int i = 0; i < arr.length; i++) {
int k_rowid = (Integer)arr[i];
cur_block = k_rowid / rows_block;
if(prev_block != cur_block) {
cluster_factor++;
}
prev_block = cur_block;
}
return cluster_factor;
} //getClusterFactor
public void dump() {
System.out.println("blevel = " + getBLevel());
System.out.println("cnt = " + getCnt());
System.out.println("min[k] = " + getMin());
System.out.println("max[k] = " + getMax());
System.out.println("--------------------");
root.dump();
System.out.println("--------------------");
}
//абстрактный класс блока: лист или ветвь
abstract class Node {
//кол-во элементов в блоке
protected int num;
//элементы в блоке
protected Key[] keys;
//высота ветви/листа
int level;
//последний блок ветви/листа
boolean last = false;
//поиск индекса элемента в массиве блока
public int getLoc(Key key, boolean is_node) {
//двоичный поиск в порядоченном массиве O=Log2N
int lo = 0;
int hi = num - 1;
//пока левая и правая границы не встретятся
while (lo <= hi) {
//находим середину
int mid = lo + (hi - lo) / 2;
//если элемент меньше середины
if (key.compareTo(keys[mid]) < 0) {
//если текущий элемент больше, а следующий меньше, то возвращаем текущий
if(mid == 0) return 0;
if(mid > 0 && key.compareTo(keys[mid - 1]) > 0) return mid;
//то верхняя граница - 1 = середина
hi = mid - 1;
} else if (key.compareTo(keys[mid]) > 0) {
//если текущий элемент меньше, а следующий больше, то возвращаем следующий
if(mid == num) return mid;
if(mid < num - 1 && key.compareTo(keys[mid + 1]) < 0) return mid + 1;
//если больше, то нижняя граница = середина + 1
lo = mid + 1;
} else {
//иначе нашли
//для ветви возвращаем следующий за найденным элемент, т.к. ссылка идет налево
if(is_node) return mid + 1;
//для листы чисто найденный элемент
return mid;
}
}
return num;
} //getLoc
// возвращает null, если блок не нужно разделять, иначе информация о разделении
abstract public Split insert(Key key, Value value);
abstract public void dump();
} //Node
//листовой блок дерева
class LNode extends Node {
//ссылки на реальные значения - строки таблицы
final Value[] values = (Value[]) new Object[rows_block];
//ссылка на следующий блок
LNode next;
public LNode() {
keys = (Key[]) new Comparable[rows_block];
level = 0;
} //LNode
public int getLoc(Key key) {
return getLoc(key, false);
} //getLoc
//вставка элемента в листовой блок
public Split insert(Key key, Value value) {
// находим место для вставки
int i = getLoc(key);
//место вставки последний элемент, блок необходимо разбить на 2 части
if (this.num == rows_block) {
/*
* Пример 50/50:
*
3
1 2 3 4 5
---
mid = 5/2 = 2
snum = 4 - 2 = 2 -- уходит направо
mid=2 --уходит налево
keys[mid]=mid[3] = 3 --средний элемент, уходит наверх
* */
//делим блок на 90/10 поумолчанию
int mid = rows_block;
//если вставка идет не в конец
if(!this.last || i < mid) {
//то делим блок 50/50
mid = (rows_block + 1) / 2;
}
//mid = (rows_block + 1) / 2;
//кол-во элементов в правой части
int sNum = this.num - mid;
//новый правый листовой блок
LNode sibling = new LNode();
sibling.num = sNum;
//перемещаем в него половину элементов
System.arraycopy(this.keys, mid, sibling.keys, 0, sNum);
System.arraycopy(this.values, mid, sibling.values, 0, sNum);
//делим ровно на полам, все элементы разойдутся налево или направо
this.num = mid;
//если сплитится последний блок, то помечаем последним правый
if(this.last) {
this.last = false;
sibling.last = true;
}
//позиция в левом блоке
if (i < mid) {
this.insertNonfull(key, value, i);
} else {
//или в правой
sibling.insertNonfull(key, value, i - mid);
}
//информируем блок ветви о разделении: {значение разделения, левый блок, правый блок, 0 уровень листа}
//элемент разделения берем из правой части
Split result = new Split(sibling.keys[0], this, sibling, level);
//связываем текущий блок со следующим
sibling.next = this.next;
this.next = sibling;
return result;
} else {
//блок не полон, вставляем элемент в i мето
this.insertNonfull(key, value, i);
return null;
}
}
//вставка элемента в неполный листовой блок
private void insertNonfull(Key key, Value value, int idx) {
//смещаем все элементы массивов правее idx на 1 элемент
System.arraycopy(keys, idx, keys, idx + 1, num - idx);
System.arraycopy(values, idx, values, idx + 1, num - idx);
//в освободившееся место вставляем элемент
keys[idx] = key;
values[idx] = value;
//число элементов в блоке
num++;
//всего элементов в индексе
cnt++;
}
public void dump() {
if(last) {
System.out.println("(last):");
}
for (int i = 0; i < num; i++) {
System.out.println(keys[i]);
}
}
} //LNode
//класс блока ветви
class INode extends Node {
final Node[] children = new BPTree.Node[rows_block + 1];
public INode() {
keys = (Key[]) new Comparable[rows_block];
} //INode
//поиск индекса для вставки в блоке-ветви
public int getLoc(Key key) {
return getLoc(key, true);
} //getLoc
//вставка элемента в ветвь
public Split insert(Key key, Value value) {
/*
* Упрощенный вариант сплита, когда разделение идет сверху вниз,
* что может привести к преждевременному росту дерева и как следствие дисковых чтений в бд.
* В реальности разделение должно идти снизу вверх - это минимизирует рост дерева.
*
* */
//число элементов в блоке достигло предела - разделяем
if (this.num == rows_block) {
/*
* Пример:
*
2
1 3 4 (3 max)
3
1 2 4 5 (4 max)
---
mid = 5/2 = 2
snum = 4 - 2 = 2 -- уходит направо
mid-1=1 --уходит налево
keys[mid-1]=mid[1] = 2 --средний элемент, уходит наверх
* */
//середина
int mid = (rows_block + 1) / 2;
//создаем блок справа
int sNum = this.num - mid;
INode sibling = new INode();
sibling.num = sNum;
sibling.level = this.level;
//копируем в него половину значений
System.arraycopy(this.keys, mid, sibling.keys, 0, sNum);
//копируем дочерние элементы +1(?)
System.arraycopy(this.children, mid, sibling.children, 0, sNum + 1);
//в левой части будет -1 элемент, он уходит на верхний уровень
this.num = mid - 1;
//передаем информацию о разделении выше: {средний элемент, левая, правая ветвь}
Split result = new Split(this.keys[mid - 1], this, sibling, this.level);
//если элемент меньше середины, то вставляем в левую чать
if (key.compareTo(result.key) < 0) {
this.insertNonfull(key, value);
} else {
//иначе в правую
sibling.insertNonfull(key, value);
}
//информируем вышестоящуюю ветвь о разделении, может ее тоже надо будет разделить
return result;
} else {
//место под разбиение нижних еще есть - вставляем
this.insertNonfull(key, value);
return null;
}
} //insert
private void insertNonfull(Key key, Value value) {
//ищем индекс для вставки
int idx = getLoc(key);
//рекурсивный вызов для нижележайшей ветви
Split result = children[idx].insert(key, value);
//нижний блок пришлось разбить на 2 части
if (result != null) {
//вставка в крайнее правое место
if (idx == num) {
keys[idx] = result.key;
// на нашем уровен становится 2 элемета-ветви
//текущий будет ссылаться на левую чать разделенной дочерней части
//а новый элемент снизу - на правую
children[idx] = result.left;
children[idx + 1] = result.right;
num++;
} else {
//вставка в середину массива
//смещаем все элементы вправа на 1 позицию
System.arraycopy(keys, idx, keys, idx + 1, num - idx);
System.arraycopy(children, idx, children, idx + 1, num - idx + 1);
//аналогично
children[idx] = result.left;
children[idx + 1] = result.right;
keys[idx] = result.key;
num++;
}
} // result != null
} //insertNonfull
public void dump() {
for (int i = 0; i < num; i++) {
children[i].dump();
for(int j = 0; j < level; j++) System.out.print(" . ");
System.out.println("> " + keys[i] + " ("+num+")");
}
children[num].dump();
}
} //INode
//структура с информацией о разделении: значение разделения, левая и правая часть и уровень ветви
class Split {
public final Key key;
public final Node left;
public final Node right;
public final int level;
public Split(Key k, Node l, Node r, int h) {
key = k;
left = l;
right = r;
level = h;
}
} //Split
public static void main(String[] args) {
int rows_on_block = 3;
BPTree t = new BPTree(rows_on_block);
/*for(int i = 0; i <= 99; i++) {
t.insert(i, i);
}*/
for(int i = 99; i >= 0; i--) {
t.insert(i, i);
}
/*for(int i = 99; i >= 0; i--) {
t.insert(ThreadLocalRandom.current().nextInt(0, 100), i);
}*/
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13
/*Integer arr_tst[] = {2, 6, 3, 5, 1, 7, 8, 0, 27, 17, 99, 13, 1, 7};
for(int i = 0; i < arr_tst.length; i++) {
t.insert(arr_tst[i], i);
}*/
t.dump();
System.out.println("indexScan (5) = " + t.indexScan(5));
System.out.println("indexScan (6) = " + t.indexScan(6));
System.out.println("indexScan (4) = " + t.indexScan(4));
System.out.println("indexScan (1) = " + t.indexScan(1));
System.out.println("indexScan (99) = " + t.indexScan(99));
System.out.println("indexScan (100) = " + t.indexScan(100));
Object arr[] = new Integer[t.getCnt()];
arr = t.fullScan();
System.out.print("fullScan = ");
for(int i = 0; i < arr.length; i++) {
System.out.print((Integer)arr[i] + ", ");
}
System.out.println(" ");
System.out.println("cluster_factor = " + t.getClusterFactor());
arr = t.rangeScan(2, 7);
System.out.print("rangeScan(2,7) = ");
for(int i = 0; i < arr.length; i++) {
System.out.print((Integer)arr[i] + ", ");
}
} //main
} //BPTree
|
package com.droie.sprinkle;
import java.util.Deque;
import java.util.stream.Stream;
public class Floor {
private int floorLevel;
private Deque<Passenger> personQueue;
public Floor(int floorLevel, Deque<Passenger> personQueue) {
this.floorLevel = floorLevel;
this.personQueue = personQueue;
}
public Stream<Passenger> personsGoingToOtherFloor() {
return personQueue.stream().filter(passenger -> floorLevel != passenger.getDestinationFloor());
}
public Stream<Passenger> personsGoingUpwards() {
return personQueue.stream().filter(passenger -> floorLevel < passenger.getDestinationFloor());
}
public Stream<Passenger> personsGoingDownwards() {
return personQueue.stream().filter(passenger -> floorLevel > passenger.getDestinationFloor());
}
public int getFloorLevel() {
return floorLevel;
}
public Deque<Passenger> getPersonQueue() {
return personQueue;
}
@Override
public String toString() {
return String.valueOf(floorLevel);
}
}
|
package com.locadoraveiculosweb.controller;
import static com.locadoraveiculosweb.constants.ServiceConstants.FABRICANTE;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import org.omnifaces.cdi.ViewScoped;
import com.locadoraveiculosweb.modelo.dtos.FabricanteDto;
import com.locadoraveiculosweb.service.FabricanteService;
import com.locadoraveiculosweb.service.Service;
import lombok.Getter;
import lombok.Setter;
@Named
@ViewScoped
public class CadastroFabricanteBean extends BaseBeanController<FabricanteDto> {
private static final long serialVersionUID = 1L;
@Inject
private FabricanteService cadastroFabricanteSerivice;
@Getter @Setter
private FabricanteDto fabricante = new FabricanteDto();
@Override
@PostConstruct
public void initializer(){
clean();
}
@Override
protected Service<FabricanteDto> getService() {
return cadastroFabricanteSerivice;
}
@Override
protected FabricanteDto getViewObject() {
return fabricante;
}
@Override
protected void clean() {
fabricante = new FabricanteDto();
}
@Override
protected String getNameMessage() {
return FABRICANTE;
}
@Override
protected String getViewObjectPropertyMsg() {
return fabricante.getNome();
}
@Override
protected void setViewObject(FabricanteDto dto) {
setFabricante(dto);
}
}
|
package itemsApplication;
import DashBoardApp.SideBarApp;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
public class ItemsLeft extends VBox{
private Button exitBtn, newItemBtn;
//Constructor
public ItemsLeft() {
//Children nodes
//exit button
exitBtn = new Button("Retour");
//Action
SideBarApp.toggleItemsAction(exitBtn);
//new Item Btn
newItemBtn = new Button("Ajouter un service/Bien");
//Action
ItemsApp.newItemAction(newItemBtn);
//Seperator region
Region seperator = new Region();
//Style
seperator.setPrefHeight(200);
// Adding children nodes
getChildren().addAll(exitBtn, seperator, newItemBtn);
//Styling layout
setPadding(new Insets(20));
}
// getters
public Button getExitBtn() {
return exitBtn;
}
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package net.nan21.dnet.module.bd.domain.impl.attr;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PrePersist;
import javax.persistence.QueryHint;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import net.nan21.dnet.core.domain.impl.AbstractTypeWithCode;
import net.nan21.dnet.module.bd.domain.impl.attr.AttributeSet;
import org.eclipse.persistence.config.HintValues;
import org.eclipse.persistence.config.QueryHints;
/**
* Attribute sub-group definition. A second level within an attribute group.
* In case of many attributes in a group, use sub-groups to provide a better overview.
*/
@NamedQueries({
@NamedQuery(name = AttributeSubSet.NQ_FIND_BY_CODE, query = "SELECT e FROM AttributeSubSet e WHERE e.clientId = :clientId and e.attributeSet = :attributeSet and e.code = :code", hints = @QueryHint(name = QueryHints.BIND_PARAMETERS, value = HintValues.TRUE)),
@NamedQuery(name = AttributeSubSet.NQ_FIND_BY_CODE_PRIMITIVE, query = "SELECT e FROM AttributeSubSet e WHERE e.clientId = :clientId and e.attributeSet.id = :attributeSetId and e.code = :code", hints = @QueryHint(name = QueryHints.BIND_PARAMETERS, value = HintValues.TRUE))})
@Entity
@Table(name = AttributeSubSet.TABLE_NAME, uniqueConstraints = {@UniqueConstraint(name = AttributeSubSet.TABLE_NAME
+ "_UK1", columnNames = {"CLIENTID", "ATTRIBUTESET_ID", "CODE"})})
public class AttributeSubSet extends AbstractTypeWithCode {
public static final String TABLE_NAME = "BD_ATTRSUBSET";
private static final long serialVersionUID = -8865917134914502125L;
/**
* Named query find by unique key: Code.
*/
public static final String NQ_FIND_BY_CODE = "AttributeSubSet.findByCode";
/**
* Named query find by unique key: Code using the ID field for references.
*/
public static final String NQ_FIND_BY_CODE_PRIMITIVE = "AttributeSubSet.findByCode_PRIMITIVE";
@Column(name = "SEQUENCENO", precision = 10)
private Integer sequenceNo;
@ManyToOne(fetch = FetchType.LAZY, targetEntity = AttributeSet.class)
@JoinColumn(name = "ATTRIBUTESET_ID", referencedColumnName = "ID")
private AttributeSet attributeSet;
public Integer getSequenceNo() {
return this.sequenceNo;
}
public void setSequenceNo(Integer sequenceNo) {
this.sequenceNo = sequenceNo;
}
public AttributeSet getAttributeSet() {
return this.attributeSet;
}
public void setAttributeSet(AttributeSet attributeSet) {
if (attributeSet != null) {
this.__validate_client_context__(attributeSet.getClientId());
}
this.attributeSet = attributeSet;
}
@PrePersist
public void prePersist() {
super.prePersist();
}
}
|
package com.mahadihasan.mc.patient;
import java.util.ArrayList;
/**
*
* @author MAHADI HASAN NAHID
*/
public class MedicalRecord {
private ArrayList<String> date;
private ArrayList<String> disease;
private ArrayList<String> medicine;
public MedicalRecord(ArrayList<String> d,
ArrayList<String> dis, ArrayList<String> medi) {
setDate(d);
setDisease(dis);
setMedicine(medi);
}
private void setDate(ArrayList<String> dt) {
date = dt;
}
public ArrayList<String> getDate() {
return date;
}
private void setDisease(ArrayList<String> dis) {
disease = dis;
}
public ArrayList<String> getDisease() {
return disease;
}
private void setMedicine(ArrayList<String> medi) {
medicine = medi;
}
public ArrayList<String> getMedicine() {
return medicine;
}
}
|
package com.dezzmeister.cryptopix.main.dialogs;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import com.dezzmeister.cryptopix.R;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
public class UnsupportedAlgorithmDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
final Bundle bundle = getArguments();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.unsupported_algorithm_dialog)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// TODO: Start activity to encode secret message
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// TODO: Do nothing
}
});
return builder.create();
}
}
|
package com.sendgrid.helpers.mail.objects;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
public class ContentVerifier {
private static final List<Pattern> FORBIDDEN_PATTERNS = Collections.singletonList(
Pattern.compile(".*SG\\.[a-zA-Z0-9(-|_)]*\\.[a-zA-Z0-9(-|_)]*.*")
);
static void verifyContent(String content) {
for (Pattern pattern : FORBIDDEN_PATTERNS) {
if (pattern.matcher(content).matches()) {
throw new IllegalArgumentException("Found a Forbidden Pattern in the content of the email");
}
}
}
}
|
package com.example.dany.phonebook.utils;
/**
* Created by Dany on 13.10.2018 г..
*/
public class Constants {
public static final String DATABASE_NAME = "phone_book_db";
public static final String COUNTRY_TABLE = "country";
public static final String CONTACT_TABLE = "contact";
public static final String COUNTRY_ID = "country_id";
public static final String COUNTRY_NAME = "country_name";
public static final String COUNTRY_CODE = "country_code";
public static final String CONTACT_ID = "contact_id";
public static final String CONTACT_FIRST_NAME = "first_name";
public static final String CONTACT_LAST_NAME = "last_name";
public static final String CONTACT_EMAIL = "email";
public static final String CONTACT_SEX = "sex";
public static final String CONTACT_PHONE = "phone";
public static final String MALE = "Male";
public static final String FEMALE = "Female";
public static final String APPLY_FILTER_FRAGMENT = "applyFilterFragment";
}
|
package com.example.spring.data.jpa.soft.delete.sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDataJpaSoftDeleteSampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataJpaSoftDeleteSampleApplication.class, args);
}
}
|
package com.seemoreinteractive.virtualshot.helper;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import com.gmail.yuyang226.flickr.Flickr;
import com.gmail.yuyang226.flickr.auth.Permission;
import com.gmail.yuyang226.flickr.oauth.OAuthToken;
import com.seemoreinteractive.virtualshot.FlickrActivity;
import com.seemoreinteractive.virtualshot.utils.Constants;
public class GetFlickrAuth extends AsyncTask<Void, Integer, String> {
private static final Uri OAUTH_CALLBACK_URI = Uri.parse(Constants.FLICKR_CALLBACK_SCHEME + "://oauth");
private Activity mContext;
public GetFlickrAuth(Activity context) {
super();
this.mContext = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params) {
try {
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthToken oauthToken = f.getOAuthInterface().getRequestToken(
OAUTH_CALLBACK_URI.toString());
saveTokenSecrent(oauthToken.getOauthTokenSecret());
URL oauthUrl = f.getOAuthInterface().buildAuthenticationUrl(
Permission.WRITE, oauthToken);
return oauthUrl.toString();
} catch (Exception e) {
return "error:" + e.getMessage();
}
}
private void saveTokenSecrent(String tokenSecret) {
FlickrActivity act = (FlickrActivity) mContext;
act.saveOAuthToken(null, null, null, tokenSecret);
}
@Override
protected void onPostExecute(String result) {
Log.i("Trends", "OAuthTask onPost Executed.");
if (result != null && !result.startsWith("error")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(result));
mContext.startActivity(intent);
}
}
}
|
package ec.com.yacare.y4all.activities.evento;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import ec.com.yacare.y4all.activities.DatosAplicacion;
import ec.com.yacare.y4all.activities.R;
import ec.com.yacare.y4all.adapter.SectionedGridRecyclerViewAdapter;
import ec.com.yacare.y4all.adapter.SimpleAdapter;
import ec.com.yacare.y4all.lib.dto.Evento;
import ec.com.yacare.y4all.lib.sqllite.EventoDataSource;
import ec.com.yacare.y4all.lib.util.AudioQueu;
import ec.com.yacare.y4all.lib.util.EndlessRecyclerViewScrollListener;
public class EventosActivity extends AppCompatActivity {
private DatosAplicacion datosAplicacion;
private Typeface fontRegular;
private Button btnVisitas, btnFotos, btnBuzon, btnSensor;
public ArrayList<Evento> eventoCol;
protected static final int PAGESIZE = 20;
private int paginacionActual = 0;
private RecyclerView listEvento;
private SimpleAdapter mAdapter;
public int tabActivo = 0;
private EndlessRecyclerViewScrollListener scrollListener;
private SectionedGridRecyclerViewAdapter mSectionedAdapter;
private SectionedGridRecyclerViewAdapter.Section[] dummy;
private List<SectionedGridRecyclerViewAdapter.Section> sections;
private String fecha;
private int i;
public static final int REQUEST_DETALLE_VISITA = 0;
public Boolean multipleSelection = false;
public ArrayList<Evento> eventoSeleccionadoCol = new ArrayList<>();
private Integer numeroColumnas;
private GridLayoutManager gridLayoutManager;
public ImageButton fabEliminarSeleccion, fabSalir;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_evento_paginada);
datosAplicacion = (DatosAplicacion) getApplicationContext();
datosAplicacion.setEventosActivity(EventosActivity.this);
numeroColumnas = 3;
if(isScreenLarge()) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
numeroColumnas = 4;
}
} else {
AudioQueu.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
btnVisitas = (Button) findViewById(R.id.btnVisitas);
btnFotos = (Button) findViewById(R.id.btnFotos);
btnBuzon = (Button) findViewById(R.id.btnBuzon);
btnSensor = (Button) findViewById(R.id.btnSensor);
listEvento = (RecyclerView) findViewById(R.id.listEvento);
listEvento.setHasFixedSize(true);
fabEliminarSeleccion = (ImageButton) findViewById(R.id.fabEliminarSeleccion);
fabEliminarSeleccion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(Evento evento: eventoSeleccionadoCol){
File fileVideo = new File(evento.getVideoBuzon());
if (fileVideo.exists()) {
fileVideo.delete();
}
fileVideo = new File(evento.getVideoPuerta());
if (fileVideo.exists()) {
fileVideo.delete();
}
fileVideo = new File(evento.getVideoInicial());
if (fileVideo.exists()) {
fileVideo.delete();
}
fileVideo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Y4Home/" + evento.getId() + ".jpg");
if (fileVideo.exists()) {
fileVideo.delete();
}
EventoDataSource datasource = new EventoDataSource(getApplicationContext());
datasource.open();
datasource.deleteEvento(evento.getId());
datasource.close();
}
paginacionActual = 0;
EventoDataSource datasource = new EventoDataSource(getApplicationContext());
datasource.open();
if(tabActivo == 0){
eventoCol = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('TIMBRAR','BUZON')", datosAplicacion.getEquipoSeleccionado().getId());
}else if(tabActivo == 1){
eventoCol = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('FOTO')", datosAplicacion.getEquipoSeleccionado().getId());
}else if(tabActivo == 2){
eventoCol = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('BUZON')", datosAplicacion.getEquipoSeleccionado().getId());
}else{
eventoCol = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('PUERTA')", datosAplicacion.getEquipoSeleccionado().getId());
}
datasource.close();
cargarListaPrimeraVez();
fabEliminarSeleccion.setVisibility(View.GONE);
}
});
fabSalir = (ImageButton) findViewById(R.id.fabSalir);
fabSalir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
gridLayoutManager = new GridLayoutManager(EventosActivity.this, numeroColumnas);
listEvento.setLayoutManager(gridLayoutManager);
fontRegular = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
btnVisitas.setTypeface(fontRegular);
btnFotos.setTypeface(fontRegular);
btnBuzon.setTypeface(fontRegular);
btnSensor.setTypeface(fontRegular);
RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
itemAnimator.setAddDuration(1000);
itemAnimator.setRemoveDuration(1000);
listEvento.setItemAnimator(itemAnimator);
scrollListener = new EndlessRecyclerViewScrollListener(gridLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
Log.d("paginar","paginar");
paginacionActual = paginacionActual + 1;
ArrayList<Evento> eventoCol2 = null;
EventoDataSource datasource = new EventoDataSource(getApplicationContext());
datasource.open();
if(tabActivo == 0){
eventoCol2 = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('TIMBRAR','BUZON')", datosAplicacion.getEquipoSeleccionado().getId());
}else if(tabActivo == 1){
eventoCol2 = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('FOTO')", datosAplicacion.getEquipoSeleccionado().getId());
}else if(tabActivo == 2){
eventoCol2 = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('BUZON')", datosAplicacion.getEquipoSeleccionado().getId());
}else{
eventoCol2 = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('PUERTA')", datosAplicacion.getEquipoSeleccionado().getId());
}
datasource.close();
actualizarLista(eventoCol2);
}
};
listEvento.addOnScrollListener(scrollListener);
btnVisitas.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tabActivo != 0) {
tabActivo = 0;
paginacionActual = 0;
cargarEventoVisitas();
}
}
});
btnFotos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tabActivo != 1) {
tabActivo = 1;
paginacionActual = 0;
EventoDataSource datasource = new EventoDataSource(getApplicationContext());
datasource.open();
eventoCol = datasource.getPaginaEventosTipoEvento(0, PAGESIZE, "('FOTO')", datosAplicacion.getEquipoSeleccionado().getId());
datasource.close();
cargarListaPrimeraVez();
}
}
});
btnBuzon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tabActivo != 2) {
tabActivo = 2;
paginacionActual = 0;
EventoDataSource datasource = new EventoDataSource(getApplicationContext());
datasource.open();
eventoCol = datasource.getPaginaEventosTipoEvento(0, PAGESIZE, "('BUZON')", datosAplicacion.getEquipoSeleccionado().getId());
datasource.close();
cargarListaPrimeraVez();
}
}
});
btnSensor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tabActivo != 3) {
tabActivo = 3;
paginacionActual = 0;
cargarEventoPuerta();
}
}
});
cargarEventoVisitas();
if(isScreenLarge()) {
onConfigurationChanged(getResources().getConfiguration());
}
}
public Boolean orientacionPortrait = false;
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
if(isScreenLarge()) {
numeroColumnas = 4;
}
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
if(isScreenLarge()) {
numeroColumnas = 3;
}
}
gridLayoutManager = new GridLayoutManager(EventosActivity.this, numeroColumnas);
gridLayoutManager.setSpanSizeLookup(onSpanSizeLookup);
dummy = new SectionedGridRecyclerViewAdapter.Section[sections.size()];
mSectionedAdapter = new
SectionedGridRecyclerViewAdapter(EventosActivity.this, R.layout.evento_section, R.id.dia, listEvento, mAdapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
listEvento.setAdapter(mSectionedAdapter);
}
GridLayoutManager.SpanSizeLookup onSpanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if(isScreenLarge()) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
return 4;
}else{
return 3;
}
}
return 3;
}
};
private void cargarListaPrimeraVez() {
fabEliminarSeleccion.setVisibility(View.GONE);
mAdapter = new SimpleAdapter(EventosActivity.this, eventoCol, EventosActivity.this);
sections = new ArrayList<SectionedGridRecyclerViewAdapter.Section>();
fecha = "";
i = 0;
for (Evento evento : eventoCol) {
if (fecha.equals("") || !fecha.equals(evento.getFecha().substring(0, 10))) {
sections.add(new SectionedGridRecyclerViewAdapter.Section(i, evento.getFecha().substring(0, 10)));
fecha = evento.getFecha().substring(0, 10);
}
i++;
}
dummy = new SectionedGridRecyclerViewAdapter.Section[sections.size()];
mSectionedAdapter = new
SectionedGridRecyclerViewAdapter(EventosActivity.this, R.layout.evento_section, R.id.dia, listEvento, mAdapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
listEvento.setAdapter(mSectionedAdapter);
// listEvento.addOnScrollListener(scrollListener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
paginacionActual = 0;
EventoDataSource datasource = new EventoDataSource(getApplicationContext());
datasource.open();
if(tabActivo == 0){
eventoCol = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('TIMBRAR','BUZON')", datosAplicacion.getEquipoSeleccionado().getId());
}else if(tabActivo == 1){
eventoCol = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('FOTO')", datosAplicacion.getEquipoSeleccionado().getId());
}else if(tabActivo == 2){
eventoCol = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('BUZON')", datosAplicacion.getEquipoSeleccionado().getId());
}else{
eventoCol = datasource.getPaginaEventosTipoEvento(PAGESIZE * paginacionActual, PAGESIZE, "('PUERTA')", datosAplicacion.getEquipoSeleccionado().getId());
}
datasource.close();
cargarListaPrimeraVez();
fabEliminarSeleccion.setVisibility(View.GONE);
listEvento.addOnScrollListener(scrollListener);
}
private void actualizarLista(ArrayList<Evento> eventoCol2) {
for(Evento evento: eventoCol2){
if(fecha.equals("") || !fecha.equals(evento.getFecha().substring(0,10))){
sections.add(new SectionedGridRecyclerViewAdapter.Section(i, evento.getFecha().substring(0,10)));
fecha = evento.getFecha().substring(0,10);
}
i++;
}
eventoCol.addAll(eventoCol2);
mSectionedAdapter.setSections(sections.toArray(dummy));
mSectionedAdapter.notifyDataSetChanged();
}
private void cargarEventoPuerta() {
EventoDataSource datasource = new EventoDataSource(getApplicationContext());
datasource.open();
eventoCol = datasource.getPaginaEventosTipoEvento(0, PAGESIZE, "('PUERTA')", datosAplicacion.getEquipoSeleccionado().getId());
datasource.close();
cargarListaPrimeraVez();
}
public void actualizarLista(){
runOnUiThread(new Runnable() {
@Override
public void run() {
mSectionedAdapter.notifyDataSetChanged();
}
});
}
private void cargarEventoVisitas() {
EventoDataSource datasource = new EventoDataSource(getApplicationContext());
datasource.open();
eventoCol = datasource.getPaginaEventosTipoEvento(0, PAGESIZE, "('TIMBRAR','BUZON')", datosAplicacion.getEquipoSeleccionado().getId());
datasource.close();
cargarListaPrimeraVez();
}
public boolean isScreenLarge() {
final int screenSize = getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK;
return screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE
|| screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
@Override
protected void onDestroy() {
super.onDestroy();
datosAplicacion.setEventosActivity(null);
}
}
|
package com.company.bank.domain;
public enum Swift {
BREXPLPWMUL("MBank"),
BPKOPLPW("PKO BP"),
PLPK0PL("Pekao s.a.");
private final String text;
Swift(String text) {
this.text = text;
}
@Override
public String toString() {
return text;
}
}
|
/* 1: */ package com.kaldin.user.adminprofile.action;
/* 2: */
/* 3: */ import com.kaldin.user.register.dao.impl.SettingsDAO;
/* 4: */ import com.kaldin.user.register.dto.RegisterDTO;
/* 5: */ import com.kaldin.user.register.form.SettingForm;
/* 6: */ import javax.servlet.http.HttpServletRequest;
/* 7: */ import javax.servlet.http.HttpServletResponse;
/* 8: */ import javax.servlet.http.HttpSession;
/* 9: */ import org.apache.struts.action.Action;
/* 10: */ import org.apache.struts.action.ActionForm;
/* 11: */ import org.apache.struts.action.ActionForward;
/* 12: */ import org.apache.struts.action.ActionMapping;
/* 13: */
/* 14: */ public class SettingAction
/* 15: */ extends Action
/* 16: */ {
/* 17: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
/* 18: */ {
/* 19:20 */ SettingForm settingForm = (SettingForm)form;
/* 20:21 */ SettingsDAO settingsDAO = new SettingsDAO();
/* 21:22 */ RegisterDTO registerDTO = null;
/* 22: */
/* 23:24 */ int companyId = 0;
/* 24:25 */ if (request.getSession().getAttribute("CompanyId") != null) {
/* 25:26 */ companyId = ((Integer)request.getSession().getAttribute("CompanyId")).intValue();
/* 26: */ }
/* 27:29 */ if (settingForm.getOperation().equals("save"))
/* 28: */ {
/* 29:30 */ settingsDAO.saveSettings(companyId, settingForm);
/* 30:31 */ settingForm.setOperation("");
/* 31: */ }
/* 32: */ else
/* 33: */ {
/* 34:33 */ settingsDAO.getSettings(companyId, settingForm);
/* 35: */ }
/* 36:36 */ request.setAttribute("showCandidateResult", settingForm.getShowCandidateResult());
/* 37: */
/* 38:38 */ return mapping.findForward("success");
/* 39: */ }
/* 40: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.user.adminprofile.action.SettingAction
* JD-Core Version: 0.7.0.1
*/
|
package lesson7;
import lesson6.Order;
import java.util.Date;
public class DemoHomeWork {
public static void main(String[] args) {
DemoHomeWork homeWork = new DemoHomeWork();
homeWork.createOrder();
homeWork.createOrderAndCallMethods();
System.out.println(homeWork.createOrder().price);
System.out.println(homeWork.createOrder().dateCreated);
System.out.println(homeWork.createOrder().isConfirmed);
System.out.println(homeWork.createOrder().dateConfirmed);
System.out.println(homeWork.createOrder().city);
System.out.println(homeWork.createOrder().country);
System.out.println(homeWork.createOrder().type);
System.out.println("");
System.out.println(homeWork.createOrder().confirmOrder());
System.out.println(homeWork.createOrder().checkPrice());
System.out.println(homeWork.createOrder().isValidType());
System.out.println("");
System.out.println(homeWork.createOrderAndCallMethods().price);
System.out.println(homeWork.createOrderAndCallMethods().dateCreated);
System.out.println(homeWork.createOrderAndCallMethods().isConfirmed);
System.out.println(homeWork.createOrderAndCallMethods().dateConfirmed);
System.out.println(homeWork.createOrderAndCallMethods().city);
System.out.println(homeWork.createOrderAndCallMethods().country);
System.out.println(homeWork.createOrderAndCallMethods().type);
System.out.println("");
System.out.println(homeWork.createOrderAndCallMethods().confirmOrder());
System.out.println(homeWork.createOrderAndCallMethods().checkPrice());
System.out.println(homeWork.createOrderAndCallMethods().isValidType());
}
public Order createOrder() {
return new Order(100, new Date(), false, null, "Dnepr", "Ukraine", "Buy");
}
public Order createOrderAndCallMethods() {
Order otherOrder = new Order();
otherOrder.price = 100;
otherOrder.dateCreated = new Date();
otherOrder.isConfirmed = true;
otherOrder.dateConfirmed = new Date();
otherOrder.city = "Kiev";
otherOrder.country = "Ukraine";
otherOrder.type = "SomeValue";
otherOrder.confirmOrder();
otherOrder.checkPrice();
otherOrder.isValidType();
return otherOrder;
}
}
|
package ru.netology.manager;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import ru.netology.comparator.IssueCountCommentsComparator;
import ru.netology.comparator.IssueCreatedTimeComparator;
import ru.netology.comparator.IssueUpdatedTimeComparator;
import ru.netology.domain.Issue;
import ru.netology.domain.State;
import ru.netology.exception.NotFoundException;
import java.util.ArrayList;
import java.util.HashSet;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class IssueManagerEmptyRepositoryTest {
private IssueManager manager = new IssueManager();
HashSet<Integer> assigneesId = new HashSet<>();
HashSet<String> labels = new HashSet<>();
HashSet<Integer> projectsId = new HashSet<>();
@Nested
public class FilterAndFindTest{
@Test
void findOpenIssuesTest() {
ArrayList<Issue> actual = manager.findOpenIssues();
ArrayList<Issue> expected = new ArrayList<>();
assertEquals(actual, expected);
}
@Test
void findClosedIssuesTest() {
ArrayList<Issue> actual = manager.findClosedIssues();
ArrayList<Issue> expected = new ArrayList<>();
assertEquals(actual, expected);
}
@Test
void filterByAuthorTest() {
ArrayList<Issue> actual = manager.filterByAuthor(14);
ArrayList<Issue> expected = new ArrayList<>();
assertEquals(actual, expected);
}
@Test
void filterByLabelTest() {
ArrayList<Issue> actual = manager.filterByLabel("Label 10");
ArrayList<Issue> expected = new ArrayList<>();
assertEquals(actual, expected);
}
@Test
void filterByAssigneeTest() {
ArrayList<Issue> actual = manager.filterByAssignee(30);
ArrayList<Issue> expected = new ArrayList<>();
assertEquals(actual, expected);
}
}
@Nested
public class SortTest{
@Test
void sortByCreatedTimeTest() {
IssueCreatedTimeComparator comparator = new IssueCreatedTimeComparator();
ArrayList<Issue> actual = manager.sort(comparator);
ArrayList<Issue> expected = new ArrayList<>();
assertEquals(actual, expected);
}
@Test
void sortByUpdatedTimeTest() {
IssueUpdatedTimeComparator comparator = new IssueUpdatedTimeComparator();
ArrayList<Issue> actual = manager.sort(comparator);
ArrayList<Issue> expected = new ArrayList<>();
assertEquals(actual, expected);
}
@Test
void sortByCountCommentsTest() {
IssueCountCommentsComparator comparator = new IssueCountCommentsComparator();
ArrayList<Issue> actual = manager.sort(comparator);
ArrayList<Issue> expected = new ArrayList<>();
assertEquals(actual, expected);
}
}
@Nested
public class AddTest{
@Test
void addIssueTest(){
Issue issue = new Issue(1, "title 1", "test 1", 11, assigneesId, labels, projectsId, 1, 1, 4);
manager.add(issue);
ArrayList<Issue> actual = manager.findAll();
ArrayList<Issue> expected = new ArrayList<>();
expected.add(issue);
assertEquals(actual, expected);
}
}
@Nested
public class UpdateIssueTest{
@Test
void updateIssueByIdTest() {
assertThrows(NotFoundException.class, () -> manager.updateIssueById(7, State.UPDATE));
}
}
}
|
package org.fuserleer.serialization.mapper;
import java.util.Collection;
import java.util.Map;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
/**
* A field filter for DSON output modes.
*/
public class DsonFieldFilter extends SimpleBeanPropertyFilter {
private final ImmutableMap<Class<?>, ImmutableSet<String>> includedItems;
/**
* Create a {@link FilterProvider} with a {@link DsonFieldFilter}
* @param includedFields Set of {@code Class<?>} and field names to include for this filter.
* @return A freshly created {@link FilterProvider} with the specified DSON filter included.
*/
public static FilterProvider filterProviderFor(ImmutableMap<Class<?>, ImmutableSet<String>> includedFields) {
return new SimpleFilterProvider().addFilter(MapperConstants.DSON_FILTER_NAME, new DsonFieldFilter(includedFields));
}
DsonFieldFilter(ImmutableMap<Class<?>, ImmutableSet<String>> includedItems) {
// No need to make copy of immutable set.
this.includedItems = includedItems;
}
@Override
public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) throws Exception
{
Object parent = jgen.getOutputContext().getCurrentValue();
if (shouldInclude(parent.getClass(), writer.getName())) {
writer.serializeAsField(pojo, jgen, provider);
} else if (!jgen.canOmitFields()) { // since 2.3
writer.serializeAsOmittedField(pojo, jgen, provider);
}
}
@Override
protected boolean include(BeanPropertyWriter writer)
{
return true;
}
@Override
protected boolean include(PropertyWriter writer)
{
return true;
}
private boolean shouldInclude(Class<?> cls, String property)
{
// FIXME: Special cases ideally handled better
if (Map.class.isAssignableFrom(cls) || Collection.class.isAssignableFrom(cls)) {
return true;
}
ImmutableSet<String> fieldsForClass = this.includedItems.get(cls);
return fieldsForClass == null ? false : fieldsForClass.contains(property);
}
}
|
package net.jeremiahsmith.recipeapi.controllers;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IngredientsController {
}
|
package pe.egcc.geniosapp.prueba;
import pe.egcc.geniosapp.service.GeniosService;
public class Prueba01 {
public static void main(String[] args) {
//int base, altura;
//datos
int base = (int) Math.floor(Math.random()* 100);
int altura= (int) Math.floor(Math.random()* 100);
//proceso
GeniosService gs = new GeniosService();
double area = gs.CalculaArea(base, altura);
System.out.println("Base:" + base);
System.out.println("Altura:" + altura);
System.out.println("Area:" + String.format("%.2f",area));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.