text
stringlengths
10
2.72M
package com.wkrzywiec.spring.library.config; import java.util.Properties; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @EnableTransactionManagement @EnableAspectJAutoProxy(proxyTargetClass = true) @ComponentScan(basePackages="com.wkrzywiec.spring.library") @PropertySource(value = { "classpath:properties/datasource.properties", "classpath:properties/hibernate.properties" }) public class LibraryConfig implements WebMvcConfigurer { @Autowired private Environment env; @Value("${hibernate.hbm2ddl.auto}") private String hibernatehbm2ddl; @Value("${hibernate.dialect}") private String hibernateDialect; @Value("${hibernate.search.default.directory_provider}") private String hibernateDirectoryProvider; @Value("${hibernate.search.default.indexBase}") private String hibernateIndexBase; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Bean public ViewResolver getViewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Bean public DataSource getDataSource(){ DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("datasource.driver")); dataSource.setUrl(env.getProperty("datasource.url")); dataSource.setUsername(env.getProperty("datasource.user")); dataSource.setPassword(env.getProperty("datasource.password")); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){ LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean(); entityManager.setDataSource(getDataSource()); entityManager.setPackagesToScan("com.wkrzywiec.spring.library.entity"); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); entityManager.setJpaVendorAdapter(vendorAdapter); entityManager.setJpaProperties(additionalProperties()); return entityManager; } @Bean public PlatformTransactionManager transactionManager(){ JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject()); return transactionManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){ return new PersistenceExceptionTranslationPostProcessor(); } private Properties additionalProperties() { Properties properties = new Properties(); properties.setProperty("hibernate.hbm2ddl.auto", hibernatehbm2ddl); properties.setProperty("hibernate.dialect", hibernateDialect); properties.setProperty("hibernate.search.default.directory_provider", hibernateDirectoryProvider); properties.setProperty("hibernate.search.default.indexBase", hibernateIndexBase); return properties; } @Bean public JavaMailSender getJavaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("smtp.gmail.com"); mailSender.setPort(587); mailSender.setUsername("YOUR_EMAIL_ADDRESS"); mailSender.setPassword("YOUR_PASSWORD"); Properties props = mailSender.getJavaMailProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.debug", "true"); return mailSender; } }
package com.zhku.my21days.vo; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.zhku.my21days.base.AbstractExample; /** * <p>系统名称: <b>NETARK-通用网管平台V1.0</b></p> * <p>公司: 中通服软件科技有限公司</p> * <p>表名称:test_analys</p> * <p>域对象:Analys.java</p> * <p>SQL映射文件:org.androidpn.server.model.test_analys_SqlMap.xml</p> * @see org.androidpn.server.model.Analys * @see org.androidpn.server.dao.AnalysDAO * @author 戈亮锋 * @Create On:2014-03-22 16:35:35 */ public class AnalysExample extends AbstractExample { protected String orderByClause; protected List<Criteria> oredCriteria; public AnalysExample() { oredCriteria = new ArrayList<Criteria>(); } protected AnalysExample(AnalysExample example) { this.orderByClause = example.orderByClause; this.oredCriteria = example.oredCriteria; } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); } public String getTableName() { return "test_analys"; } /** * 对应关联的表名为: test_analys */ public static class Criteria { protected List<String> criteriaWithoutValue; protected List<Map<String, Object>> criteriaWithSingleValue; protected List<Map<String, Object>> criteriaWithListValue; protected List<Map<String, Object>> criteriaWithBetweenValue; protected Criteria() { super(); criteriaWithoutValue = new ArrayList<String>(); criteriaWithSingleValue = new ArrayList<Map<String, Object>>(); criteriaWithListValue = new ArrayList<Map<String, Object>>(); criteriaWithBetweenValue = new ArrayList<Map<String, Object>>(); } public boolean isValid() { return criteriaWithoutValue.size() > 0 || criteriaWithSingleValue.size() > 0 || criteriaWithListValue.size() > 0 || criteriaWithBetweenValue.size() > 0; } public List<String> getCriteriaWithoutValue() { return criteriaWithoutValue; } public List<Map<String, Object>> getCriteriaWithSingleValue() { return criteriaWithSingleValue; } public List<Map<String, Object>> getCriteriaWithListValue() { return criteriaWithListValue; } public List<Map<String, Object>> getCriteriaWithBetweenValue() { return criteriaWithBetweenValue; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteriaWithoutValue.add(condition); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } Map<String, Object> map = new HashMap<String, Object>(); map.put("condition", condition); map.put("value", value); criteriaWithSingleValue.add(map); } protected void addCriterion(String condition, List<? extends Object> values, String property) { if (values == null || values.size() == 0) { throw new RuntimeException("Value list for " + property + " cannot be null or empty"); } Map<String, Object> map = new HashMap<String, Object>(); map.put("condition", condition); map.put("values", values); criteriaWithListValue.add(map); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } List<Object> list = new ArrayList<Object>(); list.add(value1); list.add(value2); Map<String, Object> map = new HashMap<String, Object>(); map.put("condition", condition); map.put("values", list); criteriaWithBetweenValue.add(map); } public Criteria andAIdIsNull() { addCriterion("id is null"); return this; } public Criteria andAIdIsNotNull() { addCriterion("id is not null"); return this; } public Criteria andAIdEqualTo(Integer value) { addCriterion("id =", value, "aId"); return this; } public Criteria andAIdNotEqualTo(Integer value) { addCriterion("id <>", value, "aId"); return this; } public Criteria andAIdGreaterThan(Integer value) { addCriterion("id >", value, "aId"); return this; } public Criteria andAIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "aId"); return this; } public Criteria andAIdLessThan(Integer value) { addCriterion("id <", value, "aId"); return this; } public Criteria andAIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "aId"); return this; } public Criteria andAIdIn(List<Integer> values) { addCriterion("id in", values, "aId"); return this; } public Criteria andAIdNotIn(List<Integer> values) { addCriterion("id not in", values, "aId"); return this; } public Criteria andAIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "aId"); return this; } public Criteria andAIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "aId"); return this; } public Criteria andAnimalIsNull() { addCriterion("animal is null"); return this; } public Criteria andAnimalIsNotNull() { addCriterion("animal is not null"); return this; } public Criteria andAnimalEqualTo(String value) { addCriterion("animal =", value, "animal"); return this; } public Criteria andAnimalNotEqualTo(String value) { addCriterion("animal <>", value, "animal"); return this; } public Criteria andAnimalGreaterThan(String value) { addCriterion("animal >", value, "animal"); return this; } public Criteria andAnimalGreaterThanOrEqualTo(String value) { addCriterion("animal >=", value, "animal"); return this; } public Criteria andAnimalLessThan(String value) { addCriterion("animal <", value, "animal"); return this; } public Criteria andAnimalLessThanOrEqualTo(String value) { addCriterion("animal <=", value, "animal"); return this; } public Criteria andAnimalLike(String value) { addCriterion("animal like", value, "animal"); return this; } public Criteria andAnimalNotLike(String value) { addCriterion("animal not like", value, "animal"); return this; } public Criteria andAnimalIn(List<String> values) { addCriterion("animal in", values, "animal"); return this; } public Criteria andAnimalNotIn(List<String> values) { addCriterion("animal not in", values, "animal"); return this; } public Criteria andAnimalBetween(String value1, String value2) { addCriterion("animal between", value1, value2, "animal"); return this; } public Criteria andAnimalNotBetween(String value1, String value2) { addCriterion("animal not between", value1, value2, "animal"); return this; } public Criteria andDicripIsNull() { addCriterion("dicrip is null"); return this; } public Criteria andDicripIsNotNull() { addCriterion("dicrip is not null"); return this; } public Criteria andDicripEqualTo(String value) { addCriterion("dicrip =", value, "dicrip"); return this; } public Criteria andDicripNotEqualTo(String value) { addCriterion("dicrip <>", value, "dicrip"); return this; } public Criteria andDicripGreaterThan(String value) { addCriterion("dicrip >", value, "dicrip"); return this; } public Criteria andDicripGreaterThanOrEqualTo(String value) { addCriterion("dicrip >=", value, "dicrip"); return this; } public Criteria andDicripLessThan(String value) { addCriterion("dicrip <", value, "dicrip"); return this; } public Criteria andDicripLessThanOrEqualTo(String value) { addCriterion("dicrip <=", value, "dicrip"); return this; } public Criteria andDicripLike(String value) { addCriterion("dicrip like", value, "dicrip"); return this; } public Criteria andDicripNotLike(String value) { addCriterion("dicrip not like", value, "dicrip"); return this; } public Criteria andDicripIn(List<String> values) { addCriterion("dicrip in", values, "dicrip"); return this; } public Criteria andDicripNotIn(List<String> values) { addCriterion("dicrip not in", values, "dicrip"); return this; } public Criteria andDicripBetween(String value1, String value2) { addCriterion("dicrip between", value1, value2, "dicrip"); return this; } public Criteria andDicripNotBetween(String value1, String value2) { addCriterion("dicrip not between", value1, value2, "dicrip"); return this; } public Criteria andTimeIsNull() { addCriterion("time is null"); return this; } public Criteria andTimeIsNotNull() { addCriterion("time is not null"); return this; } public Criteria andTimeEqualTo(Date value) { addCriterion("time =", value, "time"); return this; } public Criteria andTimeNotEqualTo(Date value) { addCriterion("time <>", value, "time"); return this; } public Criteria andTimeGreaterThan(Date value) { addCriterion("time >", value, "time"); return this; } public Criteria andTimeGreaterThanOrEqualTo(Date value) { addCriterion("time >=", value, "time"); return this; } public Criteria andTimeLessThan(Date value) { addCriterion("time <", value, "time"); return this; } public Criteria andTimeLessThanOrEqualTo(Date value) { addCriterion("time <=", value, "time"); return this; } public Criteria andTimeIn(List<Date> values) { addCriterion("time in", values, "time"); return this; } public Criteria andTimeNotIn(List<Date> values) { addCriterion("time not in", values, "time"); return this; } public Criteria andTimeBetween(Date value1, Date value2) { addCriterion("time between", value1, value2, "time"); return this; } public Criteria andTimeNotBetween(Date value1, Date value2) { addCriterion("time not between", value1, value2, "time"); return this; } } }
package testfiles; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import DataModify.ExtractFile; import IDExtract.ID_Extract_Tools; import MainRuns.FilePaths; public class forTsubo { public static final String GPSdeeppath = "/home/c-tyabe/Data/grid/0/tmp/ktsubouc/gps_"; // public static void main(String args[]) throws IOException{ // // File out = new File("/home/c-tyabe/Data/dayslogs_results.csv"); // // ArrayList<String> subjects = getdates(); // // for(int i = 0; i<subjects.size(); i++){ // // System.out.println(subjects.get(i)); // // } // // for(String ymd : subjects){ // ExtractFile.extractfromcommand(ymd); System.out.println("#done uncompressing "+ymd); // String unzippedfile = FilePaths.deephomepath(ymd); // getres(unzippedfile, ymd, out); // } // } public static void main(String[] args) throws IOException{ File out = new File("/home/c-tyabe/Data/idslogs_results.csv"); ArrayList<String> subjects = getdatesshort(); for(String ymd:subjects){ ExtractFile.extractfromcommand(ymd); System.out.println("#done uncompressing "+ymd); String unzippedfile = FilePaths.deephomepath(ymd); getloghisto(unzippedfile,ymd,out); } } public static ArrayList<String> getdates(){ ArrayList<String> subjects = new ArrayList<String>(); String year = "2014"; for(int i = 11; i<=12; i++){ for(int j = 1; j<=30; j++){ subjects.add(year+String.valueOf(i)+String.format("%02d", j)); } } year = "2015"; for(int i = 1; i<=7; i++){ for(int j = 1; j<=28; j++){ subjects.add(year+String.format("%02d", i)+String.format("%02d", j)); } } return subjects; } public static ArrayList<String> getdatesshort(){ ArrayList<String> subjects = new ArrayList<String>(); String year = "2015"; int i = 6; for(int j = 1; j<=20; j++){ subjects.add(year+String.format("%02d", i)+String.format("%02d", j)); } return subjects; } public static void getres(String file, String ymd, File out) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(file)); BufferedWriter bw = new BufferedWriter(new FileWriter(out,true)); String line = null; String prevline = null; int count = 0; HashSet<String> set = new HashSet<String>(); while((line=br.readLine())!= null){ if(ID_Extract_Tools.SameLogCheck(line,prevline)==true){ String[] tokens = line.split("\t"); if(tokens.length>=5){ if(!tokens[4].equals("null")){ String id = tokens[0]; if(!id.equals("null")){ set.add(id); count++; } } } prevline = line; } } bw.write(ymd+","+count+","+set.size()); bw.newLine(); br.close(); bw.close(); File i = new File(GPSdeeppath+ymd+".csv"); i.delete(); } public static void getloghisto(String file, String ymd, File out) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(file)); BufferedWriter bw = new BufferedWriter(new FileWriter(out,true)); String line = null; String prevline = null; HashMap<String,Integer> set = new HashMap<String,Integer>(); while((line=br.readLine())!= null){ if(ID_Extract_Tools.SameLogCheck(line,prevline)==true){ String[] tokens = line.split("\t"); if(tokens.length>=5){ if(!tokens[4].equals("null")){ String id = tokens[0]; if(!id.equals("null")){ if(set.containsKey(id)){ int count = set.get(id) + 1; set.put(id, count); } else{ set.put(id, 1); } } } } prevline = line; } } for(String ids : set.keySet()){ bw.write(String.valueOf(set.get(ids))); bw.newLine(); } br.close(); bw.close(); File i = new File(GPSdeeppath+ymd+".csv"); i.delete(); } }
package be.mxs.common.util.system; import java.awt.AlphaComposite; import java.awt.Composite; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.HeadlessException; import java.awt.Image; import java.awt.Toolkit; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.awt.image.PixelGrabber; import java.awt.image.RGBImageFilter; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Iterator; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import be.mxs.common.util.db.MedwanQuery; import be.openclinic.datacenter.District; public class Imaging { public static BufferedImage drawDistricts(String countryFile, int totalcolors, double min, double max, District[] districts){ String cf = ""; SAXReader reader = new SAXReader(false); try { String sDoc = MedwanQuery.getInstance().getConfigString("templateSource") + countryFile; Document document = reader.read(new URL(sDoc)); Element root = document.getRootElement(); cf=root.attributeValue("directory")+"/"+root.attributeValue("countrymap"); } catch (Exception e) { if (Debug.enabled) Debug.println(e.getMessage()); } BufferedImage resultImage= toBufferedImage(Miscelaneous.getImage(cf)); for (int n=0; n<districts.length;n++){ if(districts[n]!=null){ int color=getColor(totalcolors,min,max,districts[n].getScore()); BufferedImage im1=toBufferedImage(replaceColor(Miscelaneous.getImage(districts[n].getMap()),0xffff0000,color)); resultImage = createComposite(resultImage, im1, 1f); } } return resultImage; } public static BufferedImage drawDistrictsById(String countryFile, int totalcolors, double min, double max, double[][] districts){ String cf = ""; SAXReader reader = new SAXReader(false); try { String sDoc = MedwanQuery.getInstance().getConfigString("templateSource") + countryFile; Document document = reader.read(new URL(sDoc)); Element root = document.getRootElement(); cf=root.attributeValue("directory")+"/"+root.attributeValue("countrymap"); } catch (Exception e) { if (Debug.enabled) Debug.println(e.getMessage()); } BufferedImage resultImage= toBufferedImage(Miscelaneous.getImage(cf)); for (int n=0; n<districts.length;n++){ if(districts[n]!=null){ District district = District.getDistrictWithId(countryFile, new Double (districts[n][0]).intValue()+""); if(district!=null){ int color=getColor(totalcolors,min,max,districts[n][1]); BufferedImage im1=toBufferedImage(replaceColor(Miscelaneous.getImage(district.getMap()),0xffff0000,color)); resultImage = createComposite(resultImage, im1, 1f); } } } return resultImage; } public static BufferedImage drawDistrictsByZipCode(String countryFile, int totalcolors, double min, double max, String[][] districts){ String cf = ""; SAXReader reader = new SAXReader(false); try { String sDoc = MedwanQuery.getInstance().getConfigString("templateSource") + countryFile; Document document = reader.read(new URL(sDoc)); Element root = document.getRootElement(); cf=root.attributeValue("directory")+"/"+root.attributeValue("countrymap"); } catch (Exception e) { if (Debug.enabled) Debug.println(e.getMessage()); } BufferedImage resultImage= toBufferedImage(Miscelaneous.getImage(cf)); for (int n=0; n<districts.length;n++){ if(districts[n]!=null){ District district = District.getDistrictWithZipcode(countryFile, districts[n][0]); if(district!=null){ BufferedImage im1=toBufferedImage(replaceColor(Miscelaneous.getImage(district.getMap()),0xffff0000,getColor(totalcolors,min,max,Double.parseDouble(districts[n][1])))); resultImage = createComposite(resultImage, im1, 1f); } } } return resultImage; } public static int getColor(int totalcolors, double min, double max, double value){ double step = (max-min)/totalcolors; int w_value=new Double((value-min)/step).intValue(); int red,green,blue; if(w_value<=totalcolors/2){ red=255; green=255 * (totalcolors/2-w_value) / (totalcolors/2); blue=255 * (totalcolors/2-w_value) / (totalcolors/2); } else { red=255 * (totalcolors - w_value) / (totalcolors/2); green=0; blue=0; } return new Double(0xff000000 + 256*256*red +256*green + blue).intValue(); } public static Image replaceColor(Image image, int sourcergb, int destinationrgb){ ImageFilter filter = new GetColorFilter(sourcergb,destinationrgb); FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(), filter); return Toolkit.getDefaultToolkit().createImage(filteredSrc); } public static Image keepColor(Image image, int sourcergb){ ImageFilter filter = new KeepColorFilter(sourcergb); FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(), filter); return Toolkit.getDefaultToolkit().createImage(filteredSrc); } public static BufferedImage createComposite(BufferedImage im1, BufferedImage im2, float alpha) { BufferedImage buffer = new BufferedImage(Math.max(im1.getWidth(), im2.getWidth()), Math.max(im1.getHeight(), im2.getHeight()),BufferedImage.TYPE_INT_ARGB); Graphics2D g2=buffer.createGraphics(); g2.drawImage(im1, null, null); Composite newComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha); g2.setComposite(newComposite); g2.drawImage(im2, null, null); g2.dispose(); return buffer; } public static BufferedImage toBufferedImage(Image image) { if (image instanceof BufferedImage) {return (BufferedImage)image;} // This code ensures that all the pixels in the image are loaded image = new ImageIcon(image).getImage(); // Determine if the image has transparent pixels boolean hasAlpha = hasAlpha(image); // Create a buffered image with a format that's compatible with the screen BufferedImage bimage = null; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); try { // Determine the type of transparency of the new buffered image int transparency = Transparency.OPAQUE; if (hasAlpha == true) {transparency = Transparency.BITMASK;} // Create the buffered image GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency); } catch (HeadlessException e) {} //No screen if (bimage == null) { // Create a buffered image using the default color model int type = BufferedImage.TYPE_INT_RGB; if (hasAlpha == true) {type = BufferedImage.TYPE_INT_ARGB;} bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type); } // Copy image to buffered image Graphics g = bimage.createGraphics(); // Paint the image onto the buffered image g.drawImage(image, 0, 0, null); g.dispose(); return bimage; } public static boolean hasAlpha(Image image) { // If buffered image, the color model is readily available if (image instanceof BufferedImage) {return ((BufferedImage)image).getColorModel().hasAlpha();} // Use a pixel grabber to retrieve the image's color model; // grabbing a single pixel is usually sufficient PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false); try {pg.grabPixels();} catch (InterruptedException e) {} // Get the image's color model return pg.getColorModel().hasAlpha(); } }
package com.docker.script; import chat.errors.CoreException; import chat.logs.LoggerEx; import chat.utils.TimerEx; import chat.utils.TimerTaskEx; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.util.TypeUtils; import com.docker.annotations.*; import com.docker.data.Service; import com.docker.errors.CoreErrorCodes; import com.docker.script.i18n.I18nHandler; import com.docker.server.OnlineServer; import com.docker.storage.adapters.DockerStatusService; import com.docker.storage.adapters.ServersService; import com.docker.utils.SpringContextUtil; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.model.FileHeader; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.bson.Document; import script.file.FileAdapter; import script.file.FileAdapter.FileEntity; import script.file.FileAdapter.PathEx; import script.groovy.runtime.ClassAnnotationHandler; import script.groovy.runtime.FieldInjectionListener; import script.utils.ShutdownListener; import javax.annotation.Resource; import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipException; public class ScriptManager implements ShutdownListener { private static final String TAG = ScriptManager.class.getSimpleName(); // @Resource private FileAdapter fileAdapter = (FileAdapter) SpringContextUtil.getBean("fileAdapter"); // @Resource private ServersService serversService = (ServersService) SpringContextUtil.getBean("serversService"); private DockerStatusService dockerStatusService; private String remotePath; private String localPath; private ConcurrentHashMap<String, BaseRuntime> scriptRuntimeMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, List<BaseRuntime>> serviceVersionMap = new ConcurrentHashMap<>(); private Class<?> baseRuntimeClass; boolean isShutdown = false; public static final String SERVICE_NOTFOUND = "servicenotfound"; public static final Boolean DELETELOCAL = false; public void init() { // dslFileAdapter.getFilesInDirectory(arg0) TimerEx.schedule(new TimerTaskEx() { @Override public void execute() { synchronized (ScriptManager.this) { if (!isShutdown) reload(); } } }, 5000, TimeUnit.SECONDS.toMillis(10));//30 } public BaseRuntime getBaseRuntime(String service) { BaseRuntime runtime = scriptRuntimeMap.get(service); if (runtime == null) { List<BaseRuntime> runtimes = serviceVersionMap.get(service); if (runtimes != null && !runtimes.isEmpty()) { runtime = runtimes.get(runtimes.size() - 1); } } if (runtime == null) { MyBaseRuntime notFoundRuntime = (MyBaseRuntime) scriptRuntimeMap.get(SERVICE_NOTFOUND); if (notFoundRuntime != null) { runtime = notFoundRuntime.getRuntimeWhenNotFound(service); } } return runtime; } public Set<Map.Entry<String, BaseRuntime>> getBaseRunTimes() { return scriptRuntimeMap.entrySet(); } private String getServiceName(String service) { Integer version = null; String versionSeperator = "_v"; int lastIndex = service.lastIndexOf(versionSeperator); if (lastIndex > 0) { String curVerStr = service.substring(lastIndex + versionSeperator.length()); if (curVerStr != null) { try { version = Integer.parseInt(curVerStr); } catch (Exception e) { } } if (version != null) { String serviceName = service.substring(0, lastIndex); return serviceName; } } return service; } private Integer getServiceVersion(String service) { Integer version = null; String versionSeperator = "_v"; int lastIndex = service.lastIndexOf(versionSeperator); if (lastIndex > 0) { String curVerStr = service.substring(lastIndex + versionSeperator.length()); if (curVerStr != null) { try { version = Integer.parseInt(curVerStr); } catch (Exception e) { } } } if (version == null) version = 1; return version; } private void reload() { try { Collection<FileEntity> files = fileAdapter.getFilesInDirectory(new PathEx(remotePath), new String[]{"zip"}, true); OnlineServer server = OnlineServer.getInstance(); if (server == null) { LoggerEx.error(TAG, "Online server is null while reload scripts"); return; } String serverType = server.getServerType(); if (serverType == null) { LoggerEx.error(TAG, "ServerType is null while reload scripts"); return; } if (files != null) { Set<String> remoteServices = new HashSet<>(); String serverTypePath = "/" + serverType + "/"; for (FileEntity file : files) { try { // for example, /gateway/SS/groovy.zip String abPath = file.getAbsolutePath(); int index = abPath.indexOf(serverTypePath); boolean createRuntime = false; if (index > -1) { String thePath = abPath.substring(index + serverTypePath.length(), abPath.length()); //SS/groovy.zip String[] strs = thePath.split("/"); if (strs.length == 2) { String service = strs[0]; String zipFile = strs[1]; String language = null; String localScriptPath = null; remoteServices.add(service); BaseRuntime runtime = scriptRuntimeMap.get(service); boolean needRedeploy = false; if (runtime != null && (runtime.getVersion() == null || runtime.getVersion() < file.getLastModificationTime())) { needRedeploy = true; try { runtime.close(); scriptRuntimeMap.remove(service); List<BaseRuntime> runtimes = serviceVersionMap.get(runtime.getServiceName()); if (runtimes != null && !runtimes.isEmpty()) { runtimes.remove(runtime); } LoggerEx.error(TAG, "Runtime " + runtime + " service " + service + " closed because of deployment"); } catch (Throwable t) { t.printStackTrace(); LoggerEx.error(TAG, "close runtime " + runtime + " service " + service + " failed, " + t.getMessage()); } finally { runtime = null; } } if (runtime == null) { createRuntime = true; needRedeploy = true; language = zipFile.substring(0, zipFile.length() - ".zip".length()).toLowerCase(); switch (language) { case "groovy": if (baseRuntimeClass != null) { runtime = (BaseRuntime) baseRuntimeClass.newInstance(); } else { runtime = new MyBaseRuntime(); } if (runtime instanceof MyBaseRuntime) { final MyBaseRuntime baseRuntime = (MyBaseRuntime) runtime; runtime.addFieldInjectionListener(new FieldInjectionListener<ServiceBean>() { public Class<ServiceBean> annotationClass() { return ServiceBean.class; } @Override public void inject(ServiceBean annotation, Field field, Object obj) { String serviceName = annotation.name(); if (!StringUtils.isBlank(serviceName)) { baseRuntime.prepareServiceStubProxy(); Object serviceStub = baseRuntime.getServiceStubManager().getService(serviceName, field.getType()); if (!field.isAccessible()) field.setAccessible(true); try { field.set(obj, serviceStub); } catch (Throwable e) { e.printStackTrace(); LoggerEx.error(TAG, "Set field " + field.getName() + " for service " + serviceName + " class " + field.getType() + " in class " + obj.getClass()); } } } }); runtime.addFieldInjectionListener(new FieldInjectionListener<ConfigProperty>() { public Class<ConfigProperty> annotationClass() { return ConfigProperty.class; } @Override public void inject(ConfigProperty annotation, Field field, Object obj) { String key = annotation.name(); if (!StringUtils.isBlank(key)) { Properties properties = baseRuntime.getConfig(); if (properties == null) return; String value = properties.getProperty(key); if (value == null) return; if (!field.isAccessible()) field.setAccessible(true); try { field.set(obj, TypeUtils.cast(value, field.getType(), ParserConfig.getGlobalInstance())); } catch (Throwable e) { e.printStackTrace(); LoggerEx.error(TAG, "Set field " + field.getName() + " for config key " + key + " class " + field.getType() + " in class " + obj.getClass()); } } } }); runtime.addFieldInjectionListener(new FieldInjectionListener<I18nBean>() { public Class<I18nBean> annotationClass(){ return I18nBean.class; } @Override public void inject(I18nBean annotation, Field field, Object obj) { I18nHandler i18nHandler = baseRuntime.getI18nHandler(); if (!field.isAccessible()) field.setAccessible(true); try { field.set(obj, TypeUtils.cast(i18nHandler, field.getType(), ParserConfig.getGlobalInstance())); } catch (Throwable e) { e.printStackTrace(); LoggerEx.error(TAG, "Set field " + field.getName() + " for i18nhandler key "+ i18nHandler + " class " + field.getType() + " in class " + obj.getClass()); } } }); } // switch(serverType) { // case "gateway": // runtime = new GatewayGroovyRuntime(); // break; // case "login": // runtime = new LoginGroovyRuntime(); // break; // case "presence": // runtime = new PresenceGroovyRuntime(); // break; // } break; } if (runtime != null) { localScriptPath = localPath + serverTypePath + service + "/" + language; runtime.setPath(localScriptPath + "/"); } } if (runtime != null && needRedeploy) { File localZipFile = new File(localPath + serverTypePath + thePath); FileUtils.deleteQuietly(localZipFile); OutputStream zipOs = FileUtils.openOutputStream(localZipFile); fileAdapter.readFile(new PathEx(file.getAbsolutePath()), zipOs); IOUtils.closeQuietly(zipOs); String n = localZipFile.getName(); n = n.substring(0, n.length() - ".zip".length()); localScriptPath = localPath + serverTypePath + service + "/" + n; FileUtils.deleteDirectory(new File(localScriptPath)); CRC32 crc = new CRC32(); String str = "groovy.zip"; crc.update(str.getBytes()); long valuePwd = crc.getValue(); unzip(localZipFile, localScriptPath, String.valueOf(valuePwd)); Service theService = null; if (createRuntime) { String propertiesPath = localScriptPath + "/config.properties"; Properties properties = new Properties(); File propertiesFile = new File(propertiesPath); if (propertiesFile.exists() && propertiesFile.isFile()) { InputStream is = FileUtils.openInputStream(propertiesFile); properties.load(is); IOUtils.closeQuietly(is); } String minVersionStr = properties != null ? properties.getProperty("service.minversion") : null; Integer minVersion = null; if (minVersionStr != null) { try { minVersion = Integer.parseInt(minVersionStr); } catch (Exception e) { } } if (minVersion == null) { minVersion = 0; } Integer version = getServiceVersion(service); String serviceName = getServiceName(service); runtime.setServiceName(serviceName); runtime.setServiceVersion(version); try { if (serversService != null) { Document configDoc = serversService.getServerConfig(serviceName); if (configDoc != null) { LoggerEx.info(TAG, "Read server " + serviceName + " config " + configDoc); Set<String> keys = configDoc.keySet(); for (String key : keys) { String theValue = configDoc.getString(key); String value = properties.getProperty(key); if (value == null) { key = key.replaceAll("_", "."); value = properties.getProperty(key); } if (value != null) { properties.put(key, theValue); } } } } else { LoggerEx.info(TAG, "serversService is null, will not read config from database for service " + serviceName); } } catch (Throwable t) { LoggerEx.error(TAG, "Read server " + serviceName + " config failed, " + t.getMessage()); } runtime.prepare(service, properties, localScriptPath); theService = new Service(); theService.setService(serviceName); theService.setMinVersion(minVersion); theService.setVersion(version); theService.setUploadTime(file.getLastModificationTime()); // theService.setType(Service.FIELD_SERVER_TYPE_NORMAL); if (dockerStatusService != null) { //Aplomb delete service first before add, fixed the duplicated service bug. dockerStatusService.deleteService(OnlineServer.getInstance().getServer(), theService.getService(), theService.getVersion()); } scriptRuntimeMap.put(service, runtime); List<BaseRuntime> versionList = serviceVersionMap.get(serviceName); //使用新的容器是因为防止删除的一瞬间, 获取为空的问题, 因此采用新容器更换的办法。 List<BaseRuntime> newVersionList = null; if (versionList == null) { newVersionList = new ArrayList<>(); } else { newVersionList = new ArrayList<>(versionList); } // if (newVersionList.contains(runtime)) { // newVersionList.remove(runtime); // } newVersionList.add(runtime); Collections.sort(newVersionList, new Comparator<BaseRuntime>() { @Override public int compare(BaseRuntime o1, BaseRuntime o2) { return o1.getServiceVersion().compareTo(o2.getServiceVersion()); } }); serviceVersionMap.put(serviceName, newVersionList); } else { Integer version = getServiceVersion(service); String serviceName = getServiceName(service); if (dockerStatusService != null) dockerStatusService.updateServiceUpdateTime(OnlineServer.getInstance().getServer(), serviceName, version, file.getLastModificationTime()); } Integer version = getServiceVersion(service); String serviceName = getServiceName(service); try { runtime.setVersion(file.getLastModificationTime()); runtime.redeploy(); Collection<ClassAnnotationHandler> handlers = runtime.getAnnotationHandlers(); if (handlers != null && theService != null) { for (ClassAnnotationHandler handler : handlers) { if (handler instanceof ClassAnnotationHandlerEx) ((ClassAnnotationHandlerEx) handler).configService(theService); } } theService.setType(Service.FIELD_SERVER_TYPE_NORMAL); } catch (Throwable t) { LoggerEx.error(TAG, "Redeploy service " + service + " failed, " + t.getMessage()); theService.setType(Service.FIELD_SERVER_TYPE_DEPLOY_FAILED); // if(dockerStatusService != null) // dockerStatusService.updateServiceType(OnlineServer.getInstance().getServer(), serviceName, version, Service.FIELD_SERVER_TYPE_DEPLOY_FAILED); throw t; } finally { if (dockerStatusService != null) { dockerStatusService.addService(OnlineServer.getInstance().getServer(), theService); // dockerStatusService.updateServiceType(OnlineServer.getInstance().getServer(), serviceName, version, Service.FIELD_SERVER_TYPE_NORMAL); } // String servicePathex = abPath.split("groovy.zip")[0]; // String servicePath = servicePathex.split("/scripts")[1]; if (DELETELOCAL) { String servicePath = serverTypePath + service; File localFile = new File(localPath + servicePath); File temp = null; Collection<File> filelist = FileUtils.listFiles(localFile, new String[]{"groovy", "zip"}, true); try { if (filelist != null) { for (File file1 : filelist) { file1.delete(); } } LoggerEx.info(TAG, "delete localFile: " + localFile + " success"); } catch (Exception e) { LoggerEx.error(TAG, "delete file failed"); throw e; } } } } } } } catch (Throwable t) { t.printStackTrace(); LoggerEx.error(TAG, "Reload script zip file " + file.getAbsolutePath() + " failed, " + t.getMessage()); } } Collection<String> keys = scriptRuntimeMap.keySet(); for (String key : keys) { if (!remoteServices.contains(key)) { BaseRuntime runtime = scriptRuntimeMap.remove(key); if (runtime != null) { LoggerEx.info(TAG, "Service " + key + " is going to be removed, because it is not found in remote."); try { runtime.close(); } catch (Throwable t) { t.printStackTrace(); } finally { try { String serviceName = getServiceName(key); Integer version = getServiceVersion(key); List<BaseRuntime> runtimes = serviceVersionMap.get(serviceName); if (runtimes != null) { runtimes.remove(runtime); } if (dockerStatusService != null) { dockerStatusService.deleteService(OnlineServer.getInstance().getServer(), serviceName, version); } } catch (CoreException e) { e.printStackTrace(); LoggerEx.error(TAG, "Delete service " + key + " from docker " + OnlineServer.getInstance().getServer() + " failed, " + e.getMessage()); } } } } } } } catch (IOException e) { e.printStackTrace(); LoggerEx.error(TAG, "reload failed, " + e.getMessage()); } } private void unzip(File zipFile, String dir, String passwd) throws CoreException { ZipFile zFile = null; try { zFile = new ZipFile(zipFile); File destDir = new File(dir); if (destDir.isDirectory() && !destDir.exists()) { destDir.mkdir(); } if (zFile.isEncrypted()) { zFile.setPassword(passwd.toCharArray()); } zFile.extractAll(dir); List<FileHeader> headerList = zFile.getFileHeaders(); List<File> extractedFileList = new ArrayList<File>(); for (FileHeader fileHeader : headerList) { if (!fileHeader.isDirectory()) { extractedFileList.add(new File(destDir, fileHeader.getFileName())); } } File[] extractedFiles = new File[extractedFileList.size()]; extractedFileList.toArray(extractedFiles); } catch (net.lingala.zip4j.exception.ZipException e) { e.printStackTrace(); LoggerEx.error(TAG, "password is error,destFile:" + dir); } } @Override public synchronized void shutdown() { isShutdown = true; Collection<String> keys = scriptRuntimeMap.keySet(); for (String key : keys) { BaseRuntime runtime = scriptRuntimeMap.remove(key); if (runtime != null) { LoggerEx.info(TAG, "Service " + key + " is going to be removed, because of shutdown"); try { runtime.close(); LoggerEx.info(TAG, "Service " + key + " has been removed, because of shutdown"); } catch (Throwable t) { t.printStackTrace(); LoggerEx.info(TAG, "Service " + key + " remove failed, " + t.getMessage()); } } } } public String getRemotePath() { return remotePath; } public void setRemotePath(String remotePath) { this.remotePath = remotePath; } public String getLocalPath() { return localPath; } public void setLocalPath(String localPath) { this.localPath = localPath; } public DockerStatusService getDockerStatusService() { return dockerStatusService; } public void setDockerStatusService(DockerStatusService dockerStatusService) { this.dockerStatusService = dockerStatusService; } public Class<?> getBaseRuntimeClass() { return baseRuntimeClass; } public void setBaseRuntimeClass(Class<?> baseRuntimeClass) { this.baseRuntimeClass = baseRuntimeClass; } }
package com.classroom.services.facade.dto.entities; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.classroom.services.web.dto.mappers.LocalDateTimeAdapter; import org.joda.time.LocalDateTime; @XmlRootElement(name="searchCirculars") public class CircularSearchDTO{ private LocalDateTime startDate; private boolean isExam; private Integer id; /** * Gets the startDate. * * @return the startDate. */ @XmlJavaTypeAdapter(value = LocalDateTimeAdapter.class) public LocalDateTime getStartDate() { System.out.println("he " + startDate); return startDate; } public void setStartDate(LocalDateTime startDate) { this.startDate = startDate; } public boolean getIsExam() { return isExam; } public void setIsExam(boolean isExam) { this.isExam = isExam; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
package com.zxt.compplatform.formengine.action; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.zxt.compplatform.authority.entity.Role; import com.zxt.compplatform.authority.service.AuthorityFrameService; import com.zxt.compplatform.authority.service.FieldGrantService; import com.zxt.compplatform.codegenerate.service.ICodeGenerateService; import com.zxt.compplatform.formengine.entity.dataset.TableVO; import com.zxt.compplatform.formengine.entity.view.EditColumn; import com.zxt.compplatform.formengine.entity.view.Param; import com.zxt.compplatform.formengine.entity.view.Tab; import com.zxt.compplatform.formengine.entity.view.ViewColumn; import com.zxt.compplatform.formengine.entity.view.ViewPage; import com.zxt.compplatform.formengine.service.ComponentsService; import com.zxt.compplatform.formengine.service.IQueryXmlDataService; import com.zxt.compplatform.formengine.service.PageService; import com.zxt.compplatform.formengine.util.StrTools; import com.zxt.compplatform.formengine.util.TabPageUtil; import com.zxt.compplatform.organization.dao.OrganizationDao; /** * 查看页Action * @author 007 */ public class ViewPageAction extends ActionSupport { private static final Log log = LogFactory.getLog(ViewPageAction.class); private static final long serialVersionUID = 1L; /** * result 动态页面地址 */ String pageUrl; /** * 多标签页操作工具 */ private TabPageUtil tabPageUtil; /** * 暂时存储区域 */ public static Map map = new HashMap(); /** * 页面业务操作接口 */ private PageService pageService; /** * xml数据查询业务操作接口 */ private IQueryXmlDataService queryXmlDataService; /** * 代码生成操作接口 */ private ICodeGenerateService codeGenerateService; /** * 页面组件操作接口 */ private ComponentsService componentsService; /** * 展示查看页 * @return */ public String executeViewPage() { HttpServletRequest request = null; ViewPage viewPage = null; String urlParmer = "";//加载多标签传的页面参数 try { request = ServletActionContext.getRequest(); String formId = request.getParameter("formId"); request.setAttribute("formId", formId); String viewPageDivId = request.getParameter("viewPageDivId"); request.setAttribute("viewPageDivId", viewPageDivId); String parentAppId = request.getParameter("parentAppId"); viewPage = null; Param param=null; String key=""; String value=""; //第一次固化时。此参数值用于区分是否 在编辑页时VALUE显示的内容。 String valueDefine=request.getParameter("valueDefine"); if(valueDefine==null) valueDefine=""; request.setAttribute("valueDefine",valueDefine); map = pageService.load_service(formId); if (map != null) { viewPage = (ViewPage) map.get("viewPage"); } if (viewPage == null) { if ("0".equals(request.getParameter("preview"))) { return "preview-viewPage"; } else { return "view-page"; } } /** * 多标签获取主键参数,应替换获取页面参数 */ if (viewPage.getViewPageParams() != null) { for (int j = 0; j < viewPage.getViewPageParams().size(); j++) { param = (Param) viewPage.getViewPageParams().get(j); key = param.getKey().trim(); value = request.getParameter(key); value = StrTools.charsetFormat(value, "ISO8859-1", "UTF-8"); if ((value != null) && (!"".equals(value))) { urlParmer="&"+key+"="+value; } } request.setAttribute("urlParmer", urlParmer); } viewPage.setId(request.getParameter("formId").trim()); viewPage = componentsService.loadViewPage(viewPage, request); List list = viewPage.getViewColumn(); String appid = ""; for(int i = 0;i < list.size();i++){ ViewColumn viewColumn = (ViewColumn)list.get(i); if("APP_ID".equals(viewColumn.getName())){ appid = viewColumn.getData(); break; } } request.setAttribute("appid", appid); /** * 编辑页多标签 */ if (viewPage != null) { if (viewPage.getTabs() != null) { if (viewPage.getIsUseTab() != null) { if (viewPage.getIsUseTab().booleanValue()) { List tabPageList = viewPage.getTabs(); if (tabPageList != null) { Tab tab = null; for (int i = 0; i < tabPageList.size(); i++) { tab = (Tab) tabPageList.get(i); if (tab.getUrl().equals(viewPage.getId())) { tabPageList.remove(i); } } tabPageList = tabPageUtil.initTabList( tabPageList, request, null); viewPage.setTabs(tabPageList); } } } } } } catch (Exception e) { // TODO: handle exception } request.setAttribute("viewPage", viewPage); if ("0".equals(request.getParameter("preview"))) { return "preview-viewPage"; } if (viewPage != null && viewPage.getIsUseTab() != null && viewPage.getIsUseTab().booleanValue()) { return "loadTabViewPage"; } try { String customPath = request.getParameter("customPath"); if ((customPath != null) && (!"".equals(customPath))) { request.getRequestDispatcher(customPath).forward(request, ServletActionContext.getResponse()); return null; } } catch (Exception e) { // TODO Auto-generated catch block log.error("跳转异常"); } //目的得到表名称: String tableNameReal=null; List listView=viewPage.getTable(); TableVO tableVO=(TableVO)listView.get(0); if(tableVO.getName()==null){ log.error("ViewPageAction in tableName is null...//表名为空,需要在表单列表--》详情页中 重新保存一次即可解决。"); return "view-page"; }else{ tableNameReal=tableVO.getName(); } /** * AUTHOR:GUOWEIXIN * 1得到角色ID,表名 字段授权 编辑页--> 设计 * 2查询出数据库该角色相应的字段权限。再和现有的对比,筛选到相应结果 */ Long rid=null; /** * 得到当前角色名称,根据名称得到其角色ID */ String roleName=(String)request.getSession().getAttribute("stwitchRole");//在session范围中得到用户ID String ridReal = authorityFrameService.initAuthorityRidFrameByAccount(roleName); if(ridReal!=null) rid=new Long(ridReal); else return "view-page"; Map<Long,Map> mapRoot=(Map<Long,Map>)fieldGrantService.load_service(rid); if(mapRoot!=null){ Map<String,List> mapTable=mapRoot.get(rid); List strFields=mapTable.get(tableNameReal); if(strFields!=null){ //所有字段列 List listAll=viewPage.getViewColumn(); List resultAll=new ArrayList();//结果字段 if(listAll!=null){ for (int i = 0; i < listAll.size(); i++) { ViewColumn field=(ViewColumn)listAll.get(i); if(field!=null){ for(int j=0;j<strFields.size();j++){ String comStrField=(String)strFields.get(j); if(comStrField.equals(field.getName())){ resultAll.add(field); } } } } viewPage.setViewColumn(resultAll); } } } //-----end GUOWEIXIN //-----start lenny String forwardType = request.getParameter("forwardType");//固化功能 动态result String pageUrl = request.getParameter("pageUrl"); this.setPageUrl(pageUrl);//result 动态页面地址 if ("curing".equals(forwardType)){ return "curingPage"; //struts2 动态result 地址 } //-----end lenny return "view-page"; } public PageService getPageService() { return pageService; } public void setPageService(PageService pageService) { this.pageService = pageService; } public IQueryXmlDataService getQueryXmlDataService() { return queryXmlDataService; } public void setQueryXmlDataService(IQueryXmlDataService queryXmlDataService) { this.queryXmlDataService = queryXmlDataService; } public ICodeGenerateService getCodeGenerateService() { return codeGenerateService; } public void setCodeGenerateService(ICodeGenerateService codeGenerateService) { this.codeGenerateService = codeGenerateService; } public ComponentsService getComponentsService() { return componentsService; } public void setComponentsService(ComponentsService componentsService) { this.componentsService = componentsService; } public TabPageUtil getTabPageUtil() { return tabPageUtil; } public void setTabPageUtil(TabPageUtil tabPageUtil) { this.tabPageUtil = tabPageUtil; } /** * 字段授权 操作业务逻辑实体 SET注入 GUOWEIXIN */ private FieldGrantService fieldGrantService; public void setFieldGrantService(FieldGrantService fieldGrantService) { this.fieldGrantService = fieldGrantService; } /** * 权限框架业务操作接口 根据角色名称 得到其角色ID SET注入:GUOWEIXIN */ private AuthorityFrameService authorityFrameService; public AuthorityFrameService getAuthorityFrameService() { return authorityFrameService; } public void setAuthorityFrameService( AuthorityFrameService authorityFrameService) { this.authorityFrameService = authorityFrameService; } public String getPageUrl() { return pageUrl; } public void setPageUrl(String pageUrl) { this.pageUrl = pageUrl; } }
package controller; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; import model.MultiLayerImageProcessingModel; import model.SimpleMultiLayerImageProcessingModel; /** * The loadProject command function object used in the command pattern for the controller. */ public class LoadProject implements ImageProcessingCommands { private final String filepath; /** * Creates a LoadProject command object with the given filepath. * @param filepath the filepath * @throws IllegalArgumentException if the filepath is null */ public LoadProject(String filepath) throws IllegalArgumentException { if (filepath == null) { throw new IllegalArgumentException("Filepath must be given."); } this.filepath = filepath; } @Override public void run(MultiLayerImageProcessingModel m) throws IllegalArgumentException { if (m == null) { throw new IllegalArgumentException("The model given was null."); } File f = new File(filepath + "/" + "LayerAttributes.txt"); Scanner sc; try { sc = new Scanner(f); } catch (FileNotFoundException e) { throw new IllegalArgumentException("Text file cannot be found."); } List<String> filePaths = new ArrayList<>(); List<String> fileNames = new ArrayList<>(); List<Boolean> fileVisibility = new ArrayList<>(); while (sc.hasNextLine()) { String line1; String line2; String line3; try { line1 = sc.nextLine(); line2 = sc.nextLine(); line3 = sc.nextLine(); } catch (NoSuchElementException e) { throw new IllegalArgumentException("Text file is malformed."); } String filePath = line1; String name = line2; String visibility = line3; if (!visibility.equals("true") && !visibility.equals("false")) { System.out.println(visibility); throw new IllegalArgumentException("Visibility needs to be true or false."); } filePaths.add(filePath); fileNames.add(name); fileVisibility.add(Boolean.valueOf(visibility)); } SimpleMultiLayerImageProcessingModel tempModel = new SimpleMultiLayerImageProcessingModel(); for (int i = 0; i < filePaths.size(); i++) { tempModel.createLayer(fileNames.get(i)); try { new Load(filePaths.get(i)).run(tempModel); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("File path was invalid"); } if (fileVisibility.get(i)) { tempModel.setVisible(fileNames.get(i)); } else { tempModel.setInvisible(fileNames.get(i)); } } m.reset(tempModel); } }
package com.icanit.app.util; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public final class JSONUtil { private static JSONUtil self = new JSONUtil(); private JSONUtil(){} public static JSONUtil getInstance(){ return self; } public static void jsonArrayToList(JSONArray ja) throws JSONException{ } public static void jsonObjectToList(JSONObject jo,List list) throws JSONException{ } }
package com.ebanq.web.elements; import org.openqa.selenium.By; public class EbanqText extends ElementImpl implements Text { private final static String TEXT_ELEMENT_XPATH = "//*[contains(text(), '%s')]/parent::div"; private String label; public EbanqText(String label) { super(By.xpath(String.format(TEXT_ELEMENT_XPATH, label))); this.label = label; } @Override public String get() { return element.getText().replaceAll(".+\n", ""); } }
package com.rncodetest; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import java.util.Map; import java.util.HashMap; public class NativeInfo extends ReactContextBaseJavaModule { private static ReactApplicationContext reactContext; private static final String DURATION_SHORT_KEY = "SHORT"; private static final String DURATION_LONG_KEY = "LONG"; NativeInfo(ReactApplicationContext context) { super(context); reactContext = context; } @Override public String getName() { return "NativeInfo"; } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); String buildConfig = BuildConfig.BUILD_TYPE.toLowerCase(); String serviceKey = reactContext.getString(R.string.service_key_production); constants.put("ENVIRONMENT", buildConfig); if (buildConfig=="debug") { serviceKey = reactContext.getString(R.string.service_key); } constants.put("SERVICE_KEY", serviceKey); return constants; } @ReactMethod public void showServiceKey(Callback callback) { String serviceKey = reactContext.getString(R.string.service_key); callback.invoke(serviceKey); } }
package com.baseLucene; import org.junit.Test; public class LuceneTest03 { @Test public void search(){ SearcherUtil.termQuery(); } @Test public void searchPageByAfter(){ SearcherUtil.querySearcherPageByAfter(2, 10); } }
package br.assembleia.converter; import br.assembleia.entidades.Aluno; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Component; @Component("alunoConverter") public class AlunoConverter implements Converter { @PersistenceContext(unitName = "WeHaveSciencePU") private EntityManager em; @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { Aluno p = new Aluno(); p = em.find(Aluno.class, Long.valueOf(value)); return p; } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { return value.toString(); } }
import java.util.*; public class demo { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int sum=0; for(int i=0;i<=n;i++) sum+=i; System.out.print(sum); } }
package com.spring.testable.mock.manage; import com.spring.testable.mock.dao.HeroDao; import com.spring.testable.mock.pojo.entity.Hero; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * @author caijie */ @Component public class HeroManage { @Resource private HeroDao heroDao; public Hero getHeroInfoById(Long id){ return heroDao.heroinfo(id); } public boolean insert(Hero hero){ return heroDao.insert(hero); } public boolean update(Hero hero){ return heroDao.update(hero); } }
package v1; import java.util.Random; import java.util.concurrent.ExecutorService; public final class MasterVariables { static final int MASTER_GENERATIONS = 2, POPSIZE_PER_PROCESSOR = 53, MINRANDOM = 0, MAXRANDOM = 1, PROFILES_PER_CAT = 1000, MINSYSTEM = 2, MAXSYSTEM = 4, MAX_LEN = 10000, DEPTH = 5, TSIZE = 2, simulations = 100; static final int RANDOMNUMBERS = 50, CAPMED = RANDOMNUMBERS, CAPSTD = CAPMED + 1, CAPMIN = CAPSTD + 1, CAPMAX = CAPMIN + 1, MYCAP = CAPMAX + 1, OPPCAP = MYCAP + 1, MYSIDECAP = OPPCAP + 1, LEFTCAPSUM = MYSIDECAP + 1, MYENMITY = LEFTCAPSUM + 1, OPPENMITY = MYENMITY + 1, ADD = OPPENMITY + 1, SUB = ADD + 1, MUL = ADD + 2, DIV = ADD + 3, GT = ADD + 4, LT = ADD + 5, EQ = ADD + 6, AND = ADD + 7, OR = ADD + 8, TSET_1_START = CAPMED, TSET_1_END = LEFTCAPSUM, TSET_2_START = MYENMITY, TSET_2_END = OPPENMITY, FSET_1_START = ADD, FSET_1_END = DIV, FSET_2_START = GT, FSET_2_END = EQ, FSET_3_START = AND, FSET_3_END = OR; static final double RANDOMPLAYER_PROB = 0.01, ENHANCMENT_MARGIN = 0, PMUT_PER_NODE = 0, MOD_CROSSOVER_PROB = 0.1, REPLICATION_PROB = 0.1, CROSSOVER_PROB = 0.1, SUBTREE_MUT_PROB = 0.1, PMUT_PROB = 0.1, ABIOGENSIS_PROB = 0.5, GAUSS_PROB_FACTOR = 0; static final int INTERACTIONROUNDS = 2; static final boolean SIMULATECONSTRUCTIVISM = true; static final double[] randNum = new double[RANDOMNUMBERS];; static final Random rd = new Random(); static final int[] TESTCASES = { 100, 100, 100 }; static Strategy[] bestStrategies; static double[][] TestCasesCapabilities, TestCasesRandNums, TestCasesRandGauss; static double [][][] TestCasesCapChangeRates; static int[][] bestStrategiesOrder; static int[] testedStratgyIndexes; static int testedSize, testCases; static boolean setupCompleted; static World_System_Shell[][] profilingWorlds_Attacks, profilingWorlds_Joins; static ExecutorService executor; static WriteFile profiles_writer, state_profiles_writer; static int Threads, uniqueWorldSizes, currentSimulation, currentGen, TOTAL_POPSIZE_PER_DEME; MasterVariables() { for (int i = 0; i < RANDOMNUMBERS; i++) randNum[i] = (MAXRANDOM - MINRANDOM) * rd.nextDouble() + MINRANDOM; uniqueWorldSizes = 1 + MAXSYSTEM - MINSYSTEM; CheckErrors(); } public static void setupFitnessWorlds(Strategy[] bStrategies, int testedSize, int testCases) { if (setupCompleted) return; bestStrategies = bStrategies; TestCasesCapabilities = new double[testCases][]; TestCasesRandNums = new double[testCases][]; TestCasesRandGauss = new double[testCases][]; TestCasesCapChangeRates = new double[testCases][INTERACTIONROUNDS - 1][]; bestStrategiesOrder = new int[testCases][]; testedStratgyIndexes = new int[testCases]; MasterVariables.testedSize = testedSize; for (int test = 0; test < testCases; test++) { double remainder = 1; TestCasesCapabilities[test] = new double[testedSize]; for (int i = 0; i < testedSize - 1; i++) { TestCasesCapabilities[test][i] = remainder * rd.nextDouble(); remainder -= TestCasesCapabilities[test][i]; } TestCasesCapabilities[test][testedSize - 1] = remainder; // shuffle capabilities to ensure their uniform distribution for (int i = testedSize - 1; i > 0; i--) { int index = rd.nextInt(i + 1); double temp = TestCasesCapabilities[test][index]; TestCasesCapabilities[test][index] = TestCasesCapabilities[test][i]; TestCasesCapabilities[test][i] = temp; } TestCasesRandNums[test] = new double[(int) (Math.pow(testedSize, testedSize) * testedSize * INTERACTIONROUNDS)]; TestCasesRandGauss[test] = new double[(int) (Math.pow(testedSize, testedSize) * testedSize * INTERACTIONROUNDS)]; for (int i = 0; i < TestCasesRandNums[test].length; i++) { TestCasesRandNums[test][i] = rd.nextDouble(); TestCasesRandGauss[test][i] = rd.nextGaussian(); } for (int i = 0; i < INTERACTIONROUNDS - 1; i++) { TestCasesCapChangeRates[test][i] = new double[testedSize]; for (int k = 0; k < testedSize; k++) TestCasesCapChangeRates[test][i][k] = rd.nextDouble(); } testedStratgyIndexes[test] = rd.nextInt(testedSize); int[] order = new int[testedSize - 1]; for (int i = 0; i < testedSize - 1; i++) { order[i] = i; } int random; bestStrategiesOrder[test] = new int[testedSize - 1]; for (int i = 0; i < testedSize - 1; i++) { random = rd.nextInt(testedSize - 1); while (order[random] == -99) random = rd.nextInt(testedSize - 1); bestStrategiesOrder[test][i] = random; order[random] = -99; } } setupCompleted = true; } public static void resetFitnessWorlds() { bestStrategies = null; TestCasesCapabilities = null; TestCasesRandNums = null; TestCasesRandGauss = null; TestCasesCapChangeRates = null; bestStrategiesOrder = null; testedStratgyIndexes = null; testedSize = 0; testCases = 0; setupCompleted = false; } private void CheckErrors() { if (MASTER_GENERATIONS < 1 || POPSIZE_PER_PROCESSOR < 1 || PROFILES_PER_CAT < 1 || MINSYSTEM != 2 || MAXSYSTEM < 2 || MAX_LEN < 1 || DEPTH < 2 || TSIZE < 2 || simulations < 1 || INTERACTIONROUNDS < 1) { System.out.println("Too low value error"); System.exit(0); } if ((MINSYSTEM > MAXSYSTEM) || (TSET_1_START >= TSET_1_END) || (TSET_2_START >= TSET_2_END) || (FSET_1_START >= FSET_1_END) || (FSET_2_START >= FSET_2_END) || (FSET_3_START >= FSET_3_END)) { System.out.println("Illogical value error"); System.exit(0); } if (Math.abs(MOD_CROSSOVER_PROB + REPLICATION_PROB + CROSSOVER_PROB + SUBTREE_MUT_PROB + PMUT_PROB + ABIOGENSIS_PROB - 1) > 1E-10) { System.out.println("Sum error"); System.exit(0); } if (uniqueWorldSizes != TESTCASES.length) { System.out.println("Error!!! Test cases array and mina dn max system don't match!!"); System.exit(0); } } }
package com.javarush.task.task18.task1827; /* Прайсы */ import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws Exception { if(args.length != 0) { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String file = reader.readLine(); //Получаем все id из файла List<Integer> idList = new ArrayList(); String content; reader = new BufferedReader(new FileReader(file)); while(reader.ready()) { content = reader.readLine(); int id = Integer.parseInt(content.substring(0, 8).trim()); idList.add(id); } reader.close(); int max = Collections.max(idList); String id = String.format("%-8.8s", max + 1); String productName = String.format("%-30.30s", args[1]); String price = String.format("%-8.8s", args[2]); String quantity = String.format("%-4.4s", args[3]); String result = id + productName + price + quantity; BufferedWriter writer = new BufferedWriter(new FileWriter(file, true)); writer.newLine(); writer.write(result); writer.close(); } } }
package ug.tch; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; /** * Same as org.apache.hadoop.mapred.lib.LongSumReducer * only outputs (count, word) as opposed to (word, count) */ public class LongSumInvertedOutputReducer extends MapReduceBase implements Reducer<Text, LongWritable, LongWritable, Text> { private LongWritable outputValue = new LongWritable(); public void reduce(Text word, Iterator<LongWritable> values, OutputCollector<LongWritable, Text> output, Reporter reporter) throws IOException { long count = 0L; while (values.hasNext()) { LongWritable value = values.next(); count += value.get(); } outputValue.set(count); output.collect(outputValue, word); } }
package ar.edu.unju.fi.service; import ar.edu.unju.fi.model.Noticia; /** * * @author Damian Merlos *La Interfaz INoticiaService, es un servicio contiene metodos que se aplican a la clase Noticia. */ public interface INoticiaService { public void Guardar(); public Noticia mostrar(); public void eliminar(); public Noticia modificar(); }
// Problem URL : http://www.spoj.com/problems/JULKA/ import java.math.BigInteger; import java.util.Scanner; class Julka { public static void main(String args[]) { BigInteger total, lead; Scanner s = new Scanner(System.in); for (int i = 0; i < 10; i++) { total = s.nextBigInteger(); lead = s.nextBigInteger(); find f = new find(); f.findAnswer(total, lead); } } } class find { public BigInteger j, k, a; BigInteger two = new BigInteger("2"); public void findAnswer(BigInteger t, BigInteger l) { j = t.divide(two); a = l.divide(two); j = j.subtract(a); k = j.add(l); System.out.println(k + "\n" + j); } }
package ro.ase.csie.cts.g1093.lab3; import ro.ase.csie.cts.g1093.lab3.exceptions.InvalidAccountAgeException; import ro.ase.csie.cts.g1093.lab3.exceptions.InvalidPriceException; import ro.ase.csie.cts.g1093.lab3.stage1.Product; import ro.ase.csie.cts.g1093.lab3.stage1.ProductType; public class TestProduct { public static void main(String[] args) { Product product = new Product(); try { product.getFinalPrice(ProductType.NEW, 0, 0); } catch (InvalidPriceException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidAccountAgeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.example.mvvmdatabinding.Database; import android.content.Context; import android.os.AsyncTask; import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.sqlite.db.SupportSQLiteDatabase; import com.example.mvvmdatabinding.DAO.ProjectDao; import com.example.mvvmdatabinding.entity.Project; @Database(entities = {Project.class},exportSchema = false,version = 1) public abstract class ProjectDatabase extends RoomDatabase { public abstract ProjectDao mProjectDao(); public static ProjectDatabase INSTANCE; public static final String DATABASE_NAME = "project_db"; public static final Object LOCK = new Object(); public static final ProjectDatabase getInstance(Context context){ if(INSTANCE == null){ synchronized (LOCK){ if (INSTANCE == null){ INSTANCE = Room.databaseBuilder(context.getApplicationContext(), ProjectDatabase.class,DATABASE_NAME) .addCallback(sCallback) .build(); } } } return INSTANCE; } public static RoomDatabase.Callback sCallback = new RoomDatabase.Callback(){ @Override public void onCreate(@NonNull SupportSQLiteDatabase db) { super.onCreate(db); new PopulateDbAsyncTask(INSTANCE).execute(); } }; public static class PopulateDbAsyncTask extends AsyncTask<Void,Void,Void> { private ProjectDao mProjectDao; private PopulateDbAsyncTask(ProjectDatabase projectDatabase){ mProjectDao =projectDatabase.mProjectDao(); } @Override protected Void doInBackground(Void... voids) { mProjectDao.insert(new Project("MVVM","Android",7,1)); mProjectDao.insert(new Project("Caurotines","Kotlin",4,40)); mProjectDao.insert(new Project("Lambda","Java",3,2)); mProjectDao.insert(new Project("RxJava","Java",3,2)); mProjectDao.insert(new Project("Layouts","Architecture",1,2)); return null; } } }
import javax.swing.JComponent; public class Tela { public String nomeTela; public EnumMenus menu; public JComponent tela; public Tela (String nomeTela, EnumMenus menu, JComponent tela){ this.nomeTela = nomeTela; this.menu = menu; this.tela = tela; } }
import java.awt.*; import java.awt.event.*; class mix extends Frame implements ActionListener,AdjustementListener { TextField t1; Label l1,l2,l3,l4,l5,l6; Scrollbar sb1,sb2,sb3; public void de() { t1=new TextField(); l1=new Label("RED"); l2=new Label("GREEN"); l3=new Label("BLUE"); l4=new Label(); l5=new Label(); l6=new Label(); sb1=new Scrollbar("HSB1"); sb2=new Scrollbar("HSB2"); sb3=new Scrollbar("HSb3"); setLayout(null); l1.setBounds(30,30,100,30); sb1.setBounds(140,30,300,30); l2.setBounds(450,30,60,50); l3.setBounds(30,160,100,30); sb2.setBounds(140,160,300,30); l4.setBounds(450,160,100,30); l5.setBounds(30,180,100,30); sb3.setBounds(140,180,300,30); l6.setBounds(450,180,100,30); t1.setBounds(30,200,400,40); setBounds(30,30,500,500); show(); setBackground(Color.RED); add(l1); add(l2); add(l3); add(l4); add(l5); add(l6); add(sb1); add(sb2); add(sb3); sb1.addAdjustementListener(this); sb2.addAdjustementListener(this); sb3.addAdjustementListener(this); }//close of de()
import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; public class Common extends Agent { public Common(int id, double probOfMeeting) { super(id, probOfMeeting); } private boolean drawMeeting(Day[] days, Random r) { double probOfM = probOfMeeting; if(isInfected()) probOfM /= 2; if(r.nextDouble() <= probOfM) { if(this.getFriendsNumber() > 0) { int whoToMeet = r.nextInt(friends.size()); Agent toMeet = friends.get(whoToMeet); if(toMeet.condition != Condition.IMMUNE) days[r.nextInt(days.length)].addMeeting(new Meeting(this, toMeet)); return true; } } return false; } public void drawMeetings(Day[] days, Random r) { if(this.condition != Condition.IMMUNE) //inaczej spotkanie nie będzie miało żadnego efektu { while (drawMeeting(days, r)); } } }
package commandLineMenus.examples.lambda; import java.util.ArrayList; import commandLineMenus.List; public class ListActions { public static void main(String[] args) { java.util.List<String> people = new ArrayList<>(); people.add("Ginette"); people.add("Marcel"); people.add("Gisèle"); List<String> list = getPeopleList(people); list.start(); } private static List<String> getPeopleList(final java.util.List<String> people) { List<String> liste = new List<>("Select someone to display his name", () -> people, // The list to print (int index, String someone) -> System.out.println(someone) // what happens when a item is selected ); liste.setAutoBack(false); liste.addQuit("q"); return liste; } }
package org.wuxinshui.boosters.designPatterns.facade; /** * Created with IntelliJ IDEA. * User: FujiRen * Date: 2016/11/16 * Time: 17:12 * To change this template use File | Settings | File Templates. * <p> * 外观模式就是提供一个统一的接口,用来访问子系统中的一群接口。 */ public class WatchTVSwitchFacade { private Television tv; private Light light; private Screen screen; private AirCondition air; public WatchTVSwitchFacade(Television tv, Light light, Screen screen, AirCondition air) { this.tv = tv; this.light = light; this.screen = screen; this.air = air; } public void on() { System.out.println("正在启动电器。。。"); tv.on(); light.on(); screen.down(); air.on(); } public void off() { System.out.println("正在关闭电器。。。"); tv.off(); light.off(); screen.up(); air.off(); } }
package fruit; public class Lemon extends Citrus { private int sourness; public Lemon() { super.setColor("yellow"); } public Lemon(int sourness, String taste, boolean rotten) { super(taste, "yellow", rotten); this.sourness = sourness; } public int getSourness() { return sourness; } public void setSourness(int sourness) { this.sourness = sourness; } public String toString() { return "Lemon[" + super.toString() + ", sourness=" + this.sourness + "]"; } public boolean equals(Object o) { if (super.equals(o)) { if (o instanceof Lemon) { Lemon l1 = (Lemon)o; if (this.sourness == l1.sourness) { return true; } } } return false; } public static void main (String[] args) { Lemon lemon1 = new Lemon(5, "bitter", true); System.out.println(lemon1.toString()); Lemon lemon2 = new Lemon(); System.out.println(lemon2.toString()); lemon2.setSourness(10); lemon2.setTaste("sweet and sour"); System.out.println(lemon2.toString()); } }
package kata.model; import java.time.LocalDateTime; public class Message { private String messageText; private LocalDateTime messageTime; public Message(String messageText) { this.messageText = messageText; this.messageTime = LocalDateTime.now(); } public String getMessageText() { return this.messageText; } public void setMessageText(String messageText) { this.messageText = messageText; } public LocalDateTime getMessageTime() { return this.messageTime; } public void setMessageTime(LocalDateTime messageTime) { this.messageTime = messageTime; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Super_ascii { public static int main(String[] args) { // TODO Auto-generated method stub //Accepting the no of strings to work with int number = 0,i; int j; BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); try { number=Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { // TODO Auto-generated catch block System.out.println("there is some problem with input"); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("there is some problem with input"); } if(number>0 && number>100){ return -1; } //no of test cases accepted String array[]=new String[number]; //now proceeding to accept T lines of text for ( i = 0; i < number; i++) { try { array[i]=br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("there is some problem with input please retry"); } } //now logic if (array[i].length() > 400 || array[i].length()<0) { return -1; } int ascii, flag = 0; for (i = 0; i< number; i++) { for ( j = 0; j < array[i].length(); j++) { //ascii generation char c=array[i].charAt(j); ascii=array[i].charAt(j); ascii-=96; int count = 0,k; //for checking purpose for ( k = 0; k < array[i].length(); k++) { if(c==array[i].charAt(k)){ count++; } } //the final checking if (count==ascii) { flag=1; continue; } else { flag=0; break; } } //the final output if (flag==1) { System.out.println(array[i]+"\t"+ "yes"); } else { System.out.println(array[i]+"\t"+ "no"); } } return -1; } }
/* * Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webui.common.identities; import java.sql.Date; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.types.basic.Identity; import pl.edu.icm.unity.types.basic.IdentityParam; import pl.edu.icm.unity.types.basic.IdentityTypeDefinition; import pl.edu.icm.unity.types.confirmation.ConfirmationInfo; /** * Utility class presenting an {@link Identity} or {@link IdentityParam} in web-ready and readable form. * * @author K. Benedyczak */ public class IdentityFormatter { public static String toString(UnityMessageSource msg, Identity id) { StringBuilder sb = new StringBuilder(); boolean verifiable = id.getType().getIdentityTypeProvider().isVerifiable(); sb.append(toStringSimple(msg, id.getValue(), id, verifiable)); if (id.getCreationTs() != null && id.getUpdateTs() != null) { sb.append(" "); sb.append(msg.getMessage("IdentityFormatter.timestampsInfo", id.getCreationTs(), id.getUpdateTs())); } return sb.toString(); } public static String toString(UnityMessageSource msg, IdentityParam id, IdentityTypeDefinition idType) { return toStringSimple(msg, id.getValue(), id, idType.isVerifiable()); } private static String toStringSimple(UnityMessageSource msg, String coreValue, IdentityParam id, boolean verifiable) { StringBuilder sb = new StringBuilder(); sb.append(msg.getMessage("IdentityFormatter.identityCore", id.getTypeId(), coreValue)); if (verifiable) sb.append(getConfirmationStatusString(msg, id.getConfirmationInfo())); sb.append(getRemoteInfoString(msg, id)); return sb.toString(); } public static String getConfirmationStatusString(UnityMessageSource msg, ConfirmationInfo cdata) { StringBuilder rep = new StringBuilder(); if (cdata != null) { rep.append(" "); if (cdata.isConfirmed()) { rep.append(msg.getMessage("VerifiableEmail.confirmed", new Date(cdata.getConfirmationDate()))); } else { if (cdata.getSentRequestAmount() == 0) rep.append(msg.getMessage("VerifiableEmail.unconfirmed")); else rep.append(msg.getMessage("VerifiableEmail.unconfirmedWithRequests", cdata.getSentRequestAmount())); } } return rep.toString(); } private static String getRemoteInfoString(UnityMessageSource msg, IdentityParam id) { StringBuilder rep = new StringBuilder(); if (!id.isLocal()) { rep.append(" "); rep.append(msg.getMessage("IdentityFormatter.remoteInfo", id.getRemoteIdp())); if (id.getTranslationProfile() != null) { rep.append(" "); rep.append(msg.getMessage("IdentityFormatter.profileInfo", id.getTranslationProfile())); } } return rep.toString(); } }
package tugas; public class ListTest2 { public static void main(String[] args) { List ls = new List(); ls.addHead(1); ls.addHead(5); ls.addHead(3); ls.addHead(6); ls.addHead(2); ls.displayElement(); System.out.println(" "); System.out.println(" "); ls.removeTail(); ls.displayElement(); System.out.println(" "); System.out.println(" "); ls.removeHead(); ls.displayElement(); System.out.println(" "); System.out.println(" "); ls.removeTail(); ls.displayElement(); } }
package com.example.demo.mapper; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.example.demo.model.TbHistory201611; @RunWith(SpringRunner.class) @SpringBootTest public class TbHistory201611Test { @Autowired private TbHistory201611Mapper tbHistory201611Mapper; @Test public void testGetOne() throws Exception { TbHistory201611 history = tbHistory201611Mapper.getOne(80L); Integer hisId = history.getId(); Assert.assertEquals(hisId, Integer.valueOf((int) 80L)); } @Test public void testInsert() { TbHistory201611 history = tbHistory201611Mapper.getOne(80L); history.setPhone("15220289885"); tbHistory201611Mapper.insert(history); } }
package elements; public abstract class SpecialElement { private String name; protected int x, y; protected boolean inAir; public SpecialElement(String name, int x, int y, boolean inAir) { this.name = name; this.x = x; this.y = y; this.inAir = inAir; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isInAir() { return inAir; } public void setInAir(boolean inAir) { this.inAir = inAir; } }
package haircutter.bussinessmodel; import lombok.Getter; import lombok.Setter; public class LoginServiceModel { @Getter @Setter private Long serviceId; @Getter @Setter private String name; }
package lab3; import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class StartPoint extends Application { @Override public void start(Stage stage) throws Exception { final Parent root1 = FXMLLoader.load(getClass().getResource("/dmenu.fxml")); final Scene scene1 = new Scene(root1); stage.setScene(scene1); stage.setTitle("Color parameters"); stage.setMinWidth(scene1.getWindow().getWidth()); stage.setMinHeight(scene1.getWindow().getHeight()); stage.show(); Platform.runLater(() -> { try { new Lab().start(new Stage()); } catch (Exception e) { e.printStackTrace(); } }); } public static void main(String[] args) { launch(args); } }
package com.youthlin.example.reflect; import java.io.Serializable; /** * @author : youthlin.chen @ 2019-11-02 15:22 */ public class MyClass { public interface A { CharSequence get(); } public interface B { Serializable get(); } private static class ClassInner implements A, B { @Override public String get() { return "ClassInner"; } } public void sayHello() { System.out.println("Hello!"); } public A getALambda() { return () -> "Lambda"; } public A getAMethodClass() { class MethodInner implements A { @Override public String get() { return "MethodInner"; } } return new MethodInner(); } public A getAClassInner() { return new ClassInner(); } }
package com.eclipseop.discordbot.command.impl; import com.eclipseop.discordbot.Bot; import com.eclipseop.discordbot.command.Command; import com.eclipseop.discordbot.util.MessageBuilder; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.TextChannel; import java.util.Random; public class RollCommand extends Command { private final Random random; public RollCommand(Bot bot) { super(bot); random = new Random(); } @Override public String getPrefix() { return "r"; } @Override public MessageEmbed getHelpText() { MessageBuilder commands = new MessageBuilder("Roll Command"); commands.addField("**`r**: Rolls a random number 1-10."); commands.addField("**`r {max}**: Rolls a number 1-max."); commands.addField("**`r {min, max}**: Rolls a number min-max."); return commands.build(); } @Override public void execute(Message trigger) { TextChannel textChannel = trigger.getTextChannel(); String message = trigger.getContentRaw().trim(); MessageBuilder messageBuilder = new MessageBuilder(""); if (message.length() == 2) { messageBuilder.setTitle("Random number from 1-10"); messageBuilder.addField("" + (random.nextInt(10) + 1)); } else { try { message = trigger.getContentRaw().substring(3); String[] split = message.split(" "); if (split.length == 1) { int max = Integer.parseInt(split[0]); messageBuilder.setTitle("Random number from 1-" + max); messageBuilder.addField("" + (random.nextInt(max + 1) + 1)); } else { int min = Integer.parseInt(split[0]); int max = Integer.parseInt(split[1]); messageBuilder.setTitle("Random number from " + min + "-" + max); messageBuilder.addField("" + (random.nextInt(max + 1 - min) + min)); } } catch (NumberFormatException e) { getBot().sendMessage("Recieved a String, expected numbers!", textChannel); return; } } getBot().sendMessage(messageBuilder.build(), textChannel); } }
package com.pisen.ott.launcher.localplayer; import java.util.ArrayList; import java.util.List; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.izy.widget.DefaultPagerAdapter; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.pisen.ott.common.view.focus.DefaultKeyFocus.OnItemClickListener; import com.pisen.ott.launcher.R; import com.pisen.ott.launcher.base.DefaultActivity; import com.pisen.ott.launcher.widget.OTTWiatProgress; /** * 本地播放 * * @author yangyp */ public class LocalPlayerActivity extends DefaultActivity implements OnPageChangeListener, OnItemClickListener { public FileCategoryLayout menuLayout; private ViewPager vPager; private DefaultPagerAdapter browserAdapter; private GridViewPack frmFile; private GridViewPack frmVideo; private GridViewPack frmImage; private GridViewPack frmMusic; public OTTWiatProgress animViewVideo; public OTTWiatProgress animViewImage; public OTTWiatProgress animViewMusic; private VideoLocalPalyerPagerView videoView; private FileLocalPalyerPagerView fileView; private ImageLocalPalyerPagerView imageView; private MusicLocalPalyerPagerView musicView; // private List<LocalPalyerPagerViewBase> listPages;// 保存4个GridView /** * 刷新media数据 */ private void refreshMediaChanged() { int pos = vPager.getCurrentItem(); for (int i=1;i<browserAdapter.getCount();i++) { final GridViewPack page = (GridViewPack) browserAdapter.getItem(i); final LocalPalyerPagerViewBase gridView = page.getPagerView(); if (i == pos) { menuLayout.getChildAt(i).requestFocus(); } final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { ((LocalPalyerPagerAdapter) gridView.getAdapter()).setData((List<AlbumData>) msg.obj); //page.cancelAnim(); } }; (new Thread() { @Override public void run() { Message msg = new Message(); msg.obj = gridView.findAlbums(LocalPlayerActivity.this); msg.setTarget(handler); handler.sendMessage(msg); } }).start(); } } private void refreshFileChanged() { int pos = vPager.getCurrentItem(); LocalPalyerPagerViewBase gridView =(LocalPalyerPagerViewBase) ((GridViewPack)browserAdapter.getItem(0)).getPagerView(); ((LocalPalyerPagerAdapter) gridView.getAdapter()).setData(gridView.findAlbums(this)); vPager.setCurrentItem(pos); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.localplayer); menuLayout = (FileCategoryLayout) findViewById(R.id.menuLocalPlayer); menuLayout.setOnItemClickListener(this); //frmFile = new GridViewPack(this); //frmVideo = new GridViewPack(this); //frmImage = new GridViewPack(this); //frmMusic = new GridViewPack(this); browserAdapter = new DefaultPagerAdapter(); initImagePage(new FileLocalPalyerPagerView(this),GridViewPack.FRM_FILE_ID); initImagePage(new VideoLocalPalyerPagerView(this),GridViewPack.FRM_VIDEO_ID); initImagePage(new ImageLocalPalyerPagerView(this),GridViewPack.FRM_IMAGE_ID); initImagePage(new MusicLocalPalyerPagerView(this),GridViewPack.FRM_MUSIC_ID); vPager = (ViewPager) findViewById(R.id.vPager); vPager.setAdapter(browserAdapter); vPager.setOffscreenPageLimit(browserAdapter.getCount() - 1); vPager.setOnPageChangeListener(this); menuLayout.setvPager(vPager); /*listPages = new ArrayList<LocalPalyerPagerViewBase>(); listPages.add(fileView); listPages.add(videoView); listPages.add(imageView); listPages.add(musicView);*/ // 注册Usb插拔广播 IntentFilter iFilter = new IntentFilter(); iFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); iFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); iFilter.addDataScheme("file"); registerReceiver(usbReceiver, iFilter); } private void initFilePage() { LinearLayout emptyFile = (LinearLayout) getLayoutInflater().inflate(R.layout.empty, null, false); fileView = new FileLocalPalyerPagerView(this); frmFile.addView(fileView); frmFile.addView(emptyFile); frmFile.setId(GridViewPack.FRM_FILE_ID); fileView.setEmptyView(emptyFile); browserAdapter.add(frmFile); } private void initVideoPage() { LinearLayout emptyVideo = (LinearLayout) getLayoutInflater().inflate(R.layout.empty, null, false); animViewVideo = new OTTWiatProgress(this); animViewVideo.setVisibility(View.GONE); FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER; animViewVideo.setLayoutParams(lp); videoView = new VideoLocalPalyerPagerView(this); frmVideo.addView(videoView); frmVideo.addView(emptyVideo); frmVideo.addView(animViewVideo); frmVideo.setId(GridViewPack.FRM_VIDEO_ID); videoView.setEmptyView(emptyVideo); browserAdapter.add(frmVideo); } private void initImagePage(LocalPalyerPagerViewBase pageView,int id) { GridViewPack page = new GridViewPack(this, menuLayout, pageView, id); browserAdapter.add(page); pageView.asyncLoadData(); } private void initMusicPage() { LinearLayout emptymusic = (LinearLayout) getLayoutInflater().inflate(R.layout.empty, null, false); animViewMusic = new OTTWiatProgress(this); animViewMusic.setVisibility(View.GONE); FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER; animViewMusic.setLayoutParams(lp); musicView = new MusicLocalPalyerPagerView(this); frmMusic.addView(musicView); frmMusic.addView(emptymusic); frmMusic.addView(animViewMusic); frmMusic.setId(GridViewPack.FRM_MUSIC_ID); musicView.setEmptyView(emptymusic); browserAdapter.add(frmMusic); } @Override protected void onDestroy() { unregisterReceiver(usbReceiver); super.onDestroy(); } private BroadcastReceiver usbReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { // 刷新 refreshFileChanged(); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { // 刷新 refreshFileChanged(); //加载媒体动画 for (int i=1;i<browserAdapter.getCount();i++) { GridViewPack page = (GridViewPack) browserAdapter.getItem(i); page.showAnim(); } } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { // 刷新 refreshMediaChanged(); //取消媒体动画 for (int i=1;i<browserAdapter.getCount();i++) { GridViewPack page = (GridViewPack) browserAdapter.getItem(i); page.cancelAnim(); } } } }; @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int position) { menuLayout.setIndex(position); } @Override public void onItemClick(View v) { switch (v.getId()) { case R.id.btnFileLocalPlayer: vPager.setCurrentItem(0); break; case R.id.btnVideoLocalPlayer: vPager.setCurrentItem(1); break; case R.id.btnImageLocalPlayer: vPager.setCurrentItem(2); break; case R.id.btnMusicLocalPlayer: vPager.setCurrentItem(3); break; } } // public List<LocalPalyerPagerViewBase> getListPages() { // return listPages; // } public ViewPager getPager() { return vPager; } public DefaultPagerAdapter getBrowserAdapter() { return browserAdapter; } }
package variaveis; import javax.swing.JOptionPane; public class Carrinho { public static void main(String[] args) { String nome_prod = JOptionPane.showInputDialog("Digite o nome"); String cate_prod = JOptionPane.showInputDialog("Digite categoria produto"); double valor_prod = Double.parseDouble(JOptionPane.showInputDialog("Digite o valor")); double qtidade_prod = Double.parseDouble(JOptionPane.showInputDialog("Digite a Quantidade do Produto")); double imposto_prod = Double.parseDouble(JOptionPane.showInputDialog("Digite o Imposto")); double total_semimp = valor_prod*qtidade_prod; double total_ci = total_semimp + (total_semimp * (imposto_prod/100)) ; double valor_imp = total_ci - total_semimp; double total_cid = total_ci - (total_ci * 0.10) ; System.out.println("Nome: "+ nome_prod); System.out.println("Categoria: "+ cate_prod); System.out.println("Valor: "+ valor_prod); System.out.println("Quantidade: "+ qtidade_prod); System.out.println("Imposto: "+ imposto_prod); System.out.println("Total sem Imposto: "+ total_semimp); System.out.println("Total com Imposto: "+ total_ci); System.out.println("Valor Imposto: "+ valor_imp); System.out.println("Total com Imposto + 10% Desconto: "+ total_cid); } }
package com.microsoft.firstapp; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Aty1 extends Activity { private Button btnClose; // private TextView tvOut; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.aty1); // btnClose = (Button) findViewById(R.id.btnClose); // btnClose.setOnClickListener(new View.OnClickListener() { // // @Override // public void onClick(View v) { // // TODO Auto-generated method stub // // // Intent i = new Intent(); // // i.putExtra("result", "Hello MainActivity"); // // // // setResult(0, i); // // //finish(); // Intent i = new Intent(Aty1.this, SignUpActivity.class); // startActivity(i); // } // }); // data transfer // tvOut = (TextView) findViewById(R.id.tvOut); // tvOut.setText(getIntent().getStringExtra("txt")); // Bundle data = getIntent().getExtras(); // String txt = data.getString("txt"); // tvOut.setText(txt); // ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // if (conMgr.getActiveNetworkInfo() == null // && !conMgr.getActiveNetworkInfo().isConnected() // && !conMgr.getActiveNetworkInfo().isAvailable()) { // // No connectivity - Show alert // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setMessage( // "Unable to reach server, \nPlease check your connectivity.") // .setTitle("TD RSS Reader") // .setCancelable(false) // .setPositiveButton("Exit", // new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, // int id) { // finish(); // } // }); // // AlertDialog alert = builder.create(); // alert.show(); // // } else { // // Connected - Start parsing // // new AsyncLoadXMLFeed().execute(); // } } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.tags.form; import jakarta.servlet.jsp.JspException; /** * The {@code <password>} tag renders an HTML 'input' tag with type 'password' * using the bound value. * * <h3>Attribute Summary</h3> * <table> * <thead> * <tr> * <th class="table-header col-first">Attribute</th> * <th class="table-header col-second">Required?</th> * <th class="table-header col-second">Runtime Expression?</th> * <th class="table-header col-last">Description</th> * </tr> * </thead> * <tbody> * <tr class="even-row-color"> * <td><p>accesskey</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Standard Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>alt</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Optional Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>autocomplete</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>Common Optional Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>cssClass</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Optional Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>cssErrorClass</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Optional Attribute. Used when the bound field has * errors.</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>cssStyle</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Optional Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>dir</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Standard Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>disabled</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Optional Attribute. Setting the value of this attribute to 'true' * will disable the HTML element.</p></td> * </tr> * <tr class="even-row-color"> * <td><p>htmlEscape</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>Enable/disable HTML escaping of rendered values.</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>id</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Standard Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>lang</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Standard Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>maxlength</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Optional Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>onblur</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>onchange</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>onclick</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>ondblclick</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>onfocus</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>onkeydown</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>onkeypress</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>onkeyup</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>onmousedown</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>onmousemove</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>onmouseout</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>onmouseover</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>onmouseup</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>onselect</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Event Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>path</p></td> * <td><p>true</p></td> * <td><p>true</p></td> * <td><p>Path to property for data binding</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>readonly</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Optional Attribute. Setting the value of this attribute to 'true' * will make the HTML element readonly.</p></td> * </tr> * <tr class="even-row-color"> * <td><p>showPassword</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>Is the password value to be shown? Defaults to false.</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>size</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Optional Attribute</p></td> * </tr> * <tr class="even-row-color"> * <td><p>tabindex</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Standard Attribute</p></td> * </tr> * <tr class="odd-row-color"> * <td><p>title</p></td> * <td><p>false</p></td> * <td><p>true</p></td> * <td><p>HTML Standard Attribute</p></td> * </tr> * </tbody> * </table> * * @author Rob Harrop * @author Rick Evans * @author Rossen Stoyanchev * @since 2.0 */ @SuppressWarnings("serial") public class PasswordInputTag extends InputTag { private boolean showPassword = false; /** * Is the password value to be rendered? * @param showPassword {@code true} if the password value is to be rendered */ public void setShowPassword(boolean showPassword) { this.showPassword = showPassword; } /** * Is the password value to be rendered? * @return {@code true} if the password value to be rendered */ public boolean isShowPassword() { return this.showPassword; } /** * Flags "type" as an illegal dynamic attribute. */ @Override protected boolean isValidDynamicAttribute(String localName, Object value) { return !"type".equals(localName); } /** * Return '{@code password}' causing the rendered HTML '{@code input}' * element to have a '{@code type}' of '{@code password}'. */ @Override protected String getType() { return "password"; } /** * The {@link PasswordInputTag} only writes its value if the * {@link #setShowPassword(boolean) 'showPassword'} property value is * {@link Boolean#TRUE true}. */ @Override protected void writeValue(TagWriter tagWriter) throws JspException { if (this.showPassword) { super.writeValue(tagWriter); } else { tagWriter.writeAttribute("value", processFieldValue(getName(), "", getType())); } } }
package com.fhsoft.word.service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.fhsoft.base.bean.Page; import com.fhsoft.model.PlaceName; import com.fhsoft.model.SubjectProperty; import com.fhsoft.model.Word; import com.fhsoft.word.dao.NameAndPlaceNameDao; @Service("nameService") @Transactional public class NameAndPlaceNameService { @Autowired private NameAndPlaceNameDao nameDao; @Resource private Set<String> nameTypeSet; /** * * @Description * @param pageNo * @param pageSize * @param subject * @param code * @param values * @return * @Date 2015-11-5 上午10:02:00 */ public Page list(int pageNo, int pageSize,PlaceName name){ return nameDao.list(pageNo, pageSize,name); } /** * * @Description * @param word * @Date 2015-11-5 下午3:21:46 */ public void addName(PlaceName name) { nameDao.addName(name); } /** * * @Description * @param word * @Date 2015-11-6 上午9:44:53 */ public void updateName(PlaceName name) { nameDao.updateName(name); } /** * * @Description * @param word * @Date 2015-11-6 上午9:58:19 */ public void delName(PlaceName name) { nameDao.delName(name); } /** * * @Description * @param list * @return * @Date 2015-11-16 下午4:22:34 */ public String save(List<PlaceName> list) { StringBuffer msg = new StringBuffer(); Map<String,Integer> map = new HashMap<String,Integer>(); for(int i = 0; i < list.size(); i++) { PlaceName name = list.get(i); if(!nameTypeSet.contains(name.getType())) { msg.append("第" + (i + 1) + "行类型错误,只能选择:人名或地名;\r\n"); } if(name.getName() == null || name.getName().trim().length() == 0) { msg.append("第" + (i + 1) + "行英文名称必填;\r\n"); } if(name.getCname() == null || name.getCname().trim().length() == 0) { msg.append("第" + (i + 1) + "行中文名称必填;\r\n"); } if(name.getName() != null && name.getName().trim().length() > 0) { if(nameDao.getWordByName(name.getName()).size() > 0) { msg.append("第" + (i + 1) + "行字词已存在;\r\n"); } else { if(map.containsKey(name.getName())) { msg.append("第" + (i + 1) + "行与"+map.get(name.getName())+"行重复;\r\n"); } else { map.put(name.getName(), i + 1); } } } if(name.getName() != null && name.getName().length() > 500) { msg.append("第" + (i + 1) + "行英文名称,最多只能输入200字符;\r\n"); } if(name.getCname() != null && name.getCname().length() > 500) { msg.append("第" + (i + 1) + "行中文名称,最多只能输入200字符;\r\n"); } } if(msg.length() > 0) { return msg.toString(); } nameDao.save(list); return "success"; } public List<SubjectProperty> getJctxOfYw() { return nameDao.getJctxOfYw(); } /** * * @Description 得到字词的教材体系 * @param word * @return * @Date 2015-12-7 下午5:17:24 */ public List<Word> getWordJctx(PlaceName name) { return nameDao.getWordJctx(name); } public List<PlaceName> getWordInfo(PlaceName name) { return nameDao.getWordById(name); } }
package com.iesvirgendelcarmen.POO.ejercicios; public class Libro { private String isbn; private String title; private String writer; private String gender; private int totalPages; public Libro(String isbn, String title, String writer, String gender, int totalPages) { this.isbn = isbn; this.title = title; this.writer = writer; this.gender = gender; this.totalPages = totalPages; } public Libro() {} // constructor por defecto, ya no lo crea java porque ya existe public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } @Override public String toString() { return " [isbn=" + isbn + ", title=" + title + ", writer=" + writer + ", gender=" + gender + ", totalPages=" + totalPages + "]"; } }
package com.markfeldman.recyclerview; public class DataProvider { private int img_res; private String teamName, teamLocation; public DataProvider(int img_res, String teamName, String teamLocation){ this.setImg_res(img_res); this.setTeamName(teamName); this.setTeamLocation(teamLocation); } public int getImg_res() { return img_res; } public void setImg_res(int img_res) { this.img_res = img_res; } public String getTeamName() { return teamName; } public void setTeamName(String teamName) { this.teamName = teamName; } public String getTeamLocation() { return teamLocation; } public void setTeamLocation(String teamLocation) { this.teamLocation = teamLocation; } }
package com.example.sample.usertribe.Activities; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.example.sample.usertribe.Helper.CustomDialog; import com.example.sample.usertribe.Helper.SharedHelper; import com.example.sample.usertribe.Model.UserAccount; import com.example.sample.usertribe.R; import com.example.sample.usertribe.utils.NetworkUtils; import com.example.sample.usertribe.utils.Utilities; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.squareup.picasso.Picasso; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class EditProfileActivity extends AppCompatActivity { private static String TAG="EditProdile"; public Context context=EditProfileActivity.this; public Activity activity=EditProfileActivity.this; CustomDialog customDialog; NetworkUtils helper; boolean isInternet; private ImageView profile; EditText profile_fname; EditText profile_lname; EditText profile_email; EditText profile_phone; EditText service_type; Button save; TextView changePasswordTxt; FirebaseStorage storage; StorageReference storageReference; DatabaseReference databaseReference; FirebaseAuth firebaseAuth; Uri filePathUri; private static final int Image_Request_Code = 432; String Storage_Path = "All_Image_Uploads/"; Utilities utils = new Utilities(); String id; Boolean isImageChanged = false; UserAccount userAccount=new UserAccount(); String fname,lname,mobile,mail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_profile); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("Edit Profile"); profile_fname=(EditText)findViewById(R.id.profile_fname); profile_lname=(EditText)findViewById(R.id.profile_lname); profile_email=(EditText)findViewById(R.id.profile_email); profile_phone=(EditText)findViewById(R.id.profile_phone); profile=(ImageView)findViewById(R.id.img_profile); save=(Button)findViewById(R.id.edit_profile_proceed); if(getIntent()!=null) { fname=getIntent().getStringExtra("fname"); lname=getIntent().getStringExtra("lname"); mobile=getIntent().getStringExtra("phone"); mail=getIntent().getStringExtra("email"); } profile_fname.setText(fname); profile_lname.setText(lname); profile_email.setText(mail); profile_phone.setText(mobile); if (!SharedHelper.getKey(context, "photo").equalsIgnoreCase("") && !SharedHelper.getKey(context, "photo").equalsIgnoreCase(null) && SharedHelper.getKey(context, "photo") != null) { Picasso.get() .load(SharedHelper.getKey(context, "photo")) .placeholder(R.drawable.ic_dummy_user) .error(R.drawable.ic_dummy_user) .into(profile); } else { Picasso.get() .load(R.drawable.ic_dummy_user) .placeholder(R.drawable.ic_dummy_user) .error(R.drawable.ic_dummy_user) .into(profile); } save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Pattern ps = Pattern.compile(".*[0-9].*"); Matcher firstName = ps.matcher(profile_fname.getText().toString()); Matcher lastName = ps.matcher(profile_lname.getText().toString()); if (profile_email.getText().toString().equals("") || profile_email.getText().toString().length() == 0) { displayMessage("Enter Your Email ID."); } else if (profile_phone.getText().toString().equals("") || profile_phone.getText().toString().length() == 0) { displayMessage("Enter Yout Mobile Number."); } else if (profile_phone.getText().toString().length() < 10 || profile_phone.getText().toString().length() > 20) { displayMessage("Mobile number length must be in between 10 to 20 digits. "); } else if (profile_fname.getText().toString().equals("") || profile_fname.getText().toString().length() == 0) { displayMessage("First name is Empty."); } else if (profile_lname.getText().toString().equals("") || profile_lname.getText().toString().length() == 0) { displayMessage("Last name is Empty."); } else if (firstName.matches()) { displayMessage("First name do not accept numbers."); } else if (lastName.matches()) { displayMessage("Last name do not accept numbers."); } else { if (isInternet) { updateProfile(); } else { displayMessage("Something went wrong"); } } } }); helper=new NetworkUtils(); isInternet=helper.isNetworkAvailable(context); storage = FirebaseStorage.getInstance(); storageReference = storage.getReference(); databaseReference= FirebaseDatabase.getInstance().getReference("Users"); firebaseAuth=FirebaseAuth.getInstance(); profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (checkStoragePermission()) { requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, 432); } else goToImageIntent(); } }); } private void updateProfile() { customDialog = new CustomDialog(context); customDialog.show(); customDialog.setCancelable(false); databaseReference.child(firebaseAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { customDialog.dismiss(); for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()) { if(dataSnapshot1.exists()) { dataSnapshot1.getRef().child("fname").setValue(profile_fname.getText().toString()); dataSnapshot1.getRef().child("lname").setValue(profile_lname.getText().toString()); dataSnapshot1.getRef().child("picture").setValue(SharedHelper.getKey(context,"photo")); // String fname = dataSnapshot1.child("fname").getValue().toString(); // String lname = dataSnapshot1.child("lname").getValue().toString(); // String photo=dataSnapshot1.child("picture").getValue().toString(); // SharedHelper.putKey(context,"fname",fname); // SharedHelper.putKey(context,"lname",lname); // SharedHelper.putKey(context,"photo",photo); startActivity(new Intent(EditProfileActivity.this,ProfileVisitActivity.class)); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == Image_Request_Code && resultCode == RESULT_OK && data != null && data.getData() != null ) { filePathUri = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePathUri); profile.setImageBitmap(bitmap); uploadImage(); } catch (IOException e) { e.printStackTrace(); } } } private void uploadImage() { if(filePathUri != null) { final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setTitle("Uploading..."); progressDialog.show(); progressDialog.setCancelable(false); StorageReference ref = storageReference.child("images/"+ System.currentTimeMillis() + "." + GetFileExtension(filePathUri)); ref.putFile(filePathUri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) { // databaseReference=FirebaseDatabase.getInstance().getReference("Driver"); // databaseReference.addListenerForSingleValueEvent(new ValueEventListener() { // @Override // public void onDataChange(DataSnapshot dataSnapshot) { // for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()) // { // id=dataSnapshot1.getKey(); // } // } // // @Override // public void onCancelled(DatabaseError databaseError) { // // } // }); progressDialog.dismiss(); SharedHelper.putKey(context,"photo",taskSnapshot.getDownloadUrl().toString()); // Query query=databaseReference.orderByChild("img"); // query.addListenerForSingleValueEvent(new ValueEventListener() { // @Override // public void onDataChange(DataSnapshot dataSnapshot) { // for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()) // { // dataSnapshot1.getRef().child("img").setValue(taskSnapshot.getDownloadUrl().toString()); // // } // } // // @Override // public void onCancelled(DatabaseError databaseError) { // // } // }); displayMessage("upload Successfull"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); displayMessage("Upload Failed"); } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot .getTotalByteCount()); progressDialog.setMessage("Uploaded "+(int)progress+"%"); } }); } } private String GetFileExtension(Uri uri) { ContentResolver contentResolver = getContentResolver(); MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); // Returning the file Extension. return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ; } private void goToImageIntent() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), Image_Request_Code); } private boolean checkStoragePermission() { return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 432) for (int grantResult : grantResults) if (grantResult == PackageManager.PERMISSION_GRANTED) goToImageIntent(); } public void displayMessage(String toastString) { utils.print("displayMessage", "" + toastString); Snackbar.make(getCurrentFocus(), toastString, Snackbar.LENGTH_SHORT) .setAction("Action", null).show(); } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); } @Override public void onBackPressed() { super.onBackPressed(); } @Override protected void onDestroy() { super.onDestroy(); } @Override protected void onStop() { super.onStop(); } }
package com.lxl.dao; import com.lxl.beans.vo.DfGroup; import com.lxl.beans.vo.DfItem; import com.lxl.beans.vo.ProductExtInfoItem; import java.util.List; public interface MyGroupAndItemMapper { List<DfGroup> selectGroupByType2Id(long typeid); List<DfItem> selectItemsByGroupId(long groupid); List<DfItem> selectItemsByProductId(long productId); }
package com.test.model; import java.io.Serializable; import lombok.Data; @SuppressWarnings("serial") @Data public class City implements Serializable { public Integer cityId; public String cityName; }
package common.util; import java.util.Date; import org.apache.commons.beanutils.Converter; public class StringConverter implements Converter { @Override public Object convert(Class type, Object value) { if (value == null) { return null; } else if (value instanceof Date) { return DateTimeUtil.convertDateToString((Date) value); } else if (value instanceof Long) { return Formater.formatNumber((Long) value); } else if (value instanceof Double) { return Formater.formatNumber((Double) value); } else { return value.toString(); } } }
package com.pdd.pop.sdk.http.api.response; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.PopBaseHttpResponse; public class PddPromotionCouponCloseResponse extends PopBaseHttpResponse{ /** * 关闭批次接口响应对象 */ @JsonProperty("promotion_coupon_batch_close_response") private PromotionCouponBatchCloseResponse promotionCouponBatchCloseResponse; public PromotionCouponBatchCloseResponse getPromotionCouponBatchCloseResponse() { return promotionCouponBatchCloseResponse; } public static class PromotionCouponBatchCloseResponse { /** * 是否关闭成功,true-成功,false-失败 */ @JsonProperty("is_success") private Boolean isSuccess; public Boolean getIsSuccess() { return isSuccess; } } }
package lang; public class StringBufferDemo { public StringBufferDemo() { // StringBuffer s = new StringBuffer("neyuH"); // s.insert(0, "napaJ sevol "); // s.reverse(); // System.out.println(s); String s = "admin (a, b, "; s = s.substring(0, s.length() - 2); s = s + ")"; System.out.println("<" + s + ">"); } public static void main(String args[]) { new StringBufferDemo(); } }
import java.util.Scanner; class GradeNilai { int nilai; public char huruf() { if (this.nilai >= 80) { return 'A'; } else if (this.nilai >= 70 && this.nilai < 80) { return 'B'; } else if (this.nilai >= 60 && this.nilai < 70) { return 'C'; } else if (this.nilai >= 50 && this.nilai < 60) { return 'D'; } else { return 'E'; } } } class NilaiMahasiswa { public static void main(String[] args) { GradeNilai nilaiPBO = new GradeNilai(); System.out.print("Berapakah Nilai Anda? "); Scanner keyboard = new Scanner(System.in); nilaiPBO.nilai = keyboard.nextInt(); System.out.println("Huruf dari nilai " + nilaiPBO.nilai + " = " + nilaiPBO.huruf()); } }
package com.zlsu.service.imp; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.zlsu.dao.PersionDao; import com.zlsu.doma.Persion; import com.zlsu.service.PersionService; @Service("persionService") public class PersionServiceImp implements PersionService { private PersionDao persionDao; public PersionDao getPersionDao() { return persionDao; } @Resource public void setPersionDao(PersionDao persionDao) { this.persionDao = persionDao; } @Override public void insert(Persion persion) { persionDao.insert(persion); } @Override public void deleteById(int id) { persionDao.deleteByid(id); } @Override public void updata(Persion persion) { persionDao.updata(persion); } @Override public List<Persion> findAll() { return persionDao.findAll(); } }
package sr.hakrinbank.intranet.api.service.bean; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PostFilter; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import sr.hakrinbank.intranet.api.model.LeaveOfAbsence; import sr.hakrinbank.intranet.api.repository.EmployeeRepository; import sr.hakrinbank.intranet.api.repository.LeaveRepository; import sr.hakrinbank.intranet.api.service.LeaveService; import sr.hakrinbank.intranet.api.util.Constant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class LeaveServiceBean implements LeaveService { @Autowired private LeaveRepository leaveRepository; @Autowired private EmployeeRepository employeeRepository; @Override @PostFilter("filterObject.deleted() == false") public List<LeaveOfAbsence> findAllLeave() { return leaveRepository.findAll(); } @Override public LeaveOfAbsence findById(long id) { return leaveRepository.findOne(id); } @Override public void updateLeave(LeaveOfAbsence LeaveOfAbsence) { leaveRepository.save(LeaveOfAbsence); } @Override public int countLeaveOfTheWeek() { List<LeaveOfAbsence> leaveOfAbsenceList = leaveRepository.findActiveLeave(); DateTime currentDate = new DateTime(); int weekOfCurrentDate = currentDate.getWeekOfWeekyear(); int yearOfCurrentDate = currentDate.getYear(); List<LeaveOfAbsence> countList = new ArrayList<>(); DateTime specificDate; int weekOfSpecificDate; int yearOfSpecificDate; for(LeaveOfAbsence LeaveOfAbsence : leaveOfAbsenceList){ specificDate = new DateTime(); weekOfSpecificDate = specificDate.getWeekOfWeekyear(); yearOfSpecificDate = specificDate.getYear(); if( (yearOfCurrentDate == yearOfSpecificDate) && (weekOfCurrentDate == weekOfSpecificDate) ){ countList.add(LeaveOfAbsence); } } return countList.size(); } @Override public List<LeaveOfAbsence> findAllActiveLeave() { return leaveRepository.findActiveLeave(); } @Override public List<LeaveOfAbsence> findByName(String qry) { return leaveRepository.findByEmployeeFullName(qry); } @Override public LeaveOfAbsence findByEmployee(Long empoyeeId) { return leaveRepository.findByEmployee(employeeRepository.findOne(empoyeeId)); } @Override public List<LeaveOfAbsence> findAllActiveLeaveByDate(String byDate) { if(byDate != null && !byDate.isEmpty() && byDate != "" && !byDate.contentEquals(Constant.UNDEFINED_VALUE) && !byDate.contentEquals(Constant.NULL_VALUE) && !byDate.contentEquals(Constant.INVALID_DATE)){ LocalDate localDate = LocalDate.parse(byDate, DateTimeFormatter.ofPattern(Constant.DATE_FIELD_FORMAT)); LocalDateTime todayStartOfDay = localDate.atStartOfDay(); Date startOfDay = Date.from(todayStartOfDay.atZone(ZoneId.systemDefault()).toInstant()); LocalDateTime todayEndOfDay = localDate.atTime(LocalTime.MAX); Date endOfDay = Date.from(todayEndOfDay.atZone(ZoneId.systemDefault()).toInstant()); return leaveRepository.findAllActiveLeaveByDate(startOfDay, endOfDay); } return null; } }
package com.meizu.scriptkeeper.broadcast; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.meizu.scriptkeeper.preferences.SchedulePreference; import com.meizu.scriptkeeper.schedule.ScheduleControl; import com.meizu.scriptkeeper.services.scriptkeeper.LifeKeeperService; import com.meizu.scriptkeeper.utils.Log; import com.meizu.scriptkeeper.schedule.monkey.MonkeyError; import java.io.File; import java.util.Calendar; /** * Author: jinghao * Date: 2014-11-04 */ public class BootReceiver extends BroadcastReceiver { public SchedulePreference pref_schedule; public ScheduleControl control; public File report; @Override public void onReceive(Context context, Intent intent) { this.pref_schedule = new SchedulePreference(context); this.control = new ScheduleControl(context); this.report = new File(pref_schedule.getJsonPath() + "report.json"); //reboot service Intent life = new Intent(context, LifeKeeperService.class); context.startService(life); //if reboot while task running, set reboot flag true. if(pref_schedule.isTaskRunning()){ Log.e("Fuck, system reboot while task running!"); //if monkey task remain, add reboot crash type. if (this.pref_schedule.isMonkeyRunning()) { control.insertMonkeyError(pref_schedule.getTaskId(), MonkeyError.TYPE_REBOOT + Calendar.getInstance().getTimeInMillis(), MonkeyError.INT_REBOOT); } new Thread(new Runnable() { @Override public void run() { try { while (LifeKeeperService.scriptkeeper == null){ Thread.sleep(1000); } //reboot LifeKeeperService.scriptkeeper.notifyReboot(); }catch (Exception e){ e.printStackTrace(); } } }).start(); } } }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.result.view.freemarker; import org.springframework.web.reactive.result.view.AbstractUrlBasedView; import org.springframework.web.reactive.result.view.UrlBasedViewResolver; /** * A {@code ViewResolver} for resolving {@link FreeMarkerView} instances, i.e. * FreeMarker templates and custom subclasses of it. * * <p>The view class for all views generated by this resolver can be specified * via the "viewClass" property. See {@link UrlBasedViewResolver} for details. * * @author Rossen Stoyanchev * @since 5.0 */ public class FreeMarkerViewResolver extends UrlBasedViewResolver { /** * Simple constructor. */ public FreeMarkerViewResolver() { setViewClass(requiredViewClass()); } /** * Convenience constructor with a prefix and suffix. * @param suffix the suffix to prepend view names with * @param prefix the prefix to prepend view names with */ public FreeMarkerViewResolver(String prefix, String suffix) { setViewClass(requiredViewClass()); setPrefix(prefix); setSuffix(suffix); } /** * Requires {@link FreeMarkerView}. */ @Override protected Class<?> requiredViewClass() { return FreeMarkerView.class; } @Override protected AbstractUrlBasedView instantiateView() { return (getViewClass() == FreeMarkerView.class ? new FreeMarkerView() : super.instantiateView()); } }
package hp.Seals.GetSolutionApiVsDB; public class KeyGetSolution<K1,K2> { public K1 event_Code; public K2 update_TS; private String short_Description; private String severity; //Constructor public KeyGetSolution(K1 event_Code, K2 update_TS) { this.event_Code = event_Code; this.update_TS = update_TS; } // Getter and setters methods public K1 getEvent_Code() { return event_Code; } public void setEvent_Code(K1 event_Code) { this.event_Code = event_Code; } public K2 getUpdate_TS() { return update_TS; } public void setUpdate_TS(K2 update_TS) { this.update_TS = update_TS; } public String getShort_Description() { return short_Description; } public void setShort_Description(String short_Description) { this.short_Description = short_Description; } public String getSeverity() { return severity; } public void setSeverity(String severity) { this.severity = severity; } @SuppressWarnings("rawtypes") @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; KeyGetSolution key = (KeyGetSolution) o; if (event_Code != null ? !event_Code.equals(key.event_Code) : key.event_Code != null) return false; if (update_TS != null ? !update_TS.equals(key.update_TS) : key.update_TS != null) return false; return true; } @Override public int hashCode() { int result = event_Code != null ? event_Code.hashCode() : 0; result = 31 * result + (update_TS != null ? update_TS.hashCode() : 0); return result; } @Override public String toString() { return "[ \"event_Code\": \"" + event_Code + "\" , \"update_TS\": \"" + update_TS + "\"" + " ]"; } }
package com.ipartek.apps.cartas; public class Carta { private Palo palo; private Numero numero; public Carta(Palo palo, Numero numero) { super(); this.palo = palo; this.numero = numero; } public Palo getPalo() { return palo; } public void setPalo(Palo palo) { this.palo = palo; } public Numero getNumero() { return numero; } public void setNumero(Numero numero) { this.numero = numero; } @Override public String toString() { return "Carta [palo=" + palo + ", numero=" + numero + "]"; } }
package com.mbms.service; import java.util.Collection; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Positive; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mbms.exceptions.CouponSystemException; import com.mbms.model.Coupon; import com.mbms.model.CouponCaregory; import com.mbms.model.Customer; import com.mbms.repository.CompanyRepository; import com.mbms.repository.CouponRepository; import com.mbms.repository.CustomerRepository; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; @Service @NoArgsConstructor @AllArgsConstructor public class CustomerServiceImpl implements CustomerService { @Autowired private CouponRepository couponRepository; @Autowired private CustomerRepository customerRepository; public boolean performLogin(String name, String password) { Customer customer = customerRepository.findByNameAndPassword(name, password); if (customer == null) { return false; } else { return true; } } @Override public void purchaseCoupon(int couponId, int customerId)throws CouponSystemException { // Check if the coupon exists. if (couponRepository.findById(couponId).isPresent()) { // Check if the customer already purchased this coupon. if (!checkIfCustomerAlraedyPurchasedCoupon(customerId, couponId)) { Coupon coupon = couponRepository.findById(couponId).get(); Customer customer = customerRepository.findById(customerId).get(); // Check if the amount of the coupon bigger then 0. if (coupon.getAmount() > 0) { // Reduces in 1 amount of coupons coupon.setAmount(coupon.getAmount() - 1); customer.addCoupon(coupon); } else { throw new CouponSystemException("the customer is alredy purcech the coupon"); } } } } @Override public Collection<Coupon> getAllCoupons() { return couponRepository.findAll(); } @Override public Coupon getCouponById(@Positive int id) throws CouponSystemException { if (couponRepository.findById(id).isPresent()) { return couponRepository.findById(id).get(); } else { throw new CouponSystemException("there is no coupon with this id "+ id); } } @Override public Collection<Coupon> getAllCustomerCoupons(@Positive int customerId) throws CouponSystemException { return couponRepository.couponsCustomerByCustomerId(customerId); } @Override public Customer getCustomer(@Positive int customerId) throws CouponSystemException { if (customerRepository.findById(customerId).isPresent()) { return customerRepository.findById(customerId).get(); } else { throw new CouponSystemException("Customer id number"+ customerId+"is not excist"); } } @Override public Collection<Coupon> getCouponByCategory(@NotNull int customerId,CouponCaregory category) { return couponRepository.findByCategory(category); } @Override public Collection<Coupon> getCouponLowerThanPrice(@Positive int customerId, double price) { return couponRepository.findByPriceLessThan(price); } @Override public Customer getCustomerByName(@NotBlank String name) throws CouponSystemException { Customer customer = customerRepository.findByName(name); if (customer == null) { throw new CouponSystemException("Customer name"+ name+ "is not excist"); } return customer; } @Override public boolean checkIfCustomerAlraedyPurchasedCoupon(int customerId, int couponId) { Coupon coupon = couponRepository.couponByCustomerIdAndCouponId(customerId, couponId); if (coupon == null) { return false; } else { return true; } } }
package com.inhatc.cs; import java.util.Map; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.inhatc.service.BoardService; @Controller @RequestMapping("/*") public class BoardController { private static final Logger logger = LoggerFactory.getLogger(BoardController.class); @Inject private BoardService service; @RequestMapping(value = "/cpu_bench", method = RequestMethod.GET) public void listAll(Model model) throws Exception { logger.info("show all list......................"); model.addAttribute("list", service.listAll()); } @RequestMapping(value = "/gpu_bench", method = RequestMethod.GET) public void listAll_gpu(Model model) throws Exception { logger.info("show all list......................"); model.addAttribute("list", service.listAll_gpu()); } }
/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.Reader; /** * * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class Test { public static Object lock = new Object(); public static boolean ready = false; public static void main(String[] args) throws Exception { // launch the server new Thread(new TestServer()).start(); // wait for the server to become ready while( !ready ) { synchronized( lock ) { lock.wait(1000); } } // reset the flag ready = false; // run the client new TestClient().run(); // wait for the server to finish processing data // from the client while( !ready ) { synchronized( lock ) { lock.wait(1000); } } System.exit(0); } }
package com.research; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; public class ProductDate { public static void main(String[] args) { //当前日期 Date currentDate = new Date(); //将日期转为long,方便计算(以格林维治为基础) long currentTime = currentDate.getTime(); //定义商品生产日期 Calendar productDate1 = Calendar.getInstance(); //calendar中月份从0开始的,所以10月对应的应该是9,炸了。。。 productDate1.set(2019, 9, 12); //将calendar 转换为date Date productDateFinal = productDate1.getTime(); long productDateFinalTime = productDateFinal.getTime(); //计算相隔的天数,算了算去,结果还不知道对不对。又炸一次 long intervalDay1 = (currentTime-productDateFinalTime)/1000/60/60/24; System.out.println("老版本实现商品距离今日有:"+intervalDay1+"天"); //java8 实现,一行代码 long intervalDay2 = ChronoUnit.DAYS.between(LocalDate.of(2019, 10, 12), LocalDate.now()); System.out.println("java8实现商品距离今日有:"+intervalDay2+"天"); } }
package com.mycompany.interacciondb; /** * @author elias */ public class datos { private static String email,Nombre; private static int id; public static void setEmail(String e){ email= e; } public static String getEmail(){ return email; } public static void setNombre(String nom){ Nombre= nom; } public static String getNombre(){ return Nombre; } public static int getId() { return id; } public static void setId(int i) { id = i; } }
package com.ufpr.tads.dac.facade; import com.ufpr.tads.dac.beans.FuncionarioBean; import com.ufpr.tads.dac.dao.impl.FuncionarioDAOimpl; import com.ufpr.tads.dac.exceptions.FuncionarioException; import java.util.ArrayList; public class FuncionarioFacade { static FuncionarioDAOimpl FuncionarioDAO = new FuncionarioDAOimpl(); public static FuncionarioBean getFuncionarioByLogin(String email, String senha) throws FuncionarioException{ return FuncionarioDAO.getFuncionarioLogin(email, senha); } public static ArrayList<FuncionarioBean> getAllFuncionarios() throws FuncionarioException{ return FuncionarioDAO.getAllFuncionarios(); } public static void novoFuncionario(FuncionarioBean f) throws FuncionarioException { FuncionarioDAO.setFuncionario(f); } public static void deleteFuncionario(int fId) throws FuncionarioException { FuncionarioDAO.deleteFuncionario(fId); } public static void updateFuncionario(FuncionarioBean f) throws FuncionarioException { FuncionarioDAO.updateFuncionario(f); } public static FuncionarioBean getFuncionarioById(int funcId) throws FuncionarioException { return FuncionarioDAO.getFuncionarioById(funcId); } }
package StringDemo; //将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg” public class StringTest { //方式一:转换为char[] public String reverse(String str,int startIndex,int endIndex){ if(str!=null){ char[] arr=str.toCharArray(); for(int x=startIndex,y=endIndex;x<=y;x++,y--){ char temp=arr[x]; arr[x]=arr[y]; arr[y]=temp; } String result=new String(arr); return result; } return null; } //方式二:使用StringBuffer/StringBuilder替换String public String reverse1(String str,int startIndex,int endIndex){ if(str!=null) { StringBuffer buffer = new StringBuffer(str.length()); buffer.append(str.substring(0,startIndex)); for(int x=endIndex;x>=startIndex;x--){ buffer.append(str.charAt(x)); } buffer.append(str.substring(endIndex+1)); return buffer.toString(); } return null; } //方式三:使用String的拼接 public String reverse2(String str,int startIndex,int endIndex){ if(str != null){ String reverse=str.substring(0,startIndex); for(int x=endIndex;x>=startIndex;x--){ reverse+=str.charAt(x); } reverse+=str.substring(endIndex+1); return reverse; } return null; } public static void main(String[] args) { StringTest test=new StringTest(); String str = "abcdefg"; String result=test.reverse(str,2,5); System.out.println(result); String result1=test.reverse1(str,2,5); System.out.println(result1); String result2=test.reverse2(str,2,5); System.out.println(result2); } }
package edu.mit.cci.wikipedia.experience; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.simpleframework.xml.core.Persister; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.mit.cci.wikipedia.experience.util.MapSorter; import edu.mit.cci.wikipedia.experience.xml.Api; public class XMLFetcher { private static final String ANSWER_FORMAT = "&format=xml"; private static final String DEFAULT_ENCODING = "UTF-8"; private static final String LANG_CODE = "en"; private static final int MAX_NUMBER_OF_EDITORS = 20; private final static Logger LOG = LoggerFactory.getLogger(XMLFetcher.class); public static void main(String []args) throws Exception { XMLFetcher xmlFetcher = new XMLFetcher(); // ---------------- // PAGE NAME // ---------------- String pageName = "The_Beatles"; List<String> topEditorsForPage = xmlFetcher.getTopEditorsForPage(LANG_CODE, pageName); for (String userName : topEditorsForPage) { String userDetailsXML = xmlFetcher.getUserDetails(userName); Api deserializedUsers = xmlFetcher.deserialize(userDetailsXML); Long userScore = deserializedUsers.generateScoreForUser(); System.out.println(userScore); } } private String getUserDetails(String userName) throws UnsupportedEncodingException { return executeHTTPRequest(generateUserDetailsRequestURL(LANG_CODE, userName)); } /** * @return List of the top MAX_NUMBER_OF_EDITORS user names with the * most edits for the given page */ private List<String> getTopEditorsForPage(String langCode, String pageName) throws Exception { String requestURL = generateRevisionRequestURL(langCode, pageName); String xmlResult = executeHTTPRequest(requestURL); Api xmlResultObject = deserialize(xmlResult); Map<String, Integer> ranking = xmlResultObject .generateRankingOfAllNonAnonymousUsers(); Map<String, Integer> sortedRanking = new MapSorter<String, Integer>().sortByValue(ranking); Iterator<String> iterator = sortedRanking.keySet().iterator(); List<String> topUsers = new LinkedList<String>(); for(int i = 0; i < MAX_NUMBER_OF_EDITORS && iterator.hasNext(); i++) { topUsers.add(iterator.next()); } return topUsers; } /** * Last 500 changes to page, no date restrictions */ private String generateRevisionRequestURL(String langCode, String pageName) { return "http://" + langCode + ".wikipedia.org/w/api.php?action=query&prop=revisions&titles=" + pageName + "&rvprop=user&rvlimit=500" + ANSWER_FORMAT; } /** * editcount and reg date */ private String generateUserDetailsRequestURL(String langCode, String userName) throws UnsupportedEncodingException { String userFields = URLEncoder.encode("editcount|registration", DEFAULT_ENCODING); String userNameEncoded = URLEncoder.encode(userName, DEFAULT_ENCODING); return "http://" + langCode + ".wikipedia.org/w/api.php?action=query&list=users&ususers=" + userNameEncoded + "&usprop=" + userFields + ANSWER_FORMAT; } /** * Executes HTTP Request and returns contents as String */ private String executeHTTPRequest(String url) { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet(url); LOG.debug("executing request " + httpget.getURI()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); return httpclient.execute(httpget, responseHandler); } catch (ClientProtocolException e) { LOG.error("ClientProtocolException", e); } catch (IOException e) { LOG.error("IOException", e); } finally { httpclient.getConnectionManager().shutdown(); } LOG.error("Problem while executing request"); return ""; } /** * Turns XML String into a Java object */ private Api deserialize(String s) throws Exception { return new Persister().read(Api.class, s); } }
/* * Created on 2005-5-8 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.aof.webapp.form.prm.bill; import com.aof.webapp.form.BaseForm; /** * @author CN01458 * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class EditLostRecordForm extends BaseForm { private String formAction; private Long lostRecordId; private Long billId; private String projectId; private String currency; private Float exchangeRate; private Double amount; private String note; /** * @return Returns the amount. */ public Double getAmount() { return amount; } /** * @param amount The amount to set. */ public void setAmount(Double amount) { this.amount = amount; } /** * @return Returns the billId. */ public Long getBillId() { return billId; } /** * @param billId The billId to set. */ public void setBillId(Long billId) { this.billId = billId; } /** * @return Returns the currency. */ public String getCurrency() { return currency; } /** * @param currency The currency to set. */ public void setCurrency(String currency) { this.currency = currency; } /** * @return Returns the currencyRate. */ public Float getExchangeRate() { return exchangeRate; } /** * @param currencyRate The currencyRate to set. */ public void setExchangeRate(Float currencyRate) { this.exchangeRate = currencyRate; } /** * @return Returns the formAction. */ public String getFormAction() { return formAction; } /** * @param formAction The formAction to set. */ public void setFormAction(String formAction) { this.formAction = formAction; } /** * @return Returns the lostRecordId. */ public Long getLostRecordId() { return lostRecordId; } /** * @param lostRecordId The lostRecordId to set. */ public void setLostRecordId(Long lostRecordId) { this.lostRecordId = lostRecordId; } /** * @return Returns the note. */ public String getNote() { return note; } /** * @param note The note to set. */ public void setNote(String note) { this.note = note; } /** * @return Returns the projectId. */ public String getProjectId() { return projectId; } /** * @param projectId The projectId to set. */ public void setProjectId(String projectId) { this.projectId = projectId; } }
package com.programacion.apuntes; //Inicio del Programa: 23/11/2020 import java.util.Scanner; public class Main { public static void main(String[] args) { Validacion obx = new Validacion(); //float res = obx.validarDato(); float res = obx.validaWhile(); System.out.println("Dato válido "+ res); } }
package com.dg.android.lcp.activities; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import android.app.Application; import android.content.res.Resources; import android.os.Build; import android.util.Log; import com.dg.android.lcp.utils.ExceptionHandler; public class ApplicationController extends Application { final static String TAG = "ApplicationController"; final static String APP_ID = "PYYznPetBdoHFpxM"; //final static String CHAIN_ID = "780"; private static File privateDirectory; public static boolean firstRun = true; public static boolean isFirstRun() { if (firstRun) { firstRun = false; return true; } else { return false; } } public static File getPrivateDirectory() { return privateDirectory; } private static String preferencesFileName = "gobbles"; public static String getPreferencesFileName() { return preferencesFileName; } private static Properties properties; public String getProperty(String property) { String result = null; if (properties != null) result = properties.getProperty(property); return result; } public void initialize() { Log.v(TAG, "Android OS " + Build.VERSION.RELEASE + " API Level " + Build.VERSION.SDK_INT + "\nMANUFACTURER : " + Build.MANUFACTURER + "\nMODEL : " + Build.MODEL + "\nBRAND : " + Build.BRAND + "\n"); privateDirectory = getExternalFilesDir(null); Resources resources = this.getResources(); InputStream rawResource = resources.openRawResource(R.raw.takataka); properties = new Properties(); try { properties.load(rawResource); } catch (IOException e) { ExceptionHandler.logException(e); e.printStackTrace(); } } @Override public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler()); Log.v(TAG, "Starting TakaTaka....."); initialize(); } }
package cn.edu.swufe.myapp; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; public class DBManager { private DBHelper dbHelper; private String TBNAME; public DBManager(Context context) { dbHelper = new DBHelper(context); TBNAME = DBHelper.TB_NAME; } public void add(Choices cho){ SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("question", cho.getQuestion()); values.put("result", cho.getResult()); values.put("time", cho.getTime()); db.insert(TBNAME, null, values); db.close(); } public void delete(int id){ SQLiteDatabase db = dbHelper.getWritableDatabase(); db.delete(TBNAME, "ID=?", new String[]{String.valueOf(id)}); db.close(); } public List<Choices> listAll(){ List<Choices> rateList = null; SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(TBNAME, null, null, null, null, null, null); if(cursor!=null){ rateList = new ArrayList<Choices>(); while(cursor.moveToNext()){ Choices item = new Choices(); item.setId(cursor.getInt(cursor.getColumnIndex("ID"))); item.setQuestion(cursor.getString(cursor.getColumnIndex("QUESTION"))); item.setResult(cursor.getString(cursor.getColumnIndex("RESULT"))); item.setTime(cursor.getString(cursor.getColumnIndex("TIME"))); rateList.add(item); } cursor.close(); } db.close(); return rateList; } public Choices findById(int id){ SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(TBNAME, null, "ID=?", new String[]{String.valueOf(id)}, null, null, null); Choices rateItem = null; if(cursor!=null && cursor.moveToFirst()){ rateItem = new Choices(); rateItem.setId(cursor.getInt(cursor.getColumnIndex("ID"))); rateItem.setQuestion(cursor.getString(cursor.getColumnIndex("QUESTION"))); rateItem.setResult(cursor.getString(cursor.getColumnIndex("RESULT"))); rateItem.setTime(cursor.getString(cursor.getColumnIndex("TIME"))); cursor.close(); } db.close(); return rateItem; } }
package com.springboot.racemanage.po; public class Teamer { private Integer id; private String uuid; private String proUuid; private String stuUuid; private String description; private String duty; private String stuname; private Integer progress; private String dutydescription; private String proame; private Integer status; @Override public String toString() { return "Teamer{" + "id=" + id + ", uuid='" + uuid + '\'' + ", proUuid='" + proUuid + '\'' + ", strUuid='" + stuUuid + '\'' + ", description='" + description + '\'' + ", duty='" + duty + '\'' + ", stuname='" + stuname + '\'' + ", progress=" + progress + ", dutydescription='" + dutydescription + '\'' + ", proame='" + proame + '\'' + ", status=" + status + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getProUuid() { return proUuid; } public void setProUuid(String proUuid) { this.proUuid = proUuid; } public String getStuUuid() { return stuUuid; } public void setStuUuid(String stuUuid) { this.stuUuid = stuUuid; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDuty() { return duty; } public void setDuty(String duty) { this.duty = duty; } public String getStuname() { return stuname; } public void setStuname(String stuname) { this.stuname = stuname; } public Integer getProgress() { return progress; } public void setProgress(Integer progress) { this.progress = progress; } public String getDutydescription() { return dutydescription; } public void setDutydescription(String dutydescription) { this.dutydescription = dutydescription; } public String getProame() { return proame; } public void setProame(String proame) { this.proame = proame; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } }
package javaapplication5; import java.awt.*; import java.applet.Applet; public class ex5_7 extends Applet { Label display; Panel bottom; Panel num_panel; Panel func_panel; Button number[] = new Button[10]; Button function[] = new Button[6]; public void init() { setLayout(new BorderLayout()); display = new Label("0", Label.RIGHT); add("North", display); bottom = new Panel(); bottom.setLayout(new BorderLayout()); num_panel = new Panel(); num_panel.setLayout(new GridLayout(4, 3)); for (int x = 9; x >= 0; x--) { number[x] = new Button((new String()).valueOf(x)); num_panel.add(number[x]); } function[4] = new Button("."); num_panel.add(function[4]); function[5] = new Button("="); num_panel.add(function[5]); bottom.add("Center", num_panel); func_panel = new Panel(); func_panel.setLayout(new GridLayout(4, 1)); function[0] = new Button("+"); function[1] = new Button("-"); function[2] = new Button("*"); function[3] = new Button("/"); for (int x = 0; x < 4; x++) func_panel.add(function[x]); bottom.add("East", func_panel); add("Center", bottom); } }
/** * Acts as a node wrapper around a TrainCar object. */ public class TrainCarNode { private TrainCarNode prev; private TrainCarNode next; private TrainCar car; public TrainCarNode() { } /** * @param car */ public TrainCarNode(TrainCar car) { this.car = car; } /** * @return node at prev */ public TrainCarNode getPrev() { return prev; } /** * @param prev the node before cursor */ public void setPrev(TrainCarNode prev) { this.prev = prev; } /** * @return node after cursor */ public TrainCarNode getNext() { return next; } /** * @param next the node after cursor */ public void setNext(TrainCarNode next) { this.next = next; } /** * @return TrainCar */ public TrainCar getCar() { return car; } /** * @param car */ public void setCar(TrainCar car) { this.car = car; } /** * toString method */ public String toString() { String str = ""; str += "Car Length: "; str += car.getCarLength(); str += "Car Weight: "; str += car.getCarWeight(); str += "Product name: "; str += car.getProductLoad().getProductName(); str += "Product Weight: "; str += car.getProductLoad().getWeight(); str += "Product Value: "; str += car.getProductLoad().getValue(); return str; } }
package com.yummy.modal; import javax.persistence.*; @Entity @Table(name = "menu") public class Menu { private Long id ; private Long shopid; private String name; @Id @GeneratedValue(strategy= GenerationType.AUTO) @Column(name = "id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "shopid") public Long getShopid() { return shopid; } public void setShopid(Long shopid) { this.shopid = shopid; } @Column(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.alex.patterns.prototype.example; public abstract class Car { /* some fields */ private int speed; public Car(int speed) { this.speed = speed; } public Car(Car car) { this.speed = car.speed; } /* Method for cloning object. It can also be an interface*/ public abstract Car clone(); }
package com.bridgelabz.employeePayroll; import java.util.List; public class EmployeePayrollFIleIOService { public void writeData(List<EmployeePayrollData> employeePayrollList) { } public int countEntries() { return 0; } public void printData() { } }
package patterns.structure.adaptor; public class LenovoComputer implements Computer { @Override public String readSD(SDCard sdCard) { if(null == sdCard) { System.out.println("请插入sd卡"); return null; } return sdCard.readSD(); } }
package de.hofuniversity.io.db; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * @author Michael Jahn, Markus Exner * */ public class Database { public Database() {} private Connection connection; public Connection getConnection(String dbname) throws Exception { if (this.getConnection() == null) { this.newConnection(dbname); } return this.connection; } private Connection getConnection() { return this.connection; } private void newConnection(String dbname) throws Exception { Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver") .newInstance(); DriverManager.registerDriver(driver); this.connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/" + dbname, "root", ""); } public void createSchema() throws Exception { Statement stmt = this.getConnection("mysql").createStatement(); for (String sql : getCreateDDL()) { if (sql.length() > 10) { stmt.execute(sql); } } stmt.close(); this.closeConnection(); } private String[] getCreateDDL() throws IOException { InputStream in = getClass().getResourceAsStream("soccer.sql"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line, sql = ""; while ((line = br.readLine()) != null) { sql += line + "\n"; } br.close(); return sql.split("[;]"); } public int getLastAutoId() throws Exception { Connection connection = this.getConnection(); if (connection == null) { return -2; } Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery("Select last_INSERT_ID()"); int id = res.next() ? res.getInt(1) : -1; stmt.close(); return id; } public void closeConnection() throws SQLException { if (this.connection != null) { this.connection.close(); this.connection = null; } } }
package net.tecgurus.exception; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice @RestController public class ManejeErroresPersonalizados extends ResponseEntityExceptionHandler{ @ExceptionHandler(Exception.class) public final ResponseEntity<ExceptionRespuesta> manejarTodasLasExcepciones(Exception ex, WebRequest request){ ExceptionRespuesta exceptionRspuesta = new ExceptionRespuesta( new Date(), null, ex.getMessage(), request.getDescription(true) ); return new ResponseEntity<ExceptionRespuesta>(exceptionRspuesta, HttpStatus.INTERNAL_SERVER_ERROR); } @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { //binding result guarda errores cuando algun dato no cuadra con el dto de entrada BindingResult br = ex.getBindingResult();//lista de errores List<ObjectError> errores = br.getAllErrors(); List<MensajeError> listaErrores = new ArrayList<MensajeError>(); for (ObjectError oError : errores) { MensajeError me = new MensajeError( oError.getObjectName(), oError.getCodes()[1], oError.getDefaultMessage(), "" ); listaErrores.add(me); } ExceptionRespuesta exceptionRspuesta = new ExceptionRespuesta( new Date(), listaErrores, "Fallo la validacion de campos", "Revisar lista de errores adjunta" ); return new ResponseEntity<Object> (exceptionRspuesta, HttpStatus.BAD_REQUEST); } }
package com.defalt.lelangonline.ui.register; import android.util.Patterns; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.defalt.lelangonline.R; import com.defalt.lelangonline.ui.login.LoggedInUserView; public class RegisterViewModel extends ViewModel { private MutableLiveData<RegisterFormState> registerFormState = new MutableLiveData<>(); private MutableLiveData<RegisterResult> registerResult = new MutableLiveData<>(); LiveData<RegisterFormState> getRegisterFormState() { return registerFormState; } LiveData<RegisterResult> getRegisterResult() { return registerResult; } public void registerDataChanged(String fullName, String email, String password) { if (!isFullNameValid(fullName)) { registerFormState.setValue(new RegisterFormState(R.string.form_invalid_username_empty, null, null)); } else if (!isEmailValid(email)) { registerFormState.setValue(new RegisterFormState(null, R.string.form_invalid_email, null)); } else if (!isPasswordValid(password)) { registerFormState.setValue(new RegisterFormState(null, null, R.string.form_invalid_password)); } else { registerFormState.setValue(new RegisterFormState(true)); } } private boolean isFullNameValid(String fullName) { return fullName != null && fullName.trim().length() >= 1; } private boolean isEmailValid(String email) { if (email.contains("@")) { return Patterns.EMAIL_ADDRESS.matcher(email).matches(); } else { return false; } } private boolean isPasswordValid(String password) { return password != null && password.trim().length() >= 8; } public void registerEnd(Boolean isSuccess, String message, String fullName) { if (isSuccess) { registerResult.setValue(new RegisterResult(new LoggedInUserView(fullName))); } else { registerResult.setValue(new RegisterResult(message)); } } }
package com.natsu.threaddemo.threadMethod; import com.natsu.threaddemo.threadMethod.Character.Hero; public class method_priority { final static Hero gareen = new Hero("gareen", 16, 1); final static Hero teemo = new Hero("teemo", 13, 1); final static Hero SA = new Hero("SA", 15, 1); final static Hero VS = new Hero("VS", 14, 1); public static void main(String[] args) { method_priority(); // method_without_priority(); } /** * 设置线程优先级 当线程处于竞争关系时, 优先级高的线程会有更大的几率获得CPU资源 */ public static void method_priority() { System.out.println("===== method_priority start ====="); Thread thread1 = new Thread() { @Override public void run() { while (!teemo.isDead()) { gareen.attackHero(teemo); } } }; Thread thread2 = new Thread() { @Override public void run() { while (!SA.isDead()) { VS.attackHero(SA); } } }; thread1.setPriority(Thread.MAX_PRIORITY); thread2.setPriority(Thread.MIN_PRIORITY); thread1.start(); thread2.start(); } public static void method_without_priority() { System.out.println("===== method_without_priority start ====="); Thread thread1 = new Thread() { @Override public void run() { while (!teemo.isDead()) { gareen.attackHero(teemo); } } }; Thread thread2 = new Thread() { @Override public void run() { while (!SA.isDead()) { VS.attackHero(SA); } } }; thread1.start(); thread2.start(); } }
package com.kevin.cloud.provider.api; import com.kevin.cloud.commons.dto.article.vo.SiColumnVo; import com.kevin.cloud.commons.dto.blog.dto.CommentDto; import com.kevin.cloud.commons.dto.blog.dto.TypeViewDto; import com.kevin.cloud.commons.dto.blog.vo.CommentVo; import com.kevin.cloud.commons.dto.cloud.dto.SmsDto; import com.kevin.cloud.commons.platform.dto.PageResult; import com.kevin.cloud.provider.domain.SiColumnType; import com.kevin.cloud.provider.domain.SiComment; import java.util.List; /** * @ProjectName: vue-blog-backend * @Package: com.kevin.cloud.provider.api * @ClassName: BlogService * @Author: kevin * @Description: * @Date: 2020/2/3 16:50 * @Version: 1.0 */ public interface BlogService { List<TypeViewDto> initTypesData(); List<CommentDto> initCommentData(Integer isReply); boolean commitComment(CommentVo commentVo); int commentLiks(String commentId); List<CommentDto> loadCommentData(String esId); boolean articleCommentSubmit(CommentVo commentVo); PageResult initColumnTypesData(SiColumnVo siColumnVo); int deleteColumn(SiColumnVo siColumnVo); int addTypes(SiColumnVo siColumnVo); int editType(SiColumnVo siColumnVo); List<SiColumnType> getTypeTags(); int testTransaction(SiComment siComment, String esId); }
package br.com.drem.entity; /** * @author AndreMart * @contacts: andremartins@outlook.com.br;andre.drem@gmail.com * @tel: 63 8412 1921 * @site: drem.com.br */ import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="pais") public class Pais { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE) private long idPais; @Column(name="nome") private String nome; @Column(name="sigla") private String sigla; @OneToMany(mappedBy="pais") List<Estado>estado; public long getIdPais() { return idPais; } public void setIdPais(long idPais) { this.idPais = idPais; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSigla() { return sigla; } public void setSigla(String sigla) { this.sigla = sigla; } public List<Estado> getEstado() { if(estado == null) { estado = new ArrayList<Estado>(); } return estado; } public void setEstado(List<Estado> estado) { this.estado = estado; } }
package com.xyzj.crawler.utils.gethtmlstring; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.util.CollectionUtils; /** * Created by paranoid on 17-4-10. * 进行代理访问 * <p> * setConnectTimeout:设置连接超时时间,单位毫秒. * setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒. * 这个属性是新加的属性,因为目前版本是可以共享连接池的. * setSocketTimeout:请求获取数据的超时时间,单位毫秒.如果访问一个接口,多少时间内无法返回数据, * 就直接放弃此次调用。 */ @Slf4j public class MyHttpResponse { public static String getHtmlWithProxyIp(String url, String ip, String port, String charset, Map<String, String> headerInfos) { if (StringUtils.isEmpty(charset)) { charset = "utf-8"; } String entity = null; CloseableHttpClient httpClient = HttpClients.createDefault(); //设置代理访问和超时处理 log.info("此时线程: " + Thread.currentThread().getName() + " 爬取所使用的代理为: " + ip + ":" + port); HttpHost proxy = new HttpHost(ip, Integer.parseInt(port)); RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(3000). setSocketTimeout(3000).build(); HttpGet httpGet = new HttpGet(url); httpGet.setConfig(config); // 遍历map 设置请求头信息 if (!CollectionUtils.isEmpty(headerInfos)) { for (String key : headerInfos.keySet()) { httpGet.setHeader(key, headerInfos.get(key)); } } try { //客户端执行httpGet方法,返回响应 CloseableHttpResponse httpResponse = httpClient.execute(httpGet); //得到服务响应状态码 if (httpResponse.getStatusLine().getStatusCode() == 200) { entity = EntityUtils.toString(httpResponse.getEntity(), "utf-8"); } httpResponse.close(); httpClient.close(); } catch (Exception e) { log.error("Exception:{}", e); } return entity; } public static String getHtml(String url, String charset, Map<String, String> headerInfos) { if (StringUtils.isEmpty(charset)) { charset = "utf-8"; } String entity = null; CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig config = RequestConfig.custom().setConnectTimeout(3000). setSocketTimeout(3000).build(); HttpGet httpGet = new HttpGet(url); httpGet.setConfig(config); // 遍历map 设置请求头信息 if (!CollectionUtils.isEmpty(headerInfos)) { for (String key : headerInfos.keySet()) { httpGet.setHeader(key, headerInfos.get(key)); } } try { //客户端执行httpGet方法,返回响应 CloseableHttpResponse httpResponse = httpClient.execute(httpGet); //得到服务响应状态码 if (httpResponse.getStatusLine().getStatusCode() == 200) { entity = EntityUtils.toString(httpResponse.getEntity(), "utf-8"); } httpResponse.close(); httpClient.close(); } catch (Exception e) { log.error("Exception:{}", e); } return entity; } }
package test; import java.util.ArrayList; public class Hand { ArrayList<Cards> hand = new ArrayList<>(); public void addCardToHand(Cards yourCard){ hand.add(yourCard); } public ArrayList<Cards> getHand() { return hand; } public void setHand(ArrayList<Cards> hand) { this.hand = hand; } }
package com.revature.service; import java.util.Set; import com.revature.model.Employee; import com.revature.model.Reimbursement; import com.revature.model.ReimbursementType; import com.revature.repository.ReimbursementRepositoryjdbc; public class ReimbursementServiceAlpha implements ReimbursementService { private static ReimbursementService reimbursementService = new ReimbursementServiceAlpha(); private ReimbursementServiceAlpha() {} public static ReimbursementService getInstance(){ return reimbursementService; } @Override public boolean submitRequest(Reimbursement reimbursement) { return ReimbursementRepositoryjdbc.getInstance().insert(reimbursement); } @Override public boolean finalizeRequest(Reimbursement reimbursement) { return ReimbursementRepositoryjdbc.getInstance().update(reimbursement); } @Override public Reimbursement getSingleRequest(Reimbursement reimbursement) { return ReimbursementRepositoryjdbc.getInstance().select(reimbursement.getId()); } @Override public Set<Reimbursement> getUserPendingRequests(Employee employee) { //Set<Reimbursement> reimbursements= ReimbursementRepositoryjdbc.getInstance().selectPending(employee.getId()); System.out.println("This is in service: "+ ReimbursementRepositoryjdbc.getInstance().selectPending(employee.getId())); return ReimbursementRepositoryjdbc.getInstance().selectPending(employee.getId()); } @Override public Set<Reimbursement> getUserFinalizedRequests(Employee employee) { Set<Reimbursement> reimbursements= ReimbursementRepositoryjdbc.getInstance().selectFinalized(employee.getId()); return reimbursements; } @Override public Set<Reimbursement> getAllPendingRequests() { Set<Reimbursement> reimbursements= ReimbursementRepositoryjdbc.getInstance().selectAllPending(); return reimbursements; } @Override public Set<Reimbursement> getAllResolvedRequests() { Set<Reimbursement> reimbursements= ReimbursementRepositoryjdbc.getInstance().selectAllFinalized(); return reimbursements; } @Override public Set<ReimbursementType> getReimbursementTypes() { Set<ReimbursementType> reimbursements= ReimbursementRepositoryjdbc.getInstance().selectTypes(); return reimbursements; } }
package me.oscardoras.claim.command; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Entity; import org.bukkit.permissions.Permission; import org.bukkit.scoreboard.Team; import me.oscardoras.claim.Message; import me.oscardoras.claim.claimable.Claim; import me.oscardoras.claim.claimable.Claimable; import me.oscardoras.claim.claimable.ProtectedClaim; import me.oscardoras.claim.owner.EntityOwner; import me.oscardoras.claim.owner.Owner; import me.oscardoras.claim.owner.TeamOwner; import me.oscardoras.claim.rule.ClaimRule; import me.oscardoras.claim.rule.RuleTarget; import me.oscardoras.spigotutils.command.v1_16_1_V1.Argument; import me.oscardoras.spigotutils.command.v1_16_1_V1.CommandRegister; import me.oscardoras.spigotutils.command.v1_16_1_V1.LiteralArgument; import me.oscardoras.spigotutils.command.v1_16_1_V1.CommandRegister.CommandExecutorType; import me.oscardoras.spigotutils.command.v1_16_1_V1.arguments.BooleanArgument; import me.oscardoras.spigotutils.command.v1_16_1_V1.arguments.OfflinePlayerArgument; import me.oscardoras.spigotutils.command.v1_16_1_V1.arguments.QuotedStringArgument; import me.oscardoras.spigotutils.command.v1_16_1_V1.arguments.ScoreboardTeamArgument; import net.md_5.bungee.api.chat.TextComponent; public final class ClaimCommand { private ClaimCommand() {} private static void register(LinkedHashMap<String, Argument<?>> arguments, ClaimCommandRunnable runnable) { CommandRegister.register("claim", arguments, new Permission("claim.command.claim"), CommandExecutorType.ENTITY, (cmd) -> { return runnable.run(cmd, new EntityOwner((Entity) cmd.getExecutor())); }); LinkedHashMap<String, Argument<?>> argu = new LinkedHashMap<>(); argu.put("claim_literal", new LiteralArgument("claim").withPermission(new Permission("claim.command.team"))); argu.putAll(arguments); CommandRegister.register("t", argu, new Permission("team.command.team"), CommandExecutorType.ENTITY, (cmd) -> { Team team = Bukkit.getScoreboardManager().getMainScoreboard().getEntryTeam(cmd.getExecutor().getName()); if (team != null) return runnable.run(cmd, new TeamOwner(team)); else { cmd.sendFailureMessage(new Message("sender.does_not_have_team")); return 0; } }); } public static void list() { LinkedHashMap<String, Argument<?>> arguments = new LinkedHashMap<>(); arguments.put("list", new LiteralArgument("list").withPermission(new Permission("claim.command.claim.list"))); register(arguments, (cmd, owner) -> { List<String> list = new ArrayList<String>(); for (ProtectedClaim protectedClaim : owner.getProtectedClaims()) { String name = protectedClaim.getName(); if (!list.contains(name)) list.add(name); } cmd.sendListMessage(list, new Object[] {new Message("command.claim.list.list")}, new Object[] {new Message("command.claim.list.empty")}); return list.size(); }); } public static void claim() { LinkedHashMap<String, Argument<?>> arguments = new LinkedHashMap<>(); arguments.put("claim", new LiteralArgument("claim").withPermission(new Permission("claim.command.claim.claim"))); register(arguments, (cmd, owner) -> { Claimable claimable = Claimable.get(cmd.getLocation().getChunk()); if (!(claimable instanceof Claim) || owner.equals(((Claim) claimable).getOwner())) { if (claimable.checkClaim(owner)) { claimable.claim(owner); cmd.sendMessage(new Message("command.claim.claim")); return 1; } else { cmd.sendFailureMessage(new Message("claim.is_too_far")); return 0; } } else if (((Claim) claimable).canBeStolen() || cmd.hasPermission("claim.ignore")) { if (claimable.checkClaim(owner)) { claimable.claim(owner); cmd.sendMessage(new Message("command.claim.steal")); return 1; } else { cmd.sendFailureMessage(new Message("claim.is_too_far")); return 0; } } else { cmd.sendFailureMessage(new Message("claim.can_not_be_stolen")); return 0; } }); } public static void unclaim() { LinkedHashMap<String, Argument<?>> arguments = new LinkedHashMap<>(); arguments.put("unclaim", new LiteralArgument("unclaim").withPermission(new Permission("claim.command.claim.unclaim"))); register(arguments, (cmd, owner) -> { Claimable claimable = Claimable.get(cmd.getLocation().getChunk()); if (claimable instanceof Claim) { Claim claim = (Claim) claimable; if (owner.equals(claim.getOwner())) { claim.unClaim(); cmd.sendMessage(new Message("command.claim.unclaim")); return 1; } else if (claim.canBeStolen() || cmd.hasPermission("claim.ignore")) { claim.unClaim(); cmd.sendMessage(new Message("command.claim.steal")); return 1; } else { cmd.sendFailureMessage(new Message("claim.can_not_be_stolen")); return 0; } } else { cmd.sendFailureMessage(new Message("claim.is_not_owned")); return 0; } }); } public static void protect() { LinkedHashMap<String, Argument<?>> arguments = new LinkedHashMap<>(); arguments.put("protect", new LiteralArgument("protect").withPermission(new Permission("claim.command.claim.protect"))); register(arguments, (cmd, owner) -> { Claimable claimable = Claimable.get(cmd.getLocation().getChunk()); if (!(claimable instanceof Claim) || owner.equals(((Claim) claimable).getOwner())) { claimable.protect(owner); cmd.sendMessage(new Message("command.claim.protect")); return 1; } else if (((Claim) claimable).canBeStolen() || cmd.hasPermission("claim.ignore")) { claimable.protect(owner); cmd.sendMessage(new Message("command.claim.steal")); return 1; } else { cmd.sendFailureMessage(new Message("claim.can_not_be_stolen")); return 0; } }); } public static void unprotect() { LinkedHashMap<String, Argument<?>> arguments = new LinkedHashMap<>(); arguments.put("unprotect", new LiteralArgument("unprotect").withPermission(new Permission("claim.command.claim.unprotect"))); register(arguments, (cmd, owner) -> { Claimable claimable = Claimable.get(cmd.getLocation().getChunk()); if (claimable instanceof Claim && owner.equals(((Claim) claimable).getOwner())) { if (claimable instanceof ProtectedClaim) { ((ProtectedClaim) claimable).unProtect(); cmd.sendMessage(new Message("command.claim.unprotect")); return 1; } else { cmd.sendFailureMessage(new Message("claim.is_not_protected")); return 0; } } else { cmd.sendFailureMessage(new Message("claim.is_not_owned")); return 0; } }); } public static void name() { LinkedHashMap<String, Argument<?>> arguments = new LinkedHashMap<>(); arguments.put("name_literal", new LiteralArgument("name").withPermission(new Permission("claim.command.claim.name"))); register(arguments, (cmd, owner) -> { Claimable claimable = Claimable.get(cmd.getLocation().getChunk()); if (claimable instanceof Claim && owner.equals(((Claim) claimable).getOwner())) { if (claimable instanceof ProtectedClaim) { cmd.sendMessage(new Message("command.claim.name.get", ((ProtectedClaim) claimable).getName())); return 1; } else { cmd.sendFailureMessage(new Message("claim.is_not_protected")); return 0; } } else { cmd.sendFailureMessage(new Message("claim.is_not_owned")); return 0; } }); arguments = new LinkedHashMap<>(); arguments.put("name_literal", new LiteralArgument("name").withPermission(new Permission("claim.command.claim.name"))); arguments.put("name", new QuotedStringArgument()); register(arguments, (cmd, owner) -> { Claimable claimable = Claimable.get(cmd.getLocation().getChunk()); if (claimable instanceof Claim && owner.equals(((Claim) claimable).getOwner())) { if (claimable instanceof ProtectedClaim) { ProtectedClaim protectedClaim = (ProtectedClaim) claimable; protectedClaim.setName((String) cmd.getArg(0)); cmd.sendMessage(new Message("command.claim.name.set", protectedClaim.getName())); return 1; } else { cmd.sendFailureMessage(new Message("claim.is_not_protected")); return 0; } } else { cmd.sendFailureMessage(new Message("claim.is_not_owned")); return 0; } }); } public static void rule() { for (ClaimRule rule : ClaimRule.values()) { LinkedHashMap<String, Argument<?>> arguments = new LinkedHashMap<>(); arguments.put("rule_literal", new LiteralArgument("rule").withPermission(new Permission("claim.command.claim.rule"))); arguments.put("protectedClaim", new QuotedStringArgument()); arguments.put("rule", new LiteralArgument(rule.name())); register(arguments, (cmd, owner) -> { List<ProtectedClaim> protectedClaims = ProtectedClaim.getProtectedClaims(owner, (String) cmd.getArg(0)); if (!protectedClaims.isEmpty()) { Map<RuleTarget, Boolean> ruleValues = protectedClaims.get(0).getClaimRuleValues(rule); ruleValues.putIfAbsent(RuleTarget.NEUTRALS, false); for (RuleTarget ruleTarget : ruleValues.keySet()) { if (ruleTarget.equals(RuleTarget.NEUTRALS) && !cmd.hasPermission("claim.target.neutrals")) continue; if (ruleTarget instanceof TeamOwner && !cmd.hasPermission("claim.target.team")) continue; if (ruleTarget instanceof EntityOwner && !cmd.hasPermission("claim.target.player")) continue; String id; if (ruleTarget.equals(RuleTarget.NEUTRALS)) id = new Message("neutrals").getMessage(cmd.getLanguage()); else if (ruleTarget instanceof Owner) id = ((Owner) ruleTarget).getDisplayName(); else id = ruleTarget.getId(); boolean ruleValue = ruleValues.get(ruleTarget); ChatColor color = ruleValue ? ChatColor.GREEN : ChatColor.RED; cmd.sendMessage(new TextComponent(id + ": " + color + ruleValue)); } return 1; } else { cmd.sendFailureMessage(new Message("claim.does_not_exist", (String) cmd.getArg(0))); return 0; } }); for (String string : new String[] {"neutrals", "team", "player"}) { arguments = new LinkedHashMap<>(); arguments.put("rule_literal", new LiteralArgument("rule").withPermission(new Permission("claim.command.claim.rule"))); arguments.put("protectedClaim", new QuotedStringArgument()); arguments.put("rule", new LiteralArgument(rule.name())); arguments.put("targetType", new LiteralArgument(string).withPermission(new Permission("claim.target." + string))); if (string.equals("player")) arguments.put("target", new OfflinePlayerArgument()); if (string.equals("team")) arguments.put("target", new ScoreboardTeamArgument()); arguments.put("value", new BooleanArgument()); register(arguments, (cmd, owner) -> { List<ProtectedClaim> protectedClaims = ProtectedClaim.getProtectedClaims(owner, (String) cmd.getArg(0)); if (!protectedClaims.isEmpty()) { String id; if (string.equals("neutrals")) id = "@neutrals"; else if (string.equals("team")) id = ((Team) cmd.getArg(1)).getName() + "@team"; else if (string.equals("player")) id = ((OfflinePlayer) cmd.getArg(1)).getUniqueId().toString() + "@entity"; else id = null; RuleTarget target = RuleTarget.getRuleTarget(id); boolean value = (boolean) cmd.getArg(string.equals("neutrals") ? 1 : 2); for (ProtectedClaim protectedClaim : protectedClaims) protectedClaim.setClaimRuleValue(rule, target, value); cmd.sendMessage(new Message("command.claim.rule.set", rule.name(), ""+value)); return 1; } else { cmd.sendFailureMessage(new Message("claim.does_not_exist", (String) cmd.getArg(0))); return 0; } }); arguments = new LinkedHashMap<>(); arguments.put("rule_literal", new LiteralArgument("rule").withPermission(new Permission("claim.command.claim.rule"))); arguments.put("protectedClaim", new QuotedStringArgument()); arguments.put("rule", new LiteralArgument(rule.name())); arguments.put("targetType", new LiteralArgument(string)); if (string.equals("player")) arguments.put("target", new OfflinePlayerArgument()); if (string.equals("team")) arguments.put("target", new ScoreboardTeamArgument()); arguments.put("remove", new LiteralArgument("remove")); register(arguments, (cmd, owner) -> { List<ProtectedClaim> protectedClaims = ProtectedClaim.getProtectedClaims(owner, (String) cmd.getArg(0)); if (!protectedClaims.isEmpty()) { String id; if (string.equals("neutrals")) id = "@neutrals"; else if (string.equals("team")) id = ((Team) cmd.getArg(1)).getName() + "@team"; else if (string.equals("player")) id = ((OfflinePlayer) cmd.getArg(1)).getUniqueId().toString() + "@entity"; else id = null; RuleTarget target = RuleTarget.getRuleTarget(id); for (ProtectedClaim protectedClaim : protectedClaims) protectedClaim.removeClaimRuleValue(rule, target); cmd.sendMessage(new Message("command.claim.rule.remove", rule.name())); return 1; } else { cmd.sendFailureMessage(new Message("claim.does_not_exist", (String) cmd.getArg(0))); return 0; } }); } } } }
package xyz.asassecreations.voxel.shaders; import static org.lwjgl.opengl.GL20.GL_FRAGMENT_SHADER; import static org.lwjgl.opengl.GL20.GL_VERTEX_SHADER; import xyz.asassecreations.engine.math.vector.Mat4; import xyz.asassecreations.engine.render.color.Color; import xyz.asassecreations.engine.render.shader.Shader; public final class PanelShader extends Shader { public PanelShader() { super(null); addShader("/shaders/gui/panel.vsh", GL_VERTEX_SHADER); addShader("/shaders/gui/panel.fsh", GL_FRAGMENT_SHADER); compile(); } protected final void getAllUniformLocations() { } protected final void bindAttributes() { } public final void loadTransformationMatrix(final Mat4 mat) { loadMatrix("transformation", mat); } public final void loadColor(final Color color) { loadVector("panelColor", color.asVec4()); } }
package io.dcbn.backend.core; import de.fraunhofer.iosb.iad.maritime.datamodel.Vessel; import de.fraunhofer.iosb.iad.maritime.datamodel.VesselType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Set; import static org.junit.jupiter.api.Assertions.*; public class VesselCacheTest { private final int timeSteps = 5; private VesselCache vesselCache; private Vessel vessel; private Vessel vesselTwo; @BeforeEach public void setUp() { vesselCache = new VesselCache(timeSteps); vessel = new Vessel("Vessel1", System.currentTimeMillis()); vesselTwo = new Vessel("Vessel2", System.currentTimeMillis()); } @Test public void getAllVesselsInTimeSliceByTypeExceptionTest() { assertThrows(IllegalArgumentException.class, () -> vesselCache.getAllVesselsInTimeSliceByType(-1, VesselType.CARGO)); assertThrows(IllegalArgumentException.class, () -> vesselCache.getAllVesselsInTimeSliceByType(5, VesselType.CARGO)); } @Test public void getAllVesselsInTimeSliceExceptionTest() { assertThrows(IllegalArgumentException.class, () -> vesselCache.getAllVesselsInTimeSlice(-1)); assertThrows(IllegalArgumentException.class, () -> vesselCache.getAllVesselsInTimeSlice(5)); } @Test public void getAllVesselsInTimeSliceByTypeTest() { vessel.setSpeed(0.0); vessel.setVesselType(VesselType.FISHING_VESSEL); vesselCache.insert(vessel); vesselTwo.setVesselType(VesselType.CARGO); vesselTwo.setSpeed(0.0); vesselCache.insert(vesselTwo); vesselCache.updateTimeSlices(); vessel = Vessel.copy(vessel); vesselTwo = Vessel.copy(vesselTwo); vessel.setSpeed(1.0); vesselCache.insert(vessel); vesselTwo.setSpeed(2.0); vesselCache.insert(vesselTwo); Set<Vessel> vesselSet = vesselCache.getAllVesselsInTimeSliceByType(0, VesselType.CARGO); assertTrue(vesselSet.contains(vesselTwo)); assertEquals(1, vesselSet.size()); for(Vessel vessel : vesselSet) { assertEquals(VesselType.CARGO, vessel.getVesselType()); assertEquals(2.0, vessel.getSpeed()); } vesselSet = vesselCache.getAllVesselsInTimeSliceByType(1, VesselType.FISHING_VESSEL); assertEquals(1, vesselSet.size()); for(Vessel vessel : vesselSet) { assertEquals(VesselType.FISHING_VESSEL, vessel.getVesselType()); assertEquals(0.0, vessel.getSpeed()); } } @Test public void getAllVesselsInTimeSliceTest() { vessel.setSpeed(0.0); vesselCache.insert(vessel); vesselTwo.setSpeed(0.0); vesselCache.insert(vesselTwo); vesselCache.updateTimeSlices(); vessel = Vessel.copy(vessel); vesselTwo = Vessel.copy(vesselTwo); vessel.setSpeed(1.0); vesselCache.insert(vessel); vesselTwo.setSpeed(2.0); vesselCache.insert(vesselTwo); Set<Vessel> vesselSet = vesselCache.getAllVesselsInTimeSlice(0); assertTrue(vesselSet.contains(vessel)); assertTrue(vesselSet.contains(vesselTwo)); assertEquals(2, vesselSet.size()); for(Vessel vessel : vesselSet) { if(vessel.getUuid().equals("Vessel1")) { assertEquals(1.0, vessel.getSpeed()); } else if (vessel.getUuid().equals("Vessel2")) { assertEquals(2.0, vessel.getSpeed()); } } vesselSet = vesselCache.getAllVesselsInTimeSlice(1); assertEquals(2, vesselSet.size()); for(Vessel vessel : vesselSet) { if(vessel.getUuid().equals("Vessel1")) { assertEquals(0.0, vessel.getSpeed()); } else if (vessel.getUuid().equals("Vessel2")) { assertEquals(0.0, vessel.getSpeed()); } } } @Test public void getAllUuidsWithEmptyCacheTest() { assertTrue(vesselCache.getAllVesselUuids().isEmpty()); } @Test public void getAllUuidsTest() { vesselCache.insert(vessel); vesselCache.insert(vesselTwo); Set<String> uuids = vesselCache.getAllVesselUuids(); assertTrue(uuids.contains(vessel.getUuid())); assertTrue(uuids.contains(vesselTwo.getUuid())); assertEquals(2, uuids.size()); } @Test public void insertOneVesselTest() { vesselCache.insert(vessel); assertEquals("Vessel1", vesselCache.getVesselsByUuid(vessel.getUuid())[0].getUuid()); } @Test public void insertThreeInSameTimeSliceTest() { vessel.setSpeed(0.0); vesselCache.insert(vessel); vessel = Vessel.copy(vessel); vessel.setSpeed(1.0); vesselCache.insert(vessel); vessel = Vessel.copy(vessel); vessel.setSpeed(0.5); vesselCache.insert(vessel); assertEquals(0.5, vesselCache.getVesselsByUuid(vessel.getUuid())[0].getSpeed(), 1e-5); } @Test public void insertTwoInSameTimeSliceTest() { vessel.setSpeed(0.0); vesselCache.insert(vessel); vessel = Vessel.copy(vessel); vessel.setSpeed(1.0); vesselCache.insert(vessel); for (int i = 0; i < vesselCache.getVesselsByUuid(vessel.getUuid()).length; i++) { if (i == 0) { assertEquals(1.0, vesselCache.getVesselsByUuid(vessel.getUuid())[0].getSpeed(), 1e-5); assertFalse(vesselCache.getVesselsByUuid(vessel.getUuid())[0].isFiller()); } else { assertEquals(0.0, vesselCache.getVesselsByUuid(vessel.getUuid())[i].getSpeed(), 1e-5); assertTrue(vesselCache.getVesselsByUuid(vessel.getUuid())[i].isFiller()); } } } @Test public void numberOfTimeStepsTest() { vesselCache.insert(vessel); assertEquals(timeSteps, vesselCache.getVesselsByUuid(vessel.getUuid()).length); } @Test public void insertNullTest() { assertThrows(IllegalArgumentException.class, () -> vesselCache.insert(null)); } @Test public void getNullUuidTest() { assertNull(vesselCache.getVesselsByUuid("hello")); } @Test public void updateTimeSlicesTest() { vessel.setSpeed(4.0); vesselCache.insert(vessel); vesselCache.updateTimeSlices(); vessel = Vessel.copy(vessel); vessel.setSpeed(3.0); vesselCache.insert(vessel); vesselCache.updateTimeSlices(); vessel = Vessel.copy(vessel); vessel.setSpeed(2.0); vesselCache.insert(vessel); vesselCache.updateTimeSlices(); vessel = Vessel.copy(vessel); vessel.setSpeed(1.0); vesselCache.insert(vessel); vesselCache.updateTimeSlices(); vessel = Vessel.copy(vessel); vessel.setSpeed(0.0); vesselCache.insert(vessel); for (int i = 0; i < vesselCache.getVesselsByUuid(vessel.getUuid()).length; i++) { assertEquals(i, vesselCache.getVesselsByUuid(vessel.getUuid())[i].getSpeed(), 1e-5); } vesselCache.updateTimeSlices(); vessel = Vessel.copy(vessel); vessel.setSpeed(10.0); vesselCache.insert(vessel); assertEquals(10.0, vesselCache.getVesselsByUuid(vessel.getUuid())[0].getSpeed(), 1e-5); assertEquals(3.0, vesselCache.getVesselsByUuid(vessel.getUuid())[timeSteps - 1].getSpeed(), 1e-5); } @Test public void refreshCacheAndDeleteTest() { assertNull(vesselCache.getVesselsByUuid(vessel.getUuid())); vessel.setSpeed(1.0); vesselCache.insert(vessel); assertNotNull(vesselCache.getVesselsByUuid(vessel.getUuid())); for (int i = 0; i < timeSteps; i++) { vesselCache.updateTimeSlices(); } vesselCache.refreshCache(); assertNull(vesselCache.getVesselsByUuid(vessel.getUuid())); } @Test public void fillerFlagTest() { vessel.setSpeed(1.0); vesselCache.insert(vessel); vesselCache.updateTimeSlices(); assertEquals(1.0, vesselCache.getVesselsByUuid(vessel.getUuid())[1].getSpeed(), 1e-5); assertFalse(vesselCache.getVesselsByUuid(vessel.getUuid())[1].isFiller()); assertEquals(1.0, vesselCache.getVesselsByUuid(vessel.getUuid())[0].getSpeed(), 1e-5); assertTrue(vesselCache.getVesselsByUuid(vessel.getUuid())[0].isFiller()); } @Test public void refreshCacheAndDontDeleteTest() { assertNull(vesselCache.getVesselsByUuid(vessel.getUuid())); vessel.setSpeed(1.0); vesselCache.insert(vessel); assertNotNull(vesselCache.getVesselsByUuid(vessel.getUuid())); vesselCache.updateTimeSlices(); vesselCache.refreshCache(); assertTrue(vesselCache.getVesselsByUuid(vessel.getUuid())[2].isFiller()); assertFalse(vesselCache.getVesselsByUuid(vessel.getUuid())[1].isFiller()); assertTrue(vesselCache.getVesselsByUuid(vessel.getUuid())[0].isFiller()); } }
package com.example.km.genericapp.activities; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.example.km.genericapp.R; import com.example.km.genericapp.adapters.NavigationCustomAdapter; import com.example.km.genericapp.fragments.MainFragment; import com.example.km.genericapp.fragments.PostsFragment; import com.example.km.genericapp.fragments.RecipesFragment; import com.example.km.genericapp.fragments.SettingsFragment; import com.example.km.genericapp.fragments.VersionsFragment; import com.example.km.genericapp.models.navigation.NavigationDrawerItem; import com.example.km.genericapp.utilities.SnackbarHelper; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.functions.Consumer; public class MainActivity extends AppCompatActivity { private static final int HOME_ITEM = 0; private static final int POSTS_ITEM = 1; private static final int RECIPES_ITEM = 2; private static final int VERSIONS_ITEM = 3; private static final int SETTINGS_ITEM = 4; private static final int DRAWER_ITEMS_COUNT = 5; private ActionBar actionBar; private String[] navigationDrawerItemTitles; private DrawerLayout drawerLayout; private ListView drawerList; private LinearLayout drawerPanel; private TextView navigationDrawerHeaderTitle; private ActionBarDrawerToggle drawerToggle; FloatingActionButton fab; private CompositeDisposable observers; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupNavigationDrawer(); setupActionBar(); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SnackbarHelper.showSnackbar(MainActivity.this, view, getString(R.string.fab_click_message)); } }); LoadHomeFragment(); } private void LoadHomeFragment() { LoadPostsFragment(); setActionBarTitle(getString(R.string.app_name)); } private void LoadMainFragment() { Fragment fragment = new MainFragment(); if (fragment != null) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); } } private void LoadPostsFragment() { Fragment fragment = new PostsFragment(); if (fragment != null) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); } } private void LoadRecipesFragment() { Fragment fragment = new RecipesFragment(); if (fragment != null) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); } } private void LoadVersionsFragment() { Fragment fragment = new VersionsFragment(); if (fragment != null) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); } } private void LoadSettingsFragment() { SettingsFragment fragment = new SettingsFragment(); if (fragment != null) { setupViewObservers(fragment); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); } } private void setupViewObservers(SettingsFragment settingsFragment) { if (observers == null) { observers = new CompositeDisposable(); } observers.add(settingsFragment.launchPosts() .subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean aBoolean) throws Exception { LoadPostsFragment(); setActionBarTitle(getString(R.string.action_posts)); } })); observers.add(settingsFragment.launchRecipes() .subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean aBoolean) throws Exception { LoadRecipesFragment(); setActionBarTitle(getString(R.string.action_recipes)); } })); } private void setActionBarTitle(final String title) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { actionBar.setTitle(title); } }); } @Override protected void onResume() { super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(Gravity.LEFT); } else { drawerLayout.openDrawer(Gravity.LEFT); } return true; case R.id.action_home: LoadHomeFragment(); setActionBarTitle(getString(R.string.app_name)); return true; case R.id.action_posts: LoadPostsFragment(); setActionBarTitle(getString(R.string.action_posts)); return true; case R.id.action_recipes: LoadRecipesFragment(); setActionBarTitle(getString(R.string.action_recipes)); return true; case R.id.action_versions: LoadVersionsFragment(); setActionBarTitle(getString(R.string.action_versions)); return true; case R.id.action_settings: LoadSettingsFragment(); setActionBarTitle(getString(R.string.action_settings)); return true; default: return super.onOptionsItemSelected(item); } } private void setupNavigationDrawer() { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerToggle = new ActionBarDrawerToggle( this, drawerLayout, R.string.title_drawer_open, R.string.title_drawer_close) { public void onDrawerClosed(View view) { super.onDrawerClosed(view); } public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } }; // Set the drawer toggle as the DrawerListener drawerLayout.setDrawerListener(drawerToggle); navigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerList = (ListView) findViewById(R.id.left_drawer); drawerPanel = (LinearLayout) findViewById(R.id.drawer_panel); navigationDrawerHeaderTitle = (TextView) findViewById(R.id.navigationDrawerHeaderTitle); NavigationDrawerItem[] drawerItem = new NavigationDrawerItem[DRAWER_ITEMS_COUNT]; drawerItem[0] = new NavigationDrawerItem(R.drawable.ic_home, navigationDrawerItemTitles[0]); drawerItem[1] = new NavigationDrawerItem(R.drawable.ic_posts, navigationDrawerItemTitles[1]); drawerItem[2] = new NavigationDrawerItem(R.drawable.ic_search, navigationDrawerItemTitles[2]); drawerItem[3] = new NavigationDrawerItem(R.drawable.ic_versions, navigationDrawerItemTitles[3]); drawerItem[4] = new NavigationDrawerItem(R.drawable.ic_settings, navigationDrawerItemTitles[4]); NavigationCustomAdapter adapter = new NavigationCustomAdapter(this, R.layout.navigation_item_row, drawerItem); drawerList.setAdapter(adapter); drawerList.setOnItemClickListener(new DrawerItemClickListener()); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) protected void setupActionBar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(R.string.app_name); actionBar.setHomeAsUpIndicator(R.drawable.ic_drawer_menu); } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } } private void selectItem(int position) { switch (position) { case HOME_ITEM: LoadHomeFragment(); break; case POSTS_ITEM: LoadPostsFragment(); break; case RECIPES_ITEM: LoadRecipesFragment(); break; case VERSIONS_ITEM: LoadVersionsFragment(); break; case SETTINGS_ITEM: LoadSettingsFragment(); break; default: break; } drawerList.setItemChecked(position, true); drawerList.setSelection(position); if (actionBar != null) { actionBar.setTitle(navigationDrawerItemTitles[position]); } drawerLayout.closeDrawer(drawerPanel); } }
package com.lenovohit.ssm.app.community.web.rest; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.lenovohit.core.dao.Page; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.core.utils.JSONUtils; import com.lenovohit.core.utils.StringUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.rest.BaseRestController; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.ssm.app.community.model.ConsultRecord; @RestController @RequestMapping("/hwe/app/consultRecord") public class ConsultRecordRestController extends BaseRestController{ @Autowired private GenericManager<ConsultRecord, String> consultRecordManager; @RequestMapping(value = "/create",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result forCreate(@RequestBody String data){ ConsultRecord model = JSONUtils.deserialize(data, ConsultRecord.class); ConsultRecord record = this.consultRecordManager.save(model); return ResultUtils.renderSuccessResult(record); } @RequestMapping(value = "/remove/{id}",method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8) public Result forRemove(@PathVariable("id") String id){ ConsultRecord record = this.consultRecordManager.delete(id); return ResultUtils.renderSuccessResult(record); } @RequestMapping(value = "/update",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result forUpdate(@RequestBody String data){ ConsultRecord model = JSONUtils.deserialize(data, ConsultRecord.class); if(model == null || StringUtils.isBlank(model.getId())){ return ResultUtils.renderFailureResult("不存在此对象"); } ConsultRecord record = this.consultRecordManager.save(model); return ResultUtils.renderSuccessResult(record); } @RequestMapping(value = "/list",method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forList(){ List<ConsultRecord> list = consultRecordManager.findAll(); return ResultUtils.renderSuccessResult(list); } @RequestMapping(value = "/page/{start}/{limit}",method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forPage(@PathVariable("start") String start , @PathVariable("limit") String limit ){ List<Object> values = new ArrayList<Object>(); StringBuilder jql = new StringBuilder( " from ConsultRecord where 1=1 "); Page page = new Page(); page.setStart(start); page.setPageSize(limit); page.setQuery(jql.toString()); page.setValues(values.toArray()); this.consultRecordManager.findPage(page); return ResultUtils.renderSuccessResult(page); } }
package model; import java.text.SimpleDateFormat; import java.util.Date; import org.genericdao.ConnectionPool; import org.genericdao.DAOException; import org.genericdao.GenericDAO; import org.genericdao.RollbackException; import databean.VisitBean; public class VisitDAO extends GenericDAO<VisitBean>{ public VisitDAO(ConnectionPool cp, String tableName) throws DAOException { super(VisitBean.class, tableName, cp); } public void increase() throws RollbackException { Date dt = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); String str = dateFormat.format(dt); VisitBean visit = read(str); if (visit == null) { VisitBean visitBean= new VisitBean(); visitBean.setNumOfVisit(1); visitBean.setDate(str); create(visitBean); } else { visit.setNumOfVisit(visit.getNumOfVisit() + 1); update(visit); } } public VisitBean[] getRecord() throws RollbackException { VisitBean[] temp = match(); return temp; } }
package com.codingproject.spotter; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.Layout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatDialogFragment; public class RestDayDialog extends AppCompatDialogFragment { @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View v = inflater.inflate(R.layout.rest_day_layout, null); builder.setView(v).setTitle("Rest Day Today!").setPositiveButton("CONTINUE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // do nothing } }).setNegativeButton("EXIT APP", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // exit app getActivity().finishAffinity(); } }); return builder.create(); } }
import java .awt.*; import java .applet.*; public class msg1 extand Applet { public void paint(Graphice g) { g.drawString("WELCOM",40,50); }//close of paint }//close of class
package be.openclinic.common; /** * Created by IntelliJ IDEA. * User: Frank Verbeke * Date: 10-sep-2006 * Time: 21:26:35 * To change this template use Options | File Templates. */ public class ObjectReference { private String objectType; private String objectUid; public ObjectReference(){ } public ObjectReference(String objectType,String objectUid){ this.setObjectUid(objectUid); this.setObjectType(objectType); } public String getObjectType() { return objectType; } public void setObjectType(String objectType) { this.objectType = objectType; } public String getObjectUid() { return objectUid; } public void setObjectUid(String objectUid) { this.objectUid = objectUid; } public boolean equals(ObjectReference objectReference){ return objectReference.getObjectType().equalsIgnoreCase(this.getObjectType()) && objectReference.getObjectUid().equalsIgnoreCase(this.getObjectUid()); } }
package OnTap1; import java.util.ArrayList; import java.util.Scanner; public class HSHocSinh extends Nguoi{ Scanner scanner = new Scanner(System.in); String classID; String course; String semester; String checkNgaySinh= "[0-9]{2}\\/[0-9]{2}\\/[0-9]{4}"; ArrayList<HSHocSinh> mangHS = new ArrayList<>(); public HSHocSinh() { super(); } public HSHocSinh(String classID, String course, String semester,String name,String birth, String adress) { super(name, birth, adress); this.classID = classID; this.course = course; this.semester = semester; } public String getclassID() { return classID; } public void showHS() { System.out.println("Lớp: \n" + classID); System.out.println("Khóa học: \n" + course); System.out.println("Kỳ học: \n" + semester); } public void inputHSHocSinh() { System.out.println("Nhập vào số học sinh:"); int n = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < n; i++) { HSHocSinh hshs = new HSHocSinh(); System.out.println("Nhập thông tin học sinh thứ " + (i + 1) + ": "); System.out.println("Nhập họ tên:"); hshs.name = scanner.nextLine(); System.out.println("Nhập ngày sinh (xx/xx/xxxx):"); hshs.birth = scanner.nextLine(); while (true) { if(hshs.birth.matches(checkNgaySinh)) { break; } else { System.out.println("Nhập sai định dạng ngày sinh: "); hshs.birth = scanner.nextLine(); } } System.out.println("Nhập quê quán (Nhập có dấu mới nhận nha ^^):"); hshs.adress = scanner.nextLine(); System.out.print("Nhập lớp: "); hshs.classID = scanner.nextLine(); System.out.print("Khóa học: "); hshs.course = scanner.nextLine(); System.out.print("Kỳ học: "); hshs.semester = scanner.nextLine(); mangHS.add(hshs); } } public void showArray() { for (int i = 0; i < mangHS.size(); i++) { System.out.println("\nThông tin học sinh thứ " + (i+1) + ": "); mangHS.get(i).show(); mangHS.get(i).showHS(); } } public void find1985TN() { System.out.println("\nNhững Học Sinh sinh năm 1985 và có quê ở Thái Nguyên là: "); String check= "[0-9]{2}\\/[0-9]{2}\\/1985"; for (int i = 0; i < mangHS.size(); i++) { if (mangHS.get(i).getadress().equalsIgnoreCase("Thái Nguyên") && mangHS.get(i).birth.matches(check) ) { mangHS.get(i).show(); mangHS.get(i).showHS(); } else { System.out.println("Không có sinh viên như điệu kiện"); } } } public void find10a1() { System.out.println("\nNhững Học Sinh học lớp 10A1 là: "); for (int i = 0; i < mangHS.size(); i++) { if (mangHS.get(i).getclassID().equalsIgnoreCase("10A1")) { mangHS.get(i).show(); mangHS.get(i).showHS(); } else { System.out.println("Không có sinh viên như điệu kiện"); } } } }
package com.unicom.patrolDoor.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.*; /** * @Author wrk * @Date 2021/4/21 9:48 */ public class SensitivewordFilter { public static void main(String[] args) throws Exception { SensitivewordFilter sensitivewordFilterTest=new SensitivewordFilter(); String file ="D://sensitive.txt"; System.out.println(sensitivewordFilterTest.replaceSensitiveWord("腐败", 1,"*",file)); } //读取敏感词文件 获取到敏感词文件的内容 public List<String> readSensitiveWordByFile(String filePath) throws Exception{ List<String> list = null; //File file = new File("msc/SensitiveWord.txt"); //读取文件 File file = new File(filePath); //读取文件 InputStreamReader read = new InputStreamReader(new FileInputStream(file),"UTF-8"); try { if(file.isFile() && file.exists()){ //文件流是否存在 list = new ArrayList<String>(); BufferedReader bufferedReader = new BufferedReader(read); String txt = null; while((txt = bufferedReader.readLine()) != null){ //读取文件,将文件内容放入到set中 String[] strSplit=txt.trim().split(","); for(String str:strSplit){ list.add(str); } } }else{ //不存在抛出异常信息 throw new Exception("词库文件不存在"); } } catch (Exception e) { throw e; }finally{ read.close(); //关闭文件流 } return list; } //将敏感词内容添加到map中 private Map addSensitiveWord(List<String> datas) { Map sensitiveWordMap = new HashMap(datas.size()); Iterator<String> iterator = datas.iterator(); Map<String, Object> now = null; Map now2 = null; while (iterator.hasNext()) { now2 = sensitiveWordMap; String word = iterator.next().trim(); //敏感词 for (int i = 0; i < word.length(); i++) { char key_word = word.charAt(i); Object obj = now2.get(key_word); if (obj != null) { //存在 now2 = (Map) obj; } else { //不存在 now = new HashMap<String, Object>(); now.put("isEnd","0"); now2.put(key_word, now); now2 = now; } if (i == word.length() - 1) { now2.put("isEnd","1"); } } } return sensitiveWordMap; } //根据输入的内容 判断是否包含敏感词 public List<String> getSensitiveWord(String text, int matchType,Map sensitiveWordMap) { List<String> words = new ArrayList<String>(); Map now = sensitiveWordMap; int count = 0; //初始化敏感词长度 int start = 0; //标志敏感词开始的下标 for (int i = 0; i < text.length(); i++) { char key = text.charAt(i); now = (Map) now.get(key); if (now != null) { //存在 count++; if (count ==1) { start = i; } if ("1".equals(now.get("isEnd"))) { //敏感词结束 now = sensitiveWordMap; //重新获取敏感词库 words.add(text.substring(start, start + count)); //取出敏感词,添加到集合 count = 0; //初始化敏感词长度 } } else { //不存在 now = sensitiveWordMap;//重新获取敏感词库 if (count == 1 && matchType == 1) { //不最佳匹配 count = 0; } else if (count == 1 && matchType == 2) { //最佳匹配 words.add(text.substring(start, start + count)); count = 0; } } } return words; } //提取敏感词内容 public String replaceSensitiveWord(String txt, int matchType, String replaceChar,String filePath) throws Exception { SensitivewordFilter test=new SensitivewordFilter(); String resultTxt = txt; List<String> set = test.getSensitiveWord(txt, matchType, test.returnMap(filePath)); //获取所有的敏感词 /** * 以下是替换成*的逻辑 */ // System.err.println(set); // Iterator<String> iterator = set.iterator(); // String word = null; // String replaceString = null; // while (iterator.hasNext()) { // word = iterator.next(); // replaceString = getReplaceChars(replaceChar, word.length()); // resultTxt = resultTxt.replaceAll(word, replaceString); // } /** * 以下是提取的逻辑 */ if (set.size() > 0) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < set.size(); i++) { buffer.append(set.get(i)+","); } resultTxt = buffer.toString().substring(0,buffer.toString().length()-1); } else { resultTxt = "false"; } return resultTxt; } public Map returnMap(String filePath) throws Exception { SensitivewordFilter test=new SensitivewordFilter(); Map map=test.addSensitiveWord(test.readSensitiveWordByFile(filePath)); return map; } }
package cn.kitho.core.utilService.mail; /** * 邮件实体 * * @author KITHO LING */ public class Email { /** * 发送人昵称 */ private String senderNickName; /** 收件人列表(优先) */ private String[] addressee; /** * 单个收件人 */ private String receiver; /** 标题 */ private String subject; /** 内容 */ private String content; public Email() { } public Email(String senderNickName, String[] addressee, String subject, String content) { this.senderNickName = senderNickName; this.addressee = addressee; this.subject = subject; this.content = content; } public Email(String senderNickName, String receiver, String subject, String content) { this.senderNickName = senderNickName; this.receiver = receiver; this.subject = subject; this.content = content; } public String getSenderNickName() { return senderNickName; } public void setSenderNickName(String senderNickName) { this.senderNickName = senderNickName; } public String[] getAddressee() { return addressee; } public void setAddressee(String[] addressee) { this.addressee = addressee; } public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package portal.data.enumdata; public enum TypeUser { CUSTOMER_NEW_SUBSCRIPTION("No Name", "test8992@portal.cloud", "7720288603", "U&*HFD&HU"), CUSTOMER_CHECK_NAME_SUBSCRIPTION("No name", "test1045@portal.cloud", "7606069927", "U&*HFD&HU"), CUSTOMER_NEW_SUBSCRIPTION_EMAIL("ТПФ \"ДИ-МЕР", "test2035@portal.cloud","7610071510", "U&*HFD&HU"), CUSTOMER_CHANGE_SUBSCRIPTION("No name", "test1026@portal.cloud", "6674354092", "U&*HFD&HU"), NEW_CUSTOMER("No name", "test1145@portal.cloud", "6154064527","U&*HFD&HU"), CUSTOMER_INDIVIDUAL("No name", "test1146@portal.cloud","1646039822","U&*HFD&HU"), CUSTOMER_OFFER("No name","test1147@portal.cloud","4345130777","U&*HFD&HU"), CUSTOMER_CHANGE_REQUEST("No name", "test1026@portal.cloud", "6674354092","6N7SsuwRE#"), USER_ADMIN("Test", "robot@portal.cloud", "freeInn","68&&@h*PQQw)$M"); private String name; private String email; private String inn; private String password; TypeUser( String name, String email, String inn, String password){ this.name = name; this.email = email; this.inn = inn; this.password = password; } public String getName() { return name; } public String getEmail() { return email; } public String getInn() { return inn; } public String getPassword() { return password; } }
package com.ipartek.formacion.nombreproyecto.pojo; public class Dado { public static String aAlumnos[] = { "Selene", "Edu", "Andoni", "Borja", "Joseba Zaldunbide", "Jon", "Jon Ander", "Daniel", "Josu", "Joseba", "Monica", "Isabel", "Bolaņos", "Ekaitz", "Aitor"}; /** * Genera numero aleatorio * @return <code>int</code> numero entre 0 y longitud del array aAlumnos */ public static int generarNumAleatorio() { return (int) (Math.random()*aAlumnos.length); } public static void main(String[] args) { int iAleatorio = generarNumAleatorio(); System.out.println("El/a voluntario/a es: " + aAlumnos[ iAleatorio ] ); } }