text
stringlengths
10
2.72M
package go.app.greeter; import go.app.greet.Person; import java.util.List; public interface IGreeter { List<Person> greetedPeople(); String greet(String name, String language); Integer getCount(); }
package com.kevin.cloud.commons.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import java.util.List; /** * @program: vue-blog-backend * @description: 平台公共工具类 * @author: kevin * @create: 2020-01-23 11:55 **/ public class CommonUtils { /** * 将对象转成JsonObject 对象 * @param o 转换对象 * @param serializerFeature 默认值策略 * @return 转换后数据 * */ public static JSONObject beanToJSONObject(Object o, SerializerFeature serializerFeature) { return JSONObject.parseObject(JSON.toJSONString(o, serializerFeature)); } /** 策略攻略 * SerializerFeature.PrettyFormat:格式化输出 * SerializerFeature.WriteMapNullValue:是否输出值为null的字段,默认为false * SerializerFeature.DisableCircularReferenceDetect:消除循环引用 * SerializerFeature.WriteNullStringAsEmpty:将为null的字段值显示为"" * WriteNullListAsEmpty:List字段如果为null,输出为[],而非null * WriteNullNumberAsZero:数值字段如果为null,输出为0,而非null * WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null * SkipTransientField:如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。默认为true * SortField:按字段名称排序后输出。默认为false * WriteDateUseDateFormat:全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat); * BeanToArray:将对象转为array输出 * QuoteFieldNames:输出key时是否使用双引号,默认为true * UseSingleQuotes:输出key时使用单引号而不是双引号,默认为false(经测试,这里的key是指所有的输出结果,而非key/value的key,而是key,和value都使用单引号或双引号输出) * @param o * @return */ public static JSONObject beanToJSONObject(Object o) { return JSONObject.parseObject(JSON.toJSONString(o, SerializerFeature.WriteNullNumberAsZero)); } /** * 生成六位随机数用于短信服务 */ public static String createSmsCode(){ String vcode=""; for (int i=0; i<6; i++) { vcode=vcode+(int)(Math.random() * 9); } return vcode; } /* * Java将字符串的首字母转换大小写 * */ //首字母转小写 public static String toLowerCaseFirstOne(String s){ if(Character.isLowerCase(s.charAt(0))) return s; else return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString(); } //首字母转大写 public static String toUpperCaseFirstOne(String s){ if(Character.isUpperCase(s.charAt(0))) return s; else return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString(); } }
package LLambdaTop.functional; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.function.*; public class Mains { public static void main(String[] args) { Employee john = new Employee("john ss",23); Employee sol = new Employee("sol rrt",22); Employee al = new Employee("al gg",66); Employee cri = new Employee("cri ooo",11); List<Employee> employeeList = new ArrayList<>(); employeeList.add(john); employeeList.add(sol); employeeList.add(al); employeeList.add(cri); printEmployeesByAge(employeeList, "employer younger than 25 ", new Predicate<Employee>() { @Override public boolean test(Employee employee) { return employee.getAge()<25; } }); //predicate IntPredicate intp = i -> i>15; System.out.println(intp.test(10)); int a=20; System.out.println(intp.test(a+5)); System.out.println("----------------------------------"); //supplier Random random = new Random(); Supplier<Integer> randomSupplier = ()->random.nextInt(1000); for(int i=0;i<10;i++){ System.out.println(random.nextInt(1000)); System.out.println(randomSupplier.get() ); } System.out.println("-------------------------"); //get last name from list //function Function<Employee, String> getLastName = (Employee employee)->{ return employee.getName().substring(employee.getName().indexOf(' ')+1); }; String lastName = getLastName.apply(employeeList.get(1)); System.out.println(lastName); Function<Employee, String> getFirstName = (Employee employee)-> { return employee.getName().substring(0,employee.getName().indexOf(' ')); }; System.out.println("------------------------"); //uppercase function Function<Employee, String> upperCase = employee -> employee.getName().toUpperCase(); Function<String, String> firstName = name-> name.substring(0,name.indexOf(' ')); Function chainedFunction = upperCase.andThen(firstName); System.out.println(chainedFunction.apply(employeeList.get(0))); //bifunction BiFunction<String, Employee, String> concatAge = (String name, Employee employee)->{ return name.concat(" " + employee.getAge()); }; String upperName = upperCase.apply(employeeList.get(0)); System.out.println(concatAge.apply(upperName,employeeList.get(0))); //intunartoperator IntUnaryOperator incBy5 = i->i+5; System.out.println(incBy5.applyAsInt(10)); //consumer Consumer<String> s1 = s-> s.toUpperCase(); Consumer<String> s2 = s-> System.out.println(s); s1.accept("hey"); s2.accept("hello "); //object in, nothing out //consumer // employeeList.forEach(employee ->{ // System.out.println(employee.getAge()); // System.out.println(employee.getName()); // } ); // for(Employee employee : employeeList){ // if(employee.getAge()>30){ // System.out.println(employee.getName()); // } // } employeeList.forEach(employee -> { if(employee.getAge()>30){ System.out.println(employee.getName()); } }); Random random1 = new Random(); for (Employee employee : employeeList){ if(random1.nextBoolean()){ System.out.println(getAName(getFirstName,employee)); }else{ System.out.println(getAName(getLastName,employee)); } } } private static void printEmployeesByAge(List<Employee> employees, String ageText, Predicate<Employee> ageCondition) { System.out.println("over 30 "); // for(Employee employee :employees){ // if(ageCondition.test(employee)){ // System.out.println(employee.getName()); // } // } employees.forEach(employee -> { if (employee.getAge() > 30) { System.out.println(employee.getName()); } }); } private static String getAName(Function<Employee, String> getName, Employee employee){ return "S"; } }
package com.letmesee.service.filtros; import java.awt.image.BufferedImage; import java.util.ArrayList; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.imgproc.Imgproc; import com.letmesee.entity.Imagem; import com.letmesee.service.FiltrosUtils; public class SobelFacade { private static SobelFacade instancia; private static FiltrosUtils filtrosUtils; private SobelFacade() {} public static synchronized SobelFacade getInstancia() { if(instancia == null) { instancia = new SobelFacade(); filtrosUtils = FiltrosUtils.getInstancia(); } return instancia; } public Imagem Processar(Imagem img) { String formato = img.getTipo(); String novoConteudoBase64 = ""; if(formato.equals("jpg") || formato.equals("png") || formato.equals("bmp")) { BufferedImage imagem = filtrosUtils.base64toBufferedImage(img.getConteudoBase64()); imagem = Sobel(imagem, formato); novoConteudoBase64 = filtrosUtils.BufferedImageToBase64(imagem,formato); imagem = null; } else if(formato.equals("gif")) { ArrayList<Integer> delays = new ArrayList<Integer>(); ArrayList<BufferedImage> frames = filtrosUtils.getGifFrames(img.getConteudoBase64(),delays); ArrayList<BufferedImage> framesProcessados = new ArrayList<BufferedImage>(); for(BufferedImage f : frames) { f = Sobel(f, formato); framesProcessados.add(f); } novoConteudoBase64 = filtrosUtils.gerarBase64GIF(framesProcessados,delays); frames = null; framesProcessados = null; } Imagem saida = new Imagem(img.getLargura(),img.getAltura(),formato,img.getNome().concat("+Sobel"),novoConteudoBase64); return saida; } public BufferedImage Sobel(BufferedImage img, String formato){ Mat src = filtrosUtils.BufferedImage2Mat(img, formato); if(formato.equals(filtrosUtils.FORMATO_PNG)) Imgproc.cvtColor(src, src, Imgproc.COLOR_BGRA2BGR); Mat sobel = new Mat(); Mat gradX = new Mat(); Mat squareGradX = new Mat(); Mat gradY = new Mat(); Mat squareGradY = new Mat(); int type = CvType.CV_32F; Imgproc.Sobel(src, gradX, type, 1, 0); Imgproc.Sobel(src, gradY, type, 0, 1); Core.pow(gradX,2, squareGradX); Core.pow(gradY,2, squareGradY); //Core.addWeighted(squareGradX, 0.5, squareGradY, 0.5, 1, sobel); Core.add(squareGradX, squareGradY, sobel); Core.sqrt(sobel, sobel); Core.convertScaleAbs(sobel,sobel); if(formato.equals(filtrosUtils.FORMATO_PNG)) { img = filtrosUtils.devolverTransparencia(img, filtrosUtils.Mat2BufferedImage(sobel, formato)); return img; } img = filtrosUtils.Mat2BufferedImage(sobel, formato); return img; } }
package ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.StringTokenizer; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import modelo.AgregaRelacion; public class AgregaRelacionUI extends JFrame { private JPanel contentPane; private JTextField cantidad; final JList listPadre = new JList(); final JList listHijo = new JList(); DefaultListModel modeloHijo; private JTextField fechaInicio; private JTextField fechaFIn; public String getFechaInicio() { return fechaInicio.getText(); } public void setFechaInicio(JTextField fechaInicio) { this.fechaInicio = fechaInicio; } public String getFechaFIn() { // StringTokenizer st=new StringTokenizer(,"-"); return fechaFIn.getText(); } public void setFechaFIn(JTextField fechaFIn) { this.fechaFIn = fechaFIn; } public DefaultListModel getModeloHijo() { return modeloHijo; } /** * Launch the application. */ // public static void main(String[] args) { // EventQueue.invokeLater(new Runnable() { // public void run() { // try { // ReporteUI frame = new ReporteUI(new DefaultListModel<>()); // // frame.setVisible(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } public JList getListPadre() { return listPadre; } public JList getListHijo() { return listHijo; } /** * Create the frame. */ public AgregaRelacionUI(DefaultListModel modelo1, DefaultListModel modelo2, Object[] um) { addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { // AgregaRelacionUI.this.dispose(); } }); this.modeloHijo=modelo2; setDefaultCloseOperation(DISPOSE_ON_CLOSE); // final List list_2 = new List(); final JComboBox<Object> comboBox = new JComboBox<Object>(um); //PONGO TODO LA UI setBounds(100, 100, 696, 350); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(281, 35, 229, 155); contentPane.add(scrollPane_1); scrollPane_1.setViewportView(listHijo); listHijo.setModel(modelo2); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(10, 35, 229, 155); contentPane.add(scrollPane); //DECLARO LAS LISTAS scrollPane.setViewportView(listPadre); listPadre.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { // JOptionPane.showMessageDialog(null, "f"); // listPadre.getsel } }); //APLICO EL MODELO listPadre.setModel(modelo1); setLocationRelativeTo(null); JLabel lblPadre = new JLabel("Padre"); lblPadre.setBounds(10, 11, 46, 14); contentPane.add(lblPadre); JLabel lblHijo = new JLabel("Hijo"); lblHijo.setBounds(281, 11, 46, 14); contentPane.add(lblHijo); //LISTENER BOTON AGREGAR JButton btnAgregarRelacion = new JButton("Agregar Relacion"); btnAgregarRelacion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(listPadre.getSelectedValue()!=null&& listHijo.getSelectedValue()!=null && cantidad.getText()!=null&& comboBox.getSelectedItem()!=null){ if(!listPadre.getSelectedValue().equals(listHijo.getSelectedValue())){ AgregaRelacion agre=new AgregaRelacion(); // Nodo nodo=new Nodo(p, h) System.out.println("fecha inicio"+ getFechaInicio()); System.out.println("fecha fin"+ getFechaFIn()); agre.InsertarRelacion(listPadre.getSelectedValue().toString(), listHijo.getSelectedValue().toString(),cantidad.getText().toString(), comboBox.getSelectedItem().toString(),getFechaInicio(),getFechaFIn()); } else{ JOptionPane.showMessageDialog(null, "seleccione articulos distintos");} } else { JOptionPane.showMessageDialog(null, "Complete todos los campos");} } }); btnAgregarRelacion.setBounds(526, 140, 144, 50); contentPane.add(btnAgregarRelacion); cantidad = new JTextField(); cantidad.setText("1"); cantidad.setBounds(544, 33, 86, 20); contentPane.add(cantidad); cantidad.setColumns(10); JLabel lblCantidadDelHijo = new JLabel("Cantidad del hijo"); lblCantidadDelHijo.setBounds(544, 11, 113, 14); contentPane.add(lblCantidadDelHijo); //---------------------------------------------INICIALIZO EL COMBO comboBox.setBounds(544, 80, 113, 20); contentPane.add(comboBox); // comboBox. JLabel lblUnidadDeMedida = new JLabel("Unidad de medida"); lblUnidadDeMedida.setBounds(544, 64, 86, 14); contentPane.add(lblUnidadDeMedida); JButton btnAgregeAlternativos = new JButton("Agrege Alternativos"); btnAgregeAlternativos.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(listPadre.getSelectedValue()!=null && listHijo.getSelectedValue()!=null){ AgregaRelacion a = new AgregaRelacion(); if(a.ControlAlternativos(listPadre.getSelectedValue().toString(), listHijo.getSelectedValue().toString())){ AgregarAlternativoUI alterna=new AgregarAlternativoUI(AgregaRelacionUI.this,listPadre.getSelectedValue().toString(),listHijo.getSelectedValue().toString()); alterna.setVisible(true); } else {JOptionPane.showMessageDialog(null, "la relacion No se definio");} } else{ JOptionPane.showMessageDialog(null, "seleccione una realcion"); } } }); btnAgregeAlternativos.setBounds(526, 225, 144, 50); contentPane.add(btnAgregeAlternativos); JLabel lblFechaInicio = new JLabel("Fecha inicio"); lblFechaInicio.setBounds(10, 221, 80, 14); contentPane.add(lblFechaInicio); fechaInicio = new JTextField(); fechaInicio.setBounds(83, 218, 86, 20); contentPane.add(fechaInicio); fechaInicio.setColumns(10); JLabel lblddmmyyyy = new JLabel("(YYYY-MM-DD)"); lblddmmyyyy.setBounds(181, 221, 86, 14); contentPane.add(lblddmmyyyy); JLabel lblFechaFin = new JLabel("Fecha fin"); lblFechaFin.setBounds(10, 261, 59, 14); contentPane.add(lblFechaFin); fechaFIn = new JTextField(); fechaFIn.setBounds(83, 258, 86, 20); contentPane.add(fechaFIn); fechaFIn.setColumns(10); JLabel label = new JLabel("(YYYY-MM-DD)"); label.setBounds(181, 261, 86, 14); contentPane.add(label); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); } }
package com.cinema.common.model; import com.cinema.common.model.base.TDbConfig; public class DbConfig extends TDbConfig { }
/* * 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 DAOS; import Controler.Integridade; import Model.Operador; import java.util.List; import javax.swing.JOptionPane; import org.hibernate.HibernateException; import org.hibernate.Session; /** * * @author Gabriel Dutra */ public class OperadorDAO { public boolean add(Operador operador) { boolean resultado = false; try { Session session = Util.HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.save(operador); session.flush(); session.getTransaction().commit(); session.close(); resultado = true; } catch (HibernateException ex) { resultado = false; } return resultado; } public boolean update(Operador operador) { boolean resultado = false; try { Session session = Util.HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.update(operador); session.getTransaction().commit(); session.close(); resultado = true; } catch (HibernateException ex) { resultado = false; } return resultado; } public boolean delete(Operador operador) { boolean resultado = false; try { Session session = Util.HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.delete(operador); session.getTransaction().commit(); } catch (HibernateException ex) { resultado = true; } return resultado; } public Operador umOperador(int idOperador) { Session session = Util.HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Operador operador = (Operador) session.createQuery("FROM Operador WHERE id_operador=" + idOperador).uniqueResult(); session.getTransaction().commit(); session.close(); return operador; } public List<Operador> todosOperadores() { Session session = Util.HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); List<Operador> operadores = (List<Operador>) session. createQuery("FROM Operador").list(); session.getTransaction().commit(); session.close(); return operadores; } }
package com.imooc.article.service.Impl; import com.github.pagehelper.PageHelper; import com.imooc.api.BaseService; import com.imooc.article.mapper.CommentsCustomMapper; import com.imooc.article.mapper.CommentsMapper; import com.imooc.article.service.ArticlePortalService; import com.imooc.article.service.CommentsPortalService; import com.imooc.pojo.Comments; import com.imooc.pojo.vo.ArticleDetailVO; import com.imooc.pojo.vo.CommentsVO; import com.imooc.utils.PagedGridResult; import org.n3r.idworker.Sid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class CommentsPortalServiceImpl extends BaseService implements CommentsPortalService { @Autowired private CommentsMapper commentsMapper; @Autowired private CommentsCustomMapper commentsCustomMapper; @Autowired private ArticlePortalService articlePortalService; @Autowired private Sid sid; @Override @Transactional public void createComments(String articleId, String fatherCommentId, String content, String userId, String nickname, String face) { ArticleDetailVO articleDetailVO = articlePortalService.queryDetail(articleId); Comments comments = new Comments(); String commentId = sid.nextShort(); comments.setId(commentId); comments.setWriterId(articleDetailVO.getPublishUserId()); comments.setArticleTitle(articleDetailVO.getTitle()); comments.setArticleCover(articleDetailVO.getCover()); comments.setArticleId(articleId); comments.setFatherId(fatherCommentId); comments.setCommentUserFace(face); comments.setCommentUserId(userId); comments.setCommentUserNickname(nickname); comments.setContent(content); comments.setCreateTime(new Date()); commentsMapper.insert(comments); // 评论数累加 redis.increment(REDIS_ARTICLE_COMMENT_COUNTS+":"+articleId,1); } @Override public PagedGridResult queryArticleComments(String articleId, Integer page, Integer pageSize) { Map<String,Object> map = new HashMap<>(); map.put("articleId",articleId); PageHelper.startPage(page,pageSize); List<CommentsVO> list = commentsCustomMapper.queryArticleCommentList(map); return setterPagedGrid(list,page); } @Override public PagedGridResult queryCommentsByWriterId(String writerId, Integer page, Integer pageSize) { Comments comment = new Comments(); comment.setWriterId(writerId); PageHelper.startPage(page,pageSize); List<Comments> list = commentsMapper.select(comment); return setterPagedGrid(list,page); } @Override public void deleteCommentByWriter(String writerId, String commentId) { Comments c = new Comments(); c.setId(commentId); Comments result = commentsMapper.selectOne(c); String articleId = result.getArticleId(); Comments comment = new Comments(); comment.setWriterId(writerId); comment.setId(commentId); commentsMapper.delete(comment); redis.decrement(REDIS_ARTICLE_COMMENT_COUNTS+":"+articleId,1); } }
package edu.colostate.cs.cs414.soggyZebras.rollerball.Tests.Client; public class GUIRunnerTest { }
package com.misiontic2022.c2.reto4; import com.misiontic2022.c2.reto4.view.FrmRequerimientos; import com.misiontic2022.c2.reto4.view.ViewRequerimientos; /** * Hello world! * */ public class App { public static void main( String[] args ) { /*System.out.println("Requerimiento 1"); ViewRequerimientos.requerimiento1(); System.out.println("Requerimiento 2"); ViewRequerimientos.requerimiento2(); System.out.println("Requerimiento 3"); ViewRequerimientos.requerimiento3(); */ new FrmRequerimientos().setVisible(true); } }
package com.codefundo.votenew.Offline; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.telephony.SmsManager; import android.view.Gravity; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.codefundo.votenew.AESCrypt; import com.codefundo.votenew.MainActivity; import com.codefundo.votenew.R; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Base64; import java.util.List; public class Offline extends AppCompatActivity { private static final String[] requiredPermissions = { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.SEND_SMS, Manifest.permission.READ_SMS, }; private static final int MY_PERMISSIONS_REQUEST_ACCESS_CODE = 1; EditText pin,mobile,name,aadhaar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkPermissions(); setContentView(R.layout.activity_offline); name=findViewById(R.id.name); mobile=findViewById(R.id.mobile); aadhaar=findViewById(R.id.aadhaar); pin=findViewById(R.id.pin); findViewById(R.id.send).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { //sendSMS("+917578983840",mobile.getText().toString().trim()+" "+name.getText().toString().trim()+" "+mobile.getText().toString().trim()+" "+aadhaar.getText().toString().trim()+" "+pin.getText().toString().trim()); // sendSMS("+917578983840",AESCrypt.encrypt(aadhaar.getText().toString())); sendLongSMS("+917578983840",AESCrypt.encrypt("AHI")); } catch (Exception e) { e.printStackTrace(); } } }); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_ACCESS_CODE: { if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { checkPermissions(); } } } } @TargetApi(Build.VERSION_CODES.M) private void checkPermissions() { final List<String> neededPermissions = new ArrayList<>(); for (final String permission : requiredPermissions) { if (ContextCompat.checkSelfPermission(getApplicationContext(), permission) != PackageManager.PERMISSION_GRANTED) { neededPermissions.add(permission); } } if (!neededPermissions.isEmpty()) { requestPermissions(neededPermissions.toArray(new String[]{}), MY_PERMISSIONS_REQUEST_ACCESS_CODE); } } public void sendSMS(String phoneNo, String msg) { try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNo, null, msg, null, null); Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_LONG).show(); } catch (Exception ex) { Toast.makeText(getApplicationContext(),ex.getMessage().toString(), Toast.LENGTH_LONG).show(); ex.printStackTrace(); } } public void sendLongSMS(String phone,final String msg) { String message = mobile.getText().toString().trim()+" "+name.getText().toString().trim()+" "+mobile.getText().toString().trim()+" "+aadhaar.getText().toString().trim()+" "+pin.getText().toString().trim(); SmsManager smsManager = SmsManager.getDefault(); ArrayList<String> parts = smsManager.divideMessage(message); smsManager.sendMultipartTextMessage(phone, null, parts, null, null); } }
package factory_abstract.ingredient; /** * @Description: * @Author: JackYan * @Date2019/12/27 19:13 * @Version V1.0 **/ public class MarinaraSauce extends Sauce { }
package com.avishai.MyShas; import android.app.Activity; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.CheckedTextView; import android.widget.ProgressBar; import android.widget.TextView; import java.util.HashMap; import java.util.List; /** * A class that represent the bridge between the file of a Masechet and the UI */ public class MainAdapter extends BaseExpandableListAdapter { private Activity ac; private List<String> listGroup; private HashMap<String, List<String>> listItems; private HashMap<String, Boolean> stateOfPages; private int numOfPages; private String[] link; private ProgressBar progressBar; private TextView progressTxt; private Boolean hasLastPage; /** * A constructor to init the object * @param ac - the Activity that called the method * @param listGroup - the container of the chapters in the Masechet * @param listItems - the container of the pages in the Masechet * @param store - the file to get the values and update * @param numOfPages - the number of the pages in the given Masechet * @param stateOfPages - the state of the pages before saving * @param firstLoad - to determine if this is the first load of the Activity * @param numMasechet - the number of the Masechet * @param progressBar the UI progressbar * @param progressTxt - the text of the percent of the learned pages * @param hasLastPage - to determine if the Masechet has last page */ MainAdapter(Activity ac, List<String> listGroup, HashMap<String, List<String>> listItems, Keystore store, int numOfPages, HashMap<String, Boolean> stateOfPages, Boolean firstLoad, int numMasechet, ProgressBar progressBar, TextView progressTxt, Boolean hasLastPage) { this.ac = ac; this.listGroup = listGroup; this.listItems = listItems; this.stateOfPages = stateOfPages; this.numOfPages = numOfPages; this.link = new String[]{"https://www.hebrewbooks.org/shas.aspx?mesechta=" + numMasechet + "&daf=", "&format="}; this.progressBar = progressBar; this.progressTxt = progressTxt; this.hasLastPage = hasLastPage; // to save the states when inserting the activity (boot only on first reload) if (firstLoad) { for (int i = 2; i <= this.numOfPages; ++i) { this.stateOfPages.put(String.valueOf(i), store.getBool(String.valueOf(i))); } } } @Override public int getGroupCount() { return this.listGroup.size(); } @Override public int getChildrenCount(int groupPosition) { return this.listItems.get(this.listGroup.get(groupPosition)).size(); } @Override public Object getGroup(int groupPosition) { return this.listGroup.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return this.listItems.get(this.listGroup.get(groupPosition)).get(childPosition); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return false; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup viewGroup) { String group = (String) getGroup(groupPosition); // for click on group if (convertView == null) { LayoutInflater li = (LayoutInflater) this.ac.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = li.inflate(R.layout.list_group, null); } TextView textView = convertView.findViewById(R.id.list_parent); textView.setTypeface(null, Typeface.BOLD); textView.setText(group); return convertView; } @Override public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup viewGroup) { String child = (String) getChild(groupPosition, childPosition); // for click on child if (convertView == null) { LayoutInflater li = (LayoutInflater) this.ac.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = li.inflate(R.layout.list_items, null); } final CheckedTextView textView = convertView.findViewById(R.id.list_child); // split the page to the name and the number final String[] page = child.split("-"); // add the name textView.setText(page[0]); // check against the number whether to check or uncheck the page if (stateOfPages.get(page[1])) { textView.setCheckMarkDrawable(R.drawable.checked); textView.setChecked(true); } else { textView.setCheckMarkDrawable(R.drawable.unchecked); textView.setChecked(false); } // to create a listener to handle click on the page textView.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { if (textView.isChecked()) { textView.setCheckMarkDrawable(R.drawable.unchecked); textView.setChecked(false); stateOfPages.put(page[1], false); } else { textView.setCheckMarkDrawable(R.drawable.checked); textView.setChecked(true); stateOfPages.put(page[1], true); } ProgramMethods.determineProgress(progressBar, stateOfPages, numOfPages, progressTxt); } }); // the link for page a TextView txtBtn = convertView.findViewById(R.id.txtButton); txtBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.link_exlv, 0, 0, 0); txtBtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { ProgramMethods.openLink(ac, link[0] + page[1] + link[1]); } }); // the link to page b (if there is one) TextView txtBtnB = convertView.findViewById(R.id.txtButtonB); if (this.numOfPages == Integer.valueOf(page[1]) && !this.hasLastPage) { txtBtnB.setCompoundDrawablesWithIntrinsicBounds(R.drawable.unchecked, 0, 0, 0); } else { txtBtnB.setCompoundDrawablesWithIntrinsicBounds(R.drawable.link_exlv, 0, 0, 0); txtBtnB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ProgramMethods.openLink(ac, link[0] + page[1] + "b" + link[1]); } }); } return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } /** * Method to get the first page in the group * @param groupPosition - the given group * @return - the first page */ int getNumOfFirstChild(int groupPosition) { return Integer.parseInt(this.listItems.get(this.listGroup.get(groupPosition)).get(0).split("-")[1]); } /** * Method to get the last page in the group * @param groupPosition - the given group * @return - the last page */ int getNumOfLastChild(int groupPosition) { return Integer.parseInt(this.listItems.get(this.listGroup.get(groupPosition)) .get(this.getChildrenCount(groupPosition)-1).split("-")[1]); } }
package org.me.myandroidstuff.data; import junit.framework.TestCase; public class RssItemTest extends TestCase { public void testgetTitle() { RssItem test = new RssItem(); assertTrue (test.getTitle()=="test"); } }
/* * 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; import controlador.CursoCtrl; import controlador.EstudianteCtrl; import java.awt.Color; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Dashboard extends javax.swing.JFrame { Inicio inicio = new Inicio(); ListarEstudiantes listarEsu = new ListarEstudiantes(); ListarProfesores listarProf = new ListarProfesores(); ListarCursos listarCursos = new ListarCursos(); /** * Creates new form dashboard */ public Dashboard() { this.setUndecorated(true); initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); JPContenedor = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); txtUsuario = new javax.swing.JLabel(); txtFecha = new javax.swing.JLabel(); JPSalir = new javax.swing.JPanel(); lblSalir = new javax.swing.JLabel(); JPFondoMenu = new javax.swing.JPanel(); JPMenuTOP = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); JPInicio = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); iconInicio = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); iconEstudiantes = new javax.swing.JLabel(); jPProfesores = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); JPCursos = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); tabContSesiones = new javax.swing.JTabbedPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); JPContenedor.setBackground(new java.awt.Color(255, 255, 255)); JPContenedor.addAncestorListener(new javax.swing.event.AncestorListener() { public void ancestorMoved(javax.swing.event.AncestorEvent evt) { } public void ancestorAdded(javax.swing.event.AncestorEvent evt) { JPContenedorAncestorAdded(evt); } public void ancestorRemoved(javax.swing.event.AncestorEvent evt) { } }); jPanel6.setBackground(new java.awt.Color(235, 235, 235)); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel4.setText("Bienvedido"); txtUsuario.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N txtUsuario.setText("Usuario"); txtFecha.setText("Fecha"); JPSalir.setBackground(new java.awt.Color(153, 153, 153)); JPSalir.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); JPSalir.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { JPSalirMouseClicked(evt); } }); lblSalir.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N lblSalir.setForeground(new java.awt.Color(255, 255, 255)); lblSalir.setText("Salir"); javax.swing.GroupLayout JPSalirLayout = new javax.swing.GroupLayout(JPSalir); JPSalir.setLayout(JPSalirLayout); JPSalirLayout.setHorizontalGroup( JPSalirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JPSalirLayout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(lblSalir) .addContainerGap(29, Short.MAX_VALUE)) ); JPSalirLayout.setVerticalGroup( JPSalirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblSalir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(txtFecha) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 130, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtUsuario) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 653, Short.MAX_VALUE) .addComponent(JPSalir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(520, 520, 520)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addContainerGap(31, Short.MAX_VALUE) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(txtUsuario)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtFecha) .addGap(31, 31, 31)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(JPSalir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); JPFondoMenu.setBackground(new java.awt.Color(242, 149, 107)); JPMenuTOP.setBackground(new java.awt.Color(255, 144, 103)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/edusenaBlanco.png"))); // NOI18N jPanel2.setBackground(new java.awt.Color(255, 255, 255)); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 4, Short.MAX_VALUE) ); javax.swing.GroupLayout JPMenuTOPLayout = new javax.swing.GroupLayout(JPMenuTOP); JPMenuTOP.setLayout(JPMenuTOPLayout); JPMenuTOPLayout.setHorizontalGroup( JPMenuTOPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JPMenuTOPLayout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(JPMenuTOPLayout.createSequentialGroup() .addGap(112, 112, 112) .addComponent(jLabel1) .addContainerGap(122, Short.MAX_VALUE)) ); JPMenuTOPLayout.setVerticalGroup( JPMenuTOPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JPMenuTOPLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel4.setBackground(new java.awt.Color(241, 155, 114)); JPInicio.setBackground(new java.awt.Color(241, 155, 114)); JPInicio.setToolTipText(""); JPInicio.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); JPInicio.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { JPInicioMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { JPInicioMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { JPInicioMouseExited(evt); } }); jLabel2.setBackground(new java.awt.Color(255, 255, 255)); jLabel2.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Inicio"); iconInicio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/icon-home.png"))); // NOI18N javax.swing.GroupLayout JPInicioLayout = new javax.swing.GroupLayout(JPInicio); JPInicio.setLayout(JPInicioLayout); JPInicioLayout.setHorizontalGroup( JPInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JPInicioLayout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(iconInicio) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); JPInicioLayout.setVerticalGroup( JPInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JPInicioLayout.createSequentialGroup() .addContainerGap() .addGroup(JPInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(iconInicio)) .addContainerGap(20, Short.MAX_VALUE)) ); jPanel5.setBackground(new java.awt.Color(241, 155, 114)); jPanel5.setToolTipText(""); jPanel5.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jPanel5.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jPanel5MouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jPanel5MouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jPanel5MouseExited(evt); } }); jLabel3.setBackground(new java.awt.Color(255, 255, 255)); jLabel3.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Estudiantes"); iconEstudiantes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/icon-estudiante.png"))); // NOI18N javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(iconEstudiantes) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(iconEstudiantes) .addComponent(jLabel3)) .addContainerGap(21, Short.MAX_VALUE)) ); jPProfesores.setBackground(new java.awt.Color(241, 155, 114)); jPProfesores.setToolTipText(""); jPProfesores.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jPProfesores.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jPProfesoresMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jPProfesoresMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jPProfesoresMouseExited(evt); } }); jLabel6.setBackground(new java.awt.Color(255, 255, 255)); jLabel6.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Profesores"); jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/icon-Profesor.png"))); // NOI18N javax.swing.GroupLayout jPProfesoresLayout = new javax.swing.GroupLayout(jPProfesores); jPProfesores.setLayout(jPProfesoresLayout); jPProfesoresLayout.setHorizontalGroup( jPProfesoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPProfesoresLayout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel6) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPProfesoresLayout.setVerticalGroup( jPProfesoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPProfesoresLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPProfesoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8) .addComponent(jLabel6)) .addGap(21, 21, 21)) ); JPCursos.setBackground(new java.awt.Color(241, 155, 114)); JPCursos.setToolTipText(""); JPCursos.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); JPCursos.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { JPCursosMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { JPCursosMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { JPCursosMouseExited(evt); } }); jLabel7.setBackground(new java.awt.Color(255, 255, 255)); jLabel7.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 255, 255)); jLabel7.setText("Cursos"); jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/icon-cursos.png"))); // NOI18N javax.swing.GroupLayout JPCursosLayout = new javax.swing.GroupLayout(JPCursos); JPCursos.setLayout(JPCursosLayout); JPCursosLayout.setHorizontalGroup( JPCursosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JPCursosLayout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel7) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); JPCursosLayout.setVerticalGroup( JPCursosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JPCursosLayout.createSequentialGroup() .addContainerGap(16, Short.MAX_VALUE) .addGroup(JPCursosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel9) .addComponent(jLabel7)) .addGap(21, 21, 21)) ); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JPInicio, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPProfesores, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(JPCursos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(JPInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPProfesores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(JPCursos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout JPFondoMenuLayout = new javax.swing.GroupLayout(JPFondoMenu); JPFondoMenu.setLayout(JPFondoMenuLayout); JPFondoMenuLayout.setHorizontalGroup( JPFondoMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JPMenuTOP, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); JPFondoMenuLayout.setVerticalGroup( JPFondoMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JPFondoMenuLayout.createSequentialGroup() .addComponent(JPMenuTOP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 287, Short.MAX_VALUE)) ); tabContSesiones.setBackground(new java.awt.Color(242, 149, 107)); tabContSesiones.setForeground(new java.awt.Color(255, 255, 255)); tabContSesiones.addAncestorListener(new javax.swing.event.AncestorListener() { public void ancestorMoved(javax.swing.event.AncestorEvent evt) { } public void ancestorAdded(javax.swing.event.AncestorEvent evt) { tabContSesionesAncestorAdded(evt); } public void ancestorRemoved(javax.swing.event.AncestorEvent evt) { } }); javax.swing.GroupLayout JPContenedorLayout = new javax.swing.GroupLayout(JPContenedor); JPContenedor.setLayout(JPContenedorLayout); JPContenedorLayout.setHorizontalGroup( JPContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JPContenedorLayout.createSequentialGroup() .addComponent(JPFondoMenu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JPContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tabContSesiones, javax.swing.GroupLayout.PREFERRED_SIZE, 1006, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) ); JPContenedorLayout.setVerticalGroup( JPContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JPFondoMenu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(JPContenedorLayout.createSequentialGroup() .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tabContSesiones)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JPContenedor, javax.swing.GroupLayout.PREFERRED_SIZE, 1322, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(JPContenedor, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void JPCursosMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JPCursosMouseExited JPCursos.setBackground(new Color(241,155,114)); }//GEN-LAST:event_JPCursosMouseExited private void JPCursosMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JPCursosMouseEntered JPCursos.setBackground(new Color(236,183,147)); }//GEN-LAST:event_JPCursosMouseEntered private void jPProfesoresMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPProfesoresMouseExited jPProfesores.setBackground(new Color(241,155,114));; }//GEN-LAST:event_jPProfesoresMouseExited private void jPProfesoresMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPProfesoresMouseEntered jPProfesores.setBackground(new Color(236,183,147)); }//GEN-LAST:event_jPProfesoresMouseEntered private void jPanel5MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel5MouseExited jPanel5.setBackground(new Color(241,155,114)); }//GEN-LAST:event_jPanel5MouseExited private void jPanel5MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel5MouseEntered jPanel5.setBackground(new Color(236,183,147)); }//GEN-LAST:event_jPanel5MouseEntered private void JPInicioMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JPInicioMouseExited JPInicio.setBackground(new Color(241,155,114)); }//GEN-LAST:event_JPInicioMouseExited private void JPInicioMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JPInicioMouseEntered JPInicio.setBackground(new Color(236,183,147)); }//GEN-LAST:event_JPInicioMouseEntered private void JPContenedorAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_JPContenedorAncestorAdded Date date = new Date(); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); String fecha = "Hoy es "+dateFormat.format(date); txtFecha.setText(fecha); }//GEN-LAST:event_JPContenedorAncestorAdded private void jPanel5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel5MouseClicked tabContSesiones.setSelectedComponent(listarEsu); }//GEN-LAST:event_jPanel5MouseClicked private void jPProfesoresMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPProfesoresMouseClicked tabContSesiones.setSelectedComponent(listarProf); }//GEN-LAST:event_jPProfesoresMouseClicked private void JPCursosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JPCursosMouseClicked tabContSesiones.setSelectedComponent(listarCursos); }//GEN-LAST:event_JPCursosMouseClicked private void tabContSesionesAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_tabContSesionesAncestorAdded tabContSesiones.addTab("Inicio", inicio); tabContSesiones.addTab("Estudiantes", listarEsu); tabContSesiones.addTab("Profesores", listarProf); tabContSesiones.addTab("Cursos", listarCursos); tabContSesiones.setSelectedComponent(inicio); }//GEN-LAST:event_tabContSesionesAncestorAdded private void JPInicioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JPInicioMouseClicked tabContSesiones.setSelectedComponent(inicio); }//GEN-LAST:event_JPInicioMouseClicked private void JPSalirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JPSalirMouseClicked System.exit(0); }//GEN-LAST:event_JPSalirMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Dashboard().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel JPContenedor; private javax.swing.JPanel JPCursos; private javax.swing.JPanel JPFondoMenu; private javax.swing.JPanel JPInicio; private javax.swing.JPanel JPMenuTOP; private javax.swing.JPanel JPSalir; private javax.swing.JLabel iconEstudiantes; private javax.swing.JLabel iconInicio; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPProfesores; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JLabel lblSalir; public javax.swing.JTabbedPane tabContSesiones; private javax.swing.JLabel txtFecha; private javax.swing.JLabel txtUsuario; // End of variables declaration//GEN-END:variables }
package arcs.demo.particles; import arcs.demo.services.ClipboardService; import arcs.api.Particle; import arcs.api.ParticleFactory; import arcs.api.PortableJsonParser; import javax.inject.Inject; public class RenderTextFactory implements ParticleFactory { private PortableJsonParser parser; // TODO: Inject interfaces particles normally may want in defineParticle (e.g. html, log, etc) @Inject public RenderTextFactory(PortableJsonParser parser) { this.parser = parser; } @Override public String getParticleName() { return "RenderText"; } @Override public Particle createParticle() { return new RenderText(parser); } }
package io.hankki.myrecipe.domain.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.querydsl.QueryDslPredicateExecutor; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import com.querydsl.core.types.Predicate; import io.hankki.myrecipe.domain.model.Myrecipe; @RepositoryRestResource public interface MyrecipeRepository extends JpaRepository<Myrecipe, Long>, QueryDslPredicateExecutor<Myrecipe>{ Myrecipe findById(@Param("id") Long id); List<Myrecipe> findByUserid(@Param("userid") String userid); List<Myrecipe> findAll(Predicate predicate); List<Myrecipe> findByUseridLike(@Param("userid") String userid); }
package com.icanit.app.entity; // default package import java.util.Date; /** * AppGoods entity. @author MyEclipse Persistence Tools */ public class AppGoods implements java.io.Serializable { // Fields public Integer id,amount,hot; public AppMerchant appMerchant; public AppCategory appCategory; public String goodName,detail,pic; public double curPrice,duePrice; public Date addTime; }
/* * Copyright (c) 2016 Cloudera, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.director.samples; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.beust.jcommander.Parameters; import com.cloudera.director.client.common.ApiClient; import com.cloudera.director.client.latest.api.ImportClientConfigApi; import com.cloudera.director.client.latest.model.ImportResult; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; /** * Example on how to use the API to import a client config file. */ @Parameters(commandDescription = "Import a client config file") public class DispatchSample extends CommonParameters { @Parameter(names = "--config", required = true, description = "Path to the cluster configuration file") private String configFile; @Parameter(names = "--environment", required = false, description = "Optional override for environment name") private String environmentName = null; @Parameter(names = "--deployment", required = false, description = "Optional override for deployment name") private String deploymentName = null; @Parameter(names = "--cluster", required = false, description = "Optional override for cluster name") private String clusterName = null; /** * Import client config file. */ public int run() throws Exception { String config; try { config = new String(Files.readAllBytes(Paths.get(configFile)), StandardCharsets.UTF_8); } catch (IOException e) { System.err.println("Unable to read configuration file: " + configFile); return ExitCodes.CONFIG_FILE_ERROR; } ApiClient client = ClientUtil.newAuthenticatedApiClient(this); ImportClientConfigApi api = new ImportClientConfigApi(client); ImportResult result = api.importClientConfig(config, clusterName, deploymentName, environmentName); System.out.println(result.toString()); return ExitCodes.OK; } public static void main(String[] args) throws Exception { DispatchSample sample = new DispatchSample(); JCommander jc = new JCommander(sample); jc.setProgramName("DispatchSample"); try { jc.parse(args); } catch (ParameterException e) { System.err.println(e.getMessage()); jc.usage(); System.exit(ExitCodes.OK); } System.exit(sample.run()); } }
package hw3.q01; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * * @author ribb0013 */ public class Profiler { static private Profiler instance; private Map<String,Integer> map = new HashMap<>(); private Profiler(){}; public static Profiler getSingleton(){ if(null == instance){ instance = new Profiler(); } return instance; } public void add(String methodName){ if(map.containsKey(methodName)){ map.put(methodName, map.get(methodName) + 1); }else{ map.put(methodName, 1); } } public void clear(){ Map<String,Integer> newMap = new HashMap<>(); this.map = newMap; } public int getNumberOfMethods(){ return this.map.size(); } // public int getNumberOfMethodCalls(){ int count = 0; if(!map.isEmpty()){ Iterator i = map.entrySet().iterator(); while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); count += (int)me.getValue(); } } return count; } public int getNumberOfMethodCalls(String methodName){ if(!map.isEmpty()){ return map.get(methodName); } return 0; } public MethodProfile getProfile(String methodName){ MethodProfile profile = new MethodProfile(); int total = getNumberOfMethodCalls(); profile.name = methodName; profile.count = map.get(methodName); System.out.println(""); System.out.println("--- the running output for my method below ---"); System.out.println("# total for this method = " + profile.count); System.out.println("# total method calls = " + total); profile.percentOfCalls = ((float)profile.count / (float)total); return profile; } // public List<MethodProfile> getProfiles(){ System.out.println("get profiles"); List<MethodProfile> myList = new ArrayList(); Iterator i = map.entrySet().iterator(); while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); String method = me.getKey().toString(); MethodProfile profile = getProfile(method); myList.add(profile); } return myList; } public static class getSingleton { public getSingleton() { } } }
/** Exception for invalid length. Data structures that have a fixed (integer) length throw LengthException if a given length is out of range. */ public class LengthException extends RuntimeException { private static final long serialVersionUID = 0L; }
package com.ascendaz.roster.repository; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.ascendaz.roster.model.RosterUser; @Repository("userRepository") public class UserRepository { @Autowired private SessionFactory sessionFactory; public RosterUser getUserByUsername(String username) { String hqlQuery = "FROM RosterUser " + "WHERE username = :username"; Query query = sessionFactory.getCurrentSession().createQuery(hqlQuery); query.setParameter("username", username); RosterUser user = (RosterUser)query.uniqueResult(); return user; } }
package com.example.joker.newsapp.Database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by joker on 22/11/17. */ public class SQLHelperClass extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "news.db"; public SQLHelperClass(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String CREATE_TABLE_TOP_HEADLINE = "CREATE TABLE " + NewsContractor.TopHeadline.TABLE_NAME + " ( " + NewsContractor.TopHeadline._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NewsContractor.TopHeadline.SOURCE_ID + " VARCHAR, " + NewsContractor.TopHeadline.SOURCE_NAME + " VARCHAR, " + NewsContractor.TopHeadline.TITLE + " VARCHAR, " + NewsContractor.TopHeadline.DESC + " VARCHAR, " + NewsContractor.TopHeadline.SOURCE_URL + " VARCHAR, " + NewsContractor.TopHeadline.IMAGE_URL + " VARCHAR, " + NewsContractor.TopHeadline.PUBLISHED_AT + " VARCHAR, " + NewsContractor.TopHeadline.AUTHOR + " VARCHAR ); "; sqLiteDatabase.execSQL(CREATE_TABLE_TOP_HEADLINE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + NewsContractor.TopHeadline.TABLE_NAME); onCreate(sqLiteDatabase); } }
package com.vicutu.batchdownload.http.factory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponseInterceptor; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import com.vicutu.batchdownload.http.params.HttpParamConfiguration; import com.vicutu.commons.exception.BaseRuntimeException; import com.vicutu.commons.logging.Logger; import com.vicutu.commons.logging.LoggerFactory; public abstract class AbstractHttpClientFactory implements HttpClientFactory { protected final Logger logger = LoggerFactory.getLogger(getClass()); private List<HttpRequestInterceptor> httpRequestInterceptors; private List<HttpResponseInterceptor> httpResponseInterceptors; private Map<Integer, String> schemes; private List<DefaultHttpClient> httpClients = Collections.synchronizedList(new ArrayList<DefaultHttpClient>()); private HttpParamConfiguration httpParamConfiguration; private boolean closeExpired; private long closeIdleTimeout; private long housekeepingTimeout; private IdleConnectionEvictor idleConnectionEvictor; public void setHousekeepingTimeout(long housekeepingTimeout) { this.housekeepingTimeout = housekeepingTimeout; } public void setCloseExpired(boolean closeExpired) { this.closeExpired = closeExpired; } public void setCloseIdleTimeout(long closeIdleTimeout) { this.closeIdleTimeout = closeIdleTimeout; } public void setHttpParamConfiguration(HttpParamConfiguration httpParamConfiguration) { this.httpParamConfiguration = httpParamConfiguration; } public void setSchemes(Map<Integer, String> schemes) { this.schemes = schemes; } public void setHttpRequestInterceptors(List<HttpRequestInterceptor> httpRequestInterceptors) { this.httpRequestInterceptors = httpRequestInterceptors; } public void setHttpResponseInterceptors(List<HttpResponseInterceptor> httpResponseInterceptors) { this.httpResponseInterceptors = httpResponseInterceptors; } protected abstract ClientConnectionManager getClientConnectionManager(SchemeRegistry schemeRegistry, int maxConnectionsPerRoute, int maxTotalConnections); @Override public HttpClient createHttpClientInstance() { SchemeRegistry schemeRegistry = initScheme(schemes); DefaultHttpClient httpClient = null; if (httpParamConfiguration != null) { ClientConnectionManager clientConnectionManager = getClientConnectionManager(schemeRegistry, httpParamConfiguration.getMaxConnectionsPerRoute(), httpParamConfiguration.getMaxTotalConnections()); httpClient = new DefaultHttpClient(clientConnectionManager, httpParamConfiguration.getHttpParam()); } else { ClientConnectionManager clientConnectionManager = getClientConnectionManager(schemeRegistry, -1, -1); httpClient = new DefaultHttpClient(clientConnectionManager); } initInterceptor(httpClient, httpRequestInterceptors, httpResponseInterceptors); httpClients.add(httpClient); if (housekeepingTimeout > 0) { idleConnectionEvictor = new IdleConnectionEvictor(); idleConnectionEvictor.start(); logger.info("IdleConnectionEvictor has been started."); } return httpClient; } protected void initInterceptor(DefaultHttpClient httpClient, List<HttpRequestInterceptor> httpRequestInterceptors, List<HttpResponseInterceptor> httpResponseInterceptors) { if (httpRequestInterceptors != null) { for (int i = 0; i < httpRequestInterceptors.size(); i++) { httpClient.addRequestInterceptor(httpRequestInterceptors.get(i), i); } } if (httpResponseInterceptors != null) { for (int i = 0; i < httpResponseInterceptors.size(); i++) { httpClient.addResponseInterceptor(httpResponseInterceptors.get(i), i); } } } protected SchemeRegistry initScheme(Map<Integer, String> schemes) { SchemeRegistry schemeRegistry = null; if (schemes != null && !schemes.isEmpty()) { schemeRegistry = new SchemeRegistry(); Set<Entry<Integer, String>> entrySet = schemes.entrySet(); for (Entry<Integer, String> entry : entrySet) { String protocol = entry.getValue(); int port = entry.getKey().intValue(); if ("https".equalsIgnoreCase(protocol)) { schemeRegistry.register(new Scheme("https", port, SSLSocketFactory.getSocketFactory())); } else if ("http".equalsIgnoreCase(protocol)) { schemeRegistry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory())); } else { throw new BaseRuntimeException("unknown protocol : " + protocol); } } } return schemeRegistry; } public void init() throws Throwable { } public void cleanup() throws Throwable { if (idleConnectionEvictor != null) { idleConnectionEvictor.shutdown(); idleConnectionEvictor.join(); logger.info("IdleConnectionEvictor has been shutdown."); } for (DefaultHttpClient httpClient : httpClients) { httpClient.getConnectionManager().shutdown(); } } public class IdleConnectionEvictor extends Thread { private volatile boolean shutdown; @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(housekeepingTimeout); logger.info("IdleConnectionEvictor is running."); for (DefaultHttpClient httpClient : httpClients) { // Close expired connections if (closeExpired) { httpClient.getConnectionManager().closeExpiredConnections(); } // Optionally, close connections if (closeIdleTimeout > 0) { httpClient.getConnectionManager().closeIdleConnections(closeIdleTimeout, TimeUnit.MILLISECONDS); } } } } } catch (InterruptedException ex) { // terminate } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } } }
/* * Copyright 2002-2018 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.config; import java.lang.reflect.Field; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBeanNotInitializedException; import org.springframework.beans.factory.InitializingBean; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; /** * {@link FactoryBean} which retrieves a static or non-static field value. * * <p>Typically used for retrieving public static final constants. Usage example: * * <pre class="code"> * // standard definition for exposing a static field, specifying the "staticField" property * &lt;bean id="myField" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"&gt; * &lt;property name="staticField" value="java.sql.Connection.TRANSACTION_SERIALIZABLE"/&gt; * &lt;/bean&gt; * * // convenience version that specifies a static field pattern as bean name * &lt;bean id="java.sql.Connection.TRANSACTION_SERIALIZABLE" * class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/&gt; * </pre> * * <p>If you are using Spring 2.0, you can also use the following style of configuration for * public static fields. * * <pre class="code">&lt;util:constant static-field="java.sql.Connection.TRANSACTION_SERIALIZABLE"/&gt;</pre> * * @author Juergen Hoeller * @since 1.1 * @see #setStaticField */ public class FieldRetrievingFactoryBean implements FactoryBean<Object>, BeanNameAware, BeanClassLoaderAware, InitializingBean { @Nullable private Class<?> targetClass; @Nullable private Object targetObject; @Nullable private String targetField; @Nullable private String staticField; @Nullable private String beanName; @Nullable private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); // the field we will retrieve @Nullable private Field fieldObject; /** * Set the target class on which the field is defined. * Only necessary when the target field is static; else, * a target object needs to be specified anyway. * @see #setTargetObject * @see #setTargetField */ public void setTargetClass(@Nullable Class<?> targetClass) { this.targetClass = targetClass; } /** * Return the target class on which the field is defined. */ @Nullable public Class<?> getTargetClass() { return this.targetClass; } /** * Set the target object on which the field is defined. * Only necessary when the target field is not static; * else, a target class is sufficient. * @see #setTargetClass * @see #setTargetField */ public void setTargetObject(@Nullable Object targetObject) { this.targetObject = targetObject; } /** * Return the target object on which the field is defined. */ @Nullable public Object getTargetObject() { return this.targetObject; } /** * Set the name of the field to be retrieved. * Refers to either a static field or a non-static field, * depending on a target object being set. * @see #setTargetClass * @see #setTargetObject */ public void setTargetField(@Nullable String targetField) { this.targetField = (targetField != null ? StringUtils.trimAllWhitespace(targetField) : null); } /** * Return the name of the field to be retrieved. */ @Nullable public String getTargetField() { return this.targetField; } /** * Set a fully qualified static field name to retrieve, * e.g. "example.MyExampleClass.MY_EXAMPLE_FIELD". * Convenient alternative to specifying targetClass and targetField. * @see #setTargetClass * @see #setTargetField */ public void setStaticField(String staticField) { this.staticField = StringUtils.trimAllWhitespace(staticField); } /** * The bean name of this FieldRetrievingFactoryBean will be interpreted * as "staticField" pattern, if neither "targetClass" nor "targetObject" * nor "targetField" have been specified. * This allows for concise bean definitions with just an id/name. */ @Override public void setBeanName(String beanName) { this.beanName = StringUtils.trimAllWhitespace(BeanFactoryUtils.originalBeanName(beanName)); } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } @Override public void afterPropertiesSet() throws ClassNotFoundException, NoSuchFieldException { if (this.targetClass != null && this.targetObject != null) { throw new IllegalArgumentException("Specify either targetClass or targetObject, not both"); } if (this.targetClass == null && this.targetObject == null) { if (this.targetField != null) { throw new IllegalArgumentException( "Specify targetClass or targetObject in combination with targetField"); } // If no other property specified, consider bean name as static field expression. if (this.staticField == null) { this.staticField = this.beanName; Assert.state(this.staticField != null, "No target field specified"); } // Try to parse static field into class and field. int lastDotIndex = this.staticField.lastIndexOf('.'); if (lastDotIndex == -1 || lastDotIndex == this.staticField.length()) { throw new IllegalArgumentException( "staticField must be a fully qualified class plus static field name: " + "e.g. 'example.MyExampleClass.MY_EXAMPLE_FIELD'"); } String className = this.staticField.substring(0, lastDotIndex); String fieldName = this.staticField.substring(lastDotIndex + 1); this.targetClass = ClassUtils.forName(className, this.beanClassLoader); this.targetField = fieldName; } else if (this.targetField == null) { // Either targetClass or targetObject specified. throw new IllegalArgumentException("targetField is required"); } // Try to get the exact method first. Class<?> targetClass = (this.targetObject != null ? this.targetObject.getClass() : this.targetClass); this.fieldObject = targetClass.getField(this.targetField); } @Override @Nullable public Object getObject() throws IllegalAccessException { if (this.fieldObject == null) { throw new FactoryBeanNotInitializedException(); } ReflectionUtils.makeAccessible(this.fieldObject); if (this.targetObject != null) { // instance field return this.fieldObject.get(this.targetObject); } else { // class field return this.fieldObject.get(null); } } @Override public Class<?> getObjectType() { return (this.fieldObject != null ? this.fieldObject.getType() : null); } @Override public boolean isSingleton() { return false; } }
package com.davivienda.utilidades.ws.cliente.notaCreditoTarjetaCredito; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.6-1b01 * Generated source version: 2.2 * */ @WebService(name = "INotaCreditoTarjetaCreditoService", targetNamespace = "http://notacreditotarjetacreditointerface.procesadortransacciones.davivienda.com/") @XmlSeeAlso({ ObjectFactory.class }) public interface INotaCreditoTarjetaCreditoService { /** * * @param dto * @return * returns com.davivienda.sara.clientews.notaCreditoTarjetaCredito.RespuestaNotaCreditoTarjetaCreditoDto * @throws ServicioException_Exception */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "generarNotaCreditoTarjetaCredito", targetNamespace = "http://notacreditotarjetacreditointerface.procesadortransacciones.davivienda.com/", className = "com.davivienda.sara.clientews.notaCreditoTarjetaCredito.GenerarNotaCreditoTarjetaCredito") @ResponseWrapper(localName = "generarNotaCreditoTarjetaCreditoResponse", targetNamespace = "http://notacreditotarjetacreditointerface.procesadortransacciones.davivienda.com/", className = "com.davivienda.sara.clientews.notaCreditoTarjetaCredito.GenerarNotaCreditoTarjetaCreditoResponse") public RespuestaNotaCreditoTarjetaCreditoDto generarNotaCreditoTarjetaCredito( @WebParam(name = "dto", targetNamespace = "") NotaCreditoTarjetaCreditoDto dto) throws ServicioException_Exception ; }
package com.wxt.designpattern.factorymethod.test04; /** * @Auther: weixiaotao * @ClassName C2 * @Date: 2018/10/22 15:31 * @Description: */ public class C2 implements C1{ @Override public void tc() { } }
package gil.server.data; import org.junit.Test; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; public class PeopleDataTest { @Test public void shouldAddAPerson() { PeopleData peopleData = new PeopleData(); Person p = peopleData.addPerson("Gil1", "g@tdd.com"); Person retrievedPerson = peopleData.getPerson(p.getId()); assertEquals("Gil1", retrievedPerson.getName()); assertEquals("g@tdd.com", retrievedPerson.getEmail()); } @Test public void shouldAddMultiplePersons() { PeopleData peopleData = new PeopleData(); Person p = peopleData.addPerson("Gil2", "g@tdd.com"); assertEquals("Gil2", p.getName()); assertEquals("g@tdd.com", p.getEmail()); assertTrue(p.getId() >= 0); Person p2 = peopleData.addPerson("Angel2", "a@tdd.com"); assertEquals("Angel2", p2.getName()); assertEquals("a@tdd.com", p2.getEmail()); assertTrue(p2.getId() >= 0); assertNotEquals(p.getId(), p2.getId()); } @Test public void shouldConvertAStringRepresentingAPersonToAJsonObject() { PeopleData peopleData = new PeopleData(); String jsonString = "{\"name\": \"Gil\", \"email\": \"g@tdd.com\"}"; JsonObject jsonObject = peopleData.getPersonJSONObject(jsonString); assertEquals("Gil", jsonObject.getString("name")); assertEquals("g@tdd.com", jsonObject.getString("email")); } @Test public void shouldReturnAJSONObjectWithAnArrayOfPeople() { PeopleData peopleData = new PeopleData(); peopleData.addPerson("Oliver", "oliver@tdd.com"); JsonObject data = peopleData.getPeople(); JsonArray people = data.getJsonArray("people"); Integer indexOfLastPersonAdded = people.size(); JsonObject lastPersonEntered = people.getJsonObject(indexOfLastPersonAdded - 1); assertEquals("Oliver", lastPersonEntered.getString("name")); assertEquals("oliver@tdd.com", lastPersonEntered.getString("email")); } @Test public void shouldAcceptAJsonObjectToUpdateTheStoreOfPeople() { String jsonString = "{\"id\": 0, \"name\": \"Gil\", \"email\": \"g@tdd.com\"}"; PeopleData peopleData = new PeopleData(); JsonObject personAsJSON = peopleData.getPersonJSONObject(jsonString); JsonArray people = Json.createArrayBuilder().add(personAsJSON).build(); JsonObject data = Json.createObjectBuilder().add("people", people).build(); peopleData.updatePeople(data); Person retrievedPerson = peopleData.getPerson(0); assertEquals("Gil", retrievedPerson.getName()); assertEquals("g@tdd.com", retrievedPerson.getEmail()); } }
package tony.hortalizas; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; /** * Created by Tony on 06/02/2017. */ public class HortalizasAdapter extends ArrayAdapter<String>{ private Activity context; private final String[] titulos; private final String[] descripciones; private final int[] imagenes; public HortalizasAdapter(Activity context, String[] titulos, String[] descripciones, int[] imagenes){ super(context,R.layout.item_hortaliza,titulos); this.context = context; this.titulos = titulos; this.descripciones = descripciones; this.imagenes = imagenes; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View item = inflater.inflate(R.layout.item_hortaliza, null, true); TextView nombre = (TextView) item.findViewById(R.id.nombreHortaliza); ImageView imagen = (ImageView) item.findViewById(R.id.imagenHortaliza); TextView descripcionHortaliza = (TextView) item.findViewById(R.id.subtituloHortaliza); nombre.setText(titulos[position]); descripcionHortaliza.setText(descripciones[position]); imagen.setImageResource(imagenes[position]); return item; } }
package hellorestclient; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; public class UntypedHelloClient { public static void main(String[] args) { try{ // Create a new RESTeasy client through the JAX-RS API: Client client = ClientBuilder.newClient(); // The base URL of the service: WebTarget target = client.target("http://localhost:8082/TestRest/rest"); // Building the relative URL manually for the sayHello method: WebTarget hello = target.path("hello").path("sayHello").queryParam("name", "me"); // Get the response from the target URL: Response response = hello.request().get(); // Read the result as a String: String result = response.readEntity(String.class); // Print the result to the standard output: System.out.println(result); // Close the connection: response.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
package com.cif.accumulate.rest.controller; import org.springframework.web.bind.annotation.RestController; /** * @Author: liuxincai * @Description: base controller * @Date: 2019/5/25 11:49 */ @RestController public class BaseController { }
package graphics_control.files_and_parsing; import graphics_control.game_control.ParsedValues; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * PreferencesFileParser Class. */ public class PreferencesFileParser { static final int PREFERENCE = 0; static final int CHOICE = 1; /** * parseFile(). * * @return a ParsedValues object, containing the preferences set by the player. */ public ParsedValues parseFile() { String firstTurnPlayer = null; String player1Color = null; String player2Color = null; String boardSize = null; try { BufferedReader bufferedReader = new BufferedReader(new FileReader("preferences.txt")); String currLine; while ((currLine = bufferedReader.readLine()) != null) { String[] preference = currLine.split(" "); switch (preference[PREFERENCE]) { case "firstTurnPlayer:": firstTurnPlayer = preference[CHOICE]; break; case "player1Color:": player1Color = preference[CHOICE]; break; case "player2Color:": player2Color = preference[CHOICE]; break; case "boardSize:": boardSize = preference[CHOICE]; break; } } bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } return new ParsedValues(firstTurnPlayer, player1Color, player2Color, boardSize); } }
package MVC.controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import MVC.models.inventoryModel; import MVC.models.productModel; import MVC.views.addInvsView; import MVC.views.cProductView; import MVC.views.errorView; public class productController implements ActionListener { private cProductView view; private inventoryModel model; private productModel proModel; private errorView errorView; private ArrayList<String> partsList = new ArrayList(); private ArrayList<String> parts = new ArrayList(); private ArrayList<String> products = new ArrayList(); private int flag = 0; public productController(inventoryModel model, productModel proModel, cProductView view) { // TODO Auto-generated constructor stub this.view = view; this.model = model; this.proModel = proModel; } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String command = e.getActionCommand(); if (command.equals("Cancel")) { view.closeWindow(); } else if (command.equals("Create Product")) { String product = view.getProduct(); String location = view.getLoc(); parts.clear(); // System.out.println("product = " +product+ ", loccation = " // +location); // int locId = model.getLocationId(location); parts = model.getLocationIdPartByName(location); // System.out.println("parts at location selected = " // +parts.toString()); flag = model.getProductFlag(); if (flag == 1) { products = model.getProductsArray(location); // System.out.println("product Arraylist = " // +products.toString()); for (String tmp : products) { // System.out.println("products"); int pid = Integer.parseInt(tmp); String productDesc = proModel.getProductDescById(pid); parts.add(productDesc); break; } model.resetSearch(); } // System.out.println("parts at location selected = "+parts.toString()); int productId = proModel.getProductIdByDesc(product); proModel.setId(productId); proModel.getAllProductParts(); partsList = proModel.getProductPartsArray(); // System.out.println("product parts list = " // +partsList.toString()); model.checkCreation(parts, partsList); int exist = model.checkProductQ(product); if (exist == 1) { model.updateProductQ(product, productId); model.resetInv(); model.resetList(); view.closeWindow(); } else { if (model.getFlag() == 0) { model.addProduct(productId, location); model.resetInv(); model.resetList(); view.closeWindow(); } else if (model.getFlag() == 1) { errorView = new errorView(model); errorView.setSize(400, 300); errorView.setVisible(true); } } } } }
package com.example.graduation; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.res.ResourcesCompat; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.graduation.java.HttpUtil; import com.example.graduation.java.StatusBarTransparent; import com.google.gson.Gson; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.Response; public class TeacherActivity extends AppCompatActivity implements View.OnClickListener { private ImageView imageBack; private TextView textSchool; private SharedPreferences sp; private SharedPreferences sharedPreferences; private SharedPreferences.Editor editor; private String school; private String uid; private ListView listView; private String[] grade = {"一","二","三","四","五","六",}; private List<String> gradeList; private int itemPosition; private String url = "http://47.106.112.29:8080/class/createClass"; private Button butCreate; private Handler mHandler = new Handler(){ @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); switch(msg.what){ case 1: editor.putString("myclass","yes"); editor.commit(); finish(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_teacher); if (getSupportActionBar() != null){ getSupportActionBar().hide(); StatusBarTransparent.makeStatusBarTransparent(this); } initView(); } private void initView(){ imageBack = findViewById(R.id.teacher_image_back); textSchool = findViewById(R.id.teacher_text_school); textSchool.setOnClickListener(this); imageBack.setOnClickListener(this); listView = findViewById(R.id.teacher_listview); butCreate = findViewById(R.id.teacher_button_ceate); butCreate.setOnClickListener(this); sp = getSharedPreferences("modul",MODE_PRIVATE); school = sp.getString("school",""); if (school!=null && !TextUtils.isEmpty(school)){ textSchool.setText(school); } sharedPreferences = getSharedPreferences("user",MODE_PRIVATE); editor = sharedPreferences.edit(); uid = sharedPreferences.getString("uid",""); gradeList = new ArrayList<>(); for (int i = 0; i < grade.length; i++) { gradeList.add(grade[i]); } final Adapter adapter = new Adapter(this,gradeList); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { adapter.setDefSelect(position); itemPosition = position; } }); } @Override protected void onRestart() { super.onRestart(); school = sp.getString("school",""); if (school!=null && !TextUtils.isEmpty(school)){ textSchool.setText(school); } } @Override public void onClick(View v) { switch(v.getId()){ case R.id.teacher_image_back: finish(); break; case R.id.teacher_text_school: startActivity(new Intent(TeacherActivity.this,SearchSchoolActivity.class)); break; case R.id.teacher_button_ceate: createClass(url); break; } } private void createClass(String url){ ClassModel classModel = new ClassModel(school,grade[itemPosition],uid); Gson gson = new Gson(); String json = gson.toJson(classModel); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); HttpUtil.sendJsonOkhttpRequest(url, body, new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { Log.e("createClass",response.body().string()); Message msg = new Message(); msg.what = 1; mHandler.sendMessage(msg); } }); } class ClassModel { private String school; private String grade; private String createId; public ClassModel(String school,String grade,String createId){ this.school = school; this.grade = grade; this.createId = createId; } } class Adapter extends BaseAdapter{ private Context context; private List<String> list; int defItem; public Adapter(Context context,List<String> list){ this.context = context; this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = LayoutInflater.from(context).inflate(R.layout.gradelistview_item,null); TextView grade = convertView.findViewById(R.id.gradelistview_text_grade); grade.setText(list.get(position)+"年级"); if (defItem == position){ Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.gradelistview_item_click, null); convertView.setBackground(drawable); }else{ Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.gradelistview_item_normal, null); convertView.setBackground(drawable); } return convertView; } public void setDefSelect(int position){ this.defItem = position; notifyDataSetChanged(); } } }
package org.quickbundle.itf.base; public interface IRmIdWrapper { public void init(); public String[] nextValue(int length); }
package com.filestore.callable; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.concurrent.Callable; import org.codehaus.jettison.json.JSONObject; public class DeleteCallable implements Callable<Boolean> { private String key = null; private int expiryTime = 0; private String storeLoc = null; public DeleteCallable(String key, String dataStoreLocation) { this.key = key; this.storeLoc=dataStoreLocation; } @Override public Boolean call() throws Exception { boolean isDone = true; try { String className = "com.filestore.manager.DataStoreManager"; Class<?> classType = Class.forName(className); Class<?>[] parameterTypesForConstructor = {}; Constructor<?> constructorInstance = classType.getConstructor(parameterTypesForConstructor); Object[] initArguments = {}; Object instance = constructorInstance.newInstance(initArguments); Class<?>[] parameterTypes = { String.class, String.class }; Object[] args = { this.key, this.storeLoc }; Method methodToInvoke; methodToInvoke = classType.getMethod("delete", parameterTypes); methodToInvoke.invoke(instance, args); } catch (Exception e) { isDone = false; e.printStackTrace(); } return isDone; } }
/* * Copyright 2002-2019 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.context.request; import jakarta.servlet.ServletRequestEvent; import org.junit.jupiter.api.Test; import org.springframework.core.task.MockRunnable; import org.springframework.web.testfixture.servlet.MockHttpServletRequest; import org.springframework.web.testfixture.servlet.MockServletContext; import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller */ public class RequestContextListenerTests { @Test public void requestContextListenerWithSameThread() { RequestContextListener listener = new RequestContextListener(); MockServletContext context = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(context); request.setAttribute("test", "value"); assertThat(RequestContextHolder.getRequestAttributes()).isNull(); listener.requestInitialized(new ServletRequestEvent(context, request)); assertThat(RequestContextHolder.getRequestAttributes()).isNotNull(); assertThat(RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)).isEqualTo("value"); MockRunnable runnable = new MockRunnable(); RequestContextHolder.getRequestAttributes().registerDestructionCallback( "test", runnable, RequestAttributes.SCOPE_REQUEST); listener.requestDestroyed(new ServletRequestEvent(context, request)); assertThat(RequestContextHolder.getRequestAttributes()).isNull(); assertThat(runnable.wasExecuted()).isTrue(); } @Test public void requestContextListenerWithSameThreadAndAttributesGone() { RequestContextListener listener = new RequestContextListener(); MockServletContext context = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(context); request.setAttribute("test", "value"); assertThat(RequestContextHolder.getRequestAttributes()).isNull(); listener.requestInitialized(new ServletRequestEvent(context, request)); assertThat(RequestContextHolder.getRequestAttributes()).isNotNull(); assertThat(RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)).isEqualTo("value"); MockRunnable runnable = new MockRunnable(); RequestContextHolder.getRequestAttributes().registerDestructionCallback( "test", runnable, RequestAttributes.SCOPE_REQUEST); request.clearAttributes(); listener.requestDestroyed(new ServletRequestEvent(context, request)); assertThat(RequestContextHolder.getRequestAttributes()).isNull(); assertThat(runnable.wasExecuted()).isTrue(); } @Test public void requestContextListenerWithDifferentThread() { final RequestContextListener listener = new RequestContextListener(); final MockServletContext context = new MockServletContext(); final MockHttpServletRequest request = new MockHttpServletRequest(context); request.setAttribute("test", "value"); assertThat(RequestContextHolder.getRequestAttributes()).isNull(); listener.requestInitialized(new ServletRequestEvent(context, request)); assertThat(RequestContextHolder.getRequestAttributes()).isNotNull(); assertThat(RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)).isEqualTo("value"); MockRunnable runnable = new MockRunnable(); RequestContextHolder.getRequestAttributes().registerDestructionCallback( "test", runnable, RequestAttributes.SCOPE_REQUEST); // Execute requestDestroyed callback in different thread. Thread thread = new Thread() { @Override public void run() { listener.requestDestroyed(new ServletRequestEvent(context, request)); } }; thread.start(); try { thread.join(); } catch (InterruptedException ex) { } // Still bound to original thread, but at least completed. assertThat(RequestContextHolder.getRequestAttributes()).isNotNull(); assertThat(runnable.wasExecuted()).isTrue(); // Check that a repeated execution in the same thread works and performs cleanup. listener.requestInitialized(new ServletRequestEvent(context, request)); listener.requestDestroyed(new ServletRequestEvent(context, request)); assertThat(RequestContextHolder.getRequestAttributes()).isNull(); } }
package com.lwc.auth.fallback; import com.lwc.auth.api.AuthApi; import com.lwc.auth.bo.AuthBo; import com.lwc.common.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.security.jwt.Jwt; import org.springframework.stereotype.Component; @Component @Slf4j public class AuthApiFallback implements AuthApi { @Override public Result<Boolean> checkIgnore(AuthBo authBo) { log.warn("checkIgnore接口异常,已熔断", authBo); return Result.FAILED("checkIgnore接口异常,已熔断"); } @Override public Result<Boolean> hasPermission(AuthBo authBo) { log.warn("hasPermission接口异常,已熔断", authBo); return Result.FAILED("hasPermission接口异常,已熔断"); } @Override public Result<Jwt> getJwt(AuthBo authBo) { log.warn("getJwt接口异常,已熔断", authBo); return Result.FAILED("getJwt接口异常,已熔断"); } }
package com.mod.loan.config.pb; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class PbConfig { @Value("${pb.merchant.id:}") private String merchantId; @Value("${pb.version:}") private String version; @Value("${pb.product.id:}") private String productId; @Value("${pb.private.key:}") private String privateKey; @Value("${pb.public.key:}") private String publicKey; @Value("${pb.prev.host:}") private String prevHost; public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public String getPublicKey() { return publicKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getPrevHost() { return prevHost; } public void setPrevHost(String prevHost) { this.prevHost = prevHost; } @Override public String toString() { return "PbConfig{" + "merchantId='" + merchantId + '\'' + ", version='" + version + '\'' + ", productId='" + productId + '\'' + ", privateKey='" + privateKey + '\'' + ", publicKey='" + publicKey + '\'' + ", prevHost='" + prevHost + '\'' + '}'; } }
package de.fraunhofer.iais.kd.bda.spark; public class Basic { public static long hash(int i, String s) { long[] prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173}; long p = 1009; long r = 1000; long a = prime[i]; long b = prime[i+20]; long x = Math.abs(s.hashCode()); long res = ((a*x + b) % p) % r; return res; } }
//Exercise 2.28 import java.util. Scanner; import java.lang.Math; public class Area{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int r; int diameter; double area; double circumference; System.out.print("Enter the value of radius "); r = scan.nextInt(); diameter = r * r; circumference = 2 * r * Math.PI; area = r * r * Math.PI ; System.out.println("Area is: " + area); System.out.println("Circumference is: " + circumference); System.out.println("Diameter is: " + diameter); } }
package org.wuxinshui.boosters.data; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; /** * @ClassName: MathUtils * @author: [Wuxinshui] * @CreateDate: 2017/8/1 14:07 * @UpdateUser: [Wuxinshui] * @UpdateDate: 2017/8/1 14:07 * @UpdateRemark: [说明本次修改内容] * @Description: [TODO(用一句话描述该文件做什么)] * @version: [V1.0] */ public class MathUtils { /** * 由于Java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精 确的浮点数运算,包括加减乘除和四舍五入。 */ // 默认运算精度 private static final int DEFAULT_SCALE = 10; // 这个类不能实例化 private MathUtils() { } /** * 提供精确的加法运算。 * * @param v1 被加数 * @param v2 加数 * @return 两个参数的和 */ public static double add(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2).doubleValue(); } /** * 提供精确的减法运算。 * * @param v1 被减数 * @param v2 减数 * @return 两个参数的差 */ public static double sub(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.subtract(b2).doubleValue(); } /** * 提供精确的乘法运算。 * * @param v1 被乘数 * @param v2 乘数 * @return 两个参数的积 */ public static double mul(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.multiply(b2).doubleValue(); } /** * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。 * * @param v1 被除数 * @param v2 除数 * @return 两个参数的商 */ public static double div(double v1, double v2) { return div(v1, v2, DEFAULT_SCALE); } /** * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。 * * @param v1 被除数 * @param v2 除数 * @param scale 表示表示需要精确到小数点以后几位。 * @return 两个参数的商 */ public static double div(double v1, double v2, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /** * 提供精确的小数位四舍五入处理。 * * @param v 需要四舍五入的数字 * @param scale 小数点后保留几位 * @return 四舍五入后的结果 */ public static double round(double v, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static BigDecimal getBigDecimalByObject(Object obj) { BigDecimal bd = new BigDecimal(0); if (obj.getClass().getName().equals("java.lang.Integer")) { bd = new BigDecimal((Integer) obj); } else if (obj.getClass().getName().equals("java.lang.Float")) { bd = new BigDecimal((Float) obj); } else if (obj.getClass().getName().equals("java.lang.Double")) { bd = new BigDecimal((Double) obj); } else if (obj.getClass().getName().equals("java.math.BigDecimal")) { bd = (BigDecimal) obj; } return bd; } /** * 方差s^2=[(x1-x)^2 +...(xn-x)^2]/n * 默认精度:10 * * @param x * @return */ public static BigDecimal variance(BigDecimal[] x) { return variance(x, 10); } /** * 方差s^2=[(x1-x)^2 +...(xn-x)^2]/n * 默认精度:10 * 默认精度策略:RoundingMode.HALF_UP * * @param x * @return */ public static BigDecimal variance(BigDecimal[] x, int scale) { return variance(x, scale, RoundingMode.HALF_UP); } /** * 方差s^2=[(x1-x)^2 +...(xn-x)^2]/n * 结果精度:scale * * @param x * @param scale * @return */ public static BigDecimal variance(BigDecimal[] x, int scale, RoundingMode setRoundingMode) { BigDecimal m = new BigDecimal(x.length); if (m.compareTo(BigDecimal.ZERO)==0){ return BigDecimal.ZERO; } BigDecimal sum = BigDecimal.ZERO; //求和 for (BigDecimal b : x) { sum = sum.add(b); } //求平均值 BigDecimal dAve = sum.divide(m, 10, setRoundingMode); BigDecimal dVar = BigDecimal.ZERO; //求方差 for (BigDecimal b : x) { dVar = dVar.add(b.subtract(dAve).pow(2)); } return dVar.divide(m, 10, setRoundingMode).setScale(scale, setRoundingMode); } /** * 标准差σ=sqrt(s^2) * 默认精度:10 * * @param x * @return */ public static BigDecimal standardDeviation(BigDecimal[] x) { return standardDeviation(x, DEFAULT_SCALE); } /** * 标准差σ=sqrt(s^2) * 结果精度:scale * 默认精度策略:RoundingMode.HALF_UP * 牛顿迭代法求大数开方 * * @param x * @param scale * @return */ public static BigDecimal standardDeviation(BigDecimal[] x, int scale) { //默认RoundingMode.HALF_UP return standardDeviation(x, scale, RoundingMode.HALF_UP); } /** * 标准差σ=sqrt(s^2) * 结果精度:scale * 牛顿迭代法求大数开方 * * @param x * @param scale * @return */ public static BigDecimal standardDeviation(BigDecimal[] x, int scale, RoundingMode setRoundingMode) { //方差 BigDecimal variance = variance(x, scale); if (variance.compareTo(BigDecimal.ZERO)==0){ return BigDecimal.ZERO; } BigDecimal base2 = BigDecimal.valueOf(2.0); //计算精度 int precision = 100; MathContext mc = new MathContext(precision, setRoundingMode); BigDecimal deviation = variance; int cnt = 0; while (cnt < 100) { deviation = (deviation.add(variance.divide(deviation, mc))).divide(base2, mc); cnt++; } deviation = deviation.setScale(scale, setRoundingMode); return deviation; } }
package page.test; import java.util.Scanner; import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import page.objects.LoginPage; import utility.*; public class LoginPageTest { public static void fillForm(WebDriver driver) throws Exception { String data; ExcelUtils.setExcelFile(Constant.Path_TestData + Constant.File_TestData, Constant.SHEET_NAME); /* * Loop that is initiating pass through the Excel table where is collecting data * and using for automated login from 0-i */ for (int i = 1; i < ExcelUtils.getWorkSheet().getLastRowNum(); i++) { LoginPage.clickLogUsername(driver); data = ExcelUtils.getCellData(i, 2); LoginPage.SendKeysLogUsername(driver, data); LoginPage.clickLogPassword(driver); data = ExcelUtils.getCellData(i, 4); LoginPage.SendKeysLogPassword(driver, data); LoginPage.clickLoginButton(driver); LoginPage.clickLogoutButton(driver); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } } /* * User is asked to create login by scanner and those data are used for * automated login on website */ public static void ScannerLog(WebDriver driver) throws Exception { Scanner sc = new Scanner(System.in); LoginPage.clickLogUsername(driver); System.out.println("Please, enter your Username:"); String Username = sc.nextLine(); LoginPage.SendKeysLogUsername(driver, Username); LoginPage.clickLogPassword(driver); System.out.println("Please, enter your Password:"); String Password = sc.nextLine(); LoginPage.SendKeysLogPassword(driver, Password); LoginPage.clickLoginButton(driver); LoginPage.clickLogoutButton(driver); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); sc.close(); } }
package com.futs.model; import lombok.Data; import javax.persistence.*; import java.util.Date; @Data @Entity @Table(schema = "DB_FUTTS", name = "TB_JOGADOR") public class Jogador { @Id @Column(name = "IDT", unique = true, nullable = false) private String idt; @Column(name = "IDTIME", unique = true, nullable = false) private Integer idTime; @Column(name = "NOME") private String nome; @Column(name = "VERSAO", unique = true, nullable = false) private char versao; @Column(name = "INICIO_CONTRATO") private Date inicioContrato; @Column(name = "FIM_CONTRATO") private Date fimContrato; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "IDTIME", referencedColumnName = "ID", insertable = false, updatable = false) private Time time; }
package com.uniksoft.web; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import org.springframework.web.servlet.view.RedirectView; import com.uniksoft.domain.ProductManager; import com.uniksoft.service.PriceIncrease; public class PriceIncreaseFormController extends SimpleFormController { private ProductManager productManager; public ModelAndView onSubmit(Object command) throws ServletException { int increase = ((PriceIncrease) command).getPercentage(); productManager.increasePrice(increase); return new ModelAndView(new RedirectView(getSuccessView())); } protected Object formBackingObject(HttpServletRequest request) throws ServletException { PriceIncrease priceIncrease = new PriceIncrease(); priceIncrease.setPercentage(20); return priceIncrease; } public void setProductManager(ProductManager productManager) { this.productManager = productManager; } public ProductManager getProductManager() { return productManager; } }
package br.com.senac.Telas; import br.com.senac.Classes.Mamifero; import br.com.senac.Exceptions.MamiferoException; import br.com.senac.Servicos.MamiferoServico; import java.awt.Dimension; import java.util.ArrayList; import javax.swing.JInternalFrame; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; public class MamiferoConsultar extends javax.swing.JInternalFrame { private MamiferoEditar mamiferoEditar = new MamiferoEditar(); String ultimaPesquisa = null; public MamiferoConsultar() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); textPesquisar = new javax.swing.JTextField(); buttonPesquisar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tabelaPesquisa = new javax.swing.JTable(); buttonExcluir = new javax.swing.JButton(); buttonEditar = new javax.swing.JButton(); setClosable(true); setIconifiable(true); setToolTipText("Pesquisar Aves"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Pesquisar")); jLabel1.setText("Espécie"); buttonPesquisar.setText("Buscar"); buttonPesquisar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonPesquisarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(179, 179, 179) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 369, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(buttonPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(textPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buttonPesquisar)) .addContainerGap(16, Short.MAX_VALUE)) ); tabelaPesquisa.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "Espécie", "Locomoção", "Tamanho", "Peso", "Gênero", "Cor", "Pelo", "Membros", "Quantidade" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane1.setViewportView(tabelaPesquisa); buttonExcluir.setText("Excluir"); buttonExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonExcluirActionPerformed(evt); } }); buttonEditar.setText("Editar"); buttonEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonEditarActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.PREFERRED_SIZE, 867, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(buttonEditar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(buttonExcluir))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(buttonExcluir) .addComponent(buttonEditar)) .addGap(0, 25, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void buttonPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPesquisarActionPerformed boolean resultSearch = false; if (textPesquisar.getText() != null && !textPesquisar.getText().equals("")) { try { ultimaPesquisa = textPesquisar.getText(); } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, "Só é possível" + " pesquisar por um valor inteiro válido", "Campo de pesquisa inválido", JOptionPane.ERROR_MESSAGE); return; } } else { ultimaPesquisa = null; } try { resultSearch = atualizarLista(); } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, e.getMessage(), "Falha ao obter lista", JOptionPane.ERROR_MESSAGE); return; } if (!resultSearch) { JOptionPane.showMessageDialog(rootPane, "A pesquisa não retornou " + "resultados ", "Sem resultados", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_buttonPesquisarActionPerformed private void buttonExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExcluirActionPerformed if (tabelaPesquisa.getSelectedRow() >= 0) { final int row = tabelaPesquisa.getSelectedRow(); String nome = (String) tabelaPesquisa.getValueAt(row, 1); int resposta = JOptionPane.showConfirmDialog(rootPane, "Excluir o mamífero \"" + nome + "\"?", "Confirmar exclusao", JOptionPane.YES_OPTION); if (resposta == JOptionPane.YES_OPTION) { try { Integer id = (Integer) tabelaPesquisa.getValueAt(row, 0); MamiferoServico.excluirMamifero(id); JOptionPane.showMessageDialog(rootPane, "Mamífero excluida com sucesso"); this.atualizarLista(); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(rootPane, e.getMessage(), "Erro ao excluir", JOptionPane.ERROR_MESSAGE); } } } }//GEN-LAST:event_buttonExcluirActionPerformed private void buttonEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEditarActionPerformed try { final int row = tabelaPesquisa.getSelectedRow(); if (row >= 0) { Integer id = (Integer) tabelaPesquisa.getValueAt(row, 0); Mamifero mamifero = MamiferoServico.obterMamifero(id); mamiferoEditar.dispose(); mamiferoEditar = new MamiferoEditar(); mamiferoEditar.setMamifero(mamifero); mamiferoEditar.setTitle("Mamífero: " + mamifero.getEspecie()); this.getParent().add(mamiferoEditar); this.openFrameInCenter(mamiferoEditar); mamiferoEditar.toFront(); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(rootPane, "Não é possível " + "exibir os detalhes deste mamífero.", "Erro ao abrir detalhe", JOptionPane.ERROR_MESSAGE); } this.dispose(); }//GEN-LAST:event_buttonEditarActionPerformed public boolean atualizarLista() throws MamiferoException, Exception { ArrayList<Mamifero> resultado = MamiferoServico.procurarMamifero(ultimaPesquisa); DefaultTableModel model = (DefaultTableModel) tabelaPesquisa.getModel(); model.setRowCount(0); if (resultado == null || resultado.size() <= 0) { return false; } for (int i = 0; i < resultado.size(); i++) { Mamifero mamifero = resultado.get(i); if (mamifero != null) { Object[] row = new Object[10]; row[0] = mamifero.getId(); row[1] = mamifero.getEspecie(); row[2] = mamifero.getLocomocao(); row[3] = mamifero.getTamanho(); row[4] = mamifero.getPeso(); row[5] = mamifero.getGenero(); row[6] = mamifero.getCor(); row[7] = mamifero.getPelo(); row[8] = mamifero.getMembros(); row[9] = mamifero.getQuantidade(); model.addRow(row); } } return true; } public void centralizar() { Dimension d = this.getDesktopPane().getSize(); this.setLocation((d.width - this.getSize().width) / 2, (d.height - this.getSize().height) / 2); } public void openFrameInCenter(JInternalFrame jif) { Dimension desktopSize = this.getParent().getSize(); Dimension jInternalFrameSize = jif.getSize(); int width = (desktopSize.width - jInternalFrameSize.width) / 2; int height = (desktopSize.height - jInternalFrameSize.height) / 2; jif.setLocation(width, height); jif.setVisible(true); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buttonEditar; private javax.swing.JButton buttonExcluir; private javax.swing.JButton buttonPesquisar; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tabelaPesquisa; private javax.swing.JTextField textPesquisar; // End of variables declaration//GEN-END:variables }
package com.testcases; import org.testng.annotations.Test; import com.BaseClass.BaseClass; import com.BaseClass.TestDataUtility; public class SearchCustomers extends BaseClass{ @Test(dataProviderClass =TestDataUtility.class,dataProvider = "dp" ) public void SearchCustomersTest(String Name) throws InterruptedException { click("customersBtn_CSS"); type("SearchInput_CSS",Name); Thread.sleep(3000); click("DeleteBtton_CSS"); } }
public class quickfuf{ private int [] parent; public void quickfuf(int n) { parent=new int[n]; for(int i=0; i<n; i++) parent[i]=i; } public int find(int p) { while(p != parent[p]) p = parent[p]; return p; } private void validate(int p) { int n = parent.length; if (p < 0 || p >= n) { throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1)); } } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; parent[rootP] = rootQ; } public boolean connected(int p, int q) { return find(p) == find(q); } public static void main(String[] args) { int n = StdIn.readInt(); QuickUnionUF uf = new QuickUnionUF(n); while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.find(p) == uf.find(q)) continue; uf.union(p, q); StdOut.println(p + " " + q); } } }
package Problem_2153; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int number = 0; for(int i = 0; i<str.length();i++) { char s = str.charAt(i); if('A' <= s && s <='Z') { number += (s-'A'+27); } if('a' <= s && s <='z') { number += (s-'a'+1); } } boolean[] isPrime = new boolean[3000]; Arrays.fill(isPrime, true); isPrime[0] = false; isPrime[1] = true; for(int i = 2; i<= 2000; i++) { for(int j = i+i; j<=2000; j += i) { isPrime[j] = false; } } if(isPrime[number]) System.out.println("It is a prime word."); else System.out.println("It is not a prime word."); } }
public class test { public static void main(String[] args) { Frazione f = new Frazione(8, 3, '-'); System.out.println(f.toString()); } }
public class EditDistance { public int minDistance(String word1, String word2) { int m = word1.length(),n = word2.length(); int ans[] = new int[n+1]; int prev,cuv; for(int i=0;i<=n;i++){ ans[i] = i; } for(int i=1;i<=m;i++){ prev = i; for(int j=1;j<=n;j++){ if( word1.charAt(i-1) == word2.charAt(j-1) ){ cuv = ans[j-1]; }else{ cuv = Math.min( Math.min( ans[j], prev) , ans[j-1]) + 1; } ans[j-1] = prev; prev = cuv; } ans[n] = prev; } return ans[n]; } }
package raft.server.storage; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import java.util.ArrayList; import java.util.List; /** * Author: ylgrgyq * Date: 18/6/10 */ class ManifestRecord { private int nextFileNumber; private int logNumber; private Type type; private final List<SSTableFileMetaInfo> metas; private ManifestRecord(Type type) { this.metas = new ArrayList<>(); this.type = type; } static ManifestRecord newPlainRecord(){ return new ManifestRecord(Type.PLAIN); } static ManifestRecord newReplaceAllExistedMetasRecord() { return new ManifestRecord(Type.REPLACE_METAS); } int getNextFileNumber() { if (type == Type.PLAIN) { return nextFileNumber; } else { return -1; } } void setNextFileNumber(int nextFileNumber) { assert type == Type.PLAIN; this.nextFileNumber = nextFileNumber; } int getLogNumber() { if (type == Type.PLAIN) { return logNumber; } else { return -1; } } void setLogNumber(int logNumber) { this.logNumber = logNumber; } Type getType() { return type; } List<SSTableFileMetaInfo> getMetas() { return metas; } void addMeta(SSTableFileMetaInfo meta) { assert meta != null; metas.add(meta); } void addMetas(List<SSTableFileMetaInfo> ms) { assert ms != null && ! ms.isEmpty(); metas.addAll(ms); } byte[] encode(){ ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeInt(nextFileNumber); out.writeInt(logNumber); out.writeInt(metas.size()); for (SSTableFileMetaInfo meta : metas) { out.writeLong(meta.getFileSize()); out.writeInt(meta.getFileNumber()); out.writeLong(meta.getFirstKey()); out.writeLong(meta.getLastKey()); } return out.toByteArray(); } static ManifestRecord decode(byte[] bytes) { ManifestRecord record = new ManifestRecord(Type.PLAIN); ByteArrayDataInput in = ByteStreams.newDataInput(bytes); record.setNextFileNumber(in.readInt()); record.setLogNumber(in.readInt()); int metasSize = in.readInt(); for (int i = 0; i < metasSize; i++) { SSTableFileMetaInfo meta = new SSTableFileMetaInfo(); meta.setFileSize(in.readLong()); meta.setFileNumber(in.readInt()); meta.setFirstKey(in.readLong()); meta.setLastKey(in.readLong()); record.addMeta(meta); } return record; } @Override public String toString() { StringBuilder builder = new StringBuilder("ManifestRecord{" + "type=" + type + ", nextFileNumber=" + nextFileNumber + ", logNumber=" + logNumber); if (!metas.isEmpty()) { long from = metas.get(0).getFirstKey(); long to = metas.get(metas.size() - 1).getLastKey(); builder.append(", metaKeysFrom="); builder.append(from); builder.append(", metaKeysTo="); builder.append(to); } builder.append("}"); return builder.toString(); } enum Type { PLAIN, REPLACE_METAS } }
package com.beike.entity.onlineorder; public enum DiscoutType { OVERALLFOLD,FULLLESS,INTERVALLESS }
public class SplayRecord<K extends Comparable<K>, V> implements Comparable<SplayRecord<K, V>>{ private K key; private V value; private SplayRecord<K, V> left; private SplayRecord<K, V> right; private SplayRecord<K, V> parent; public SplayRecord(K key, V value){ this.key = key; this.value = value; } public void setParent(SplayRecord<K, V> parent) { this.parent = parent; } public void setValue(V value) { this.value = value; } public void setKey(K key) { this.key = key; } public void setRight(SplayRecord<K, V> right) { this.right = right; } public void setLeft(SplayRecord<K, V> left) { this.left = left; } public V getValue() { return value; } public K getKey() { return key; } public SplayRecord<K, V> getRight() { return right; } public SplayRecord<K, V> getLeft() { return left; } public SplayRecord<K, V> getParent() { return parent; } @Override public int compareTo(SplayRecord<K, V> other){ return this.key.compareTo(other.getKey()); } @Override public String toString(){ return "Key: " + (this.key == null ? "" : this.key.toString()) + " " + "Value: " + (this.value == null ? "" : this.value.toString()) + "\n\t" + "To the left: " + (this.left == null ? "" : this.left.toString()) + "\n\t" + "To the right: " + (this.right == null ? "" : this.right.toString()); } }
package com.software3.servlet; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.software3.service.BookService; import com.software3.service.UserService; import com.software3.service.impl.BookServiceImpl; import com.software3.service.impl.UserServiceImpl; @WebServlet("/borrowbook") public class BorrowBookServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; BookService bs = new BookServiceImpl(); UserService us = new UserServiceImpl(); protected void doGet(HttpServletRequest request,HttpServletResponse response){ response.setCharacterEncoding("utf-8"); //检查积分 if(!us.checkCredits(request.getSession(true).getAttribute("studentid").toString())){ try { response.getWriter().write("积分不够,请先分享图书"); } catch (IOException e) { e.printStackTrace(); } return ; } String studentid = request.getSession(true).getAttribute("studentid").toString(); String bookid = request.getParameter("bookid"); String remark = "双方已同意"; try { if(bs.BorrowBook(studentid, bookid, remark)){ response.getWriter().write("操作成功"); }else{ response.getWriter().write("操作失败"); } } catch (IOException e) { e.printStackTrace(); } } }
package com.snapup.dao; import com.snapup.pojo.TrainRun; public interface TrainRunMapper { //通过车次编号查询车次信息 public TrainRun findTrainRunByCode(String run_code); }
package com.minipacific.bleprototype1; import android.app.Activity; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAdapter.LeScanCallback; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements LeScanCallback{ private static final String TAG = "BluetoothGattActivity"; //------------------------------------------scan------------------------------------------------ private BluetoothAdapter mBtAdapter; private BluetoothDevice mDevice; private static String deviceName=null; private static String deviceAdr=null; private static final int REQUEST_ENABLE_BT = 1; //-----------------------------------------Gatt-------------------------------------------------- private BluetoothLeService mBluetoothLeService; private boolean mConnected = false; private BluetoothGattCharacteristic mNotifyCharacteristic; private final String LIST_NAME= "NAME"; private final String LIST_UUID= "UUID"; TextView luxData, gattState, dataState, dataName, subject; ProgressDialog dialog; private static final int MSG_PROGRESS = 101; private static final int MSG_DISMISS = 102; Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub switch(msg.what){ case MSG_PROGRESS : dialog.setMessage((String)msg.obj); if(!dialog.isShowing()){ dialog.show(); } break; case MSG_DISMISS : dialog.hide(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); initialize(); reqeustLeDevice(); makeAdapter(); requestDevice(); clearUi(); Intent gattServiceIntent = new Intent (this, BluetoothLeService.class); bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE); } private void clearUi() { // TODO Auto-generated method stub luxData.setText("_____"); gattState.setVisibility(View.INVISIBLE); dataState.setVisibility(View.INVISIBLE); } private void requestDevice() { // TODO Auto-generated method stub if(mBtAdapter==null){ Intent enableBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBt, REQUEST_ENABLE_BT); } } private void makeAdapter() { // TODO Auto-generated method stub BluetoothManager mManager = (BluetoothManager)getSystemService(BLUETOOTH_SERVICE); mBtAdapter = mManager.getAdapter(); } private void reqeustLeDevice() { // TODO Auto-generated method stub if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){ Toast.makeText(this, "BLE is not support", Toast.LENGTH_SHORT).show(); finish(); } } private void initialize() { // TODO Auto-generated method stub luxData = (TextView)findViewById(R.id.data); gattState = (TextView)findViewById(R.id.state_connected); dataState = (TextView)findViewById(R.id.state_data_available); dataName = (TextView)findViewById(R.id.lux); subject = (TextView)findViewById(R.id.subject); subject.setTypeface(Typeface.createFromAsset(getAssets(), "helvetica.ttf")); luxData.setTypeface(Typeface.createFromAsset(getAssets(), "helvetica.ttf")); dataName.setTypeface(Typeface.createFromAsset(getAssets(), "helvetica.ttf")); dialog = new ProgressDialog(this); dialog.setTitle("Connecting BLE"); dialog.setMessage("Please wait while service connect"); dialog.setCancelable(false); dialog.setIndeterminate(true); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub if(requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED){ finish(); return; } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if(!mBtAdapter.isEnabled()){ if(!mBtAdapter.isEnabled()){ Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } scanLeDevice(true); registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); if(mBluetoothLeService != null) { final boolean result = mBluetoothLeService.connect(deviceAdr); Log.w(TAG, "BLE Service connection state : " + result); } } private static IntentFilter makeGattUpdateIntentFilter() { final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICE_NOTIFY); intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE); return intentFilter; } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); scanLeDevice(false); unregisterReceiver(mGattUpdateReceiver); clearUi(); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); unbindService(mServiceConnection); mBluetoothLeService = null; } private void scanLeDevice(final boolean enable) { // TODO Auto-generated method stub if(enable){ mHandler.postDelayed(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub mBtAdapter.stopLeScan(MainActivity.this); mHandler.sendEmptyMessage(MSG_DISMISS); mBluetoothLeService.connect(deviceAdr); } }, 2500); mBtAdapter.startLeScan(this); mHandler.sendMessage(Message.obtain(null, MSG_PROGRESS, "Connect Sensor")); } } @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { // TODO Auto-generated method stub if(BluetoothDevice.ACTION_FOUND.equals("android.bluetooth.device.action.FOUND")){ deviceName = device.getName(); deviceAdr = device.getAddress(); mDevice = device; } } private final ServiceConnection mServiceConnection = new ServiceConnection(){ @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub mBluetoothLeService = ((BluetoothLeService.LocalBinder)service).getService(); if(!mBluetoothLeService.initialize()){ finish(); } Log.w(TAG, "invoked serviceConnection "); mBluetoothLeService.connect(deviceAdr); } @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub mBluetoothLeService = null; } }; private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub final String action = intent.getAction(); if(BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)){ mConnected = true; //gattState.setVisibility(View.VISIBLE); }else if(BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)){ mConnected= false; clearUi(); }else if (BluetoothLeService.ACTION_GATT_SERVICE_NOTIFY.equals(action)){ //dataState.setVisibility(View.VISIBLE); }else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)){ displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA)); } } }; private void displayData(String data) { // TODO Auto-generated method stub if(data != null){ luxData.setText(data); } } }
package com.getkhaki.api.bff.persistence.repositories; import com.getkhaki.api.bff.persistence.models.EmailDao; import com.getkhaki.api.bff.persistence.models.PersonDao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; import java.util.UUID; @Repository public interface PersonRepositoryInterface extends JpaRepository<PersonDao, UUID> { PersonDao findDistinctByEmailsUserAndEmailsDomainName(String userName, String domainName); PersonDao findDistinctByEmployeeId(UUID id); Optional<PersonDao> findDistinctByEmails(EmailDao emailDao); @Query( value = "select id as id, " + " first_name as firstName, " + " last_name as lastName " + " from person_dao pd " + " where exists ( " + " select 'x' " + " from calendar_event_participant_dao cepd," + " email_dao_people edp " + " where cepd.email_id = edp.emails_id " + " and edp.people_id = pd.id " + " and cepd.calendar_event_id = :calendarEventId )", nativeQuery = true ) List<PersonDao> findDistinctByCalendarEvent(UUID calendarEventId); @Query( value = "select id as id, " + " first_name as firstName, " + " last_name as lastName " + " from person_dao pd " + " where exists ( " + " select 'x' " + " from calendar_event_participant_dao cepd," + " email_dao_people edp " + " where cepd.email_id = edp.emails_id " + " and edp.people_id = pd.id " + " and cepd.organizer = true " + " and cepd.calendar_event_id = :calendarEventId )", nativeQuery = true ) PersonDao findOrganizerByCalendarEvent(UUID calendarEventId); }
/** * COPYRIGHT (C) 2013 KonyLabs. All Rights Reserved. * * @author rbanking */ package com.classroom.services.facade.exceptions; /** * Thrown to indicate that a method has been passed an illegal or inappropriate * argument. */ public class FacadeIllegalArgumentException extends Exception { private static final long serialVersionUID = 1L; /** * The Constructor. * * @param message * the message */ public FacadeIllegalArgumentException(String message) { super(message); } /** * The Constructor. * * @param message * the message * @param cause * the cause */ public FacadeIllegalArgumentException(String message, Throwable cause) { super(message, cause); } }
package recursion_and_backtracking; public class Hanio { public static void main(String[] args) { TowersOfHanoi(4,'a','b','c'); } public static void TowersOfHanoi(int n, char frompeg, char topeg, char auxpeg){ if(n == 1){ System.out.println("Move disk 1 from pge " + frompeg + " to peg " + topeg); return; } TowersOfHanoi(n-1,frompeg,auxpeg,topeg); System.out.println("Move disk " + n + " from peg " + frompeg + " to peg " + topeg); TowersOfHanoi(n-1,auxpeg,topeg,frompeg); } }
package nightgames.skills; import java.util.function.Predicate; import nightgames.characters.Character; import nightgames.characters.Emotion; import nightgames.characters.body.BodyPart; import nightgames.characters.body.PussyPart; import nightgames.combat.Combat; import nightgames.combat.Result; import nightgames.global.Global; import nightgames.items.Item; import nightgames.items.clothing.ClothingSlot; public class Aphrodisiac extends Skill { public Aphrodisiac(Character self) { super("Use Aphrodisiac", self); } @Override public boolean requirements(Combat c, Character user, Character target) { return true; } private final Predicate<BodyPart> hasSuccubusPussy = new Predicate<BodyPart>(){ @Override public boolean test(BodyPart bodyPart) { return bodyPart.isType("pussy") && bodyPart.moddedPartCountsAs(getSelf(), PussyPart.succubus); } }; @Override public boolean usable(Combat c, Character target) { boolean canMove = c.getStance().mobile(getSelf()) && getSelf().canAct(); boolean hasItem = getSelf().has(Item.Aphrodisiac); boolean canGetFromOwnBody = !(getSelf().body.getCurrentPartsThatMatch(hasSuccubusPussy).isEmpty()) && getSelf().getArousal().get() >= 10 && !c.getStance().prone(getSelf()); return canMove && (hasItem || canGetFromOwnBody); } @Override public boolean resolve(Combat c, Character target) { int magnitude = Global.random(5) + 15; if (!getSelf().body.getCurrentPartsThatMatch(hasSuccubusPussy).isEmpty()) {//TODO: Arousal check? Otherwise, you can bypass the arousal check by having aphrodisiac in inventory c.write(getSelf(), receive(c, magnitude, Result.strong, target)); target.arouse(magnitude, c); target.emote(Emotion.horny, 20); } else if (getSelf().has(Item.Aersolizer)) { if (getSelf().human()) { c.write(getSelf(), deal(c, 0, Result.special, target)); } else if (target.human()) { c.write(getSelf(), receive(c, 0, Result.special, getSelf())); } getSelf().consume(Item.Aphrodisiac, 1); target.arouse(magnitude, c); target.emote(Emotion.horny, 20); } else if (target.roll(this, c, accuracy(c))) { if (getSelf().human()) { c.write(getSelf(), deal(c, magnitude, Result.normal, target)); } else { c.write(getSelf(), receive(c, magnitude, Result.normal, getSelf())); } target.emote(Emotion.horny, 20); getSelf().consume(Item.Aphrodisiac, 1); target.arouse(magnitude, c); } else { if (getSelf().human()) { c.write(getSelf(), deal(c, 0, Result.miss, target)); } else if (target.human()) { c.write(getSelf(), receive(c, 0, Result.miss, target)); } return false; } return true; } @Override public Skill copy(Character user) { return new Aphrodisiac(user); } @Override public Tactics type(Combat c) { return Tactics.pleasure; } @Override public String deal(Combat c, int damage, Result modifier, Character target) { if (modifier == Result.special) { return String.format("You pop an Aphrodisiac into your Aerosolizer and spray %s" + " with a cloud of mist. %s flushes and %s eyes fill with lust as it takes hold.", target.name(), Global.capitalizeFirstLetter(target.pronoun()), target.possessivePronoun()); } else if (modifier == Result.miss) { return "You throw an Aphrodisiac at " + target.name() + ", but "+target.pronoun()+" ducks out of the way and it splashes harmlessly on the ground. What a waste."; } else if (modifier == Result.strong) { return getSelf().subjectAction("dip", "dips") + " a finger " + (getSelf().crotchAvailable() ? "" : "under " + getSelf().possessivePronoun() + " " + getSelf().getOutfit().getTopOfSlot(ClothingSlot.bottom) .getName() + " and ") + "into " + getSelf().possessivePronoun() + " pussy. Once " + getSelf().subjectAction("have", "has") + " collected a drop of " + getSelf().possessivePronoun() + " juices" + " on " + getSelf().possessivePronoun() + " fingertip, " + getSelf().subjectAction("pull", "pulls") + " it out and flicks it at " + target.directObject() + "," + " skillfully depositing it in " + target.possessivePronoun() + " open mouth. " + Global.capitalizeFirstLetter(target.subject()) + " immediately feel" + " a flash of heat spread through " + target.directObject() + " and only a small part of it results from the anger caused by " + getSelf().possessivePronoun() + " dirty move."; } else { return "You uncap a small bottle of Aphrodisiac and splash it in " + target.name() + "'s face. For a second, "+target.possessivePronoun()+"'s just surprised, but gradually a growing desire " + "starts to make "+target.directObject()+" weak in the knees."; } } @Override public String receive(Combat c, int damage, Result modifier, Character target) { if (modifier == Result.miss) { return getSelf().subjectAction("splash", "splashes") + " a bottle of liquid in " + target.nameOrPossessivePronoun() + " direction, but none of it hits you."; } else if (modifier == Result.special) { return getSelf().name() + " inserts a bottle into the attachment on "+getSelf().possessivePronoun()+" arm. You're suddenly surrounded by a sweet smelling cloud of mist. You feel your blood boil " + "with desire as the unnatural gas takes effect."; } else if (modifier == Result.strong) { return getSelf().subjectAction("dip", "dips") + " a finger " + (getSelf().crotchAvailable() ? "" : "under " + getSelf().possessivePronoun() + " " + getSelf().getOutfit().getTopOfSlot(ClothingSlot.bottom) .getName() + " and ") + "into " + getSelf().possessivePronoun() + " pussy. Once " + getSelf().subjectAction("have", "has") + " collected a drop of " + getSelf().possessivePronoun() + " juices" + " on " + getSelf().possessivePronoun() + " fingertip, " + getSelf().subjectAction("pull", "pulls") + " it out and flicks it at " + target.directObject() + "," + " skillfully depositing it in " + target.possessivePronoun() + " open mouth. " + Global.capitalizeFirstLetter(target.subject()) + " immediately feel" + " a flash of heat spread through " + target.directObject() + " and only a small part of it" + " results from the anger caused by " + getSelf().possessivePronoun() + " dirty move."; } else { return getSelf().name() + " throws a strange, sweet-smelling liquid in your face. An unnatural warmth spreads through your body and gathers in your dick like a fire."; } } @Override public String describe(Combat c) { return "Throws a bottle of Aphrodisiac at the opponent"; } }
package com.yuan.iliya.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.Result; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.struts2.dispatcher.HttpParameters; import org.apache.struts2.result.ServletDispatcherResult; import java.util.Map; /** * All Rights Reserved, Designed By Iliya Kaslana * * @author Iliya Kaslana * @version 1.0 * @date 2018/6/17 13:53 * @copyright ©2018 */ public class LoggerInterceptor extends AbstractInterceptor { private static final Logger LOG = LogManager.getLogger(LoggerInterceptor.class); public String intercept(ActionInvocation invocation) throws Exception { LOG.info("begin-----------------------------"); //得到运行的action对象,打印类名 LOG.info("Action: " + invocation.getAction().getClass().getName()); LOG.info("Method: " + invocation.getProxy().getMethod()); HttpParameters params = invocation.getInvocationContext().getParameters(); for (String key:params.keySet()){ Object obj = params.get(key); if (obj instanceof String[]){ String[] arr = (String[])obj; LOG.info("Params: " + key); StringBuilder message = new StringBuilder(); for (String value:arr){ message.append(value + " "); } LOG.info(message.toString()); } } String result = invocation.invoke(); Result result1 = invocation.getResult(); if (result1 instanceof ServletDispatcherResult){ ServletDispatcherResult result2 = (ServletDispatcherResult)result1; LOG.info("JSP: " + result2.getLastFinalLocation()); } LOG.info("end-----------------------------"); return result; } }
package com.pbeder.chip8; public interface Beeper { void beep(); }
package com.aspect; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestAspect { public static void main(String[] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("com/aspect/applicationContext.xml"); CustomerBo customer = (CustomerBo) ctx.getBean("customerBo"); customer.addCustomer(); customer.addCustomerReturnValue(); //customer.addCustomerThrowException(); customer.addCustomerAround("srini"); } }
package App.dao.Repositories; import org.springframework.data.jpa.repository.JpaRepository; import App.dao.entity.*; public interface StudentRepositories extends JpaRepository<Student,Long> { }
/* * Created Fri Nov 12 12:04:37 CST 2004 by MyEclipse Hibernate Tool. */ package com.aof.component.helpdesk; import java.io.Serializable; /** * A class that represents a row in the 'CM_Action_History' table. * This class may be customized as it is never re-generated * after being created. */ public class CallActionHistory extends AbstractCallActionHistory implements Serializable { /** * Simple constructor of CallActionHistory instances. */ public CallActionHistory() { } /** * Constructor of CallActionHistory instances given a simple primary key. * @param cmahId */ public CallActionHistory(java.lang.Integer cmahId) { super(cmahId); } /* Add customized code below */ }
package com.esum.comp.ftp.table; import com.esum.common.record.InterfaceInfoRecord; import com.esum.comp.ftp.FtpConfig; import com.esum.framework.common.sql.Record; import com.esum.framework.core.component.ComponentException; /** * FTP_INFO 테이블의 레코드와 매칭되는 클래스 * * Copyright(c) eSum Technologies, Inc. All rights reserved. */ public class FtpInfoRecord extends InterfaceInfoRecord { private static final long serialVersionUID = 20140619L; public static final String POLLING = "P"; public static final String CRON = "C"; private boolean useInbound; private String inboundGatherHostIp; private int inboundGatherHostPort; private String inboundFtpAuthInfoId; private String inboundTransferType; private String inboundConnectionMode; private String inboundGatherDir; private String inboundGatherFileSuffix; private String inboundGatherStartType; private int inboundGatherInterval; private int inboundGatherCountOnce; private String inboundGatherCronPattern; private boolean inboundGatherUse; private String inboundGatherRename; private String inboundGatherLocale; private boolean inboundSync; private String inboundResponseRule; private String inboundGatherPkiAlias; private boolean inboundGatherUseSSL; private String inboundFileEncoding; private boolean useOutbound; private String outboundHostIp; private int outboundHostPort; private String outboundFtpAuthInfoId; private String outboundUserDir; private String outboundTransferType; private String outboundConnectionMode; private String outboundRename; private String outboundPkiAlias; private boolean outboundUseSSL; public FtpInfoRecord(Record record) throws ComponentException { super(record); } public FtpInfoRecord(String[] ids, Record record) throws ComponentException { super(ids, record); } protected void init(Record record) throws ComponentException { super.setInterfaceId(record.getString("INTERFACE_ID").trim()); this.useInbound = record.getString("USE_INBOUND").trim().equals("Y"); if (useInbound) { this.inboundGatherHostIp = record.getString("INBOUND_GATHER_HOST_IP").trim(); String tmp = record.getString("INBOUND_GATHER_HOST_PORT", "21"); this.inboundGatherHostPort = Integer.parseInt(tmp); this.inboundFtpAuthInfoId = record.getString("INBOUND_FTP_AUTH_INFO_ID"); this.inboundTransferType = record.getString("INBOUND_TRANSFER_TYPE", "A").trim(); this.inboundConnectionMode = record.getString("INBOUND_CONNECTION_MODE", "A").trim(); this.inboundGatherDir = record.getString("INBOUND_GATHER_DIR", ".").trim(); this.inboundGatherFileSuffix = record.getString("INBOUND_GATHER_FILE_SUFFIX").trim(); this.inboundGatherStartType = record.getString("INBOUND_GATHER_START_TYPE", POLLING).trim(); tmp = record.getString("INBOUND_GATHER_INTERVAL", "60"); inboundGatherInterval = Integer.parseInt(tmp); if(inboundGatherInterval==0 || inboundGatherInterval<0) { inboundGatherInterval = 60; } this.inboundGatherCountOnce = record.getInt("INBOUND_GATHER_COUNT_ONCE", FtpConfig.DEFAULT_FILE_CNT_ONCE); this.inboundGatherCronPattern = record.getString("INBOUND_GATHER_CRON_PATTERN").trim(); this.inboundGatherUse = record.getString("INBOUND_GATHER_USE", "N").equalsIgnoreCase("Y")? true : false; this.inboundGatherRename = record.getString("INBOUND_GATHER_RENAME", "").trim(); this.inboundGatherLocale = record.getString("INBOUND_GATHER_LOCALE", "").trim(); this.inboundGatherPkiAlias = record.getString("INBOUND_GATHER_PKI_ALIAS", "").trim(); this.inboundGatherUseSSL = record.getString("INBOUND_GATHER_USE_SSL", "N").equalsIgnoreCase("Y")? true : false; this.inboundFileEncoding = record.getString("INBOUND_FILE_ENCODING", ""); this.inboundSync = record.getString("INBOUND_SYNC_USE", "N").equalsIgnoreCase("Y")? true : false;; if(inboundSync){ this.inboundResponseRule = record.getString("INBOUND_RESPONSE_RULE", ""); } } super.setNodeList(toArrayList(record.getString("INBOUND_NODE_ID"), ",")); this.useOutbound = record.getString("USE_OUTBOUND").trim().equals("Y"); if (useOutbound) { this.outboundHostIp = record.getString("OUTBOUND_HOST_IP").trim(); String tmp = record.getString("OUTBOUND_HOST_PORT", "21"); this.outboundHostPort = Integer.parseInt(tmp); this.outboundFtpAuthInfoId = record.getString("OUTBOUND_FTP_AUTH_INFO_ID"); this.outboundUserDir = record.getString("OUTBOUND_DIR", ".").trim(); this.outboundTransferType = record.getString("OUTBOUND_TRANSFER_TYPE", "A").trim(); this.outboundConnectionMode = record.getString("OUTBOUND_CONNECTION_MODE", "A").trim(); this.outboundRename = record.getString("OUTBOUND_RENAME", "").trim(); this.outboundPkiAlias = record.getString("OUTBOUND_PKI_ALIAS", "").trim(); this.outboundUseSSL = record.getString("OUTBOUND_USE_SSL", "N").equalsIgnoreCase("Y")? true : false; } super.setParsingRule(record.getString("PARSING_RULE").trim()); } public String getInboundGatherLocale() { return inboundGatherLocale; } public void setInboundGatherLocale(String inboundGatherLocale) { this.inboundGatherLocale = inboundGatherLocale; } public String getInboundGatherRename() { return inboundGatherRename; } public void setInboundGatherRename(String inboundGatherRename) { this.inboundGatherRename = inboundGatherRename; } public String getInboundFileEncoding() { return inboundFileEncoding; } public void setInboundFileEncoding(String inboundFileEncoding) { this.inboundFileEncoding = inboundFileEncoding; } public String getOutboundRename() { return outboundRename; } public void setOutboundRename(String outboundRename) { this.outboundRename = outboundRename; } public String getInboundGatherHostIp() { return inboundGatherHostIp; } public int getInboundGatherHostPort() { return inboundGatherHostPort; } public String getInboundTransferType() { return inboundTransferType; } public String getInboundConnectionMode() { return inboundConnectionMode; } public String getInboundGatherDir() { return inboundGatherDir; } public String getInboundGatherFileSuffix() { return inboundGatherFileSuffix; } public String getInboundGatherStartType() { return inboundGatherStartType; } public int getInboundGatherInterval() { return inboundGatherInterval; } public String getInboundGatherCronPattern() { return inboundGatherCronPattern; } public boolean isInboundGatherUse() { return inboundGatherUse; } public String getOutboundHostIp() { return outboundHostIp; } public int getOutboundHostPort() { return outboundHostPort; } public String getOutboundUserDir() { return outboundUserDir; } public String getOutboundTransferType() { return outboundTransferType; } public String getOutboundConnectionMode() { return outboundConnectionMode; } public void setInboundGatherHostIp(String inboundGatherHostIp) { this.inboundGatherHostIp = inboundGatherHostIp; } public void setInboundGatherHostPort(int inboundGatherHostPort) { this.inboundGatherHostPort = inboundGatherHostPort; } public String getInboundFtpAuthInfoId() { return inboundFtpAuthInfoId; } public void setInboundFtpAuthInfoId(String inboundFtpAuthInfoId) { this.inboundFtpAuthInfoId = inboundFtpAuthInfoId; } public void setInboundTransferType(String inboundTransferType) { this.inboundTransferType = inboundTransferType; } public void setInboundConnectionMode(String inboundConnectionMode) { this.inboundConnectionMode = inboundConnectionMode; } public void setInboundGatherDir(String inboundGatherDir) { this.inboundGatherDir = inboundGatherDir; } public void setInboundGatherFileSuffix(String inboundGatherFileSuffix) { this.inboundGatherFileSuffix = inboundGatherFileSuffix; } public void setInboundGatherStartType(String inboundGatherStartType) { this.inboundGatherStartType = inboundGatherStartType; } public void setInboundGatherInterval(int inboundGatherInterval) { this.inboundGatherInterval = inboundGatherInterval; } public void setInboundGatherCronPattern(String inboundGatherCronPattern) { this.inboundGatherCronPattern = inboundGatherCronPattern; } public void setInboundGatherUse(boolean inboundGatherUse) { this.inboundGatherUse = inboundGatherUse; } public void setOutboundHostIp(String outboundHostIp) { this.outboundHostIp = outboundHostIp; } public void setOutboundHostPort(int outboundHostPort) { this.outboundHostPort = outboundHostPort; } public String getOutboundFtpAuthInfoId() { return outboundFtpAuthInfoId; } public void setOutboundFtpAuthInfoId(String outboundFtpAuthInfoId) { this.outboundFtpAuthInfoId = outboundFtpAuthInfoId; } public void setOutboundUserDir(String outboundUserDir) { this.outboundUserDir = outboundUserDir; } public void setOutboundTransferType(String outboundTransferType) { this.outboundTransferType = outboundTransferType; } public void setOutboundConnectionMode(String outboundConnectionMode) { this.outboundConnectionMode = outboundConnectionMode; } public boolean isInboundSync() { return inboundSync; } public void setInboundSync(boolean inboundSync) { this.inboundSync = inboundSync; } public String getInboundResponseRule() { return inboundResponseRule; } public void setInboundResponseRule(String inboundResponseRule) { this.inboundResponseRule = inboundResponseRule; } public String getInboundGatherPkiAlias() { return inboundGatherPkiAlias; } public void setInboundGatherPkiAlias(String inboundGatherPkiAlias) { this.inboundGatherPkiAlias = inboundGatherPkiAlias; } public String getOutboundPkiAlias() { return outboundPkiAlias; } public void setOutboundPkiAlias(String outboundPkiAlias) { this.outboundPkiAlias = outboundPkiAlias; } public boolean isInboundGatherUseSSL() { return inboundGatherUseSSL; } public void setInboundGatherUseSSL(boolean inboundGatherUseSSL) { this.inboundGatherUseSSL = inboundGatherUseSSL; } public boolean isOutboundUseSSL() { return outboundUseSSL; } public void setOutboundUseSSL(boolean outboundUseSSL) { this.outboundUseSSL = outboundUseSSL; } public int getInboundGatherCountOnce() { return inboundGatherCountOnce; } public void setInboundGatherCountOnce(int inboundGatherCountOnce) { this.inboundGatherCountOnce = inboundGatherCountOnce; } public boolean isUseInbound() { return useInbound; } public void setUseInbound(boolean useInbound) { this.useInbound = useInbound; } public boolean isUseOutbound() { return useOutbound; } public void setUseOutbound(boolean useOutbound) { this.useOutbound = useOutbound; } }
package org.wuxinshui.boosters.designPatterns.simpleFacthory.normal; /** * Created by FujiRen on 2016/10/28. * 简单工厂模式不属于23中涉及模式,简单工厂一般分为:普通简单工厂、多方法简单工厂、静态方法简单工厂。 */ public class SendFactory { public Sender producer(String type) { if ("EMAIL".equals(type)) { return new Email(); } else if ("SMS".equals(type)) { return new Sms(); } else { return null; } } }
package mb.tianxundai.com.toptoken.aty.wallet; import android.Manifest; import android.annotation.SuppressLint; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.kongzue.dialog.v2.WaitDialog; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import mb.tianxundai.com.toptoken.MyApp; import mb.tianxundai.com.toptoken.R; import mb.tianxundai.com.toptoken.base.BaseAty; import mb.tianxundai.com.toptoken.base.HttpRequest; import mb.tianxundai.com.toptoken.bean.ZhunBeiZhuanZhangBean; import mb.tianxundai.com.toptoken.interfaces.DarkStatusBarTheme; import mb.tianxundai.com.toptoken.interfaces.Layout; import mb.tianxundai.com.toptoken.listener.ResponseListener; import mb.tianxundai.com.toptoken.uitl.JSONUtils; import mb.tianxundai.com.toptoken.uitl.JinZhiZhuanHua; import mb.tianxundai.com.toptoken.uitl.JumpParameter; import mb.tianxundai.com.toptoken.uitl.MapUntils; import mb.tianxundai.com.toptoken.uitl.NullStringEmptyTypeAdapterFactory; import mb.tianxundai.com.toptoken.uitl.OnResponseListener; import mb.tianxundai.com.toptoken.uitl.Parameter; import mb.tianxundai.com.toptoken.view.Open2Dialog; import mb.tianxundai.com.toptoken.view.OpenDialog; import mb.tianxundai.com.toptoken.view.QueRenDialog; import zxing.CaptureActivity; import zxing.Constant; import zxing.ZxingConfig; import static android.text.TextUtils.isEmpty; import static mb.tianxundai.com.toptoken.api.WalletApi.prepareTransaction; import static mb.tianxundai.com.toptoken.api.WalletApi.runTransaction; /** * 创建人: Nine tails fox * 创建时间: 2018/10/6 16:00 * 功能描述: 转账界面 * 联系方式:1037438704@qq.com * * @author dell-pc */ @Layout(R.layout.aty_receivables) @DarkStatusBarTheme(true) //开启顶部状态栏图标、文字暗色模式 public class ReceivablesAty extends BaseAty { @BindView(R.id.iv_back) ImageView ivBack; @BindView(R.id.rl_title) RelativeLayout rlTitle; @BindView(R.id.text_scan) TextView textScan; @BindView(R.id.tv_dizhi) TextView tvDizhi; @BindView(R.id.tv_quanbu) TextView tvQuanbu; @BindView(R.id.submit) TextView submit; @BindView(R.id.tv_titile) TextView tvTitile; @BindView(R.id.tv_yue) TextView tvYue; @BindView(R.id.tv_kaungfei) TextView tvKaungfei; @BindView(R.id.et_price) EditText etPrice; @BindView(R.id.et_address) EditText etAddress; @BindView(R.id.et_beizhu) EditText etBeizhu; private String userWalletCoinId = ""; private String toAddress = ""; private String tsValue = ""; private String password = ""; private String comment = ""; private String address =""; Open2Dialog openDialog; PopupWindow mPopWindow; ZhunBeiZhuanZhangBean zhuanZhangBean; @Override public void initViews() { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); ButterKnife.bind(this); if (getParameter() != null) { if (getParameter().get("userWalletCoinId") != null) { userWalletCoinId = getParameter().get("userWalletCoinId").toString(); } if(getParameter().get("address")!=null){ address = getParameter().get("address").toString(); Map<String,String> map= MapUntils.getHeader(address); String[] paramsArr = address.split("\\?"); if(paramsArr.length>1){ if(paramsArr[0].contains("iban")){ String[] address_fen = paramsArr[0].split(":"); if(address_fen.length>1){ JinZhiZhuanHua jinZhiZhuanHua = new JinZhiZhuanHua(); jinZhiZhuanHua.toDecimal(address_fen[1].substring(4,address_fen[1].length()),36); jinZhiZhuanHua.toAnyConversion(jinZhiZhuanHua.getToDecimalResult(), BigInteger.valueOf(16)); etAddress.setText("0x"+jinZhiZhuanHua.getToAnyConversion().trim()); } }else{ if(paramsArr[0].contains(":")){ String[] mao = paramsArr[0].split(":"); if(mao.length>1){ etAddress.setText(mao[1]); } }else{ etAddress.setText(paramsArr[0]); } } } if(map.get("amount")!=null){ etPrice.setText(map.get("amount")); } if(map.get("token")!=null){ } if(map.get("label")!=null){ etBeizhu.setText(map.get("label")); }else{ } // if(!address.equals("")){ // if(!address.contains(":")){ // address=":"+address; // } // if(address.contains(":")){ // String[] parts = address.split(":"); // String[] parts2 = address.split("="); // if(address.contains("&")){ // String[] bei = address.split("&"); // String[] beizhuss = bei[1].split("="); // if(beizhuss[0].equals("label")){ // etBeizhu.setText(beizhuss[1]); // } // // } // String shu =""; // if(parts2[1].contains("&")){ // if(parts2[1].contains("amount")){ // String[] jine = parts2[1].split("&"); // shu = jine[0]; // } // // }else{ // shu = parts2[1]; // } // String[] addressChang = parts[1].split("="); // String address2 = addressChang[0].substring(0,(addressChang[0].length()-7)); // 034556 // etPrice.setText(shu+""); // if(parts[0].equals("iban")){ // JinZhiZhuanHua jinZhiZhuanHua = new JinZhiZhuanHua(); // jinZhiZhuanHua.toDecimal(address2.substring(4,address2.length()),36); // jinZhiZhuanHua.toAnyConversion(jinZhiZhuanHua.getToDecimalResult(), BigInteger.valueOf(16)); // etAddress.setText(jinZhiZhuanHua.getToAnyConversion().trim()); // }else{ // etAddress.setText(address2.trim()+""); // } // } // } } } } @Override public void initDatas(JumpParameter jumpParameter) { WaitDialog.show(me,getResources().getString(R.string.loading)); HttpRequest.POST(me, prepareTransaction, new Parameter().add("userWalletCoinId", userWalletCoinId), new ResponseListener() { @Override public void onResponse(String s, Exception e) { WaitDialog.dismiss(); if (e == null) { Map<String, String> map = JSONUtils.parseKeyAndValueToMap(s); if(map.get("code")==null){ return; } if (map.get("code").equals("101")) { // toast(me.getResources().getString(R.string.show101)); Gson gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringEmptyTypeAdapterFactory()).create(); zhuanZhangBean = gson.fromJson(s, ZhunBeiZhuanZhangBean.class); if(zhuanZhangBean!=null){ if(zhuanZhangBean.getData().getCoinShortName()!=null){ tvTitile.setText(getResources().getString(R.string.zhuanzhang) + zhuanZhangBean.getData().getCoinShortName()); String[] listFee = {"ETH","BTC","ETC","LTC","USDT","XRP","EOS","DASH","QTUM","DOGE"}; if(containts(listFee,zhuanZhangBean.getData().getCoinShortName())){ tvKaungfei.setText(getResources().getString(R.string.queren_kuangfei)+" " + zhuanZhangBean.getData().getGasPrice() + zhuanZhangBean.getData().getCoinShortName()); }else{ tvKaungfei.setText(getResources().getString(R.string.queren_kuangfei)+" " + zhuanZhangBean.getData().getGasPrice() + "ETH"); } tvYue.setText(getResources().getString(R.string.qianbao_yue)+" " + new BigDecimal(new Double(new BigDecimal(zhuanZhangBean.getData().getPrice()).doubleValue()).toString())+"" + zhuanZhangBean.getData().getCoinShortName() + ","); String[] list = {"EOS","XRP"}; if (containts(list,zhuanZhangBean.getData().getCoinShortName()) && etAddress.getText().toString().trim().equals(zhuanZhangBean.getData().getCoinAddress()) ) { etBeizhu.setHint(getResources().getString(R.string.mark_tag)); }else { } } } } else { Log.e("error", map.get("code") + map.get("message")); } } else { // toast(me.getResources().getString(R.string.inter_error)); } } }); } public static boolean containts(String[] arr,String targetValue){ return Arrays.asList(arr).contains(targetValue); } @Override public void setEvents() { etAddress.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { String[] list = {"EOS","XRP"}; boolean isEosOrXrp = containts(list,zhuanZhangBean.getData().getCoinShortName()); String selfAddress = zhuanZhangBean.getData().getCoinAddress(); boolean isSelf = etAddress.getText().toString().equals(selfAddress); if (isSelf && isEosOrXrp == true){ etBeizhu.setHint(getResources().getString(R.string.mark_tag)); }else{ etBeizhu.setHint(getResources().getString(R.string.beizhu)); } } }); } @OnClick({R.id.iv_back, R.id.text_scan, R.id.tv_dizhi, R.id.tv_quanbu, R.id.submit}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.iv_back: finish(); break; case R.id.text_scan: requestPermissions(); break; case R.id.tv_dizhi: jump(AdressJiLuAty.class, new JumpParameter().put("userWalletCoinId", userWalletCoinId), new OnResponseListener() { @Override public void OnResponse(JumpParameter jumpParameter) { if(jumpParameter!=null){ if(jumpParameter.get("address")!=null){ etAddress.setText(jumpParameter.get("address").toString().trim()); } } } }); break; case R.id.tv_quanbu: etPrice.setText(zhuanZhangBean.getData().getPrice() + ""); break; case R.id.submit: toAddress = etAddress.getText().toString().trim(); tsValue = etPrice.getText().toString().trim(); comment = etBeizhu.getText().toString().trim(); if (isEmpty(toAddress)) { toast(me.getResources().getString(R.string.tv_address)); return; } if (isEmpty(tsValue)) { toast(me.getResources().getString(R.string.tv_money)); return; } if(Double.parseDouble(tsValue) <= 0){ toast(me.getResources().getString(R.string.true_money)); return; } String[] list = {"EOS","XRP"}; boolean isEosOrXrp = containts(list,zhuanZhangBean.getData().getCoinShortName()); String selfAddress = zhuanZhangBean.getData().getCoinAddress(); boolean isSelf = etAddress.getText().toString().equals(selfAddress); if (isEosOrXrp && isSelf && etBeizhu.getText().toString().length() <= 0 ) { toast(me.getResources().getString(R.string.tip_input_trans_info)); return; } if(toAddress.equals(zhuanZhangBean.getData().getCoinAddress()) && isEosOrXrp == false){ toast(me.getResources().getString(R.string.zhuandizhi)); return; } String[] listFee = {"ETH","BTC","ETC","LTC","USDT","XRP","EOS","DASH","QTUM","DOGE"}; if(containts(listFee,zhuanZhangBean.getData().getCoinShortName()) == false) { // if(zhuanZhangBean.getData().getCoinShortName().equals("TOP")){ if(Double.parseDouble(tsValue)>zhuanZhangBean.getData().getPrice() ){ toast(me.getResources().getString(R.string.yuebuzu)); return; } }else{ BigDecimal fee = new BigDecimal(zhuanZhangBean.getData().getGasPrice()+""); BigDecimal money = new BigDecimal(tsValue).add(fee); BigDecimal yue = new BigDecimal(zhuanZhangBean.getData().getPrice()+""); int code = money.compareTo(yue); if(code == 1){ toast(me.getResources().getString(R.string.yuebuzu)); return; } } QueRenDialog queRenDialog = new QueRenDialog(me, toAddress, tsValue, comment, tvKaungfei.getText().toString().trim(), new QueRenDialog.SignListener() { @Override public void sign() { openDialog = new Open2Dialog(me,"isqian",new Open2Dialog.SignListener() { @Override public void sign(String pass) { password = pass; initHttp(); } }); openDialog.show(); } }); queRenDialog.show(); break; } } void initHttp() { if (isEmpty(password)) { toast(getResources().getString(R.string.zhifu)); return; } WaitDialog.show(me,getResources().getString(R.string.loading)); HttpRequest.POST(me, runTransaction, new Parameter().add("userWalletCoinId", userWalletCoinId).add("toAddress", toAddress) .add("tsValue", tsValue).add("password", password).add("comment", comment), new ResponseListener() { @Override public void onResponse(String s, Exception e) { WaitDialog.dismiss(); if (e == null) { Map<String, String> map = JSONUtils.parseKeyAndValueToMap(s); if(map.get("code")==null){ toast(me.getResources().getString(R.string.inter_error)); return; } if (map.get("code").equals("109")) { toast(me.getResources().getString(R.string.show109)); if(map.get("data")!=null){ // tvYue.setText(map.get("data")+""); tvYue.setText(getResources().getString(R.string.qianbao_yue)+" " + map.get("data")+"" + zhuanZhangBean.getData().getCoinShortName() + ","); etAddress.setText(""); etBeizhu.setText(""); etPrice.setText(""); } } else { if(MyApp.mToastMap.get(map.get("code"))!=null){ toast(MyApp.mToastMap.get(map.get("code"))); }else{ toast(map.get("message")); } } } else { toast(me.getResources().getString(R.string.inter_error)); } } }); } public void inPop() { //设置contentView View contentView = LayoutInflater.from(ReceivablesAty.this).inflate(R.layout.pop_enter_pass, null); mPopWindow = new PopupWindow(contentView, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true); mPopWindow.setContentView(contentView); //防止PopupWindow被软件盘挡住(可能只要下面一句,可能需要这两句) // mPopWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED); mPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); //设置软键盘弹出 InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInput(1000, InputMethodManager.HIDE_NOT_ALWAYS);//这里给它设置了弹出的时间 //设置各个控件的点击响应 // final EditText editText = contentView.findViewById(R.id.pop_editText); // Button btn = contentView.findViewById(R.id.pop_btn); // btn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // String inputString = editText.getText().toString(); // Toast.makeText(MainActivity.this, inputString, Toast.LENGTH_SHORT).show(); // mPopWindow.dismiss();//让PopupWindow消失 // } // }); //是否具有获取焦点的能力 mPopWindow.setFocusable(true); //显示PopupWindow View rootview = LayoutInflater.from(ReceivablesAty.this).inflate(R.layout.aty_receivables, null); mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0); // LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); // View view = layoutInflater.inflate(R.layout.pop_enter_pass, null); // // 创建一个PopuWidow对象 // mPopWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, 400); EditText et_pass = (EditText) contentView.findViewById(R.id.et_pass); RelativeLayout rl_back = (RelativeLayout) contentView.findViewById(R.id.rl_back); ////popupwindow弹出时的动画 popWindow.setAnimationStyle(R.style.popupWindowAnimation); // // // 设置允许在外点击消失 // mPopWindow.setOutsideTouchable(false); // // 设置背景,这个是为了点击“返回Back”也能使其消失,并且并不会影响你的背景 // mPopWindow.setBackgroundDrawable(new BitmapDrawable()); // //软键盘不会挡着popupwindow // mPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); // 使其聚集 ,要想监听菜单里控件的事件就必须要调用此方法 // mPopWindow.setFocusable(true); et_pass.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { password = et_pass.getText().toString().trim(); // initHttp(); } return false; } }); rl_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPopWindow.dismiss(); //拿到InputMethodManager InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); //如果window上view获取焦点 && view不为空 if (imm.isActive() && getCurrentFocus() != null) { // 拿到view的token 不为空 if (getCurrentFocus().getWindowToken() != null) { // 表示软键盘窗口总是隐藏,除非开始时以SHOW_FORCED显示。 imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } } }); ////设置软键盘弹出 // InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); // inputMethodManager.toggleSoftInput(1000, InputMethodManager.HIDE_NOT_ALWAYS);//这里给它设置了弹出的时间 // //显示PopupWindow // View rootview = LayoutInflater.from(ReceivablesAty.this).inflate(R.layout.aty_receivables, null); // mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0); } void openJIanpan() { new Handler().postDelayed(new Runnable() { @Override public void run() { InputMethodManager imm = (InputMethodManager) submit.getContext().getSystemService(Service.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); } }, 100); } /** * 扫描完二维码 */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // 扫描二维码/条码回传 if (requestCode == 1 && resultCode == RESULT_OK) { if (data != null) { String adress = data.getStringExtra(Constant.CODED_CONTENT); Map<String,String> map= MapUntils.getHeader(adress); String[] paramsArr = adress.split("\\?"); if(paramsArr.length>1){ if(paramsArr[0].contains("iban")){ String[] address_fen = paramsArr[0].split(":"); if(address_fen.length>1){ JinZhiZhuanHua jinZhiZhuanHua = new JinZhiZhuanHua(); jinZhiZhuanHua.toDecimal(address_fen[1].substring(4,address_fen[1].length()),36); jinZhiZhuanHua.toAnyConversion(jinZhiZhuanHua.getToDecimalResult(), BigInteger.valueOf(16)); etAddress.setText("0x"+jinZhiZhuanHua.getToAnyConversion().trim()); } }else{ if(paramsArr[0].contains(":")){ String[] mao = paramsArr[0].split(":"); if(mao.length>1){ etAddress.setText(mao[1]); } }else{ etAddress.setText(paramsArr[0]); } } }else { if(paramsArr[0].contains(":")){ String[] mao = adress.split(":"); if(mao.length>1){ etAddress.setText(mao[1]); } }else { etAddress.setText(paramsArr[0]); } } if(map.get("amount")!=null){ etPrice.setText(map.get("amount")); } if(map.get("token")!=null){ } if(map.get("label")!=null){ etBeizhu.setText(map.get("label")); } // if(!adress.contains(":")){ // if(!address.contains(":")){ // address=":"+address; // } // String[] parts = adress.split(":"); // String[] parts2 = adress.split("="); // if(adress.contains("?")){ // String[] bei = adress.split("&"); // String[] beizhuss = bei[1].split("="); // if(beizhuss[0].equals("label")){ // etBeizhu.setText(beizhuss[1]); // } // // }else{ // // } // String shu =""; // if(parts2[1].contains("&")){ // String[] jine = parts2[1].split("&"); // shu = jine[0]; // }else{ // shu = parts2[1]; // } // String[] addressChang = parts[1].split("="); // String address = addressChang[0].substring(0,(addressChang[0].length()-7)); // 034556 // etPrice.setText(shu+""); // if(parts[0].equals("iban")){ // JinZhiZhuanHua jinZhiZhuanHua = new JinZhiZhuanHua(); // jinZhiZhuanHua.toDecimal(address,36); // jinZhiZhuanHua.toAnyConversion(jinZhiZhuanHua.getToDecimalResult(), BigInteger.valueOf(16)); // etAddress.setText(jinZhiZhuanHua.getToAnyConversion()); // }else{ // etAddress.setText(address+""); // } // }else{ // etAddress.setText(adress); // } } } } /** * 当有多个权限需要申请的时候 * 这里以打电话和SD卡读写权限为例 */ private void requestPermissions() { List<String> permissionList = new ArrayList<>(); if (ContextCompat.checkSelfPermission(me, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { permissionList.add(Manifest.permission.CAMERA); } if (ContextCompat.checkSelfPermission(me, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE); } if (!permissionList.isEmpty()) { //申请的集合不为空时,表示有需要申请的权限 ActivityCompat.requestPermissions(me, permissionList.toArray(new String[permissionList.size()]), 1); } else { //所有的权限都已经授权过了 Intent intent = new Intent(me, CaptureActivity.class); /*ZxingConfig是配置类 可以设置是否显示底部布局,闪光灯,相册,是否播放提示音 震动等动能 * 也可以不传这个参数 * 不传的话 默认都为默认不震动 其他都为true * */ ZxingConfig config = new ZxingConfig(); config.setShowbottomLayout(false);//底部布局(包括闪光灯和相册) config.setPlayBeep(true);//是否播放提示音 config.setShake(true);//是否震动 config.setFullScreenScan(true); config.setDecodeBarCode(true); // config.setShowAlbum(true);//是否显示相册 // config.setShowFlashLight(false);//是否显示闪光灯 intent.putExtra(Constant.INTENT_ZXING_CONFIG, config); startActivityForResult(intent, 1); } } /** * 权限申请返回结果 * * @param requestCode 请求码 * @param permissions 权限数组 * @param grantResults 申请结果数组,里面都是int类型的数 */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 1: if (grantResults.length > 0) { //安全写法,如果小于0,肯定会出错了 for (int i = 0; i < grantResults.length; i++) { int grantResult = grantResults[i]; if (grantResult == PackageManager.PERMISSION_DENIED) { //这个是权限拒绝 String s = permissions[i]; toast(s + "权限被拒绝了"); } else { //授权成功了 Intent intent = new Intent(me, CaptureActivity.class); /*ZxingConfig是配置类 可以设置是否显示底部布局,闪光灯,相册,是否播放提示音 震动等动能 * 也可以不传这个参数 * 不传的话 默认都为默认不震动 其他都为true * */ ZxingConfig config = new ZxingConfig(); config.setShowbottomLayout(false);//底部布局(包括闪光灯和相册) config.setPlayBeep(true);//是否播放提示音 config.setShake(true);//是否震动 config.setFullScreenScan(true); config.setDecodeBarCode(true); // config.setShowAlbum(false);//是否显示相册 // config.setShowFlashLight(false);//是否显示闪光灯 intent.putExtra(Constant.INTENT_ZXING_CONFIG, config); startActivityForResult(intent, 1); } } } break; default: break; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } }
package com.thinking.machines.school.servlets; import com.thinking.machines.school.dao.*; import com.thinking.machines.school.beans.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.net.*; public class DeleteServlet extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res) { try { int rollNumber; boolean exists; StudentBean sb=(StudentBean)req.getAttribute("studentBean"); rollNumber=sb.getRollNumber(); Connection c=DAOConnection.getConnection(); Statement s=c.createStatement(); int r=s.executeUpdate("delete from student where roll_number="+rollNumber); c.close(); ServiceResponse sr=new ServiceResponse(); sr.setCode(3); sr.setSuccess(true); req.setAttribute("serviceResponse",sr); RequestDispatcher rd; rd=req.getRequestDispatcher("/Students.jsp"); rd.forward(req,res); }catch(Exception e) { System.out.println(e); } } }
package com.trannguyentanthuan2903.yourfoods.history_ship_store.model; import com.trannguyentanthuan2903.yourfoods.product.model.OrderProduct; import java.util.ArrayList; /** * Created by Administrator on 10/16/2017. */ public class ListOrderProduct { public ArrayList<OrderProduct> getOrderProductList() { return orderProductList; } public void setOrderProductList(ArrayList<OrderProduct> orderProductList) { this.orderProductList = orderProductList; } private ArrayList<OrderProduct> orderProductList; public ListOrderProduct(ArrayList<OrderProduct> orderProductList) { this.orderProductList = orderProductList; } }
package fema.controllers; public class JogadorController { }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jdbc.datasource.lookup; import java.lang.reflect.Field; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.springframework.transaction.TransactionDefinition; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.springframework.transaction.TransactionDefinition.ISOLATION_DEFAULT; import static org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED; import static org.springframework.transaction.TransactionDefinition.ISOLATION_READ_UNCOMMITTED; import static org.springframework.transaction.TransactionDefinition.ISOLATION_REPEATABLE_READ; import static org.springframework.transaction.TransactionDefinition.ISOLATION_SERIALIZABLE; /** * Tests for {@link IsolationLevelDataSourceRouter}. * * @author Sam Brannen * @since 6.1 */ class IsolationLevelDataSourceRouterTests { private final IsolationLevelDataSourceRouter router = new IsolationLevelDataSourceRouter(); @Test void resolveSpecifiedLookupKeyForInvalidTypes() { assertThatIllegalArgumentException().isThrownBy(() -> router.resolveSpecifiedLookupKey(new Object())); assertThatIllegalArgumentException().isThrownBy(() -> router.resolveSpecifiedLookupKey('X')); } @Test void resolveSpecifiedLookupKeyByNameForUnsupportedValues() { assertThatIllegalArgumentException().isThrownBy(() -> router.resolveSpecifiedLookupKey(null)); assertThatIllegalArgumentException().isThrownBy(() -> router.resolveSpecifiedLookupKey(" ")); assertThatIllegalArgumentException().isThrownBy(() -> router.resolveSpecifiedLookupKey("bogus")); } /** * Verify that the internal 'constants' map is properly configured for all * ISOLATION_ constants defined in {@link TransactionDefinition}. */ @Test void resolveSpecifiedLookupKeyByNameForAllSupportedValues() { Set<Integer> uniqueValues = new HashSet<>(); streamIsolationConstants() .forEach(name -> { Integer isolationLevel = (Integer) router.resolveSpecifiedLookupKey(name); Integer expected = IsolationLevelDataSourceRouter.constants.get(name); assertThat(isolationLevel).isEqualTo(expected); uniqueValues.add(isolationLevel); }); assertThat(uniqueValues).containsExactlyInAnyOrderElementsOf(IsolationLevelDataSourceRouter.constants.values()); } @Test void resolveSpecifiedLookupKeyByInteger() { assertThatIllegalArgumentException().isThrownBy(() -> router.resolveSpecifiedLookupKey(999)); assertThat(router.resolveSpecifiedLookupKey(ISOLATION_DEFAULT)).isEqualTo(ISOLATION_DEFAULT); assertThat(router.resolveSpecifiedLookupKey(ISOLATION_READ_UNCOMMITTED)).isEqualTo(ISOLATION_READ_UNCOMMITTED); assertThat(router.resolveSpecifiedLookupKey(ISOLATION_READ_COMMITTED)).isEqualTo(ISOLATION_READ_COMMITTED); assertThat(router.resolveSpecifiedLookupKey(ISOLATION_REPEATABLE_READ)).isEqualTo(ISOLATION_REPEATABLE_READ); assertThat(router.resolveSpecifiedLookupKey(ISOLATION_SERIALIZABLE)).isEqualTo(ISOLATION_SERIALIZABLE); } private static Stream<String> streamIsolationConstants() { return Arrays.stream(TransactionDefinition.class.getFields()) .filter(ReflectionUtils::isPublicStaticFinal) .map(Field::getName) .filter(name -> name.startsWith("ISOLATION_")); } }
package com.example.geoffrey.receivesms; import android.app.Activity; import android.database.Cursor; import android.database.CursorJoiner; import android.database.MergeCursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.provider.Telephony; import android.telephony.SmsManager; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class InboxActivity extends Activity { private static final String INBOX_URI = "content://sms/inbox"; private static final String OUTBOX_URI = "content://sms/sent"; private static TextView inbox; private static final int SMS_ADDRESS = 2; private static final int SMS_BODY = 12; private static String tid = ""; private static String[] selectionArgs = {""}; private static String searchString = ""; private static String selectionClause = "address = ?"; private static ArrayList<String> convo = new ArrayList<String>(); private static ListView msgListview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inbox); Bundle b = getIntent().getExtras(); tid = b.getString("thread_id"); msgListview = (ListView)findViewById(R.id.msg_list); Button replyBtn = (Button)findViewById(R.id.replyButton); //displaying the conversations convo = getConversationMessages(); // for(String msg: convo) // inbox.append(msg+"\n"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, convo); msgListview.setBackgroundColor(Color.BLACK); msgListview.setAdapter(adapter); msgListview.setSelection(convo.size()); //add listener for reply button replyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String number = tid; EditText textInput = (EditText)findViewById(R.id.editText); String msg = textInput.getText().toString(); textInput.setText(""); sendSMSMessage(number, msg); v.invalidate(); //should refresh finish(); startActivity(getIntent()); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_inbox, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } //Returns the messages sent to the conversation with id:thread_id (phone number) protected ArrayList<String> getConversationMessages() { Uri inboxUri = Uri.parse(INBOX_URI); Uri outboxUri = Uri.parse(OUTBOX_URI); // MergeCursor c = new MergeCursor(); ArrayList<String> messages = new ArrayList<String>(); selectionArgs[0] = tid; //probably a better way to query both inbox and outbox Cursor curIn = getContentResolver().query(inboxUri, null, selectionClause, selectionArgs, "DATE desc"); Cursor curOut = getContentResolver().query(outboxUri, null, selectionClause, selectionArgs, "Date desc"); for (int i=0; i<curIn.getColumnCount();i++) { Log.e(curIn.getColumnName(i),"colName"); } //iterate through both queries and add text body to //the end of an ArrayList sorted by date curIn.moveToFirst(); curOut.moveToFirst(); while(!curIn.isClosed() || !curOut.isClosed()) { String msg = ""; String iTime = "-1"; //use negative one to compare if one cursor is closed String oTime = "-1"; if (!curIn.isClosed()) { if (curIn.getCount() != 0) iTime = curIn.getString(4); else curIn.close(); } if(!curOut.isClosed()) { if (curOut.getCount() != 0) oTime = curOut.getString(4); else curOut.close(); } double iT = Double.parseDouble(iTime); double oT = Double.parseDouble(oTime); if( iT > oT) { if (!curIn.isClosed()) { msg = curIn.getString(SMS_BODY); messages.add(0, msg); if (curIn.isLast()) { curIn.close(); continue; } else { curIn.moveToNext(); } } } else { if (!curOut.isClosed()) { msg = "\t\t\t" + curOut.getString(SMS_BODY); messages.add(0, msg); if (curOut.isLast()) { curOut.close(); continue; } else { curOut.moveToNext(); } } } } return messages; } protected void sendSMSMessage(String number, String textBody) { SmsManager sms = SmsManager.getDefault(); try { sms.sendTextMessage(number, null, textBody, null, null); } catch(Exception e) { Log.e(e.toString(),"exception "); Toast.makeText(getApplicationContext(), "SMS failed, please try again.", Toast.LENGTH_LONG).show(); } } }
package test.java; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class LinearRegressionTest { @Test void fitTest() { assertEquals( 1, 1 ); } @Test void predictTest() { assertEquals( 1, 1 ); } @Test void scoreTest() { assertEquals( 1, 1 ); } }
package login; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JTextField; import javax.swing.JButton; import chatroom.client; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.awt.Rectangle; @SuppressWarnings("serial") public class login extends JFrame{ private JTextField textField; private JTextField textField_1 ; public login() { setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("\u767B\u5F55"); setBounds(new Rectangle(300, 300, 450, 300)); getContentPane().setLayout(null); JPanel panel = new JPanel(); panel.setBounds(10, 11, 424, 250); getContentPane().add(panel); panel.setLayout(null); JLabel label = new JLabel("\u6B22\u8FCE\u4F7F\u7528\u804A\u5929\u5BA4"); label.setFont(new Font("YouYuan", Font.PLAIN, 30)); label.setBounds(93, 11, 253, 42); panel.add(label); JLabel label_1 = new JLabel("\u7528\u6237\u540D"); label_1.setBounds(54, 86, 58, 23); panel.add(label_1); JLabel label_2 = new JLabel("\u5BC6\u7801"); label_2.setBounds(54, 137, 46, 14); panel.add(label_2); textField = new JTextField(); textField.setBounds(200, 87, 146, 20); panel.add(textField); textField.setColumns(10); textField_1 = new JTextField(); textField_1.setColumns(10); textField_1.setBounds(200, 134, 146, 20); panel.add(textField_1); JButton button = new JButton("\u767B\u5F55"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String id =new String(textField.getText()); String passcode=new String(textField_1.getText()); //使用JDBC链接数据库 try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } String url="jdbc:sqlserver://127.0.0.1;DatabaseName=Chat"; Connection conn=null; try{ String username="arthur"; String password="asd"; boolean flag=false; conn=DriverManager.getConnection(url,username,password); Statement st=conn.createStatement(); String sql=("select * from userinfo where id=\'"+id+"\'"+";"); ResultSet rs=st.executeQuery(sql); if(rs.next()){ String tpasscode=new String(); tpasscode=rs.getString(2); if(passcode.equals(tpasscode)){ flag=true; } else{ flag=false; } } if(flag){ dispose(); new client(id).setVisible(true); } else{ new bad("登录失败").setVisible(true); dispose(); //失败 } }catch(SQLException e){ e.printStackTrace(); }finally{ if(conn!=null){ try{ conn.close(); }catch(Exception e){ e.printStackTrace(); } } } } }); button.setBounds(54, 202, 100, 23); panel.add(button); JButton button_1 = new JButton("\u6CE8\u518C\u65B0\u7528\u6237"); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); new reg().setVisible(true); } }); button_1.setBounds(164, 202, 100, 23); panel.add(button_1); JButton button_2 = new JButton("\u9000\u51FA"); button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); button_2.setBounds(274, 202, 100, 23); panel.add(button_2); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String args[]){ new login().setVisible(true); } }
package mobi.app.redis.netty.reply; import mobi.app.redis.transcoders.Transcoder; /** * User: thor * Date: 12-12-20 * Time: 下午2:10 */ public interface Reply<T> { Object get(); T decode(Transcoder transcoder); }
package f.star.iota.milk.ui.artstation.station; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import f.star.iota.milk.base.PVContract; import f.star.iota.milk.base.StringPresenter; public class StationPresenter extends StringPresenter<List<StationBean>> { public StationPresenter(PVContract.View view) { super(view); } @Override protected List<StationBean> dealResponse(String s, HashMap<String, String> headers) { Pattern pattern = Pattern.compile("\"assets\":\\[(.*?)\\]"); Matcher matcher = pattern.matcher(s); StringBuilder sb = new StringBuilder(); while (matcher.find()) { sb.append(matcher.group(1)).append(","); } String result = "[" + sb.substring(0, sb.lastIndexOf(",")) + "]"; return new Gson().fromJson(result, new TypeToken<List<StationBean>>() { }.getType()); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.innovaciones.reporte.dao; import com.innovaciones.reporte.model.DTO.NotificacionDTO; import com.innovaciones.reporte.model.DTO.ReportesDTO; import java.text.ParseException; import java.util.List; /** * * @author pisama */ public interface NotificacionDAO { public List<NotificacionDTO> getNotificacionesByEstadoReporte(boolean preasignacion); public List<NotificacionDTO> getNotificacionesByEstadoReporteByIdUsuario(Integer idUsuario, boolean preasignacion); public NotificacionDTO getNotificacionById(int id); List<ReportesDTO> getReportesPorProducto(int rows, int idProducto) throws ParseException; }
package kr.or.ddit.basic; /* * 은행의 입출금을 쓰레드로 처리하는 예제 * (Lock을 이용한 동기화 처리) */ import java.util.concurrent.locks.ReentrantLock; public class T17_LockAccountTest { public static void main(String[] args) { LockAccount lAcc = new LockAccount(); lAcc.setBalance(10000); // 입금 BankThread2 bth1 = new BankThread2(lAcc); BankThread2 bth2 = new BankThread2(lAcc); bth1.start(); bth2.start(); } } //입출금을 담당하는 클래스 class LockAccount{ private int balance; // 잔액 //lock 객체 생성 => 되도록이면 private final로 만든다. private final ReentrantLock lock = new ReentrantLock(); public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } //입금하는 메소드 public void deposit(int money) { //Lock 객체의 lock() 메소드가 동기화 시작, unlock()메소드가 동기화의 끝 // lock() 메소드로 동기화를 설정한 곳에서는 반드시 unlock()으로 해제해주어야한다. lock.lock(); // 시작 balance += money; // 동기화 처리 부분 lock.unlock(); // 해제 } // 출금하는 메소드(출금 성공: true, 실패 : false) public boolean withdraw(int money) { lock.lock(); boolean chk = false; // try~catch 블럭을 사용할 경우 -> unlock()메소드 호출을 finally 블럭에서 하도록 함 try { if(balance >=money) { for(int i=1; i<=1000000000;i++) {} balance -= money; System.out.println("메소드 안에서 balance = " + getBalance()); chk = true; } }catch(Exception e) { e.printStackTrace(); }finally { lock.unlock(); } return chk; } } //은행업무를 처리하는 쓰레드 class BankThread2 extends Thread{ private LockAccount lAcc; public BankThread2(LockAccount lAcc) { this.lAcc = lAcc; } @Override public void run() { boolean result = lAcc.withdraw(6000); System.out.println("쓰레드 안에서 result=" + result + ", balance = " + lAcc.getBalance()); } }
package com.diplom.service.clustering; import com.diplom.domain.KYF; import org.apache.commons.math3.ml.clustering.*; import org.apache.commons.math3.ml.clustering.evaluation.SumOfClusterVariances; import org.apache.commons.math3.ml.distance.*; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Igor_Kravchenko on 2/1/17. */ @Service public class ClusteringServiceImpl implements ClusteringService { private final Map<String, DistanceMeasure> distanceMeasureAlgorithms = new HashMap<String, DistanceMeasure>() {{ put("EuclideanDistance", new EuclideanDistance()); put("ChebyshevDistance", new ChebyshevDistance()); put("CanberraDistance", new CanberraDistance()); put("EarthMoversDistance", new EarthMoversDistance()); put("ManhattanDistance", new ManhattanDistance()); }}; @Override public List<? extends Cluster<ClusterableRow>> doClustering(List<List<KYF>> kyfMatrix, String clusteringAlgorithmName, String distanceMeasureAlgorithmName) { List<ClusterableRow> clusterInput = wrapMatrixIntoClusterableRows(kyfMatrix); Clusterer<ClusterableRow> clusterer = getConfiguredClusteringAlgorithm(clusteringAlgorithmName, distanceMeasureAlgorithmName); return clusterer.cluster(clusterInput); } private List<ClusterableRow> wrapMatrixIntoClusterableRows(List<List<KYF>> kyfMatrix) { List<ClusterableRow> clusterInput = new ArrayList<>(); for (List<KYF> kyfRow : kyfMatrix) { clusterInput.add(wrapKyfRow(kyfRow)); } return clusterInput; } private ClusterableRow wrapKyfRow(List<KYF> kyfs) { return ClusterableRow.createWrappedRow(kyfs); } private Clusterer<ClusterableRow> getConfiguredClusteringAlgorithm(String clusteringAlgorithmName, String distanceMeasureAlgorithmName) { DistanceMeasure distanceMeasure = distanceMeasureAlgorithms.get(distanceMeasureAlgorithmName); return getClustererInstance(clusteringAlgorithmName, distanceMeasure); } //todo configure clustering parameters public Clusterer<ClusterableRow> getClustererInstance(String clusteringAlgorithmName, DistanceMeasure distanceMeasure) { switch (clusteringAlgorithmName) { case "KMeans": return new KMeansPlusPlusClusterer<>(3, 100000000, distanceMeasure); case "FuzzyKMeans": return new FuzzyKMeansClusterer<>(1, 1, 10000, distanceMeasure); case "MultiKMeans": return new MultiKMeansPlusPlusClusterer<>( new KMeansPlusPlusClusterer<>(3, 10000, distanceMeasure), 10000000, new SumOfClusterVariances<>(distanceMeasure)); case "DBSCAN": return new DBSCANClusterer<>(1, 10000, distanceMeasure); default: return new KMeansPlusPlusClusterer<>(1, 10000, distanceMeasure); } } }
package com.ylkj.modules.sqfz.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ylkj.common.util.ResultVO; import com.ylkj.modules.sqfz.domain.Picture; import com.ylkj.modules.sqfz.service.IPictureService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import com.baomidou.mybatisplus.core.metadata.IPage; /** * <p> * 前端控制器 * </p> * * @author hyy * @since 2021-04-28 */ @RestController @RequestMapping("/sqfz/picture") @RequiredArgsConstructor @Api(tags = "社区发展-照片墙") public class PictureController { private final IPictureService service; /** * 分页查询 */ @GetMapping("/page") @ApiOperation("分页查询") public IPage<Picture> page(@RequestParam(name = "current", defaultValue = "1", required = false) @ApiParam("当前页")Integer current, @RequestParam(name = "pageSize", defaultValue = "10", required = false) @ApiParam("每页显示条数")Integer pageSize){ return service.page(new Page<>(current, pageSize)); } /** * 新增 */ @ApiOperation("新增") @PostMapping public Boolean save(@RequestBody Picture body){ return service.save(body); } /** * 修改 */ @ApiOperation("修改") @PutMapping public Boolean update(@RequestBody Picture body){ return service.updateById(body); } /** * 根据ID获取当前对象 */ @ApiOperation("查询") @GetMapping("/{id}") public Picture getOneById(@PathVariable Long id){ return service.getById(id); } /** * 删除 */ @ApiOperation("删除") @DeleteMapping("/{id}") public Boolean delete(@PathVariable Long id){ return service.removeById(id); } @ApiOperation("全部查询") @GetMapping("/list/{type}") public ResultVO list(@PathVariable int type){ return new ResultVO(service.findByType(type)); } }
package net.sduhsd.royr6099.unit11.gradebook; //© A+ Computer Science - www.apluscompsci.com //Name - //Date - //Class - //Lab - import java.util.Arrays; import java.util.Scanner; import static java.lang.System.*; import static java.util.Arrays.*; public class GradeBookRunner { public static void main( String args[] ) { out.println("Welcome to the Class Stats program!"); Scanner keyboard = new Scanner(System.in); System.out.print("What is the name of this class? "); String className = keyboard.nextLine(); System.out.print("How many students are in this class? "); int numStudents = keyboard.nextInt(); Class c = new Class(className, numStudents); keyboard.nextLine(); for (int i = 1; i <= numStudents; i++) { System.out.print("Enter the name for student " + i + ": "); String stuName = keyboard.nextLine(); System.out.println("Enter the grades for " + stuName + ", using the format (x - grade grade ...)"); String gradeList = keyboard.nextLine(); Student s = new Student(stuName, gradeList); c.addStudent(i - 1, s); } out.println(c); out.println("Failure List = " + c.getFailureList(70)); out.println("Highest Average = " + c.getStudentWithHighestAverage()); out.println("Lowest Average = " + c.getStudentWithLowestAverage()); out.println(String.format("Class Average = %.2f",c.getClassAverage())); } }
import java.util.Scanner; /* * 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 mati */ import java.util.*; public class Suma { public static void main (String args[]) { int valor, valor1, result; Scanner tcl= new Scanner(System.in); System.out.println("Pon un numero"); valor=tcl.nextInt(); System.out.println("Pon otro numero"); valor1=tcl.nextInt(); result= valor+valor1; System.out.println("La suma es"+ result); } }
package com.mytaxi.service.car; import java.util.List; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.mytaxi.dataaccessobject.CarRepository; import com.mytaxi.dataaccessobject.ManufacturerRepository; import com.mytaxi.domainobject.CarDO; import com.mytaxi.domainobject.ManufacturerDO; import com.mytaxi.domainvalue.OnlineStatus; import com.mytaxi.exception.ConstraintsViolationException; import com.mytaxi.exception.EntityNotFoundException; /** * * Service to encapsulate the link between DAO and controller and to have business logic for some car specific things. * <p/> * @author rajkumar */ @Service public class DefaultCarService implements CarService { private static org.slf4j.Logger LOG = LoggerFactory.getLogger(DefaultCarService.class); private final CarRepository carRepository; private final ManufacturerRepository manRepository; @Autowired public DefaultCarService(final CarRepository carRepository, ManufacturerRepository manRepository) { this.carRepository = carRepository; this.manRepository = manRepository; } /** * Selects a car by id. * * @param dcarId * @return found car * @throws EntityNotFoundException if no car with the given id was found. */ @Override public CarDO find(Long carId) throws EntityNotFoundException { return findCarChecked(carId); } /** * Save the given car. * * @param carDo * @return * @throws ConstraintsViolationException if a car already exists with the given license_plate, ... . */ @Override public CarDO save(CarDO carDO) throws ConstraintsViolationException { CarDO car; try { car = carRepository.save(carDO); } catch (DataIntegrityViolationException e) { LOG.warn("ConstraintsViolationException while creating a car: {}", carDO, e); throw new ConstraintsViolationException(e.getMessage()); } return car; } /** * Delete car by Id * * @param carId * @throws EntityNotFoundException */ @Override @Transactional public void delete(Long carId) throws EntityNotFoundException { CarDO carDO = findCarChecked(carId); carRepository.delete(carDO); } /** * Find car by onlineStatue * * @param onlineStatus * @return List<CarDO> * @throws EntityNotFoundException */ @Override public List<CarDO> find(OnlineStatus onlineStatus) { return carRepository.findByOnlineStatus(onlineStatus); } /** * Find car by car name * * @param name * @return CarDO * @throws EntityNotFoundException */ public CarDO findByName(String name) throws EntityNotFoundException { return carRepository.findByName(name); } public ManufacturerDO findManufacturer(Long manId) throws EntityNotFoundException { return manRepository.findById(manId).orElseThrow(() -> new EntityNotFoundException("Could not find Manufacturer entity with id: " + manId)); } /** * @param carId * @return CarDO * @throws EntityNotFoundException */ private CarDO findCarChecked(Long carId) throws EntityNotFoundException { return carRepository.findById(carId) .orElseThrow(() -> new EntityNotFoundException("Could not find entity with id: " + carId)); } }
package sorting; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class UnderstandIntegers { @Before public void setUp() throws Exception { } @Test public void test() { int bit = 1; assertEquals(2, 1 << bit); bit = Integer.SIZE - 1; assertEquals(-1 * (Math.pow(2, Integer.SIZE - 1)), 1 << bit, 0.1); assertEquals(-1 * (Math.pow(2, 31)), 1 << bit, 0.1); bit = 2; assertEquals(4, (4 & (1 << bit))); } }
package controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import modelo.Factura; import modelo.FacturaDAO; import vista.frmFactura; /** * * @author Cristobal Torres * @version mayo 2019 * Clase controlador se declara implements para heredar e implementar varias * interfaces en Java. Se define en la clase controlador modelo logico * que hace de intermediario con Modelo Vista. * */ public class controllerFactura implements ActionListener { FacturaDAO dao = new FacturaDAO(); Factura c = new Factura(); frmFactura frmfactura = new frmFactura(); DefaultTableModel modelo = new DefaultTableModel(); /** * Instancias de formulario para comunicación con modelo vista en el formulario Factura */ public controllerFactura(frmFactura v){ this.frmfactura = v; this.frmfactura.btnListarFactura.addActionListener(this); this.frmfactura.btnAgregarFactura.addActionListener(this); this.frmfactura.btnEditarFactura.addActionListener(this); this.frmfactura.btnSeleccionarFactura.addActionListener(this); this.frmfactura.btnEliminarFactura.addActionListener(this); this.frmfactura.cmbSerieLibroFactura.removeAllItems(); this.frmfactura.cmbRutDistFactura.removeAllItems(); this.frmfactura.cmbMetodoFactura.removeAllItems(); llenarLibro(); llenarRut(); llenarMetodo(); } /** * * @param ae nos permite establecer comunicación con la vista * ActionEvent recibe metodos de los objetos en el formulario */ @Override public void actionPerformed(ActionEvent ae) { if(ae.getSource()==frmfactura.btnListarFactura){ limpiarTabla(); listar(frmfactura.TablaFactura); } if(ae.getSource()==frmfactura.btnAgregarFactura){ limpiarTabla(); agregar(); listar(frmfactura.TablaFactura); } if(ae.getSource()==frmfactura.btnSeleccionarFactura){ frmfactura.txtIdFactura.setEnabled(false); int fila = frmfactura.TablaFactura.getSelectedRow(); if(fila == -1){ JOptionPane.showMessageDialog(frmfactura, "Debe seleccionar una fila"); } else{ int idfactura = Integer.parseInt((String)frmfactura.TablaFactura.getValueAt(fila, 0).toString()); int folio = Integer.parseInt((String)frmfactura.TablaFactura.getValueAt(fila, 1).toString()); int precioneto = Integer.parseInt((String)frmfactura.TablaFactura.getValueAt(fila, 2).toString()); int precioiva = Integer.parseInt((String)frmfactura.TablaFactura.getValueAt(fila, 3).toString()); String titulo = (String)frmfactura.TablaFactura.getValueAt(fila, 4); frmfactura.txtIdFactura.setText(""+idfactura); frmfactura.txtFolioFactura.setText(""+folio); frmfactura.txtPrecioNetoFactura.setText(""+precioneto); frmfactura.txtPrecioIVAFactura.setText(""+precioiva); frmfactura.txtHoraFactura.setText(titulo); } } if(ae.getSource()==frmfactura.btnEditarFactura){ limpiarTabla(); modificar(); listar(frmfactura.TablaFactura); } if (ae.getSource()==frmfactura.btnEliminarFactura){ int fila = frmfactura.TablaFactura.getSelectedRow(); if (fila == -1){ JOptionPane.showMessageDialog(frmfactura, "Debe seleccionar una Factura antes de eliminar"); } else{ int idfactura = Integer.parseInt((String)frmfactura.TablaFactura.getValueAt(fila, 0).toString()); dao.borrar(idfactura); JOptionPane.showMessageDialog(frmfactura, "Factura eliminada"); } limpiarTabla(); listar(frmfactura.TablaFactura); } } /** * * @param tabla con datos llenados mediante un array List * Metodo Listar para mostrar Factura libros */ public void listar (JTable tabla){ modelo = (DefaultTableModel)tabla.getModel(); List<modelo.Factura>lista=dao.listar(); Object[]object=new Object[8]; for (int i = 0; i < lista.size(); i++){ object[0] = lista.get(i).getIdFactura(); object[1] = lista.get(i).getFolio(); object[2] = lista.get(i).getPrecioNeto(); object[3] = lista.get(i).getPrecioIVA(); object[4] = lista.get(i).getHora(); object[5] = lista.get(i).getNumSerie(); object[6] = lista.get(i).getNombreDistribuidor(); object[7] = lista.get(i).getMetodoNombre(); modelo.addRow(object); } frmfactura.TablaFactura.setModel(modelo); } public void llenarLibro(){ ArrayList<String> lista = new ArrayList<String>(); lista = (ArrayList<String>) dao.llenarLibro(); for(int i = 0; i<lista.size();i++){ frmfactura.cmbSerieLibroFactura.addItem(lista.get(i)); // frmlibro.cmbEditorialLibro.addItem(lista.get()); } } public void llenarRut(){ ArrayList<String> lista = new ArrayList<String>(); lista = (ArrayList<String>) dao.llenarRut(); for(int i = 0; i<lista.size();i++){ frmfactura.cmbRutDistFactura.addItem(lista.get(i)); } } public void llenarMetodo(){ ArrayList<String> lista = new ArrayList<String>(); lista = (ArrayList<String>) dao.llenarMetodo(); for(int i = 0; i<lista.size();i++){ frmfactura.cmbMetodoFactura.addItem(lista.get(i)); } } /** * Metodo agregar que comunica con la capa modelo para permitir validar datos * @param idfactura valor entero de ID editorial * @param idfolio valor de tipo string que define el nombre de la editorial * @param precioneto valor entero de precio * @param precioiva valor entero de IVA * @param horacompra valor string de tipo texto para la hora de compra * @param numeroserie valor que toma de dato de tabla libro * @param rutdit valor de tipo entero id como forenea de tabla distribuidor * @param metodo metodo de pago referente a la factura */ public void agregar(){ //if para campo de validación de textos vacios if(frmfactura.txtIdFactura.getText().length()>0 && frmfactura.txtFolioFactura.getText().length() > 0){ int idfactura = Integer.parseInt(frmfactura.txtIdFactura.getText()); int idfolio = Integer.parseInt(frmfactura.txtFolioFactura.getText()); int precioneto = Integer.parseInt(frmfactura.txtPrecioNetoFactura.getText()); int previoiva = Integer.parseInt(frmfactura.txtPrecioIVAFactura.getText()); String horacompra = frmfactura.txtHoraFactura.getText(); int numeroserie = Integer.parseInt(frmfactura.cmbSerieLibroFactura.getSelectedItem().toString()); int rutdist = Integer.parseInt(frmfactura.cmbRutDistFactura.getSelectedItem().toString()); int metodo = Integer.parseInt(frmfactura.cmbMetodoFactura.getSelectedItem().toString()); c.setIdFactura(idfactura); c.setFolio(idfolio); c.setPrecioNeto(precioneto); c.setPrecioIVA(previoiva); c.setHora(horacompra); c.setNumSerie(numeroserie); c.setRutDist(rutdist); c.setMetodoPago(metodo); int r = dao.agregar(c); if(r != 0){ JOptionPane.showMessageDialog(frmfactura, "Factura agregado exitosamente"); } } else{ JOptionPane.showMessageDialog(frmfactura, "Error no se pueden dejar campos vacios"); } } public void modificar(){ if(frmfactura.txtIdFactura.getText().length()>0 && frmfactura.txtFolioFactura.getText().length() > 0){ int idfactura = Integer.parseInt(frmfactura.txtIdFactura.getText()); int idfolio = Integer.parseInt(frmfactura.txtFolioFactura.getText()); int precioneto = Integer.parseInt(frmfactura.txtPrecioNetoFactura.getText()); int previoiva = Integer.parseInt(frmfactura.txtPrecioIVAFactura.getText()); String horacompra = frmfactura.txtHoraFactura.getText(); int numeroserie = Integer.parseInt(frmfactura.cmbSerieLibroFactura.getSelectedItem().toString()); int rutdist = Integer.parseInt(frmfactura.cmbRutDistFactura.getSelectedItem().toString()); int metodo = Integer.parseInt(frmfactura.cmbMetodoFactura.getSelectedItem().toString()); c.setIdFactura(idfactura); c.setFolio(idfolio); c.setPrecioNeto(precioneto); c.setPrecioIVA(previoiva); c.setHora(horacompra); c.setNumSerie(numeroserie); c.setRutDist(rutdist); c.setMetodoPago(metodo); int r = dao.modificar(c); if(r != 0){ JOptionPane.showMessageDialog(frmfactura, "La factura ha sido modificado exitosamente"); } }else{ JOptionPane.showMessageDialog(frmfactura, "Error al modificar Factura"); } } public void limpiarTabla(){ for (int i = 0; i < frmfactura.TablaFactura.getRowCount(); i++){ modelo.removeRow(i); i = i-1; } } }
package hk.ust.felab.rase.slave; import hk.ust.felab.rase.agent.Agent; import hk.ust.felab.rase.sim.Sim; import hk.ust.felab.rase.vo.SimInput; import hk.ust.felab.rase.vo.SimOutput; import org.apache.log4j.Logger; public class Slave implements Runnable { /** * t1; t2, simInput; t3, simOutput */ private transient final Logger log = Logger.getLogger("slaves"); private Sim sim; private Agent agent; public Slave(Sim sim, Agent agent) { this.sim = sim; this.agent = agent; } @Override public void run() { while (true) { try { StringBuilder logLine = null; if (log.isInfoEnabled()) { logLine = new StringBuilder(); logLine.append(System.currentTimeMillis() + "; "); } SimInput simIn = agent.takeSimInput(); if (log.isInfoEnabled()) { logLine.append(System.currentTimeMillis() + ", " + simIn + "; "); } double[] simResult = sim.sim(simIn.args, simIn.seed); SimOutput simOut = new SimOutput(simIn.syncID, simIn.altID, simResult); if (log.isInfoEnabled()) { logLine.append(System.currentTimeMillis() + ", " + simOut); } agent.putSimOutput(simOut); log.info(logLine.toString()); } catch (InterruptedException e) { return; } } } }
package algo3.fiuba.modelo.cartas.moldes_cartas.cartas_monstruos; import algo3.fiuba.modelo.cartas.estados_cartas.EnJuego; import algo3.fiuba.modelo.cartas.modo_monstruo.ModoDeAtaque; import algo3.fiuba.modelo.excepciones.SacrificiosIncorrectosExcepcion; import algo3.fiuba.modelo.jugador.Jugador; import algo3.fiuba.modelo.cartas.Monstruo; import algo3.fiuba.modelo.cartas.efectos.EfectoInsectoComeHombres; import algo3.fiuba.modelo.cartas.efectos.EfectoNulo; import algo3.fiuba.modelo.resultado_combate.ResultadoCombate; import algo3.fiuba.modelo.resultado_combate.ResultadoCombateNulo; import java.util.Observable; public class InsectoComeHombres extends Monstruo { private boolean primerTurno; public InsectoComeHombres(Jugador jugador) { super("Insecto Come-HOMBRES", 450, 600, 2, new EfectoNulo()); setJugador(jugador); setEfecto(new EfectoInsectoComeHombres(jugador)); this.primerTurno = false; } @Override public ResultadoCombate recibirAtaque(Monstruo monstruoAtacante, Integer puntosAtaqueRival) { if (estadoCarta.estaBocaAbajo()) { girarCarta(); return new ResultadoCombateNulo(); } else { return super.recibirAtaque(monstruoAtacante, puntosAtaqueRival); } } @Override public void girarCarta() { if (!primerTurno) { activarEfecto(); } estadoCarta = estadoCarta.girarCarta(); } @Override public void activarEfecto() { if (!primerTurno) { efecto.activar(this); } estadoCarta = estadoCarta.girarCarta(); } @Override public void colocarEnCampo(Jugador jugador, EnJuego tipoEnJuego, Monstruo... sacrificios) { if (!nivel.sacrificiosSuficientes(sacrificios)) throw new SacrificiosIncorrectosExcepcion(String.format("Se necesitan estrictamente %d sacrificios para invocarlo.", nivel.sacrificiosRequeridos())); this.realizarSacrificios(sacrificios); modoMonstruo = new ModoDeAtaque(); // !!! sacarg jugador.colocarCartaEnCampo(this, tipoEnJuego, sacrificios); primerTurno = true; } @Override public void update(Observable o, Object arg) { super.update(o, arg); primerTurno = false; } }
package com.meta.challenge.service; import com.meta.challenge.entity.Address; import com.meta.challenge.entity.Customer; import com.meta.challenge.repository.CustomerRepository; import org.hibernate.exception.ConstraintViolationException; import org.springframework.beans.BeanUtils; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import java.util.List; @Service public class CustomerService { private final CustomerRepository customerRepository; public CustomerService(CustomerRepository customerRepository) { this.customerRepository = customerRepository; } public List<Customer> findAll() { return customerRepository.findAll(); } public Customer saveCustomer(Customer customer) { for (Address address : customer.getAddresses()) { address.setCustomer(customer); } try { return customerRepository.save(customer); } catch( ConstraintViolationException | DataIntegrityViolationException e) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "CPF already registered"); } } public void delete(Long id) { Customer customer = customerRepository.findById(id) .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Customer not found.")); customerRepository.delete(customer); } public void update(Long id, Customer customerRequest) { Customer customer = customerRepository.findById(id) .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Customer not found.")); copyProperties(customer, customerRequest, id); for (Address address : customer.getAddresses()) { address.setCustomer(customer); } customerRepository.save(customer); } private void copyProperties(Customer customer, Customer customerRequest, Long id) { BeanUtils.copyProperties(customerRequest, customer); customer.setId(id); } }
// Matt Knicos // mknicos@gmail.com import acm.program.*; @SuppressWarnings("serial") // The Pythagorean Theorem states a^2 + b^2 = c^2 where ^2 means squared. This program will ask the user // for "a" and "b" and print the the screen the value of "c". Its a dialog program put tested and works // as well as a console program too. public class PythagoreanTheorem extends DialogProgram { public void run(){ println("Enter values to compute the PythagoreanTheorem."); //get values from user double a = readDouble("a: "); double b = readDouble("b: "); a *= a; //square a b *= b; //square b double c = a + b; c = Math.sqrt(c); println("c = " + c); } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.resource; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.cache.Cache; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.web.reactive.resource.GzipSupport.GzippedFiles; import org.springframework.web.testfixture.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest.get; /** * Unit tests for {@link CachingResourceResolver}. * * @author Rossen Stoyanchev */ @ExtendWith(GzipSupport.class) public class CachingResourceResolverTests { private static final Duration TIMEOUT = Duration.ofSeconds(5); private Cache cache; private ResourceResolverChain chain; private List<Resource> locations; @BeforeEach public void setup() { this.cache = new ConcurrentMapCache("resourceCache"); List<ResourceResolver> resolvers = new ArrayList<>(); resolvers.add(new CachingResourceResolver(this.cache)); resolvers.add(new PathResourceResolver()); this.chain = new DefaultResourceResolverChain(resolvers); this.locations = new ArrayList<>(); this.locations.add(new ClassPathResource("test/", getClass())); } @Test public void resolveResourceInternal() { Resource expected = new ClassPathResource("test/bar.css", getClass()); MockServerWebExchange exchange = MockServerWebExchange.from(get("")); Resource actual = this.chain.resolveResource(exchange, "bar.css", this.locations).block(TIMEOUT); assertThat(actual).isNotSameAs(expected); assertThat(actual).isEqualTo(expected); } @Test public void resolveResourceInternalFromCache() { Resource expected = mock(); this.cache.put(resourceKey("bar.css"), expected); MockServerWebExchange exchange = MockServerWebExchange.from(get("")); Resource actual = this.chain.resolveResource(exchange, "bar.css", this.locations).block(TIMEOUT); assertThat(actual).isSameAs(expected); } @Test public void resolveResourceInternalNoMatch() { MockServerWebExchange exchange = MockServerWebExchange.from(get("")); assertThat(this.chain.resolveResource(exchange, "invalid.css", this.locations).block(TIMEOUT)).isNull(); } @Test public void resolverUrlPath() { String expected = "/foo.css"; String actual = this.chain.resolveUrlPath(expected, this.locations).block(TIMEOUT); assertThat(actual).isEqualTo(expected); } @Test public void resolverUrlPathFromCache() { String expected = "cached-imaginary.css"; this.cache.put(CachingResourceResolver.RESOLVED_URL_PATH_CACHE_KEY_PREFIX + "imaginary.css", expected); String actual = this.chain.resolveUrlPath("imaginary.css", this.locations).block(TIMEOUT); assertThat(actual).isEqualTo(expected); } @Test public void resolverUrlPathNoMatch() { assertThat(this.chain.resolveUrlPath("invalid.css", this.locations).block(TIMEOUT)).isNull(); } @Test public void resolveResourceAcceptEncodingInCacheKey(GzippedFiles gzippedFiles) throws IOException { String file = "bar.css"; gzippedFiles.create(file); // 1. Resolve plain resource MockServerWebExchange exchange = MockServerWebExchange.from(get(file)); Resource expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); String cacheKey = resourceKey(file); assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); // 2. Resolve with Accept-Encoding exchange = MockServerWebExchange.from(get(file) .header("Accept-Encoding", "gzip ; a=b , deflate , br ; c=d ")); expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); cacheKey = resourceKey(file + "+encoding=br,gzip"); assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); // 3. Resolve with Accept-Encoding but no matching codings exchange = MockServerWebExchange.from(get(file).header("Accept-Encoding", "deflate")); expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); cacheKey = resourceKey(file); assertThat(this.cache.get(cacheKey).get()).isSameAs(expected); } @Test public void resolveResourceNoAcceptEncoding() { String file = "bar.css"; MockServerWebExchange exchange = MockServerWebExchange.from(get(file)); Resource expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT); String cacheKey = resourceKey(file); Object actual = this.cache.get(cacheKey).get(); assertThat(actual).isEqualTo(expected); } @Test public void resolveResourceMatchingEncoding() { Resource resource = mock(); Resource gzipped = mock(); this.cache.put(resourceKey("bar.css"), resource); this.cache.put(resourceKey("bar.css+encoding=gzip"), gzipped); String file = "bar.css"; MockServerWebExchange exchange = MockServerWebExchange.from(get(file)); assertThat(this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT)).isSameAs(resource); exchange = MockServerWebExchange.from(get(file).header("Accept-Encoding", "gzip")); assertThat(this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT)).isSameAs(gzipped); } private static String resourceKey(String key) { return CachingResourceResolver.RESOLVED_RESOURCE_CACHE_KEY_PREFIX + key; } }
//package com.dropaline.gui; // //import java.awt.Desktop; //import java.awt.Dimension; //import java.awt.event.ActionEvent; //import java.awt.event.ActionListener; //import java.awt.event.MouseAdapter; //import java.awt.event.MouseEvent; //import java.io.File; //import java.io.FileWriter; //import java.io.IOException; //import java.util.ArrayList; //import java.util.Arrays; //import java.util.HashMap; //import java.util.List; //import java.util.Map.Entry; //import java.util.TreeSet; //import java.util.logging.Level; //import java.util.logging.Logger; // //import javax.inject.Inject; //import javax.inject.Singleton; //import javax.swing.DefaultComboBoxModel; //import javax.swing.JButton; //import javax.swing.JCheckBox; //import javax.swing.JComboBox; //import javax.swing.JLabel; //import javax.swing.JPanel; //import javax.swing.JTextField; //import javax.swing.event.PopupMenuEvent; //import javax.swing.event.PopupMenuListener; // //import org.eclipse.e4.core.di.annotations.Creatable; //import org.mcavallo.opencloud.Cloud; //import org.mcavallo.opencloud.Tag; //import org.netbeans.lib.awtextra.AbsoluteConstraints; //import org.netbeans.lib.awtextra.AbsoluteLayout; // //import com.devpmts.DevsLogger; //import com.devpmts.util.e4.DI; //// imcom.devpmts.dropaline.corealine.core.application.ThAppContext; //import com.dropaline.plugins.apis.toodleDo.Symbols; //import com.dropaline.plugins.apis.toodleDo.ToodledoPimApi; // //@Singleton //@Creatable //public class ChangeTag<TASK extends Object> extends JPanel { // // private static final String EXCLUDE_TAGS = DI.getString("excludeTags"); // // private static final String TAG_CLOUD_THRESHOLD = DI.getString("TagCloud_threshold"); // // private static final String INCLUDE_TAGS = DI.getString("includeTags"); // // private static final String INCLUDE_COMPLETED = DI.getString("includeCompleted"); // // private JButton apply; // // private JButton applyExclude; // // private JButton applyInclude; // // private JButton applyThreshold; // // private JTextField excludeTags; // // private JCheckBox includeCompleted; // // private JTextField includeTags; // // private JButton jButton1; // // private JButton jButton2; // // private JButton jButton3; // // private JButton jButton4; // // private JButton jButton5; // // private JLabel jLabel1; // // private JLabel jLabel2; // // private JLabel jLabel3; // // private JTextField newFolder; // // private JTextField newTagName; // // private JButton openCloud; // // private JComboBox tag; // // private JTextField threshold; // // { // tag = new JComboBox(); // newTagName = new JTextField(); // apply = new JButton(); // includeCompleted = new JCheckBox(); // openCloud = new JButton(); // jButton1 = new JButton(); // excludeTags = new JTextField(); // includeTags = new JTextField(); // jLabel1 = new JLabel(); // jLabel2 = new JLabel(); // applyInclude = new JButton(); // applyExclude = new JButton(); // jButton2 = new JButton(); // threshold = new JTextField(); // jLabel3 = new JLabel(); // applyThreshold = new JButton(); // jButton3 = new JButton(); // newFolder = new JTextField(); // jButton4 = new JButton(); // jButton5 = new JButton(); // } // // @Inject // ToodledoPimApi taskApi; // // ArrayList<TASK> tasks; // // TreeSet<String> tagSet; // // private boolean tagsLower; // // @Inject // public ChangeTag() { // DI.injectContextIn(this); // initComponents(); // } // // public void init() { // taskApi.includeCompletedTasks = DI.get(INCLUDE_COMPLETED, false); // includeCompleted.setSelected(taskApi.includeCompletedTasks); // includeTags.setText(DI.getString(INCLUDE_TAGS)); // applyIncludes(); // excludeTags.setText(DI.get(EXCLUDE_TAGS).toString()); // applyExcludes(); // Double thresDouble = DI.get(TAG_CLOUD_THRESHOLD, 0d); // threshold.setText(thresDouble.toString()); // } // // private void initComponents() { // // setAlignmentX(0.0F); // setPreferredSize(new Dimension(300, 350)); // setLayout(new AbsoluteLayout()); // // tag.addMouseListener(new MouseAdapter() { // // @Override // public void mousePressed(MouseEvent evt) { // } // }); // tag.addPopupMenuListener(new PopupMenuListener() { // // @Override // public void popupMenuCanceled(PopupMenuEvent evt) { // } // // @Override // public void popupMenuWillBecomeInvisible(PopupMenuEvent evt) { // } // // @Override // public void popupMenuWillBecomeVisible(PopupMenuEvent evt) { // if (tag.getModel().getSize() == 0) { // populateTags(); // } // } // }); // add(tag, new AbsoluteConstraints(10, 30, 117, -1)); // add(newTagName, new AbsoluteConstraints(130, 30, 111, -1)); // // apply.setText("apply"); // apply.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // HashMap<String, String> changes = new HashMap<>(); // if (!((String) tag.getSelectedItem()).isEmpty() && newTagName.getText() != null) { // changes.put(tag.getSelectedItem().toString(), newTagName.getText()); // taskApi.changeTag(changes, (ArrayList<com.maldworth.toodledo.response.models.Task>) tasks); // Object[] tagArray = tagSet.toArray(); // tagSet.clear(); // for (int i = 0; i < tagArray.length; i++) { // for (Entry<String, String> entry : changes.entrySet()) { // if (entry.getKey().equals(tagArray[i])) { // tagArray[i] = entry.getValue(); // } // } // tagSet.add((String) tagArray[i]); // } // Object[] tmp = tagSet.toArray(); // int index = Arrays.asList(tmp).indexOf(changes.entrySet().iterator().next().getValue()); // populateTags(); // if (index > 0) { // tag.setSelectedIndex(index); // } // newTagName.setText(""); // } // } // }); // add(apply, new AbsoluteConstraints(240, 30, 70, -1)); // // includeCompleted.setText("include Completed"); // includeCompleted.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // boolean bool = includeCompleted.isSelected(); // taskApi.includeCompletedTasks = bool; // DI.set(INCLUDE_COMPLETED, bool); // } // }); // add(includeCompleted, new AbsoluteConstraints(240, 0, -1, -1)); // // openCloud.setText("open Cloud"); // openCloud.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // openCloud(); // } // }); // add(openCloud, new AbsoluteConstraints(120, 0, 117, -1)); // // jButton1.setText("connect Tasks with contactNotes via Tags"); // jButton1.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // } // }); // add(jButton1, new AbsoluteConstraints(0, 320, 262, -1)); // add(excludeTags, new AbsoluteConstraints(10, 180, 180, -1)); // add(includeTags, new AbsoluteConstraints(10, 120, 180, -1)); // // jLabel1.setText("include Tags (Comma-separated):"); // add(jLabel1, new AbsoluteConstraints(10, 100, -1, -1)); // // jLabel2.setText("exclude Tags (Comma-separated):"); // add(jLabel2, new AbsoluteConstraints(10, 160, -1, -1)); // // applyInclude.setText("apply"); // applyInclude.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // applyIncludes(); // } // }); // add(applyInclude, new AbsoluteConstraints(190, 120, -1, -1)); // // applyExclude.setText("apply"); // applyExclude.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // DevsLogger.log(ChangeTag.this.excludeTags.getText()); // applyExcludes(); // } // }); // add(applyExclude, new AbsoluteConstraints(190, 180, -1, -1)); // // jButton2.setText("populate Tags"); // jButton2.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // populateTags(); // } // }); // add(jButton2, new AbsoluteConstraints(0, 0, -1, -1)); // add(threshold, new AbsoluteConstraints(130, 220, 60, -1)); // // jLabel3.setText("tag threshold"); // add(jLabel3, new AbsoluteConstraints(40, 220, -1, -1)); // // applyThreshold.setText("apply"); // applyThreshold.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // DI.set(TAG_CLOUD_THRESHOLD, threshold.getText()); // DevsLogger.log("threshold changed to " + DI.get(TAG_CLOUD_THRESHOLD, 0d)); // } // }); // add(applyThreshold, new AbsoluteConstraints(190, 220, -1, -1)); // // jButton3.setText("get Lower threshold Tags"); // jButton3.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // ChangeTag.this.getLowerThresholdTags(); // } // }); // add(jButton3, new AbsoluteConstraints(50, 250, -1, -1)); // add(newFolder, new AbsoluteConstraints(130, 60, 110, -1)); // // jButton4.setText("apply"); // jButton4.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // if (!((String) tag.getSelectedItem()).isEmpty() && !newFolder.getText().isEmpty()) { // populateTags(); // taskApi.tag2Folder(tag.getSelectedItem().toString(), newFolder.getText(), // (ArrayList<com.maldworth.toodledo.response.models.Task>) tasks); // } // } // }); // add(jButton4, new AbsoluteConstraints(240, 60, -1, -1)); // // jButton5.setText("remove duplicate Tasks"); // jButton5.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent evt) { // taskApi.cleanTags(); // } // }); // add(jButton5, new AbsoluteConstraints(40, 280, -1, -1)); // } // // public void openCloud() { // populateTags(); // try { // int count = 0; // int countTasks = taskApi.taskCount; // int countUsage = 0; // List<Tag> tags = getCloudTags(); // String az = "\""; // String str = "<html><head>"; // // // str += // // "<meta http-equiv="+az+"content-type"+az+" content="+az+"text/html; charset=Unicode"+az+">"; // str += "</head><body><p style=" + az + "text-align:center; font-size:40px;" + az + ">"; // str += "<a href=http://www.toodledo.com/views/folder.php>folder</a> "; // str += "<a href=http://www.toodledo.com/views/index.php?i=0>hotlist</a> "; // str += "<a href=http://www.toodledo.com/views/index.php?i=4>starred</a> "; // str += "<a href=http://www.toodledo.com/views/search.php?i=9829>inbox</a> "; // str += "<br><br>"; // str += "<style type=" // + az // + "text/css" // + az // + "> A:link { text-decoration: none margin-left:10px } A:visited {text-decoration: none} A:active {text-decoration: none} A:hover {text-decoration: underline; color: red;} </style>"; // String strBig = ""; // for (Tag tagTmp : tags) { // if (tagsLower && !taskApi.tagIncludeSet.contains(tagTmp.getName().trim())) { // DevsLogger.log("skipping..." + tagTmp.getName()); // countTasks--; // continue; // } // count++; // countUsage += tagTmp.getScoreInt(); // boolean big = false; // tagTmp.setLink("http://www.toodledo.com/views/search.php?i=-9&xx=1340583&numrules=2&numgroups=0&andor=1&mygroup1=0&field1=2&type11=6&type21=6&type31=6&type41=6&type51=6&type61=6&mygroup2=0&field2=18&type12=1&type22=2&type32=2&type42=2&type52=2&type62=2&value2=" // + tagTmp.getName() + "&search=1"); // // double weight = tag.getWeight(); // // if (weight > 0.06) { // // weight = 0.06 + ((weight - 0.06) * 1 / 10); // // } // // if (weight > 1) { // // big = true; // // } // // if (weight < 0.06) { // // weight = 0.06; // // } // int score = (tagTmp.getScoreInt()); // score = (score < 50) ? score : 50; // score = score * 1 / 3 + 13; // // if (tag.getWeight() <= 1) { // // score = 15 + 15 * tag.getWeightInt(); // // } // String tmp = " <a href=" + tagTmp.getLink() + " style=" + az + "font-size: " + score + "px" + az + ";>" // + tagTmp.getName() + "(" + tagTmp.getScoreInt() + ") </a> "; // tmp += "<a style=" + az + "font-size:12px" + az + "; text-color:white!important;></a> "; // // // + "("+ tag.getScoreInt() + ")</a> "; // if (big) { // strBig += tmp; // } else { // str += tmp; // } // } // str += strBig; // str += "<p style=" + az + "color:#ccc; text-align:left; font-size:15px;" + az + ">"; // str += "<br>"; // str += "number of Tags: " + count + "<br>"; // str += "number of all Tasks: " + countTasks + "<br>"; // str += "number of Usages: " + countUsage + "<br>"; // if (!tagsLower) { // str += "included Tags: " + taskApi.tagExcludeSet + "<br>"; // } // str += "excluded Tags: " + taskApi.tagIncludeSet + "<br>"; // str += "</p></body></html>"; // File file = new File("tagCloud.html"); // FileWriter fw = new FileWriter(file); // fw.write(str); // fw.close(); // Desktop.getDesktop().open(file); // } catch (IOException ex) { // Logger.getLogger(ChangeTag.class.getName()).log(Level.SEVERE, null, ex); // } // } // // public void getTagCloud(String text) { // text = text.substring(Symbols.SYMBOL_TAG_CLOUD.length()); // taskApi.tagIncludeSet.clear(); // tag.setModel(new DefaultComboBoxModel()); // taskApi.tagIncludeSet.addAll(Arrays.asList(text.split(","))); // openCloud(); // } // // private void populateTags() { // DevsLogger.log("populating tags"); // tasks = (ArrayList<TASK>) taskApi.getTasks(); // tagSet = taskApi.getTags((ArrayList<com.maldworth.toodledo.response.models.Task>) tasks); // Object[] tags = tagSet.toArray(); // tag.setModel(new DefaultComboBoxModel(tags)); // } // // private void applyIncludes() { // getTaskPimApi().tagIncludeSet.clear(); // getTaskPimApi().tagIncludeSet.addAll(Arrays.asList(includeTags.getText().split((",")))); // DI.set(INCLUDE_TAGS, getTaskPimApi().tagIncludeSet); // } // // private void applyExcludes() { // getTaskPimApi().tagExcludeSet.clear(); // getTaskPimApi().tagExcludeSet.addAll(Arrays.asList(excludeTags.getText().split((",")))); // DI.set(EXCLUDE_TAGS, getTaskPimApi().tagExcludeSet); // } // // private ToodledoPimApi getTaskPimApi() { // return DI.get(ToodledoPimApi.class); // } // // List<Tag> getCloudTags() { // Cloud cloud = new Cloud(); // cloud.setThreshold(DI.get(TAG_CLOUD_THRESHOLD, 0d)); // cloud.setMaxTagsToDisplay(500); // cloud.addText(taskApi.tagText); // DevsLogger.log(taskApi.tagText); // return cloud.tags(); // } // // void getLowerThresholdTags() { // Double d = DI.get(TAG_CLOUD_THRESHOLD, 0d); // taskApi.tagIncludeSet.clear(); // DI.set(TAG_CLOUD_THRESHOLD, d + 1d); // populateTags(); // List<Tag> listUpper = getCloudTags(); // DI.set(TAG_CLOUD_THRESHOLD, 0d); // List<Tag> listLower = getCloudTags(); // List<String> strUp = new ArrayList<>(); // List<String> strLow = new ArrayList<>(); // for (Tag tag : listLower) { // strLow.add(tag.getName()); // } // for (Tag tag : listUpper) { // strUp.add(tag.getName()); // } // for (String tagLow : strLow) { // if (!strUp.contains(tagLow) && !tagLow.equals("")) { // taskApi.tagIncludeSet.add(tagLow); // } // } // tagsLower = true; // openCloud(); // tagsLower = false; // taskApi.tagIncludeSet.clear(); // DI.set(TAG_CLOUD_THRESHOLD, d); // } // }
package Pro09.PalindromeNumber; //判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 import java.util.Scanner; public class Solution { public static void main(String[] args) { System.out.println("Please enter the number: "); Scanner scanner = new Scanner(System.in); // double x = scanner.nextDouble(); int x = scanner.nextInt(); scanner.close(); Solution solution = new Solution(); boolean result = solution.isPalindrome(x); System.out.println("result: " + result); } public boolean isPalindrome(int x) { String number = String.valueOf(x); int length = number.length(); int l = length; // 如果这个数是小数,或者小于0的话一定不是回文串 if (x < 1 & x != 0) { return false; } // 如果位数为偶数的话,形如1001的情况 else if (length % 2 == 0 & length >= 2) { for (int i = 0; i < length/2; i++) { l--; if (number.charAt(i) != number.charAt(l)) { return false; } } return true; } // 形如12121、123454321的情况 else { for (int i = 0; i < (length + 1) / 2; i++) { l--; if (number.charAt(i) != number.charAt(l)) { return false; } } return true; } } }
/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.xjc.api; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; /** * Implemented by the driver of the compiler engine to handle * errors found during the compiliation. * * <p> * This class implements {@link ErrorHandler} so it can be * passed to anywhere where {@link ErrorHandler} is expected. * * <p> * However, to make the error handling easy (and make it work * with visitor patterns nicely), this interface is not allowed * to abort the processing. It merely receives errors. * * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public interface ErrorListener extends com.sun.xml.bind.api.ErrorListener { void error(SAXParseException exception); void fatalError(SAXParseException exception); void warning(SAXParseException exception); /** * Used to report possibly verbose information that * can be safely ignored. */ void info(SAXParseException exception); }
package com.unicom.patrolDoor.service; import com.unicom.patrolDoor.entity.Question; import javax.management.ObjectName; import java.util.List; import java.util.Map; /** * @Author wrk * @Date 2021/3/24 16:02 */ public interface QuestionService { List<Question> selectAllQuestion(Integer tag,String title); void save(Question question); Question selectById(Integer id); List<Question> selectAllQuestionByViewCount(Integer tag); Integer sendQuestionNum(String begin, String end); List<Map<Object, Object>> selectQuestionByHot(); void updateViewNumById(Integer id); List<Question> selectByTagId(int tagId); void updateQuestionByTagId(int tagId,String time); List<Question> selectByNameAndStatu(String name,Integer userId); List<Question> selectByName(String title); void updateTagByQuestionAndTag(int questionId, int tag); Question selectLastQuestion(); List<Question> selectAllQuestionByTagAndTypeAndUserId(Integer tag, Integer type, Integer userId,String title); }
package com.bon.wx; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ImportResource; /** * 系统管理启动类 * com.bon.wx.service * * @author pengwen * @create 2018/4/27 0027 **/ @SpringBootApplication @ComponentScan({"com.bon"}) @ImportResource({"classpath:dubbo.xml"}) public class SystemApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication app = new SpringApplication(SystemApplication.class); app.setWebEnvironment(false); app.run(args); synchronized (SystemApplication.class) { while (true) { try { SystemApplication.class.wait(); } catch (Throwable e) { } } } } @Override public void run(String... strings) throws Exception { } }
/** * */ package com.gp.graphqlaggregator.graphql.datafetcher; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.gp.graphqlaggregator.entity.User; import com.gp.graphqlaggregator.repo.UserRepository; import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; /** * @author GANESH * */ @Component public class AllUserAccountsDataFetcher implements DataFetcher<List<User>> { @Autowired private UserRepository userRepo; @Override public List<User> get(DataFetchingEnvironment env) { List<User> u=userRepo.findAll(); return u; } }
package cit360junit; import java.util.Arrays; import java.util.Random; public class Hero { private String hero_class; private int health; private int strength; private boolean disease; private String items[]; public Hero(String chosen_class, int class_health, int class_strength){ hero_class = chosen_class; health = class_health; strength = class_strength; disease = false; items = new String[]{"Potion", "Potion", "Bread"}; } public String getHeroClass() { return hero_class; } public int getHealth() { return health; } public int getStrength() { return strength; } public boolean isDisease() { return disease; } public String[] getItems() { return items; } public void takeDamage(int hitAmount) { health = health - hitAmount; } public void useItem(String item) { for (int i = 0; i < items.length; i++) { // If Item is found if(items[i].equals(item)){ // Item is removed from array for (int j = i; j < items.length - 1; j++) { items[j] = items[j+1]; items[j+1] = null; } // if item was a potion then disease is healed and strength // returns to normal if (item.equals("Potion")) { disease = false; strength = 10; } // if item was bread then health is raised if (item.equals("Bread")) { //Prevents health of exceeding 100 if (health > 80) { health = 100; } else { health = health + 20; } } break; } } } public boolean addItem(String item) { // finds the first null spot to add item for (int i = 0; i < items.length; i++) { if(items[i] == null) { items[i] = item; return true; } } return false; } public void getDisease() { if (health < 20) { disease = true; Random newStrength = new Random(); // While loop ensures that strength can never be the standard 10 // after contracting a disease while (strength == 10) { strength = 0 + newStrength.nextInt(15); } } } }
package com.neusoft.springtest.homework; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.neusoft.springtest.json.User; public class IteratorTest { public static void main(String[] args) { // MAP读取 Map<String, String> map = new HashMap<String, String>(); map.put("key1", "value1"); map.put("key2", "value2"); // 将map集合中的映射关系取出,存入到set集合 Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Entry e = (Entry) it.next(); System.out.println("键" + e.getKey() + "的值为" + e.getValue()); } Iterator itkeyMap = map.keySet().iterator(); while (itkeyMap.hasNext()) { Object key= itkeyMap.next(); System.out.println("keySet方法读取的值"+map.get(key)); } //set读取 Set<String> objectSet = new HashSet<String>(); objectSet.add("white"); objectSet.add("white"); objectSet.add("green"); objectSet.add("yellow"); objectSet.add("blue"); objectSet.add("Yellow"); objectSet.add("red"); objectSet.add("white"); System.out.println("第一种方式读取set1 --------------------"); for (String item : objectSet) { System.out.println(item); } //for 循环根据类型进行相应的转换 for (Object obj : objectSet) { if(obj instanceof Integer){ int aa= (Integer)obj; System.out.println(aa); }else if(obj instanceof String){ String aa = (String)obj; System.out.println(aa); } } System.out.println("第二种方式读取set2 --------------------"); Iterator it1 = objectSet.iterator(); while (it1.hasNext()) { System.out.println(it1.next()); } //读取list List<User> list=new ArrayList<User>(); User user = new User(); user.setName("小民"); user.setEmail("xiaomin@sina.com"); user.setAge(20); User userb = new User(); userb.setName("小彬"); userb.setEmail("xiaobin@sina.com"); userb.setAge(20); list.add(user); list.add(userb); Iterator it2=list.iterator(); while(it2.hasNext()){ User u=(User) it2.next(); System.out.println("读取的LIST对象的属性值"+u.getName()); } for(User userEntity:list){ System.out.println("userEntity属性值"+userEntity.getName()); } for(int i=0;i<list.size();i++){ User u1=list.get(i); System.out.println("for循环2中的userEntity属性值"+u1.getName()); } } }