text stringlengths 10 2.72M |
|---|
package dedup;
public class Solution {
public String deDup(String input) {
// Write your solution here.
if(input == null){
return null;
}
char [] array = input.toCharArray();
//char [] p = input.toCharArray();
int slow = 0;
//!!!array[fast]!=array[slow-1]
for(int fast = 0; fast < array.length; fast++){
if (slow == 0 || array[slow-1] != array[fast]){
array[slow] = array[fast];
slow++;
}
}
return new String(array, 0 ,slow);
}
public static void main(String [] args){
Solution s = new Solution();
System.out.println(s.deDup("abcc"));
}
}
|
package com.smxknife.lock.redis;
import com.smxknife.lock.BaseLock;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;
/**
* @author smxknife
* 2021/6/11
*/
@Deprecated
public class RedisSetLock extends BaseLock {
private JedisPool jedisPool;
private String lockName;
private long expireMills;
public void lock() {
/**
* 方案2:
* set lock_name threadid ex 10 nx
* 加锁是没有问题的,
* 解锁:threadid == get lock_name 然后 del lock_name 不是原子的
*/
try (final Jedis jedis = jedisPool.getResource()) {
while (true) {
// 为了对可重入进行判断
// 到那时这种方式是错误的,因为jedis.get返回的线程名,与下一步的判断不是一个原子操作,
// 假如刚获得的name为本线程id,但是由于watchdog没有及时续约,
// final String name = jedis.get(lockName);
// if (name.equals(Thread.currentThread().getName())) {
//
// }
final String string = jedis.set(lockName, Thread.currentThread().getName(), SetParams.setParams().nx().px(expireMills));
if ("OK".equals(string)) {
// 加锁成功
return;
}
}
} catch (Exception e) {
// redis连接异常,加锁失败
}
}
@Deprecated
public void unlock() {
// 这里就是删除key的过程
try(final Jedis jedis = jedisPool.getResource()) {
/**
* 删除key
* 但是不能随便删除,不能删除别人的锁,所以需要判断一下key对应的值是否为当前的线程
* 但是,出现判读是否可重入就可能出问题,因为非原子的
*/
final String threadName = jedis.get(this.lockName);
if (Thread.currentThread().getName().equals(threadName)) {
jedis.del(this.lockName);
}
} catch (Exception e) {
// jedis 连接获取异常,解锁失败
}
}
}
|
package com.tencent.mm.plugin.shake.b;
public final class i {
public static final int mWK = 1;
private static final /* synthetic */ int[] mWL = new int[]{mWK};
}
|
package org.jboss.perf.test.server.controller.forms;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.hibernate.validator.constraints.NotEmpty;
@ManagedBean
@ViewScoped
public class ThresholdForm implements Serializable {
private static final long serialVersionUID = 1L;
@NotEmpty(message="Attribute must be not empty.")
private String attribute;
// for restriction is used DoubleValueValidator
private String value;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void clear() {
attribute = null;
value = null;
}
}
|
import java.sql.SQLException;
import java.util.ArrayList;
public class Gruppe {
Integer grId;
int art,instId;
String name,bemerkung;
static ArrayList<Gruppe> gruppen;
Gruppe(){
grId=null; name=bemerkung=null;
art=instId=0;
}
Gruppe(SqCursor c) throws SQLException{
grId=c.getI(1); instId=c.geti(2); name=c.getS(3);
art=c.geti(4); bemerkung=c.getS(5);
}
void Sync() throws SQLException{
BindBef b;
if (grId==null) {
b=new BindBef(Config.coInt,"insert into public.gruppen values(?,?,?,?,?)");
grId=Config.coInt.getI("select coalesce(max(GrId))+1 from public.gruppen");
b.add(grId); b.add(instId); b.add(name); b.add(art); b.add(bemerkung);
} else {
b=new BindBef(Config.coInt,"update public.gruppen set InstId=?,Name=?,Art=?,Bemerkung=? where grId=?");
b.add(instId); b.add(name); b.add(art); b.add(bemerkung); b.add(grId);
}
b.exec();
}
static void ladeGruppen(){
gruppen=new ArrayList<>();
try {
SqCursor c=new SqCursor(Config.coInt);
for (c.open("select * from public.Gruppen order by Name");c.next();)
gruppen.add(new Gruppe(c));
c.close();
} catch(SQLException e) { Conf.dbError("Gruppenladen",e);}
}
static Gruppe suche(int id) {
for (Gruppe k:gruppen)
if (k.grId==id) return k;
return null;
}
static Gruppe suche(String name) {
for (Gruppe k:gruppen)
if (k.name.equals(name)) return k;
return null;
}
static void list(Integer nuId) throws SQLException{
SqCursor c=new SqCursor(Config.coInt);
if (nuId!=null)
c.open("select GrId,Name,Instanz,Art from public.DspGruppen where GrId in(select GrId from public.Rechte where NuId="+nuId+") order by 2");
else
c.open("select GrId,Name,Instanz,Art from public.DspGruppen order by 2");
SpaltenTab t=new SpaltenTab("#Id","Name","Instanz","Art");
while (c.next()) {
t.add(c.geti(1)); t.add(c.getS(2)); t.add(c.getS(3)); t.add(c.getS(4));
}
t.ausgabe();
}
}
|
package com.mes.cep.event;
import com.bstek.urule.model.Label;
public class CheckEvent extends Event {
@Label("检验请求")
private String checkRequest;
@Label("检验完成")
private String checkFinish;
public String getCheckRequest() {
return checkRequest;
}
public void setCheckRequest(String checkRequest) {
this.checkRequest = checkRequest;
}
public String getCheckFinish() {
return checkFinish;
}
public void setCheckFinish(String checkFinish) {
this.checkFinish = checkFinish;
}
}
|
/*
* 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 mathsapp;
/**
*
* @author x14428818
*/
public class ConJnr extends javax.swing.JFrame {
/**
* Creates new form Theorems1
*/
public ConJnr() {
initComponents();
}
/**
* 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() {
Logo = new javax.swing.JLabel();
Back = new javax.swing.JButton();
home = new javax.swing.JButton();
Construction1 = new javax.swing.JButton();
Construction2 = new javax.swing.JButton();
Construction3 = new javax.swing.JButton();
Construction4 = new javax.swing.JButton();
Search = new javax.swing.JButton();
Construction5 = new javax.swing.JButton();
Background = new javax.swing.JLabel();
home1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Logo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mathsapp/purple logo.JPG"))); // NOI18N
Logo.setText("jLabel1");
getContentPane().add(Logo, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 30, 200, 70));
Back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mathsapp/back.png"))); // NOI18N
Back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BackActionPerformed(evt);
}
});
getContentPane().add(Back, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 430, 40, 40));
home.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mathsapp/home.png"))); // NOI18N
home.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
homeActionPerformed(evt);
}
});
getContentPane().add(home, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 430, 40, 40));
Construction1.setBackground(new java.awt.Color(255, 255, 204));
Construction1.setForeground(new java.awt.Color(0, 153, 51));
Construction1.setText("Construction 1");
Construction1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Construction1ActionPerformed(evt);
}
});
getContentPane().add(Construction1, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 140, 160, 30));
Construction2.setBackground(new java.awt.Color(255, 255, 204));
Construction2.setForeground(new java.awt.Color(0, 153, 51));
Construction2.setText("Construction 2");
Construction2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Construction2ActionPerformed(evt);
}
});
getContentPane().add(Construction2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 190, 160, 30));
Construction3.setBackground(new java.awt.Color(255, 255, 204));
Construction3.setForeground(new java.awt.Color(0, 153, 51));
Construction3.setText("Construction 3");
Construction3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Construction3ActionPerformed(evt);
}
});
getContentPane().add(Construction3, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 240, 160, 30));
Construction4.setBackground(new java.awt.Color(255, 255, 204));
Construction4.setForeground(new java.awt.Color(0, 153, 51));
Construction4.setText("Construction 4");
Construction4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Construction4ActionPerformed(evt);
}
});
getContentPane().add(Construction4, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 290, 160, 30));
Search.setBackground(new java.awt.Color(255, 255, 204));
Search.setForeground(new java.awt.Color(0, 153, 51));
Search.setText("Search");
Search.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SearchActionPerformed(evt);
}
});
getContentPane().add(Search, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 440, 80, 20));
Construction5.setBackground(new java.awt.Color(255, 255, 204));
Construction5.setForeground(new java.awt.Color(0, 153, 51));
Construction5.setText("Construction 5");
Construction5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Construction5ActionPerformed(evt);
}
});
getContentPane().add(Construction5, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 340, 160, 30));
Background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mathsapp/background.jpg"))); // NOI18N
Background.setText("jLabel1");
getContentPane().add(Background, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 391, 480));
Background.getAccessibleContext().setAccessibleName("background");
home1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mathsapp/home.png"))); // NOI18N
home1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
home1ActionPerformed(evt);
}
});
getContentPane().add(home1, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 430, 40, 40));
setSize(new java.awt.Dimension(407, 518));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void Construction1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Construction1ActionPerformed
Construction1 myConstruction1 = new Construction1();
myConstruction1.setVisible(true);
dispose();// TODO add your handling code here:
}//GEN-LAST:event_Construction1ActionPerformed
private void Construction3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Construction3ActionPerformed
Construction3 myConstruction3 = new Construction3();
myConstruction3.setVisible(true);
dispose();
}//GEN-LAST:event_Construction3ActionPerformed
private void Construction4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Construction4ActionPerformed
Construction4 myConstruction4 = new Construction4();
myConstruction4.setVisible(true);
dispose();
}//GEN-LAST:event_Construction4ActionPerformed
private void BackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackActionPerformed
ConstructionsGUI myConstructions = new ConstructionsGUI();
myConstructions.setVisible(true);
dispose();
// TODO add your handling code here:
}//GEN-LAST:event_BackActionPerformed
private void homeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_homeActionPerformed
HomePageGUI myHomePage = new HomePageGUI();
myHomePage.setVisible(true);
dispose();
// TODO add your handling code here:
}//GEN-LAST:event_homeActionPerformed
private void Construction2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Construction2ActionPerformed
Construction2 myConstruction2 = new Construction2();
myConstruction2.setVisible(true);
dispose();
}//GEN-LAST:event_Construction2ActionPerformed
private void SearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchActionPerformed
ConSearch myConSearch = new ConSearch();
myConSearch.setVisible(true);
dispose();
}//GEN-LAST:event_SearchActionPerformed
private void Construction5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Construction5ActionPerformed
Construction5 myConstruction5 = new Construction5();
myConstruction5.setVisible(true);
dispose();
}//GEN-LAST:event_Construction5ActionPerformed
private void home1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_home1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_home1ActionPerformed
/**
* @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(ConJnr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ConJnr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ConJnr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ConJnr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ConJnr().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Back;
private javax.swing.JLabel Background;
private javax.swing.JButton Construction1;
private javax.swing.JButton Construction2;
private javax.swing.JButton Construction3;
private javax.swing.JButton Construction4;
private javax.swing.JButton Construction5;
private javax.swing.JLabel Logo;
private javax.swing.JButton Search;
private javax.swing.JButton home;
private javax.swing.JButton home1;
// End of variables declaration//GEN-END:variables
}
|
package model;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class HandGunBulletTest {
private HandGunBullet b1;
private Player p;
@BeforeEach
public void setUp() {
p = new Player();
b1 = new HandGunBullet(p);
}
@Test
public void testConstructor() {
assertEquals(b1.getDir(), p.getDir());
assertEquals(b1.getX(), p.getX());
assertEquals(b1.getY(), p.getY());
assertEquals(b1.getWeaponType(), WeaponType.HANDGUN);
assertEquals(b1.getDamage(), b1.damage);
}
@Test
public void testMoveNorth() {
assertEquals(p.STARTING_XC, b1.getX());
assertEquals(p.STARTING_YC, b1.getY());
b1.move();
assertEquals(p.STARTING_XC, b1.getX());
assertEquals(p.STARTING_YC - b1.SPEED, b1.getY());
}
@Test
public void testMoveSouth() {
assertEquals(p.STARTING_XC, b1.getX());
assertEquals(p.STARTING_YC, b1.getY());
b1.setDir(Direction.SOUTH);
b1.move();
assertEquals(p.STARTING_XC, b1.getX());
assertEquals(p.STARTING_YC + b1.SPEED, b1.getY());
}
@Test
public void testMoveEast() {
assertEquals(p.STARTING_XC, b1.getX());
assertEquals(p.STARTING_YC, b1.getY());
b1.setDir(Direction.EAST);
b1.move();
assertEquals(p.STARTING_XC + b1.SPEED, b1.getX());
assertEquals(p.STARTING_YC, b1.getY());
}
@Test
public void testMoveWest() {
assertEquals(p.STARTING_XC, b1.getX());
assertEquals(p.STARTING_YC, b1.getY());
b1.setDir(Direction.WEST);
b1.move();
assertEquals(p.STARTING_XC - b1.SPEED, b1.getX());
assertEquals(p.STARTING_YC, b1.getY());
}
// tests for getters and setters for completion
@Test
public void testSetX() {
assertEquals(p.STARTING_XC, b1.getX());
b1.setX(120);
assertEquals(120, b1.getX());
}
@Test
public void testSetY() {
assertEquals(p.STARTING_YC, b1.getY());
b1.setY(120);
assertEquals(120, b1.getY());
}
}
|
package com.lecture.spring;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.lecture.spring.dao.IDao;
import com.lecture.spring.dao.PhamphletDao;
import com.lecture.spring.model.ModelCanvas;
import com.lecture.spring.model.ModelComment;
import com.lecture.spring.model.ModelEvalutation;
import com.lecture.spring.model.ModelFont;
import com.lecture.spring.model.ModelImage;
import com.lecture.spring.model.ModelPamphelt;
import com.lecture.spring.model.ModelPamphletBackground;
import com.lecture.spring.model.ModelPamphletComponentBasicAttribute;
import com.lecture.spring.model.ModelPamphletComponentdetailAttributeTable;
import com.lecture.spring.model.ModelVideo;
public class DBtest {
private static Logger logger = LoggerFactory.getLogger(DBtest.class);
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
IDao one = new PhamphletDao();
ModelFont test = null;
test = one.getComponentFont(1);
if(test != null){
System.out.println(test);
}
else
assertTrue(false);
}
}
|
package com.mx.profuturo.bolsa.model.wallet.vo;
public class WalletResultVO {
private Integer idCandidato;
private String areaInteres;
private int idAreaInteres;
private String calificacion;
private int idCalificacion;
private String subAreaInteres;
private int idSubAreaInteres;
private String tiempoEnCartera;
private int idTiempoCartera;
private String nombre;
private int edad;
private String escolaridad;
private int idEscolaridad;
private String ubicacion;
private int idUbicacion;
public String getTiempoEnCartera() { return tiempoEnCartera; }
public void setTiempoEnCartera(String tiempoEnCartera) { this.tiempoEnCartera = tiempoEnCartera; }
public int getIdAreaInteres() {
return idAreaInteres;
}
public void setIdAreaInteres(int idAreaInteres) {
this.idAreaInteres = idAreaInteres;
}
public int getIdCalificacion() {
return idCalificacion;
}
public void setIdCalificacion(int idCalificacion) {
this.idCalificacion = idCalificacion;
}
public int getIdSubAreaInteres() {
return idSubAreaInteres;
}
public void setIdSubAreaInteres(int idSubAreaInteres) {
this.idSubAreaInteres = idSubAreaInteres;
}
public int getIdTiempoCartera() {
return idTiempoCartera;
}
public void setIdTiempoCartera(int idTiempoCartera) {
this.idTiempoCartera = idTiempoCartera;
}
public int getIdEscolaridad() {
return idEscolaridad;
}
public void setIdEscolaridad(int idEscolaridad) {
this.idEscolaridad = idEscolaridad;
}
public int getIdUbicacion() {
return idUbicacion;
}
public void setIdUbicacion(int idUbicacion) {
this.idUbicacion = idUbicacion;
}
public Integer getIdCandidato() {
return idCandidato;
}
public void setIdCandidato(Integer idCandidato) {
this.idCandidato = idCandidato;
}
public String getAreaInteres() {
return areaInteres;
}
public void setAreaInteres(String areaInteres) {
this.areaInteres = areaInteres;
}
public String getCalificacion() {
return calificacion;
}
public void setCalificacion(String calificacion) {
this.calificacion = calificacion;
}
public String getSubAreaInteres() {
return subAreaInteres;
}
public void setSubAreaInteres(String subAreaInteres) {
this.subAreaInteres = subAreaInteres;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getEdad() {
return edad;
}
public void setEdad(int edad) {
this.edad = edad;
}
public String getEscolaridad() {
return escolaridad;
}
public void setEscolaridad(String escolaridad) {
this.escolaridad = escolaridad;
}
public String getUbicacion() {
return ubicacion;
}
public void setUbicacion(String ubicacion) {
this.ubicacion = ubicacion;
}
}
|
package com.wanglu.movcat.repository;
import com.wanglu.movcat.model.Background;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface BackgroundRepository extends JpaRepository<Background, Integer>{
@Query(value = "SELECT * FROM background ORDER BY RAND() LIMIT 1", nativeQuery = true)
Background randomfindBackground();
}
|
package tk.mybatis.simple.mapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.Test;
import tk.mybatis.simple.model.SysPrivilege;
import tk.mybatis.simple.model.SysRole;
import tk.mybatis.simple.model.SysUser;
import tk.mybatis.simple.type.Enabled;
import java.util.*;
public class UserMapperTest extends BaseMapperTest {
@Test
public void testSelectById(){
//获取 sqlSession
SqlSession sqlSession = getSqlSession();
try {
//获取 UserMapper 接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用 selectById 方法,查询 id = 1 的用户
SysUser user = userMapper.selectById(1l);
//user 不为空
Assert.assertNotNull(user);
//userName = admin
Assert.assertEquals("admin", user.getUserName());
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectAll(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用 selectAll 方法查询所有用户
List<SysUser> userList = userMapper.selectAll();
//结果不为空
Assert.assertNotNull(userList);
//用户数量大于 0 个
Assert.assertTrue(userList.size() > 0);
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectRolesByUserId(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用 selectRolesByUserId 方法查询用户的角色
List<SysRole> roleList = userMapper.selectRolesByUserId(1L);
//结果不为空
Assert.assertNotNull(roleList);
//角色数量大于 0 个
Assert.assertTrue(roleList.size() > 0);
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectRolesByUserIdAndRoleEnabled(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用 selectRolesByUserIdAndRoleEnabled 方法查询用户的角色
List<SysRole> roleList = userMapper.selectRolesByUserIdAndRoleEnabled(1L, null);
//结果不为空
Assert.assertNotNull(roleList);
//角色数量大于 0 个
Assert.assertTrue(roleList.size() > 0);
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectRolesByUserAndRole(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用 selectRolesByUserIdAndRoleEnabled 方法查询用户的角色
SysUser user = new SysUser();
user.setId(1L);
SysRole role = new SysRole();
role.setEnabled(Enabled.enabled);
List<SysRole> userList = userMapper.selectRolesByUserAndRole(user, role);
//结果不为空
Assert.assertNotNull(userList);
//角色数量大于 0 个
Assert.assertTrue(userList.size() > 0);
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testInsert(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//创建一个 user 对象
SysUser user = new SysUser();
user.setUserName("test1");
user.setUserPassword("123456");
user.setUserEmail("test@mybatis.tk");
user.setUserInfo("test info");
//正常情况下应该读入一张图片存到 byte 数组中
user.setHeadImg(new byte[]{1,2,3});
user.setCreateTime(new Date());
//将新建的对象插入数据库中,特别注意,这里的返回值 result 是执行的 SQL 影响的行数
int result = userMapper.insert(user);
//只插入 1 条数据
Assert.assertEquals(1, result);
//id 为 null,我们没有给 id 赋值,并且没有配置回写 id 的值
Assert.assertNull(user.getId());
} finally {
//为了不影响数据库中的数据导致其他测试失败,这里选择回滚
//由于默认的 sqlSessionFactory.openSession() 是不自动提交的,
//因此不手动执行 commit 也不会提交到数据库
sqlSession.rollback();
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testInsert2(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//创建一个 user 对象
SysUser user = new SysUser();
user.setUserName("test1");
user.setUserPassword("123456");
user.setUserEmail("test@mybatis.tk");
user.setUserInfo("test info");
user.setHeadImg(new byte[]{1,2,3});
user.setCreateTime(new Date());
int result = userMapper.insert2(user);
//只插入 1 条数据
Assert.assertEquals(1, result);
//因为 id 回写,所以 id 不为 null
Assert.assertNotNull(user.getId());
} finally {
sqlSession.commit();
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testInsert2Selective(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//创建一个 user 对象
SysUser user = new SysUser();
user.setUserName("test-selective");
user.setUserPassword("123456");
user.setUserInfo("test info");
user.setCreateTime(new Date());
//插入数据库
userMapper.insert2(user);
//获取插入的这条数据
user = userMapper.selectById(user.getId());
Assert.assertEquals("test@mybatis.tk", user.getUserEmail());
} finally {
sqlSession.rollback();
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testUpdateById(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//从数据库查询 1 个 user 对象
SysUser user = userMapper.selectById(1L);
//当前 userName 为 admin
Assert.assertEquals("admin", user.getUserName());
//修改用户名
user.setUserName("admin_test");
//修改邮箱
user.setUserEmail("test@mybatis.tk");
//更新数据,特别注意,这里的返回值 result 是执行的 SQL 影响的行数
int result = userMapper.updateById(user);
//只更新 1 条数据
Assert.assertEquals(1, result);
//根据当前 id 查询修改后的数据
user = userMapper.selectById(1L);
//修改后的名字 admin_test
Assert.assertEquals("admin_test", user.getUserName());
} finally {
//为了不影响数据库中的数据导致其他测试失败,这里选择回滚
//由于默认的 sqlSessionFactory.openSession() 是不自动提交的,
//因此不手动执行 commit 也不会提交到数据库
sqlSession.rollback();
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testDeleteById(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//从数据库查询 1 个 user 对象,根据 id = 1 查询
SysUser user1 = userMapper.selectById(1L);
//现在还能查询出 user 对象
Assert.assertNotNull(user1);
//调用方法删除
Assert.assertEquals(1, userMapper.deleteById(1L));
//再次查询,这时应该没有值,为 null
Assert.assertNull(userMapper.selectById(1L));
//使用 SysUser 参数再做一遍测试,根据 id = 1001 查询
SysUser user2 = userMapper.selectById(1001L);
//现在还能查询出 user 对象
Assert.assertNotNull(user2);
//调用方法删除,注意这里使用参数为 user2
Assert.assertEquals(1, userMapper.deleteById(user2));
//再次查询,这时应该没有值,为 null
Assert.assertNull(userMapper.selectById(1001L));
//使用 SysUser 参数再做一遍测试
} finally {
//为了不影响数据库中的数据导致其他测试失败,这里选择回滚
//由于默认的 sqlSessionFactory.openSession() 是不自动提交的,
//因此不手动执行 commit 也不会提交到数据库
sqlSession.rollback();
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectByUser(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//只查询用户名时
SysUser query = new SysUser();
query.setUserName("ad");
List<SysUser> userList = userMapper.selectByUser(query);
Assert.assertTrue(userList.size() > 0);
//只查询用户邮箱时
query = new SysUser();
query.setUserEmail("test@mybatis.tk");
userList = userMapper.selectByUser(query);
Assert.assertTrue(userList.size() > 0);
//当同时查询用户名和邮箱时
query = new SysUser();
query.setUserName("ad");
query.setUserEmail("test@mybatis.tk");
userList = userMapper.selectByUser(query);
//由于没有同时符合这两个条件的用户,查询结果数为 0
Assert.assertTrue(userList.size() == 0);
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectByIdOrUserName(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//只查询用户名时
SysUser query = new SysUser();
query.setId(1L);
query.setUserName("admin");
SysUser user = userMapper.selectByIdOrUserName(query);
Assert.assertNotNull(user);
//当没有 id 时
query.setId(null);
user = userMapper.selectByIdOrUserName(query);
Assert.assertNotNull(user);
//当 id 和 name 都为空时
query.setUserName(null);
user = userMapper.selectByIdOrUserName(query);
Assert.assertNull(user);
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testUpdateByIdSelective(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//从数据库查询 1 个 user 对象
SysUser user = new SysUser();
//更新 id = 1 的用户
user.setId(1L);
//修改邮箱
user.setUserEmail("test@mybatis.tk");
//将新建的对象插入数据库中,特别注意,这里的返回值 result 是执行的 SQL 影响的行数
int result = userMapper.updateByIdSelective(user);
//只更新 1 条数据
Assert.assertEquals(1, result);
//根据当前 id 查询修改后的数据
user = userMapper.selectById(1L);
//修改后的名字保持不变,但是邮箱变成了新的
Assert.assertEquals("admin", user.getUserName());
Assert.assertEquals("test@mybatis.tk", user.getUserEmail());
} finally {
//为了不影响数据库中的数据导致其他测试失败,这里选择回滚
sqlSession.rollback();
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectByIdList(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<Long> idList = new ArrayList<Long>();
idList.add(1L);
idList.add(1001L);
//业务逻辑中必须校验 idList.size() > 0
List<SysUser> userList = userMapper.selectByIdList(idList);
Assert.assertEquals(2, userList.size());
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testInsertList(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//创建一个 user 对象
List<SysUser> userList = new ArrayList<SysUser>();
for(int i = 0; i < 2; i++){
SysUser user = new SysUser();
user.setUserName("test" + i);
user.setUserPassword("123456");
user.setUserEmail("test@mybatis.tk");
userList.add(user);
}
//将新建的对象批量插入数据库中,特别注意,这里的返回值 result 是执行的 SQL 影响的行数
int result = userMapper.insertList(userList);
Assert.assertEquals(2, result);
for(SysUser user : userList){
System.out.println(user.getId());
}
} finally {
//为了不影响数据库中的数据导致其他测试失败,这里选择回滚
sqlSession.rollback();
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testUpdateByMap(){
SqlSession sqlSession = getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//从数据库查询 1 个 user 对象
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", 1L);
map.put("user_email", "test@mybatis.tk");
map.put("user_password", "12345678");
//更新数据
userMapper.updateByMap(map);
//根据当前 id 查询修改后的数据
SysUser user = userMapper.selectById(1L);
Assert.assertEquals("test@mybatis.tk", user.getUserEmail());
} finally {
//为了不影响数据库中的数据导致其他测试失败,这里选择回滚
sqlSession.rollback();
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectUserAndRoleById(){
//获取 sqlSession
SqlSession sqlSession = getSqlSession();
try {
//获取 UserMapper 接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//特别注意,在我们测试数据中,id = 1L 的用户有两个角色
//由于后面覆盖前面的,因此只能得到最后一个角色
//我们这里使用只有一个角色的用户(id = 1001L)
//可以用 selectUserAndRoleById2 替换进行测试
SysUser user = userMapper.selectUserAndRoleById(1001L);
//user 不为空
Assert.assertNotNull(user);
//user.role 也不为空
Assert.assertNotNull(user.getRole());
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectUserAndRoleByIdSelect(){
//获取 sqlSession
SqlSession sqlSession = getSqlSession();
try {
//获取 UserMapper 接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//特别注意,在我们测试数据中,id = 1L 的用户有两个角色
//由于后面覆盖前面的,因此只能得到最后一个角色
//我们这里使用只有一个角色的用户(id = 1001L)
SysUser user = userMapper.selectUserAndRoleByIdSelect(1001L);
//user 不为空
Assert.assertNotNull(user);
//user.role 也不为空
System.out.println("调用 user.equals(null)");
user.equals(null);
System.out.println("调用 user.getRole()");
Assert.assertNotNull(user.getRole());
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectAllUserAndRoles(){
//获取 sqlSession
SqlSession sqlSession = getSqlSession();
try {
//获取 UserMapper 接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<SysUser> userList = userMapper.selectAllUserAndRoles();
System.out.println("用户数:" + userList.size());
for(SysUser user : userList){
System.out.println("用户名:" + user.getUserName());
for(SysRole role: user.getRoleList()){
System.out.println("角色名:" + role.getRoleName());
for(SysPrivilege privilege : role.getPrivilegeList()){
System.out.println("权限名:" + privilege.getPrivilegeName());
}
}
}
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectAllUserAndRolesSelect(){
//获取 sqlSession
SqlSession sqlSession = getSqlSession();
try {
//获取 UserMapper 接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
SysUser user = userMapper.selectAllUserAndRolesSelect(1L);
System.out.println("用户名:" + user.getUserName());
for(SysRole role: user.getRoleList()){
System.out.println("角色名:" + role.getRoleName());
for(SysPrivilege privilege : role.getPrivilegeList()){
System.out.println("权限名:" + privilege.getPrivilegeName());
}
}
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectUserById(){
//获取 sqlSession
SqlSession sqlSession = getSqlSession();
try {
//获取 UserMapper 接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
SysUser user = new SysUser();
user.setId(1L);
userMapper.selectUserById(user);
Assert.assertNotNull(user.getUserName());
System.out.println("用户名:" + user.getUserName());
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testSelectUserPage(){
//获取 sqlSession
SqlSession sqlSession = getSqlSession();
try {
//获取 UserMapper 接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> params = new HashMap<String, Object>();
params.put("userName", "ad");
params.put("offset", 0);
params.put("limit", 10);
List<SysUser> userList = userMapper.selectUserPage(params);
Long total = (Long) params.get("total");
System.out.println("总数:" + total);
for(SysUser user : userList){
System.out.println("用户名:" + user.getUserName());
}
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
@Test
public void testInsertAndDelete(){
//获取 sqlSession
SqlSession sqlSession = getSqlSession();
try {
//获取 UserMapper 接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
SysUser user = new SysUser();
user.setUserName("test1");
user.setUserPassword("123456");
user.setUserEmail("test@mybatis.tk");
user.setUserInfo("test info");
//正常情况下应该读入一张图片存到 byte 数组中
user.setHeadImg(new byte[]{1,2,3});
//插入数据
userMapper.insertUserAndRoles(user, "1,2");
Assert.assertNotNull(user.getId());
Assert.assertNotNull(user.getCreateTime());
//可以执行下面的 commit 后查看数据库中的数据
//sqlSession.commit();
//测试删除刚刚插入的数据
userMapper.deleteUserById(user.getId());
} finally {
//不要忘记关闭 sqlSession
sqlSession.close();
}
}
}
|
/**
*
*/
package com.lmiky.dubbo.provider.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.container.Container;
import com.alibaba.dubbo.container.spring.SpringContainer;
import com.lmiky.platform.logger.util.LoggerUtils;
/**
* 初始化
* @author lmiky
* @date 2015年9月5日 上午11:00:04
*/
public class InitServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private SpringContainer container;
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#init()
*/
@Override
public void init() throws ServletException {
super.init();
LoggerUtils.info("starting.......");
// new SpringContainer().start();
SpringContainer container = (SpringContainer) ExtensionLoader.getExtensionLoader(Container.class)
.getExtension("spring");
container.start();
LoggerUtils.info("started.......");
}
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#destroy()
*/
@Override
public void destroy() {
super.destroy();
LoggerUtils.info("stoping.......");
container.stop();
LoggerUtils.info("stoped.......");
}
}
|
package designer.ui.editor.element;
import java.awt.*;
/**
* Created by Tomas Hanus on 4/17/2015.
*/
public class EdgeOnValue extends Edge {
private String on;
public EdgeOnValue(Element parent, Element child) {
super(parent, child);
}
public EdgeOnValue(Element parent, Point tmpChildrenPoint) {
super(parent, tmpChildrenPoint);
}
public String getOn() {
return on;
}
public void setOn(String on) {
this.on = on;
}
}
|
package com.asiainfo.fdc.business.tclz;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import jef.database.QB;
import jef.database.query.Query;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.ailk.easyframe.web.common.Page;
import com.asiainfo.fdc.business.BaseBusiness;
import com.asiainfo.fdc.persistence.tclz.FjTclzAllSumDao;
import com.asiainfo.fdc.persistence.tclz.FjUserBillFeeDao;
import com.asiainfo.fdc.persistence.tclz.entity.FjTclzAllSum;
import com.asiainfo.fdc.persistence.tclz.entity.FjUserBillFee;
public class TclzUserBillToSumBusiness extends BaseBusiness implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public FjTclzAllSumDao tclz_fjTclzAllSumDao;
public FjTclzAllSumDao getTclz_fjTclzAllSumDao() {
return tclz_fjTclzAllSumDao;
}
public void setTclz_fjTclzAllSumDao(FjTclzAllSumDao tclz_fjTclzAllSumDao) {
this.tclz_fjTclzAllSumDao = tclz_fjTclzAllSumDao;
}
public List<FjUserBillFee> findUserBillFees(FjUserBillFee fjUserBillFee, int start, int limit) throws Exception {
Query<FjUserBillFee> query = QB.create(FjUserBillFee.class);
query.setAttribute(FjUserBillFee.Field.regionCode.name(), fjUserBillFee.getRegionCode());
query.setAttribute(FjUserBillFee.Field.fiscalPeriod.name(), fjUserBillFee.getFiscalPeriod());
query.addCondition(FjUserBillFee.Field.fiscalPeriod, fjUserBillFee.getFiscalPeriod());
query.addCondition(FjUserBillFee.Field.regionCode, fjUserBillFee.getRegionCode());
query.addOrderBy(true, FjUserBillFee.Field.userId);
// AutoCloseIterator<FjUserBillFee> iterator=
// this.getCommonDao().getClient().iteratedSelect(query,new IntRange(1, 40000), new QueryArg.MyTableName(null));
Page<FjUserBillFee> userBillFees = this.getDao(FjUserBillFeeDao.class).findAndPage(query.getInstance(), start, limit);
return userBillFees.getList();
}
// @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = { RuntimeException.class,
// Exception.class,
// SQLException.class})
public void batchInsert(List<FjUserBillFee> fjUserBillFees) throws Exception {
this.getDao(FjUserBillFeeDao.class).batchInsert(fjUserBillFees);
}
// @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = { RuntimeException.class,
// Exception.class,
// SQLException.class})
public void batchInsertFjTclzAllSum(List<FjTclzAllSum> fjTclzAllSums) throws Exception {
//this.getDao(FjTclzAllSumDao.class).batchInsert(fjTclzAllSums);
tclz_fjTclzAllSumDao.batchInsert(fjTclzAllSums);
}
}
|
package algorithms.tasks;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
import static org.assertj.core.api.Assertions.assertThat;
class QHeap1Test {
private QHeap1 qHeap1;
@BeforeEach
void setUp() {
qHeap1 = new QHeap1();
}
@Test
void case1() {
InputStream inputStream = this.getClass().getResourceAsStream("/qheap1/01.in");
System.setIn(inputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
qHeap1.parse();
compare("/qheap1/01.out", outputStream.toString());
}
@Test
void case2() {
InputStream inputStream = this.getClass().getResourceAsStream("/qheap1/02.in");
System.setIn(inputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
qHeap1.parse();
compare("/qheap1/02.out", outputStream.toString());
}
@Test
void case3() {
InputStream inputStream = this.getClass().getResourceAsStream("/qheap1/03.in");
System.setIn(inputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
qHeap1.parse();
compare("/qheap1/03.out", outputStream.toString());
}
@Test
void case4() {
InputStream inputStream = this.getClass().getResourceAsStream("/qheap1/04.in");
System.setIn(inputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
qHeap1.parse();
compare("/qheap1/04.out", outputStream.toString());
}
private void compare(String expectedFile, String result) {
InputStream inputStream = this.getClass().getResourceAsStream(expectedFile);
Scanner scanner = new Scanner(inputStream);
String expected = "";
while (scanner.hasNext()) {
if (expected.length() > 0) expected = expected + "\r\n";
expected = expected + scanner.nextLine();
}
assertThat(Arrays.asList(result.trim().split("\r\n"))).isEqualTo(
Arrays.asList(expected.trim().split("\r\n")));
}
} |
package Principal;
import Presentacion.MenuInicio;
public class Alimentos {
public static void main(String[] args) {
MenuInicio interfaz = new MenuInicio();
interfaz.setVisible(true);
}
} |
package magical.robot.global;
/**
*
* @author Pavel Rubinson
*
*/
public interface ObjectInfoContainer {
/**
* Set the horizontal location (X axis coordinate) of the object.
* @param location
*/
public void setHorizontalLocation(double location);
/**
* Set the approximate distance from camera, in cm, of the object
* @param dist
*/
public void setDistance(double dist);
/**
* Set the color we are expecting the object to be.
* i.e. the color we are searching for.
* @param color a Color object with the HSV range for the color
*/
public void setColor(Color color);
/**
* Set if the object was found/not found
* @param found True if found, false otherwise
*/
public void setFound(boolean found);
/**
* Set the expected aspect ratio (width/height) of the object
* @param min The minimum expected aspect ratio
* @param max The maximum expected aspect ratio
*/
public void setAspectRatio(double min, double max);
/**
* Set the expected extent ([bounding box area]/[object contour area]) of the object.
* @param min The minimum expected extent
* @param max The maximum expected extent
*/
public void setExtent(double min, double max);
/**
* Check if the object was found/not found
* @return True if found, false otherwise
*/
public boolean getFound();
/**
* Get the horizontal location (X axis coordinates) of the object
* @return
*/
public double getHorizontalLocation();
/**
* Get the approximate distance from camera of the object
* @return approximate distance in cm
*/
public double getDistance();
/**
* Get the expected color of the object
* @return A Color object with an HSV range of the color.
*/
public Color getColor();
/**
* Get the minimum expected aspect ratio (width/height) of the object
* @return
*/
public double getAspectRatioMin();
/**
* Get the maximum expected aspect ratio (width/height) of the object
* @return
*/
public double getAspectRatioMax();
/**
* Get the minimum expected extent ([bounding box area]/[object contour area]) of the object
* @return
*/
public double getExtentMin();
/**
* Get the maximum expected extent ([bounding box area]/[object contour area]) of the object
* @return
*/
public double getExtentMax();
}
|
package my.sheshenya.samplespringdatajdbc;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface MasterRepository extends CrudRepository<Master, Long> {
} |
/*
* 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 ec.edu.ups.clases;
/**
*
* @author LENOVO
*/
public class Materia {
private int codigo;
private String nombre;
private int numeroCreditos;
private int numeroHoras;
private int nivel;
private Grupo grupo;
private Profesor profesor;
public Materia(){
}
public Materia(int codigo, String nombre, int nivel) {
this.codigo = codigo;
this.nombre = nombre;
this.nivel = nivel;
}
public void setCodigo(int codigo){
this.codigo=codigo;
}
public void setNombre(String nombre){
this.nombre=nombre;
}
public void setNumeroHoras(int numeroHoras){
this.numeroHoras=numeroHoras;
}
public void setNumeroCreditos(int numeroCreditos){
this.numeroCreditos=numeroCreditos;
}
public void setNivel(int nivel){
this.nivel=nivel;
}
public void setGrupo(Grupo grupo){
this.grupo=grupo;
}
public void setProfesor(Profesor profesor){
this.profesor=profesor;
}
public int getCodigo(){
return this.codigo;
}
public String getNombre(){
return this.nombre;
}
public int getNumeroHoras(){
return this.numeroHoras;
}
public int getNumeroCreditos(){
return this.numeroCreditos;
}
public int getNivel(){
return this.nivel;
}
public Grupo getGrupo(){
return this.grupo;
}
public Profesor getProfesor(){
return this.profesor;
}
} |
package com.reigens;
import com.badlogic.gdx.Game;
import com.reigens.screens.Splash;
public class MasterWarrior extends Game
{
public static final String TITLE = "Master Warrior";
public static final String VERSION = "0.0.0.2";
@Override
public void create () {
setScreen(new Splash());
}
@Override
public void dispose()
{
super.dispose();
}
@Override
public void render () {
super.render();
}
@Override
public void resize(int width, int height)
{
super.resize(width, height);
}
@Override
public void pause()
{
super.pause();
}
@Override
public void resume()
{
super.resume();
}
}
|
package foo.dbgroup.RDFstruct;
import java.net.UnknownHostException;
import java.util.List;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.logging.MorphiaLoggerFactory;
import com.google.code.morphia.logging.slf4j.SLF4JLogrImplFactory;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import foo.dbgroup.RDFstruct.voidQuery.BuildVoidQuery;
import foo.dbgroup.RDFstruct.voidQuery.QueryExecutorRemote;
import foo.dbgroup.RDFstruct.voidQuery.QueryExecutorRemoteNCBO;
import foo.dbgroup.mongo.dao.DatasetResultDAO;
import foo.dbgroup.mongo.dao.EndpointSparqlDAO;
import foo.dbgroup.mongo.entity.EndPointSparql;
import foo.dbgroup.mongo.entity.GenericQuery;
public class ResultFromSelectedEndpointNCBO {
public static void main(String[] args) {
// TODO Auto-generated method stub
BuildVoidQuery qu=new BuildVoidQuery();
MorphiaLoggerFactory.registerLogger(SLF4JLogrImplFactory.class);
List<GenericQuery> liqu=qu.getVoidQuery();
QueryExecutorRemoteNCBO exe = new QueryExecutorRemoteNCBO();
MongoClient mongoClient;
Mongo mongo= null;
try {
mongo = new Mongo();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mongoClient = new MongoClient( "localhost" );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Morphia morphia = new Morphia();
EndpointSparqlDAO dao = new EndpointSparqlDAO(mongo, morphia);
DatasetResultDAO rDao=new DatasetResultDAO(mongo, morphia);
//*******************************************
EndPointSparql e=dao.findOne("id", 100);
exe.setDataset(e.getUri(),e.getNome());
Datastore ds = morphia.createDatastore(mongo, "RDFstruct");
for (GenericQuery current :liqu ){
exe.setQuery(current);
exe.executeQuery(true);
exe.printResult();
}
// exe.saveToMongo(rDao);
}
}
|
/**
* Copyright 2016-02-15 the original author or authors.
*/
package pl.szkolenie.orders;
import pl.com.softproject.lilu.model.order.Order;
import pl.com.softproject.utils.xml.BaseXMLSerializer;
/**
* @author Adrian Lapierre {@literal <adrian@soft-project.pl>}
*/
public class OrderSerializer extends BaseXMLSerializer<Order> {
public OrderSerializer() {
super("pl.com.softproject.lilu.model.order", "order.xsd", "");
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.k;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.tencent.mm.plugin.appbrand.s$g;
import com.tencent.mm.plugin.appbrand.s.h;
import java.util.ArrayList;
final class b$a extends BaseAdapter {
private final ArrayList<String> fXG;
private final int fXH;
public b$a(ArrayList<String> arrayList, int i) {
this.fXG = arrayList;
this.fXH = i;
}
public final int getCount() {
return this.fXG.size();
}
private String jl(int i) {
return (String) this.fXG.get(i);
}
public final long getItemId(int i) {
return (long) i;
}
public final View getView(int i, View view, ViewGroup viewGroup) {
a aVar;
if (view == null) {
view = View.inflate(viewGroup.getContext(), h.app_brand_show_action_sheet_item, null);
a aVar2 = new a((byte) 0);
aVar2.eGX = (TextView) view.findViewById(s$g.title);
view.setTag(aVar2);
aVar = aVar2;
} else {
aVar = (a) view.getTag();
}
aVar.eGX.setText(jl(i));
aVar.eGX.setTextColor(this.fXH);
return view;
}
}
|
/*********************************************************************
* Este package implementa o container do evento pendente. discreteStochasticSim tambem oferece uma interface caso outros pecs
* sejam necessarios.
*
* @author Grupo 11
*
*********************************************************************/
package discreteStochaticSim; |
package com.espendwise.manta.util.parser;
import org.apache.log4j.Logger;
import java.util.Date;
public class AppParserFactory {
private static final Logger logger = Logger.getLogger(AppParserFactory.class);
public static <T> AppParser<T> getParser(Class<T> type) {
if (Integer.class.isAssignableFrom(type)) {
return (AppParser<T>) getIntegerParser();
} else if (Long.class.isAssignableFrom(type)) {
return (AppParser<T>) getLongParser();
} else if (Date.class.isAssignableFrom(type)) {
return (AppParser<T>) getDateParser();
} else if (Double.class.isAssignableFrom(type)) {
return (AppParser<T>) getDoubleParser();
}
return null;
}
public static MonthWithDayParser getMonthWithDayParser() {
return new MonthWithDayParser();
}
public static DateParser getDateParser() {
return new DateParser();
}
public static LongParser getLongParser() {
return new LongParser();
}
public static DoubleParser getDoubleParser() {
return new DoubleParser();
}
public static IntegerParser getIntegerParser() {
return new IntegerParser();
}
public static PercentParserInt getPercentParserInt() {
return new PercentParserInt();
}
public static AmountParser getAmountParser() {
return new AmountParser();
}
}
|
package com.registered;
public class RegisteredDTO {
private String member_name;
private String registered_date;
private String id;
private int listNum;
public String getMember_name() {
return member_name;
}
public void setMember_name(String member_name) {
this.member_name = member_name;
}
public String getRegistered_date() {
return registered_date;
}
public void setRegistered_date(String registered_date) {
this.registered_date = registered_date;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getListNum() {
return listNum;
}
public void setListNum(int listNum) {
this.listNum = listNum;
}
}
|
public class Person {
private String firstName;
private String lastName;
/**
* Constructor for Person
*
* @param firstName First name
* @param lastName Last name
*/
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
/**
* Getter for first name
*
* @return First name
*/
public String getFirstName() {
return firstName;
}
/**
* Getter for last name
*
* @return Last name
*/
public String getLastName() {
return lastName;
}
/**
* Override toString function and print person's specific
*
* @return Person's specific
*/
@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
|
package superintendent.features.wiki.links;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import superintendent.apis.common.Listener;
import superintendent.apis.common.events.CreateEvent;
import superintendent.apis.discord.DiscordMessage;
import superintendent.apis.discord.InsufficientPermissionsException;
public class WikiLinkListener implements Listener<CreateEvent<DiscordMessage>> {
private static final Map<String, SupportedWiki> wikis;
private static final List<LinkType> linkTypes;
static {
Map<String, SupportedWiki> map = new HashMap<>();
for (SupportedWiki wiki : SupportedWikis.values()) {
if (!wiki.equals(SupportedWikis.DEFAULT)) {
map.put(wiki.getPrefix(), wiki);
}
}
wikis = Collections.unmodifiableMap(map);
linkTypes = Arrays.asList(LinkTypes.values());
}
@Override
public void heard(CreateEvent<DiscordMessage> event) {
String text = event.getTrigger().getText();
Map<LinkType, List<String>> linkMap = new HashMap<>();
for (LinkType type : linkTypes) {
List<String> links = getLinks(text, type)
.stream()
.map(l -> generateUrl(l, type))
.collect(Collectors.toList());
if (!links.isEmpty()) {
linkMap.put(type, links);
}
}
if (!linkMap.isEmpty()) {
try {
event.getTrigger().getChannel().post(generateMessage(linkMap));
} catch (InsufficientPermissionsException e) {
// No error correction needed here - it just means the bot didn't have
// the right permissions
}
}
}
private List<String> getLinks(String text, LinkType type) {
List<String> result = new ArrayList<>();
Matcher matcher = Pattern.compile(type.getSearchRegex()).matcher(text);
while (matcher.find()) {
result.add(matcher.group().replaceAll(type.getCleanupRegex(), ""));
}
return result;
}
private String generateUrl(String link, LinkType type) {
StringBuilder url = new StringBuilder();
SupportedWiki wiki = SupportedWikis.DEFAULT;
for (String prefix : wikis.keySet()) {
if (link.toLowerCase().startsWith(prefix.toLowerCase())) {
wiki = wikis.get(prefix);
break;
}
}
url.append(wiki.getBaseUrl());
link = link.substring(wiki.getPrefix().length());
if (!(link.matches("[^:]*:.*") || type.getDefaultNamespace().equals(""))) {
url.append(type.getDefaultNamespace());
url.append(':');
} else if (link.startsWith(":")) {
link = link.substring(1);
}
url.append(link.replaceAll("\\p{Space}", "_"));
return url.toString();
}
private String generateMessage(Map<LinkType, List<String>> links) {
StringBuilder message = new StringBuilder();
for (LinkType type : links.keySet()) {
if (links.get(type).isEmpty()) {
continue;
}
message.append("**");
message.append(type.getName());
message.append(" links detected!**\n\n");
for (String link : links.get(type)) {
message.append('*');
message.append(link);
message.append('*');
message.append('\n');
}
message.append('\n');
}
return message.toString();
}
} |
package main.model;
/**
* Created by gijin on 2017-12-06.
*/
public class Character {
public enum CharacterName {
DANNING,
ALEXIA,
FELICITY,
AMY,
WANLIN,
DALE,
DONNY,
ED,
WILLIAM
} // do Character or name?
// include information about each character
private String pathToCharacter;
private String displayName;
private
}
|
/*
* generated by Xtext
*/
package org.eclipselabs.spray.shapes.formatting;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.xtext.Keyword;
import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter;
import org.eclipse.xtext.formatting.impl.FormattingConfig;
import org.eclipse.xtext.util.Pair;
import org.eclipselabs.spray.shapes.services.ShapeGrammarAccess;
import javax.inject.Inject;
/**
* This class contains custom formatting description.
* see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#formatting
* on how and when to use it
* Also see {@link org.eclipse.xtext.xtext.XtextFormattingTokenSerializer} as an
* example
*/
public class ShapeFormatter extends AbstractDeclarativeFormatter {
@Inject
private ShapeGrammarAccess grammar;
@Override
protected void configureFormatting(FormattingConfig c) {
c.setLinewrap(0, 1, 2).before(grammar.getSL_COMMENTRule());
c.setLinewrap(0, 1, 2).before(grammar.getML_COMMENTRule());
c.setLinewrap(0, 1, 1).after(grammar.getML_COMMENTRule());
c.setAutoLinewrap(120);
handleBlocks(c);
List<Keyword> bracketsToIgnore = new ArrayList<Keyword>();
bracketsToIgnore.add(grammar.getHighlightingValuesAccess().getLeftParenthesisKeyword_1());
bracketsToIgnore.add(grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_1());
bracketsToIgnore.add(grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_2_1_1());
for (Pair<Keyword, Keyword> kw : grammar.findKeywordPairs("(", ")")) {
if(!bracketsToIgnore.contains(kw.getFirst())) {
c.setSpace(" ").before(kw.getFirst());
c.setNoSpace().after(kw.getFirst());
c.setNoSpace().before(kw.getSecond());
}
}
// no space around =, except for text value assignment
for (Keyword kw : grammar.findKeywords("=")) {
if (kw == grammar.getTextBodyAccess().getEqualsSignKeyword_2()) {
c.setSpace(" ").around(kw);
} else {
c.setNoSpace().around(kw);
}
}
c.setSpace(" ").around(grammar.getCompartmentInfoAccess().getEqualsSignKeyword_2_0_1());
List<Keyword> commasToIgnore = new ArrayList<Keyword>();
commasToIgnore.add(grammar.getCompartmentInfoAccess().getCommaKeyword_2_1_5());
// no space befor comma, one space after
for (Keyword kw : grammar.findKeywords(",")) {
if(!commasToIgnore.contains(kw)) {
c.setNoSpace().before(kw);
c.setSpace(" ").after(kw);
}
}
c.setNoSpace().before(grammar.getCompartmentInfoAccess().getCommaKeyword_2_1_5());
c.setLinewrap().after(grammar.getCompartmentInfoAccess().getCommaKeyword_2_1_5());
handleNoSpaceBeforeINT(c);
handleLineWrapBeforeKeywords(c);
c.setLinewrap(2).between(grammar.getShapeDefinitionRule(), grammar.getShapeDefinitionRule());
c.setLinewrap(2).between(grammar.getConnectionDefinitionRule(), grammar.getConnectionDefinitionRule());
c.setLinewrap(2).between(grammar.getConnectionDefinitionRule(), grammar.getShapeDefinitionRule());
c.setLinewrap(2).between(grammar.getShapeDefinitionRule(), grammar.getConnectionDefinitionRule());
c.setIndentation(
grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_1(),
grammar.getCompartmentInfoAccess().getRightParenthesisKeyword_3()
);
c.setLinewrap().after(grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_1());
c.setLinewrap().around(grammar.getCompartmentInfoAccess().getRightParenthesisKeyword_3());
c.setLinewrap().after(grammar.getHighlightingValuesAccess().getLeftParenthesisKeyword_1());
c.setLinewrap().around(grammar.getHighlightingValuesAccess().getRightParenthesisKeyword_6());
c.setLinewrap().around(grammar.getHighlightingValuesAccess().getSelectedAssignment_2_2());
c.setLinewrap().around(grammar.getHighlightingValuesAccess().getMultiselectedAssignment_3_2());
c.setLinewrap().around(grammar.getHighlightingValuesAccess().getAllowedAssignment_4_2());
c.setLinewrap().around(grammar.getHighlightingValuesAccess().getUnallowedAssignment_5_2());
c.setIndentation(
grammar.getHighlightingValuesAccess().getLeftParenthesisKeyword_1(),
grammar.getHighlightingValuesAccess().getRightParenthesisKeyword_6()
);
c.setLinewrap().after(grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_2_1_1());
c.setLinewrap().around(grammar.getCompartmentInfoAccess().getRightParenthesisKeyword_2_1_9());
c.setLinewrap().around(grammar.getCompartmentInfoAccess().getStretchHAssignment_2_1_4());
c.setLinewrap().around(grammar.getCompartmentInfoAccess().getStretchVAssignment_2_1_8());
c.setIndentation(
grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_2_1_1(),
grammar.getCompartmentInfoAccess().getRightParenthesisKeyword_2_1_9()
);
c.setLinewrap().around(grammar.getCommonLayoutRule());
}
protected void handleLineWrapBeforeKeywords(FormattingConfig c) {
// line wraps
c.setLinewrap().before(grammar.getShapeRule());
c.setLinewrap().before(grammar.getShapeConnectionRule());
c.setLinewrap().before(grammar.getPointRule());
c.setLinewrap().before(grammar.getPlacingDefinitionAccess().getPlacingKeyword_0());
c.setLinewrap().before(grammar.getAnchorPositionRule());
c.setLinewrap().before(grammar.getCommonLayoutAccess().getPositionKeyword_1_0_0());
c.setLinewrap().before(grammar.getCommonLayoutAccess().getSizeKeyword_1_1_0());
c.setLinewrap().before(grammar.getRoundedRectangleLayoutAccess().getCurveKeyword_1_1_0());
c.setLinewrap().before(grammar.getTextLayoutAccess().getAlignKeyword_1_1_0());
c.setLinewrap().before(grammar.getTextBodyAccess().getIdKeyword_1());
c.setLinewrap().before(grammar.getShapestyleLayoutAccess().getStyleKeyword_1_0());
for (Keyword kw : grammar.findKeywords("line", "ellipse", "rectangle", "rounded-rectangle",
"polyline", "polygon", "text", "description", "align", "id", "compartment",
"layout", "invisible", "stretching", "margin", "spacing", "vertical")) {
c.setLinewrap().before(kw);
}
c.setLinewrap().before(grammar.getCDTextRule());
}
protected void handleNoSpaceBeforeINT(FormattingConfig c) {
// no space before integers
c.setNoSpace().before(grammar.getCommonLayoutAccess().getXcorN_INTParserRuleCall_1_0_4_0());
c.setNoSpace().before(grammar.getCommonLayoutAccess().getYcorN_INTParserRuleCall_1_0_8_0());
c.setNoSpace().before(grammar.getPointAccess().getXcorN_INTParserRuleCall_1_4_0());
c.setNoSpace().before(grammar.getPointAccess().getYcorN_INTParserRuleCall_1_8_0());
c.setNoSpace().before(grammar.getAnchorFixPointPositionAccess().getXcorINTTerminalRuleCall_2_0());
c.setNoSpace().before(grammar.getAnchorFixPointPositionAccess().getYcorINTTerminalRuleCall_6_0());
}
protected void handleBlocks(FormattingConfig c) {
for (Pair<Keyword, Keyword> kw : grammar.findKeywordPairs("{", "}")) {
c.setLinewrap().after(kw.getFirst());
c.setLinewrap().around(kw.getSecond());
c.setIndentation(kw.getFirst(), kw.getSecond());
}
}
}
|
import org.junit.*;
import static org.junit.Assert.*;
public class LibraryTest {
private Library library;
@Before
public void buildUp() {
library = new LibraryImpl("British Library");
}
@Test
public void testsGetName() {
String output = library.getName();
String expected = "British Library";
assertEquals(expected, output);
}
@Test
public void testsMaxBooks() {
int input = 3;
library.setMaxBooksPerUser(input);
int output = library.getMaxBooksPerUser();
int expected = input;
assertEquals(expected, output);
}
@Test
public void testsNegativeMaxBooks() {
int input = -3;
library.setMaxBooksPerUser(input);
int output = library.getMaxBooksPerUser();
int expected = 0;
assertEquals(expected, output);
}
@Test
public void testsGetID() {
User user1 = new UserImpl("John Smith");
user1.register(library);
int output = library.getID(user1.getName());
int expected = 0;
assertEquals(expected, output);
// once set, ID should remain the same
output = library.getID(user1.getName());
assertEquals(expected, output);
// new user should get unique ID
User user2 = new UserImpl("Janet Bobbins");
user2.register(library);
output = library.getID(user2.getName());
expected = 1;
assertEquals(expected, output);
// once set, ID should remain the same
output = library.getID(user1.getName());
expected = 0;
assertEquals(expected, output);
// once set, ID should remain the same
expected = 1;
output = library.getID(user2.getName());
assertEquals(expected, output);
}
@Test
public void testsGetLoadsOfIDs() {
User user;
for (int i = 0; i < 500; i++) {
String name = "John Smith" + i;
user = new UserImpl(name);
user.register(library);
user.getID();
}
int output = library.getID("John Smith499");
int expected = 499;
assertEquals(expected, output);
}
}
|
import java.util.*;
class Array2D{
public static void main(String args[]){
System.out.println("Enter array size");
int n,i,j;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
int arr[][];
arr= new int[n][n];
//int arr= new int[n];
for(i=0;i<n;i++){
for(j=0;j<n;j++){
System.out.println("Enter element");
arr[i][j]=sc.nextInt();
}
}
System.out.println("Your array is");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
System.out.println(arr[i][j]);
}
}
}
}
|
package com.TestCases;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.GenericMethods.GenericMethods;
import cucumber.api.DataTable;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class Tc_01_DressessPageopen extends GenericMethods{
public static boolean stepstatus;
@Given("Launch the firefox browser")
public static void launchBrowser(DataTable data)
{
List<List<String>> url= data.raw();
stepstatus = GenericMethods.launchBrowser("ff", url.get(0).get(0));
}
@When("click on dresses option and text should display")
public static void navigatetodressespage()
{
//click on dresses page and display text in dresses page
WebElement ele = driver.findElement(By.xpath("//div[@id='block_top_menu']/ul/li[2]/a[text()='Dresses']"));
stepstatus= GenericMethods.hoverAndClick(ele);
if(stepstatus)
{
String pagetext = driver.findElement(By.xpath("//div[@id='categories_block_left']/h2")).getText();
if(pagetext.equalsIgnoreCase("Dresses"))
System.out.println("\n"+ "Dresses page is displyed");
}
}
/*driver.findElement(By.linkText("DRESSES")).click();
boolean status = true;
if(status)
{
System.out.println("Dresses page is clicked");
}
else{
System.out.println("Dresses page is not clicked");
}
//stepstatus = GenericMethods.imagesdisplay();
//stepstatus = GenericMethods.linksdisplay();
//stepstatus = GenericMethods.checkboxes();
} */
/*@Then("verify dresses page text displayed")
public static void DressesPageDis() {
driver.findElement(By.xpath("//span[@class='category-name']")).isDisplayed();
boolean status = true;
if(status)
{
System.out.println("Dresses page is displayed");
}
else{
System.out.println("Dresses page is not displayed");
}*/
}
|
package com.kindy.dao;
import java.util.List;
import com.kindy.domain.QueryCondition;
import com.kindy.domain.Task;
public interface DailyTaskDao {
public List<Task> getTodayTaskList();
public boolean addNewDailyTask(Task task);
public boolean updateTodayDailyTask(Task task);
public List<Task> getTaskListByCondition(QueryCondition condition);
}
|
package business;
import java.io.Serializable;
import java.util.Date;
/**
* Created by wierz on 2016/4/20.
*/
public class PerformanceADBean implements Serializable {
private int employeeID;
private String name;
private String department;
private String rank;
private Date date;
private String performance;
public int getEmployeeID() {
return employeeID;
}
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getPerformance() {
return performance;
}
public void setPerformance(String performance) {
this.performance = performance;
}
}
|
package com.codegym.cms.controller;
import com.codegym.cms.model.Customer;
import com.codegym.cms.model.Province;
import com.codegym.cms.repository.CustomerRepository;
import com.codegym.cms.service.CustomerService;
import com.codegym.cms.service.ProvinceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ProvinceController {
@Autowired
private ProvinceService provinceService;
@Autowired
private CustomerService customerService;
@GetMapping("/provinces")
public ModelAndView listProvinces(){
Iterable<Province> provinces = provinceService.findAll();
ModelAndView modelAndView = new ModelAndView("/province/list");
modelAndView.addObject("provinces", provinces);
return modelAndView;
}
@GetMapping("/create-province")
public ModelAndView showCreateForm(){
ModelAndView modelAndView = new ModelAndView("/province/create");
modelAndView.addObject("province", new Province());
return modelAndView;
}
@PostMapping("/create-province")
public ModelAndView saveProvince(@ModelAttribute("province") Province province){
provinceService.save(province);
ModelAndView modelAndView = new ModelAndView("/province/create");
modelAndView.addObject("province", new Province());
modelAndView.addObject("message", "New province created successfully");
return modelAndView;
}
@GetMapping("/edit-province/{id}")
public ModelAndView showEditForm(@PathVariable Long id){
Province province = provinceService.findById(id);
if(province != null) {
ModelAndView modelAndView = new ModelAndView("/province/edit");
modelAndView.addObject("province", province);
return modelAndView;
}else {
ModelAndView modelAndView = new ModelAndView("/error.404");
return modelAndView;
}
}
@PostMapping("/edit-province")
public ModelAndView updateProvince(@ModelAttribute("province") Province province){
provinceService.save(province);
ModelAndView modelAndView = new ModelAndView("/province/edit");
modelAndView.addObject("province", province);
modelAndView.addObject("message", "Province updated successfully");
return modelAndView;
}
@GetMapping("/delete-province/{id}")
public ModelAndView showDeleteForm(@PathVariable Long id){
Province province = provinceService.findById(id);
if(province != null) {
ModelAndView modelAndView = new ModelAndView("/province/delete");
modelAndView.addObject("province", province);
return modelAndView;
}else {
ModelAndView modelAndView = new ModelAndView("/error.404");
return modelAndView;
}
}
@PostMapping("/delete-province")
public String deleteProvince(@ModelAttribute("province") Province province){
provinceService.remove(province.getId());
return "redirect:provinces";
}
@GetMapping("/view-province/{id}")
public ModelAndView viewProvince(@PathVariable("id") Long id){
Province province = provinceService.findById(id);
if(province == null){
return new ModelAndView("/error.404");
}
Iterable<Customer> customers = customerService.findAllByProvince(province);
ModelAndView modelAndView = new ModelAndView("/province/view");
modelAndView.addObject("province", province);
modelAndView.addObject("customers", customers);
return modelAndView;
}
}
|
package de.jmda.home.ui.vaadin.usermgmt;
import javax.ejb.EJB;
import org.vaadin.virkki.cdiutils.application.UIContext.UIScoped;
import de.jmda.cbo.user.User;
import de.jmda.common.ui.web.vaadin.service.DefaultSessionContext;
import de.jmda.home.bl.usermgmt.UserManagementBean;
@UIScoped // virkii version
public class AuthenticatorDB implements Authenticator
{
/**
* TODO make use of CDI as soon as possible
*/
@EJB
private UserManagementBean userManagement =
DefaultSessionContext.get().getUserManagement();
@Override
public String authenticate(String username, String password)
{
User user = userManagement.findUserByUsername(username);
if (user == null)
{
return
userManagement.findRegistrationRequestUsernameByUsernameRegistrationCode(
username, password);
}
return user.getUsername();
}
} |
package pt.ist.sonet.service;
import java.util.List;
import pt.ist.sonet.service.*;
import pt.ist.sonet.service.dto.*;
import pt.ist.sonet.domain.*;
import pt.ist.sonet.exception.*;
import jvstm.Atomic;
import pt.ist.fenixframework.pstm.Transaction;
public class ObtainAgentPublicationTest extends SonetServiceTestCase {
private static String EXISTING_INDIVIDUAL_USERNAME = "Fonfas";
private static String EXISTING_INDIVIDUAL_USERNAME2 = "Zezinho";
private static String NON_EXISTING_INDIVIDUAL_USERNAME = "Benny";
private static String EXISTING_ORGANIZATION_NAME = "IST";
private static String NON_EXISTING_ORGANIZATION_NAME = "IST-LEIC";
public ObtainAgentPublicationTest(String msg) {
super(msg);
}
public ObtainAgentPublicationTest() {
super();
}
@Override
public void setUp() {
super.setUp();
super.addOrganization("istleic", EXISTING_ORGANIZATION_NAME, "ist@email",
"Lisboa", "Portugal", "password");
super.addOrganization("ist", NON_EXISTING_ORGANIZATION_NAME, "ist@email",
"Lisboa", "Portugal", "password");
super.addIndividual(EXISTING_INDIVIDUAL_USERNAME,"Afonso", "Afonso@email", "Porto", "Portugal", "pass");
super.addIndividual(EXISTING_INDIVIDUAL_USERNAME2,"Ze", "Ze@email", "Porto", "Portugal", "pass");
Agent istleic = returnAgentByName(EXISTING_ORGANIZATION_NAME);
Agent zezinho = returnAgentByUsername(EXISTING_INDIVIDUAL_USERNAME2);
super.addPubNote(istleic, 2, "Publicacao Note Teste IST-LEIC");
super.addPubUrl(zezinho, 3, "Publicacao URL 1 Teste zezinho", 0);
super.addPubUrl(zezinho, 4, "Publicacao URL 2 Teste zezinho", 0);
}
public void testObtainExistentPublicationNoteFromOrganization() {
// Arrange
OrganizationDto orgExistingNameDto = new OrganizationDto("istleic",
EXISTING_ORGANIZATION_NAME, "ist@email", "Lisboa",
"Portugal", "password");
ObtainPublicationsService PublicationService = new ObtainPublicationsService(
orgExistingNameDto, orgExistingNameDto);
// Act
try {
PublicationService.execute();
} catch (AgentNotFoundException e) {
System.out.println("------------[TEST FAIL] FOR AgentNotFoundException!");
}
// Assert
assertEquals("List of publications should have 1 element", 1, PublicationService.getPublications().size());
assertEquals("Publications should have same ID", 2 , PublicationService.getPublications().get(0).getId());
}
public void testObtainInexistentPublicationFromIndividual() {
// Arrange
IndividualDto indExistingNameDto = new IndividualDto(EXISTING_INDIVIDUAL_USERNAME,"Afonso", "Afonso@email", "Porto", "Portugal", "pass");
ObtainPublicationsService PublicationService = new ObtainPublicationsService(indExistingNameDto, indExistingNameDto);
// Act
try {
PublicationService.execute();
} catch (AgentNotFoundException e) {
System.out.println("------------[TEST FAIL] FOR AgentNotFoundException!");
}
// Assert
assertEquals("List of publications should be empty", 0, PublicationService.getPublications().size());
}
public void testObtainPublicationFromInexistentAgent() {
// Arrange
IndividualDto indInexistentNameDto = new IndividualDto(NON_EXISTING_INDIVIDUAL_USERNAME,"Bernardo", "Bernardo@email", "Porto", "Portugal", "pass");
ObtainPublicationsService PublicationService = new ObtainPublicationsService(indInexistentNameDto, indInexistentNameDto);
// Act
try {
PublicationService.execute();
} catch (AgentNotFoundException e) {
System.out.println("------------[TEST] AgentNotFoundException CATCHED! :D");
}
}
public void testObtainExistentPublicationNoteFromIndividual() {
// Arrange
IndividualDto indExistingNameDto = new IndividualDto(EXISTING_INDIVIDUAL_USERNAME2,"Ze", "Ze@email", "Porto", "Portugal", "pass");
ObtainPublicationsService PublicationService = new ObtainPublicationsService(
indExistingNameDto, indExistingNameDto);
// Act
try {
PublicationService.execute();
} catch (AgentNotFoundException e) {
System.out.println("------------[TEST FAIL] FOR AgentNotFoundException!");
}
// Assert
assertEquals("List of publications should have 2 elements", 2, PublicationService.getPublications().size());
assertEquals("Publication 1 should have ID 3", 4 , PublicationService.getPublications().get(0).getId());
assertEquals("Publication 2 should have ID 4", 3 , PublicationService.getPublications().get(1).getId());
}
}
|
package com.zlzkj.app.mapper.index;
import com.zlzkj.app.model.index.Role;
import com.zlzkj.core.sql.Row;
import java.util.List;
import java.util.Map;
public interface RoleMapper {
int deleteByPrimaryKey(String id);
int deleteAdminByPrimaryKey(String id);
int insert(Role record);
Role selectByPrimaryKey(String id);
int updateByPrimaryKey(Role record);
List<Row> selectByMap(Map<String, Object> map);
int countByMap(Map<String, Object> map);
List<Row> selectByTenant_id(String Tenant_id);
} |
package com.scnuweb.domain;
/**
*
* @author yehao
* @date 2016年2月16日
* @comment 用来包装button,select,input的类
*/
public class Item {
public static final String ITEM_BUTTON = "button";
public static final String ITEM_SELECT = "select";
public static final String ITEM_INPUT = "input";
private String type;
private Button button;
private Input input;
private Select select;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Button getButton() {
return button;
}
public void setButton(Button button) {
this.button = button;
}
public Input getInput() {
return input;
}
public void setInput(Input input) {
this.input = input;
}
public Select getSelect() {
return select;
}
public void setSelect(Select select) {
this.select = select;
}
}
|
package com.catnap.core.util;
import static org.junit.Assert.*;
import org.junit.Test;
import java.beans.PropertyDescriptor;
import java.util.Date;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
*
* @author gwhit7
*/
public class ClassUtilTest
{
static abstract class BaseMockModel
{
private String baseProperty = "basePropertyValue";
public String getBaseProperty() { return baseProperty; }
public void setBaseProperty(String baseProperty) { this.baseProperty = baseProperty; }
}
static class MockModel extends BaseMockModel
{
private String property = "propertyValue";
private String unreadableProperty = "unreadablePropertyValue";
public String getProperty() { return property; }
public void setProperty(String property) { this.property = property; }
}
@Test
public void nullIsNotPrimitive()
{
assertFalse(ClassUtil.isPrimitiveType(null));
}
@Test
public void booleanIsPrimitive()
{
assertTrue(ClassUtil.isPrimitiveType(boolean.class));
}
@Test
public void stringIsPrimitive()
{
assertTrue(ClassUtil.isPrimitiveType(String.class));
}
@Test
public void numberIsPrimitive()
{
assertTrue(ClassUtil.isPrimitiveType(Number.class));
}
@Test
public void characterIsPrimitive()
{
assertTrue(ClassUtil.isPrimitiveType(Character.class));
}
@Test
public void dateIsPrimitive()
{
//Date is considered a primitive type according to Catnap, even though it is not.
assertTrue(ClassUtil.isPrimitiveType(Date.class));
}
@Test
public void getAllReadablePropertiesAsMap()
{
Map<String, PropertyDescriptor> props = ClassUtil.getReadablePropertiesAsMap(MockModel.class);
assertEquals(2, props.size());
assertTrue(props.containsKey("baseProperty"));
assertTrue(props.containsKey("property"));
}
@Test
public void getReadableProperty()
{
PropertyDescriptor descriptor = ClassUtil.getReadableProperty("property", MockModel.class);
assertEquals("property", descriptor.getName());
}
@Test
public void getReadablePropertyForUnknownPropertyReturnsNull()
{
assertNull(ClassUtil.getReadableProperty("invalidProperty", MockModel.class));
}
@Test
public void loadingNullInstanceOfClassReturnsNull()
{
assertNull(ClassUtil.loadClass(null));
}
@Test
public void loadClass()
{
assertTrue(ClassUtil.loadClass(new Boolean(true)).isAssignableFrom(Boolean.class));
}
}
|
一、html
由标签组成
1、简介
1.1、html是什么?
Html是用来描述网页的一种语言。
HTML 指的是超文本标记语言 (Hyper Text Markup Language)
HTML 不是一种编程语言,而是一种标记语言 (markup language)
html 标记语言是一套标记标签 (markup tag)
HTML 使用标记标签来描述网页"
1.2、超文本 标记 语言
超文本:
笔普通文本强大,但是超越了普通文本的范畴,普通文本不能实现的超文本都能实现,包含超链接的文本
标记:
就是标签,不同的标签会实现不同的功能
语言:
人与计算机交互的工具
1.3、html能做什么
html可以编写网页,把信息展示给我们
1.4、书写规范
(1) 良好的结构,以html作为根标签,包裹着head和body
(2) html标签是以尖括号包括关键字成对出现的,有开始标签有结束标签,能支持正确的嵌套
(3) 大部分标签有属性 格式:属性="属性值"多个属性之间使用空格隔开
(4) 空标签 功能比较单一 不需要含有标签体 <br></br> == <br/>
(5) html不区分大小写 但是建议写成小写
需求:
写一段文字,将其中部分文字改变颜色改变字号
例如:
<html>
<head></head>
<body>
我请大家<font color="red" size="5">吃饭</font>,大家很高兴,<br/>所以大家没人给了我一百块钱
</body>
</html>
2、基本标签
2.1、文件标签(结构标签)
<html>:就是一个根标签
<head>:写一些资讯信息
页面的整体属性标签:<title>页面的标题
指导解析器解析html的标签:<meta http-equiv="content-type" content="text/html; charset=UTF-8">
引入外部文件的标签:<link rel="stylesheet" type="text/css" href="styles.css">
seo的搜索优化:<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<body>:写一些需要展示的内容和标签
属性:
text: body中的文本的颜色
bgcolor: body的背景颜色
background: 背景图片
2.2、排版标签
换行标签:<br/>
段落标签:<p>文本内容</p>
特点:段誉段之间有空行
属性:
align:对齐方式
取值:left(默认值)/center/rigth
2.3、水平线标签
<hr/>:产生一条水平线
属性:
width:长度(默认占父标签的100%)
size:高度(粗细)
color:颜色
align:对齐方式
取值:left/center(默认值)/rigth
颜色和长度的写法:
颜色:
英文单词:red、green、pink等
rgb写法:rgb(0,0,0),数字的范围0~255
16进制写法(开发中常用):#000000 #ffffff
注意:
使用工具来识别颜色
长度:
像素的写法:300px(默认)
百分比写法:50%(父标签的百分比)
两者的区别:
百分比会随着父标签的变化而变化,
像素写法始终占固定的比例
2.4、注释标签:
<!-- -->
2.5、块标签
<div>:行级块标签(自动换行)
属性:align
取值:left(默认值)、center、right
作用:用于div+css布局
<span>:行内块标签(正行)
作用:例如:注册页面的有好提示
2.6、文字标签
基本文字标签:<font>
属性:
color:颜色
size:字体大小
最大:7号
最小:1号
默认:3号
face:文字类型(宋体、微软雅黑等等)
2.7、标题标签:<h1>-<h6>
特点:
依次减小
占据一行
有内置的字号
自动加粗
标题标签作用:
书写页面的标题
2.8、清单标签(列表标签)
无序标签:<ul>--<li>
ul属性:type
取值:
disc:(默认值)
square:实心方块
circle:空心圆点
有序标签
<ol>--<li>
ol属性:
type:表示列表前的顺序标志
取值:A、I、a、i、1(默认值)
start:从哪个位置开始
取值:数字
清单标签的作用:
实现横向和纵向的菜单
生成简单列表
2.9、图像标签:<img/>
属性:
scr:指定图片路径
alt:图片的文字说明(在图片未加载或加载失败或将鼠标放在图像上时用于显示的文字)
width:长度
heigth:宽度
border:边框
align:对齐方式
取值:
left:左对齐
rigth:右对齐
center:失效
以下三个取值的作用是指相邻的文字相对于图片的位置
top:文字在图片的上面
bottom:文字在图片的下面
middle:文字在图片右边
1.10、链接标签:<a></a>
<a>显示的内容(也可以是图片)</a>
属性:
href:跳转的地址
name:名称(锚点)
例如:
在页面顶端:<a name="top"></a>
在页面底部:<a href="#top">置顶</a>
target:控制是否开启新页
取值:
_self(默认值):在当前页打开
_blank:在新的页面打开
其他功能:
在框架标签<frameset>时使用,在指定的区域块中打开
1.11、表格标签
表格标签:<table></table>
属性:
border:边框
width:表格的长度
align:对齐方式
bgcolor:背景颜色
<tr>:代表表格中的行
align:对齐方式
bgcolo:背景颜色
<td>:代表行中的单元格
属性:
rowspan:行合并
cols:列合并
<th>:代表表头,默认样式居中、加粗
<caption>:代表表格标题
作用:
1、单纯的做表格
2、做网页的布局
1.12、上午练习bookstore
详见bookstoredemo.html
3、表单标签
<form>:仅仅声明这是一个表单
属性:
action:提交的url的地址
name:表单名称
method:提交方式
取值:
POST:将数据封装到http请求的请求体中进行提交
GET(默认值):将数据显示到地址栏进行提交
POST/GET提交的区别:
1、get数据显示在地址栏上,而post不显示
2、get提交相对不安全,而post提交相对安全
3、get提交有大小限制,一句浏览器的不同而不同
post没有大小限制(例如上传图片)
<input>:输入框
属性:
value:input标签的默认值
checked="checked":默认选中其中一个
name:表单项的名称
type:值不同代表的功能不同
取值:
text:普通的输入框
password:密码输入框,输入的内容不可见
radio:单选按钮(例如男/女)
checked="checked"、默认选中其中一个
注意:name值必须一致,才能成为一组互斥
checkbox:多选按钮
checked="checked"、默认选中其中一个
注意:name值必须一致,才能成为一组互斥
file:文件上传
submit:提交按钮
reset:重置按钮,点击的时候恢复默认值
button:普通按钮
image:图片按钮
src:必须包含一个src属性,指定按钮图片的路径
功能:与submit是一样的
hidden:隐藏域
作用:服务器需要但是不让用户看到的数据
<select>:表示一个下拉列表
<option>:代表一个下拉框内的选项
selected="selected",当前默认被选择
注意:
select中的name属性值等于option中的value值
<textarea>:代表一个多行文本域
属性;
clos:列数
rows:行数
注意:
默认的内容写在两个标签中间
4、框架标签
见图1
<frameset>:表示是一个框架
属性:
rows:按照行进行分割
clos:按照列进行分割
*:代表剩余的全部
注意:
<frameset>标签的位置是和<body>标签同级
<frame>:代表最终的一块区域,是<frameset>标签的字标签
属性:
name:名称
src:要加载页面的地址
注意:
不能自闭和
不能有结束标签
target="right",在指定的右侧打开链接
5、其他标签
5.1、其他标签
<base>:在head标签内使用
属性:
href:指定统一的域名(跳转路径)
例如:
<base href="http://www.baidu"></base>
在页面中所用的链接之前都会自动加上这个链接
<head>:写一些资讯信息
页面的整体属性标签:<title>页面的标题
指导解析器解析html的标签:<meta http-equiv="content-type" content="text/html; charset=UTF-8">
引入外部文件的标签:<link rel="stylesheet" type="text/css" href="styles.css">
seo的搜索优化:<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
5.2、特殊字符
代表空格
>代表大于号
<代表小于号
©代表版权符号(圆圈中一个c)
®代表注册商标(圆圈中一个R)
二、css
对html的美化
三、javascript(js)
动态的添加或修改html标签和css样式
四、jQuery
是js的一个封装
五、mysql
|
package com.infosys.userms.entity;
public class UserEntity {
}
|
package com.example.vineet.easybuy;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PaymentSuccessActivity extends AppCompatActivity {
SessionManager sessionManager;
TextView txt;
Button btn;
String paytm_bal,wallet_amount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_success);
sessionManager = new SessionManager(this);
txt=findViewById(R.id.txt);
btn=findViewById(R.id.btn);
paytm_bal= sessionManager.getPreferences("paytm_wallet");
wallet_amount = sessionManager.getPreferences("wallet_amount");
Log.e("Amount",paytm_bal+"1"+" "+wallet_amount);
//Toast.makeText(PaymentSuccessActivity.this,String.valueOf(paytm_bal+" "+wallet_amount), Toast.LENGTH_SHORT).show();
String status = getIntent().getStringExtra("type");
// String status = "1";
if(status.equals("1")){
txt.setText("Payment successful!\nYour remaining Pocket Money EMI Wallet is "+wallet_amount+".");
}else if(status.equals("2")){
txt.setText("Payment successful!\nYour remaining Paytm Wallet is "+paytm_bal+".");
}
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(PaymentSuccessActivity.this, Menu.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});
}
}
|
//********** Nov 9 - P1*****************
package ExceptionHandling;
public class ThrowKeyword {
public static void main(String[] args) {
//Throw Keyword --> It is used to generate our own exception
//we will use this in our framework
//Advantages -
//1. proper error messaging
//2 . deliberately throw your own exception
System.out.println("Hello Testing");
// try
// {
// throw new Exception("Some exception is coming ....");
// }
// catch(Exception e)
// {
// System.out.println(e.getMessage());
// e.printStackTrace();
// }
//String s="Naveen";//this data is coming from excel sheet
String s="Naveen";
//if(s.equals(null))
//s.equals(null)
System.out.println(s.equals(null));
//if(s.equals(null)) {//the moment s==null, i want to throw my own exception
System.out.println("bye");//will it print bye ..no ..y coz s is not equl to null
// try
// {
// throw new Exception("Excel value Exception - value is null");
// }
// catch(Exception e) {
// e.printStackTrace();
// }
}
}
|
package com.wllfengshu.mysql.model.entity;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* 响应结果
*/
@Getter
@Setter
public class ResultSet {
public ResultSet(boolean success) {
this.success = success;
}
public ResultSet(boolean success, String failReasons) {
this.success = success;
this.failReasons = failReasons;
}
/**
* 操作结果
*/
private Boolean success;
/**
* 失败原因
*/
private String failReasons;
/**
* 内容
*/
private List<Object> content;
@Override
public String toString() {
return "ResultSet{" +
"success=" + success +
", failReasons='" + failReasons + '\'' +
", content=" + content +
'}';
}
}
|
package com.framework.model;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableName;
@TableName("t_pro_field")
public class ProField {
private Integer id;
private Integer formId;
private String name;
private String comments;
private boolean isPri;
private boolean isGridCol;
private boolean isFormField;
private String fieldType;
private boolean isQuery;
private String queryType;
private String basicType;
private String expandParam;
private String columnName;//数据库表中的列名称
private String dataType;//数据类型
private Date createDate;
private String createBy;
private Date modifyDate;
private String modifyBy;
public Integer getId() {
return id;
}
public Integer getFormId() {
return formId;
}
public String getName() {
return name;
}
public String getComments() {
return comments;
}
public boolean isPri() {
return isPri;
}
public boolean isGridCol() {
return isGridCol;
}
public boolean isFormField() {
return isFormField;
}
public String getFieldType() {
return fieldType;
}
public boolean isQuery() {
return isQuery;
}
public String getQueryType() {
return queryType;
}
public String getBasicType() {
return basicType;
}
public String getExpandParam() {
return expandParam;
}
public Date getCreateDate() {
return createDate;
}
public String getCreateBy() {
return createBy;
}
public Date getModifyDate() {
return modifyDate;
}
public String getModifyBy() {
return modifyBy;
}
public void setId(Integer id) {
this.id = id;
}
public void setFormId(Integer formId) {
this.formId = formId;
}
public void setName(String name) {
this.name = name;
}
public void setComments(String comments) {
this.comments = comments;
}
public void setPri(boolean isPri) {
this.isPri = isPri;
}
public void setGridCol(boolean isGridCol) {
this.isGridCol = isGridCol;
}
public void setFormField(boolean isFormField) {
this.isFormField = isFormField;
}
public void setFieldType(String fieldType) {
this.fieldType = fieldType;
}
public void setQuery(boolean isQuery) {
this.isQuery = isQuery;
}
public void setQueryType(String queryType) {
this.queryType = queryType;
}
public void setBasicType(String basicType) {
this.basicType = basicType;
}
public void setExpandParam(String expandParam) {
this.expandParam = expandParam;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
public void setModifyBy(String modifyBy) {
this.modifyBy = modifyBy;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
} |
package com.aprendoz_test.data.output;
import java.util.Date;
/**
* Generated for query "estudiantes_listado_curriculo" on 01/19/2015 07:59:26
*
*/
public class Estudiantes_listado_curriculoRtnType {
private Integer idasignatura;
private Integer idpersona;
private Integer idunidad;
private String unidad;
private Integer numerounidad;
private Integer idsubtopico;
private String subtopico;
private Integer numerosubtopico;
private Integer idaprendizaje;
private String aprendizaje;
private Date fechaesperada;
private Integer peso;
public Integer getIdasignatura() {
return idasignatura;
}
public void setIdasignatura(Integer idasignatura) {
this.idasignatura = idasignatura;
}
public Integer getIdpersona() {
return idpersona;
}
public void setIdpersona(Integer idpersona) {
this.idpersona = idpersona;
}
public Integer getIdunidad() {
return idunidad;
}
public void setIdunidad(Integer idunidad) {
this.idunidad = idunidad;
}
public String getUnidad() {
return unidad;
}
public void setUnidad(String unidad) {
this.unidad = unidad;
}
public Integer getNumerounidad() {
return numerounidad;
}
public void setNumerounidad(Integer numerounidad) {
this.numerounidad = numerounidad;
}
public Integer getIdsubtopico() {
return idsubtopico;
}
public void setIdsubtopico(Integer idsubtopico) {
this.idsubtopico = idsubtopico;
}
public String getSubtopico() {
return subtopico;
}
public void setSubtopico(String subtopico) {
this.subtopico = subtopico;
}
public Integer getNumerosubtopico() {
return numerosubtopico;
}
public void setNumerosubtopico(Integer numerosubtopico) {
this.numerosubtopico = numerosubtopico;
}
public Integer getIdaprendizaje() {
return idaprendizaje;
}
public void setIdaprendizaje(Integer idaprendizaje) {
this.idaprendizaje = idaprendizaje;
}
public String getAprendizaje() {
return aprendizaje;
}
public void setAprendizaje(String aprendizaje) {
this.aprendizaje = aprendizaje;
}
public Date getFechaesperada() {
return fechaesperada;
}
public void setFechaesperada(Date fechaesperada) {
this.fechaesperada = fechaesperada;
}
public Integer getPeso() {
return peso;
}
public void setPeso(Integer peso) {
this.peso = peso;
}
}
|
package com.meebu;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.meebu.adapter.MyReviewPagerAdapter;
import com.meebu.databinding.ActivityReviewsBinding;
import com.meebu.fragment.MyReviewFragment;
import com.meebu.fragment.OtherFragment;
public class ReviewsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityReviewsBinding binding= DataBindingUtil.setContentView(ReviewsActivity.this,R.layout.activity_reviews);
MyReviewPagerAdapter myReviewPagerAdapter=new MyReviewPagerAdapter(getSupportFragmentManager());
myReviewPagerAdapter.addFragments( new MyReviewFragment(),"My Review");
myReviewPagerAdapter.addFragments( new OtherFragment(),"Other");
binding.reviewViewpager.setAdapter(myReviewPagerAdapter);
binding.reviewTabs.setupWithViewPager(binding.reviewViewpager);
binding.back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
}
}
|
package ual.dra.artifact19;
import java.util.List;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
@Autowired
private CrudRepository repository;
Controller(CrudRepository repository) {
this.repository = repository;
}
// Devuelve todos los aditivos
@GetMapping("/cartas")
List<Carta> all() {
return (List<Carta>) repository.findAll();
}
@PostMapping("/cartas")
Carta newCarta(@RequestBody Carta carta) {
return repository.save(carta);
}
// Busca por Id
@GetMapping("/cartas/{id}")
Carta getCarta(@PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new EntityNotFoundException());
}
}
|
package com.hdc.seckill.controller;
import com.hdc.seckill.pojo.User;
import com.hdc.seckill.service.IGoodsService;
import com.hdc.seckill.service.IUserService;
import com.hdc.seckill.vo.DetailVo;
import com.hdc.seckill.vo.GoodsVo;
import com.hdc.seckill.vo.RespBean;
import com.hdc.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* @ClassName GoodsController
* @Description controller of goods
* @Author prog_evil
* @Date 2021/7/24 10:04 下午
* @Version 1.0
**/
@Controller
@RequestMapping("/goods")
public class GoodsController {
@Autowired
private IUserService userService;
@Autowired
private IGoodsService goodsService;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ThymeleafViewResolver thymeleafViewResolver;
@RequestMapping(value = "/toList",produces = "text/html;charset=utf-8")
@ResponseBody
public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response){
//redis中获取页面,如果不为空,直接返回页面
ValueOperations valueOperations = redisTemplate.opsForValue();
String html = (String) valueOperations.get("goodsList");
if(!StringUtils.isEmpty(html)){
return html;
}
model.addAttribute("user",user);
model.addAttribute("goodsList",goodsService.findGoodsVo());
//return "goodsList"
//如果为空,手动渲染,存入Redis并返回
WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
html = thymeleafViewResolver.getTemplateEngine().process("goodsList",webContext);
if(!StringUtils.isEmpty(html)){
valueOperations.set("goodsList",html,60, TimeUnit.SECONDS);
}
return html;
}
@RequestMapping(value = "/toDetailB/{goodsId}",produces = "text/html;charset=utf-8")
@ResponseBody
public String toDetailB(Model model, User user, @PathVariable Long goodsId,HttpServletResponse response,HttpServletRequest request){
ValueOperations valueOperations = redisTemplate.opsForValue();
//从redis中获取页面 如果不为空 直接返回页面
String html = (String) (valueOperations.get("goodsDetail:" + goodsId));
GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
//秒杀开始时间
Date startDate = goodsVo.getStartDate();
//秒杀结束时间
Date endDate = goodsVo.getEndDate();
//现在时间
Date nowDate = new Date();
//标记为秒杀状态
int secKillStatus = 0;
//秒杀倒计时
int remainSeconds = 0;
if(nowDate.before(startDate)){//秒杀未开始
remainSeconds = (int) ((startDate.getTime() - nowDate.getTime())/1000);
}else if(nowDate.after(endDate)){//秒杀已结束
secKillStatus = 2;
remainSeconds = -1;
}else{//秒杀进行中
secKillStatus = 1;
remainSeconds = 0;
}
model.addAttribute("user",user);
model.addAttribute("secKillStatus",secKillStatus);
model.addAttribute("remainSeconds",remainSeconds);
model.addAttribute("goods",goodsVo);
WebContext context = new WebContext(request,response, request.getServletContext(),request.getLocale(), model.asMap());
html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail",context);
if(!StringUtils.isEmpty(html)){
valueOperations.set("goodsDetail"+goodsId,html,60,TimeUnit.SECONDS);
}
return html;
}
@RequestMapping( "/toDetail/{goodsId}")
@ResponseBody
public RespBean toDetail(Model model, User user, @PathVariable Long goodsId){
GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
//秒杀开始时间
Date startDate = goodsVo.getStartDate();
//秒杀结束时间
Date endDate = goodsVo.getEndDate();
//现在时间
Date nowDate = new Date();
//标记为秒杀状态
int secKillStatus = 0;
//秒杀倒计时
int remainSeconds = 0;
if(nowDate.before(startDate)){//秒杀未开始
remainSeconds = (int) ((startDate.getTime() - nowDate.getTime())/1000);
}else if(nowDate.after(endDate)){//秒杀已结束
secKillStatus = 2;
remainSeconds = -1;
}else{//秒杀进行中
secKillStatus = 1;
remainSeconds = 0;
}
DetailVo detailVo = new DetailVo();
detailVo.setUser(user);
detailVo.setGoodsVo(goodsVo);
detailVo.setSecKillStatus(secKillStatus);
detailVo.setRemainSeconds(remainSeconds);
return RespBean.success(detailVo);
}
}
|
package leetcode;
/**
* @author kangkang lou
*/
/**
* Greedy,贪心算法
*/
public class Main_45 {
/**
* 算法思想:贪心算法
* 假设,我们要跳跃的范围是【curBegin,curEnd】,curFarthest表示在【curBegin,curEnd】范围内
* 基于某个点所能到达的最远点,一旦到达边界点curEnd,则触发下一次跳跃。
* 下次跳跃的边界修改为curFarthest。
*
* @param nums
* @return
*/
public static int jump(int[] nums) {
int jumps = 0, curEnd = 0, curFarthest = 0;
for (int i = 0; i < nums.length - 1; i++) {
curFarthest = Math.max(curFarthest, i + nums[i]);
if (curFarthest == i + nums[i]) {
System.out.print(i + " ");
}
if (i == curEnd) {
jumps++;
curEnd = curFarthest;
}
}
return jumps;
}
public static void main(String[] args) {
int[] arr = {2, 3, 1, 1, 4};
jump(arr);
}
}
|
package org.github.chajian.matchgame.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.github.chajian.matchgame.data.IntegralPO;
/**
* 积分mapper
*/
@Mapper
public interface IntegralMapper {
IntegralPO selectByPlayerAndGameId(@Param("playerName") String playerName, @Param("gameId") String gameId);
void registerIntegral(IntegralPO integralPO);
}
|
package elements;
import elementfactory.base.Element;
import elementfactory.base.ElementImpl;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class InputImpl extends ElementImpl implements Input {
public InputImpl(WebElement wrappedElement) {
super(wrappedElement);
}
@FindBy(tagName = "input")
private Element inputField;
@FindBy(className = "form-error")
private Element errMessage;
@FindBy(tagName = "label")
private Element label;
@Override
public void sendKeys(CharSequence... keysToSend) {
clear();
inputField.sendKeys(keysToSend);
}
@Override
public void clear() {
inputField.clear();
}
@Override
public String getErrorMessage() {
return errMessage.getText();
}
@Override
public String getLabel() {
return label.getText();
}
@Override
public boolean hasError() {
return getClassAttribute().contains("has-error");
}
}
|
package com.yiki.blog.SecurityLearn;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
public User getUserByUserName(String name);
//查询用户拥有的权限
public List<Permission> getPermissionByUserName(String name);
public void InsertUser(User user);
}
|
package 프로젝트day03;
public class 산술계산 {
public static void main(String[] args) {
int x = 111;
int y = 222;
System.out.println("두 수의 합은 " + (x + y));
System.out.println("두 수의 나눗셈은 " + (x / y));
int sum = x + y;
// 1 3 2
int avg1 = sum / 2;
System.out.println("평균 " + avg1);
// 자바에서는 정수와 정수의 계산은 무조건 정수
// 자바에서는 하나라도 실수면 무조건 실수의 결과
double avg2 = sum / 2.0;
System.out.println("평균 " + avg2);
int count = 2;
avg2 = sum / (double) count;
System.out.println("평균 " + avg2);
// casting, 캐스팅 : cpu가 원래 데이터의 타입을 다른 타입으로 강제로 변환
// 강제로 타입 변환, 강제형변환 () 써서 변환
// int x2 = 22.0;
double y2 = 22;
}
}
|
package org.sathya;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.app.Employee;
public class Test {
private static Logger log = Logger.getLogger(Employee.class);
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
Layout layout = new SimpleLayout();
Appender ap = new ConsoleAppender(layout);
log.addAppender(ap);
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Query qry= session.createQuery("select v.vendorName, c.customerName from Vendor v Left Join v.children c");
log.info("data fetched successfully using left join");
List l = qry.list();
Iterator it=l.iterator();
while(it.hasNext())
{
Object rows[] = (Object[])it.next();
System.out.println(rows[0]+ " -- " +rows[1]);
}
}
}
|
/*
* 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.mycompany.visitorp;
import java.util.ArrayList;
/**
*
* @author User
*/
public class VisitorConcretTocarClaxon implements IVisitor{
@Override
public void visitar(ElementConcretAuto auto) {
System.out.println("AUTO toco claxon");
}
@Override
public void visitar(ElementConcretMoto moto) {
System.err.println("MOTO toco claxon");
}
@Override
public void visitar(ArrayList<IElemento> movilidades) {
for (IElemento movilidade : movilidades) {
movilidade.accept(this);
}
}
}
|
package ad.joyplus.com.myapplication.network;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import ad.joyplus.com.myapplication.AppUtil.AdExceptionUtil;
import ad.joyplus.com.myapplication.AppUtil.Consts;
import ad.joyplus.com.myapplication.AppUtil.glide.Glide;
import ad.joyplus.com.myapplication.AppUtil.glide.load.engine.DiskCacheStrategy;
import ad.joyplus.com.myapplication.AppUtil.gson.Gson;
import ad.joyplus.com.myapplication.AppUtil.gson.reflect.TypeToken;
import ad.joyplus.com.myapplication.AppUtil.volley.DefaultRetryPolicy;
import ad.joyplus.com.myapplication.AppUtil.volley.RequestQueue;
import ad.joyplus.com.myapplication.AppUtil.volley.Response;
import ad.joyplus.com.myapplication.AppUtil.volley.VolleyError;
import ad.joyplus.com.myapplication.AppUtil.volley.toolbox.ImageRequest;
import ad.joyplus.com.myapplication.AppUtil.volley.toolbox.StringRequest;
import ad.joyplus.com.myapplication.AppUtil.volley.toolbox.Volley;
import ad.joyplus.com.myapplication.entity.AdModel;
import ad.joyplus.com.myapplication.entity.ConfigModel;
import ad.joyplus.com.myapplication.entity.EndMediaModel;
import ad.joyplus.com.myapplication.entity.ImageViewModel;
import ad.joyplus.com.myapplication.entity.OpeningAdModel;
import ad.joyplus.com.myapplication.entity.StartMediaModel;
import ad.joyplus.com.myapplication.entity.URLModel;
/**
* 网络接口具体的实现类
* 利用第三方Volley框架进行Http请求
* Created by UPC on 2016/8/29.
*/
public class TrueHttpRequest implements IRequest {
private RequestQueue mQueue;
private Gson mGson;
private AdExceptionUtil exceptionUtil;
public TrueHttpRequest(Context context) {
mQueue = Volley.newRequestQueue(context);
mGson = new Gson();
exceptionUtil = new AdExceptionUtil();
}
@Override
public void getBaseModel(final int type, String url, final RequestIterface.IADmodel models) {
if (type == Consts.OPEN) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
if (!reqeust.toString().isEmpty()) {
String tempjson = "{ \"Code\":\"1\", \"VersonCode\":\"1.0\", \"msg\":\"ok\", \"data\":{ \"imageurl\":\"http://fwcdn.joyplus.tv/m/1920-1080V2.jpg\", \"impressionurl\":\"http://fwcdn.joyplus.tv/m/zhibodi.jpg\", \"clickurl\":\"\", \"showcount\":\"http://rapi.joyplus.tv/r.php?z=21&s=34\",\"html5_url\":\"\",\"thridreport\":[\"http://g.dtv.cn.miaozhen.com/x/k=4003363&p=2hhY3&ns=__IP__&nx=__LAB__&sn=__SN__&ni=__IESID__&m1=__ANDROIDID1__&m1a=__ANDROIDID__&m4=__AAID__&m6=__MAC1__&m6a=__MAC__&rt=2&nd=__DRA__&nt=__TIME__&rfm=__RFM__&tdt=__TDT__&tdr=__TDR__&o=\",\"http://g.dtv.cn.miaozhen.com/x/k=4003363&p=2hhY3&ns=__IP__&nx=__LAB__&sn=__SN__&ni=__IESID__&m1=__ANDROIDID1__&m1a=__ANDROIDID__&m4=__AAID__&m6=__MAC1__&m6a=__MAC__&rt=2&nd=__DRA__&nt=__TIME__&rfm=__RFM__&tdt=__TDT__&tdr=__TDR__&o=\"] } }";
Type type1 = new TypeToken<AdModel<OpeningAdModel>>() {
}.getType();
AdModel<OpeningAdModel> openingAdModel = mGson.fromJson(tempjson, type1);
models.onAdModelBack(openingAdModel);
} else {
models.onAdModelBack(null);
}
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
} else if (type == Consts.STARTMEDIA) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
if (!reqeust.toString().isEmpty()) {
Type type1 = new TypeToken<AdModel<StartMediaModel>>() {
}.getType();
AdModel<StartMediaModel> openingAdModel = mGson.fromJson(reqeust.toString(), type1);
models.onAdModelBack(openingAdModel);
} else {
models.onAdModelBack(null);
}
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
} else if (type == Consts.ENDMEDIA) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
if (!reqeust.toString().isEmpty()) {
Type type1 = new TypeToken<AdModel<EndMediaModel>>() {
}.getType();
AdModel<EndMediaModel> openingAdModel = mGson.fromJson(reqeust.toString(), type1);
models.onAdModelBack(openingAdModel);
} else {
models.onAdModelBack(null);
}
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
} else if (type == Consts.VIDEOIMG) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
if (!reqeust.toString().isEmpty()) {
Type type1 = new TypeToken<AdModel<ImageViewModel>>() {
}.getType();
AdModel<ImageViewModel> openingAdModel = mGson.fromJson(reqeust.toString(), type1);
models.onAdModelBack(openingAdModel);
} else {
models.onAdModelBack(null);
}
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
} else if (type == Consts.CORNERIMG) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
if (!reqeust.toString().isEmpty()) {
Type type1 = new TypeToken<AdModel<ImageViewModel>>() {
}.getType();
AdModel<ImageViewModel> openingAdModel = mGson.fromJson(reqeust.toString(), type1);
models.onAdModelBack(openingAdModel);
} else {
models.onAdModelBack(null);
}
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
} else if (type == Consts.SIMPLEIMG) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
if (!reqeust.toString().isEmpty()) {
Type type1 = new TypeToken<AdModel<ImageViewModel>>() {
}.getType();
AdModel<ImageViewModel> openingAdModel = mGson.fromJson(reqeust.toString(), type1);
models.onAdModelBack(openingAdModel);
} else {
models.onAdModelBack(null);
}
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
}
}
@Override
public void getImgFromGlide(ImageView view, String url, Object object) {
LoadImgFromGlide(view, url, object);
}
@Override
public void getGifFromGlide(ImageView view, String url, Context context) {
Glide.with(context).load(Uri.fromFile(new File(url))).into(view);
}
@Override
public void getHitmlInfo(String url, final RequestIterface.IHtmlInfoCallBack callBack) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
URLModel model = mGson.fromJson(reqeust.toString(), URLModel.class);
callBack.OnHtmlBack(model);
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
}
@Override
public void getConfigInfo(String url, final RequestIterface.IModelCallBack callBack) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
AdModel<ConfigModel<Map<String, String>>> adModel = mGson.fromJson(reqeust.toString(), new TypeToken<AdModel<ConfigModel<Map<String, String>>>>() {
}.getType());
callBack.onConfigModelBack(adModel);
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
}
/**
* 获取开屏对应资源的信息
*
* @param url
* @param callBack
*/
@Override
public void getOpeningInfo(String url, final RequestIterface.IOpeningInfoCallBack callBack) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
AdModel<OpeningAdModel> model = mGson.fromJson(reqeust.toString(), new TypeToken<AdModel<OpeningAdModel>>() {
}.getType());
callBack.onOpeningBack(model.data);
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
}
/**
* 获取配置信息的方法
*
* @param url
*/
@Override
public void DownLoadFiles(String targetFilepath, String url, RequestIterface.IDownLoadProgress progress, RequestIterface.IDownLoadSuccess success) {
DownLodResource(targetFilepath, url, progress, success);
}
/**
* @param url
* @param callback
*/
@Override
public void getStartMediaInfo(String url, final RequestIterface.IStartMediaCallBack callback) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
if (!reqeust.toString().isEmpty()) {
AdModel<StartMediaModel> model = mGson.fromJson(reqeust.toString(), new TypeToken<AdModel<StartMediaModel>>() {
}.getType());
callback.onStartMediaBack(model);
} else {
callback.onStartMediaBack(null);
}
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
}
/**
* 获取后贴片的视频资源
*
* @param url
* @param callBack
*/
@Override
public void getEndMediaInfo(String url, final RequestIterface.IEndMediaCallBack callBack) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
if (!reqeust.toString().isEmpty()) {
AdModel<StartMediaModel> model = mGson.fromJson(reqeust.toString(), new TypeToken<AdModel<StartMediaModel>>() {
}.getType());
callBack.onEndMediaBack(model);
} else {
callBack.onEndMediaBack(null);
}
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
Log.e("APPADSDK_HttpError", request.toString());
}
});
}
@Override
public void reportInfo(String url, final RequestIterface.IReportInfoCallBack callBack) {
TrueConfigInfomation(url, new RequestIterface.ISuccessRequest() {
@Override
public void onSuccess(Object reqeust) {
callBack.onReportBack(true);
}
}, new RequestIterface.IFaileRequest() {
@Override
public void onFailed(Object request) {
callBack.onReportBack(false);
}
});
}
@Override
public void getImageBitMap(String url, RequestIterface.IImageBitMap callBack) {
ThregetBitMap(url, callBack);
}
private void ThregetBitMap(String url, final RequestIterface.IImageBitMap callBack) {
ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
callBack.onImageBitMap(response);
}
}, 1920, 1080, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//交给exceptionUtil来处理
exceptionUtil.checkErrorFactory(error);
}
});
mQueue.add(request);
}
private void TrueConfigInfomation(String url, final RequestIterface.ISuccessRequest successRequest, final RequestIterface.IFaileRequest faileRequest) {
StringRequest request = new StringRequest(StringRequest.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
successRequest.onSuccess(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
exceptionUtil.checkErrorFactory(error);
faileRequest.onFailed(error);
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mQueue.add(request);
}
private void DownLodResource(final String targetfilepath, final String sourceurl, final RequestIterface.IDownLoadProgress pro, final RequestIterface.IDownLoadSuccess success) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
try {
File file = new File(targetfilepath);
if (file.exists()) {
//对已存在的本地文件做处理
}
URL urls = new URL(sourceurl);
URLConnection urlConnection = urls.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.connect();
int contentLength = httpURLConnection.getContentLength();
RandomAccessFile accessFile = new RandomAccessFile(targetfilepath, "rwd");
byte[] bytes = new byte[1024 * 50];
int length = -1;
long downsize = 0;
InputStream is = httpURLConnection.getInputStream();
while ((length = is.read(bytes)) != -1) {
accessFile.write(bytes, 0, length);
downsize += length;
pro.onDownLoadProgress((int) downsize);
if (contentLength == downsize) {
success.onDownLoadSuccess("success");
return "success";
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
private void LoadImgFromGlide(ImageView imageView, String url, Object context) {
if (context instanceof Context) {
Glide.with((Context) context).load(url).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
} else if (context instanceof Activity) {
Glide.with((Activity) context).load(url).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
} else if (context instanceof Fragment) {
Glide.with((Fragment) context).load(url).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
} else if (context instanceof android.support.v4.app.Fragment) {
Glide.with((android.support.v4.app.Fragment) context).load(url).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
} else if (context instanceof FragmentActivity) {
Glide.with((FragmentActivity) context).load(url).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
}
}
}
|
package com.yqwl.dao;
import java.math.BigInteger;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.yqwl.pojo.Color;
/**
*
* @ClassName: ColorMapper
* @description 色系的查询,新增,删除等方法
*
* @author dujiawei
* @createDate 2019年6月6日
*/
public interface ColorMapper {
/**
* @Title: listColor
* @description (后台)分页查询所有的色系
* @param @param beginPageIndex
* @param @param limit
* @return List<Color>
* @author dujiawei
* @createDate 2019年6月6日
*/
List<Color> listColor(@Param("beginPageIndex")Integer beginPageIndex,@Param("limit")Integer limit);
/**
* @Title: countColor
* @description 所有色系的数量
* @return int
* @author dujiawei
* @createDate 2019年6月6日
*/
public int countColor();
/**
* @Title: saveColor
* @description (后台)增加一条色系
* @param @param color
* @return int
* @author dujiawei
* @createDate 2019年6月6日
*/
public int saveColor(Color color);
/**
* @Title: removeColor
* @description (后台)删除一条色系
* @param @param id
* @return int
* @author dujiawei
* @createDate 2019年6月6日
*/
public int removeColor(@Param("id") BigInteger id);
/**
* @Title: getColorById
* @description (后台)通过id查询对应的色系
* @param @param color
* @return Color
* @author dujiawei
* @createDate 2019年6月6日
*/
public Color getColorById(Color color);
/**
* @Title: showAllColor
* @description (前台)显示所有的色系
* @return List<Color>
* @author dujiawei
* @createDate 2019年6月6日
*/
public List<Color> showAllColor();
}
|
package com.akikun.leetcode;
/**
* @author 李俊秋(龙泽)
*/
public class _00944_DeleteColumnsToMakeSorted {
public static void main(String[] args) {
// Excepted: 5
// String[] strs = {"cba", "daf", "ghi"};
String[] strs = {"a", "b"};
_00944_DeleteColumnsToMakeSorted test = new _00944_DeleteColumnsToMakeSorted();
int result = test.minDeletionSize(strs);
System.out.println(result);
}
public int minDeletionSize(String[] strs) {
if (strs.length < 2) {
return 0;
}
char[] lastCharArr = strs[0].toCharArray();
boolean[] isDelete = new boolean[lastCharArr.length];
for (int i = 1; i < strs.length; ++i) {
char[] currCharArr = strs[i].toCharArray();
for (int j = 0; j < isDelete.length; ++j) {
if (!isDelete[j] && (currCharArr[j] - lastCharArr[j] < 0)) {
isDelete[j] = true;
}
}
lastCharArr = currCharArr;
}
int cnt = 0;
for (int i = 0; i <isDelete.length; ++i) {
if (isDelete[i]) {
cnt++;
}
}
return cnt;
}
}
|
package com.vilio.mps.receivepush.service.impl;
import com.vilio.mps.common.dao.CommonDao;
import com.vilio.mps.common.dao.MpsMessageReceiveInfoMapper;
import com.vilio.mps.common.pojo.MpsReceiveMessageInfo;
import com.vilio.mps.receivepush.service.ReceiveMessage;
import com.vilio.mps.util.CommonUtil;
import com.vilio.mps.glob.Fields;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by dell on 2017/5/18/0018.
*/
@Service
public class ReceiveMessageImpl implements ReceiveMessage {
public static Logger logger = Logger.getLogger(ReceiveMessageImpl.class);
@Resource
MpsMessageReceiveInfoMapper mpsMessageReceiveInfoMapper;
@Resource
CommonDao commonDao;
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED,
rollbackFor = Exception.class)
public Map saveMessage(Map paramMap) throws InvocationTargetException, IntrospectionException, InstantiationException, IllegalAccessException, CloneNotSupportedException {
Map<String, Object> bodyMap = new HashMap<String, Object>();
MpsReceiveMessageInfo messageReceiveInfo = (MpsReceiveMessageInfo) CommonUtil.convertMapToEntity(MpsReceiveMessageInfo.class, paramMap);
List<MpsReceiveMessageInfo> listMessageResp = new ArrayList<MpsReceiveMessageInfo>();
List<Map> receiverListMap = (List<Map>) paramMap.get(Fields.PARAM_MPS_RECEIVEUSERLIST);
for(Map receiverMap: receiverListMap){
messageReceiveInfo.setReceiverCompanyCode((String) receiverMap.get(Fields.PARAM_MPS_RECEIVERCOMPANYCODE));
messageReceiveInfo.setReceiverCompanyName((String) receiverMap.get(Fields.PARAM_MPS_RECEIVERCOMPANYNAME));
messageReceiveInfo.setReceiverDepartmentCode((String) receiverMap.get(Fields.PARAM_MPS_RECEIVERDEPARTMENTCODE));
messageReceiveInfo.setReceiverDepartmentName((String) receiverMap.get(Fields.PARAM_MPS_RECEIVERDEPARTMENTNAME));
messageReceiveInfo.setReceiverIdentityId((String) receiverMap.get(Fields.PARAM_MPS_RECEIVERIDENTITYID));
messageReceiveInfo.setReceiverName((String) receiverMap.get(Fields.PARAM_MPS_RECEIVERNAME));
messageReceiveInfo.setReceiverSystem((String) receiverMap.get(Fields.PARAM_MPS_RECEIVERSYSTEM));
messageReceiveInfo.setRequestNo((String) receiverMap.get(Fields.PARAM_MPS_RECEIVER_CODE));
String serialNo = CommonUtil.getCurrentTimeStr("M","X");
messageReceiveInfo.setSerialNo(serialNo);
//保存到本地
mpsMessageReceiveInfoMapper.insertMessageReceiveInfo(messageReceiveInfo);
listMessageResp.add(messageReceiveInfo.clone());
}
bodyMap.put(Fields.PARAM_MPS_MESSAGELIST, listMessageResp);
return bodyMap;
}
public Map getMessageListBySerialNoList(Map paramMap) throws Exception {
Map<String, Object> bodyMap = new HashMap<String, Object>();
StringBuffer sb = new StringBuffer();
List<MpsReceiveMessageInfo> list = new ArrayList<MpsReceiveMessageInfo>();
list = mpsMessageReceiveInfoMapper.getMessageBySerialNoList(paramMap);
List<Map> messageList = new ArrayList<Map>();
if(null != messageList){
for(MpsReceiveMessageInfo info :list){
Map<String, String> messageMap = new HashMap<String, String>();
messageMap.put(Fields.PARAM_MPS_RECEIVER_SERIAL_NO, info.getSerialNo());
messageMap.put(Fields.PARAM_MPS_TTITLE, info.getTitle());
messageMap.put(Fields.PARAM_MPS_CONTENT, info.getContent());
messageMap.put(Fields.PARAM_MPS_RECEIVERCOMPANYCODE, info.getReceiverCompanyCode());
messageMap.put(Fields.PARAM_MPS_RECEIVERCOMPANYNAME, info.getReceiverCompanyName());
messageMap.put(Fields.PARAM_MPS_RECEIVERDEPARTMENTCODE, info.getReceiverDepartmentCode());
messageMap.put(Fields.PARAM_MPS_RECEIVERDEPARTMENTNAME, info.getReceiverDepartmentName());
messageMap.put(Fields.PARAM_MPS_RECEIVERIDENTITYID, info.getReceiverIdentityId());
messageMap.put(Fields.PARAM_MPS_RECEIVERNAME, info.getReceiverName());
messageMap.put(Fields.PARAM_MPS_SENDERCOMPANYNAME, info.getSenderCompanyName());
messageMap.put(Fields.PARAM_MPS_SENDERCOMPANYCODE, info.getSenderCompanyCode());
messageMap.put(Fields.PARAM_MPS_SENDERCOMPANYNAME, info.getSenderCompanyName());
messageMap.put(Fields.PARAM_MPS_SENDERDEPARTMENTCODE, info.getSenderDepartmentCode());
messageMap.put(Fields.PARAM_MPS_SENDERDEPARTMENTNAME, info.getSenderDepartmentName());
messageMap.put(Fields.PARAM_MPS_SENDERIDENTITYID, info.getSenderIdentityId());
messageMap.put(Fields.PARAM_MPS_RECEIVERNAME, info.getReceiverName());
messageList.add(messageMap);
}
}
bodyMap.put(Fields.PARAM_MPS_MESSAGELIST, messageList);
return bodyMap;
}
}
|
package miggy.cpu.instructions.tst;
import miggy.BasicSetup;
import miggy.SystemModel;
import miggy.SystemModel.CpuFlag;
// $Revision: 21 $
public class TSTTest extends BasicSetup {
public TSTTest(String test) {
super(test);
}
public void testByte() {
setInstruction(0x4a00); //tst.b d0
SystemModel.CPU.setDataRegister(0, 0x12345600);
SystemModel.CPU.setCCR((byte) 0);
int time = SystemModel.CPU.execute();
assertEquals("Check result", 0x12345600, SystemModel.CPU.getDataRegister(0));
assertFalse("Check X", SystemModel.CPU.isSet(CpuFlag.X));
assertFalse("Check N", SystemModel.CPU.isSet(CpuFlag.N));
assertTrue("Check Z", SystemModel.CPU.isSet(CpuFlag.Z));
assertFalse("Check V", SystemModel.CPU.isSet(CpuFlag.V));
assertFalse("Check C", SystemModel.CPU.isSet(CpuFlag.C));
}
public void testWord() {
setInstruction(0x4a40); //tst.w d0
SystemModel.CPU.setDataRegister(0, 0x12345678);
SystemModel.CPU.setCCR((byte) 0);
int time = SystemModel.CPU.execute();
assertEquals("Check result", 0x12345678, SystemModel.CPU.getDataRegister(0));
assertFalse("Check X", SystemModel.CPU.isSet(CpuFlag.X));
assertFalse("Check N", SystemModel.CPU.isSet(CpuFlag.N));
assertFalse("Check Z", SystemModel.CPU.isSet(CpuFlag.Z));
assertFalse("Check V", SystemModel.CPU.isSet(CpuFlag.V));
assertFalse("Check C", SystemModel.CPU.isSet(CpuFlag.C));
}
public void testLong() {
setInstruction(0x4a80); //tst.l d0
SystemModel.CPU.setDataRegister(0, 0x87654321);
SystemModel.CPU.setCCR((byte) 0);
int time = SystemModel.CPU.execute();
assertEquals("Check result", 0x87654321, SystemModel.CPU.getDataRegister(0));
assertFalse("Check X", SystemModel.CPU.isSet(CpuFlag.X));
assertTrue("Check N", SystemModel.CPU.isSet(CpuFlag.N));
assertFalse("Check Z", SystemModel.CPU.isSet(CpuFlag.Z));
assertFalse("Check V", SystemModel.CPU.isSet(CpuFlag.V));
assertFalse("Check C", SystemModel.CPU.isSet(CpuFlag.C));
}
}
|
package kr.ds.fragment;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import kr.ds.ObservableScrollView.ObservableListView;
import kr.ds.ObservableScrollView.ObservableScrollViewCallbacks;
import kr.ds.ObservableScrollView.ScrollState;
import kr.ds.adapter.Content3BaseAdapter;
import kr.ds.adapter.MySpinnerAdapter;
import kr.ds.custom.ProgressFragment;
import kr.ds.handler.Content3Handler;
import kr.ds.mylotto.CustomMapActivity;
import kr.ds.mylotto.MainActivity;
import kr.ds.mylotto.R;
import kr.ds.parcelable.ParcelableMapData;
import kr.ds.parser.AppParser;
import kr.ds.utils.HttpHelper;
import kr.ds.utils.JSONParser;
import kr.ds.utils.NetworkCheck;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class Fragment_3 extends ProgressFragment implements OnClickListener,ObservableScrollViewCallbacks {
private Context mContext;
private View mView;
private ObservableListView mListView;
private ArrayList<Content3Handler> mDATA;
private String Url = "";
private Button mTab1, mTab2;
private final int TAB1=0, TAB2=1;
private Content3BaseAdapter mContent3BaseAdapter;
private boolean tab1=false, tab2=false;
private MySpinnerAdapter mSpinnerAdapter;
private ArrayList<String> mDATANUM = new ArrayList<String>();
private Spinner mSpinnerNum;
private String mNums = "";
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
mContext = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
mView = inflater.inflate(R.layout.content_listview3, null);
(mTab1 = (Button)mView.findViewById(R.id.button_tab1)).setOnClickListener(this);
(mTab2 = (Button)mView.findViewById(R.id.button_tab2)).setOnClickListener(this);
mSpinnerNum = (Spinner)mView.findViewById(R.id.spinner_num);
mSpinnerNum.setPrompt("회차를 선택하세요.");
mListView = (ObservableListView)mView.findViewById(R.id.listview);
mListView.setScrollViewCallbacks(this);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
new HttpJson(mContext,splitFunction(mDATA.get(position).getTitle()), mDATA.get(position).getAddress()).execute("https://maps.googleapis.com/maps/api/geocode/json?address="+getURLEncode(mDATA.get(position).getAddress())+"&key=AIzaSyDRu_HMrNRLsC0v_XlopGaEwtco6KmCxZY");
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
public String splitFunction(String where){
String mWhere = "";
String[] array = where.split("\\.");
for(int i=0; i< array.length; i++){
if(i != 0){
mWhere += array[i];
}
}
mWhere = mWhere.trim();
return mWhere;
}
class HttpJson extends AsyncTask<String, Integer, JSONObject> {
Context context;
String lat = "";
String lng = "";
String mTitle = "";
String mAddress = "";
private HttpJson(Context context, String title, String address) {
this.context = context;
mTitle = title;
mAddress = address;
}
@Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(params[0]);
return json;
}
@Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONArray mJsonArray = result.getJSONArray("results");
JSONObject mJsonObject2 = mJsonArray.getJSONObject(0);
lat = mJsonObject2.getJSONObject("geometry").getJSONObject("location").getString("lat");
lng = mJsonObject2.getJSONObject("geometry").getJSONObject("location").getString("lng");
Log.i("TEST",lat+"");
Log.i("TEST",lng+"");
Log.i("TEST",result+"");
if(!lat.matches("") && !lng.matches("")){
Intent NextIntent = new Intent();
NextIntent.setClass(context, CustomMapActivity.class);
NextIntent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
NextIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ParcelableMapData data = new ParcelableMapData(mTitle, mAddress, lat, lng);
NextIntent.putExtra("data", data);
context.startActivity(NextIntent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(mContext, R.string.error2, Toast.LENGTH_SHORT).show();
}
}
}
private String getURLEncode(String content){
try {
return URLEncoder.encode(content, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
setContentView(mView);
setContentShown(false);//progress
setContentShown(true);
setTab(TAB1);
if (NetworkCheck.isonline(mContext)) {
Url = "http://pctu1213.cafe24.com/app/lotto/num.php";
new View1().execute(Url);
}else{
Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
setContentShown(true);
}
}
public void setTab(int position){
mTab1.setBackgroundResource(R.drawable.btn_off);
mTab2.setBackgroundResource(R.drawable.btn_off);
mTab1.setTextColor(0xff000000);
mTab2.setTextColor(0xff000000);
tab1 = false;
tab2 = false;
if(position == TAB1){
tab1 = true;
mTab1.setBackgroundResource(R.drawable.btn_on);
mTab1.setTextColor(0xffffffff);
}else if(position == TAB2){
tab2 = true;
mTab2.setBackgroundResource(R.drawable.btn_on);
mTab2.setTextColor(0xffffffff);
}
}
class View1 extends AsyncTask<String, Integer, JSONObject> {
private JSONObject jObj = null;
private int mNum = 0;
private String mResult = "";
protected void onPreExecute() {
};
@Override
protected JSONObject doInBackground(String... params) {
try {
String content = HttpHelper.getHttpContent(mContext,params[0]);
jObj = new JSONObject(content);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
@Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
mNum = result.getInt("NUM");
mResult = result.getString("RESULT");
if(mNum != 0 && mResult.trim().matches("SUCCESS")){
for(int i = mNum; i>=1; i--){
mDATANUM.add(String.valueOf(i));
//Log.i("TEST",i+"");
}
if(mDATANUM != null && mDATANUM.size()>0){
mSpinnerAdapter = new MySpinnerAdapter(mContext, mDATANUM);
mSpinnerNum.setAdapter(mSpinnerAdapter);
mSpinnerNum.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
mNums = mDATANUM.get(position).toString().replace("회", "");
mNums = mDATANUM.get(position).toString().replace("차", "");
mNums = mDATANUM.get(position).toString().trim();
if (NetworkCheck.isonline(mContext)) {
if(tab1 == true){
Url = "http://pctu1213.cafe24.com/app/lotto/location1.php?num="+mNums;
}else if(tab2 == true){
Url = "http://pctu1213.cafe24.com/app/lotto/location2.php?num="+mNums;
}
new View2().execute(Url);
}else{
Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
setContentShown(true);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
if (NetworkCheck.isonline(mContext)) {
Url = "http://pctu1213.cafe24.com/app/lotto/location1.php";
new View2().execute(Url);
}else{
Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
setContentShown(true);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
}
// if(mDATA3 != null){
// mSpinnerAdapter = new MySpinnerAdapter(mContext, mDATA3);
// mSpinnerLoction.setAdapter(mSpinnerAdapter);
// mSpinnerLoction.setOnItemSelectedListener(new OnItemSelectedListener() {
// @Override
// public void onItemSelected(AdapterView<?> parent, View view,
// int position, long id) {
// // TODO Auto-generated method stub
// mCode = mDATA3.get(position).getCode();
// new View1().execute(mCode);
// }
// @Override
// public void onNothingSelected(AdapterView<?> parent) {
// // TODO Auto-generated method stub
// }
// });
// }else{
// mProgressBar.setVisibility(View.GONE);
// }
}
}
class View2 extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
};
@Override
protected String doInBackground(String... arg0) {
Content3Handler DATA = new Content3Handler();
AppParser ps = new AppParser(DATA);
ps.Content3Parser(arg0[0]);
mDATA = ps.getContent3Load();
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
setContentShown(true);
if(mDATA != null && mDATA.size()>0){
mContent3BaseAdapter = new Content3BaseAdapter(mContext,mDATA);
mListView.setAdapter(mContent3BaseAdapter);
}else{
Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.button_tab1:
setContentShown(false);
setTab(TAB1);
if (NetworkCheck.isonline(mContext)) {
if(mNums !=null && !mNums.trim().matches("")){
Url = "http://pctu1213.cafe24.com/app/lotto/location1.php?num="+mNums;
}else{
Url = "http://pctu1213.cafe24.com/app/lotto/location1.php";
}
new View2().execute(Url);
}else{
Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
setContentShown(true);
}
break;
case R.id.button_tab2:
setContentShown(false);
setTab(TAB2);
if (NetworkCheck.isonline(mContext)) {
if(mNums !=null && !mNums.trim().matches("")){
Url = "http://pctu1213.cafe24.com/app/lotto/location2.php?num="+mNums;
}else{
Url = "http://pctu1213.cafe24.com/app/lotto/location2.php";
}
new View2().execute(Url);
}else{
Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
setContentShown(true);
}
break;
}
}
@Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
setContentShown(true);
}
@Override
public void onScrollChanged(int scrollY, boolean firstScroll,
boolean dragging) {
// TODO Auto-generated method stub
}
@Override
public void onDownMotionEvent() {
// TODO Auto-generated method stub
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
// TODO Auto-generated method stub
MainActivity activity = (MainActivity) getActivity();
if (activity == null) {
return;
}
ActionBar ab = activity.getSupportActionBar();
if (scrollState == ScrollState.UP) {
if (ab.isShowing()) {
ab.hide();
}
} else if (scrollState == ScrollState.DOWN) {
if (!ab.isShowing()) {
ab.show();
}
}
}
}
|
/*
* 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 utn.resumiderobilletes.ui.forms;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import utn.resumiderobilletes.entidades.Categoria;
import utn.resumiderobilletes.entidades.Cuenta;
import utn.resumiderobilletes.entidades.Movimiento;
import utn.resumiderobilletes.excepciones.ResumideroValidationException;
import utn.resumiderobilletes.listas.ListaGenerica;
import utn.resumiderobilletes.repositorios.Archivo;
/**
*
* @author Luciano
*/
public class FrmMovimiento extends javax.swing.JFrame {
ListaGenerica<Cuenta> cuentas = Archivo.getDatos().getCuentas();
ListaGenerica<Categoria> categorias = Archivo.getDatos().getCategorias();
ListaGenerica<Movimiento> movimientos = Archivo.getDatos().getMovimientos();
private FrmPrincipal frmParent;
private Double monto;
/**
* Creates new form FrmMovimiento
*/
public FrmMovimiento() {
initComponents();
cargarFormulario();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
radioDeposito = new javax.swing.JRadioButton();
radioExtraccion = new javax.swing.JRadioButton();
btGuardar = new javax.swing.JButton();
txtMonto = new javax.swing.JTextField();
comboCuenta = new javax.swing.JComboBox();
comboCategoria = new javax.swing.JComboBox();
jLabel5 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("SansSerif", 1, 18)); // NOI18N
jLabel1.setText("Crear Movimiento");
jLabel2.setText("Cuenta:");
jLabel3.setText("Monto $:");
jLabel4.setText("Categoria/Motivo:");
radioDeposito.setText("Deposito");
radioDeposito.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radioDepositoActionPerformed(evt);
}
});
radioExtraccion.setText("Extracción");
radioExtraccion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radioExtraccionActionPerformed(evt);
}
});
btGuardar.setText("Guardar");
btGuardar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btGuardarActionPerformed(evt);
}
});
comboCuenta.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
comboCategoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel5.setText("Operación:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtMonto, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(comboCuenta, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(comboCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(radioDeposito)
.addGap(18, 18, 18)
.addComponent(radioExtraccion))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(btGuardar)
.addGap(186, 186, 186)))
.addContainerGap(54, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jLabel1)
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(comboCuenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(comboCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(radioDeposito)
.addComponent(radioExtraccion)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addComponent(btGuardar)
.addContainerGap(25, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void radioDepositoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioDepositoActionPerformed
setRadios(true);
}//GEN-LAST:event_radioDepositoActionPerformed
private void radioExtraccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioExtraccionActionPerformed
setRadios(false);
}//GEN-LAST:event_radioExtraccionActionPerformed
private void btGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGuardarActionPerformed
try {
Cuenta cuenta = (Cuenta) comboCuenta.getSelectedItem();
Categoria categoria = (Categoria) comboCategoria.getSelectedItem();
boolean isNumber = isnumber(txtMonto.getText());
if (isNumber) {
int idmov = movimientos.getCantidad() + 1;
Movimiento mov = new Movimiento(idmov, cuenta.getNumeroCuenta(), categoria.getId(), monto, radioDeposito.isSelected());
if (radioDeposito.isSelected()) {
cuenta.depositar(monto);
} else {
if (cuenta.retirar(monto) == false) {
throw new ResumideroValidationException("No se pudo retirar el dinero de la cuenta. Compruebe el monto de la cuenta.");
}
}
categoria.agregar(mov);
movimientos.agregar(mov);
Archivo.guardar();
frmParent.iniciarFormulario();
JOptionPane.showMessageDialog(this, "El Movimiento se creo exitosamente!!!", "Error", JOptionPane.INFORMATION_MESSAGE);
this.dispose();
} else {
JOptionPane.showMessageDialog(this, "El monto tiene que ser un numero valido mayor que 0.", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (ResumideroValidationException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_btGuardarActionPerformed
/**
* @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(FrmMovimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmMovimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmMovimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmMovimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FrmMovimiento().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btGuardar;
private javax.swing.JComboBox comboCategoria;
private javax.swing.JComboBox comboCuenta;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JRadioButton radioDeposito;
private javax.swing.JRadioButton radioExtraccion;
private javax.swing.JTextField txtMonto;
// End of variables declaration//GEN-END:variables
private void cargarFormulario() {
txtMonto.setText("");
setRadios(true);
cargarCategorias();
cargarCuentas();
}
private void cargarCategorias() {
comboCategoria.removeAllItems();
for (Categoria categoria : categorias) {
comboCategoria.addItem(categoria);
}
comboCategoria.repaint();
}
public void setPadre(FrmPrincipal pPadre) {
frmParent = pPadre;
}
private void setRadios(boolean value) {
radioDeposito.setSelected(value);;
radioExtraccion.setSelected(!value);
}
private void cargarCuentas() {
comboCuenta.removeAllItems();
for (Cuenta cuenta : cuentas) {
comboCuenta.addItem(cuenta);
}
comboCuenta.repaint();
}
private boolean isnumber(String text) {
try {
monto = Double.valueOf(text);
return monto > 0;
} catch (NumberFormatException e) {
return false;
}
}
}
|
/*
* Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory
* CODE-743439.
* All rights reserved.
* This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool.
*
* Licensed under the Apache License, Version 2.0 (the “Licensee”); 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.
*
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
*/
package llnl.gnem.core.gui.plotting.jmultiaxisplot;
/**
* A type-safe enum class for Pick Error Symbol direction.
*
* @author Doug Dodge
*/
public class PickErrorDir {
private final String name;
private PickErrorDir(String name) {
this.name = name;
}
/**
* Return a String description of this type.
*
* @return The String description
*/
public String toString() {
return name;
}
/**
* Numbers increase to the left
*/
public final static PickErrorDir LEFT = new PickErrorDir("left");
/**
* Numbers increase to the right
*/
public final static PickErrorDir RIGHT = new PickErrorDir("right");
}
|
/*
Three friends came up with a game for having fun in the break between the classes.
One of them says a three-digit number and the others use it to form a mathematical
expressions by using operators for sum and multiplication between the digits of that number.
The winner is the first one who founds the biggest number that is a result of the above mentioned rules.
Write a program 'game', which prints out that biggest number.
*/
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String n = in.nextLine();
/* Първи опит - не покрива всички тестове.
int num01= Integer.parseInt(String.valueOf(n.charAt(0)));
int num02= Integer.parseInt(String.valueOf(n.charAt(1)));
int num03= Integer.parseInt(String.valueOf(n.charAt(2)));
int sum = 0;
if(num01 == 0 || num01 == 1
&& num02 != 1 || num02 != 0
&& num03 != 1 || num03 != 0){
sum = num02*num03 + num01;
}else if(num02 == 0 || num02 == 1
&& num01 != 1 || num01 != 0
&& num03 != 1 || num03 != 0){
sum = num01*num03 + num02;
}else if(num03 == 0 || num03 == 1
&& num02 != 1 || num02 != 0
&& num01 != 1 || num01 != 0){
sum = num02*num01 + num03;
}else{
sum = num01*num02*num03;
}
System.out.println(sum);
*/
// Втори опит - покрива всички тестове.
int num01 = n.charAt(0) - '0';
int num02 = n.charAt(1) - '0';
int num03 = n.charAt(2) - '0';
int result = -1;
result = Math.max(result, num01 + num02 + num03);
result = Math.max(result, num01 + num02 * num03);
result = Math.max(result, num01 * num02 + num03);
result = Math.max(result, num01 * num02 * num03);
System.out.println(result);
}
}
|
package fun.witt.lambda;
import java.util.function.Function;
/**
* @author witt
* @fileName MyMoney
* @date 2018/8/18 13:27
* @description
* @history <author> <time> <version> <desc>
*/
public class MyMoney {
private final int money;
public MyMoney(int money) {
this.money = money;
}
public void printMoney(MoneyFormat moneyFormat) {
System.out.println("存款: " + moneyFormat.format(this.money));
}
/**
* @Description: 函数接口的使用
* @Param: [moneyFormat]
* @return: void
* @Date: 2018/8/18
*/
public void printMoney(Function<Integer, String> moneyFormat) {
System.out.println("存款: " + moneyFormat.apply(this.money));
}
}
interface MoneyFormat{
String format(int money);
} |
package com.example.billage.backend.api;
import android.content.SharedPreferences;
import android.util.Log;
import com.example.billage.backend.api.data.UserAccount;
import com.example.billage.backend.common.AppData;
import com.example.billage.backend.common.Utils;
import com.example.billage.backend.http.ApiCallAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class UserInfo {
public static void request_userInfo(){
String accessToken = AppData.getPref().getString("access_token","");
ArrayList<String> user_accounts = new ArrayList<String>();
HashMap<String, String> paramMap = new HashMap<>();
//요청시 필요한 parameters
paramMap.put("user_seq_no", AppData.getPref().getString("user_seq_no",""));//사용자 일련번호
ApiCallAdapter.getInstance()
.userMe("Bearer" + accessToken, paramMap)
.enqueue(new Callback<Map>() {
@Override
public void onResponse(@NotNull Call<Map> call, @NotNull Response<Map> response) {
if(response.isSuccessful()){
try {
String responseJson = new Gson().toJson(response.body());
JsonObject json = new JsonParser().parse(responseJson).getAsJsonObject();
//사용자 이름
JsonElement name_elem = json.get("user_name");
String name = name_elem.getAsString();
//등록된 계좌 수
JsonElement acc_count_elem = json.get("res_cnt");
String acc_count = acc_count_elem.getAsString();
//등록된 계좌 목록
JsonArray acc_list = json.getAsJsonArray("res_list");
for(int i = 0 ; i<acc_list.size(); i++){
JsonObject acc = acc_list.get(i).getAsJsonObject();
JsonElement acc_fintechNum = acc.get("fintech_use_num");
JsonElement acc_bankCode = acc.get("bank_code_std");
JsonElement acc_bankName = acc.get("bank_name");
JsonElement acc_num = acc.get("account_num_masked");
Log.d("acc_info",acc_fintechNum.getAsString()+" "+acc_bankCode.getAsString()+" "+acc_bankName.getAsString()+" "+acc_num.getAsString());
user_accounts.add(acc_fintechNum.getAsString()+","+acc_bankCode.getAsString()+","+acc_bankName.getAsString()+","+acc_num.getAsString());
}
//앱데이터에 저장
SharedPreferences.Editor editor = AppData.getPref().edit();
editor.putString("user_name",name);
JSONArray tmp = new JSONArray();
for (int i=0; i<user_accounts.size(); i++){
tmp.put(user_accounts.get(i));
}
if (!user_accounts.isEmpty()) {
editor.putString("user_accounts", tmp.toString());
} else {
editor.putString("user_accounts", null);
}
editor.apply();
} catch (Exception e){
Log.d("user_info_err", String.valueOf(e));
}
}
}
@Override
public void onFailure(@NotNull Call<Map> call, @NotNull Throwable t) {
System.out.println("통신실패: 서버 접속에 실패하였습니다.");
}
});
}
}
|
package edu.nyu.xyz.parser;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class GlassDoorDataParser {
public static void main(String[] args) {
String inputFilePath =
"/Users/longyang/git/RealTimeBigData/data/glassdoor/company/glassdoor.json";
String companyNamesPositionsOuputFilePath =
"/Users/longyang/git/RealTimeBigData/data/glassdoor//CompanyIndustry.json";
String companyAllPositionsOutputFilePath =
"/Users/longyang/git/RealTimeBigData/data/glassdoor/company_all_position.json";
String industry = "Information Technology";
String companyPositionSalaryOutputFilePath =
"/Users/longyang/git/RealTimeBigData/data/glassdoor/companyPositionSalary.json";
getCompanyNamesAndPosition(inputFilePath, companyNamesPositionsOuputFilePath,
companyAllPositionsOutputFilePath, ParserConstants.ALL);
// companyPositionSalary(companyNamesPositionsOuputFilePath, companyPositionSalaryOutputFilePath);
}
/**
* Method used to parse the input JSON typed file and get only company names and their
* regarding position and salaries.
* @param inputFilePath input file path, and the input file format is as following:
* [
* {
* "name": "Google",
* "info":
* {
* "satisfaction": {},
* "ceo": {},
* "meta": {},
* "salary":
* [
* {
* "position": "SDE",
* "range": [100000, 110000]
* },
* {
* "position": "QA",
* "range": [80000, 100000]
* }
* ]
* }
* }
* ]
* @param outputFilePath output file path, and the output file format is as following:
* [
* {
* "name": "Google",
* "position_number": 20,
* "position": // make it easy for do people search on LinkedIn.
* [
* "SDE",
* "QA"
* ],
* "position_range":
* {
* "SDE": [100000, 110000],
* "QA": [80000, 100000]
* }
* }
* ]
* @param outputPositionFilePath output file path for all position data.
* @param industry determine which industry we are focusing on, and it can be "All" which means
* you want all industry's data.
*/
@SuppressWarnings("unchecked")
public static void getCompanyNamesAndPosition(String inputFilePath, String outputFilePath,
String outputPositionFilePath, String industry) {
if( inputFilePath == null || inputFilePath.isEmpty() ||
outputFilePath == null || outputFilePath.isEmpty() ||
industry == null || industry.isEmpty()) {
throw new IllegalArgumentException("inputFilePath, outputFilePath and industry "
+ "should not be null or empty!");
}
JSONParser parser = new JSONParser();
try {
int illegalData = 0;
FileReader inputFile = new FileReader(inputFilePath);
Object object = parser.parse(inputFile);
JSONArray inputJsonArray = (JSONArray) object;
JSONArray outputJsonArray = new JSONArray();
// JSONArray allPositionsArray = new JSONArray();
// Set<String> allPositionsSet = new HashSet<String>();
for(int i = 0; i < inputJsonArray.size(); i++) {
// 1. Get all the information from "inputJsonObject"
JSONObject inputJsonObject = (JSONObject) inputJsonArray.get(i);
String name = (String) inputJsonObject.get(ParserConstants.NAME);
System.out.println("Number " + i + ": " + name + ": processing...");
JSONObject info = new JSONObject();
if( inputJsonObject.get(ParserConstants.INFO) instanceof JSONObject) {
info = (JSONObject) inputJsonObject.get(ParserConstants.INFO);
} else {
continue;
}
JSONObject info_meta = (JSONObject) info.get(ParserConstants.META);
String info_meta_industry = (String) info_meta.get(ParserConstants.INPUT_INDUSTRY);
// if( !industry.equalsIgnoreCase(ParserConstants.ALL) &&
// !industry.equalsIgnoreCase(info_meta_industry)) {
// continue;
// }
JSONArray info_salary = (JSONArray) info.get(ParserConstants.SALARY);
// 2. Construct output object
JSONObject outputJsonObject = new JSONObject();
outputJsonObject.put(ParserConstants.COMPANY, name.toLowerCase());
if (info_meta_industry == null || info_meta_industry.isEmpty()) {
continue;
} else {
outputJsonObject.put(ParserConstants.INDUSTRY, info_meta_industry.toLowerCase());
}
if(info_salary.size() <= 0) {
illegalData = illegalData + 1;
continue;
}
// outputJsonObject.put(ParserConstants.POSITION_NUMBER, info_salary.size());
// JSONArray name_position = new JSONArray();
// JSONObject position_range = new JSONObject();
// for(int j = 0; j < info_salary.size(); j++) {
// JSONObject infoSalaryObject = (JSONObject) info_salary.get(j);
// String info_salary_position = (String) infoSalaryObject.get(ParserConstants.POSITION);
// allPositionsSet.add(info_salary_position);
// String positionStr = info_salary_position;
// name_position.add(positionStr);
// JSONArray info_salary_range = (JSONArray) infoSalaryObject.get(ParserConstants.RANGE);
// position_range.put(positionStr, info_salary_range);
// }
// outputJsonObject.put(ParserConstants.POSITION, name_position);
// outputJsonObject.put(ParserConstants.POSITION_RANGE, position_range);
outputJsonArray.add(outputJsonObject);
}
System.out.println("Done! And here comes the statistics: ");
System.out.println("Illegal Data Number: " + illegalData);
System.out.println("Total result company number: " + outputJsonArray.size());
// 3.1. Output all positions data into certain file.
// allPositionsArray.addAll(allPositionsSet);
// String niceFormatJsonAllPositions = JsonWriter.formatJson(allPositionsArray.toJSONString());
String companyIndustry = ParserUtil.getSelfDefinedJSONString(outputJsonArray);
FileWriter allPositionsFileWriter = new FileWriter(outputFilePath);
System.out.println(companyIndustry);
System.out.println(outputFilePath);
allPositionsFileWriter.write(companyIndustry);
allPositionsFileWriter.flush();
allPositionsFileWriter.close();
inputFile.close();
// 3.2. Output all companies data into certain file.
// String niceFormatJson = JsonWriter.formatJson(outputJsonArray.toJSONString());
// FileWriter fileWriter = new FileWriter(outputFilePath);
// inputFile.close();
// fileWriter.write(niceFormatJson);
// fileWriter.flush();
// fileWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static void companyPositionSalary(String inputFilePath, String outputFilePath) {
if (inputFilePath == null || inputFilePath.isEmpty() ||
outputFilePath == null || outputFilePath.isEmpty()) {
throw new IllegalArgumentException("InputFilePath and OutputFilePath should not be"
+ "null or empty!");
}
JSONParser parser = new JSONParser();
try {
FileReader inputFile = new FileReader(inputFilePath);
Object object = parser.parse(inputFile);
JSONArray inputJsonArray = (JSONArray) object;
JSONArray outputJsonArray = new JSONArray();
for (int i = 0; i < inputJsonArray.size(); i++) {
// 1. Get all the information from the input file
JSONObject inputObject = (JSONObject) inputJsonArray.get(i);
String companyName = (String) inputObject.get(ParserConstants.COMPANY);
JSONArray positions = (JSONArray) inputObject.get(ParserConstants.POSITION);
JSONObject salaryRanges = (JSONObject) inputObject.get(ParserConstants.POSITION_RANGE);
// 2. Generate the output to store into OutputFilePath
for (int j = 0; j < positions.size(); j++) {
String position = (String) positions.get(j);
JSONArray salaryRange = (JSONArray) salaryRanges.get(position);
int salaryLow = (int)((long) salaryRange.get(0));
int salaryHigh = (int)((long) salaryRange.get(1));
int salary = (salaryLow + salaryHigh) >>> 1;
JSONObject outputObject = new JSONObject();
outputObject.put(ParserConstants.COMPANY, companyName);
outputObject.put(ParserConstants.POSITION, position);
outputObject.put(ParserConstants.SALARY, salary);
outputJsonArray.add(outputObject);
}
}
System.out.println("Done! And here comes the statistics: ");
System.out.println("Total result company number: " + outputJsonArray.size());
String companyPositionSalaryStr = ParserUtil.getSelfDefinedJSONString(outputJsonArray);
FileWriter writer = new FileWriter(outputFilePath);
writer.write(companyPositionSalaryStr);
writer.flush();
writer.close();
inputFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
|
package crdhn.sis.http.service;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import crdhn.sis.configuration.Configuration;
import crdhn.sis.imagescaler.ImageWorker;
import java.io.File;
public class WebServer {
private static final Logger logger = LoggerFactory.getLogger(WebServer.class);
public void start() throws Exception {
Server server = new Server();
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMinThreads(100);
threadPool.setMaxThreads(2000);
server.setThreadPool(threadPool);
logger.info("Listening on port {}", Configuration.SERVICE_PORT);
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(Configuration.SERVICE_PORT);
connector.setMaxIdleTime(100000);
connector.setConfidentialPort(8443);
connector.setStatsOn(false);
connector.setLowResourcesConnections(20000);
connector.setLowResourcesMaxIdleTime(5000);
server.setConnectors(new Connector[]{connector});
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping("crdhn.sis.http.servlet.UploadImageController", Configuration.UPLOADIMAGE_CONTROLLER_PATH);
server.setStopAtShutdown(true);
server.setSendServerVersion(true);
for (int i = 0; i < Configuration.number_worker; i++) {
new ImageWorker(i).start();
}
File directoryOriginal = new File(Configuration.HOME_PATH + File.separator + Configuration.ORIGINAL_IMAGE_DIRECTORY);
File directoryScale = new File(Configuration.HOME_PATH + File.separator + Configuration.SCALED_IMAGE_DIRECTORY);
if (!directoryOriginal.exists()) {
directoryOriginal.mkdirs();
System.out.println("create folder success!" + Configuration.ORIGINAL_IMAGE_DIRECTORY);
}
if (!directoryScale.exists()) {
directoryScale.mkdirs();
System.out.println("Configuration.SCALED_IMAGE_DIRECTORY=" + Configuration.SCALED_IMAGE_DIRECTORY);
}
server.start();
server.join();
}
}
|
package com.cryfish.myalomatika;
import com.cryfish.myalomatika.model.MentalNumber;
import com.cryfish.myalomatika.model.MentalRandom;
import org.apache.log4j.Logger;
import java.util.ArrayList;
public class NumbersGenerator implements Constants{
private static final Logger log = Logger.getLogger(NumbersGenerator.class);
public static ArrayList<MentalNumber> generate (int level, int digit, int count, boolean combo) {
ArrayList<MentalNumber> numbers = new ArrayList<>();
int result = 0;
for (int i = 1; i <= count; i++) {
log.debug("");
log.debug("iterator: " + i);
log.debug("result: " + result);
int randomValue = MentalRandom.getRandomValue(combo, level, digit, result);
String randomColor = MentalRandom.getRandomColor(colors.size());
result += randomValue;
String value = (randomValue > 0) ? "+" + randomValue : Integer.toString(randomValue);
log.debug("value: " + value);
log.debug("color: " + randomColor);
numbers.add(new MentalNumber(
value,
randomColor
));
}
return numbers;
}
public static String[] generateJson (int level, int digit, int count, boolean combo) {
return generate(level, digit, count, combo).stream().map(MentalNumber::toJson).toArray(String[]::new);
}
}
|
package boj4673;
public class Main1 {
// 다른 사람 풀이
public static void main(String[] args) {
// TODO Auto-generated method stub
// 자료구조는 제약이 적용된 상태가 아닌 조건으로 주어진 그대로로 만든다.
// 제약은 조건 및 반복으로 구현한다.
int size = 10001;
boolean[] isNotSelfNumber = new boolean[size];
for(int i=1; i<isNotSelfNumber.length;i++) {
int result = d(i);
if(result < size) {
isNotSelfNumber[result]= true;
}
}
for(int i=1; i < isNotSelfNumber.length; i++) {
if(isNotSelfNumber[i]==false) {
System.out.println(i);
}
}
}
public static int d(int data) {
int result = data;
while(data > 0) {
result += data%10;
data /= 10;
}
return result;
}
}
|
package org.sankozi.rogueland.model;
import java.util.EnumMap;
/**
* Base of implementation of Actor class
* @author sankozi
*/
public abstract class AbstractActor extends AbstractDestroyable implements Actor{
private final EnumMap<Actor.Param, Float> params = new EnumMap<>(Actor.Param.class);
public AbstractActor(int durability) {
super(durability);
}
@Override
public float actorParam(Actor.Param param) {
Float ret = params.get(param);
if(ret == null){
return 0f;
} else {
return ret.floatValue();
}
}
@Override
public void setActorParam(Actor.Param param, float value) {
params.put(param, value);
}
}
|
package de.mufl.sandbox.osm.api.data;
import java.io.Serializable;
import java.util.ArrayList;
/**
* OSM-Element für Wege und Flächen
*
* @author Florian Müller
*/
public class Way implements Serializable{
/**
* Serilization ID
*/
private static final long serialVersionUID = -3118791757949287671L;
/**
* Id des Ways
*/
private int id = -1;
/**
* IDs der Nodes die diesen Way bilden
*/
private ArrayList<Integer> nd = new ArrayList<Integer>();
/**
* Tags des Ways
*/
private ArrayList<Tag> tags = new ArrayList<Tag>();
/**
* Fügt die ID eines Nodes dem Way hinzu
*
* @param ref ID eines Nodes
* @return War einfügen erfolgreich
*/
public boolean addNode(int ref){
return nd.add(ref);
}
/**
* Fügt die Tag dem Way hinzu
*
* @param ref neuer Tag
* @return War einfügen erfolgreich
*/
public boolean addTag(Tag tag){
return tags.add(tag);
}
/**
* @return ID des Ways
*/
public int getId() {
return id;
}
/**
* @return Liste von IDs der zum Way gehörenden Nodes
*/
public ArrayList<Integer> getNd() {
return nd;
}
/**
* @return Liste der zum Way gehörenden Tags
*/
public ArrayList<Tag> getTags() {
return tags;
}
/**
* @return Ist der Way eine Fläche?
*/
public boolean isArea(){
if(null != nd && 2 < nd.size())
return nd.get(0) == nd.get(nd.size()-1);
return false;
}
/**
* Setzt die ID des Ways
*
* @param id ID des Ways (>0)
*/
public void setId(int id){
if(0L < id)
this.id = id;
}
}
|
package com.tencent.mm.plugin.product.c;
import com.tencent.mm.bk.a;
import java.util.LinkedList;
public final class f extends a {
public j lRN;
public String lRO;
protected final int a(int i, Object... objArr) {
int fS;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
if (this.lRN != null) {
aVar.fV(1, this.lRN.boi());
this.lRN.a(aVar);
}
if (this.lRO == null) {
return 0;
}
aVar.g(2, this.lRO);
return 0;
} else if (i == 1) {
if (this.lRN != null) {
fS = f.a.a.a.fS(1, this.lRN.boi()) + 0;
} else {
fS = 0;
}
if (this.lRO != null) {
fS += f.a.a.b.b.a.h(2, this.lRO);
}
return fS;
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fS = a.a(aVar2); fS > 0; fS = a.a(aVar2)) {
if (!super.a(aVar2, this, fS)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
f fVar = (f) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
switch (intValue) {
case 1:
LinkedList IC = aVar3.IC(intValue);
int size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
byte[] bArr = (byte[]) IC.get(intValue);
j jVar = new j();
f.a.a.a.a aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (boolean z = true; z; z = jVar.a(aVar4, jVar, a.a(aVar4))) {
}
fVar.lRN = jVar;
}
return 0;
case 2:
fVar.lRO = aVar3.vHC.readString();
return 0;
default:
return -1;
}
}
}
}
|
package p4_group_8_repo.Game_button;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import p4_group_8_repo.Game_scene.MyStage;
/**
* Class of Button (START animation timer)
* @author Jun Yuan
*
*/
public class Resume_butt{
private String image_link = "/graphic_animation/play_button.png";
private Button button;
private int button_size;
private int x_position;
private int y_position;
/**
* Construct an instance of Resume_butt
* @param background is the container for the scene
* @param button_size of the resume button
* @param x_position of the button
* @param y_position of the button
*/
public Resume_butt(MyStage background, int button_size, int x_position, int y_position) {
this.button_size = button_size;
this.x_position = x_position;
this.y_position = y_position;
button = new Button();
design_button();
button.setStyle("-fx-background-color: transparent;");
ObservableList animation_list = background.getChildren();
EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
background.resume_timer();
}};
button.setOnAction(event);
}
/**
* Design and settings of button
*/
public void design_button() {
Image image = new Image(image_link, button_size, button_size - 20, true, true);
ImageView start_image = new ImageView(image);
button.setGraphic(start_image);
button.setTranslateX(x_position);
button.setTranslateY(y_position);
//Button Shadow Effect
DropShadow shadow = new DropShadow();
//Adding the shadow when the mouse cursor is on
button.addEventHandler(MouseEvent.MOUSE_ENTERED,
new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent e) {
button.setEffect(shadow);
}
});
//Removing the shadow when the mouse cursor is off
button.addEventHandler(MouseEvent.MOUSE_EXITED,
new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent e) {
button.setEffect(null);
}
});
}
/**
* Method to get Button
* @return button (Start the animation timer)
*/
public Button getButton() {
return button;
}
}
|
package com.java.abs_fact;
public class Lion implements ILandAnimal {
@Override
public IAnimal print() {
IAnimal animal=new Lion();
animal.disp();
return animal;
}
@Override
public void disp() {
System.out.println("lion class");
}
}
|
/**
* original(c) zhuoyan company
* projectName: java-design-pattern
* fileName: ProductEnums.java
* packageName: cn.zy.pattern.responsibility
* date: 2018-12-18 23:23
* history:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package cn.zy.pattern.responsibility;
/**
* @version: V1.0
* @author: ending
* @className: ProductEnums
* @packageName: cn.zy.pattern.responsibility
* @description: 判断条件
* @data: 2018-12-18 23:23
**/
public enum ProductEnums {
VIP,
RECHARGE,
COMPUTER,
PHONE
}
|
package com.podarbetweenus.Activities;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.podarbetweenus.BetweenUsConstant.Constant;
import com.podarbetweenus.Entity.LoginDetails;
import com.podarbetweenus.R;
import com.podarbetweenus.Services.DataFetchService;
import com.podarbetweenus.Utility.AppController;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Administrator on 10/13/2015.
*/
public class DetailMessageActivity extends Activity implements View.OnClickListener{
String detail_msg,date,sender_name,attachement_path,attachment_name,attachment,message_subject,reply_msg,toUslId,isStudentresource,
clt_id,usl_id,msd_ID,board_name,school_name,pmuId,versionName,announcementCount,behaviourCount,message,msgSubject,encodedUrl,downloadfilename,newFile;
String serverAddress = "betweenus.in/Uploads/Messages";
String ReplyMessageMethodName = "ReplyToMessage";
String UpdateMessageStatusMethodName = "UpdateMessageReadStatus";
int versionCode;
//ImageView
ImageView sender_img,img_attachment,img_send;
//TextView
TextView tv_date,tv_detail_msg,tv_message_subject;
//LinearLayout
LinearLayout lay_back_investment,ll_send_message_layout;
//Relative Layout
RelativeLayout rl_header;
//EditText
EditText ed_enter_msg;
//ProgressDialog
ProgressDialog progressDialog;
//LayoutEntities
HeaderControler header;
DataFetchService dft;
LoginDetails login_details;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.details_message);
findViews();
getIntentData();
init();
ed_enter_msg.setSelection(0);
if(LoginActivity.get_name(DetailMessageActivity.this).equalsIgnoreCase("6"))
{
}
if(AppController.SendMessageLayout.equalsIgnoreCase("true")){
ll_send_message_layout.setVisibility(View.VISIBLE);
}
else {
ll_send_message_layout.setVisibility(View.GONE);
}
setUIData();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//Webservice Call for UpdateMessageStatus
callWebserviceUpdateMessageStatus(pmuId, usl_id, clt_id);
}
private void callWebserviceUpdateMessageStatus(String pmuId, String usl_id, String clt_id) {
try{
if(dft.isInternetOn()==true) {
if (!progressDialog.isShowing()) {
progressDialog.show();
}
}
else{
progressDialog.dismiss();
}
dft.getUpdatdStatusMessages(pmuId, usl_id, clt_id, UpdateMessageStatusMethodName, Request.Method.POST,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
login_details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class);
if (login_details.Status.equalsIgnoreCase("1")) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
Log.d("LoginActivity", "ERROR.._---" + error.getCause());
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
private void setUIData() {
tv_detail_msg.setText(detail_msg);
/* String date_array[] = date.split(" ");
String date_format = date_array[0];
Log.e("DATE:- ", date_format);
String inputPattern = "dd/MM/yyyy";
String outputPattern = "dd-MMM-yyyy";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = null;
String formatted_date = null;
try {
date = inputFormat.parse(date_format);
formatted_date = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}*/
tv_date.setText(date);
tv_message_subject.setText(message_subject);
if(attachement_path.equalsIgnoreCase("0")|| attachement_path.equalsIgnoreCase(""))
{
img_attachment.setVisibility(View.GONE);
}
else {
img_attachment.setVisibility(View.VISIBLE);
}
}
private void getIntentData() {
try {
Intent intent = getIntent();
detail_msg = intent.getStringExtra("Message");
date = intent.getStringExtra("Date");
sender_name = intent.getStringExtra("Sender Name");
message_subject = intent.getStringExtra("Message Subject");
school_name = intent.getStringExtra("School_name");
toUslId = intent.getStringExtra("ToUslId");
clt_id = intent.getStringExtra("clt_id");
msd_ID = intent.getStringExtra("msd_ID");
usl_id = intent.getStringExtra("usl_id");
pmuId = intent.getStringExtra("PmuId");
board_name = intent.getStringExtra("board_name");
attachement_path = intent.getStringExtra("Attachment Path");
attachment_name = intent.getStringExtra("Attachment Name");
attachment = attachement_path.replace("C:\\inetpub\\", "http:\\");
announcementCount = intent.getStringExtra("annpuncement_count");
behaviourCount = intent.getStringExtra("behaviour_count");
isStudentresource = intent.getStringExtra("isStudentResource");
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
AppController.Board_name = board_name;
versionName = intent.getStringExtra("version_name");
versionCode = intent.getIntExtra("version_code", 0);
AppController.versionName = versionName;
AppController.versionCode = versionCode;
}
catch (Exception e){
e.printStackTrace();
}
}
private void init() {
header = new HeaderControler(this,true,false,sender_name);
lay_back_investment.setOnClickListener(this);
img_attachment.setOnClickListener(this);
img_send.setOnClickListener(this);
progressDialog = Constant.getProgressDialog(this);
login_details = new LoginDetails();
dft = new DataFetchService(this);
rl_header.setBackgroundColor(Color.parseColor("#00829C"));
lay_back_investment.setBackgroundColor(Color.parseColor("#00829C"));
}
private void findViews(){
//TextView
tv_detail_msg = (TextView) findViewById(R.id.tv_detail_msg);
tv_date = (TextView) findViewById(R.id.tv_date);
tv_message_subject = (TextView) findViewById(R.id.tv_message_subject);
//ImageView
sender_img = (ImageView) findViewById(R.id.sender_img);
img_attachment = (ImageView) findViewById(R.id.img_attachment);
img_send = (ImageView) findViewById(R.id.img_send);
//Linear Layout
lay_back_investment = (LinearLayout) findViewById(R.id.lay_back_investment);
ll_send_message_layout = (LinearLayout)findViewById(R.id.ll_send_message_layout);
//Relative Layout
rl_header = (RelativeLayout) findViewById(R.id.rl_header);
//Edit Text
ed_enter_msg = (EditText) findViewById(R.id.ed_enter_msg);
}
@Override
public void onClick(View v) {
if(v==lay_back_investment)
{
AppController.ListClicked = "true";
super.onBackPressed();
finish();
}
else if(v==img_attachment){
try {
//download file
try {
String host = "http://" + serverAddress + "/";
downloadfilename = attachment.substring(attachment.lastIndexOf('/') + 1);
Log.e("filename", downloadfilename);
newFile = host+downloadfilename;
encodedUrl = host + URLEncoder.encode(downloadfilename, "utf-8");
Log.e("enco url", encodedUrl);
} catch (Exception e1) {
e1.printStackTrace();
}
new DownloadFileFromURL().execute(newFile);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(newFile));
startActivity(i);
}
catch (Exception e){
e.printStackTrace();
}
}
else if(v==img_send){
InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
sendMessage();
ed_enter_msg.setText("");
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
// showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/"+downloadfilename);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
progressDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
Toast.makeText(DetailMessageActivity.this, "Downloading Completed", Toast.LENGTH_SHORT).show();
}
}
private void sendMessage() {
message = ed_enter_msg.getText().toString();
reply_msg = message+"\n\n"+"--Old Message--"+date+"\n"+detail_msg;
if(message_subject.contains("Re: ")){
msgSubject = message_subject;
}
else {
msgSubject = "Re: "+message_subject;
}
//Webservice call for Reply Message
if(message.equalsIgnoreCase("")){
Constant.showOkPopup(this, "Please Enter Message", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
else {
callReplyMessageswebservcie(clt_id, msgSubject, reply_msg, usl_id, msd_ID, toUslId);
}
}
private void callReplyMessageswebservcie(String clt_id,String message_subject,String reply_msg,String usl_id,String msd_ID,String toUslId) {
if(dft.isInternetOn()==true) {
if (!progressDialog.isShowing()) {
progressDialog.show();
}
}
else{
progressDialog.dismiss();
}
dft.getReplyMessage(clt_id, message_subject, reply_msg, usl_id, msd_ID, toUslId, ReplyMessageMethodName, Request.Method.POST,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
login_details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class);
if (login_details.Status.equalsIgnoreCase("1")) {
Constant.showOkPopup(DetailMessageActivity.this, login_details.StatusMsg, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(DetailMessageActivity.this, DashboardActivity.class);
Intent intent = getIntent();
String clt_id = intent.getStringExtra("clt_id");
String msd_ID = intent.getStringExtra("msd_ID");
String usl_id = intent.getStringExtra("usl_id");
school_name = intent.getStringExtra("School_name");
board_name = intent.getStringExtra("board_name");
versionName = intent.getStringExtra("version_name");
versionCode = intent.getIntExtra("version_code", 0);
isStudentresource = intent.getStringExtra("isStudentResource");
announcementCount = intent.getStringExtra("annpuncement_count");
behaviourCount = intent.getStringExtra("behaviour_count");
AppController.versionName = versionName;
AppController.versionCode = versionCode;
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
i.putExtra("clt_id", AppController.clt_id);
i.putExtra("msd_ID", AppController.msd_ID);
i.putExtra("usl_id", AppController.usl_id);
i.putExtra("board_name", AppController.Board_name);
i.putExtra("School_name", AppController.school_name);
i.putExtra("version_name", AppController.versionName);
i.putExtra("version_code", AppController.versionCode);
i.putExtra("annpuncement_count", announcementCount);
i.putExtra("behaviour_count", behaviourCount);
i.putExtra("isStudentResource", isStudentresource);
startActivity(i);
finish();
dialog.dismiss();
}
});
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
} else if (login_details.Status.equalsIgnoreCase("0")) {
Constant.showOkPopup(DetailMessageActivity.this, login_details.StatusMsg, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
Log.d("DetailMessageActivity", "ERROR.._---" + error.getCause());
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
AppController.ListClicked = "true";
AppController.school_name = school_name;
AppController.Board_name = board_name;
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
finish();
}
}
|
package edu.mtholyoke.cs341bd.p0;
import java.util. *;
public class Card implements Comparable<Card>{
private Integer order; //1 or 14
private String suit;
private Integer cost; //cost of A is 15
public Card(Integer c, String s, Integer o )
{
cost=c;
suit=s;
order=o;
}
public Integer getOrder() //1 or 14
{
return order;
}
public Integer getCost()
{
return cost;
}
public String getSuit()
{
return suit;
}
/** print string form of card**/
/** public String toString()
{
StringBuilder s= new StringBuilder(""); //string builder with empty string
s.append(this.cost);
s.append(this.suit);
s.append(this.order);
return s.toString();
}
**/
//rewrote toString
public String toString()
{
StringBuilder s= new StringBuilder("");
Integer cost= this.cost;
String suit=this.suit;
Integer order= this.order;
if(order==1)
{
s.append("A");
}
else if(order==11)
{
s.append("J");
}
else if(order == 12)
{
s.append("Q");
}
else if(order==13)
{
s.append("K");
}
else
{
s.append(order);
}
s.append(suit);
return s.toString();
}
/** compared to according to order**/
public int compareTo(Card b)
{
if(this.order>b.getOrder())
{
return 1;
}
else if( this.order.equals(b.getOrder()))
{
return 0;
}
else
{
return -1;
}
}
public boolean isRunPiece(Card a, Card b)
{
return true;
}
@Override
public boolean equals(Object card)
{
if(this.getOrder().equals(((Card)card).getOrder()) && this.getCost().equals(((Card)card).getCost()) && this.getSuit().equals(((Card)card).getSuit()))
{
return true;
}
return false;
}
public static void main(String[] args)
{
Card card1= new Card(1, "H", 1);
Card card2= new Card(14, "H", 14);
Card card3= new Card(4, "a", 4);
Card card4= new Card(5, "c", 5);
ArrayList<Card> listOfCards= new ArrayList<Card>();
listOfCards.add(card3);
listOfCards.add(card1);
listOfCards.add(card4);
listOfCards.add(card2);
Collections.sort(listOfCards); //this works it can actually be sorted
int l= listOfCards.size();
for(Card c:listOfCards)
{
c.toString();
}
if(listOfCards.contains(new Card(1,"H",1)))
{
listOfCards.remove(new Card(1,"H",1));
}
for(Card c:listOfCards)
{
c.toString();
}
}
//comparator by suit
//by order
//one deck of cards
//sort according to suit
//sort according to order
//have a collection of cards hashset ....
//sorting things
//runs one suite at a time
//hashmap of suite to list of cards
//don't write a sort function
//Collections.sort(list must be comparable)
}
|
package SpritesheetRender;
//<!> ATENÇÃO esse código foi alterado com base no arquivo em GraficosComJava (Java Project) > RenderizandoStrings (package) > Game (class)
//Se deseja ver os comentários desse código, vá para aquela class
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable{
public static JFrame frame;
private boolean isRunning;
private final int WIDTH = 160;
private final int HEIGHT = 120;
private final int SCALE = 4;
private Thread thread;
private int x = 0;
private BufferedImage image;
private Spritesheet sheet;
private BufferedImage player;
public synchronized void start() {
thread = new Thread(this);
isRunning = true;
thread.start();
}
public synchronized void stop() {
isRunning = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Game() {
sheet = new Spritesheet("/spritesheet01.png"); //criamos uma variável objeto que armazena o spritesheet selecionado
player = sheet.getSprite(0, 0, 16, 16); //temos uma variável objeto que armazena a imagem do player (recortada do spritesheet sheet)
setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
initFrame();
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
}
public void initFrame() {
frame = new JFrame("My First Game");
frame.add(this);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) { //<!!!> Main
Game game = new Game();
game.start();
}
public void tick() {
x++; //incrementa o movimento x de alguns elementos
//logo, quando a tela atualizar, a posição será diferente, causando o efeito de movimento (animação)
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs ==null) {
this.createBufferStrategy(3);
return;
}
Graphics g = image.getGraphics();
g.setColor(new Color(100,12,118));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.CYAN);
g.fillRoundRect(20, 20, 60, 60, 20, 20);
g.fillOval(100, 10, 50, 50);
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 10));
g.drawString("Fala meu consagrado!", 30, 95);
g.setColor(Color.GREEN);
g.fillRoundRect(25, 25, 18, 18, 5, 5);
/************/
/*<!> DESENHANDO SPRITE DO PLAYER*/
g.drawImage(player, 38, 38, null);
/* drawImage: 1 - Qual imagem você quer colocar
2 - Posição x na tela
3 - Posição y na tela
4 - ?
*/
/*EXTRAS: DESENHANDO LINHAS*/
g.setColor(Color.MAGENTA);
g.drawLine(50, 50, x, 64);
/************/
g.drawImage(player, x - 2, 52, null);
//podendo ser colocado quantas vezes quiser
//O personagem aparenta estar com o efeito de segurar a corda por conta do -2 colocado, sem ele o efeito
//não ocorre corretamente por o sprite do player ter 2px de camada alfa entre o começo da box e a mão
g.dispose(); //comando que visa a performance gráfica do jogo
g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, WIDTH * SCALE, HEIGHT * SCALE, null);
bs.show();
}
@Override
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
int frames = 0;
double timer = System.currentTimeMillis();
double delta = 0;
while(isRunning) {
long now = System.nanoTime();
delta+= (now - lastTime) / ns;
lastTime = now;
if(delta>=1) {
tick();
render();
frames++;
delta--;
}
if(System.currentTimeMillis() - timer >= 1000) {
System.out.println("FPS: " + frames);
frames = 0;
timer += 1000;
}
}
stop();
}
}
|
/****
Copyright (c) 2015, Skyley Networks, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Skyley Networks, Inc. nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Skyley Networks, Inc. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
****/
package com.skyley.skstack_ip.api.skcommands;
/**
* SKUDPPORTコマンドに対応したクラス、SKCommandを継承
* @author Skyley Networks, Inc.
* @version 0.1
*/
public class SKUdpPort extends SKCommand {
/** UDPハンドル番号 */
private byte handle;
/** 待ち受けポート番号 */
private int port;
/**
* コンストラクタ
* @param handle UDPハンドル番号
* @param port 待ち受けポート番号
*/
public SKUdpPort(byte handle, int port) {
this.handle = handle;
this.port = port;
}
/**
* 引数チェック
*/
@Override
public boolean checkArgs() {
// TODO 自動生成されたメソッド・スタブ
if (handle < 1 || handle > 6) {
return false;
}
if (port < 0 || port > 0xFFFF) {
return false;
}
return true;
}
/**
* コマンド文字列組み立て
*/
@Override
public void buildCommand() {
// TODO 自動生成されたメソッド・スタブ
int hdl = Byte.toUnsignedInt(handle);
commandString = "SKUDPPORT " + Integer.toHexString(hdl) + " " + Integer.toHexString(port) + "\r\n";
}
}
|
package com.tencent.mm.plugin.sns.ui;
import com.tencent.mm.plugin.sns.c.a;
class bb$14 implements Runnable {
final /* synthetic */ bb ogl;
bb$14(bb bbVar) {
this.ogl = bbVar;
}
public final void run() {
a.ezo.vn();
}
}
|
package yand.service;
import java.util.Map;
public interface LoginService {
public Map<String, Object> queryUserBean(Map<String, Object> paramMap);
}
|
package com.lubarov.daniel.wedding.rsvp;
import com.lubarov.daniel.data.option.Option;
import com.lubarov.daniel.data.order.AbstractOrdering;
import com.lubarov.daniel.data.order.Ordering;
import com.lubarov.daniel.data.order.Relation;
import com.lubarov.daniel.data.unit.Instant;
public class RSVP {
public static final Ordering<RSVP> ASCENDING_CREATED_AT_ORDERING =
new AbstractOrdering<RSVP>() {
@Override
public Relation compare(RSVP a, RSVP b) {
return Instant.ASCENDING_ORDERING.compare(a.createdAt, b.createdAt);
}
};
public static final class Builder {
private Option<String> uuid = Option.none();
private Option<Instant> createdAt = Option.none();
private Option<String> name = Option.none();
private Option<String> email = Option.none();
private Option<Boolean> attending = Option.none();
private Option<String> entree = Option.none();
private Option<Boolean> guestAttending = Option.none();
private Option<String> guestName = Option.none();
private Option<String> guestEntree = Option.none();
private Option<String> notes = Option.none();
public Builder setUUID(String uuid) {
this.uuid = Option.some(uuid);
return this;
}
public Builder setCreatedAt(Instant createdAt) {
this.createdAt = Option.some(createdAt);
return this;
}
public Builder setName(String name) {
this.name = Option.some(name);
return this;
}
public Builder setEmail(String email) {
this.email = Option.some(email);
return this;
}
public Builder setAttending(boolean attending) {
this.attending = Option.some(attending);
return this;
}
public Builder setEntree(String entree) {
this.entree = Option.some(entree);
return this;
}
public Builder setGuestAttending(boolean guestAttending) {
this.guestAttending = Option.some(guestAttending);
return this;
}
public Builder setGuestName(String guestName) {
this.guestName = Option.some(guestName);
return this;
}
public Builder setGuestEntree(String guestEntree) {
this.guestEntree = Option.some(guestEntree);
return this;
}
public Builder setNotes(String notes) {
this.notes = Option.some(notes);
return this;
}
public RSVP build() {
return new RSVP(this);
}
}
public final String uuid;
public final Instant createdAt;
public final String name;
public final String email;
public final boolean attending;
public final String entree;
public final boolean guestAttending;
public final String guestName;
public final String guestEntree;
public final String notes;
private RSVP(Builder builder) {
uuid = builder.uuid.getOrThrow("Missing UUID");
createdAt = builder.createdAt.getOrThrow("Missing created at");
name = builder.name.getOrThrow("Missing name");
email = builder.email.getOrThrow("Missing email");
attending = builder.attending.getOrThrow("Missing attending");
entree = builder.entree.getOrThrow("Missing entree");
guestAttending = builder.guestAttending.getOrThrow("Missing guest attending");
guestName = builder.guestName.getOrThrow("Missing guest name");
guestEntree = builder.guestEntree.getOrThrow("Missing guest entree");
notes = builder.notes.getOrThrow("Missing notes");
}
}
|
package com.kh.runLearn.member.model.service;
import com.kh.runLearn.member.model.vo.Member;
import com.kh.runLearn.member.model.vo.Member_Image;
public interface MemberService {
Member login(Member m); // 로그인
int getAllUserCount();// 회원수조회 블랙포함
int insertMember(Member m); // 회원가입
int checkId(String id); // 아이디 중복확인
int checkNick(String nick); // 닉네임 중복확인
int checkEmailo(String m_email); // 이메일 중복확인
int checkPhone(Member m); // 휴대폰 번호 확인
int checkPhone2(Member m); // 휴대폰 번호 확인(비밀전호 찾기)
int checkEmail(Member m); // 이메일 확인
int checkEmail2(Member m); // 이메일 확인(비밀번호 찾기)
Member findMember(Member m); // 아이디 조회
Member_Image findMemberImg(String m_id); // 이미지 조회
int pwChange(Member m); // 암호 변경
String checkPw(String id); // 암호 확인
int insertMember_Image(Member_Image mi); // 프로필 사진 등록
}
|
package com.petersoft.mgl.model;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Entity
public class Karbantartas {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int karbantartasId;
@OneToOne
@JoinColumn(name = "lepcsoSzama")
private Lepcso lepcso;
private LocalDate karbantartasDatum;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "karbTipusId")
private KarbantartasTipus karbantartasTipus;
private int muszakSzama;
private boolean elvegezve;
@Transient
private int karbTipusId;
@CreationTimestamp
private LocalDateTime creationDateTime;
@UpdateTimestamp
private LocalDateTime updateDateTime;
public Karbantartas() {
}
public Karbantartas(Lepcso lepcso, LocalDate karbantartasDatum) {
}
public int getKarbantartasId() {
return karbantartasId;
}
public void setKarbantartasId(int karbantartasId) {
this.karbantartasId = karbantartasId;
}
public Lepcso getLepcso() {
return lepcso;
}
public void setLepcso(Lepcso lepcso) {
this.lepcso = lepcso;
}
public LocalDate getKarbantartasDatum() {
return karbantartasDatum;
}
public void setKarbantartasDatum(LocalDate karbantartasDatum) {
this.karbantartasDatum = karbantartasDatum;
}
public KarbantartasTipus getKarbantartasTipus() {
return karbantartasTipus;
}
public void setKarbantartasTipus(KarbantartasTipus karbantartasTipus) {
this.karbantartasTipus = karbantartasTipus;
}
public boolean isElvegezve() {
return elvegezve;
}
public void setElvegezve(boolean elvegezve) {
this.elvegezve = elvegezve;
}
public int getMuszakSzama() {
return muszakSzama;
}
public void setMuszakSzama(int muszakSzama) {
this.muszakSzama = muszakSzama;
}
@Override
public String toString() {
return karbantartasTipus.getKarbTipusKod();
}
public LocalDateTime getCreationDateTime() {
return creationDateTime;
}
public void setCreationDateTime(LocalDateTime creationDateTime) {
this.creationDateTime = creationDateTime;
}
public LocalDateTime getUpdateDateTime() {
return updateDateTime;
}
public void setUpdateDateTime(LocalDateTime updateDateTime) {
this.updateDateTime = updateDateTime;
}
public int getKarbTipusId() {
return this.karbantartasTipus.getKarbTipusId();
}
public void setKarbTipusId(int karbTipusId) {
this.karbTipusId = karbTipusId;
}
}
|
package br.com.giorgetti.games.squareplatform.gameobjects.sprite;
/**
* Possible states of a Sprite.
*
* @author fgiorgetti
*
*/
public enum SpriteState {
IDLE, WALKING, RUNNING, JUMPING, FALLING, CROUCHING;
}
|
package org.fuserleer.time;
import java.util.concurrent.TimeUnit;
import org.fuserleer.Configuration;
public class WallClockTime implements TimeProvider
{
public WallClockTime(final Configuration configuration)
{
super();
}
@Override
public long getSystemTime()
{
return System.currentTimeMillis();
}
@Override
public int getLedgerTimeSeconds()
{
return (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
}
@Override
public long getLedgerTimeMS()
{
return System.currentTimeMillis();
}
@Override
public boolean isSynchronized()
{
return false;
}
}
|
/**
*
*/
package com.ruyuapp;
import com.ruyuapp.proxy.HttpProxy;
import com.ruyuapp.proxy.ProxyPool;
import com.ruyuapp.util.HttpStatus;
import java.io.IOException;
import java.net.*;
import java.util.concurrent.TimeUnit;
/**
* @author <a href="mailto:letcheng@ruyuapp.com">letcheng</a>
* @version create at 2016年3月28日 15:32
*/
public class Main {
/**
* 为了阻塞主线程,不在junit中测试
*
* @param args
*/
public static void main(String args[]) {
ProxyPool proxyPool = new ProxyPool();
proxyPool.add("203.171.230.230", 80);
proxyPool.add("121.9.221.188", 80);
HttpProxy httpProxy = proxyPool.borrow(); // 从 ProxyPool 中获取一个Proxy
URL url = null;
try {
url = new URL("http://www.ruyuapp.com");
HttpURLConnection uc = (HttpURLConnection)url.openConnection(httpProxy.getProxy());
System.out.println(uc.getResponseCode());
uc.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
proxyPool.reback(httpProxy, HttpStatus.SC_OK); // 使用完成之后,归还 Proxy,并将请求结果的 http 状态码一起传入
proxyPool.allProxyStatus(); // 可以获取 ProxyPool 中所有 Proxy 的当前状态
}
}
|
package pe.egcc.cartesianoapp.service;
public class CartesianoService {
public Double calculaDistancia(double x1, double y1, double x2, double y2 ){
double distancia;
distancia = Math.hypot(x2 - x1, y2 - y1);
return distancia;
}
public String determinaCuadrante(double x1, double y1, double x2, double y2 ) {
String resultado = "";
if (x1 > 0 && y1 > 0) {
resultado = "El primer punto (" + x1 + "," + y1 + ") esta en el primer cuadrante";
} else if (x1 < 0 && y1 > 0) {
resultado = "El primer punto (" + x1 + "," + y1 + ") esta en el segundo cuadrante";
} else if (x1 < 0 && y1 < 0) {
resultado = "El primer punto (" + x1 + "," + y1 + ") esta en el tercer cuadrante";
} else if (x1 > 0 && y1 < 0) {
resultado = "El primer punto (" + x1 + "," + y1 + ") esta en el cuarto cuadrante";
};
if (x2 > 0 && y2 > 0) {
resultado = resultado + "\n" + "El segundo punto (" + x2+ "," + y2 + ") esta en el primer cuadrante";
} else if (x2 < 0 && y2 > 0) {
resultado = resultado + "\n" + "El segundo punto (" + x2 + "," + y2 + ") esta en el segundo cuadrante";
} else if (x2 < 0 && y2 < 0) {
resultado = resultado + "\n" + "El segundo punto (" + x2 + "," + y2 + ") esta en el tercer cuadrante";
} else if (x2 > 0 && y2 < 0) {
resultado = resultado + "\n" + "El segundo punto (" + x2 + "," + y2 + ") esta en el cuarto cuadrante";
};
return resultado;
}
}
|
package com.wwwjf.wscreenrecord.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.File;
import java.lang.reflect.Field;
/**
* Created by Administrator on 2018/3/12 0012.
*/
public class ImageUtil {
public static void setPicToImageView(ImageView imageView, String imagePath){
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, opts);
ImageSize imageSize = getImageViewSize(imageView);
opts.inSampleSize = caculateInSampleSize(opts,imageSize.width,imageSize.height);
opts.inPurgeable = true;
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, opts);
imageView.setImageBitmap(bitmap);
}
public static void setPicToImageView(Context context, ImageView imageView, int resId){
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeResource(context.getResources(),resId,opts);
ImageSize imageSize = getImageViewSize(imageView);
opts.inSampleSize = caculateInSampleSize(opts,imageSize.width,imageSize.height);
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),resId,opts);
imageView.setImageBitmap(bitmap);
}
/**
* 根据需求的宽和高以及图片实际的宽和高计算SampleSize
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth,
int reqHeight)
{
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize = 1;
if (width > reqWidth || height > reqHeight)
{
int widthRadio = Math.round(width * 1.0f / reqWidth);
int heightRadio = Math.round(height * 1.0f / reqHeight);
inSampleSize = Math.max(widthRadio, heightRadio);
}
return inSampleSize;
}
/**
* 根据ImageView获适当的压缩的宽和高
*
* @param imageView
* @return
*/
public static ImageSize getImageViewSize(ImageView imageView)
{
ImageSize imageSize = new ImageSize();
DisplayMetrics displayMetrics = imageView.getContext().getResources()
.getDisplayMetrics();
ViewGroup.LayoutParams lp = imageView.getLayoutParams();
int width = imageView.getWidth();// 获取imageview的实际宽度
if (width <= 0)
{
width = lp.width;// 获取imageview在layout中声明的宽度
}
if (width <= 0)
{
//width = imageView.getMaxWidth();// 检查最大值
width = getImageViewFieldValue(imageView, "mMaxWidth");
}
if (width <= 0)
{
width = displayMetrics.widthPixels;
}
int height = imageView.getHeight();// 获取imageview的实际高度
if (height <= 0)
{
height = lp.height;// 获取imageview在layout中声明的宽度
}
if (height <= 0)
{
height = getImageViewFieldValue(imageView, "mMaxHeight");// 检查最大值
}
if (height <= 0)
{
height = displayMetrics.heightPixels;
}
imageSize.width = width;
imageSize.height = height;
/*Log.w("screen","imageSize width: "+imageSize.width);
Log.w("screen","imageSize height: "+imageSize.height);
Log.w("screen","screen width : "+ ShareData.m_screenWidth);
Log.w("screen","screen height : "+ ShareData.m_screenHeight);
Log.w("screen","displayMetrics.widthPixels : "+displayMetrics.widthPixels);
Log.w("screen","displayMetrics.heightPixels : "+displayMetrics.heightPixels);*/
return imageSize;
}
public static class ImageSize
{
int width;
int height;
}
/**
* 通过反射获取imageview的某个属性值
*
* @param object
* @param fieldName
* @return
*/
private static int getImageViewFieldValue(Object object, String fieldName)
{
int value = 0;
try
{
Field field = ImageView.class.getDeclaredField(fieldName);
field.setAccessible(true);
int fieldValue = field.getInt(object);
if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE)
{
value = fieldValue;
}
} catch (Exception e)
{
}
return value;
}
/**
* 根据要求的宽高,从本地路径得到bitmap
* @param picPath
* @param width
* @param height
* @return
*/
public static Bitmap createBitmap(String picPath, int width, int height){
if(!TextUtils.isEmpty(picPath)){
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picPath, opts);
opts.inSampleSize = caculateInSampleSize(opts,width,height);
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(picPath, opts);
return bitmap;
}
return null;
}
public static Bitmap createBitmap(Context context, int resId, int width, int height){
if( resId != 0){
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeResource(context.getResources(),resId,opts);
opts.inSampleSize = caculateInSampleSize(opts,width,height);
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),resId,opts);
return bitmap;
}
return null;
}
public static Bitmap getBitmap(Context context, Object path, int width, int height){
Bitmap bitmap = null;
if (path instanceof String){
bitmap = createBitmap((String) path,width,height);
} else if (path instanceof Integer){
if (context != null ){
bitmap = createBitmap(context, (Integer) path,width,height);
}
}
return bitmap;
}
/**
* 得到图片的尺寸
* @param picPath
* @return size[0] width; size[1] height
*/
public static int[] getPicSize(String picPath){
int[] size = new int[]{0,0};
File file = new File(picPath);
if(!TextUtils.isEmpty(picPath) && file.exists() && file.isFile() ){
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picPath, opts);
size[0] = opts.outWidth;
size[1] = opts.outHeight;
return size;
}
return size;
}
}
|
package com.projects.houronearth.activities.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeUtiliserClass
{
public static int printDifference(String startDate1) {
//milliseconds
Date startDate= null;
try {
startDate = new SimpleDateFormat("dd/MM/yyyy").parse(startDate1);
Date endDate = Calendar.getInstance().getTime();
long different = startDate.getTime() - endDate.getTime();
System.out.println("endDate : " + endDate);
System.out.println("startDate : "+ startDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long yearsinMilli = daysInMilli * 365;
int elapsedYears =0;
if (different>yearsinMilli) {
elapsedYears = (int) (different / yearsinMilli);
different = different % elapsedYears;
}
return elapsedYears;
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
}
|
package pl.edu.wat.wcy.pz.project.server.entity.game;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import pl.edu.wat.wcy.pz.project.server.entity.User;
import javax.persistence.*;
import java.util.Date;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "TIC_TAC_TOE_MOVE")
public class TicTacToeMove {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MOVE_ID")
private Long moveId;
@Column(name = "MOVE_NO")
private Long moveNo;
@Column(name = "CREATED")
private Date created;
@Column(name = "FIELD")
private int field;
@ManyToOne
@JoinColumn(name = "GAME_ID", nullable = false)
private TicTacToeGame game;
@ManyToOne
@JoinColumn(name = "USER_ID")
private User user;
}
|
package com.example.parkminhyun.trackengine;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AccreditInfoTab3_Major extends Fragment {
public String spotName;
private LinearLayout inflatedLayout;
private List<Item> items;
private RecyclerView rv;
AccreditAdapter adapter;
private List<String> subjects;
UserStudyData userStudyData;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
inflatedLayout = (LinearLayout) inflater.inflate(R.layout.accredit_tab, container, false);
subjects= Arrays.asList("C프로그래밍및실습","공학설계기초","고급C프로그래밍및실습",
"자료구조및실습","알고리즘및실습","컴퓨터구조론","운영체제","컴퓨터네트워크",
"웹프로그래밍","데이터베이스","네트워크프로그래밍","인공지능");
userStudyData = new UserStudyData(getActivity());
List<String> userStudy = userStudyData.loadStudyDataList();
items = new ArrayList<>();
String str="";
boolean isMatch;
for(int i=0;i<subjects.size();i++)
{
isMatch=false;
for(int j=0;j<userStudy.size();j++)
{
str=userStudy.get(j).toString().replaceAll(" ",""); //공백 제거
Log.i("str==",str);
Log.i("subjects.get(i)==",subjects.get(i));
if(str.equals(subjects.get(i).toString()))
{
isMatch=true;
}
}
if(isMatch==false)
items.add(new Item(subjects.get(i).toString()));
}
rv = (RecyclerView) inflatedLayout.findViewById(R.id.accredit_rv);
rv.setHasFixedSize(true);
adapter = new AccreditAdapter(getActivity(),items);
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
setContentWork();
return inflatedLayout;
}
public void setContentWork() {
}
} |
package com.example.userportal.requestmodel.payu;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class Buyer {
String email;
String phone;
String firstName;
String lastName;
String language;
}
|
package com.ing.product.controller;
import java.util.List;
import com.ing.product.service.ProductDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.ing.product.model.ProductDetails;
import com.ing.product.service.ProductGroupServiceImpl;
@RestController
public class ProductDetailsController implements ProductDetailsControllerApi {
@Autowired
private ProductDetailsService pgs;
@Override
@GetMapping("/getProductDetails/{id}")
public List<ProductDetails> getProductDetails(@PathVariable ("id") Long id) {
return pgs.getProductDetails(id) ;
}
} |
package day16owerloading;
public class Constructor03 {
String isim = "Ali Can";
int yas = 33;
int kilo = 85;
String meslek = "Automation Teseter";
boolean emekli = false;
Constructor03(){ //bu constructor uretme
}
Constructor03(String isim, int yas){ //bu yeni bir constructor uretme
this.isim = isim;
this.yas = yas;
}
Constructor03(String isim, int yas, boolean emekli){ //bu yeni bir constructor uretme
this.isim = isim;
this.yas = yas;
this.emekli = emekli;
}
public static void main(String[] args) {
Constructor03 insan01 = new Constructor03();// bu object olusturma
System.out.println(insan01.isim);
Constructor03 insan02 = new Constructor03("Ayhan Yildiz", 56);// bu object olusturma
System.out.println(insan02.isim);
Constructor03 insan03 = new Constructor03("Ayhan Yildiz", 56, true);// bu object olusturma
System.out.println(insan03.isim);
System.out.println(insan03.yas);
System.out.println(insan03.emekli);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.