text
stringlengths
10
2.72M
package com.dayuanit.shop.vo; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; public class UserAddressVo { private Integer id; private Integer userId; @NotNull @Length(min=6, max=6, message="provinceCode长度为6") private String provinceCode; @NotNull @Length(min=6, max=6, message="cityCode长度为6") private String cityCode; @NotNull @Length(min=6, max=6, message="areaCode长度为6") private String areaCode; @NotNull private String dtaAddress; @NotNull private String userRealName; @NotNull private String phone; private Integer status; @NotNull private Integer isDefauAdress; @NotNull private String provinceName; @NotNull private String cityName; @NotNull private String areaName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getProvinceCode() { return provinceCode; } public void setProvinceCode(String provinceCode) { this.provinceCode = provinceCode; } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public String getDtaAddress() { return dtaAddress; } public void setDtaAddress(String dtaAddress) { this.dtaAddress = dtaAddress; } public String getUserRealName() { return userRealName; } public void setUserRealName(String userRealName) { this.userRealName = userRealName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getIsDefauAdress() { return isDefauAdress; } public void setIsDefauAdress(Integer isDefauAdress) { this.isDefauAdress = isDefauAdress; } public String getProvinceName() { return provinceName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } }
package org.idea.plugin.atg.psi.reference; import com.intellij.openapi.components.ServiceManager; import com.intellij.psi.PsiElementResolveResult; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiPolyVariantReferenceBase; import com.intellij.psi.ResolveResult; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import org.apache.commons.lang.StringUtils; import org.idea.plugin.atg.index.AtgIndexService; import org.idea.plugin.atg.util.AtgComponentUtil; import org.jetbrains.annotations.NotNull; import java.util.HashSet; import java.util.Objects; import java.util.Optional; import java.util.Set; public class ItemDescriptorReference extends PsiPolyVariantReferenceBase<XmlAttributeValue> { public ItemDescriptorReference(@NotNull XmlAttributeValue element) { super(element); } @Override public Object @NotNull [] getVariants() { return new String[0]; } @Override public ResolveResult @NotNull [] multiResolve(boolean incompleteCode) { PsiFile containingFile = getElement().getContainingFile(); if (!(containingFile instanceof XmlFile)) return ResolveResult.EMPTY_ARRAY; String seekingItemDescriptorName = getElement().getValue(); if (StringUtils.isBlank(seekingItemDescriptorName)) return ResolveResult.EMPTY_ARRAY; Set<XmlFile> xmlFilesWithSamePath = new HashSet<>(); xmlFilesWithSamePath.add((XmlFile) containingFile); AtgIndexService componentsService = ServiceManager.getService(containingFile.getProject(), AtgIndexService.class); Optional<String> xmlRelativePath = AtgComponentUtil.getXmlRelativePath((XmlFile) containingFile); xmlRelativePath.ifPresent(s -> xmlFilesWithSamePath.addAll(componentsService.getXmlsByName(s))); return xmlFilesWithSamePath.stream() .map(f -> findItemDescriptorByName(seekingItemDescriptorName, f)) .filter(Objects::nonNull) .map(attr -> new PsiElementResolveResult(attr, true)) .toArray(ResolveResult[]::new); } private XmlAttributeValue findItemDescriptorByName(@NotNull final String seekingItemDescriptorName, @NotNull final XmlFile xmlFile) { XmlTag rootTag = xmlFile.getRootTag(); if (rootTag != null) { for (XmlTag itemDescriptorTag : rootTag.findSubTags("item-descriptor")) { XmlAttribute nameAttribute = itemDescriptorTag.getAttribute("name"); if (nameAttribute != null && seekingItemDescriptorName.equals(itemDescriptorTag.getAttributeValue("name"))) { return nameAttribute.getValueElement(); } } } return null; } }
package issue87; import org.concordion.api.Resource; import org.concordion.api.extension.ConcordionExtender; import org.concordion.api.extension.ConcordionExtension; public class JQueryExtension implements ConcordionExtension { @Override public void addTo(ConcordionExtender concordionExtender) { concordionExtender.withLinkedJavaScript("/issue87/script/jquery-2.1.1.min.js", new Resource("/issue87/script/jquery-2.1.1.min.js")); } }
package com.budget.controller; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.budget.service.NewJoinService; import com.budget.serviceImpl.NewJoinServiceImpl; import com.budget.spring.beans.AdminJoin; import com.budget.spring.beans.UserJoin; @Controller public class SignupController { @RequestMapping(value = "/signupadmin", method = RequestMethod.GET) public String adminsignupPage(Map<String,Object> model) { AdminJoin adminjoin=new AdminJoin(); model.put("joinadmin",adminjoin); return "adminsignup"; } @RequestMapping(value = "/signupuser", method = RequestMethod.GET) public String usersignupPage(Map<String,Object> model) { UserJoin userjoin=new UserJoin(); model.put("joinuser",userjoin); return "usersignup"; } @RequestMapping(value = "/joinadmin", method = RequestMethod.POST) public String adminregisterSucess(@ModelAttribute("joinadmin")AdminJoin adminjoin,BindingResult result) { if(result==null) { return "adminsignup"; } else { NewJoinService service=new NewJoinServiceImpl(); String modelAndView= service.registerAdminDetails( adminjoin); return "joinSuccess"; } } @RequestMapping(value = "/joinuser", method = RequestMethod.POST) public String userregisterSucess(@ModelAttribute("userjoin")UserJoin userjoin,BindingResult result) { if(result==null) { return "usersignup"; } else { NewJoinService service=new NewJoinServiceImpl(); String modelAndView= service.registerUserDetails( userjoin);; return "joinSuccess"; } } }
package nju.cs.lw.shoot; public class Bullet extends FlyingObject{ private int speed = 3;//子弹可以向上移动,具有移动的速度作为属性 //构造器 public Bullet(int x, int y){ this.x = x; this.y = y; this.image = ShootGame.bullet; } //移动方法 @Override public void step(){ y -= speed; } //越界处理,越界返回true @Override public boolean outOfBounds(){ return y < -height; } }
package com.santhosh.model; import java.sql.Timestamp; import javax.persistence.*; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; @Entity @Table(name="directtransaction") public class Dstatus { @Id private int sno; @NotNull(message="Customer ID cannot be empty") private String custid; @NotNull(message="Source Account cannot be empty") private String sourceaccount; @NotNull(message="Target Account cannot be empty") private String targetaccount; @NotNull(message="Amount cannot be empty") private String amountinr; private String transactionnumber; private Timestamp timestamp; @Override public String toString() { return "Dstatus [sno=" + sno + ", custid=" + custid + ", sourceaccount=" + sourceaccount + ", targetaccount=" + targetaccount + ", amountinr=" + amountinr + ", transactionnumber=" + transactionnumber + ", timestamp=" + timestamp + "]"; } public int getSno() { return sno; } public void setSno(int sno) { this.sno = sno; } public String getCustid() { return custid; } public void setCustid(String custid) { this.custid = custid; } public String getSourceaccount() { return sourceaccount; } public void setSourceaccount(String sourceaccount) { this.sourceaccount = sourceaccount; } public String getTargetaccount() { return targetaccount; } public void setTargetaccount(String targetaccount) { this.targetaccount = targetaccount; } public String getAmountinr() { return amountinr; } public void setAmountinr(String amountinr) { this.amountinr = amountinr; } public String getTransactionnumber() { return transactionnumber; } public void setTransactionnumber(String transactionnumber) { this.transactionnumber = transactionnumber; } public Timestamp getTimestamp() { return timestamp; } public void setTimestamp(Timestamp timestamp) { this.timestamp = timestamp; } }
package de.codingchallenge.service; import de.codingchallenge.model.Question; import de.codingchallenge.model.SingleChoiceQuestionType; import de.codingchallenge.model.Survey; import de.codingchallenge.model.SurveyResponse; import de.codingchallenge.repository.SurveyRepository; import de.codingchallenge.repository.SurveyResponseRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class SurveyResponseService { private static final Logger log = LoggerFactory.getLogger(SurveyResponseService.class); private final SurveyResponseRepository surveyResponseRepository; private final SurveyRepository surveyRepository; @Autowired SurveyResponseService(SurveyResponseRepository surveyResponseRepository, SurveyRepository surveyRepository) { this.surveyResponseRepository = surveyResponseRepository; this.surveyRepository = surveyRepository; } public boolean validate(SurveyResponse surveyResponse) { if (surveyResponse.getAnswers() == null || surveyResponse.getAnswers().isEmpty()) { log.debug("null or empty answers"); return false; } Survey survey = surveyRepository.findAll().get(0); if (survey == null) { throw new IllegalStateException("There should be at least one survey in the DB."); } if (survey.getQuestions().size() != surveyResponse.getAnswers().size()) { log.debug("Wrong number of responses: {}", surveyResponse.getAnswers().size()); return false; } return validateQuestionType(survey.getQuestions(), surveyResponse.getAnswers()); } private boolean validateQuestionType(List<Question> questions, Map<String, Object> answers) { var questionsIterator = questions.iterator(); var i = 0; while (questionsIterator.hasNext()) { Question question = questionsIterator.next(); if (isSingleChoiceQuestionType(question) && !checkAnswerIndex( (SingleChoiceQuestionType) question.getQuestionType(), answers, i)) { log.debug("broken option {} for question {}", i, question.getQuestionText()); return false; } i++; } return true; } private boolean isSingleChoiceQuestionType(Question next) { return SingleChoiceQuestionType.TYPE_NAME.equals(next.getQuestionType().getQuestionType()); } private boolean checkAnswerIndex(SingleChoiceQuestionType questionType, Map<String, Object> answers, int i) { Object value = answers.get(String.format("q%d", i)); if (!(value instanceof Integer)) { return false; } var answerIndex = (Integer) value; int size = questionType.getOptions().size(); return size >= answerIndex && answerIndex >= 0; } public void save(SurveyResponse surveyResponse) { surveyResponseRepository.save(surveyResponse.getAnswers()); } }
package jdbchomework.controller; import jdbchomework.entity.Project; import jdbchomework.service.ProjectService; import java.util.List; public class ProjectController { private ProjectService projectService; public ProjectController(ProjectService projectService) { this.projectService = projectService; } public List<Project> getAllProjects() { return projectService.getAllProjects(); } public void addProject(String name, int cost) { projectService.addProject(name, cost); } public Project getProjectById(int id) { return projectService.getProjectById(id); } public boolean deleteProjectById(int id) { return projectService.deleteProjectById(id); } public boolean updateProjectById(int id, String name, int cost) { Project project = new Project(name, cost); return projectService.updateProjectById(id, project); } }
package com.example.kevin.weatherclothingapp; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * Created by Kevin on 10/26/2015. */ public class LocationFragment extends Fragment{ TextView mCurrentCityTextView; Button mChangeCityButton; EditText mUserCityEditText; //TODO add the ability to change cities. This should use the GeoCacher to find the new location... //TODO ...and close this fragment, returning to the first one and setting the new city with its new forecasts. @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.edit_location_fragment, container, false); mCurrentCityTextView = (TextView)v.findViewById(R.id.currentCityTextView); mChangeCityButton = (Button)v.findViewById(R.id.changeCityButton); mUserCityEditText = (EditText)v.findViewById(R.id.newCityEditText); return v; } }
package com.smxknife.java2.collections.concurrent; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author smxknife * 2019/9/2 */ public class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>(); System.out.println("==== putIfAbsent ===="); Integer integer = map.putIfAbsent(1, 10); System.out.println(map + " | " + integer); integer = map.putIfAbsent(1, 11); System.out.println(map + " | " + integer); System.out.println("==== putIfAbsent只有在key不存在时,才能添加成功,成功是返回null,不成功时返回已经存在的值"); System.out.println("==== compute ===="); integer = map.compute(1, (v1, v2) -> { System.out.println("v1 = " + v1); System.out.println("v2 = " + v2); return v2; }); System.out.println(map + " | " + integer); integer = map.compute(1, (key, val) -> { System.out.println("key = " + key); System.out.println("val = " + val); return val + key; }); System.out.println(map + " | " + integer); integer = map.compute(2, (key, val) -> { System.out.println("key = " + key); System.out.println("val = " + val); return key; }); System.out.println(map + " | " + integer); System.out.print("==== compute 用于对key的值进行重计算,key可以存在,也可以不存在,但是如果不存在时,key对应的value为null;\r\n"); System.out.println(" compute总共有两个参数,第一个为key,第二个为一个lambda表达式BiFunction,两个参数一个返回值,两个参数分别表示key和value"); System.out.println("==== computeIfAbsent ===="); integer = map.computeIfAbsent(1, (key) -> { System.out.println("key = " + key); // 因为key已经存在,所以lambda都不会执行 return null; }); System.out.println(map + " | " + integer); integer = map.computeIfAbsent(3, (key) -> { System.out.println("key = " + key); // 还有一点要注意,这里参数是key,而不是value,之前就已经误以为错误value return null; }); System.out.println(map + " | " + integer); integer = map.computeIfAbsent(3, (key) -> { System.out.println("key = " + key); // 还有一点要注意,这里参数是key,而不是value,之前就已经误以为错误value return 3; }); System.out.println(map + " | " + integer); System.out.println("==== computeIfAbsent 只有在key不存在的时候才会执行lambda,lambda可以返回null,返回null时没有任何副作用"); System.out.println("==== computeIfPresent ===="); integer = map.computeIfPresent(4, (key, val) -> { System.out.println("key = " + key); System.out.println("val = " + val); return null; }); System.out.println(map + " | " + integer); integer = map.computeIfPresent(1, (key, val) -> { System.out.println("key = " + key); System.out.println("val = " + val); return key + val; }); System.out.println(map + " | " + integer); integer = map.computeIfPresent(3, (key, val) -> { System.out.println("key = " + key); System.out.println("val = " + val); return null; }); System.out.println(map + " | " + integer); System.out.println("==== computeIfPresent 只有key存在才会进行处理,如何处理取决于lambda返回的结果,如果lambda返回为null,相当于删除;如果非null进行数据替换"); System.out.println("==== mappingCount ===="); long l = map.mappingCount(); System.out.println(l); System.out.println("==== mappingCount size的替代方法,防止int类型溢出"); System.out.println("==== keySet ===="); ConcurrentHashMap.KeySetView<Integer, Integer> integers = map.keySet(20); System.out.println(integers); System.out.println(map); boolean add = integers.add(10); System.out.println(integers); System.out.println(map); integers.addAll(Arrays.asList(2, 3, 4)); System.out.println(integers); System.out.println(map); integers.remove(4); System.out.println(integers); System.out.println(map); System.out.println("==== keySet 这是一个key的视图操作器,mappedValue对应的是通过该视图添加key的默认值。这个在某些场景下相当便利"); ConcurrentHashMap.KeySetView<Integer, Integer> integers1 = map.keySet(); // integers1.add(4); // 报错了 integers1.remove(10); System.out.println(integers1); System.out.println(map); System.out.println("==== merge ===="); integer = map.merge(4, 41, (oriVal, newVal) -> { System.out.println("oriVal = " + oriVal); System.out.println("newVal = " + newVal); return null; }); System.out.println(map + " | " + integer); integer = map.merge(4, 40, (oriVal, newVal) -> { System.out.println("oriVal = " + oriVal); System.out.println("newVal = " + newVal); return oriVal + newVal; }); System.out.println(map + " | " + integer); integer = map.merge(4, 40, (oriVal, newVal) -> { System.out.println("oriVal = " + oriVal); System.out.println("newVal = " + newVal); return null; }); System.out.println(map + " | " + integer); System.out.println("==== merge 很类似computeIfPresent,很大的不同点是lambda的表达式参数,两个都为value值,不是key"); System.out.println("==== reduce ===="); map.put(4, 40); map.put(5, 50); integer = map.reduce(4, (key, val) -> { // System.out.println(Thread.currentThread().getName() + " | key = " + key + ", val = " + val); return val; }, (pre, next) -> { System.out.println(Thread.currentThread().getName() + " | pre = " + pre + ", next = " + next); return next; }); System.out.println(map + " | " + integer); String res = map.reduce(4, (key, val) -> { // System.out.println(Thread.currentThread().getName() + " | key = " + key + ", val = " + val); return key + "_" + val; }, (pre, next) -> { System.out.println(Thread.currentThread().getName() + " | pre = " + pre + ", next = " + next); return pre + "|" + next; }); System.out.println(map + " | " + res); System.out.println("==== reduce 操作还是有点小复杂的,看技能树文档吧,里面有清晰的描述"); Map.Entry<Integer, Integer> integerIntegerEntry = map.reduceEntries(4, (e1, e2) -> { System.out.println("e1 = " + e1); System.out.println("e2 = " + e2); return e1; }); System.out.println(integerIntegerEntry); System.out.println("-----"); Map.Entry<Integer, Integer> integerIntegerEntry1 = map.reduceEntries(1, entry -> { System.out.println("entry = " + entry); return entry; }, (e1, e2) -> { System.out.println("e1 = " + e1); System.out.println("e2 = " + e2); return e1; }); System.out.println(integerIntegerEntry1); System.out.println("==== remove(key, val) ===="); System.out.println(map); boolean remove = map.remove(6, 60); System.out.println(map + " | " + remove); remove = map.remove(5, 60); System.out.println(map + " | " + remove); remove = map.remove(5, 50); System.out.println(map + " | " + remove); System.out.println("==== remove 该remove方法必须同时保证key和value都等于map里面key和value,这样才可以删除"); System.out.println("==== search ===="); res = map.search(4, (key, val) -> { System.out.println(Thread.currentThread().getName() + "key = " + key + ", val = " + val); return key + "-" + val; }); System.out.println(map + " | " + res); res = map.search(4, (key, val) -> { System.out.println(Thread.currentThread().getName() + "key = " + key + ", val = " + val); return null; }); System.out.println(map + " | " + res); } }
/** * */ package co.grandcircu.SpringLab22; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * @author kevinbusch * */ @Controller public class AppControler { @RequestMapping("/") public String index() { return "index"; } @RequestMapping("/register") public String registration() { return "registration"; } @RequestMapping("sumbit-person") public ModelAndView submitForm(Person p) { return new ModelAndView("summary", "personinfo", p.getFirstName()); } }
package hr.mealpler.database.entities; import java.math.BigDecimal; import java.sql.Date; public class MenuProductLight { private Long user_id; private Date date; private Long product_id; private BigDecimal amount; public MenuProductLight() { } public MenuProductLight(Long userId, Date date, Long productId, BigDecimal amount) { super(); this.user_id = userId; this.date = date; this.product_id = productId; this.amount = amount; } public Long getUserId() { return user_id; } public void setUserId(Long userId) { this.user_id = userId; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Long getProductId() { return product_id; } public void setProductId(Long productId) { this.product_id = productId; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } }
package com.Arrays; import java.io.*; import java.util.Arrays; public class WaterTrapping { public static void main (String[] args) throws IOException { //code BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader( new FileInputStream("input/dummy"))); } catch (FileNotFoundException e) { e.printStackTrace(); } int testCases = Integer.parseInt(input.readLine()); for(int i = 0; i < testCases; i++){ int numbers = Integer.parseInt(input.readLine()); int[] array = new int[numbers]; array = Arrays.stream(input.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); int waterTrapped = findWater(array, array.length); System.out.println(waterTrapped); } } // Method for maximum amount of water static int findWater(int[] arr, int n) { // left[i] contains height of tallest bar to the // left of i'th bar including itself int left[] = new int[n]; // Right [i] contains height of tallest bar to // the right of ith bar including itself int right[] = new int[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) left[i] = Math.max(left[i-1], arr[i]); // Fill right array right[n-1] = arr[n-1]; for (int i = n-2; i >= 0; i--) right[i] = Math.max(right[i+1], arr[i]); System.out.println(Arrays.toString(arr)); System.out.println(Arrays.toString(left)); System.out.println(Arrays.toString(right)); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 0; i < n; i++) water += Math.min(left[i],right[i]) - arr[i]; return water; } }
package com.example.hello.mymap; import android.app.ActivityManager; //import android.app.Application; import android.app.Application; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.StrictMode; import android.support.multidex.MultiDex; import android.telephony.TelephonyManager; import android.util.Log; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.SDKInitializer; import com.example.hello.mymap.map.widget.MapInptBar; import com.example.hello.mymap.utils.Config; import com.facebook.drawee.backends.pipeline.Fresco; import com.mapbox.mapboxsdk.MapboxAccountManager; import com.qiniu.android.storage.UploadManager; import java.util.Iterator; import java.util.List; import okhttp3.OkHttpClient; /** * Created by Lovepyj on 2016/5/8. */ public class MyApplication extends Application { public final String PREF_USERNAME = "username"; /** * 当前用户nickname,为了苹果推送不是userid而是昵称 */ public static String currentUserNick = ""; private static MyApplication instance; public static Context applicationContext; public static Context mainContext; // public static LocationClient mLocationClient = null; // public static UploadManager uploadManager=null; public static OkHttpClient httpClient=new OkHttpClient(); @Override public void onCreate() { super.onCreate(); MultiDex.install(this); instance=this; applicationContext=this; MapboxAccountManager.start(this,getmapToken()); //百度地图初始化 //SDKInitializer.initialize(this); // mLocationClient = new LocationClient(this); // setGpsOption(); int pid = android.os.Process.myPid(); DemoHelper.getInstance().init(applicationContext); initImg(this); } public static MyApplication getInstance() { return instance; } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } /** 初始化Fresco */ public static void initImg(Context context) { Fresco.initialize(context); } //获得app名字 private String getAppName(int pID) { String processName = null; ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); List l = am.getRunningAppProcesses(); Iterator i = l.iterator(); PackageManager pm = this.getPackageManager(); while (i.hasNext()) { ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next()); try { if (info.pid == pID) { CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA)); // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+ // info.processName +" Label: "+c.toString()); // processName = c.toString(); processName = info.processName; return processName; } } catch (Exception e) { // Log.d("Process", "Error>> :"+ e.toString()); } } return processName; } //获得版本名 public String getVersionName(){ try { PackageManager manager = this.getPackageManager(); PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); String version = info.versionName; return version; } catch (Exception e) { e.printStackTrace(); } return "0"; } public int getVersionCode()//获取版本号(内部识别号) { try { PackageManager manager = this.getPackageManager(); PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); return info.versionCode; } catch (Exception e) { return 0; } /* try { PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return pi.versionCode; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return 0; } */ } //获得map的token public String getmapToken() { return getResources().getString(R.string.accessToken); } void setGpsOption() { LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy );//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系 int span=1000; option.setScanSpan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要 option.setOpenGps(true);//可选,默认false,设置是否使用gps option.setLocationNotify(true);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 option.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集 option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤gps仿真结果,默认需要 // mLocationClient.setLocOption(option); } //获得硬件id public String getDeviceId() { TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); return tm.getDeviceId(); } }
package com.db.dao.evaluation; import java.io.IOException; import com.db.FileDB; import com.db.dao.AbstractDao; public class LoginDao extends AbstractDao{ private static LoginDao instance; public static LoginDao getInstance() throws IOException { if (instance == null) { synchronized (LoginDao.class) { if (instance == null) { instance = new LoginDao(); } } } return instance; } private LoginDao() throws IOException { super(new FileDB("cop6726.evaluation.login.db")); } }
package com.mercadolibre.desafioquality; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc public class FlightSeatsBookingTests { @Test void contextLoads() { } @Autowired private MockMvc mockMvc; String url= "http://localhost:8080/api/v1/flight-reservation"; String request = url; @Test void shouldBookFlightSeatSuccesfully() throws Exception { this.mockMvc.perform(post( request) .contentType(MediaType.APPLICATION_JSON) .content("{\n" + " \"userName\":\"julio@gmail.com\",\n" + " \"flightReservation\": {\n" + " \"dateFrom\":\"10/02/2021\",\n" + " \"dateTo\":\"24/02/2021\",\n" + " \"origin\":\"Bogotá\",\n" + " \"destination\":\"Medellín\",\n" + " \"flightNumber\":\"BOME-4442\",\n" + " \"seats\":2,\n" + " \"seatType\":\"Economy\",\n" + " \"people\": [\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Pepito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\": \"10/11/1982\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " },\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Fulanito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\":\"10/11/1983\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " }\n" + " ]\n" + " , \"paymentMethod\": {\n" + " \"type\":\"credito\",\n" + " \"number\":\"345345\",\n" + " \"dues\":6\n" + " }\n" + " }\n" + "}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().json("{\"userName\":\"julio@gmail.com\",\"amount\":11000.0,\"interest\":10.0,\"total\":12101.0,\"flightReservation\":{\"flightNumber\":\"BOME-4442\",\"origin\":\"Bogotá\",\"destination\":\"Medellín\",\"seatType\":\"Economy\",\"seats\":2,\"dateFrom\":\"10/02/2021\",\"dateTo\":\"24/02/2021\",\"people\":[{\"dni\":\"12345678\",\"name\":\"Pepito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1982\",\"mail\":\"arjonamiguel@gmail.com\"},{\"dni\":\"12345678\",\"name\":\"Fulanito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1983\",\"mail\":\"arjonamiguel@gmail.com\"}],\"paymentMethod\":{\"type\":\"credito\",\"number\":\"345345\",\"dues\":6}},\"statusCode\":{\"code\":\"200\",\"message\":\"Se han encontrado asientos de avión disponibles\"}}")); } @Test void shouldNOTBookFlightSeatSuccesfullyyWhenDestinationDoesNotExists() throws Exception { this.mockMvc.perform(post( request) .contentType(MediaType.APPLICATION_JSON) .content("{\n" + " \"userName\":\"julio@gmail.com\",\n" + " \"flightReservation\": {\n" + " \"dateFrom\":\"10/02/2021\",\n" + " \"dateTo\":\"24/02/2021\",\n" + " \"origin\":\"Bogotá\",\n" + " \"destination\":\"Scerze\",\n" + " \"flightNumber\":\"BOME-4442\",\n" + " \"seats\":2,\n" + " \"seatType\":\"Economy\",\n" + " \"people\": [\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Pepito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\": \"10/11/1982\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " },\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Fulanito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\":\"10/11/1983\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " }\n" + " ]\n" + " , \"paymentMethod\": {\n" + " \"type\":\"credito\",\n" + " \"number\":\"345345\",\n" + " \"dues\":6\n" + " }\n" + " }\n" + "}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().json("{\"userName\":\"julio@gmail.com\",\"amount\":0.0,\"interest\":0.0,\"total\":0.0,\"flightReservation\":{\"flightNumber\":\"BOME-4442\",\"origin\":\"Bogotá\",\"destination\":\"Scerze\",\"seatType\":\"Economy\",\"seats\":2,\"dateFrom\":\"10/02/2021\",\"dateTo\":\"24/02/2021\",\"people\":[{\"dni\":\"12345678\",\"name\":\"Pepito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1982\",\"mail\":\"arjonamiguel@gmail.com\"},{\"dni\":\"12345678\",\"name\":\"Fulanito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1983\",\"mail\":\"arjonamiguel@gmail.com\"}],\"paymentMethod\":{\"type\":\"credito\",\"number\":\"345345\",\"dues\":6}},\"statusCode\":{\"code\":\"404\",\"message\":\"El destino elegido no existe\"}}")); } @Test void shouldNOTBookFlightSeatSuccesfullyWhenOriginDoesNotExists() throws Exception { this.mockMvc.perform(post( request) .contentType(MediaType.APPLICATION_JSON) .content("{\n" + " \"userName\":\"julio@gmail.com\",\n" + " \"flightReservation\": {\n" + " \"dateFrom\":\"10/02/2021\",\n" + " \"dateTo\":\"24/02/2021\",\n" + " \"origin\":\"Azen\",\n" + " \"destination\":\"Medellín\",\n" + " \"flightNumber\":\"BOME-4442\",\n" + " \"seats\":2,\n" + " \"seatType\":\"Economy\",\n" + " \"people\": [\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Pepito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\": \"10/11/1982\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " },\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Fulanito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\":\"10/11/1983\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " }\n" + " ]\n" + " , \"paymentMethod\": {\n" + " \"type\":\"credito\",\n" + " \"number\":\"345345\",\n" + " \"dues\":6\n" + " }\n" + " }\n" + "}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().json("{\"userName\":\"julio@gmail.com\",\"amount\":0.0,\"interest\":0.0,\"total\":0.0,\"flightReservation\":{\"flightNumber\":\"BOME-4442\",\"origin\":\"Azen\",\"destination\":\"Medellín\",\"seatType\":\"Economy\",\"seats\":2,\"dateFrom\":\"10/02/2021\",\"dateTo\":\"24/02/2021\",\"people\":[{\"dni\":\"12345678\",\"name\":\"Pepito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1982\",\"mail\":\"arjonamiguel@gmail.com\"},{\"dni\":\"12345678\",\"name\":\"Fulanito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1983\",\"mail\":\"arjonamiguel@gmail.com\"}],\"paymentMethod\":{\"type\":\"credito\",\"number\":\"345345\",\"dues\":6}},\"statusCode\":{\"code\":\"404\",\"message\":\"El Origen elegido no existe\"}}")); } @Test void shouldNOTBookFlightSeatSuccesfullyWhenMailIsNotValid() throws Exception { this.mockMvc.perform(post( request) .contentType(MediaType.APPLICATION_JSON) .content("{\n" + " \"userName\":\"jul####@gmail.com\",\n" + " \"flightReservation\": {\n" + " \"dateFrom\":\"10/02/2021\",\n" + " \"dateTo\":\"24/02/2021\",\n" + " \"origin\":\"Bogotá\",\n" + " \"destination\":\"Medellín\",\n" + " \"flightNumber\":\"BOME-4442\",\n" + " \"seats\":2,\n" + " \"seatType\":\"Economy\",\n" + " \"people\": [\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Pepito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\": \"10/11/1982\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " },\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Fulanito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\":\"10/11/1983\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " }\n" + " ]\n" + " , \"paymentMethod\": {\n" + " \"type\":\"credito\",\n" + " \"number\":\"345345\",\n" + " \"dues\":6\n" + " }\n" + " }\n" + "}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().json("{\"userName\":\"jul####@gmail.com\",\"amount\":0.0,\"interest\":0.0,\"total\":0.0,\"flightReservation\":{\"flightNumber\":\"BOME-4442\",\"origin\":\"Bogotá\",\"destination\":\"Medellín\",\"seatType\":\"Economy\",\"seats\":2,\"dateFrom\":\"10/02/2021\",\"dateTo\":\"24/02/2021\",\"people\":[{\"dni\":\"12345678\",\"name\":\"Pepito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1982\",\"mail\":\"arjonamiguel@gmail.com\"},{\"dni\":\"12345678\",\"name\":\"Fulanito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1983\",\"mail\":\"arjonamiguel@gmail.com\"}],\"paymentMethod\":{\"type\":\"credito\",\"number\":\"345345\",\"dues\":6}},\"statusCode\":{\"code\":\"404\",\"message\":\"Porfavor ingrese un e-mail válido\"}}")); } @Test void shoulNOTdBookFlightSeatSuccesfullyWhenDateFromIsLaterThanDateTo() throws Exception { this.mockMvc.perform(post( request) .contentType(MediaType.APPLICATION_JSON) .content("{\n" + " \"userName\":\"julio@gmail.com\",\n" + " \"flightReservation\": {\n" + " \"dateFrom\":\"10/06/2021\",\n" + " \"dateTo\":\"24/02/2021\",\n" + " \"origin\":\"Bogotá\",\n" + " \"destination\":\"Medellín\",\n" + " \"flightNumber\":\"BOME-4442\",\n" + " \"seats\":2,\n" + " \"seatType\":\"Economy\",\n" + " \"people\": [\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Pepito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\": \"10/11/1982\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " },\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Fulanito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\":\"10/11/1983\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " }\n" + " ]\n" + " , \"paymentMethod\": {\n" + " \"type\":\"credito\",\n" + " \"number\":\"345345\",\n" + " \"dues\":6\n" + " }\n" + " }\n" + "}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().json("{\"userName\":\"julio@gmail.com\",\"amount\":0.0,\"interest\":0.0,\"total\":0.0,\"flightReservation\":{\"flightNumber\":\"BOME-4442\",\"origin\":\"Bogotá\",\"destination\":\"Medellín\",\"seatType\":\"Economy\",\"seats\":2,\"dateFrom\":\"10/06/2021\",\"dateTo\":\"24/02/2021\",\"people\":[{\"dni\":\"12345678\",\"name\":\"Pepito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1982\",\"mail\":\"arjonamiguel@gmail.com\"},{\"dni\":\"12345678\",\"name\":\"Fulanito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1983\",\"mail\":\"arjonamiguel@gmail.com\"}],\"paymentMethod\":{\"type\":\"credito\",\"number\":\"345345\",\"dues\":6}},\"statusCode\":{\"code\":\"404\",\"message\":\"La fecha de salida debe ser mayor a la de entrada\"}}")); } @Test void shoulnotdBookFlightSeatSuccesfullyWhenTypeSeatIsWrong() throws Exception { this.mockMvc.perform(post( request) .contentType(MediaType.APPLICATION_JSON) .content("{\n" + " \"userName\":\"julio@gmail.com\",\n" + " \"flightReservation\": {\n" + " \"dateFrom\":\"10/02/2021\",\n" + " \"dateTo\":\"24/02/2021\",\n" + " \"origin\":\"Bogotá\",\n" + " \"destination\":\"Medellín\",\n" + " \"flightNumber\":\"BOME-4442\",\n" + " \"seats\":2,\n" + " \"seatType\":\"SUPER ASIENTO\",\n" + " \"people\": [\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Pepito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\": \"10/11/1982\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " },\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Fulanito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\":\"10/11/1983\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " }\n" + " ]\n" + " , \"paymentMethod\": {\n" + " \"type\":\"credito\",\n" + " \"number\":\"345345\",\n" + " \"dues\":6\n" + " }\n" + " }\n" + "}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().json("{\"userName\":\"julio@gmail.com\",\"amount\":0.0,\"interest\":1.1,\"total\":0.0,\"flightReservation\":{\"flightNumber\":\"BOME-4442\",\"origin\":\"Bogotá\",\"destination\":\"Medellín\",\"seatType\":\"SUPER ASIENTO\",\"seats\":2,\"dateFrom\":\"10/02/2021\",\"dateTo\":\"24/02/2021\",\"people\":[{\"dni\":\"12345678\",\"name\":\"Pepito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1982\",\"mail\":\"arjonamiguel@gmail.com\"},{\"dni\":\"12345678\",\"name\":\"Fulanito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1983\",\"mail\":\"arjonamiguel@gmail.com\"}],\"paymentMethod\":{\"type\":\"credito\",\"number\":\"345345\",\"dues\":6}},\"statusCode\":{\"code\":\"200\",\"message\":\"No se encontro ningun asiento de avión disponible para las fechas indicadas\"}}")); } @Test void shouldNOTBookFlightSeatSuccesfullyWhenSeatsDoesNotMatchAmountOfPeopleInTheList() throws Exception { this.mockMvc.perform(post( request) .contentType(MediaType.APPLICATION_JSON) .content("{\n" + " \"userName\":\"julio@gmail.com\",\n" + " \"flightReservation\": {\n" + " \"dateFrom\":\"10/02/2021\",\n" + " \"dateTo\":\"24/02/2021\",\n" + " \"origin\":\"Bogotá\",\n" + " \"destination\":\"Medellín\",\n" + " \"flightNumber\":\"BOME-4442\",\n" + " \"seats\":33333,\n" + " \"seatType\":\"Economy\",\n" + " \"people\": [\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Pepito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\": \"10/11/1982\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " },\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Fulanito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\":\"10/11/1983\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " }\n" + " ]\n" + " , \"paymentMethod\": {\n" + " \"type\":\"credito\",\n" + " \"number\":\"345345\",\n" + " \"dues\":6\n" + " }\n" + " }\n" + "}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().json("{\"userName\":\"julio@gmail.com\",\"amount\":0.0,\"interest\":0.0,\"total\":0.0,\"flightReservation\":{\"flightNumber\":\"BOME-4442\",\"origin\":\"Bogotá\",\"destination\":\"Medellín\",\"seatType\":\"Economy\",\"seats\":33333,\"dateFrom\":\"10/02/2021\",\"dateTo\":\"24/02/2021\",\"people\":[{\"dni\":\"12345678\",\"name\":\"Pepito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1982\",\"mail\":\"arjonamiguel@gmail.com\"},{\"dni\":\"12345678\",\"name\":\"Fulanito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1983\",\"mail\":\"arjonamiguel@gmail.com\"}],\"paymentMethod\":{\"type\":\"credito\",\"number\":\"345345\",\"dues\":6}},\"statusCode\":{\"code\":\"404\",\"message\":\"La cantidad de gente indicada debe coincidir con la lista de personas detallada\"}}")); } @Test void shoulNotdBookFlightSeatSuccesfullyWhenTriesToPayInMoreThan1DueWithDebitCard() throws Exception { this.mockMvc.perform(post( request) .contentType(MediaType.APPLICATION_JSON) .content("{\n" + " \"userName\":\"julio@gmail.com\",\n" + " \"flightReservation\": {\n" + " \"dateFrom\":\"10/02/2021\",\n" + " \"dateTo\":\"24/02/2021\",\n" + " \"origin\":\"Bogotá\",\n" + " \"destination\":\"Medellín\",\n" + " \"flightNumber\":\"BOME-4442\",\n" + " \"seats\":2,\n" + " \"seatType\":\"Economy\",\n" + " \"people\": [\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Pepito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\": \"10/11/1982\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " },\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Fulanito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\":\"10/11/1983\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " }\n" + " ]\n" + " , \"paymentMethod\": {\n" + " \"type\":\"debito\",\n" + " \"number\":\"345345\",\n" + " \"dues\":6\n" + " }\n" + " }\n" + "}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().json("{\"userName\":\"julio@gmail.com\",\"amount\":0.0,\"interest\":0.0,\"total\":0.0,\"flightReservation\":{\"flightNumber\":\"BOME-4442\",\"origin\":\"Bogotá\",\"destination\":\"Medellín\",\"seatType\":\"Economy\",\"seats\":2,\"dateFrom\":\"10/02/2021\",\"dateTo\":\"24/02/2021\",\"people\":[{\"dni\":\"12345678\",\"name\":\"Pepito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1982\",\"mail\":\"arjonamiguel@gmail.com\"},{\"dni\":\"12345678\",\"name\":\"Fulanito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1983\",\"mail\":\"arjonamiguel@gmail.com\"}],\"paymentMethod\":{\"type\":\"debito\",\"number\":\"345345\",\"dues\":6}},\"statusCode\":{\"code\":\"404\",\"message\":\"Se ha ingresado una cantidad de cuotas distinta de 1\"}}")); } @Test void shouldNotBookFlightSeatSuccesfullyWhenDoesntInformPaymentMethod() throws Exception { this.mockMvc.perform(post( request) .contentType(MediaType.APPLICATION_JSON) .content("{\n" + " \"userName\":\"julio@gmail.com\",\n" + " \"flightReservation\": {\n" + " \"dateFrom\":\"10/02/2021\",\n" + " \"dateTo\":\"24/02/2021\",\n" + " \"origin\":\"Bogotá\",\n" + " \"destination\":\"Medellín\",\n" + " \"flightNumber\":\"BOME-4442\",\n" + " \"seats\":2,\n" + " \"seatType\":\"Economy\",\n" + " \"people\": [\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Pepito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\": \"10/11/1982\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " },\n" + " {\n" + " \"dni\":\"12345678\",\n" + " \"name\":\"Fulanito\",\n" + " \"lastname\":\"gonzalez\",\n" + " \"birthDate\":\"10/11/1983\",\n" + " \"mail\":\"arjonamiguel@gmail.com\"\n" + " }\n" + " ]\n" + " \n" + " }\n" + "}")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().json("{\"userName\":\"julio@gmail.com\",\"amount\":0.0,\"interest\":0.0,\"total\":0.0,\"flightReservation\":{\"flightNumber\":\"BOME-4442\",\"origin\":\"Bogotá\",\"destination\":\"Medellín\",\"seatType\":\"Economy\",\"seats\":2,\"dateFrom\":\"10/02/2021\",\"dateTo\":\"24/02/2021\",\"people\":[{\"dni\":\"12345678\",\"name\":\"Pepito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1982\",\"mail\":\"arjonamiguel@gmail.com\"},{\"dni\":\"12345678\",\"name\":\"Fulanito\",\"lastname\":\"gonzalez\",\"birthDate\":\"10/11/1983\",\"mail\":\"arjonamiguel@gmail.com\"}],\"paymentMethod\":null},\"statusCode\":{\"code\":\"404\",\"message\":\"ERROR, debe informar un medio de pago\"}}")); } }
package com.tencent.mm.ui.chatting.gallery; class ImageGalleryUI$8 implements Runnable { final /* synthetic */ int eKj; final /* synthetic */ ImageGalleryUI tWn; ImageGalleryUI$8(ImageGalleryUI imageGalleryUI, int i) { this.tWn = imageGalleryUI; this.eKj = i; } public final void run() { if (ImageGalleryUI.f(this.tWn) != null) { b f = ImageGalleryUI.f(this.tWn); f.tTE.pause(this.eKj); } } }
package com.lbsp.promotion.entity.model; public class Task extends BaseModel{ private String name; private String class_name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClass_name() { return class_name; } public void setClass_name(String class_name) { this.class_name = class_name; } }
package cn.yhd.config; import cn.yhd.bean.User; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.stereotype.Component; /** * @Author: yuhuadong * @Date: 2019/8/21 5:59 PM * @Description: */ @Configuration public class TestConfig { @Value("${test.value}") private String testValue; @Value("${test.password}") private String password; @Bean public User user() { User user = new User(); user.setUsername(testValue); user.setPassword(password); return user; } }
package fall2018.csc2017.scoring; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class LeaderBoardTest { /** * A LeaderBoard for testing */ private LeaderBoard testLeaderBoard; /** * A List of scores used as 'expected'. */ private List<Score> expectedScores; /** * Makes the LeaderBoard for testing, and the expectedScores for Sliding Tiles. */ private void buildBoard() { this.testLeaderBoard = new LeaderBoard(); this.expectedScores = new ArrayList<>(); for (int i = 0; i < 5; i++) { expectedScores.add(new Score("", 0)); } } /** * Tests the getGameScores() method with no updated scores.. */ @Test public void testGetGameScores() { buildBoard(); assertTrue(checkElements(expectedScores)); } /** * Tests the updateScores() method. */ @Test public void testUpdateScores() { buildBoard(); Score toAdd = new Score("User1", 100); expectedScores.set(0, toAdd); testLeaderBoard.updateScores("Sliding Tiles", toAdd); assertTrue(checkElements(expectedScores)); } /** * Tests the updateLeaderBoard() method. */ @Test public void testUpdateFullLeaderBoard() { testLeaderBoard = new LeaderBoard(); buildBoard(); Score score1 = new Score("User", 100); Score score2 = new Score("User", 200); Score score3 = new Score("User", 150); testLeaderBoard.updateScores("Sliding Tiles", score1); expectedScores.set(0, score1); assertTrue(checkElements(testLeaderBoard.getGameScores("Sliding Tiles"))); testLeaderBoard.updateScores("Sliding Tiles", score2); expectedScores.set(0, score2); expectedScores.set(1, score1); assertTrue(checkElements(testLeaderBoard.getGameScores("Sliding Tiles"))); testLeaderBoard.updateScores("Sliding Tiles", score3); expectedScores.set(1, score3); expectedScores.set(2, score1); assertTrue(checkElements(testLeaderBoard.getGameScores("Sliding Tiles"))); } /** * A helper method for checking all elements in a Score array. */ private boolean checkElements(List<Score> toCompare) { for (Score s : this.testLeaderBoard.getGameScores("Sliding Tiles")) { int i = this.testLeaderBoard.getGameScores("Sliding Tiles").indexOf(s); if (!toCompare.get(i).equals(s)) { return false; } } return true; } }
package edu.illinois.finalproject.PlayerGuides; import android.os.Parcel; import android.os.Parcelable; import java.util.List; /** * Created by liam on 12/3/17. */ /* {"Title": "Test", "User": "id" "Introduction": "to play jax one must be good at the game of league of legends", "Items": [ {"Starting Items": ["Dorans Blade", "Health Potion"]}, {"Core Items": ["Trinity Force", "Titanic Hydra"]}, {"Situational Items": ["Hexdrinker", "Randuins Omen"]} ], "Summoners": ["flash", "teleport"], "Ability Skill Order": ["w","e","q","w","w","r","w","q","w","q","r","q","q","e","e","r","e","e"], "Body": "Early game: win lane \n Mid Game: Get towers \n Late Game: rat Dota", "Countered By": ["Fiora","Teemo"], "Counters": ["Malphite", "Camille"], "Quick Tips": ["W is an Auto Reset","Can hop to Wards"] } */ public class Guide implements Parcelable { public static final Parcelable.Creator<Guide> CREATOR = new Parcelable.Creator<Guide>() { @Override public Guide createFromParcel(Parcel source) { return new Guide(source); } @Override public Guide[] newArray(int size) { return new Guide[size]; } }; private String user; private String title; private String introduction; private String body; private List<String> StartingItems; private List<String> CoreItems; private List<String> SituationalItems; private List<String> Summoners; private List<String> abilitySkillOrder; private List<String> counters; private List<String> counteredBy; private List<String> quickTips; public Guide() { } protected Guide(Parcel in) { this.user = in.readString(); this.title = in.readString(); this.introduction = in.readString(); this.body = in.readString(); this.StartingItems = in.createStringArrayList(); this.CoreItems = in.createStringArrayList(); this.SituationalItems = in.createStringArrayList(); this.Summoners = in.createStringArrayList(); this.abilitySkillOrder = in.createStringArrayList(); this.counters = in.createStringArrayList(); this.counteredBy = in.createStringArrayList(); this.quickTips = in.createStringArrayList(); } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public List getStartingItems() { return StartingItems; } public void setStartingItems(List startingItems) { StartingItems = startingItems; } public List getCoreItems() { return CoreItems; } public void setCoreItems(List coreItems) { CoreItems = coreItems; } public List getSituationalItems() { return SituationalItems; } public void setSituationalItems(List situationalItems) { SituationalItems = situationalItems; } public List getSummoners() { return Summoners; } public void setSummoners(List summoners) { Summoners = summoners; } public List getAbilitySkillOrder() { return abilitySkillOrder; } public void setAbilitySkillOrder(List abilitySkillOrder) { this.abilitySkillOrder = abilitySkillOrder; } public List getCounters() { return counters; } public void setCounters(List counters) { this.counters = counters; } public List getCounteredBy() { return counteredBy; } public void setCounteredBy(List counteredBy) { this.counteredBy = counteredBy; } public List getQuickTips() { return quickTips; } public void setQuickTips(List quickTips) { this.quickTips = quickTips; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.user); dest.writeString(this.title); dest.writeString(this.introduction); dest.writeString(this.body); dest.writeStringList(this.StartingItems); dest.writeStringList(this.CoreItems); dest.writeStringList(this.SituationalItems); dest.writeStringList(this.Summoners); dest.writeStringList(this.abilitySkillOrder); dest.writeStringList(this.counters); dest.writeStringList(this.counteredBy); dest.writeStringList(this.quickTips); } }
package com.qimou.sb.web.controller; import java.net.URLDecoder; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.qimou.sb.web.entity.Contract; import com.qimou.sb.web.service.ContractService; import com.qimou.sb.web.tool.JsonUtil; @Controller public class ContractServlet { private static final Logger logger = LoggerFactory.getLogger(ContractServlet.class); @Autowired private ContractService contractService; // @Autowired // private JsonUtil jsonUtil; /** * * @Author:HaoMing(郝明) * @Project_name:patent * @Full_path:com.qimou.sb.web.controller.ContractServlet.java * @Date:@2018 2018-7-27 下午2:03:39 * @Return_type:String * @Desc :获得一个任务(合同)实体 * jsonStr : {"taskID":"***"} */ @RequestMapping("singleTask") @ResponseBody public String singleTask(@RequestBody String jsonStr,HttpServletRequest request) throws Exception{ jsonStr = URLDecoder.decode(jsonStr, "UTF-8"); Contract singleTask = contractService.singleTask(JsonUtil.jsonStr2Map(jsonStr).get("taskID").toString()); return JsonUtil.bean2JsonStr(singleTask, null); } /** * * @throws Exception * @Author:HaoMing(郝明) * @Project_name:patent * @Full_path:com.qimou.sb.web.controller.ContractServlet.java * @Date:@2018 2018-7-27 下午2:03:12 * @Return_type:String * @Desc :获得同一合同下的所有任务 * jsonStr : {"contractID":"***"} */ @RequestMapping("listTask") @ResponseBody public String listTask(@RequestBody String jsonStr,HttpServletRequest request) throws Exception{ jsonStr = URLDecoder.decode(jsonStr, "UTF-8"); List<Contract> listTask = contractService.listTask(JsonUtil.jsonStr2Map(jsonStr).get("contractID").toString()); return JsonUtil.list2JsonStr(listTask); } /** * * @author : haoming * @date : 2018年7月31日下午1:55:01 * @patent com.qimou.sb.web.controller.ContractServlet.java.listContract * @returnType : String * @desc :获得合同列表 * jsonStr : {"stat":"***","pageNum":"***"} */ @RequestMapping("listContract") @ResponseBody public String listContract(@RequestBody String jsonStr,HttpServletRequest request){ List<Contract> listCont = null; Map<Object, Object> returnMap = new HashMap<Object, Object>(); try { jsonStr = URLDecoder.decode(jsonStr, "UTF-8"); Map<Object, Object> jsonStr2Map = JsonUtil.jsonStr2Map(jsonStr); String stat = jsonStr2Map.get("stat").toString(); String pageNum = jsonStr2Map.get("pageNum").toString(); listCont = contractService.listContract(stat==null?-1:Integer.parseInt(stat), Integer.parseInt(pageNum), 10); returnMap.put("userTotalNum", contractService.contractNum(stat==null?-1:Integer.parseInt(stat))); } catch (Exception e) { e.printStackTrace(); logger.error(e.toString()); } return JsonUtil.generalMixJson(listCont,returnMap,"userList"); } /** * * @Author:HaoMing(郝明) * @Project_name:patent * @Full_path:com.qimou.sb.web.controller.UserServlet.java * @Date:@2018 2018-7-26 上午10:25:52 * @Return_type:String * @Desc :添加实体 * jsonStr : [{"$$$":"***","###":"***",...},{"$$$":"***","###":"***",...},...] */ @RequestMapping("addContract") @ResponseBody public String addContract(@RequestBody String jsonStr,HttpServletRequest request){ // logger.info("jsonStr: "+jsonStr); Map<String, String> returnMap = new HashMap<String, String>(); String returnStr = ""; try { jsonStr = URLDecoder.decode(jsonStr, "UTF-8"); List<Object> contractList = JsonUtil.jsonStr2Beans(jsonStr, Contract.class); if(contractService.addContract(contractList)>=1){ returnMap.put("code", "0"); returnMap.put("msg", "添加成功"); } } catch (Exception e) { returnMap.put("code", "1"); returnMap.put("msg", "添加失败"); logger.error(e.toString()); } finally{ returnStr = JsonUtil.map2JsonStr(returnMap); } return returnStr; } @RequestMapping("distributeTask") @ResponseBody public String distributeTask(@RequestBody String jsonStr,HttpServletRequest request){ // logger.info("jsonStr: "+jsonStr); Map<String, String> returnMap = new HashMap<String, String>(); String returnStr = ""; try { jsonStr = URLDecoder.decode(jsonStr, "UTF-8"); List<Object> contractUserList = JsonUtil.jsonStr2Beans(jsonStr, Map.class); if(contractService.distributeTask(contractUserList)>=1){ returnMap.put("code", "0"); returnMap.put("msg", "分配成功"); } } catch (Exception e) { returnMap.put("code", "1"); returnMap.put("msg", "分配失败"); logger.error(e.toString()); } finally{ returnStr = JsonUtil.map2JsonStr(returnMap); } return returnStr; } /** * * @Author:HaoMing(郝明) * @Project_name:patent * @Full_path:com.qimou.sb.web.controller.ContractServlet.java * @Date:@2018 2018-7-27 下午12:02:02 * @Return_type:String * @Desc :修改实体 * jsonStr : {"$$$":"***","###":"***",...} */ @RequestMapping("updateTask") @ResponseBody public String updateTask(@RequestBody String jsonStr,HttpServletRequest request){ Map<String, String> returnMap = new HashMap<String, String>(); String returnStr = ""; try { jsonStr = URLDecoder.decode(jsonStr, "UTF-8"); Contract contract = (Contract)JsonUtil.jsonStr2Bean(jsonStr, Contract.class); if(contractService.updateTask(contract)>=1){ returnMap.put("code", "0"); returnMap.put("msg", "修改成功"); } } catch (Exception e) { returnMap.put("code", "1"); returnMap.put("msg", "修改失败"); logger.error(e.toString()); } finally{ returnStr = JsonUtil.map2JsonStr(returnMap); } return returnStr; } /** * * @Author:HaoMing(郝明) * @Project_name:patent * @Full_path:com.qimou.sb.web.controller.ContractServlet.java * @Date:@2018 2018-7-27 上午11:58:29 * @Return_type:String * @Desc :删除实体 【注意 content type 要设置成 application/json,否则会在请求体后多一个=】 * jsonStr : {"culName":"***","id":"***"} */ @RequestMapping("delContract") @ResponseBody public String delContract(@RequestBody String jsonStr,HttpServletRequest request){ Map<String, String> returnMap = new HashMap<String, String>(); String returnStr=""; try { jsonStr = URLDecoder.decode(jsonStr, "UTF-8"); Map<Object, Object> map = JsonUtil.jsonStr2Map(jsonStr); String culName = map.get("culName").toString(); String id = map.get("id").toString(); if(contractService.delContract(culName,id) >= 1){ returnMap.put("code", "0"); returnMap.put("msg", "删除成功"); } } catch (Exception e) { returnMap.put("code", "1"); returnMap.put("msg", "删除失败"); logger.error(e.toString()); } finally{ returnStr = JsonUtil.map2JsonStr(returnMap); } return returnStr; } }
package ns.tcphack; /** * Created by freem on 3/23/2017. */ public class InputResults { public static final int NEXT_HEADER = 6; public static final int PAYLOAD = 4; public static final int SEQUENCE_NUMBER = 44; public static final int ACK_NUMBER = 48; public static final int TCP_HEADER_SIZE = 52; public static final int FLAGS = 53; private int ipHeaderSize; private int tcpHeaderSize; private int totalSize; private int[] serverInfo; private int[] data; private long sequenceNumber; private long acknowledgeNumber; private boolean corrupted; private boolean syn; private boolean ack; private boolean fin; public InputResults(int[] serverInfo){ this.serverInfo = serverInfo; corrupted = false; try { if (serverInfo[NEXT_HEADER] == 253) { ipHeaderSize = 40; } else if (serverInfo[NEXT_HEADER + 40] == 253) { ipHeaderSize = 80; } else { ipHeaderSize = 120; } tcpHeaderSize = serverInfo[TCP_HEADER_SIZE] >> 4; data = new int[getTotalSize() - tcpHeaderSize]; System.arraycopy(serverInfo, ipHeaderSize+tcpHeaderSize, data, 0, totalSize-tcpHeaderSize-1); } catch (ArrayIndexOutOfBoundsException e) { corrupted = true; } } public int[] getData() { return data; } public long getSequenceNumber() { long seq = 0; for (int i = 0; i < 4; i++) { seq = seq << 8; seq += serverInfo[SEQUENCE_NUMBER + i]; } return seq; } public void setSequenceNumber(long sequenceNumber) { for (int i = 3; i >= 0; i++) { serverInfo[SEQUENCE_NUMBER] = (int) sequenceNumber >> (8 * i); } } public long getAcknowledgeNumber() { long ack = 0; for (int i = 0; i < 4; i++) { ack = ack << 8; ack += serverInfo[ACK_NUMBER + i]; } return ack; } public boolean isCorrupted() { return corrupted; } public boolean isSyn() { return ((serverInfo[FLAGS] >> 1) & 1) == 1; } public boolean isAck() { return ((serverInfo[FLAGS] >> 5) & 1) == 1; } public boolean isFin() { return (serverInfo[FLAGS] & 1) == 1; } public int getTotalSize() { return (serverInfo[PAYLOAD] << 8) + (serverInfo[5]); } public int[] getServerInfo() { return serverInfo; } }
package fr.products; public class Product { private String ref; // private int stock; private String price; private String name; // private int id; /** * Constructor which takes 3 params * @param ref * @param price * @param name */ public Product(String ref, String name, String price) { this.name = name; this.ref = ref; this.price = price; // this.id = id; } public void setRef(String ref) { this.ref = ref; } public void setPrice(String price) { this.price = price; } public void setName(String name) { this.name = name; } /** *le nom du produit * @return => name */ public String getName() { return name; } /** *la référence du produit * @return => ref */ public String getRef() { return ref; } /** *le prix unitaire du produit * @return => price */ public String getPrice() { return price; } // public void setId(int id) { // this.id = id; // } // // public int getId() { // return id; // } /** *Méthod of creation of an object fr.catalog.Product * @return => a new user or a update user */ @Override public String toString() { return "Product ->\t" + "Ref = " + ref + " stock = " + "\tprice = " + price + "\tname = " + name; } }
package net.rainmore.persistent.integrator; import net.rainmore.persistent.events.EntitySaveListener; import net.rainmore.persistent.events.EntitySaveOrUpdateListener; import org.hibernate.cfg.Configuration; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.integrator.spi.Integrator; import org.hibernate.metamodel.source.MetadataImplementor; import org.hibernate.service.spi.SessionFactoryServiceRegistry; public class EntityAuditIntegrator implements Integrator { public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactoryImplementor, SessionFactoryServiceRegistry sessionFactoryServiceRegistry) { final EventListenerRegistry eventListenerRegistry = sessionFactoryServiceRegistry.getService( EventListenerRegistry.class ); eventListenerRegistry.prependListeners(EventType.SAVE_UPDATE, new EntitySaveOrUpdateListener()); eventListenerRegistry.prependListeners(EventType.SAVE, new EntitySaveListener()); } public void integrate(MetadataImplementor metadataImplementor, SessionFactoryImplementor sessionFactoryImplementor, SessionFactoryServiceRegistry sessionFactoryServiceRegistry) { //To change body of implemented methods use File | Settings | File Templates. } public void disintegrate(SessionFactoryImplementor sessionFactoryImplementor, SessionFactoryServiceRegistry sessionFactoryServiceRegistry) { //To change body of implemented methods use File | Settings | File Templates. } }
package com.wq.dao; import com.wq.bean.Employee; import java.util.List; /** * Created by qwu on 2018/9/5. */ public interface EmployeeMapperPlus { /** * 根据id查询员工信息 * @param id * @return */ public Employee selectEmpById(Integer id); /** * 根据id查询员工及其部门信息 * @param id * @return */ public Employee selectEmpAndDeptById(Integer id); /** * 分步查询出员工信息、部门信息 * @param id * @return */ public Employee selectEmpAndDeptByStep(Integer id); /** * 根据部门Id查询员工信息 * @param deptId * @return */ public List<Employee> getEmpsByDeptId(Integer deptId); }
package eventbus; import com.google.common.eventbus.Subscribe; import observer.Message; import observer.Observer; /** * @Author: lty * @Date: 2021/2/1 09:33 * 实际观察者1 使用同步阻塞式 */ public class Ob1 { @Subscribe public void execute(Message message) { long l = System.currentTimeMillis(); System.out.println("第1个观察者 使用同步阻塞式 开始获取消息并处理..."); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("第1个观察者处理完毕:"+message.getMessage()); System.out.println("操作耗时:"+(System.currentTimeMillis()-l)+"ms"); System.out.println("-------------------------------------------------------------------------------"); } }
/** * CommonFramework * * Copyright (C) 2017 Black Duck Software, Inc. * http://www.blackducksoftware.com/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.blackducksoftware.tools.commonframework.core.config; import java.io.File; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Set; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.builder.fluent.Configurations; import org.apache.commons.configuration2.ex.ConfigurationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.blackducksoftware.tools.commonframework.core.exception.CommonFrameworkException; public class ConfigurationProperties { private final static Logger logger = LoggerFactory.getLogger(ConfigurationProperties.class.getName()); // When we write property values to a config file, // we are responsible for escaping these characters private static final Character[] CHARACTERS_TO_ESCAPE = { '\\', '(', '[', '$', '=', ']', ')' }; // When we read property values from a file, // we must unescape these characters private final Character[] CHARACTERS_TO_UNESCAPE = { '(', '[', '$', '=', ']', ')' }; private final static List<Character> charsToEscape = Arrays.asList(CHARACTERS_TO_ESCAPE); private final List<Character> charsToUnEscape = Arrays.asList(CHARACTERS_TO_UNESCAPE); private Configuration config = new PropertiesConfiguration(); private Properties propertiesObject; public ConfigurationProperties() { } public void load(final File file) throws CommonFrameworkException { propertiesObject = null; final Configurations configs = new Configurations(); try { config = configs.properties(file); } catch (final ConfigurationException e) { throw new CommonFrameworkException("Error loading properties from file " + file.getAbsolutePath() + ": " + e.getMessage()); } getProperties(); } private String unescape(String key, String s) { logger.debug("Before unescaping: " + obscurePassword(key, s)); final StringBuilder sb = new StringBuilder("\\x"); for (final Character c : charsToUnEscape) { sb.setCharAt(1, c); final String target = sb.toString(); final String replacement = String.valueOf(c); s = s.replace(target, replacement); } logger.debug("After unescaping: " + obscurePassword(key, s)); return s; } private String obscurePassword(String key, String value){ if (key.endsWith(".password")){ return "********"; } return value; } public Properties getProperties() { if (config == null) { logger.warn("getProperties(): config is null!"); } if (propertiesObject != null) { return propertiesObject; } propertiesObject = new Properties(); final Iterator<String> iter = config.getKeys(); while (iter.hasNext()) { final String key = iter.next(); final String unEscapedValue = unescape(key, config.getString(key)); logger.debug("getProperties(): including: " + key + "=" + obscurePassword(key, config.getString(key) + " --> " + unEscapedValue)); propertiesObject.put(key, unEscapedValue); } return propertiesObject; } /** * Escape the given string, escaping any special characters with another * backslash * * @param s * @return */ public static String escape(final String s) { final byte[] bufferIn = s.getBytes(); final StringBuilder sb = new StringBuilder(); for (int bufferInIndex = 0; bufferInIndex < bufferIn.length; bufferInIndex++) { final Character c = new Character(s.charAt(bufferInIndex)); if (charsToEscape.contains(c)) { logger.debug("Escaping: " + c); sb.append('\\'); } sb.append(c); } final String escapedString = sb.toString(); return escapedString; } /** * Add the given Properties to this config object. * * This method is not completely safe... Probably fine to use in tests, but * it's safer for production code to use load(File). Reason: This method * introduces extra processing of property values and corresponding the risk * of inconsistent handling of special characters and escaped characters. * * @param sourceProps */ public void addAll(final Properties sourceProps) { propertiesObject = null; for (final Object keyObj : sourceProps.keySet()) { final String key = (String) keyObj; logger.debug("addAll(): adding: " + key + "=" + obscurePassword(key, sourceProps.getProperty(key))); config.addProperty(key, sourceProps.getProperty(key)); } getProperties(); } public void setProperty(final String key, final String value) { config.setProperty(key, value); getProperties().setProperty(key, value); } public boolean containsKey(final String key) { return config.containsKey(key); } public String getProperty(final String key) { return getProperties().getProperty(key); } public Set<Object> keySet() { return getProperties().keySet(); } public int size() { return getProperties().size(); } @Override public String toString() { return getProperties().toString(); } }
package com.org.review.controller; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.RequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.org.review.helper.ReviewHelper; import com.org.review.model.Review; import com.org.review.service.IReviewService; @RunWith(SpringRunner.class) @WebMvcTest(value = ReviewController.class) public class TestReviewController { @MockBean IReviewService mockReviewService; @Autowired MockMvc mockMvc; @Test public void testGetReviews() throws Exception { ReviewHelper helper = new ReviewHelper(); String expectedReviewListResponse = helper.dummyReviewList(); List<Review> expectedReviewList = helper.dummyAllReviews(); when(mockReviewService.getReviews(1)).thenReturn(expectedReviewList); RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/101/reviews/getReviews") .accept(MediaType.APPLICATION_JSON); MvcResult result = mockMvc.perform(requestBuilder).andReturn(); assertEquals("Expected matches actual", expectedReviewListResponse, result.getResponse().getContentAsString()); } // @Test // public void testGetSpecificReview() throws Exception { // ReviewHelper helper = new ReviewHelper(); // ResponseEntity<Review> expectedReviewResponse = helper.dummySpecificReviewResponse(); // Review expectedReview = helper.dummySpecificReview().get(); // when(mockReviewService.getSpecificReview(1)).thenReturn(expectedReview); // RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/reviews/getSpecificReview/1") // .accept(MediaType.APPLICATION_JSON); // MvcResult result = mockMvc.perform(requestBuilder).andReturn(); // assertEquals("Expected matches actual", expectedReviewResponse.getBody().toString(), // result.getResponse().getContentAsString()); // // } // @Test // public void testAddReview() throws Exception { // ReviewHelper helper = new ReviewHelper(); // ResponseEntity<List<Review>> expectedReviewListResponse = helper.dummyReviewResponse(); // List<Review> expectedReviewList = helper.dummyAllReviews(); // //when(mockReviewService.addReview(Mockito.any(Review.class)).thenReturn(expectedReviewList); // RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/api/reviews/getReviews") // .accept(MediaType.APPLICATION_JSON); // MvcResult result = mockMvc.perform(requestBuilder).andReturn(); // assertEquals("Expected matches actual", expectedReviewListResponse.getBody().toString(), // result.getResponse().getContentAsString()); // // } // // @Test // public void testUpdateReview() throws Exception { // ReviewHelper helper = new ReviewHelper(); // ResponseEntity<List<Review>> expectedReviewListResponse = helper.dummyReviewResponse(); // List<Review> expectedReviewList = helper.dummyAllReviews(); // when(mockReviewService.getReviews()).thenReturn(expectedReviewList); // RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/reviews/getReviews") // .accept(MediaType.APPLICATION_JSON); // MvcResult result = mockMvc.perform(requestBuilder).andReturn(); // // assertEquals("Expected matches actual", expectedReviewListResponse.getBody().toString(), // result.getResponse().getContentAsString()); // // } // // @Test // public void testDeleteReview() throws Exception { // ReviewHelper helper = new ReviewHelper(); // ResponseEntity<List<Review>> expectedReviewListResponse = helper.dummyReviewResponse(); // List<Review> expectedReviewList = helper.dummyAllReviews(); // when(mockReviewService.getReviews()).thenReturn(expectedReviewList); // RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/reviews/getReviews") // .accept(MediaType.APPLICATION_JSON); // MvcResult result = mockMvc.perform(requestBuilder).andReturn(); // assertEquals("Expected matches actual", expectedReviewListResponse.getBody().toString(), // result.getResponse().getContentAsString()); // // } }
package tilePack; import java.util.ArrayList; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import mainGame.WindowGame; public class Door extends Tile { private Image openImg; private Image closeImg; private boolean open = false; private int rotation = 0; public Door(String name, ArrayList<Image> img,GameContainer container) { super(name, img.get(1)); openImg = img.get(0); closeImg = img.get(1); this.setReverse(true); // TODO Auto-generated constructor stub } @Override public void render(Graphics g,GameContainer container) { if(this.isOpen()) { openImg.setRotation(this.rotation); g.drawImage(openImg, xdraw, ydraw); } else { closeImg.setRotation(this.rotation); g.drawImage(closeImg, xdraw, ydraw); } } @Override public void update(GameContainer container, int delta){ Input input = container.getInput(); if(WindowGame.cursor.getTileXIndex() == this.getX() && WindowGame.cursor.getTileYIndex() == this.getY()) { if (input.isMousePressed(Input.MOUSE_RIGHT_BUTTON)) { this.setOpen(!this.isOpen()); } } } public void reverseImage() { if(this.getRotation() == 180) { this.setRotation(0); this.setRotation(0); } else { this.setRotation(180); this.setRotation(180); } } public boolean isOpen() { return open; } public void setOpen(boolean open) { if(open == false) { this.tag = "solid"; } else { this.tag = "transparent"; } this.open = open; } public int getRotation() { return rotation; } public void setRotation(int rotation) { this.rotation = rotation; } }
package service; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import model.Ngo; public class NgoDao { private static final String getNgo="select * from ngo where User_email = ? "; private static final String deleteNgo="Delete from ngo where User_email = ? "; private static final String getAcceptedNgo="select * from ngo where status='Accepted'"; private static final String getAllNgo="select * from ngo where status!='Accepted'"; private static final String storeLogin="insert into login values (?,?,?) "; private static final String checklogin="select type_of_user from login where user_email=? and password=?"; public Ngo getNgo(String email) { Ngo obj=null; try { Connection con=DBConnection.getConnection(); PreparedStatement pstmt=con.prepareStatement(getNgo); pstmt.setString(1, email); ResultSet rs=pstmt.executeQuery(); rs.next(); String User_email=rs.getString(1); String Name=rs.getString(2); String Address=rs.getString(3); String Mobile_Number=rs.getString(4); String Document_Link=rs.getString(5); String Status=rs.getString(6); obj=new Ngo(User_email, Name, Address, Mobile_Number, Document_Link,Status); } catch(Exception e) { System.out.println("getNgo "+e); } return obj; } public ArrayList<Ngo> getAllNgo() { ArrayList<Ngo> result=new ArrayList<Ngo>(); try { Connection con=DBConnection.getConnection(); PreparedStatement pstmt=con.prepareStatement(getAllNgo); ResultSet rs=pstmt.executeQuery(); while(rs.next()) { String User_email=rs.getString(1); String Name=rs.getString(2); String Address=rs.getString(3); String Mobile_Number=rs.getString(4); String Document_Link=rs.getString(5); String Status=rs.getString(6); Ngo obj=new Ngo(User_email, Name, Address, Mobile_Number, Document_Link,Status); result.add(obj); } } catch(Exception e) { System.out.println("getAllNgo "+e); } return result; } public ArrayList<Ngo> getAcceptedNgo() { ArrayList<Ngo> result=new ArrayList<Ngo>(); try { Connection con=DBConnection.getConnection(); PreparedStatement pstmt=con.prepareStatement(getAcceptedNgo); ResultSet rs=pstmt.executeQuery(); while(rs.next()) { String User_email=rs.getString(1); String Name=rs.getString(2); String Address=rs.getString(3); String Mobile_Number=rs.getString(4); String Document_Link=rs.getString(5); String Status=rs.getString(6); Ngo obj=new Ngo(User_email, Name, Address, Mobile_Number, Document_Link,Status); result.add(obj); } } catch(Exception e) { System.out.println("getAcceptedNgo "+e); } return result; } public void delete(String email) { try { Connection con=DBConnection.getConnection(); PreparedStatement pstmt=con.prepareStatement(deleteNgo); pstmt.setString(1, email); pstmt.executeUpdate(); } catch(Exception e) { System.out.println("delete "+e); } } public void storeLogin(String email) { try { String getPassword="select Status from ngo where User_email = ? "; Connection con=DBConnection.getConnection(); PreparedStatement pstmt=con.prepareStatement(getPassword); pstmt.setString(1, email); ResultSet rs=pstmt.executeQuery(); rs.next(); String password=rs.getString(1); String updateStatus="Update ngo set Status = 'Accepted' where User_email = ? "; pstmt=con.prepareStatement(updateStatus); pstmt.setString(1, email); pstmt.executeUpdate(); pstmt=con.prepareStatement(storeLogin); pstmt.setString(1,email); pstmt.setString(2, password); pstmt.setString(3, "ngo"); pstmt.executeUpdate(); } catch(Exception e) { System.out.println("storeLogin "+e); } } public ArrayList<ArrayList<String>> donationList(int id) { ArrayList<ArrayList<String>> res=new ArrayList<ArrayList<String>>(); try { String getdonation="select donor_email , donated_quantity , measurements , donated_date from donation where donation_id = ? "; String getDonor="select Name , Address , Mobile_Number from donor where User_email = ?"; Connection con=DBConnection.getConnection(); PreparedStatement pstmt=con.prepareStatement(getdonation); pstmt.setInt(1, id); ResultSet rs=pstmt.executeQuery(); while(rs.next()) { ArrayList<String> obj=new ArrayList<String>(); obj.add(rs.getString(1)); obj.add(String.valueOf(rs.getInt(2))+" "+rs.getString(3)); String date[]=String.valueOf(rs.getDate(4)).split("-"); String yyyy=date[0];String mm=date[1];String dd=date[2]; obj.add(dd+"-"+mm+"-"+yyyy); PreparedStatement ps=con.prepareStatement(getDonor); ps.setString(1, rs.getString(1) ); ResultSet rs1=ps.executeQuery(); rs1.next(); obj.add(rs1.getString(1)); obj.add(rs1.getString(2)); obj.add(rs1.getString(3)); res.add(obj); } } catch(Exception e) { System.out.println("donationList "+e); } return res; } public ArrayList<String> requestDetails(int id) { ArrayList<String> res=new ArrayList<String>(); String getRequest="select type_of_request , total_quantity , balance_quantity , measurements , expected_date , request_details from request where id = ? and status = ? "; try { Connection con=DBConnection.getConnection(); PreparedStatement pstmt=con.prepareStatement(getRequest); pstmt.setInt(1, id); pstmt.setString(2,"waiting"); ResultSet rs=pstmt.executeQuery(); rs.next(); res.add(rs.getString(1)); res.add(String.valueOf(rs.getInt(2))+" "+rs.getString(4)); res.add(String.valueOf(rs.getInt(3))+" "+rs.getString(4)); String date[]=String.valueOf(rs.getDate(5)).split("-"); String yyyy=date[0];String mm=date[1];String dd=date[2]; res.add(dd+"-"+mm+"-"+yyyy); res.add(rs.getString(6)); } catch(Exception e) { System.out.println("requestDetails "+e); } return res; } public ArrayList<String> requestDescription(int id) { ArrayList<String> res=new ArrayList<String>(); String getRequest="select type_of_request , total_quantity , balance_quantity , measurements , expected_date , request_details from request where id = ? and status = ? "; try { Connection con=DBConnection.getConnection(); PreparedStatement pstmt=con.prepareStatement(getRequest); pstmt.setInt(1, id); pstmt.setString(2,"Accepted"); ResultSet rs=pstmt.executeQuery(); rs.next(); res.add(rs.getString(1)); res.add(String.valueOf(rs.getInt(2))+" "+rs.getString(4)); res.add(String.valueOf(rs.getInt(3))+" "+rs.getString(4)); String date[]=String.valueOf(rs.getDate(5)).split("-"); String yyyy=date[0];String mm=date[1];String dd=date[2]; res.add(dd+"-"+mm+"-"+yyyy); res.add(rs.getString(6)); } catch(Exception e) { System.out.println("requestDescription "+e); } return res; } public boolean checkLogin(String mailid,String password,String user) { try { Connection con=DBConnection.getConnection(); PreparedStatement pstmt=con.prepareStatement(checklogin); pstmt.setString(1, mailid); pstmt.setString(2, password); ResultSet rs=pstmt.executeQuery(); if(rs.next()) { if(rs.getString("type_of_user").equals(user)) return true; } return false; } catch(Exception e) { System.out.println("checkLogin"+e); } return false; } public ArrayList<ArrayList<String>> ngoHistory(String mailid) { ArrayList<ArrayList<String>> ans=new ArrayList<ArrayList<String>>(); try { Connection con=DBConnection.getConnection(); String query1="SELECT id,type_of_request,total_quantity,measurements FROM `request` WHERE ngo_email=?"; PreparedStatement pstmt=con.prepareStatement(query1); pstmt.setString(1, mailid); System.out.println("1"); ResultSet rs=pstmt.executeQuery(); while(rs.next()) { ArrayList<String> temp=new ArrayList<String>(); String query2="SELECT donor_email,donated_quantity FROM `donation` WHERE donation_id=?"; pstmt=con.prepareStatement(query2); pstmt.setInt(1,rs.getInt("id")); System.out.println("2"); ResultSet rs1=pstmt.executeQuery(); while(rs1.next()) { temp.add(rs.getString("type_of_request")); temp.add(rs.getInt("total_quantity")+" "+rs.getString("measurements")); temp.add(rs1.getInt("donated_quantity")+" "+rs.getString("measurements")); String query3="SELECT Name,Mobile_Number FROM `donor` WHERE User_email=?"; pstmt=con.prepareStatement(query3); pstmt.setString(1,rs1.getString("donor_email")); System.out.println("3"); ResultSet rs2=pstmt.executeQuery(); if(rs2.next()) { temp.add(rs2.getString("Name")); temp.add(rs1.getString("donor_email")); temp.add(rs2.getString("Mobile_Number")); } } for(String i:temp) { System.out.println(i); } System.out.println(temp.size()); if(temp.size()==0) continue; ans.add(temp); } } catch(Exception e) { System.out.println("ngoHistory "+e); } return ans; } public ArrayList<ArrayList<String>> receivedDonation(String mailid) { ArrayList<ArrayList<String>> ans=new ArrayList<ArrayList<String>>(); try { Connection con=DBConnection.getConnection(); String query1="SELECT donor_email,donation_id,donated_quantity,measurements,donated_date,id FROM `donation` WHERE ngo_email=? and status='waiting'"; PreparedStatement pstmt=con.prepareStatement(query1); pstmt.setString(1, mailid); ResultSet rs=pstmt.executeQuery(); while(rs.next()) { ArrayList<String> temp=new ArrayList<String>(); String query2="SELECT type_of_request,total_quantity FROM `request` WHERE id=?"; pstmt=con.prepareStatement(query2); System.out.println(rs.getInt("donation_id")); pstmt.setInt(1,rs.getInt("donation_id")); ResultSet rs1=pstmt.executeQuery(); rs1.next(); String query3="SELECT Name,Address,Mobile_Number FROM `donor` WHERE User_email=?"; pstmt=con.prepareStatement(query3); pstmt.setString(1, rs.getString("donor_email")); ResultSet rs2=pstmt.executeQuery(); rs2.next(); temp.add(rs1.getString("type_of_request")); temp.add(rs1.getString("total_quantity")+" "+rs.getString("measurements")); temp.add(rs.getString("donated_quantity")+" "+rs.getString("measurements")); temp.add(rs.getString("donated_date")); temp.add(rs.getString("donor_email")); temp.add(rs2.getString("Name")); temp.add(rs2.getString("Mobile_Number")); temp.add(rs.getInt("id")+""); for(String i:temp) System.out.println(i); ans.add(temp); } } catch(Exception e) { System.out.println("receivedDonation "+e); } return ans; } public void acceptedDonation(int id,int donatedquantity) { try { String query="Update donation set status='received' where id=?"; Connection con=DBConnection.getConnection(); PreparedStatement pstmt=con.prepareStatement(query); pstmt.setInt(1, id); pstmt.executeUpdate(); String query0="select donation_id from donation where id=?"; pstmt=con.prepareStatement(query0); pstmt.setInt(1, id); ResultSet rs0=pstmt.executeQuery(); rs0.next(); int donationid=rs0.getInt("donation_id"); String query1="select balance_quantity from request where id = ?"; pstmt=con.prepareStatement(query1); pstmt.setInt(1, donationid); ResultSet rs=pstmt.executeQuery(); rs.next(); int balance=rs.getInt(1)-donatedquantity; System.out.println(rs.getInt(1)+" "+donatedquantity+" "+balance); if(balance<=0) { String query2="Update request set status = 'Accepted',balance_quantity = ? where id = ?"; pstmt=con.prepareStatement(query2); pstmt.setInt(1, 0); pstmt.setInt(2, donationid); pstmt.executeUpdate(); } else { String query2="Update request set balance_quantity = ? where id = ?"; pstmt=con.prepareStatement(query2); pstmt.setInt(1, balance); pstmt.setInt(2, donationid); pstmt.executeUpdate(); } } catch(Exception e) { System.out.println("acceptedDonation "+e); } } }
package core.java.lab3; import java.util.Scanner; public class ModifyNumber { public static void main(String[] args) { // TODO Auto-generated method stub int num = 0; System.out.println(ModifyNumber.modifyNumber(num)); } public static int modifyNumber(int num) { Scanner sc = new Scanner(System.in); System.out.println("Enter a value :"); int num1 = sc.nextInt(); int min = 9, max = 0, digit, diff; while (num1 > 0) { digit = num1 % 10; num1 = num1 / 10; } diff = max - min; System.out.println("Diff b/w consecutive numbers Digit : " + diff); return num1; } }
package org.tosch.neverrest; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import java.net.InetSocketAddress; public class BaseElasticsearchConfig { @Value("${elasticsearch.cluster.nodes}") private String[] nodes; @Value("${elasticsearch.cluster.name}") private String clusterName; @Bean public Client client() { Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName).build(); TransportClient transportClient = TransportClient.builder().settings(settings).build(); for (String node : nodes) { String[] nodeParts = node.split(":"); String host = nodeParts[0]; int port = Integer.valueOf(nodeParts[1]); InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port); TransportAddress transportAddress = new InetSocketTransportAddress(inetSocketAddress); transportClient.addTransportAddress(transportAddress); } transportClient.connectedNodes(); return transportClient; } }
package com.oasisfeng.island.installer; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PermissionInfo; import android.os.Process; import android.text.TextUtils; import android.util.Log; import com.oasisfeng.android.base.Versions; import com.oasisfeng.android.content.IntentCompat; import com.oasisfeng.android.util.Apps; import com.oasisfeng.island.notification.NotificationIds; import java.util.ArrayList; import java.util.List; import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; import static android.content.Intent.EXTRA_USER; import static android.content.pm.PackageManager.GET_PERMISSIONS; import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.M; /** * Show helper notification about newly installed app. * * Created by Oasis on 2018-11-16. */ class AppInstallationNotifier { static void onPackageInstalled(final Context context, final String caller_pkg, final CharSequence caller_app_label, final String pkg) { final PackageManager pm = context.getPackageManager(); PackageInfo installed_pkg_info = null; if (pkg != null) try { installed_pkg_info = pm.getPackageInfo(pkg, GET_UNINSTALLED_PACKAGES | GET_PERMISSIONS); } catch (final PackageManager.NameNotFoundException ignored) {} if (installed_pkg_info == null) { Log.e(TAG, "Unknown installed package: " + pkg); return; } final boolean is_update = installed_pkg_info.lastUpdateTime != installed_pkg_info.firstInstallTime, is_self_update = pkg.equals(caller_pkg); final String title = context.getString(! is_update ? R.string.notification_caller_installed_app : is_self_update ? R.string.notification_caller_updated_self : R.string.notification_caller_updated_app, caller_app_label, is_self_update ? null/* unused */ : Apps.of(context).getAppName(pkg)); final int target_api = installed_pkg_info.applicationInfo.targetSdkVersion; List<CharSequence> dangerous_permissions = null; if (! is_update && SDK_INT >= M && target_api < M && installed_pkg_info.requestedPermissions != null) { dangerous_permissions = new ArrayList<>(); for (final String requested_permission : installed_pkg_info.requestedPermissions) try { final PermissionInfo permission_info = pm.getPermissionInfo(requested_permission, 0); if ((permission_info.protectionLevel & PermissionInfo.PROTECTION_DANGEROUS) != 0) dangerous_permissions.add(permission_info.loadLabel(pm)); } catch (final PackageManager.NameNotFoundException ignored) {} } String big_text = null; final String target_version = Versions.getAndroidVersionNumber(target_api); final String text = dangerous_permissions == null ? context.getString(R.string.notification_app_target_api, target_version) : dangerous_permissions.isEmpty() ? context.getString(R.string.notification_app_target_pre_m_wo_sensitive_permissions, target_version) : (big_text = context.getString(R.string.notification_app_with_permissions, TextUtils.join(", ", dangerous_permissions))); final Intent app_info_forwarder = new Intent(IntentCompat.ACTION_SHOW_APP_INFO).setClass(context, AppInfoForwarderActivity.class) .putExtra(IntentCompat.EXTRA_PACKAGE_NAME, pkg).putExtra(EXTRA_USER, Process.myUserHandle()); final PendingIntent app_info = PendingIntent.getActivity(context, 0, app_info_forwarder, FLAG_UPDATE_CURRENT); NotificationIds.AppInstallation.post(context, pkg, new Notification.Builder(context) .setSmallIcon(R.drawable.ic_landscape_black_24dp).setColor(context.getResources().getColor(R.color.accent)) .setContentTitle(title).setContentText(text).setStyle(big_text != null ? new Notification.BigTextStyle().bigText(big_text) : null) .setContentIntent(app_info).addAction(R.drawable.ic_settings_applications_white_24dp, context.getString(R.string.action_show_app_settings), app_info)); } private static final String TAG = "Island.AIN"; }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package paquete2; import paquete1.Persona; /** * * @author reroes */ public class Prestamo extends Persona { private Persona beneficiario ; private double tiempoP; private String ciudad; public Prestamo(String nom, String ap,double temp, String ciu){ super(nom, ap); tiempoP=temp; ciudad=ciu; } public void establecerBenefi ( Persona b){ beneficiario = b; } public void establecerTiempo ( double t){ tiempoP = t; } public void establecerCiudad ( String c){ ciudad = c; } public Persona obtenerBenefi (){ return beneficiario; } public double obtenerTiempo (){ return tiempoP; } public String obtenerCiudad (){ return ciudad; } }
package Algorithm; import Algorithm.Algebra.*; import Algorithm.Arithemic.FractionQuestion; import Algorithm.Arithemic.Percentage; import Algorithm.Arithemic.RepeatedDecimal; import Algorithm.Arithemic.Subtraction; public abstract class MyAlgorithm { private static final int SUBTRACTION_WEIGHT = 0; private static final int PERCENTAGE_WEIGHT = 0; private static final int FRACTION_WEIGHT = 0; private static final int SOLVEXSIMPLE_WEIGHT = 2; private static final int SOLVE_X_INTER_WEIGHT = 3; private static final int SOLVE_RECP_X_WEIGHT = 1; private static final int SOLVE_Y_INTERCEPT = 3; private static final int SOLVE_CONSECUTIVE = 2; private static final int CONVERT_TO_FRACTION = 2; private static final double TOTAL_WEIGHT = SUBTRACTION_WEIGHT + PERCENTAGE_WEIGHT + FRACTION_WEIGHT + SOLVEXSIMPLE_WEIGHT + SOLVE_X_INTER_WEIGHT + SOLVE_RECP_X_WEIGHT + SOLVE_Y_INTERCEPT + SOLVE_CONSECUTIVE + CONVERT_TO_FRACTION; private static double subtractRatio = SUBTRACTION_WEIGHT / TOTAL_WEIGHT; private static double percentRatio = PERCENTAGE_WEIGHT / TOTAL_WEIGHT + subtractRatio; private static double fractionRatio = FRACTION_WEIGHT / TOTAL_WEIGHT + percentRatio; private static double solveXSimpleRatio = SOLVEXSIMPLE_WEIGHT / TOTAL_WEIGHT + fractionRatio; private static double solveXInterRatio = SOLVE_X_INTER_WEIGHT / TOTAL_WEIGHT + solveXSimpleRatio; private static double solveXRecpRatio = SOLVE_RECP_X_WEIGHT / TOTAL_WEIGHT + solveXInterRatio; private static double solveYInRatio = SOLVE_Y_INTERCEPT / TOTAL_WEIGHT + solveXRecpRatio; private static double solveConsecRatio = SOLVE_CONSECUTIVE / TOTAL_WEIGHT + solveYInRatio; private static double convertFracRatio = CONVERT_TO_FRACTION / TOTAL_WEIGHT + solveConsecRatio; private String question = ""; private double ans = 0; private QuestionState qState = QuestionState.NORMAL; static { System.out.println("subtractRatio: " + subtractRatio); System.out.println("percentRatio: " + percentRatio); System.out.println("fractionRatio: " + fractionRatio); System.out.println("solveXSimpleRatio: " + solveXSimpleRatio); System.out.println("solveXInterRatio: " + solveXInterRatio); System.out.println("solveXRecpRatio: " + solveXRecpRatio); System.out.println("solveYIntercept: " + solveYInRatio); System.out.println("solveConsecRatio: " + solveConsecRatio); System.out.println("convertFracRatio: " + convertFracRatio); } public MyAlgorithm() { } protected void setParameter(String question, double answer) { this.question = question; this.ans = answer; } protected void setQuestionState(QuestionState state) { qState = state; } public QuestionState getState() { return qState; } public void clearPercentState() { qState = QuestionState.NORMAL; } public double getAnswer() { return ans; } public String getQuestion() { return question; } public boolean checkAnswer(double inputAnswer) { return Math.abs(ans - inputAnswer) < 0.05; } public static MyAlgorithm instantiateQuestion() { double randQuestion = Math.random(); if (randQuestion <= subtractRatio) { return new Subtraction(); } else if (randQuestion <= percentRatio) { return new Percentage(); } else if (randQuestion <= fractionRatio) { return new FractionQuestion(); } else if (randQuestion <= solveXSimpleRatio) { return new SolveXSimple(); } else if (randQuestion <= solveXInterRatio) { return new SolveXIntermediate(); } else if (randQuestion <= solveXRecpRatio) { return new SolveReciprocateX(); } else if (randQuestion <= solveYInRatio) { return new StraightLineGraph(); } else if (randQuestion <= solveConsecRatio) { return new SumConsecutive(); } else if (randQuestion <= convertFracRatio) { return new RepeatedDecimal(); } else { return new Percentage(); } } public abstract String generateQuestion(int max); public abstract String toLatexFormat(); public abstract String getAnswerLatex(); }
package day30WrapperClassArrayList; import java.util.ArrayList; import java.util.Collections; public class ArrayListPractice5 { public static void main(String[] args) { ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<31;i++) { if(i%2==0) { list.add(i); } }System.out.println(list); System.out.println(list.size()); for(int i=0;i<list.size();i++) { System.out.print(list.get(i)+" "); } System.out.println(); //for each method for(Integer each:list) { System.out.print(each+ " "); } System.out.println(); // for(Integer each:list) {//same result/unboxing // System.out.print(each+ " "); // } // //task int num=list.get(7);//unboxing // == integer System.out.println(num); // list.clear();// size of the list becomes=0 System.out.println(list.get(2));//gives error //Collections: sorting the ArrayList Collections.sort(list); System.out.println(list); ArrayList<Integer> list1=new ArrayList<>(); for(int i=20;i>=0;i--) { list1.add(i); }System.out.println(list1); Collections.sort(list1); System.out.println(list1); //collections is a class } }
package com.tencent.mm.plugin.expt.roomexpt; import android.view.View; import android.view.View.OnClickListener; import android.widget.Toast; class RoomExptDebugUI$4 implements OnClickListener { final /* synthetic */ RoomExptDebugUI iIF; RoomExptDebugUI$4(RoomExptDebugUI roomExptDebugUI) { this.iIF = roomExptDebugUI; } public final void onClick(View view) { a.aIx().aIA(); RoomExptDebugUI.d(this.iIF).clear(); Toast.makeText(this.iIF, "del db finish", 0).show(); } }
package chapter_3; /*A basic program to store the ID and name for an Employee and display those value to the console*/ public class Employee { private int id ; private String name ; Employee() // Default Constructor. { id=0 ; name="NULL" ; } Employee(int id, String name) // Parameterized Constructor takes int and String as argument. { this.id=id ; this.name=name ; } public void disp() // Display function to display the values { System.out.println("Details of the Employee"); System.out.println("ID: "+id); System.out.println("Name "+name); } public static void main(String[] args) { Employee obj1 =new Employee() ; // Default Constructor invoked when object is initialized Employee obj2=new Employee(3865,"Ashish") ; // Parameterized Constructor invoked when object is initialized obj1.disp(); obj2.disp(); } }
package com.tencent.mm.ui.base; class HorizontalListView$2 implements Runnable { final /* synthetic */ HorizontalListView tsN; HorizontalListView$2(HorizontalListView horizontalListView) { this.tsN = horizontalListView; } public final void run() { this.tsN.requestLayout(); } }
package com.gligor.hypnosis.repositories; import com.gligor.hypnosis.entities.TroupeDescription; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface TroupeDescRepository extends JpaRepository<TroupeDescription, Integer> { public TroupeDescription findById(int id); }
package JavaSE.OO.changyonglei; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /* * 获取自1970年1月1日 00分00秒000毫秒到当前的毫秒数 * 1000毫秒 = 1秒 * * Date d=new Date();获取系统当前时间 * Date d=new Date(long millis); * * 日历 */ public class DateTest { public static void main(String[] args) throws ParseException { long now = System.currentTimeMillis(); System.out.println(now); //获取系统当前时间 Date nowTime=new Date(); //java.util.Date;以及重写了Object中的toString方法 System.out.println(nowTime);//Fri Feb 14 15:12:52 CST 2020 //引入"格式化"日期 //java.util.Date;->String /*格式:y 年 M 月 d 日 H 小时 m 分 s 秒 S 毫秒 */ //创建日期格式化对象 SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss SSS"); //开始格式化(Date->String) String strTime=sdf.format(nowTime); System.out.println(strTime);//2020年02月14日 15:23:21 756 //获取特定的日期 String time = "2020年2月2日 20:20:20 200"; //将String日期转换成Date(String->Date) //创建日期格式化对象 SimpleDateFormat sd=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss SSS");//格式不能随意必须和上方字符串格式相同 //将字符串转换成日期类型 Date t=sd.parse(time);//报异常 System.out.println(t); Date t1=new Date(1000); //Date转换成String SimpleDateFormat s=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss SSS"); System.out.println(s.format(t1)); //获取系统当前时间的前十分钟时间 Date t2=new Date(System.currentTimeMillis()-1000*60*10); System.out.println(s.format(t2)); //日历 //获取系统当前日历 Calendar c=Calendar.getInstance(); //查看当前日历的星期几 int i=c.get(Calendar.DAY_OF_WEEK); System.out.println(i);//国外周日为第一天 //获取2008 8 8 是星期几 //获取2008年8月8日的日历 String st="2008,08,08"; Date d=new SimpleDateFormat("yyyy,MM,dd").parse(st);//有异常 //该日历就是2008 8 8的日历 c.setTime(d); //获取星期几 System.out.println(c.get(Calendar.DAY_OF_WEEK)); } }
// assignment 4 // pair 043 // Wright Steven // wrights // Wang Shiyu // shiyu import tester.*; class ExamplesIBook { ExamplesIBook() { } Book b0 = new Book("Java", "Steven", 0); Book b1 = new Book("Java", "Steven", 15); RefBook rb0 = new RefBook("Java for Dummies", 0); RefBook rb1 = new RefBook("Java for Dummies", 3); AudioBook ab0 = new AudioBook("AudioBook", "James", 0); AudioBook ab1 = new AudioBook("AudioBook", "James", 15); public boolean testDaysOverdue(Tester t) { ExamplesIBook eb = new ExamplesIBook(); return t.checkExpect(eb.b0.daysOverdue(17), 3) && t.checkExpect(eb.b1.daysOverdue(17), -12) && t.checkExpect(eb.rb0.daysOverdue(5), 3) && t.checkExpect(eb.rb1.daysOverdue(5), 0) && t.checkExpect(eb.ab0.daysOverdue(17), 3) && t.checkExpect(eb.ab1.daysOverdue(17), -12); } public boolean testIsOverdue(Tester t) { ExamplesIBook eb = new ExamplesIBook(); return t.checkExpect(eb.b0.isOverdue(17), true) && t.checkExpect(eb.b1.isOverdue(17), false) && t.checkExpect(eb.rb0.isOverdue(5), true) && t.checkExpect(eb.rb1.isOverdue(5), false) && t.checkExpect(eb.ab0.isOverdue(17), true) && t.checkExpect(eb.ab1.isOverdue(17), false); } public boolean testComputeFine(Tester t) { ExamplesIBook eb = new ExamplesIBook(); return t.checkExpect(eb.b0.computeFine(17), 30) && t.checkExpect(eb.b1.computeFine(17), 0) && t.checkExpect(eb.rb0.computeFine(5), 30) && t.checkExpect(eb.rb1.computeFine(5), 0) && t.checkExpect(eb.ab0.computeFine(17), 60) && t.checkExpect(eb.ab1.computeFine(17), 0); } }
package com.elvarg.world.model.movement.path; import com.elvarg.world.collision.region.RegionClipping; import com.elvarg.world.entity.impl.Character; import com.elvarg.world.model.Position; public class PathGenerator { public static final int[][] DIR = { { -1, 1 }, { 0, 1 }, { 1, 1 }, { -1, 0 }, { 1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 } }; public static final int[] NON_DIAGONAL_DIRECTIONS = { 1, 3, 4, 6 }; public static Position getCombatPath(Character character, Character following) { if(character == null || following == null) { return null; } int characterX = character.getPosition().getX(); int characterY = character.getPosition().getY(); int characterZ = character.getPosition().getZ(); int followX = following.getPosition().getX(); int followY = following.getPosition().getY(); double lowDist = 9999.0D; int lowX = 0; int lowY = 0; int x3 = followX; int y3 = followY - 1; int loop = following.getSize(); if (RS317PathFinder.accessable(followX, followY, characterZ, x3, y3) && isInteractionPathClear(x3, y3, characterZ, followX, followY)) { lowDist = getManhattanDistance(x3, y3, characterX, characterY); lowX = x3; lowY = y3; } for (int k = 0; k < 4; k++) { for (int i = 0; i < loop - (k == 0 ? 1 : 0); i++) { if (k == 0) { x3++; } else if (k == 1) { if (i == 0) { x3++; } y3++; } else if (k == 2) { if (i == 0) { y3++; } x3--; } else if (k == 3) { if (i == 0) { x3--; } y3--; } double d; if ((d = getManhattanDistance(x3, y3, characterX, characterY)) < lowDist) { if (RS317PathFinder.accessable(followX, followY, characterZ, x3, y3) && isInteractionPathClear(x3, y3, characterZ, followX, followY)) { lowDist = d; lowX = x3; lowY = y3; } } } } return new Position(lowX, lowY, character.getPosition().getZ()); } public static Position getBasicPath(Character character, Character following) { if(character == null || following == null) { return null; } int x = following.getPosition().getX(); int y = following.getPosition().getY(); int z = following.getPosition().getZ(); int[][] nodes = { { x + DIR[NON_DIAGONAL_DIRECTIONS[0]][0], y + DIR[NON_DIAGONAL_DIRECTIONS[0]][1] }, { x + DIR[NON_DIAGONAL_DIRECTIONS[1]][0], y + DIR[NON_DIAGONAL_DIRECTIONS[1]][1] }, { x + DIR[NON_DIAGONAL_DIRECTIONS[2]][0], y + DIR[NON_DIAGONAL_DIRECTIONS[2]][1] }, { x + DIR[NON_DIAGONAL_DIRECTIONS[3]][0], y + DIR[NON_DIAGONAL_DIRECTIONS[3]][1] } }; int bestX = 0; int bestY = 0; double bestDist = 99999.0D; for (int i = 0; i < nodes.length; i++) { if (isInteractionPathClear(nodes[i][0], nodes[i][1], z, x, y)) { double dist = Math.sqrt(Math.pow(character.getPosition().getX() - nodes[i][0], 2.0D) + Math.pow(character.getPosition().getY() - nodes[i][1], 2.0D)); RegionClipping reg = RegionClipping.forPosition(x, y); if(reg == null) { continue; } if ((dist < bestDist) && (reg.canMove(new Position(character.getPosition().getX(), character.getPosition().getY(), character.getPosition().getZ()), NON_DIAGONAL_DIRECTIONS[i]))) { bestDist = dist; bestX = nodes[i][0]; bestY = nodes[i][1]; } } } if (bestX == 0 && bestY == 0) { return null; } return new Position(bestX, bestY, z); } public static boolean isInteractionPathClear(final int x0, final int y0, final int characterZ, final int followX, final int followY) { int deltaX = followX - x0; int deltaY = followY - y0; double error = 0; final double deltaError = Math.abs((deltaY) / (deltaX == 0 ? ((double) deltaY) : ((double) deltaX))); int x = x0; int y = y0; int pX = x; int pY = y; boolean incrX = x0 < followX; boolean incrY = y0 < followY; if (!RS317PathFinder.accessable(x0, y0, characterZ, followX, followY)) { return false; } while (true) { if (x != followX) { x += (incrX ? 1 : -1); } if (y != followY) { error += deltaError; if (error >= 0.5) { y += (incrY ? 1 : -1); error -= 1; } } if(!RegionClipping.canProjectileMove(pX, pY, followX, followY, characterZ, 1, 1)) { return false; } if (incrX && incrY && x >= followX && y >= followY) { break; } else if (!incrX && !incrY && x <= followX && y <= followY) { break; } else if (!incrX && incrY && x <= followX && y >= followY) { break; } else if (incrX && !incrY && x >= followX && y <= followY) { break; } pX = x; pY = y; } return true; } /** * Gets Manhattan distance * * @param x * @param y * @param x2 * @param y2 * @return */ public static int getManhattanDistance(int x, int y, int x2, int y2) { return Math.abs(x - x2) + Math.abs(y - y2); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.cmsitems.attributeconverters; import de.hybris.platform.cms2.common.functions.Converter; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Objects; import static java.util.Date.from; import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.DATE_TIME_FORMAT; /** * Attribute Converter for {@link java.util.Date}. * Converts the Date to its proper {@link java.time.Instant} object and formats the date from {@link ZoneOffset#UTC} zone. */ public class DateDataToAttributeContentConverter implements Converter<String, Date> { private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT); @Override public Date convert(final String source) { if (Objects.isNull(source)) { return null; } return from(ZonedDateTime.parse(source, DATE_FORMATTER).toInstant()); } }
package com.ponthaitay.architecturecomponentsandroid2017.room; import android.annotation.SuppressLint; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.arch.persistence.room.Room; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import com.ponthaitay.architecturecomponentsandroid2017.BaseLifecycleActivity; import com.ponthaitay.architecturecomponentsandroid2017.R; import java.util.List; public class MainRoomActivity extends BaseLifecycleActivity { @SuppressLint("StaticFieldLeak") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_room); final AppDatabase db = Room.databaseBuilder(this, AppDatabase.class, "database-app").build(); final StudentEntity entity = new StudentEntity(); entity.setId(3); entity.setFirstName("Mr.Jedsada Tiwongvorakul"); entity.setLastName("POND"); final StudentViewModel studentViewModel = ViewModelProviders.of(this).get(StudentViewModel.class); studentViewModel.insertStudent(db.studentDao(), entity); studentViewModel.getStudentById(db.studentDao(), 3) .observe(this, new Observer<List<StudentEntity>>() { @Override public void onChanged(@Nullable List<StudentEntity> studentEntities) { if (!studentEntities.isEmpty()) { Log.e("POND", String.valueOf(studentEntities.get(0).getFirstName())); } else { Log.e("POND", "ERROR"); } } }); } }
/** * Copyright (c) 2016, 指端科技. */ package com.rofour.baseball.dao.manager.mapper; import java.util.Date; import java.util.List; import java.util.Map; import javax.inject.Named; import com.rofour.baseball.controller.model.RequestWorkSigninInfo; import com.rofour.baseball.dao.manager.bean.ProvinceBean; /** * @ClassName: ProvinceMapper * @Description: 省的sql语句映射类 * @author liujingbo * @date 2016年3月26日 下午9:29:52 * */ @Named("provinceMapper") public interface ProvinceMapper { /** * * @Description: 根据主键删除 * @param provinceId * @return 删除的数量 */ int deleteByPrimaryKey(Long provinceId); /** * * @Description: 增加 * @param record * @return int */ int insert(ProvinceBean record); /** * * @Description: 增加 * @param record * @return int */ int insertSelective(ProvinceBean record); /** * * @Description: 根据主键查询 * @param provinceId * @return ProvinceBean */ ProvinceBean selectByPrimaryKey(Long provinceId); /** * * @Description: 查询 所有 * @return List<ProvinceBean> */ List<ProvinceBean> selectAllProvince(); List<ProvinceBean> selectAllProvinceAndWorkSignin(Date date); /** * 查询所有的省,运力,分页 * @param requestWorkSigninInfo * @return */ List<ProvinceBean> selectAllProvinceAndWorkSigninPage(RequestWorkSigninInfo requestWorkSigninInfo); Long selectAllWorkSignin(Date date); /** * * @Description: 更新 * @param record * @return 更新的数量 */ int updateByPrimaryKeySelective(ProvinceBean record); /** * * @Description: 省份的名字是否重复 * @param map * @return 重复的数量 */ int isExistSameProvinceName(Map<Object,Object> map); /** * * @Description: 修改自己的时是否重复 * @param map * @return 重复的数量 */ int isExistSameProvinceNameItSelf(Map<Object,Object> map); /** * * @Description: 根据主键更新 * @param record * @return 更新的数量 */ int updateByPrimaryKey(ProvinceBean record); int getProvinceTotal(); /** * * @Description: 批量删除 * @param ids */ void batchDelete(List<Long> ids); }
package com.auction.dao.bids; import com.auction.dao.AbstractDao; import com.auction.entity.Bids; public class BidsDaoImpl extends AbstractDao<Integer,Bids> implements BidsDao { }
package jp.co.sakamoto.androidproject.domain.usecase; import javax.inject.Inject; import io.reactivex.Single; import io.reactivex.disposables.Disposable; import jp.co.sakamoto.androidproject.data.entity.User; import jp.co.sakamoto.androidproject.data.repository.IUserRepository; import jp.co.sakamoto.androidproject.definition.Message; import jp.co.sakamoto.androidproject.domain.model.LoginChallenge; import jp.co.sakamoto.androidproject.domain.model.LoginResult; public class LoginUser extends Usecase { private IUserRepository userRepository; @Inject public LoginUser(IUserRepository userRepository) { this.userRepository = userRepository; } public Single<LoginResult> login(LoginChallenge model) { return this.userRepository.login(model).flatMap(loginResult -> Single.create(emitter -> { if (loginResult.isSuccess()) { User user = new User(model.getUserId(), model.getPassword(), loginResult.getToken()); Disposable disposable = this.userRepository.saveUser(user).subscribe(saveUserResult -> { String result = saveUserResult.isSuccess() ? LoginResult.RESULT_OK : LoginResult.RESULT_NG; String message = saveUserResult.isSuccess() ? Message.LOGIN_SUCCESS : saveUserResult.getMessage(); String token = saveUserResult.isSuccess() ? loginResult.getToken() : null; emitter.onSuccess(LoginResult.newInstance(result, message, token)); }); this.subscriptions.add(disposable); } else { emitter.onSuccess(LoginResult.newInstance(loginResult.getResult(), loginResult.getMessage(), null)); } })); } }
package gr.athena.innovation.fagi.utils; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import com.vividsolutions.jts.io.WKTWriter; import gr.athena.innovation.fagi.core.action.EnumFusionAction; import gr.athena.innovation.fagi.core.function.geo.MinimumOrthodromicDistance; import gr.athena.innovation.fagi.core.normalizer.phone.PhoneNumberNormalizer; import gr.athena.innovation.fagi.core.similarity.JaroWinkler; import gr.athena.innovation.fagi.core.similarity.Levenshtein; import gr.athena.innovation.fagi.exception.ApplicationException; import gr.athena.innovation.fagi.exception.WrongInputException; import gr.athena.innovation.fagi.model.CustomRDFProperty; import gr.athena.innovation.fagi.model.Entity; import gr.athena.innovation.fagi.repository.SparqlRepository; import gr.athena.innovation.fagi.specification.Configuration; import gr.athena.innovation.fagi.specification.EnumOutputMode; import gr.athena.innovation.fagi.specification.Namespace; import gr.athena.innovation.fagi.specification.SpecificationConstants; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.jena.datatypes.RDFDatatype; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.apache.logging.log4j.LogManager; /** * Utilities for String/RDF manipulation. * * @author nkarag */ public class RDFUtils { private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger(RDFUtils.class); /** * Returns the alphanumeric ID of a URI resource as String. * * @param resourceString the resource string. * @return the ID string. */ public static String getIdFromResource(String resourceString) { //example //input: http://slipo.eu/id/poi/0d1bb367-f3a5-10c1-b33c-381ef1e2f041 //returns 0d1bb367-f3a5-10c1-b33c-381ef1e2f041 int startPosition = StringUtils.ordinalIndexOf(resourceString, "/", 5) + 1; String id = resourceString.subSequence(startPosition, resourceString.length()).toString(); return id; } /** * Returns the alphanumeric ID of a URI resource object. * * @param resource the resource. * @return the ID string. */ public static String getIdFromResource(Resource resource) { String resourceString = resource.toString(); int startPosition = StringUtils.ordinalIndexOf(resourceString, "/", 5) + 1; String id = resourceString.subSequence(startPosition, resourceString.length()).toString(); return id; } /** * Returns the alphanumeric ID of a URI resource-part as String. * Resource-part can be any string that comes from splitting a triple on white-space. * * @param resourcePart the resource part. * @return the ID as a string. */ public static String getIdFromResourcePart(String resourcePart) { //expects: <namespace:id> or <namespace:id/localname> int endPosition = StringUtils.lastIndexOf(resourcePart, "/"); int startPosition = StringUtils.ordinalIndexOf(resourcePart, "/", 5) + 1; String res; if(resourcePart.substring(startPosition).contains("/")){ res = resourcePart.subSequence(startPosition, endPosition).toString(); } else { res = resourcePart.subSequence(startPosition, resourcePart.length()-1).toString(); } return res; } /** * Returns the local-name of a custom RDF property. * @param property the property. * @return the local-name. */ public static String getLocalName(CustomRDFProperty property) { String localName; if(property.isSingleLevel()){ localName = SpecificationConstants.Mapping.PROPERTY_MAPPINGS.get(property.getValueProperty().toString()); } else { localName = SpecificationConstants.Mapping.PROPERTY_MAPPINGS.get(property.getParent().toString()); } if(localName == null){ LOG.warn("Failed to retrieve mapping with property " + property.getParent() + " " + property.getValueProperty()); //do not stop fusion due to this. Single level properties do not have localnames //throw new ApplicationException("Property mapping does not exist."); } return localName; } /** * Adds brackets to a String node. * @param node the node as a string. * @return the string node with brackets. */ public static String addBrackets(String node){ return "<" + node + ">"; } /** * Removes brackets of the given string node. * @param node the node as a string. * @return the string node without brackets. */ public static String removeBrackets(String node){ return node.substring(1, node.length()-1); } /** * This method basically removes the CRS prefix from a WKT Literal. * * @param wkt the literal that contains the geometry. * @return the WKT literal with the CRS prefix removed */ public static Literal extractGeometry(Literal wkt){ String lexicalForm = wkt.getLexicalForm(); RDFDatatype geometryDatatype = Namespace.WKT_RDF_DATATYPE; if(lexicalForm.startsWith(Namespace.CRS_4326)){ lexicalForm = lexicalForm.replaceAll(Namespace.CRS_4326, "").trim(); Literal wktLiteral = ResourceFactory.createTypedLiteral(lexicalForm, geometryDatatype); return wktLiteral; } else { return wkt; } } /** * Extracts a geometry from a WKT string by checking the CRS prefix. * * @param wkt the WKT. * @return the WKT without CRS prefix. */ public static String extractGeometry(String wkt){ if(wkt.startsWith(Namespace.CRS_4326)){ String targetWKT = wkt.replaceAll(Namespace.CRS_4326, "").trim(); return targetWKT; } else { return wkt; } } /** * Returns the root resource based on the fusion mode. * * @param leftNode the left node. * @param rightNode the right node. * @return the root resource. */ public static Resource getRootResource(Entity leftNode, Entity rightNode) { EnumOutputMode mode = Configuration.getInstance().getOutputMode(); switch (mode) { case AA_MODE: case AB_MODE: case A_MODE: case L_MODE: case DEFAULT: return SparqlRepository.getSubjectOfSingleProperty(Namespace.SOURCE_NO_BRACKETS, leftNode.getEntityData().getModel()); case BB_MODE: case BA_MODE: case B_MODE: return SparqlRepository.getSubjectOfSingleProperty(Namespace.SOURCE_NO_BRACKETS, rightNode.getEntityData().getModel()); default: LOG.fatal("Cannot resolved fused Entity's URI. Check Default fused output mode."); throw new IllegalArgumentException(); } } /** * Returns the resource based on the fusion mode and the given property. * * @param leftNode the left node. * @param rightNode the right node. * @param property the custom RDF property. * @return the resource. */ public static Resource resolveResource(Entity leftNode, Entity rightNode, CustomRDFProperty property) { EnumOutputMode mode = Configuration.getInstance().getOutputMode(); Resource resource; switch (mode) { case AA_MODE: case AB_MODE: case A_MODE: case L_MODE: case DEFAULT: { resource = SparqlRepository.getSubjectOfSingleProperty(Namespace.SOURCE_NO_BRACKETS, leftNode.getEntityData().getModel()); String localName = RDFUtils.getLocalName(property); if(localName == null){ //todo: Single level properties do not have localnames. Check if is single level and avoid null check return ResourceFactory.createResource(resource.toString()); } String resourceString = resource.toString() +"/"+ RDFUtils.getLocalName(property); return ResourceFactory.createResource(resourceString); } case BB_MODE: case BA_MODE: case B_MODE:{ resource = SparqlRepository.getSubjectOfSingleProperty(Namespace.SOURCE_NO_BRACKETS, rightNode.getEntityData().getModel()); String localName = RDFUtils.getLocalName(property); if(localName == null){ return ResourceFactory.createResource(resource.toString()); } String resourceString = resource.toString() +"/"+ RDFUtils.getLocalName(property); return ResourceFactory.createResource(resourceString); } default: LOG.fatal("Cannot resolved fused Entity's URI. Check Default fused output mode."); throw new IllegalArgumentException(); } } /** * Checks if the given model is rejected from a rule previously. * A rejected model is always empty, so this method simply checks the size of the model. * * @param model the model. * @return true if the model is rejected, else otherwise. */ public static boolean isRejectedByPreviousRule(Model model) { //the link has been rejectedFromRule (or rejectedFromRule and marked ambiguous) by previous rule. //TODO: if size is 1, maybe strict check if the triple contains the ambiguity return model.isEmpty() || model.size() == 1; } /** * Constructs a statement of an ambiguous link. * * @param uri1 the first URI. * @param uri2 the second URI. * @return the statement. */ public static Statement getAmbiguousLinkStatement(String uri1, String uri2) { Property ambiguousLink = ResourceFactory.createProperty(Namespace.LINKED_AMBIGUOUSLY); Resource resource1 = ResourceFactory.createResource(uri1); Resource resource2 = ResourceFactory.createResource(uri2); Statement statement = ResourceFactory.createStatement(resource1, ambiguousLink, resource2); return statement; } /** * Constructs a statement of an ambiguous property. * * @param uri the URI. * @param property the property. * @return the statement. */ public static Statement getAmbiguousPropertyStatement(String uri, Property property) { Property ambiguousProperty = ResourceFactory.createProperty(Namespace.HAS_AMBIGUOUS_PROPERTY); Resource resource = ResourceFactory.createResource(uri); Statement statement = ResourceFactory.createStatement(resource, ambiguousProperty, property); return statement; } /** * Constructs a statement of an ambiguous sub-property. * * @param uri the URI. * @param subProperty the sub-property. * @return the statement. */ public static Statement getAmbiguousSubPropertyStatement(String uri, Property subProperty) { Property ambiguousSubProperty = ResourceFactory.createProperty(Namespace.HAS_AMBIGUOUS_SUB_PROPERTY); Resource resource = ResourceFactory.createResource(uri); Statement statement = ResourceFactory.createStatement(resource, ambiguousSubProperty, subProperty); return statement; } /** * Renames an entity based of the URI of another, * * @param entityToBeRenamed the entity to be renamed. * @param entity the base entity. */ public static void renameResourceURIs(Entity entityToBeRenamed, Entity entity) { Model original = entityToBeRenamed.getEntityData().getModel(); Iterator<Statement> statementIterator = original.listStatements().toList().iterator(); Model newModel = ModelFactory.createDefaultModel(); while (statementIterator.hasNext()) { Statement statement = statementIterator.next(); String newSub = statement.getSubject().toString().replaceAll(entityToBeRenamed.getResourceURI(), entity.getResourceURI()); String newPred = statement.getPredicate().toString().replaceAll(entityToBeRenamed.getResourceURI(), entity.getResourceURI()); String newOb = statement.getObject().toString().replaceAll(entityToBeRenamed.getResourceURI(), entity.getResourceURI()); Resource subject = ResourceFactory.createResource(newSub); Property predicate = ResourceFactory.createProperty(newPred); RDFNode object; if(statement.getObject().isResource()){ object = ResourceFactory.createResource(newOb); } else if(statement.getObject().isLiteral()){ object = statement.getObject(); } else { object = statement.getObject(); } Statement newStatement = ResourceFactory.createStatement(subject, predicate, object); newModel.add(newStatement); } entityToBeRenamed.getEntityData().setModel(newModel); } /** * Parses a geometry from a string literal. * * @param literal the literal. * @return the geometry object. */ public static Geometry parseGeometry(String literal) { String literalWithoutCRS = literal.replace(Namespace.CRS_4326 + " ", ""); int sourceSRID = 4326; //All features assumed in WGS84 lon/lat coordinates GeometryFactory geomFactory = new GeometryFactory(new PrecisionModel(), sourceSRID); WKTReader wellKnownTextReader = new WKTReader(geomFactory); Geometry geometry = null; try { geometry = wellKnownTextReader.read(literalWithoutCRS); } catch (ParseException ex) { LOG.fatal("Error parsing geometry literal " + literalWithoutCRS); LOG.fatal(ex); } return geometry; } /** * Returns the RDF node of the given property in the model. * * @param property the property. * @param model the model. * @return the RDF node. */ public static RDFNode getRDFNode(String property, Model model) { Property propertyRDF = getRDFPropertyFromString(property); if (propertyRDF != null) { return SparqlRepository.getObjectOfProperty(propertyRDF, model); } else { LOG.warn("Could not find literal with property {}", property); throw new RuntimeException("cannot find object of " + property); } } /** * Returns the literal of the given property in the given model. * * @param property the property. * @param model the model. * @return the literal object. */ public static Literal getLiteralValue(String property, Model model) { Property propertyRDF = getRDFPropertyFromString(property); if (propertyRDF != null) { return SparqlRepository.getLiteralOfProperty(propertyRDF, model); } else { LOG.warn("Could not find literal with property {}", property); return ResourceFactory.createStringLiteral(""); } } /** * Constructs a property from a string using the resource factory. * @param property the property. * @return the property. */ public static Property getRDFPropertyFromString(String property) { if (StringUtils.isBlank(property)) { return null; } Property propertyRDF = ResourceFactory.createProperty(property); return propertyRDF; } /** * Constructs a custom RDF property based on the given string property. * * @param property the property. * @return the custom RDF property. */ public static CustomRDFProperty getCustomRDFPropertyFromString(String property) { if (StringUtils.isBlank(property)) { throw new IllegalArgumentException("Property string is empty or null."); } CustomRDFProperty customRDFProperty = new CustomRDFProperty(); if(property.contains(" ")){ String[] parts = property.split(" "); customRDFProperty.setSingleLevel(false); customRDFProperty.setParent(ResourceFactory.createProperty(parts[0])); customRDFProperty.setValueProperty(ResourceFactory.createProperty(parts[1])); } else { customRDFProperty.setSingleLevel(true); customRDFProperty.setValueProperty(ResourceFactory.createProperty(property)); } return customRDFProperty; } /** * Returns the literal of the given property chain in the model. * * @param property1 the parent property. * @param property2 the child property. * @param model the model. * @return the literal. */ public static Literal getLiteralValueFromChain(String property1, String property2, Model model) { if (property1 != null) { Literal literal = SparqlRepository.getLiteralFromPropertyChain(property1, property2, model, true); if(literal == null){ literal = SparqlRepository.getLiteralFromPropertyChain(property1, property2, model, false); } return literal; } else { LOG.warn("Could not find literal with properties {}", property1, property2); return ResourceFactory.createStringLiteral(""); } } /** * Returns the RDF node of the given property chain in the model. * * @param property1 the parent property. * @param property2 the child property. * @param model the model. * @return the RDF node. */ public static RDFNode getRDFNodeFromChain(String property1, String property2, Model model) { if (property1 != null) { RDFNode node = SparqlRepository.getObjectOfPropertyChain(property1, property2, model, true); if(node == null){ node = SparqlRepository.getObjectOfPropertyChain(property1, property2, model, false); } return node; } else { LOG.warn("Could not find literal with properties {}", property1, property2); throw new RuntimeException("cannot find object of " + property1 + " " + property2); } } /** * Returns the WKT literal given a geometry object. * * @param geometry the geometry object. * @return the WKT string. */ public static String getWKTLiteral(Geometry geometry) { WKTWriter wellKnownTextWriter = new WKTWriter(); String wktString = wellKnownTextWriter.write(geometry); return wktString; } /** * Checks if the property can be used for geometric fusion. * * @param property the property. * @param action the action. * @throws WrongInputException wrong input. */ public static void validateGeometryProperty(Property property, EnumFusionAction action) throws WrongInputException { if (!property.toString().equals(Namespace.WKT)) { LOG.error("The selected action " + action.toString() + " applies only for WKT geometry literals"); throw new WrongInputException("The selected action " + action.toString() + " applies only for WKT geometry literals"); } } /** * Checks if the property refers to WKT and throws exception if it does not. * * @param property the property. * @param action the action. * @throws WrongInputException wrong input. */ public static void validateActionForProperty(Property property, EnumFusionAction action) throws WrongInputException { if (property.toString().equals(Namespace.WKT)) { LOG.error("The selected action " + action.toString() + " does not apply on geometries."); throw new WrongInputException("The selected action " + action.toString() + " does not apply on geometries."); } } /** * Checks if the property refers to a name based on the SLIPO-ontology. * @param property the property. * @throws WrongInputException wrong input. */ public static void validateNameAction(CustomRDFProperty property) throws WrongInputException { if(property.isSingleLevel()){ if(!property.getValueProperty().toString().equals(Namespace.NAME_NO_BRACKETS)){ LOG.error("The \"keep-most-complete-name\" can be applied only on the name property."); throw new WrongInputException("The \"keep-most-complete-name\" can be applied only on the name property."); } } else { if(!property.getParent().toString().equals(Namespace.NAME_NO_BRACKETS)){ LOG.error("The \"keep-most-complete-name\" can be applied only on the name property."); throw new WrongInputException("The \"keep-most-complete-name\" can be applied only on the name property."); } } } /** * Returns the statement of the interlinking score. * * @param uri the URI. * @param score the score. * @param modelA the model of A. * @param modelB the model of B. * @return the statement. */ public static Statement getInterlinkingScore(String uri, float score, Model modelA, Model modelB) { Resource resource = ResourceFactory.createResource(uri); Property scoreProperty = ResourceFactory.createProperty(Namespace.INTERLINKING_SCORE); Literal scoreA = SparqlRepository.getPreviousScore(modelA, scoreProperty); Literal scoreB = SparqlRepository.getPreviousScore(modelB, scoreProperty); Literal scoreLiteral = constructScoreLiteral(scoreA, scoreB, score); Statement statement = ResourceFactory.createStatement(resource, scoreProperty , scoreLiteral); return statement; } /** * Returns a string that denotes a fusion value for unlinked URI nodes. * @param uri the URI. * @return the unlinked flag. */ public static String getUnlinkedFlag(String uri) { String flag = uri + " " + Namespace.FUSION_GAIN + Namespace.ORIGINAL_LITERAL; return flag; } /** * Returns the fusion confidence statement. * * @param fusedUri the URI. * @param modelA the model of A. * @param modelB the model of B. * @param fusedModel the fused model. * @return the statement. */ public static Statement getFusionConfidenceStatement(String fusedUri, Model modelA, Model modelB, Model fusedModel) { Resource fusedRes = ResourceFactory.createResource(fusedUri); Property confidenceProperty = ResourceFactory.createProperty(Namespace.FUSION_CONFIDENCE_NO_BRACKETS); Double conf = computeFusionConfidence(modelA, modelB); Literal confidenceLiteral = ResourceFactory.createTypedLiteral(conf.floatValue()); Statement statement = ResourceFactory.createStatement(fusedRes, confidenceProperty , confidenceLiteral); return statement; } /** * Computes the fusion confidence. * * @param modelA the model of A. * @param modelB the model of B. * @return the fusion confidence score. */ public static Double computeFusionConfidence(Model modelA, Model modelB){ List<Double> sims = new ArrayList<>(); Double nameSimilarity = computeNameSimilarity(modelA, modelB); Double phoneSimilarity = computePhoneSimilarity(modelA, modelB); Double streetSimilarity = computeAddressStreetSimilarity(modelA, modelB); Double geoSimilarity = computeGeoSimilarity(modelA, modelB); if(nameSimilarity != null){ sims.add(nameSimilarity); } if(streetSimilarity != null){ sims.add(streetSimilarity); } if(phoneSimilarity != null){ sims.add(phoneSimilarity); } if(geoSimilarity != null){ sims.add(geoSimilarity); } double sum = sims.stream().mapToDouble(Double::doubleValue).sum(); Double confidence = sum / (double) sims.size(); return confidence; } /** * Returns the fusion-gain statement. * * @param fusedUri the URI. * @param nodeA the left node. * @param nodeB the right node. * @param modelA the left model. * @param modelB the right model. * @param fusedModel the fused model. * @return the statement. */ public static Statement getFusionGainStatement(String fusedUri, String nodeA, String nodeB, Model modelA, Model modelB, Model fusedModel) { //get previous score if exists. Append new score Resource resA = ResourceFactory.createResource(nodeA); Resource resB = ResourceFactory.createResource(nodeB); Resource fusedRes = ResourceFactory.createResource(fusedUri); float fusionGain = computeFusionGain(fusedRes, resA, resB, modelA, modelB, fusedModel); Property scoreProperty = ResourceFactory.createProperty(Namespace.FUSION_GAIN_NO_BRACKETS); Literal scoreA = SparqlRepository.getPreviousScore(modelA, scoreProperty); Literal scoreB = SparqlRepository.getPreviousScore(modelB, scoreProperty); Literal gainLiteral = constructScoreLiteral(scoreA, scoreB, fusionGain); Statement statement = ResourceFactory.createStatement(fusedRes, scoreProperty , gainLiteral); return statement; } /** * Computes the fusion-gain score. * * @param fusedUri the fused URI. * @param nodeA the left node. * @param nodeB the right node. * @param modelA the left model. * @param modelB the right model. * @param fusedModel the fused model. * @return the fusion-gain score. */ public static float computeFusionGain(Resource fusedUri, Resource nodeA, Resource nodeB, Model modelA, Model modelB, Model fusedModel) { Set<Property> propsA = SparqlRepository.getDistinctPropertiesOfResource(modelA, nodeA); Set<Property> propsB = SparqlRepository.getDistinctPropertiesOfResource(modelB, nodeB); Set<Property> fusedProps = SparqlRepository.getDistinctPropertiesOfResource(fusedModel, fusedUri); Collection common = CollectionUtils.intersection(propsA, propsB); if(propsA.isEmpty() && propsB.isEmpty()){ return 0f; } Double score = (fusedProps.size() - common.size())/ (double)(propsA.size() + propsB.size()); return score.floatValue(); } /** * Returns the last computed fusion-gain score from the given literal. * Example of fusion gain literal:{scoreA: 1.0, scoreB: 1.0, score: 0.11111111}" * * @param literal the literal. * @return the score. */ public static Double getLastFusionGainFromLiteral(Literal literal) { String value = literal.getString(); int startIndex = value.lastIndexOf(' '); int endIndex = value.lastIndexOf('}'); if(startIndex == -1 || endIndex == -1){ LOG.warn("cannot parse fusion gain from: " + literal); throw new ApplicationException("cannot parse fusion gain from: " + literal); } String gainString = value.substring(startIndex, endIndex); Double gain = Double.parseDouble(gainString); return gain; } /** * Constructs an intermediate node for POI ensemble fusion. * * @param resourceURI the resource URI. * @param localName the local-name. * @param i an integer value to construct different nodes for same properties. * @return the intermediate node as a string. */ public static String constructIntermediateEnsembleNode(Resource resourceURI, String localName, int i) { String uri = resourceURI + "/" + localName + "_" + i; return uri; } public static Set<CustomRDFProperty> convertToCustomRDFProperty(Set<String> properties) { Set<CustomRDFProperty> props = new HashSet<>(); for(String prop : properties){ CustomRDFProperty customProp = getCustomRDFPropertyFromString(prop); props.add(customProp); } return props; } private static Literal constructScoreLiteral(Literal scoreA, Literal scoreB, float score) { String a; String b; if(scoreA == null){ a = "1.0"; } else { a = scoreA.toString(); } if(scoreB == null){ b = "1.0"; } else { b = scoreB.toString(); } String scoreString = "{scoreA: " + a + ", scoreB: " + b + ", score: " + score + "}"; return ResourceFactory.createTypedLiteral(scoreString); } private static Double computeNameSimilarity(Model modelA, Model modelB) { List<String> namesA = SparqlRepository.getLiteralStringsFromPropertyChain(Namespace.NAME_NO_BRACKETS, Namespace.NAME_VALUE_NO_BRACKETS, modelA); List<String> namesB = SparqlRepository.getLiteralStringsFromPropertyChain(Namespace.NAME_NO_BRACKETS, Namespace.NAME_VALUE_NO_BRACKETS, modelB); if(namesA.isEmpty() || namesB.isEmpty()){ return null; } double maxSimilarity = 0; for (String stringA : namesA ) { for (String stringB : namesB) { double tempSimilarity = JaroWinkler.computeSimilarity(stringA, stringB); if(tempSimilarity > maxSimilarity){ maxSimilarity = tempSimilarity; } } } return maxSimilarity; } private static Double computePhoneSimilarity(Model modelA, Model modelB) { Literal phoneA = SparqlRepository.getLiteralFromPropertyChain(Namespace.PHONE_NO_BRACKETS, Namespace.CONTACT_VALUE_NO_BRACKETS, modelA); Literal phoneB = SparqlRepository.getLiteralFromPropertyChain(Namespace.PHONE_NO_BRACKETS, Namespace.CONTACT_VALUE_NO_BRACKETS, modelB); if(phoneA == null || phoneB == null){ return null; } String a = PhoneNumberNormalizer.removeNonNumericCharacters(phoneA.getLexicalForm()); String b = PhoneNumberNormalizer.removeNonNumericCharacters(phoneB.getLexicalForm()); return Levenshtein.computeSimilarity(a, b, null); } private static Double computeAddressStreetSimilarity(Model modelA, Model modelB) { Literal streetA = SparqlRepository.getLiteralFromPropertyChain(Namespace.ADDRESS_NO_BRACKETS, Namespace.STREET_NO_BRACKETS, modelA); Literal streetB = SparqlRepository.getLiteralFromPropertyChain(Namespace.ADDRESS_NO_BRACKETS, Namespace.STREET_NO_BRACKETS, modelB); if(streetA == null || streetB == null){ return null; } return JaroWinkler.computeSimilarity(streetA.toString(), streetB.toString()); } private static Double computeGeoSimilarity(Model modelA, Model modelB) { Literal geoA = SparqlRepository.getLiteralFromPropertyChain(Namespace.GEOSPARQL_HAS_GEOMETRY, Namespace.WKT, modelA); Literal geoB = SparqlRepository.getLiteralFromPropertyChain(Namespace.GEOSPARQL_HAS_GEOMETRY, Namespace.WKT, modelB); if(geoA == null || geoB == null){ return null; } Double distance = MinimumOrthodromicDistance.compute(geoA, geoB); if(distance == null){ return 0.0; } //arbitrary value for normalizing to a similarity. Distance greater than 300 meters is considered as 0 similarity. if(distance > 300){ return 0.0; } else { return 1 - (distance / (double) 300); } } }
import java.awt.*; import java.util.ArrayList; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO;; import java.io.File; import java.io.FileReader; import java.util.Collections; import java.util.Map; import java.util.Set; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class Route { private int[] im; private LinkedList list; private ArrayList<ArrayList<Integer>> used; private int floor; private JSONObject file; private BufferedImage bi; private String imageName; private String room; public Route(String img, String file, int floor, String room){ JSONParser jsonParser = new JSONParser(); this.imageName = img; this.room = room; try { this.bi = ImageIO.read((new File(img))); } catch (IOException e) { System.out.println("Image " + img + " couldn't be open!"); } this.im = this.bi.getRGB(0,0, this.bi.getWidth(), this.bi.getHeight(), null, 0,this.bi.getWidth()); try (FileReader reader = new FileReader(file)) { Object obj = jsonParser.parse(reader); JSONArray array = new JSONArray(); array.add(obj); JSONObject da = new JSONObject((Map) array.get(0)); this.file = new JSONObject ((Map) da.get(Integer.toString(floor))); } catch (Exception e) { e.printStackTrace(); } this.floor = floor; this.used = new ArrayList<>(); this.list = new LinkedList(); } private int doorPixel(String room, String key){ JSONObject r = new JSONObject ((Map) this.file.get(room)); JSONArray rooms = (JSONArray) r.get(key); JSONObject h = new JSONObject ((Map) this.file.get("hall")); JSONArray hall = (JSONArray) h.get(key); for (int i = 0; i < rooms.size(); i++){ JSONArray lis = (JSONArray) rooms.get(i); for (int j = 0; j < hall.size(); j++){ JSONArray lists = (JSONArray) hall.get(j); int first = Integer.parseInt(String.valueOf(lis.get(0))); int second = Integer.parseInt(String.valueOf(lists.get(1))); if(Math.abs(first - second) < 20){ return second; } first = Integer.parseInt(String.valueOf(lists.get(0))); second = Integer.parseInt(String.valueOf(lis.get(1))); if(Math.abs(first - second) < 20){ return first; } } } return -1; } private int doorPixelParallel(String room, String keyR, String keyH){ JSONObject r = new JSONObject ((Map) this.file.get(room)); JSONArray rooms = (JSONArray) r.get(keyR); JSONArray lis = (JSONArray) rooms.get(rooms.size() - 1); JSONObject h = new JSONObject ((Map) this.file.get("hall")); JSONArray hall = (JSONArray) h.get(keyH); JSONArray lists = (JSONArray) rooms.get(hall.size() - 1); int first = -1; int last = -1; int checkR = Integer.parseInt(String.valueOf(lis.get(1))); int checkH = Integer.parseInt(String.valueOf(lists.get(1))); if (checkR < checkH){ last = checkR; } else { last = checkH; } checkR = Integer.parseInt(String.valueOf(lis.get(0))); checkH = Integer.parseInt(String.valueOf(lists.get(0))); if(checkR > checkH){ first = checkR; } else { first = checkH; } if (first != -1){ return (first + last) / 2; } return -1; } private ArrayList<Integer> getEndPixel(String room){ ArrayList<Integer> result = new ArrayList<>(); JSONObject rooms = new JSONObject ((Map) this.file.get(room)); JSONObject hall = new JSONObject ((Map) this.file.get("hall")); Set<String> keys_room = rooms.keySet(); Set<String> keys_hall = hall.keySet(); boolean flag = false; int first = -1; int last = -1; for (String key : keys_room){ if (keys_hall.contains(key)){ int x = doorPixel(room, key); if (x != -1) { if (!flag){ first = Integer.parseInt(key); flag = true; } last = Integer.parseInt(key); } } } int mid = (first + last) / 2; if (mid != -1) { result.add(doorPixel(room, String.valueOf(mid))); result.add(mid); } else{ ArrayList<Integer> res = getEndPixelParallel(room); result.add(doorPixelParallel(room, String.valueOf(res.get(1)), String.valueOf(res.get(0)))); result.add(res.get(0)); return result; } return result; } private boolean checkRange(JSONArray range1, JSONArray range2){ int x = Integer.parseInt(String.valueOf(range1.get(0))); int y = Integer.parseInt(String.valueOf(range1.get(1))); int c = Integer.parseInt(String.valueOf(range2.get(0))); int d = Integer.parseInt(String.valueOf(range2.get(1))); if (x <= c && y <= d && y >= c){ return true; } if (x >= c && x <= d && y >= d){ return true; } if (x >= c && x <= d && y <= d && y >= c){ return true; } if (x <= c && y >= d){ return true; } return false; } private boolean checkNext(String room, String keyR, String keyH){ JSONObject r = new JSONObject ((Map) this.file.get(room)); JSONArray rooms = (JSONArray) r.get(keyR); JSONObject h = new JSONObject ((Map) this.file.get("hall")); JSONArray hall = (JSONArray) h.get(keyH); for (int i = 0; i < rooms.size(); i++){ JSONArray m = (JSONArray) rooms.get(i); for (int j = 0; j < hall.size(); j++) { JSONArray n = (JSONArray) hall.get(j); if (checkRange(m, n)){ return true; } } } return false; } private ArrayList<Integer> getEndPixelParallel(String room){ ArrayList<Integer> result = new ArrayList<>(); JSONObject rooms = new JSONObject ((Map) this.file.get(room)); JSONObject hall = new JSONObject ((Map) this.file.get("hall")); Set<String> keys_room = rooms.keySet(); Set<String> keys_hall1 = hall.keySet(); ArrayList<Integer> keys_hall = new ArrayList<>(); for(String key : keys_hall1){ keys_hall.add(Integer.parseInt(key)); } Collections.sort(keys_hall); int last_room = -1; int first_room = 800; for (String key : keys_room){ int i = Integer.parseInt(key); if (i > last_room){ last_room = i; } if(i < first_room){ first_room = i; } } for (int i : keys_hall){ if (Math.abs(i - last_room) < 15){ if (checkNext(room, String.valueOf(last_room), String.valueOf(i))){ result.add(i); result.add(last_room); return result; } } } for (int i = 0; i < keys_hall.size(); i++){ int key = keys_hall.get(keys_hall.size() - 1 - i); if (Math.abs(key - first_room) < 15){ if (checkNext(room, String.valueOf(first_room), String.valueOf(key))){ result.add(key); result.add(first_room); } } } return result; } private double dist(int x, int y, int x1, int y1){ double a = Math.pow(Math.abs(x - x1), 2); double b = Math.pow(Math.abs(y - y1), 2); return Math.sqrt(a+b); } private ArrayList<Integer> getStartPixels(){ ArrayList<Integer> result = new ArrayList<>(); JSONParser jsonParser = new JSONParser(); Object obj = null; try (FileReader reader = new FileReader("Blue.json")) { obj = jsonParser.parse(reader); } catch (Exception e) { e.printStackTrace(); } JSONArray array = new JSONArray(); array.add(obj); JSONObject da = new JSONObject((Map) array.get(0)); int blueFloor = Integer.parseInt(String.valueOf(da.keySet().toArray()[0])); int x; int y; if (blueFloor == this.floor) { da = new JSONObject((Map) da.get(String.valueOf(blueFloor))); y = Integer.parseInt(String.valueOf(da.keySet().toArray()[0])); x = Integer.parseInt(String.valueOf(da.get(String.valueOf(y)))); result.add(x); result.add(y); } else { result = getEndPixel("lift"); } return result; } private boolean isBlack (int x, int y) { if (x >= this.im.length / 720){ return true; } int red = (this.im[(y*bi.getWidth())+x] >> 16) & 0xFF; int green = (this.im[(y*bi.getWidth())+x] >> 8) & 0xFF; int blue = (this.im[(y*bi.getWidth())+x]) & 0xFF; if (red != green) { return false; } if (red != blue) { return false; } if (blue > 220) { return false; } return true; } private boolean isSomethingBlack (int x, int y, double dist, int len) { if (len < 8 || dist < 8) { return !isBlack(x, y); } for (int i = 0; i < 5; i++){ if (x - i >= 0 && x - i < 1280) { for (int j = 0; j < 5; j++){ if (y - j >= 0 && y - j < 720) { if (isBlack(x-i, y-j)){ return false; } } if (y + j >= 0 && y + j < 720) { if (isBlack(x-i, y+j)){ return false; } } } } if (x + i >= 0 && x + i < 1280) { for (int j = 0; j < 5; j++){ if (y - j >= 0 && y - j < 720) { if (isBlack(x+i, y-j)){ return false; } } if (y + j >= 0 && y + j < 720) { if (isBlack(x+i, y+j)){ return false; } } } } } return true; } private boolean checkPixel (int x, int y, double dist, int length) { if (x < 0 || x >= 1280) { return false; } if (y < 0 || y >= 720) { return false; } ArrayList<Integer> check = new ArrayList<>(); check.add(x); check.add(y); if (this.used.contains(check)) { return false; } return isSomethingBlack(x, y, dist, length); } private void addPixel (int x, int y, ArrayList<ArrayList<Integer>> prev, int length, int xs, int ys) { double dis = dist(xs, ys, x, y); if (checkPixel(x, y, dis, length)){ this.list.addElement(x, y, dis, length, prev); ArrayList<Integer> dummy = new ArrayList<>(); dummy.add(x); dummy.add(y); this.used.add(dummy); } } private ArrayList<ArrayList<Integer>> bestRoute (int xs, int ys) { ArrayList<Integer> start = getStartPixels(); int startX = start.get(0); int startY = start.get(1); this.list.addElement(startX, startY, dist(startX, startY, xs, ys), 1, new ArrayList<>()); ArrayList<Integer> dummy = new ArrayList<>(); dummy.add(startX); dummy.add(startY); this.used.add(dummy); while (!this.list.isEmpty()) { ArrayList<Object> el = this.list.getElement(); int x = (int) el.get(0); int y = (int) el.get(1); double dist = (double) el.get(2); int length = (int) el.get(3); ArrayList<ArrayList<Integer>> previous = (ArrayList<ArrayList<Integer>>) el.get(4); dummy = new ArrayList<>(); dummy.add(x); dummy.add(y); previous.add(dummy); if (dist == 0) { return previous; } length ++; addPixel(x-1, y-1, previous, length, xs, ys); addPixel(x-1, y, previous, length, xs, ys); addPixel(x-1, y+1, previous, length, xs, ys); addPixel(x, y-1, previous, length, xs, ys); addPixel(x, y+1, previous, length, xs, ys); addPixel(x+1, y-1, previous, length, xs, ys); addPixel(x+1, y, previous, length, xs, ys); addPixel(x+1, y+1, previous, length, xs, ys); } return null; } private void drawPixel (int x, int y, BufferedImage img){ if (!isBlack(x, y)){ Color col = Color.red; img.setRGB(x, y, col.getRGB()); } } private void drawRoute (int x, int y, BufferedImage img) { drawPixel(x-1, y-1, img); drawPixel(x-1, y, img); drawPixel(x-1, y+1, img); drawPixel(x, y-1, img); drawPixel(x, y, img); drawPixel(x, y+1, img); drawPixel(x+1, y-1, img); drawPixel(x+1, y, img); drawPixel(x+1, y+1, img); } private void drawRoom (String room, BufferedImage img) { JSONObject r = new JSONObject ((Map) this.file.get(room)); Set<String> keys = r.keySet(); for (String key : keys){ JSONArray rooms = (JSONArray) r.get(key); for (int j = 0; j < rooms.size(); j++) { JSONArray m = (JSONArray) rooms.get(j); int first = Integer.parseInt(String.valueOf(m.get(0))); int second = Integer.parseInt(String.valueOf(m.get(1))); for (int i = first; i <= second; i++) { drawPixel(i, Integer.parseInt(key), img); } } } } private void makePicture (String room, String name) throws IOException { BufferedImage img = ImageIO.read((new File(this.imageName))); ArrayList<Integer> end = getEndPixel(room); ArrayList<ArrayList<Integer>> route = bestRoute(end.get(0), end.get(1)); if (route == null) { System.out.println("No route found"); return; } for (ArrayList<Integer> pixel : route) { drawRoute(pixel.get(0), pixel.get(1), img); } drawRoom(room, img); File f = new File(name +".png"); ImageIO.write(img, "PNG", f); } public void run() { try { makePicture(this.room, this.floor + "/" + this.room + "Pic"); } catch (IOException e) { e.printStackTrace(); } } }
package com.tencent.mm.plugin.backup.backuppcmodel; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.ach; import com.tencent.mm.protocal.c.pw; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; class c$1 implements e { final /* synthetic */ c gWG; c$1(c cVar) { this.gWG = cVar; } public final void a(int i, int i2, String str, l lVar) { au.DF().b(595, c.a(this.gWG)); if (i == 0 && i2 == 0) { ach asA = ((com.tencent.mm.plugin.backup.f.e) lVar).asA(); au.HU(); String str2; if (!bi.oV((String) c.DT().get(2, null)).equals(asA.rfk)) { x.e("MicroMsg.BackupPcProcessMgr", "onGetConnectInfoEnd Error: not the same account"); b.arV().aqP().gRC = -5; b.arV().arX().mH(-5); h.mEJ.a(400, 112, 1, false); return; } else if (asA.rfi == null || asA.rfi.size() <= 0 || asA.rfi.getFirst() == null) { str2 = "MicroMsg.BackupPcProcessMgr"; String str3 = "onGetConnectInfoEnd AddrList is empty! AddrCount[%d], AddrList size[%s]"; Object[] objArr = new Object[2]; objArr[0] = Integer.valueOf(asA.rfh); objArr[1] = asA.rfi == null ? "null" : asA.rfi.size(); x.e(str2, str3, objArr); b.arV().aqP().gRC = -5; b.arV().arX().mH(-5); h.mEJ.a(400, 113, 1, false); return; } else { pw pwVar = (pw) asA.rfi.getFirst(); str2 = pwVar.rud; int intValue = ((Integer) pwVar.rue.getFirst()).intValue(); c cVar = this.gWG; cVar.gWx = asA.rfl; cVar.gWy = str2; cVar.gWz = intValue; x.i("MicroMsg.BackupPcProcessMgr", "onGetConnectInfoEnd type:%d, scene:%d, wifiName:%s, ip:%s, port:%d", new Object[]{Integer.valueOf(asA.hcE), Integer.valueOf(asA.otY), asA.rfl, str2, Integer.valueOf(intValue)}); b.arV().gRu = asA.ID; b.arV().gRv = asA.rfr; b.arV().gRw = asA.rfs; b.arV().gRA = asA.reV.siK.lR; c.b(this.gWG); return; } } x.i("MicroMsg.BackupPcProcessMgr", "onGetConnectInfoEnd Error: other error[%d,%d,%s]", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str}); h.mEJ.a(400, 111, 1, false); if (i == 4 && i2 == -2011) { x.e("MicroMsg.BackupPcProcessMgr", "onGetConnectInfoEnd Error: INVALID URL"); } b.arV().aqP().gRC = -5; b.arV().arX().mH(-5); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.solrfacetsearch.integration; import static java.util.stream.Collectors.toList; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.assertNotNull; import de.hybris.platform.core.PK; import de.hybris.platform.core.model.product.ProductModel; import de.hybris.platform.processing.enums.BatchType; import de.hybris.platform.processing.model.BatchModel; import de.hybris.platform.servicelayer.search.SearchResult; import de.hybris.platform.servicelayer.search.impl.DefaultFlexibleSearchService; import de.hybris.platform.solrfacetsearch.config.FacetSearchConfig; import de.hybris.platform.solrfacetsearch.indexer.impl.DefaultIndexerService; import de.hybris.platform.solrfacetsearch.model.SolrIndexerBatchModel; import de.hybris.platform.solrfacetsearch.model.SolrIndexerDistributedProcessModel; import java.util.List; import javax.annotation.Resource; import org.junit.Test; public class DistributedIndexerProcessTest extends AbstractIntegrationTest { @Resource private DefaultFlexibleSearchService flexibleSearchService; @Resource private DefaultIndexerService indexerService; @Override protected void loadData() throws Exception { importConfig("/test/integration/DistributedIndexerProcessTest.csv"); } @Test public void testDistributedProcess() throws Exception { // given final FacetSearchConfig facetSearchConfig = getFacetSearchConfig(); // when indexerService.performFullIndex(facetSearchConfig); // then final SolrIndexerDistributedProcessModel distributedIndexerProcess = getDistributedIndexerProcess(); assertThat(distributedIndexerProcess).isNotNull(); final List<SolrIndexerBatchModel> inputBatches = getInputBatches(distributedIndexerProcess); assertNotNull(inputBatches); assertNotNull(inputBatches.get(0).getContext()); final List<PK> inputBatchContext = (List<PK>) inputBatches.get(0).getContext(); assertThat(inputBatchContext).hasSize( getNumberOfIndexingItems() < distributedIndexerProcess.getBatchSize() ? getNumberOfIndexingItems() : distributedIndexerProcess.getBatchSize()); } private List<SolrIndexerBatchModel> getInputBatches(final SolrIndexerDistributedProcessModel process) { return process.getBatches().stream().filter(b -> b.getType() == BatchType.INITIAL).map(this::asSolrIndexerBatchModel) .collect(toList()); } private SolrIndexerBatchModel asSolrIndexerBatchModel(final BatchModel batch) { assertThat(batch).isInstanceOf(SolrIndexerBatchModel.class); return (SolrIndexerBatchModel) batch; } private SolrIndexerDistributedProcessModel getDistributedIndexerProcess() { final StringBuilder query = new StringBuilder("SELECT {ssidp." + SolrIndexerDistributedProcessModel.PK + "} "); query.append("FROM {" + SolrIndexerDistributedProcessModel._TYPECODE + " AS ssidp} "); query.append("ORDER BY {" + SolrIndexerDistributedProcessModel.MODIFIEDTIME + "} DESC"); final SearchResult<SolrIndexerDistributedProcessModel> searchRes = flexibleSearchService.search(query.toString()); return searchRes.getResult().get(0); } private int getNumberOfIndexingItems() { final StringBuilder query = new StringBuilder("SELECT {p." + ProductModel.PK + "} "); query.append("FROM {" + ProductModel._TYPECODE + " AS p} "); final SearchResult<ProductModel> searchRes = flexibleSearchService.search(query.toString()); return searchRes.getResult().size(); } }
package com.baizhi.entity; import java.util.HashMap; import java.util.Map; public class Cart { //想要从map中判断是否含有指定的key值 不能为空 需要new出来一个 private Map<Integer,Item> addmap=new HashMap<>(); private Map<Integer,Item> removemap =new HashMap<>(); private Double totalprice; private Double totalsave; public Map<Integer, Item> getRemovemap() { return removemap; } public void setRemovemap(Map<Integer, Item> removemap) { this.removemap = removemap; } public Double getTotalsave() { return totalsave; } public void setTotalsave(Double totalsave) { this.totalsave = totalsave; } public Map<Integer, Item> getAddmap() { return addmap; } public void setAddmap(Map<Integer, Item> addmap) { this.addmap = addmap; } public Double getTotalprice() { return totalprice; } public void setTotalprice(Double totalprice) { this.totalprice = totalprice; } @Override public String toString() { return "Cart [addmap=" + addmap + ", totalprice=" + totalprice + "]"; } }
package com.marcuschiu.jpahibernateandh2database.repository; import com.marcuschiu.jpahibernateandh2database.model.Student; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * JpaRepository<Student, Long> * - Student is the entity that is being managed * - Long is the primary key of Student */ @Repository public interface StudentRepository extends JpaRepository<Student, Long> { }
package cn.itcast.demo3; public class Computer { public void openComputer() { System.out.println("电脑打开"); } public void closeComputer() { System.out.println("电脑关闭"); } public void useUSB(USB usb)//体现多态 { usb.open();//USB usb = new Mouse();USB usb = new KeyBoard(); // 父类 变量名 = new 子类(),变量名.方法名,调用的是子类的方法。 usb.close(); } }
package br.com.conspesca.repository; import java.util.List; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import br.com.conspesca.model.Pesca; @Named public class PescaRepository { @PersistenceContext private EntityManager em; public void save(Pesca pesca) { this.em.persist(pesca); } public Pesca find(int id) { return this.em.find(Pesca.class, id); } public Pesca update(Pesca pesca) { return this.em.merge(pesca); } public List<Pesca> findAll() { CriteriaBuilder builder = this.em.getCriteriaBuilder(); CriteriaQuery<Pesca> cq = builder.createQuery(Pesca.class); Root<Pesca> rootP = cq.from(Pesca.class); rootP.fetch("pescarias"); cq.select(rootP); cq.distinct(true); return this.em.createQuery(cq).getResultList(); } }
package com.jack.jkbase.service.impl; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.jack.jkbase.entity.SysCompany; import com.jack.jkbase.entity.SysCompanyRole; import com.jack.jkbase.entity.ViewSysCompanyRole; import com.jack.jkbase.mapper.SysCompanyRoleMapper; import com.jack.jkbase.mapper.ViewSysCompanyRoleMapper; import com.jack.jkbase.service.ISysCompanyRoleService; /** * <p> * 服务实现类 * </p> * * @author LIBO * @since 2020-09-23 */ @Service public class SysCompanyRoleServiceImpl extends ServiceImpl<SysCompanyRoleMapper, SysCompanyRole> implements ISysCompanyRoleService { @Autowired ViewSysCompanyRoleMapper viewMapper; public List<ViewSysCompanyRole> selectAll(){ return viewMapper.selectList(null); } public ViewSysCompanyRole selectByCompanyid(int companyid) { return viewMapper.selectOne(Wrappers.lambdaQuery(ViewSysCompanyRole.class) .eq(ViewSysCompanyRole::getCompanyid, companyid)); } public JSONObject getTree(){ JSONObject jo = new JSONObject(); List<ViewSysCompanyRole> list = selectAll(); JSONArray ja = new JSONArray(); for(SysCompany item: list){ JSONObject joItem = (JSONObject) JSON.toJSON(item); if(item.getcParentid()!=0) joItem.put("_parentId",item.getcParentid()); //第一层(顶层 joItem.put("iconCls",item.getcLevel()==1?"fa fa-circle-o":"fa fa-circle"); ja.add(joItem); } jo.put("rows", ja); return jo; } public boolean removeByKey(SysCompanyRole entity) { return remove(Wrappers.lambdaQuery(entity)); } public boolean deleteByCompanyid(int companyid) { return remove(Wrappers.lambdaQuery(SysCompanyRole.class).eq(SysCompanyRole::getCompanyid, companyid)); } public boolean deleteByRoleid(int roleid) { return remove(Wrappers.lambdaQuery(SysCompanyRole.class).eq(SysCompanyRole::getRoleid, roleid)); } /** * 根据部门id查找角色id列表 */ public List<SysCompanyRole> selectRolesByCompanyid(int companyid){ return list(Wrappers.lambdaQuery(SysCompanyRole.class).eq(SysCompanyRole::getCompanyid, companyid)); } /* * public List<SysRole> selectRolesByCompanyid(int companyid){ String sql * =String.format("select A_AppId from sys_RoleApp where A_RoleID = %d ", * roleid); return list(Wrappers.lambdaQuery(SysApp.class).eq(SysApp::getaIssys, * 0) .notInSql(SysApp::getAppid, sql)); } */ /** * 批量添加某部门的角色列表 */ @Transactional public boolean insertbatchForCompany(int companyid,int[] roleids) { deleteByCompanyid(companyid);//先删除 if(roleids.length==0) return true; List<SysCompanyRole> list = new ArrayList<>(); for(int roleid:roleids) { list.add(new SysCompanyRole(companyid, roleid)); } return saveBatch(list); } }
package pl.cwanix.opensun.model.server; import lombok.Getter; import lombok.Setter; @Getter @Setter public class ServerModel { private int id; private int port; private String ip; private String name; }
package com.it.userportrait; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @description: * @author: Delusion * @date: 2021-09-26 0:01 */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class); } }
package str; public class SubStrRabinKrap { private static final int R = 256; private String pat; private int hash; private int Q; private int RM; public SubStrRabinKrap(String pat) { this.pat = pat; this.Q = 993; //assign some prime number RM = 1; for(int i = 1; i < pat.length(); i++) RM = (RM * R) % Q; this.hash = hash(pat, pat.length()); } public int search(String text) { int i, N = text.length(); int j, M = pat.length(); if(M > N) return -1; int localHash = hash(text, M); if(localHash == this.hash) return 0; for(i = M; i < N; i++) { localHash = (localHash + Q - text.charAt(i - M) * RM % Q) % Q; localHash = (localHash * R + text.charAt(i)) % Q; if(localHash == hash) return i - M + 1; } return -1; } private int hash(String str, int length) { int hash = 0; for(int i = 0; i < length; i++) { hash = hash * R + str.charAt(i); hash %= Q; } return hash; } /** * @param args */ public static void main(String[] args) { String pat = "yer"; String txt = "SubStrBoyerMooreSubStrBoyerMoore"; SubStrRabinKrap bm = new SubStrRabinKrap(pat); int i = bm.search(txt); System.out.println(i); if(i >= 0) System.out.println(txt.substring(i, i += pat.length())); else System.out.println("No Match found"); } }
package com.example.zahit.multipleactivityproject; import android.widget.TableRow; import android.widget.TextView; import com.google.firebase.database.Exclude; import java.util.ArrayList; /** * Created by Zahit on 18-Mar-18. */ public class Lobby { private String lobbyName; private int currentNumberOfPlayers; private int maximumNumberOfPlayers; private ArrayList<String> playerNames; private String hostUID; @Exclude private TableRow tableRow; @Exclude private TextView textView; public Lobby(){ this.playerNames = new ArrayList<String>(); } public Lobby(String lobbyName, int maxNumberOfPlayers, String hostUID){ this.lobbyName = lobbyName; this.currentNumberOfPlayers = 0; this.maximumNumberOfPlayers = maxNumberOfPlayers; this.hostUID = hostUID; this.playerNames = new ArrayList<String>(); } public Lobby(String lobbyName, int currentNumberOfPlayers, int maximumNumberOfPlayers, TableRow tableRow, TextView textView){ this.lobbyName = lobbyName; this.currentNumberOfPlayers = currentNumberOfPlayers; this.maximumNumberOfPlayers = maximumNumberOfPlayers; this.tableRow = tableRow; this.textView = textView; this.playerNames = new ArrayList<String>(); } public String getLobbyName(){ return lobbyName; } public int getMaximumNumberOfPlayers(){ return maximumNumberOfPlayers; } public TableRow getTableRow(){ return tableRow; } public TextView getTextView(){ return textView; } public int getCurrentNumberOfPlayers(){ return currentNumberOfPlayers; } public ArrayList<String> getPlayerNames(){ return playerNames; } public String getHostUID(){ return hostUID; } public boolean addPlayer(String playerName) { if(currentNumberOfPlayers >= maximumNumberOfPlayers) return false; currentNumberOfPlayers++; playerNames.add(playerName); return true; } public void removePlayer(String playerName){ currentNumberOfPlayers--; playerNames.remove(playerName); } }
package com.tencent.mm.plugin.appbrand.wxawidget.console; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.widget.FrameLayout; import com.tencent.mm.kernel.g; import com.tencent.mm.modelappbrand.e; import com.tencent.mm.plugin.appbrand.wxawidget.b.b; import com.tencent.mm.plugin.appbrand.wxawidget.b.c; import com.tencent.mm.sdk.platformtools.x; public class ControlBoardPanel extends FrameLayout { ConsolePanel fxO; a gQB; View gQC; SettingsPanel gQD; View gQE; View gQF; View gQG; View gQH; WindowManager gQI; LayoutParams gQJ; boolean gQK; static /* synthetic */ void a(ControlBoardPanel controlBoardPanel) { controlBoardPanel.gQJ.width = -2; controlBoardPanel.gQJ.height = -2; controlBoardPanel.gQJ.flags = 520; controlBoardPanel.gQI.updateViewLayout(controlBoardPanel, controlBoardPanel.gQJ); } static /* synthetic */ void b(ControlBoardPanel controlBoardPanel) { controlBoardPanel.gQJ.width = -1; controlBoardPanel.gQJ.height = -1; controlBoardPanel.gQJ.flags = 544; controlBoardPanel.gQI.updateViewLayout(controlBoardPanel, controlBoardPanel.gQJ); } public ControlBoardPanel(Context context) { super(context); init(); } public ControlBoardPanel(Context context, AttributeSet attributeSet) { super(context, attributeSet); init(); } public ControlBoardPanel(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); init(); } private void init() { Context context = getContext(); this.gQI = (WindowManager) context.getSystemService("window"); LayoutInflater.from(context).inflate(c.control_board_panel, this, true); this.gQC = findViewById(b.content_vg); this.fxO = (ConsolePanel) findViewById(b.console_panel); this.gQD = (SettingsPanel) findViewById(b.settings_panel); this.gQE = findViewById(b.performance_panel); this.gQF = findViewById(b.console_btn); this.gQG = findViewById(b.settings_btn); this.gQH = findViewById(b.performance_btn); if (!((e) g.l(e.class)).JN().JQ()) { this.gQH.setVisibility(8); } this.gQF.setOnClickListener(new OnClickListener() { public final void onClick(View view) { if (ControlBoardPanel.this.fxO.getVisibility() == 0) { ControlBoardPanel.this.gQC.setVisibility(8); ControlBoardPanel.this.fxO.setVisibility(8); ControlBoardPanel.this.gQF.setSelected(false); ControlBoardPanel.a(ControlBoardPanel.this); return; } ControlBoardPanel.this.gQC.setVisibility(0); ControlBoardPanel.this.fxO.setVisibility(0); ControlBoardPanel.this.gQD.setVisibility(8); ControlBoardPanel.this.gQE.setVisibility(8); ControlBoardPanel.this.gQF.setSelected(true); ControlBoardPanel.this.gQG.setSelected(false); ControlBoardPanel.this.gQH.setSelected(false); ControlBoardPanel.b(ControlBoardPanel.this); } }); this.gQG.setOnClickListener(new 2(this)); this.gQH.setOnClickListener(new 3(this)); setOnKeyListener(new OnKeyListener() { public final boolean onKey(View view, int i, KeyEvent keyEvent) { x.i("MicroMsg.ControlBoardPanel", "onKey(%s, %s)", new Object[]{Integer.valueOf(i), keyEvent}); if (i == 4) { ControlBoardPanel.this.gQC.setVisibility(8); ControlBoardPanel.this.gQE.setVisibility(8); ControlBoardPanel.this.gQE.setVisibility(8); ControlBoardPanel.this.gQH.setSelected(false); ControlBoardPanel.this.gQF.setSelected(false); ControlBoardPanel.this.gQG.setSelected(false); ControlBoardPanel.a(ControlBoardPanel.this); } return false; } }); this.gQD.setOnCloseDebuggerClickListener(new 5(this)); this.gQD.setOnResetDebuggerRunnable(new 6(this)); } public boolean onKeyUp(int i, KeyEvent keyEvent) { x.i("MicroMsg.ControlBoardPanel", "onKeyUp(%s, %s)", new Object[]{Integer.valueOf(i), keyEvent}); return super.onKeyUp(i, keyEvent); } public final void reset() { d.b(this.fxO); d.a(this.fxO); } }
package de.raidcraft.skillsandeffects.pvp.skills.physical; import com.sk89q.minecraft.util.commands.CommandContext; import de.raidcraft.skills.api.combat.EffectType; import de.raidcraft.skills.api.effect.common.QueuedAttack; import de.raidcraft.skills.api.exceptions.CombatException; import de.raidcraft.skills.api.hero.Hero; import de.raidcraft.skills.api.persistance.SkillProperties; import de.raidcraft.skills.api.profession.Profession; import de.raidcraft.skills.api.skill.AbstractSkill; import de.raidcraft.skills.api.skill.SkillInformation; import de.raidcraft.skills.api.trigger.CommandTriggered; import de.raidcraft.skills.tables.THeroSkill; import de.raidcraft.skills.util.ConfigUtil; import de.raidcraft.skillsandeffects.pvp.effects.potion.Invisibility; import org.bukkit.configuration.ConfigurationSection; /** * @author Silthus */ @SkillInformation( name = "Shadow Strike", description = "Verursacht extra Schaden wenn du Unsichtbar angreifst.", types = {EffectType.PHYSICAL, EffectType.HARMFUL, EffectType.DAMAGING}, queuedAttack = true ) public class ShadowStrike extends AbstractSkill implements CommandTriggered { private ConfigurationSection bonusDamage; public ShadowStrike(Hero hero, SkillProperties data, Profession profession, THeroSkill database) { super(hero, data, profession, database); } @Override public void load(ConfigurationSection data) { bonusDamage = data.getConfigurationSection("bonus-damage"); } @Override public void runCommand(CommandContext args) throws CombatException { addEffect(QueuedAttack.class).addCallback(trigger -> { if (hasEffect(Invisibility.class)) { trigger.getAttack().setDamage(trigger.getAttack().getDamage() + getBonusDamage()); } }); } private int getBonusDamage() { return (int) ConfigUtil.getTotalValue(this, bonusDamage); } }
package cn.edu.ecust.smart; public class ResponseWait { private final long id; private final long size; public ResponseWait(long id, long size) { this.id = id; this.size = size; } public long getId() { return id; } public long getSize() { return size; } }
package marchal.gabriel.bl.Coleccionista; import marchal.gabriel.bl.Categoria.Categoria; import marchal.gabriel.bl.ItemSubasta.ItemSubasta; import marchal.gabriel.bl.Usuario.Usuario; import java.time.LocalDate; import java.util.ArrayList; import java.util.Objects; /** * @author Gabriel Marchal * @version V1 * @since 2020-06-18 * */ public class Coleccionista extends Usuario { private String direccion; private ArrayList<Categoria> intereses; private ArrayList<ItemSubasta> coleccion; private int calificacion; private boolean esModerador; /** * Constructor simple del objeto Coleccionista */ public Coleccionista() { } /** * Constructor del objeto Coleccionista que toma: * @param nombre * @param identificacion * @param fechaNacimiento * @param correoElectronico * @param contrasena * @param direccion * @param intereses * @param estado * @param avatar * @param coleccion * @param calificacion * @param esModerador */ public Coleccionista(String nombre, String identificacion, LocalDate fechaNacimiento, String correoElectronico, String contrasena, boolean estado, String avatar, String direccion, ArrayList<Categoria> intereses, ArrayList<ItemSubasta> coleccion, int calificacion, boolean esModerador) { super(nombre, identificacion, fechaNacimiento, correoElectronico, contrasena, estado, avatar); this.direccion = direccion; this.intereses = intereses; this.coleccion = coleccion; this.calificacion = calificacion; this.esModerador = esModerador; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public ArrayList<Categoria> getIntereses() { return intereses; } public void setIntereses(ArrayList<Categoria> intereses) { this.intereses = intereses; } public ArrayList<ItemSubasta> getColeccion() { return coleccion; } public void setColeccion(ArrayList<ItemSubasta> coleccion) { this.coleccion = coleccion; } public int getCalificacion() { return calificacion; } public void setCalificacion(int calificacion) { this.calificacion = calificacion; } public boolean isEsModerador() { return esModerador; } public void setEsModerador(boolean esModerador) { this.esModerador = esModerador; } @Override public String toString() { String esModeradorString; if(esModerador){ esModeradorString = "Si"; }else{ esModeradorString = "No"; } return super.toString() + ", Calificacion: " + calificacion + ", esModerador: " + esModeradorString; } @Override public int hashCode() { return Objects.hash(super.hashCode(), getDireccion(), getIntereses(), getColeccion(), getCalificacion(), isEsModerador()); } }
package edu.metrostate.ics372.thatgroup.clinicaltrial.android.readingsactivity; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import java.util.List; import edu.metrostate.ics372.thatgroup.clinicaltrial.android.ClinicalTrialClient; import edu.metrostate.ics372.thatgroup.clinicaltrial.android.R; import edu.metrostate.ics372.thatgroup.clinicaltrial.android.statemachine.ClinicalTrialEvent; import edu.metrostate.ics372.thatgroup.clinicaltrial.android.statemachine.ClinicalTrialStateMachine; import edu.metrostate.ics372.thatgroup.clinicaltrial.android.statemachine.State; import edu.metrostate.ics372.thatgroup.clinicaltrial.android.statemachine.states.ReadingsState; import edu.metrostate.ics372.thatgroup.clinicaltrial.beans.Reading; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link ClinicsFragment#newInstance} factory method to * create an instance of this fragment. */ public class ReadingsFragment extends Fragment implements ReadingsView, AdapterView.OnItemClickListener, Button.OnClickListener { private ReadingsPresenter presenter; private OnFragmentInteractionListener mListener; public ReadingsFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment ClinicsFragment. */ public static ReadingsFragment newInstance() { ReadingsFragment fragment = new ReadingsFragment(); return fragment; } /** * * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /** * * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_readings, container, false); } /** * */ @Override public void onStart() { super.onStart(); if (presenter != null) { presenter.subscribe(); } final ListView viewReadings = ((ListView)getView().findViewById(R.id.readings)); viewReadings.setOnItemClickListener(this); final Button add = ((Button)getView().findViewById(R.id.add_reading)); add.setOnClickListener(this); } /** * * @param context */ @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } /** * */ @Override public void onDetach() { super.onDetach(); mListener = null; presenter = null; } /** * * @param view */ @Override public void onClick(View view) { final ClinicalTrialStateMachine machine = ((ClinicalTrialClient)getActivity().getApplication()).getMachine(); machine.process(ClinicalTrialEvent.ON_ADD); } /** * Callback method to be invoked when an item in this AdapterView has * been clicked. * <p> * Implementers can call getItemAtPosition(position) if they need * to access the data associated with the selected item. * * @param parent The AdapterView where the click happened. * @param view The view within the AdapterView that was clicked (this * will be a view provided by the adapter) * @param position The position of the view in the adapter. * @param id The row id of the item that was clicked. */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final ClinicalTrialStateMachine machine = ((ClinicalTrialClient)getActivity().getApplication()).getMachine(); Object obj = parent.getAdapter().getItem(position); if (obj instanceof Reading) { Reading reading = (Reading) obj; State state = machine.getCurrentState(); if (state instanceof ReadingsState) { ReadingsState readingsState = (ReadingsState) state; if (readingsState != null && reading != null) { readingsState.setObject(reading); machine.process(ClinicalTrialEvent.ON_SELECT); } } } } /** * * @param readings */ @Override public void setReadings(List<Reading> readings) { ArrayAdapter<Reading> arrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, readings); ((ListView)getView().findViewById(R.id.readings)).setAdapter(arrayAdapter); } /** * * @param visible */ @Override public void setVisibleAddReading(boolean visible) { ((Button)getView().findViewById(R.id.add_reading)).setVisibility(visible ? View.VISIBLE : View.GONE); } /** * * @param presenter */ @Override public void setPresenter(ReadingsPresenter presenter) { this.presenter = presenter; this.presenter.setView(this); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
package JUSLCodeClub; import java.util.Scanner; public class nthLargest { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[] = new int[n]; for(int i=0;i<n;i++) arr[i] = sc.nextInt(); int x = sc.nextInt(); System.out.println(nthLargestBat(arr,n,x)); } static int nthLargestBat(int[] arr, int n, int x) { int max = 0; for(int i=1;i<=x;i++) { max = -10001; int index = -1; for(int j=0;j<n;j++) { if(arr[j]>max) { max = arr[j]; index = j; } } arr[index] = -10001; } return max; } }
/* * Copyright (C) 2015 Miquel Sas * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.library.trading.data; import java.util.ArrayList; import java.util.List; import com.qtplaf.library.util.StringUtils; /** * Periods of trading. * * @author Miquel Sas */ public class Period implements Comparable<Period> { /** One minute period. */ public static final Period ONE_MIN = new Period(Unit.Minute, 1); /** Three minutes period. */ public static final Period THREE_MINS = new Period(Unit.Minute, 3); /** Five minutes period. */ public static final Period FiveMins = new Period(Unit.Minute, 5); /** Fifteen minutes period. */ public static final Period FIFTEEN_MINS = new Period(Unit.Minute, 15); /** Thirty minutes period. */ public static final Period THIRTY_MINS = new Period(Unit.Minute, 30); /** One hour period. */ public static final Period ONE_HOUR = new Period(Unit.Hour, 1); /** Four hours period. */ public static final Period FOUR_HOURS = new Period(Unit.Hour, 4); /** Daily period. */ public static final Period DAILY = new Period(Unit.Day, 1); /** Weekly period. */ public static final Period WEEKLY = new Period(Unit.Week, 1); /** Monthly period. */ public static final Period MONTHLY = new Period(Unit.Month, 1); /** * Returns the list of standard pre-defined periods. * * @return The list of standard pre-defined periods. */ public static List<Period> getStandardPeriods() { List<Period> periods = new ArrayList<>(); periods.add(ONE_MIN); periods.add(THREE_MINS); periods.add(FiveMins); periods.add(FIFTEEN_MINS); periods.add(THIRTY_MINS); periods.add(ONE_HOUR); periods.add(FOUR_HOURS); periods.add(DAILY); periods.add(WEEKLY); periods.add(MONTHLY); return periods; } /** * Parse a period id. * * @param id The period id. * @return The period. */ public static Period parseId(String id) { // Id length must be 5. if (id.length() != 5) { throw new IllegalArgumentException("Invalid period id"); } // Strings unit and size. String sunit = id.substring(0, 2); String ssize = id.substring(2); try { Unit unit = Unit.parseId(sunit); int size = Integer.parseInt(ssize); return new Period(unit, size); } catch (Exception exc) { throw new IllegalArgumentException("Invalid period id"); } } /** * Unit. */ private Unit unit; /** * The number of units or size. */ private int size = -1; /** * Constructor assigning unit and size. * * @param unit The unit. * @param size The size or number of units. */ public Period(Unit unit, int size) { super(); this.unit = unit; this.size = size; } /** * Returns a string id that uniquely identifies this period, by concatenating the unit id and the length padded to 3 * chars. * * @return The period id. */ public String getId() { StringBuilder b = new StringBuilder(); b.append(getUnit().getId()); b.append(StringUtils.leftPad(Integer.toString(getSize()), 3, '0')); return b.toString(); } /** * Returns the unit. * * @return The unit. */ public Unit getUnit() { return unit; } /** * Returns the size or number of units. * * @return The size or number of units. */ public int getSize() { return size; } /** * Returns the time this period elapses in millisecond. The time returned for months and years is the maximum (31 or * 366 days). * * @return The time of the priod in milliseconds. */ public long getTime() { long time = 0; switch (unit) { case Millisecond: time = 1; break; case Second: time = 1000; break; case Minute: time = 1000 * 60; break; case Hour: time = 1000 * 60 * 60; break; case Day: time = 1000 * 60 * 60 * 24; break; case Week: time = 1000 * 60 * 60 * 24 * 7; break; case Month: time = 1000 * 60 * 60 * 24 * 31; break; case Year: time = 1000 * 60 * 60 * 24 * 366; break; default: throw new IllegalArgumentException(); } time *= size; return time; } /** * Compares this period with the argument object. Returns 0 if they are equal, -1 if this value is less than the * argument, and 1 if it is greater. * * @param p The period to compare with. * @return An integer. */ @Override public int compareTo(Period p) { // Unit equals, the size decides. if (getUnit().equals(p.getUnit())) { if (getSize() < p.getSize()) { return -1; } else if (getSize() > p.getSize()) { return 1; } else { return 0; } } // The ordinal of the unit decides. if (getUnit().ordinal() < p.getUnit().ordinal()) { return -1; } else if (getUnit().ordinal() > p.getUnit().ordinal()) { return 1; } else { return 0; } } /** * Indicates whether some other object is "equal to" this one. * * @return A boolean. * @param o The object to compare with. */ @Override public boolean equals(Object o) { if (o == null) { return false; } if (o instanceof Period) { Period p = (Period) o; return compareTo(p) == 0; } return false; } /** * Returns a string representation of this period. * * @return A string representation of this period. */ @Override public String toString() { StringBuilder b = new StringBuilder(); b.append(getSize()); b.append(" "); b.append(getUnit().name()); if (getSize() > 1) { b.append("s"); } return b.toString(); } /** * Returns an XML element representation of this period. * * @return An XML element representation of this period. */ public String toXML() { StringBuilder b = new StringBuilder(); b.append("<period"); b.append(" unit=\"" + getUnit().name() + "\""); b.append(" size=\"" + getSize() + "\""); b.append("/>"); return b.toString(); } }
package control; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dao.MemberDAO; import model.MemberBean; @WebServlet("/PostWrite.do") public class PostWrite extends HttpServlet { private static final long serialVersionUID = 1L; public PostWrite() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doWrite(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doWrite(request, response); } protected void doWrite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //━━━━━━━━━━━━━━━━로그인시간체크━━━━━━━━━━━━━━━━━━━┓ HttpSession lastl = request.getSession(); //┃ String lastle = (String)lastl.getAttribute("email"); //┃ Date lastlt = new Date(); //┃ SimpleDateFormat lastlty = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //┃ String lastld = lastlty.format(lastlt); //┃ MemberDAO lastldao = new MemberDAO(); //┃ lastldao.sessionTime(lastle, lastld); //┃ //━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ String nowserver = request.getParameter("nowserver"); HttpSession session = request .getSession(); String email = (String)session.getAttribute("email"); // 글쓴이 정보 갖고오기 MemberDAO dao = new MemberDAO(); MemberBean bean = new MemberBean(); bean = dao.viewMember(email); request.setAttribute("bean", bean); request.setAttribute("nowserver", nowserver); RequestDispatcher dis = request.getRequestDispatcher("/bbs/postWrite.jsp?nowserver="+nowserver); dis.forward(request, response); } }
package io.vakin.algorithm.sort; import java.util.Arrays; /** * 希尔排序 * @description <br> * @author <a href="mailto:vakinge@gmail.com">vakin</a> * @date 2018年8月14日 */ public class ShellSort { public static void main(String []args){ int []arr ={1,4,2,7,9,8,3,6}; sort(arr); System.out.println(Arrays.toString(arr)); int []arr1 ={1,4,2,7,9,8,3,6}; sort1(arr1); System.out.println(Arrays.toString(arr1)); } /** * 希尔排序 针对有序序列在插入时采用交换法 * @param arr */ public static void sort(int []arr){ //增量gap,并逐步缩小增量 for(int gap=arr.length/2;gap>0;gap/=2){ //从第gap个元素,逐个对其所在组进行直接插入排序操作 for(int i=gap;i<arr.length;i++){ int j = i; while(j-gap>=0 && arr[j]<arr[j-gap]){ //插入排序采用交换法 swap(arr,j,j-gap); j-=gap; } } } } /** * 希尔排序 针对有序序列在插入时采用移动法。 * @param arr */ public static void sort1(int []arr){ //增量gap,并逐步缩小增量 for(int gap=arr.length/2;gap>0;gap/=2){ //从第gap个元素,逐个对其所在组进行直接插入排序操作 for(int i=gap;i<arr.length;i++){ int j = i; int temp = arr[j]; if(arr[j]<arr[j-gap]){ while(j-gap>=0 && temp<arr[j-gap]){ //移动法 arr[j] = arr[j-gap]; j-=gap; } arr[j] = temp; } } } } /** * 交换数组元素 * @param arr * @param a * @param b */ public static void swap(int []arr,int a,int b){ arr[a] = arr[a]+arr[b]; arr[b] = arr[a]-arr[b]; arr[a] = arr[a]-arr[b]; } }
package com.tt.miniapp.websocket.common; public abstract class WsStatusListener { public void onClosed(int paramInt, String paramString) {} public void onClosing(int paramInt, String paramString) {} public void onFailure(Throwable paramThrowable) {} public void onMessage(String paramString) {} public void onMessage(byte[] paramArrayOfbyte) {} public void onOpen(String paramString) {} } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\websocket\common\WsStatusListener.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package LeetCodeTopics.BinarySearch.SplitArrayLargestSum; public class Solution { public static void main(String[] args) { } public int splitArray(int[] nums, int k) { int left = 0; int right = 0; for (int num : nums) { left = Math.max(left, num); right += num; } while (left < right) { int mid = left + (right - left) / 2; if (feasible(nums, k, mid)) { right = mid; } else { left = mid + 1; } } return left; } private boolean feasible(int[] nums, int k, int threshold) { int total = 0; int count = 1; for (int num : nums) { total += num; if (total > threshold) { total = num; count++; if (count > k) { return false; } } } return true; } }
package Controlador; import Modelo.Carrito; import Modelo.Producto; import Modelo.ProductoDAO; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Controlador extends HttpServlet { ProductoDAO pdao = new ProductoDAO(); Producto pro = new Producto(); List<Producto> productos = new ArrayList<>(); List<Carrito> listaCarrito = new ArrayList<>(); int item; double totalPagar=0.0; int cantidad = 1; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String accion = request.getParameter("accion"); productos = pdao.listar(); switch(accion) { case "AgregarCarrito": int idp = Integer.parseInt(request.getParameter("id")); pro = pdao.listarId(idp); item = item + 1; Carrito car = new Carrito(); car.setItem(item); car.setIdProducto(pro.getId()); car.setNombres(pro.getNombres()); car.setDescripcion(pro.getDescripcion()); car.setPrecioCompra(pro.getPrecio()); car.setCantidad(cantidad); car.setSubTotal(cantidad*pro.getPrecio()); listaCarrito.add(car); request.setAttribute("contador", listaCarrito.size()); request.getRequestDispatcher("Controlador?accion=home").forward(request, response); break; case "Delete": int idproducto = Integer.parseInt(request.getParameter("idp")); for(int i=0;i<listaCarrito.size();i++) { if(listaCarrito.get(i).getIdProducto()==idproducto) { listaCarrito.remove(i); } } break; case "Carrito": totalPagar = 0.0; request.setAttribute("carrito", listaCarrito); for(int i=0;i<listaCarrito.size();i++) { totalPagar = totalPagar + listaCarrito.get(i).getSubTotal(); } request.setAttribute("totalPagar", totalPagar); request.getRequestDispatcher("carrito.jsp").forward(request, response); break; default: request.setAttribute("productos", productos); request.getRequestDispatcher("hombres.jsp").forward(request, response); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package com.project1.web1.application; public class MyIllegalArgumentException extends IllegalArgumentException { public MyIllegalArgumentException() { super("Illegal string"); } }
package com.example.OCP.advancedClassDesing.enums; /** * Created by guille on 10/13/18. */ public enum SeasonsMethods { WINTER{ public void printHours() { System.out.println("9am -17pm"); } }, SUMMER { public void printHours() { System.out.println("07am - 19om"); } }, SPRING { public void printHours(){ System.out.println("08am - 18pm"); } }; public abstract void printHours(); }
package com.ssafy; import java.util.Arrays; public class CarMgr{ private Car[] cars = new Car[100]; private int index; public void add(Car c) { cars[index++] =c; } public Car[] search(){ return cars; } public Car search(String num) { for(Car c : cars) { if(c==null) break; if(c.getNum().equals(num)) { return c; } } return null; } public Car[] search(int price) { Car[] tmp = new Car[100]; int idx =0; for(Car c : cars) { if(c==null) break; if(c.getPrice()<price) { tmp[idx++]= c; } } return tmp; } public void update(String num, int price) { for(Car c : cars) { if(c==null) break; if(c.getNum().equals(num)) { c.setPrice(price); return; } } } public void delete(String num) { int count = 0; for(Car c : cars) { if(c==null) break; if(c.getNum().equals(num)) { for (int i = count; i < cars.length-1; i++) { cars[i] = cars[i+1]; } index--; return; } count++; } } public int size() { return index; } public int totlaPrice() { int sum =0; for (int i = 0; i < index; i++) { sum+= cars[i].getPrice(); } return sum; } }
package com.tencent.mm.plugin.appbrand.r.a; import android.content.Context; public enum a implements e, com.tencent.mm.plugin.appbrand.r.d.a { ; public static final c gCh = null; private final e gCi; private a(String str) { this.gCi = new b(); } static { gCh = new c(); } public final void init(Context context) { this.gCi.init(context); } public final void release() { this.gCi.release(); } public final c aoB() { return this.gCi.aoB(); } public final void cL(Context context) { init(context); } public final void aoy() { release(); } }
package com.hb.rssai.view.common; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.res.Configuration; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.support.design.widget.AppBarLayout; import android.support.v4.widget.SlidingPaneLayout; import android.support.v7.app.ActionBar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.Spanned; import android.text.TextUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.hb.rssai.R; import com.hb.rssai.adapter.LikeAdapter; import com.hb.rssai.base.BaseActivity; import com.hb.rssai.bean.Evaluate; import com.hb.rssai.bean.ResBase; import com.hb.rssai.bean.ResCollectionBean; import com.hb.rssai.bean.ResInfo; import com.hb.rssai.bean.ResInformation; import com.hb.rssai.bean.ResShareCollection; import com.hb.rssai.bean.UserCollection; import com.hb.rssai.constants.Constant; import com.hb.rssai.contract.RichTextContract; import com.hb.rssai.presenter.BasePresenter; import com.hb.rssai.presenter.RichTextPresenter; import com.hb.rssai.util.CommonHandler; import com.hb.rssai.util.DateUtil; import com.hb.rssai.util.DisplayUtil; import com.hb.rssai.util.GsonUtil; import com.hb.rssai.util.HtmlImageGetter; import com.hb.rssai.util.HttpLoadImg; import com.hb.rssai.util.LiteOrmDBUtil; import com.hb.rssai.util.SharedPreferencesUtil; import com.hb.rssai.util.StatusBarUtil; import com.hb.rssai.util.StringUtil; import com.hb.rssai.util.T; import com.hb.rssai.view.widget.MyDecoration; import com.hb.rssai.view.widget.WordWrapView; import com.umeng.socialize.ShareAction; import com.umeng.socialize.UMShareAPI; import com.umeng.socialize.UMShareListener; import com.umeng.socialize.bean.SHARE_MEDIA; import com.umeng.socialize.media.UMImage; import com.umeng.socialize.media.UMWeb; import com.umeng.socialize.shareboard.ShareBoardConfig; import com.umeng.socialize.shareboard.SnsPlatform; import com.umeng.socialize.utils.Log; import com.umeng.socialize.utils.ShareBoardlistener; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import static com.google.common.base.Preconditions.checkNotNull; import static com.rss.util.StringUtil.getAllRegexImages; //import com.zzhoujay.richtext.RichText; public class RichTextActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener, View.OnClickListener, RichTextContract.View { @BindView(R.id.sys_tv_title) TextView mSysTvTitle; @BindView(R.id.sys_toolbar) Toolbar mSysToolbar; @BindView(R.id.app_bar_layout) AppBarLayout mAppBarLayout; @BindView(R.id.ca_load_progress) ProgressBar mCaLoadProgress; @BindView(R.id.webView) WebView mWebView; @BindView(R.id.rta_tv_content) TextView mRtaTvContent; @BindView(R.id.activity_add_source) LinearLayout mActivityAddSource; @BindView(R.id.rta_tv_title) TextView mRtaTvTitle; @BindView(R.id.rta_tv_date) TextView mRtaTvDate; @BindView(R.id.rta_tv_whereFrom) TextView mRtaTvWhereFrom; @BindView(R.id.rta_tv_view) TextView mRtaTvView; @BindView(R.id.rta_recycler_view) RecyclerView mRtaRecyclerView; @BindView(R.id.rta_iv_good) ImageView mRtaIvGood; @BindView(R.id.rta_tv_good) TextView mRtaTvGood; @BindView(R.id.rta_ll_good) LinearLayout mRtaLlGood; @BindView(R.id.rta_iv_not_good) ImageView mRtaIvNotGood; @BindView(R.id.rta_tv_not_good) TextView mRtaTvNotGood; @BindView(R.id.rta_ll_not_good) LinearLayout mRtaLlNotGood; @BindView(R.id.ff_find_hot_label) TextView mFfFindHotLabel; @BindView(R.id.item_iv_logo) ImageView mItemIvLogo; @BindView(R.id.wwv_his_word) WordWrapView mWwvHisWord; private LinearLayoutManager linearLayoutManager; private String abstractContent = ""; private String abstractContentFormat = ""; private String pubDate = ""; private String title = ""; private String whereFrom = ""; private String url = ""; private String id = ""; private String evaluateType = ""; private long clickGood; private long clickNotGood; private String subscribeImg; private ResCollectionBean.RetObjBean mRetObjBean; private List<ResInformation.RetObjBean.RowsBean> resInfoList = new ArrayList<>(); private LikeAdapter likeAdapter; private Evaluate evaluate = new Evaluate(); RichTextContract.Presenter mPresenter; boolean isFirst = false; private long count;//阅读数 @Override protected void onCreate(Bundle savedInstanceState) { initSwipeBackFinish(); // 允许使用transitions super.onCreate(savedInstanceState); isFirst = true; mPresenter.getLikeByTitle(title); if (!TextUtils.isEmpty(SharedPreferencesUtil.getString(this, Constant.TOKEN, ""))) { mPresenter.updateCount(id); } mPresenter.getInformation(id); } /** * 初始化滑动返回 */ private void initSwipeBackFinish() { if (isSupportSwipeBack()) { SlidingPaneLayout slidingPaneLayout = new SlidingPaneLayout(this); //通过反射改变mOverhangSize的值为0,这个mOverhangSize值为菜单到右边屏幕的最短距离,默认 //是32dp,现在给它改成0 try { //mOverhangSize属性,意思就是左菜单离右边屏幕边缘的距离 Field f_overHang = SlidingPaneLayout.class.getDeclaredField("mOverhangSize"); f_overHang.setAccessible(true); //设置左菜单离右边屏幕边缘的距离为0,设置全屏 f_overHang.set(slidingPaneLayout, 0); } catch (Exception e) { e.printStackTrace(); } slidingPaneLayout.setPanelSlideListener(this); slidingPaneLayout.setSliderFadeColor(getResources().getColor(android.R.color.transparent)); // 左侧的透明视图 View leftView = new View(this); leftView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); slidingPaneLayout.addView(leftView, 0); //添加到SlidingPaneLayout中 // 右侧的内容视图 ViewGroup decor = (ViewGroup) getWindow().getDecorView(); ViewGroup decorChild = (ViewGroup) decor.getChildAt(0); decorChild.setBackgroundColor(getResources().getColor(android.R.color.white)); decor.removeView(decorChild); decor.addView(slidingPaneLayout); // 为 SlidingPaneLayout 添加内容视图 slidingPaneLayout.addView(decorChild, 1); } } @Override protected void setAppTitle() { mSysToolbar.setTitle(""); setSupportActionBar(mSysToolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(false);//设置ActionBar一个返回箭头,主界面没有,次级界面有 actionBar.setDisplayShowTitleEnabled(false); } mSysToolbar.setNavigationIcon(R.mipmap.ic_back); mSysToolbar.setNavigationOnClickListener(v -> finish()); mSysToolbar.setOnMenuItemClickListener(this); //修改状态栏文字图标为深色 StatusBarUtil.StatusBarLightMode(this); } public void setSelfTheme(Activity activity) { setTranslucentStatus2(activity); } @Override protected void initIntent() { Bundle bundle = getIntent().getExtras(); if (bundle != null) { abstractContent = null == bundle.getString("abstractContent") ? "" : bundle.getString("abstractContent"); title = bundle.getString(ContentActivity.KEY_TITLE); whereFrom = bundle.getString("whereFrom"); pubDate = bundle.getString("pubDate"); url = bundle.getString("url"); id = bundle.getString("id"); clickGood = bundle.getLong("clickGood"); clickNotGood = bundle.getLong("clickNotGood"); if (bundle.containsKey("subscribeImg")) { subscribeImg = bundle.getString("subscribeImg", ""); } if (bundle.containsKey("count")) { count = bundle.getLong("count", 0); } try { abstractContentFormat = getNewContent(abstractContent); } catch (Exception e) { e.printStackTrace(); abstractContentFormat = abstractContent; } } } WebSettings settings; private void initWebView() { settings = mWebView.getSettings(); //自适应屏幕 settings.setUseWideViewPort(true); settings.setLoadWithOverviewMode(true); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //扩大比例的缩放 settings.setJavaScriptEnabled(true); int size = DisplayUtil.dip2px(this, 17); settings.setDefaultFontSize(size); settings.setMinimumFontSize(14);//设置 WebView 支持的最小字体大小,默认为 8 // settings.setTextZoom(300); // 通过百分比来设置文字的大小,默认值是100 mWebView.addJavascriptInterface(new JsToJava(), "imageListener"); boolean isNight = SharedPreferencesUtil.getBoolean(this, Constant.KEY_SYS_NIGHT_MODE, false); if (isNight) { mWebView.setBackgroundColor(0); // 设置背景色 xml 一定要设置background 否则此处会报空指针 mWebView.getBackground().setAlpha(0); // 设置填充透明度 范围:0-255 mWebView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { mWebView.loadUrl("javascript:document.body.style.setProperty(\"color\", \"#9C9C9C\");"); mWebView.loadUrl("javascript:document.body.style.setProperty(\"word-break\", \"break-all\");"); mWebView.loadUrl("javascript:document.body.style.setProperty(\"word-wrap\", \"break-word\");"); mWebView.loadUrl("javascript:document.body.style.setProperty(\"text-align\", \"justify\");"); // web 页面加载完成,添加监听图片的点击 js 函数 // 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,函数的功能是在图片点击的时候调用本地java接口并传递url过去 mWebView.loadUrl("javascript:(function(){" + "var objs = document.getElementsByTagName(\"img\"); " + "for(var i=0;i<objs.length;i++) " + "{" + " objs[i].onclick=function() " + " { " + " window.imageListener.startShowImageActivity(this.src); " + " } " + "}" + "})()"); } }); } else { mWebView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { mWebView.loadUrl("javascript:document.body.style.setProperty(\"color\", \"#4D4D4D\");"); mWebView.loadUrl("javascript:document.body.style.setProperty(\"word-break\", \"break-all\");"); mWebView.loadUrl("javascript:document.body.style.setProperty(\"word-wrap\", \"break-word\");"); mWebView.loadUrl("javascript:document.body.style.setProperty(\"text-align\", \"justify\");"); // web 页面加载完成,添加监听图片的点击 js 函数 // 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,函数的功能是在图片点击的时候调用本地java接口并传递url过去 mWebView.loadUrl("javascript:(function(){" + "var objs = document.getElementsByTagName(\"img\"); " + "for(var i=0;i<objs.length;i++) " + "{" + " objs[i].onclick=function() " + " { " + " window.imageListener.startShowImageActivity(this.src); " + " } " + "}" + "})()"); } }); } mWebView.loadDataWithBaseURL(null, abstractContentFormat, "text/html", "utf-8", null); } /** * 点击图片启动新的 ShowImageFromWebActivity,并传入点击图片对应的 url 和页面所有图片 * 对应的 url * * @param url 点击图片对应的 url */ List<String> arrayList = new ArrayList<>(); /** * js方法回调 */ private class JsToJava { @JavascriptInterface public void startShowImageActivity(String url) { Intent intent = new Intent(RichTextActivity.this, ImageShowActivity.class); for (int i = 0; i < arrayList.size(); i++) { if (url.equals(arrayList.get(i))) { intent.putExtra(ImageShowActivity.KEY_IMAGE_POS, i); break; } } intent.putStringArrayListExtra(ImageShowActivity.KEY_IMAGE_BEAN, (ArrayList<String>) arrayList); startActivity(intent); } } @Override protected void initView() { mRtaTvTitle.setText(title.trim()); if (TextUtils.isEmpty(url)) { mRtaTvView.setVisibility(View.GONE); } if (TextUtils.isEmpty(subscribeImg)) { mItemIvLogo.setVisibility(View.GONE); } else { mItemIvLogo.setVisibility(View.VISIBLE); HttpLoadImg.loadCircleImg(this, subscribeImg, mItemIvLogo); } String eId = SharedPreferencesUtil.getString(this, id, ""); if (null != GsonUtil.getGsonUtil().getBean(eId, Evaluate.class)) { evaluate = GsonUtil.getGsonUtil().getBean(eId, Evaluate.class); } try { if (!TextUtils.isEmpty(pubDate)) { if (count > 0) { mRtaTvWhereFrom.setText(whereFrom + " " + DateUtil.showDate(Constant.sdf.parse(pubDate), Constant.DATE_LONG_PATTERN) + " 浏览" + count + ""); } else { mRtaTvWhereFrom.setText(whereFrom + " " + DateUtil.showDate(Constant.sdf.parse(pubDate), Constant.DATE_LONG_PATTERN)); } } else { mRtaTvWhereFrom.setText(whereFrom); } } catch (ParseException e) { e.printStackTrace(); } mRtaTvNotGood.setText("" + clickNotGood); mRtaTvGood.setText("" + clickGood); boolean isOldRec = SharedPreferencesUtil.getBoolean(this, Constant.KEY_IS_OLD_REC_MODE, false); if (isOldRec) { mRtaTvContent.setVisibility(View.VISIBLE); mWebView.setVisibility(View.GONE); loadTextView(); } else { initWebView(); initShowPop(); mRtaTvContent.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } linearLayoutManager = new LinearLayoutManager(this); mRtaRecyclerView.setLayoutManager(linearLayoutManager); mRtaRecyclerView.setNestedScrollingEnabled(false); mRtaRecyclerView.setHasFixedSize(true); mRtaRecyclerView.addItemDecoration(new MyDecoration(this, LinearLayoutManager.VERTICAL)); //初始化 String eStr = SharedPreferencesUtil.getString(this, id, ""); if (!TextUtils.isEmpty(eStr)) {//如果不是空 Evaluate eva = GsonUtil.getGsonUtil().getBean(eStr, Evaluate.class); if ("1".equals(eva.getClickGood())) { mRtaIvGood.setImageResource(R.mipmap.ic_good_press); } else if ("2".equals(eva.getClickGood())) { mRtaIvGood.setImageResource(R.mipmap.ic_good); } if ("1".equals(eva.getClickNotGood())) { mRtaIvNotGood.setImageResource(R.mipmap.ic_not_good_press); } else if ("2".equals(eva.getClickNotGood())) { mRtaIvNotGood.setImageResource(R.mipmap.ic_not_good); } } initShare(); } /** * 将html文本内容中包含img标签的图片,宽度变为屏幕宽度,高度根据宽度比例自适应 **/ public String getNewContent(String htmlText) { try { if (null != arrayList && arrayList.size() > 0) { arrayList.clear(); } arrayList.addAll(getAllRegexImages(htmlText)); htmlText = htmlText.replace("<figure", "</figure"); htmlText = htmlText.replace("&nbsp;", "\t"); htmlText = htmlText.replace("&#160;", "\t"); htmlText = htmlText.replace("阅读原文", "\t"); htmlText = htmlText.replace("<pre", ""); htmlText = htmlText.replace("</pre>", ""); htmlText = htmlText.replace("<code", "<span"); htmlText = htmlText.replace("</code>", "</span>"); htmlText = htmlText.replace("\"//files.", "\"http://files."); htmlText = htmlText.replace("\"//player.", "\"http://player."); htmlText = htmlText.replace("———", ""); htmlText = htmlText.replace("<mark", "<span"); htmlText = htmlText.replace("</mark>", "</span>"); Document doc = Jsoup.parse(htmlText); String resStr = doc.toString(); if (resStr.contains("&lt;") && resStr.contains("&gt;")) { resStr = resStr.replace("&lt;", "<"); resStr = resStr.replace("&gt;", ">"); doc = Jsoup.parse(resStr); } Elements elements = doc.getElementsByTag("img"); for (Element element : elements) { element.attr("width", "100%") .attr("height", "auto") .attr("data-w", "100%") .attr("data-h", "auto") .attr("data-width", "100%") .attr("data-height", "auto") .attr("data-rawwidth", "100%") .attr("data-rawheight", "auto") .attr("style", cssStr(element.attr("style"), "width", "100%")) .attr("style", cssStr(element.attr("style"), "height", "auto")) .attr("style", cssStr(element.attr("style"), "max-width", "100%")) .attr("style", addAttr(element.attr("style"), "border-radius", "8px")); } Elements elements1 = doc.getElementsByTag("table"); for (Element element : elements1) { element.attr("width", "100%") .attr("height", "auto") .attr("data-w", "100%") .attr("data-h", "auto") .attr("style", cssStr(element.attr("style"), "width", "100%")) .attr("style", cssStr(element.attr("style"), "height", "auto")) .attr("style", cssStr(element.attr("style"), "max-width", "100%")); } Elements elements2 = doc.getElementsByTag("span"); for (Element element : elements2) { element.attr("style", cssStr(element.attr("style"), "font-size", DisplayUtil.dip2px(this, 17) + "px")); element.attr("style", cssStr(element.attr("style"), "color", "#4D4D4D")); element.attr("style", cssStr(element.attr("style"), "background-color", "rgba(0,0,0,0)")); element.attr("style", cssStr(element.attr("style"), "text-indent", "2em")); } Elements elements3 = doc.getElementsByTag("a"); for (Element element : elements3) { element.attr("style", "color:#9c9c9c;word-wrap:break-word;text-decoration:none;border-bottom:4px dashed #9c9c9c;"); } Elements elements4 = doc.getElementsByTag("iframe"); for (Element element : elements4) { element.attr("width", "100%") .attr("height", "600px"); } Elements elements5 = doc.getElementsByTag("div"); for (Element element : elements5) { element.attr("style", cssStr(element.attr("style"), "font-size", DisplayUtil.dip2px(this, 17) + "px")); element.attr("style", cssStr(element.attr("style"), "line-height", "normal")); element.attr("style", cssStr(element.attr("style"), "width", "100%")); } Elements elements6 = doc.getElementsByTag("p"); for (Element element : elements6) { element.attr("style", cssStr(element.attr("style"), "line-height", "normal")); // element.attr("style", cssStr(element.attr("style"), "text-indent", "2em")); } Elements elements7 = doc.getElementsByTag("font"); for (Element element : elements7) { element.attr("style", cssStr(element.attr("style"), "font-size", DisplayUtil.dip2px(this, 17) + "px")); element.attr("style", cssStr(element.attr("style"), "color", "#4D4D4D")); element.attr("style", cssStr(element.attr("style"), "background-color", "rgba(0,0,0,0)")); element.attr("style", cssStr(element.attr("style"), "text-indent", "2em")); } Elements elements8 = doc.getElementsByTag("video"); for (Element element : elements8) { element.attr("width", "100%") .attr("height", "auto") .attr("data-w", "100%") .attr("data-h", "auto") .attr("data-width", "100%") .attr("data-height", "auto") .attr("data-rawwidth", "100%") .attr("data-rawheight", "auto") .attr("style", cssStr(element.attr("style"), "width", "100%")) .attr("style", cssStr(element.attr("style"), "height", "auto")) .attr("style", cssStr(element.attr("style"), "max-width", "100%")) .attr("style", addAttr(element.attr("style"), "border-radius", "8px")); } return doc.toString(); } catch (Exception e) { e.printStackTrace(); return htmlText; } } /** * 替换style 中的宽度高度属性 * * @param sourceStr * @param key * @param value * @return */ private String cssStr(String sourceStr, String key, String value) { if (!sourceStr.contains(key)) { return sourceStr; } String s1 = sourceStr.substring(0, sourceStr.indexOf(key)); String s2 = sourceStr.substring(sourceStr.indexOf(key)); String s3 = ""; if (-1 == s2.indexOf(";")) { s3 = s2.substring(s2.length()); } else { s3 = s2.substring(s2.indexOf(";")); } return s1 + "" + key + ":" + value + s3; } // style="a:123"; private String addAttr(String sourceStr, String key, String value) { if (TextUtils.isEmpty(sourceStr)) { String tempStr = "" + key + ":" + value + ""; return tempStr; } else { String tempStr = key + ":" + value + "; " + sourceStr; return tempStr; } } /** * TextView 加载 */ @Deprecated private void loadTextView() { HtmlImageGetter htmlImageGetter = new HtmlImageGetter(this, this, mRtaTvContent); Spanned spanned; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { spanned = Html.fromHtml(abstractContent, Html.FROM_HTML_MODE_LEGACY, htmlImageGetter, null); } else { spanned = Html.fromHtml(abstractContent, htmlImageGetter, null); // or for older api } mRtaTvContent.setText(spanned); } private UMShareListener mShareListener; private ShareAction mShareAction; private void initShare() { mShareListener = new CustomShareListener(this); /*增加自定义按钮的分享面板*/ //SHARE_MEDIA.SINA, SHARE_MEDIA.MORE mShareAction = new ShareAction(RichTextActivity.this) .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN_FAVORITE, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE) .addButton("umeng_sharebutton_copyurl", "umeng_sharebutton_copyurl", "umeng_socialize_copyurl", "umeng_socialize_copyurl") .addButton("umeng_view_content", "umeng_view_content", "umeng_view_content", "umeng_view_content") .setShareboardclickCallback(new ShareBoardlistener() { @Override public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) { if (snsPlatform.mShowWord.equals("umeng_sharebutton_copyurl")) { StringUtil.copy(url, RichTextActivity.this); Toast.makeText(RichTextActivity.this, "复制链接成功", Toast.LENGTH_LONG).show(); } else if (snsPlatform.mShowWord.equals("umeng_view_content")) { Intent intent = new Intent(RichTextActivity.this, ContentActivity.class);//创建Intent对象 intent.putExtra(ContentActivity.KEY_TITLE, title); intent.putExtra(ContentActivity.KEY_URL, url); intent.putExtra(ContentActivity.KEY_INFORMATION_ID, id); startActivity(intent); } else if (share_media == SHARE_MEDIA.SMS) { new ShareAction(RichTextActivity.this).withText("来自ZR分享面板") .setPlatform(share_media) .setCallback(mShareListener) .share(); } else { String url = RichTextActivity.this.url; UMWeb web = new UMWeb(url); web.setTitle(title); web.setDescription(abstractContent); web.setThumb(new UMImage(RichTextActivity.this, R.mipmap.load_logo)); new ShareAction(RichTextActivity.this).withMedia(web) .setPlatform(share_media) .setCallback(mShareListener) .share(); } } }); } @Override public void setPresenter(RichTextContract.Presenter presenter) { mPresenter = checkNotNull(presenter); } @Override public void showFail(Throwable throwable) { CommonHandler.actionThrowable(throwable); } private static class CustomShareListener implements UMShareListener { private WeakReference<RichTextActivity> mActivity; private CustomShareListener(RichTextActivity activity) { mActivity = new WeakReference(activity); } @Override public void onStart(SHARE_MEDIA platform) { } @Override public void onResult(SHARE_MEDIA platform) { if (platform.name().equals("WEIXIN_FAVORITE")) { Toast.makeText(mActivity.get(), platform + " 收藏成功啦", Toast.LENGTH_SHORT).show(); } else { if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS && platform != SHARE_MEDIA.EMAIL && platform != SHARE_MEDIA.FLICKR && platform != SHARE_MEDIA.FOURSQUARE && platform != SHARE_MEDIA.TUMBLR && platform != SHARE_MEDIA.POCKET && platform != SHARE_MEDIA.PINTEREST && platform != SHARE_MEDIA.INSTAGRAM && platform != SHARE_MEDIA.GOOGLEPLUS && platform != SHARE_MEDIA.YNOTE && platform != SHARE_MEDIA.EVERNOTE) { Toast.makeText(mActivity.get(), platform + " 分享成功啦", Toast.LENGTH_SHORT).show(); } } } @Override public void onError(SHARE_MEDIA platform, Throwable t) { if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS && platform != SHARE_MEDIA.EMAIL && platform != SHARE_MEDIA.FLICKR && platform != SHARE_MEDIA.FOURSQUARE && platform != SHARE_MEDIA.TUMBLR && platform != SHARE_MEDIA.POCKET && platform != SHARE_MEDIA.PINTEREST && platform != SHARE_MEDIA.INSTAGRAM && platform != SHARE_MEDIA.GOOGLEPLUS && platform != SHARE_MEDIA.YNOTE && platform != SHARE_MEDIA.EVERNOTE) { Toast.makeText(mActivity.get(), platform + " 分享失败啦", Toast.LENGTH_SHORT).show(); if (t != null) { Log.d("throw", "throw:" + t.getMessage()); } } } @Override public void onCancel(SHARE_MEDIA platform) { Toast.makeText(mActivity.get(), platform + " 分享取消了", Toast.LENGTH_SHORT).show(); } } @Override protected int providerContentViewId() { return R.layout.activity_rich_text; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.content_menu, menu); MenuItem item = menu.findItem(R.id.toolbar_add_collection); this.item = item; if (!TextUtils.isEmpty(SharedPreferencesUtil.getString(this, Constant.TOKEN, ""))) { mPresenter.getCollectionByInfoId(id, getUserID()); } return super.onCreateOptionsMenu(menu); } private MenuItem item; @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.toolbar_add_collection: this.item = item; if (!TextUtils.isEmpty(url)) { String dateTime = DateUtil.format(new Date(), Constant.DATE_LONG_PATTERN); UserCollection collection = new UserCollection(); collection.setLink(url); collection.setTime(dateTime); collection.setTitle(title); LiteOrmDBUtil.insert(collection); T.ShowToast(RichTextActivity.this, "收藏成功!"); String userId = getUserID(); mPresenter.add(title, url, id, mRetObjBean, userId); } else { T.ShowToast(this, "收藏失败,链接错误!"); } break; case R.id.toolbar_add_share: ShareBoardConfig config = new ShareBoardConfig(); config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_NONE); mShareAction.open(config); break; case R.id.toolbar_font: //TODO 打开设置 showThemePop(); break; } return false; } private void showThemePop() { if (mPop.isShowing()) { mPop.dismiss(); } else { mPop.show(); Window window = mPop.getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); window.setBackgroundDrawable(new ColorDrawable(0)); window.setContentView(popupView);//自定义布局应该在这里添加,要在dialog.show()的后面 window.setWindowAnimations(R.style.PopupAnimation);// window.setLayout(DisplayUtil.getMobileWidth(this) * 8 / 10, ViewGroup.LayoutParams.WRAP_CONTENT); mPop.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置 } // backgroundAlpha(0.5f); // mPop.setOnDismissListener(dialogInterface -> { // //Log.v("List_noteTypeActivity:", "我是关闭事件"); // backgroundAlpha(1f); // }); } View popupView; AlertDialog mPop; void initShowPop() { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = LayoutInflater.from(this); popupView = inflater.inflate(R.layout.layout_font, null); mPop = builder.create(); SeekBar sb = popupView.findViewById(R.id.seekBar); TextView ts = popupView.findViewById(R.id.tvSize); int prgValue = SharedPreferencesUtil.getInt(RichTextActivity.this, Constant.KEY_FONT_SIZE, 0); if (prgValue > 0) { ts.setText("设置字体大小(" + prgValue + ")"); settings.setTextZoom(prgValue); int size = DisplayUtil.dip2px(RichTextActivity.this, 17 * (1 + (prgValue / 100f))); settings.setDefaultFontSize(size); sb.setProgress(prgValue); } sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { settings.setTextZoom(progress); int size = DisplayUtil.dip2px(RichTextActivity.this, 17 * (1 + (progress / 100f))); settings.setDefaultFontSize(size); ts.setText("设置字体大小(" + progress + ")"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { SharedPreferencesUtil.setInt(RichTextActivity.this, Constant.KEY_FONT_SIZE, seekBar.getProgress()); } }); sb.setOnClickListener(arg0 -> { if (mPop.isShowing()) { mPop.dismiss(); } }); // SharedPreferencesUtil.setBoolean(this, Constant.KEY_IS_SHOW_POP, true); } /** * 设置添加屏幕的背景透明度 */ // public void backgroundAlpha(float bgAlpha) { // WindowManager.LayoutParams lp = getWindow().getAttributes(); // lp.alpha = bgAlpha; //0.0-1.0 // getWindow().setAttributes(lp); // } @Override protected BasePresenter createPresenter() { return new RichTextPresenter(this); } @Override protected void onDestroy() { super.onDestroy(); mWebView.stopLoading(); mWebView.destroy(); } @Override public void loadError(Throwable throwable) { mRtaLlGood.setEnabled(true); mRtaLlNotGood.setEnabled(true); throwable.printStackTrace(); // if (throwable instanceof HttpException) { CommonHandler.actionThrowable(throwable); // if (((HttpException) throwable).response().code() == 401) { // T.ShowToast(this, Constant.MSG_NO_LOGIN); // } else { // T.ShowToast(this, Constant.MSG_NETWORK_ERROR); // } // } else { // T.ShowToast(this, Constant.MSG_NETWORK_ERROR); // } } @Override public void showUpdateResult(ResBase resBase) { //TODO 更新数量成功 } @Override public void showListResult(ResInformation resInformation) { if (resInformation.getRetCode() == 0) { if (resInformation.getRetObj().getRows() != null && resInformation.getRetObj().getRows().size() > 0) { String keyWord = resInformation.getKeyWord();//标签云 if (!TextUtils.isEmpty(keyWord)) { String[] words = keyWord.split(","); for (String w : words) { w = w.replace("%", ""); w = w.replace("'", ""); if (!TextUtils.isEmpty(w) && !"null".equals(w)) { w = "#" + w; TextView textView = new TextView(this); textView.setText(w); textView.setTextColor(getResources().getColor(R.color.color_cloud_label)); mWwvHisWord.addView(textView); } } } resInfoList.addAll(resInformation.getRetObj().getRows()); if (likeAdapter == null) { likeAdapter = new LikeAdapter(this, resInfoList); likeAdapter.setOnItemClickedListener(rowsBean1 -> { //TODO Intent intent = new Intent(this, RichTextActivity.class);//创建Intent对象 intent.putExtra(ContentActivity.KEY_TITLE, rowsBean1.getTitle()); intent.putExtra(ContentActivity.KEY_URL, rowsBean1.getLink()); intent.putExtra(ContentActivity.KEY_INFORMATION_ID, rowsBean1.getId()); intent.putExtra("pubDate", rowsBean1.getPubTime()); intent.putExtra("whereFrom", rowsBean1.getWhereFrom()); intent.putExtra("abstractContent", rowsBean1.getAbstractContent()); intent.putExtra("id", rowsBean1.getId()); startActivity(intent);//将Intent传递给Activity }); mRtaRecyclerView.setAdapter(likeAdapter); } else { likeAdapter.notifyDataSetChanged(); } } } else { T.ShowToast(this, resInformation.getRetMsg()); } } @Override public void showAddResult(ResShareCollection resShareCollection) { mPresenter.getCollectionByInfoId(id, getUserID()); T.ShowToast(this, resShareCollection.getRetMsg()); } @Override public void loadEvaluateError(Throwable throwable) { mRtaLlGood.setEnabled(true); mRtaLlNotGood.setEnabled(true); throwable.printStackTrace(); T.ShowToast(this, Constant.MSG_NETWORK_ERROR); } @Override public void showUpdateEvaluateResult(ResBase resBase) { if (resBase.getRetCode() == 0) { mPresenter.getInformation(id); } else { T.ShowToast(this, resBase.getRetMsg()); } } @Override public void showInfoResult(ResInfo resInfo) { if (resInfo.getRetCode() == 0) { mRtaTvGood.setText("" + resInfo.getRetObj().getClickGood()); mRtaTvNotGood.setText("" + resInfo.getRetObj().getClickNotGood()); //刷新 if ("1".equals(evaluateType)) { String eStr = SharedPreferencesUtil.getString(this, id, ""); if (TextUtils.isEmpty(eStr)) {//如果是空那么没操作过直接设置1 evaluate.setClickGood("1"); evaluate.setInformationId(id); SharedPreferencesUtil.setString(this, id, GsonUtil.toJson(evaluate)); mRtaIvGood.setImageResource(R.mipmap.ic_good_press); } else { Evaluate eva = GsonUtil.getGsonUtil().getBean(eStr, Evaluate.class); if ("1".equals(eva.getClickGood())) { mRtaIvGood.setImageResource(R.mipmap.ic_good); evaluate.setClickGood("2"); evaluate.setInformationId(id); SharedPreferencesUtil.setString(this, id, GsonUtil.toJson(evaluate)); } else if ("2".equals(eva.getClickGood())) { mRtaIvGood.setImageResource(R.mipmap.ic_good_press); evaluate.setClickGood("1"); evaluate.setInformationId(id); SharedPreferencesUtil.setString(this, id, GsonUtil.toJson(evaluate)); } else { evaluate.setClickGood("1"); evaluate.setInformationId(id); SharedPreferencesUtil.setString(this, id, GsonUtil.toJson(evaluate)); mRtaIvGood.setImageResource(R.mipmap.ic_good_press); } } } else if ("0".equals(evaluateType)) { String eStr = SharedPreferencesUtil.getString(this, id, ""); if (TextUtils.isEmpty(eStr)) {//如果是空那么没操作过直接设置1 evaluate.setClickNotGood("1"); evaluate.setInformationId(id); SharedPreferencesUtil.setString(this, id, GsonUtil.toJson(evaluate)); mRtaIvNotGood.setImageResource(R.mipmap.ic_not_good_press); } else { Evaluate eva = GsonUtil.getGsonUtil().getBean(eStr, Evaluate.class); if ("1".equals(eva.getClickNotGood())) { mRtaIvNotGood.setImageResource(R.mipmap.ic_not_good); evaluate.setClickNotGood("2"); evaluate.setInformationId(id); SharedPreferencesUtil.setString(this, id, GsonUtil.toJson(evaluate)); } else if ("2".equals(eva.getClickNotGood())) { mRtaIvNotGood.setImageResource(R.mipmap.ic_not_good_press); evaluate.setClickNotGood("1"); evaluate.setInformationId(id); SharedPreferencesUtil.setString(this, id, GsonUtil.toJson(evaluate)); } else { evaluate.setClickNotGood("1"); evaluate.setInformationId(id); SharedPreferencesUtil.setString(this, id, GsonUtil.toJson(evaluate)); mRtaIvNotGood.setImageResource(R.mipmap.ic_not_good_press); } } } } else { if (!isFirst) { boolean isOffline = SharedPreferencesUtil.getBoolean(this, Constant.KEY_IS_OFFLINE_MODE, false); if (isOffline) { T.ShowToast(this, getResources().getString(R.string.str_offline_notice)); } else { T.ShowToast(this, resInfo.getRetMsg()); } } isFirst = false; } mRtaLlGood.setEnabled(true); mRtaLlNotGood.setEnabled(true); } @Override public void showCollectionInfoIdResult(ResCollectionBean resCollectionBean) { mRetObjBean = resCollectionBean.getRetObj(); if (resCollectionBean.getRetCode() == 0) { //设置收藏图标 if (!resCollectionBean.getRetObj().isDeleteFlag()) { item.setIcon(R.mipmap.ic_collection_press); } else { item.setIcon(R.mipmap.ic_collection_normal); } } else { item.setIcon(R.mipmap.ic_collection_normal); } } @OnClick({R.id.rta_ll_good, R.id.rta_ll_not_good, R.id.rta_tv_view}) @Override public void onClick(View v) { String eStr = SharedPreferencesUtil.getString(this, id, ""); Evaluate eva = GsonUtil.getGsonUtil().getBean(eStr, Evaluate.class); switch (v.getId()) { case R.id.rta_tv_view: Intent intent = new Intent(RichTextActivity.this, ContentActivity.class);//创建Intent对象 intent.putExtra(ContentActivity.KEY_TITLE, title); intent.putExtra(ContentActivity.KEY_URL, url); intent.putExtra(ContentActivity.KEY_INFORMATION_ID, id); startActivity(intent); break; case R.id.rta_ll_good: evaluateType = "1"; if (null != eva && "1".equals(eva.getClickNotGood())) { T.ShowToast(this, "您已踩过了,请先取消!"); } else { mRtaLlGood.setEnabled(false); mRtaLlNotGood.setEnabled(false); mPresenter.updateEvaluateCount(id, evaluateType, evaluate); } break; case R.id.rta_ll_not_good: evaluateType = "0"; if (null != eva && "1".equals(eva.getClickGood())) { T.ShowToast(this, "您已点过赞了,请先取消!"); } else { mRtaLlGood.setEnabled(false); mRtaLlNotGood.setEnabled(false); mPresenter.updateEvaluateCount(id, evaluateType, evaluate); } break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); /** attention to this below ,must add this**/ UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data); } /** * 屏幕横竖屏切换时避免出现window leak的问题 */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mShareAction.close(); } }
package day44_custom_classes; public class Animal { String type; public void eat() { System.out.println(type +" eats"); } public void eat(String food) { System.out.println("eats " +food); } public void speak(){ System.out.println(type+ " speaks"); } }
package com.thoughtworks.rslist.service; import com.thoughtworks.rslist.domain.RsEvent; import com.thoughtworks.rslist.dto.RsEventDto; import com.thoughtworks.rslist.exception.InvalidIndexException; import java.util.List; /** * Created by wzw on 2020/8/9. */ public interface RsService { public List<RsEventDto> rsList(); public RsEventDto rsListIndex(int index) throws InvalidIndexException; public List<RsEventDto> rsListBetween(int start, int end) throws InvalidIndexException; public RsEventDto rsEvent(RsEvent rsEvent) throws InvalidIndexException; public RsEventDto update(int rsEventId, RsEvent rsEvent) throws Exception; public void delete(int index) throws InvalidIndexException; }
package com.osce.entity; import java.io.Serializable; import java.util.Date; public class SysRoleAuthorityRef implements Serializable { private static final long serialVersionUID = 7455796078372374148L; private Long id; // 主键id private Long authorityId; // 权限资源id private Long roleId; // 资源所属的角色id private Date gmtCreate; // 创建时间 private Date gmtUpdate; // 最后更新时间 public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAuthorityId() { return authorityId; } public void setAuthorityId(Long authorityId) { this.authorityId = authorityId; } public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtUpdate() { return gmtUpdate; } public void setGmtUpdate(Date gmtUpdate) { this.gmtUpdate = gmtUpdate; } }
package com.loginPage.model; public class User { private String username; private String password; private String teleNum; private String emial; //¹¹Ô캯Êý public User(String username, String password, String teleNum, String email) { this.username = username; this.password = password; this.teleNum = teleNum; this.emial = email; } //get and set public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTeleNum() { return teleNum; } public void setTeleNum(String teleNum) { this.teleNum = teleNum; } public String getEmial() { return emial; } public void setEmial(String emial) { this.emial = emial; } }
package com.wechat.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.ssm.util.TokenThread; import com.ssm.wechatpro.object.OutputObject; import com.ssm.wechatpro.util.Constants; import com.ssm.wechatpro.util.WeixinUtil; public class GetMembershipService { @Resource public static OutputObject outputObject = new OutputObject(); public static Map<String,Object> getusedMembership(String cardId) throws Exception{ String result = null; String url = "https://api.weixin.qq.com/card/get?access_token="+TokenThread.accessToken.getToken(); Map<String,Object> bean = new HashMap<>(); Map<String,Object> params = new HashMap<String, Object>(); params.put("card_id",cardId); result = UtilService.net(url, params, "POST"); JSONObject object = JSONObject.fromObject(result); while (!object.getString("errcode").equals("0")) { if (object.getString("errcode").equals(Constants.TOKEINVALID)) { TokenThread.accessToken = WeixinUtil.getAccessToken(TokenThread.appid, TokenThread.appsecret); url = "https://api.weixin.qq.com/card/get?access_token="+TokenThread.accessToken.getToken(); result = UtilService.net(url, params, "POST"); object = JSONObject.fromObject(result); } else { String returnMessage = object.getString("errmsg"); String returnCode = object.getString("errcode"); outputObject.setreturnMessage(returnMessage, returnCode); } } //获取card中的信息 JSONObject card = object.getJSONObject("card"); bean.put("card_type", card.getString("card_type")); //获取card中的member_card JSONObject member_card = card.getJSONObject(card.getString("card_type").toLowerCase()); if(member_card.containsKey("prerogative")){ bean.put("prerogative", member_card.getString("prerogative")); } if(member_card.containsKey("discount")){ bean.put("discount", member_card.getString("discount")); } if(member_card.containsKey("background_pic_url")){ bean.put("background_pic_url", member_card.getString("background_pic_url")); } //获取card中的 member_card base_info中的信息 JSONObject base_info = member_card.getJSONObject("base_info"); bean.put("logo_url", base_info.getString("logo_url")); bean.put("code_type", base_info.getString("code_type")); bean.put("brand_name", base_info.getString("brand_name")); bean.put("title", base_info.getString("title")); bean.put("color", base_info.getString("color")); bean.put("notice", base_info.getString("notice")); if(member_card.containsKey("service_phone")){ bean.put("service_phone", base_info.getString("service_phone")); } bean.put("description", base_info.getString("description")); bean.put("get_limit", base_info.getString("get_limit")); bean.put("can_share", true); bean.put("can_give_friend", base_info.getString("can_give_friend")); bean.put("createTime", base_info.getString("create_time")); if(base_info.containsKey("need_push_on_view")){ bean.put("need_push_on_view", base_info.getString("need_push_on_view")); } bean.put("use_all_locations", base_info.getString("use_all_locations")); //获取获取card中的 member_card base_info date_info JSONObject date_info = base_info.getJSONObject("date_info"); bean.put("date_info", date_info.toString()); bean.put("type", date_info.getString("type")); //获取获取card中的 member_card base_info sku JSONObject sku = base_info.getJSONObject("sku"); bean.put("sku", sku.toString()); bean.put("quantity", sku.getString("total_quantity")); //获取card中的 member_card advanced_info中的信息 JSONObject advanced_info = member_card.getJSONObject("advanced_info"); //获取card中的 member_card advanced_info text_image_list JSONArray text_image_list = advanced_info.getJSONArray("text_image_list"); if(!text_image_list.isEmpty()){ @SuppressWarnings("unchecked") Map<String,Object> textimagelist = (Map<String, Object>) text_image_list.get(0); bean.put("image_url", textimagelist.get("image_url").toString()); bean.put("text", textimagelist.get("text").toString()); } //获取card中的 member_card advanced_info business_service JSONArray businessservice = advanced_info.getJSONArray("business_service"); if(!businessservice.isEmpty()){ String business_service = businessservice.get(0).toString(); for(int i = 1 ;i < businessservice.size();i++){ business_service = business_service+"," + businessservice.get(i).toString(); } bean.put("business_service", business_service); } //获取card中的 member_card bonus_rule if(member_card.containsKey("bonus_rule")){ JSONObject bonus_rule = member_card.getJSONObject("bonus_rule"); bean.put("cost_money_unit", bonus_rule.getString("cost_money_unit")); bean.put("increase_bonus", bonus_rule.getString("increase_bonus")); bean.put("cost_bonus_unit", bonus_rule.getString("cost_bonus_unit")); bean.put("reduce_money", bonus_rule.getString("reduce_money")); bean.put("least_money_to_use_bonus", bonus_rule.getString("least_money_to_use_bonus")); bean.put("max_reduce_bonus", bonus_rule.getString("max_reduce_bonus")); } bean.put("card_id", cardId); return bean; } /** * 修改会员卡信息 * @param map * @throws Exception */ public static void updateMembership(Map<String,Object> map) throws Exception{ String result = null; String url = "https://api.weixin.qq.com/card/update?access_token="+TokenThread.accessToken.getToken(); Map<String,Object> params = new HashMap<String, Object>(); //member_card Map<String, Object> member_card = new HashMap<String,Object>(); //background_pic_url member_card.put("background_pic_url", map.get("background_pic_url")); //base_info Map<String, Object> base_info = new HashMap<String,Object>(); base_info.put("logo_url", map.get("logo_url")); base_info.put("code_type", map.get("code_type")); base_info.put("title", map.get("title")); base_info.put("color", map.get("color")); base_info.put("notice", map.get("notice")); base_info.put("logo_url", map.get("logo_url")); base_info.put("service_phone", map.get("service_phone")); base_info.put("description", map.get("description")); member_card.put("base_info", base_info); //直接获取 member_card.put("prerogative", map.get("prerogative")); Map<String, Object> bonus_rule = new HashMap<String,Object>(); bonus_rule.put("cost_money_unit", map.get("cost_money_unit")); bonus_rule.put("increase_bonus", map.get("increase_bonus")); bonus_rule.put("cost_bonus_unit", map.get("cost_bonus_unit")); bonus_rule.put("reduce_money", map.get("reduce_money")); bonus_rule.put("least_money_to_use_bonus", map.get("least_money_to_use_bonus")); bonus_rule.put("max_reduce_bonus", map.get("max_reduce_bonus")); member_card.put("bonus_rule", bonus_rule); member_card.put("discount", map.get("discount")); params.put("member_card", member_card); params.put("card_id", map.get("card_id")); result = UtilService.net(url, params, "POST"); JSONObject object = JSONObject.fromObject(result); while(!object.getString("errcode").equals("0")){ if(object.getString("errcode").equals(Constants.TOKEINVALID)){ TokenThread.accessToken = WeixinUtil.getAccessToken(TokenThread.appid,TokenThread.appsecret); url = "https://api.weixin.qq.com/card/update?access_token="+TokenThread.accessToken.getToken(); result=UtilService.net(url, params, "POST"); object = JSONObject.fromObject(result); }else{ String returnMessage = object.getString("errmsg"); String returnCode = object.getString("errcode"); outputObject.setreturnMessage(returnMessage, returnCode); } } } /** * 删除会员卡 * @param cardId * @return * @throws Exception */ public static boolean deleteMembership(String cardId) throws Exception{ String result = null; boolean errcode = false; String url = "https://api.weixin.qq.com/card/delete?access_token="+TokenThread.accessToken.getToken(); Map<String,Object> params = new HashMap<String, Object>(); params.put("card_id",cardId); result = UtilService.net(url, params, "POST"); JSONObject object = JSONObject.fromObject(result); while (!object.getString("errcode").equals("0")) { if (object.getString("errcode").equals(Constants.TOKEINVALID)) { TokenThread.accessToken = WeixinUtil.getAccessToken(TokenThread.appid, TokenThread.appsecret); url = "https://api.weixin.qq.com/card/delete?access_token="+ TokenThread.accessToken.getToken(); result = UtilService.net(url, params, "POST"); object = JSONObject.fromObject(result); } else { String returnMessage = object.getString("errmsg"); String returnCode = object.getString("errcode"); outputObject.setreturnMessage(returnMessage, returnCode); } } if (object.getString("errcode").equals("0")) { errcode = true; } return errcode; } /** * 获取已投放卡卷的id * @return * @throws Exception */ @SuppressWarnings("unchecked") public static List<String> getAllMembership() throws Exception{ String result = null; String url = "https://api.weixin.qq.com/card/batchget?access_token="+TokenThread.accessToken.getToken(); Map<String,Object> params = new HashMap<String, Object>(); params.put("offset","0"); params.put("count","50"); List<String> statusList = new ArrayList<String>(); statusList.add("CARD_STATUS_VERIFY_OK"); statusList.add("CARD_STATUS_DISPATCH"); params.put("status_list",statusList); result = UtilService.net(url, params, "POST"); JSONObject object = JSONObject.fromObject(result); while (!object.getString("errcode").equals("0")) { if (object.getString("errcode").equals(Constants.TOKEINVALID)) { TokenThread.accessToken = WeixinUtil.getAccessToken(TokenThread.appid, TokenThread.appsecret); url = "https://api.weixin.qq.com/card/batchget?access_token="+ TokenThread.accessToken.getToken(); result = UtilService.net(url, params, "POST"); object = JSONObject.fromObject(result); } else { String returnMessage = object.getString("errmsg"); String returnCode = object.getString("errcode"); outputObject.setreturnMessage(returnMessage, returnCode); } } int total_num = object.getInt("total_num"); JSONArray card_id_list = object.getJSONArray("card_id_list"); List<String> cardidlist = (List<String>)card_id_list; for(int i = 50;i<total_num;i+=50){ int count = 50 ; int offset = i; params.clear(); params.put("offset",offset); params.put("count",count); params.put("status_list","CARD_STATUS_DISPATCH"); result = UtilService.net(url, params, "POST"); object = JSONObject.fromObject(result); while (!object.getString("errcode").equals("0")) { if (object.getString("errcode").equals(Constants.TOKEINVALID)) { TokenThread.accessToken = WeixinUtil.getAccessToken(TokenThread.appid, TokenThread.appsecret); url = "https://api.weixin.qq.com/card/batchget?access_token="+ TokenThread.accessToken.getToken(); result = UtilService.net(url, params, "POST"); object = JSONObject.fromObject(result); } else { String returnMessage = object.getString("errmsg"); String returnCode = object.getString("errcode"); outputObject.setreturnMessage(returnMessage, returnCode); } } card_id_list = object.getJSONArray("card_id_list"); cardidlist.addAll((List<String>)card_id_list); } return cardidlist; } /** * 创建会员卡 * @throws Exception */ public static String creatMembership(Map<String,Object> map) throws Exception { String result = null; String cardId = null; String url = "https://api.weixin.qq.com/card/create?access_token="+TokenThread.accessToken.getToken(); //params Map<String, Object> params = new HashMap<String, Object>(); //card Map<String, Object> card = new HashMap<String,Object>(); card.put("card_type", map.get("card_type")); //member_card Map<String, Object> member_card = new HashMap<String,Object>(); //background_pic_url member_card.put("background_pic_url", map.get("background_pic_url")); //base_info Map<String, Object> base_info = new HashMap<String,Object>(); base_info.put("logo_url", map.get("logo_url")); base_info.put("brand_name", map.get("brand_name")); base_info.put("code_type", map.get("code_type")); base_info.put("title", map.get("title")); base_info.put("color", map.get("color")); base_info.put("notice", map.get("notice")); base_info.put("logo_url", map.get("logo_url")); base_info.put("service_phone", map.get("service_phone")); base_info.put("use_all_locations", map.get("use_all_locations")); base_info.put("description", map.get("description")); base_info.put("get_limit", map.get("get_limit")); base_info.put("can_give_friend", map.get("can_give_friend")); base_info.put("need_push_on_view", map.get("need_push_on_view")); base_info.put("date_info", map.get("date_info")); base_info.put("sku", map.get("sku")); member_card.put("base_info", base_info); //advanced_info Map<String, Object> advanced_info = new HashMap<String,Object>(); List<Object> text_image_list = new ArrayList<Object>(); Map<String, Object> map1 = new HashMap<String,Object>(); map1.put("image_url", map.get("image_url")); map1.put("text", map.get("text")); text_image_list.add(map1); advanced_info.put("text_image_list", text_image_list); List<Object> time_limit = new ArrayList<Object>(); Map<String, Object> timelimit = new HashMap<String,Object>(); timelimit.put("type", map.get("time_limit")); time_limit.add(timelimit); advanced_info.put("time_limit", time_limit); advanced_info.put("business_service", map.get("business_service")); member_card.put("advanced_info", advanced_info); //直接获取 member_card.put("supply_bonus", map.get("supply_bonus")); member_card.put("supply_balance", map.get("supply_balance")); member_card.put("prerogative", map.get("prerogative")); member_card.put("wx_activate", map.get("wx_activate")); Map<String, Object> bonus_rule = new HashMap<String,Object>(); bonus_rule.put("cost_money_unit", map.get("cost_money_unit")); bonus_rule.put("increase_bonus", map.get("increase_bonus")); bonus_rule.put("cost_bonus_unit", map.get("cost_bonus_unit")); bonus_rule.put("reduce_money", map.get("reduce_money")); bonus_rule.put("least_money_to_use_bonus", map.get("least_money_to_use_bonus")); bonus_rule.put("max_reduce_bonus", map.get("max_reduce_bonus")); member_card.put("bonus_rule", bonus_rule); member_card.put("discount", map.get("discount")); card.put("member_card", member_card); params.put("card", card); result = UtilService.net(url, params, "POST"); JSONObject object = JSONObject.fromObject(result); while (!object.getString("errcode").equals("0")) { if (object.getString("errcode").equals(Constants.TOKEINVALID)) { TokenThread.accessToken = WeixinUtil.getAccessToken(TokenThread.appid, TokenThread.appsecret); url = "https://api.weixin.qq.com/card/create?access_token="+ TokenThread.accessToken.getToken(); result = UtilService.net(url, params, "POST"); object = JSONObject.fromObject(result); } else { String returnMessage = object.getString("errmsg"); String returnCode = object.getString("errcode"); outputObject.setreturnMessage(returnMessage, returnCode); } } cardId = object.getString("card_id"); return cardId; } public static void main(String[] agrs) throws Exception{ System.out.println(getusedMembership("pSU_mtwB0QX7Wc4U4fu_8Vdg_u4M")); } }
/** * by Kocherga Vitalii 2016.12.10 */ import java.util.concurrent.locks.*; import java.util.*; import java.io.*; import java.util.regex.*; public class Main{ public static void main(String[] args){ WordFinder wf = new WordFinder("storage/emulated/0/test"); //change to correct one System.out.println(wf.getWords().toString()); } } /*3. Given the following class: public class IncrementSynchronize { private int value = 0; //getNextValue() } Write three different method options for getNextValue() that will return 'value++', each method needs to be synchronized in a different way. */ class IncrementSincronize { private int value = 0; Object lock1 = new Object(); Lock lock2 = new ReentrantLock(); public synchronized int getNextValueOne(){ return value++; } public int getNextValueTwo(){ synchronized(lock1){ return value++; } } public int getNextValueThree(){ lock2.lock(); try{ return value++; } finally{ lock2.unlock(); } } } class ArrayCopier{ /*2 Write a generic method that takes an array of objects and a collection, and puts all objects in the array into the collection.*/ public static <E> void arrayCopier (E [] array, Collection <E> collection){ for(E element : array){ collection.add(element); } } } /*1. Write a program to find all distinct words from a text file. Ignore chars like ".,/-;:" and Ignore case sensitivity.*/ class WordFinder{ private String filePath; private String text; private final String REGEXP = "(?ui)([\\w]+)"; private StringBuilder builder = new StringBuilder(); private ArrayList<String> list = new ArrayList<>(); public WordFinder(String file){ this.filePath = file; } private void readFile (){ try{ InputStream in = new FileInputStream(filePath); while(true){ int data = in.read(); if(data!=-1){ builder.append((char)data); }else{ in.close(); break;} } } catch (IOException e){ } text = builder.toString(); analizeText(); } public ArrayList<String> getWords(){ readFile(); analizeText(); return list; } private void analizeText(){ Pattern pattern = Pattern.compile(REGEXP); Matcher matcher = pattern.matcher(text); while(true){ if(matcher.find()){ list.add(text.substring(matcher.start(),matcher.end())); }else{ break; } } } }
package com.osce.orm.user.role; import com.osce.dto.user.role.PfRoleDto; import com.osce.entity.SysRole; import com.osce.entity.SysRoleMenu; import com.osce.entity.UserRole; import com.osce.vo.user.role.PfRoleVo; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface PfRoleDao { /** * 获取所有角色 * * @return */ List<PfRoleVo> listRoles(PfRoleDto dto); /** * 查询角色列表 * * @return */ List<PfRoleVo> list(); /** * 根据用户id获取角色level * * @param userId 用户id * @return */ PfRoleVo selectRoleLevel(Long userId); /** * 获取用户所有角色 * * @param userId 用户id * @return */ List<PfRoleVo> listUserRole(@Param("userId") Long userId); /** * 获取角色总数 * * @return */ Long countRoles(PfRoleDto dto); /** * 新增菜单 * * @param dto * @return */ Integer addRole(SysRole dto); /** * 判断是否存在该角色 * * @param roleName 角色名称 * @return */ boolean isExistRole(@Param("roleName") String roleName); /** * 删除角色所有菜单 * * @param roleId 角色id * @return */ int delRoleMenu(@Param("roleId") Long roleId); /** * 保存角色所有菜单 * * @param list * @return */ int saveRoleMenu(@Param("list") List<SysRoleMenu> list); /** * 获取用户角色 * * @param userId * @return */ List<UserRole> listRole(@Param("userId") Long userId); /** * 修改菜单 * * @param dto * @return */ Integer updateRole(SysRole dto); /** * 删除菜单 * * @param roles * @return */ Integer delRole(@Param("list") List<Long> roles); /** * 作废/恢复角色 * * @param state 状态 * @param roleId 角色id * @return */ Integer cancelRole(@Param("state") Integer state, @Param("roleId") Long roleId); /** * 根据角色编码获取角色信息 * * @param code 角色编码 * @return */ PfRoleVo selectRoleInfoByCode(@Param("code") String code); /** * 需要过期提醒 * * @param userId 用户id * @return */ boolean needExpireNotice(@Param("userId") Long userId); /** * 用户拥有角色编码集合 * * @param userId 用户id * @return */ List<String> selectUserRoleCode(@Param("userId") Long userId); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package marblegame; import javax.microedition.lcdui.game.Sprite; import java.util.Vector; import java.io.IOException; /** * * the marble that is dropped by the user */ public class Marble { public int imageId; //the id of the image -- used when serializing and deserializing data public Sprite image; //the image that is moved around on the screen public Point velocity; //the current speed and direction of the marble //Serialization Settings public static final String marbleImageId="imageId"; public static final String marbleLocation="pegLocation"; public static final String marbleVelocity="pegStatus"; public Marble() { image = null; velocity = new Point(); } public Marble (Marble copy) { image = new Sprite(copy.image); velocity = new Point(copy.velocity); imageId = copy.imageId; } //get the marbles current location //I load it into a pooint so it is easier to work with public Point getLocation() { return new Point(image.getRefPixelX(), image.getRefPixelY(),0); } //set the marbles location usign the ref pixel public void setLocation(Point newLocation) { image.setRefPixelPosition( (int)newLocation.x, (int)newLocation.y); } public void setLocation(int x, int y) { image.setRefPixelPosition(x,y); } //create a string of data for storage in the record store public String serialize() { String newLine = GameSettings.NEWLINE; String serializedData =""; serializedData +=marbleImageId+GameSettings.SEPARATOR+imageId+newLine; serializedData +=marbleLocation+GameSettings.SEPARATOR+getLocation().serialize()+newLine; serializedData +=marbleVelocity+GameSettings.SEPARATOR+velocity.serialize()+newLine; return serializedData; } //create a marble from a string of data public void deserialize(String src) throws IOException { Vector values = Split.split(src,""+ GameSettings.NEWLINE); int i=0; Point tmpLocation = new Point(); while(i<values.size()) { Vector nameValuePair = Split.split((String)values.elementAt(i),GameSettings.SEPARATOR); if(nameValuePair.size()>=2) { if ( ((String)nameValuePair.elementAt(0)).equals( marbleImageId)) imageId=Integer.parseInt((String)nameValuePair.elementAt(1)); if ( ((String)nameValuePair.elementAt(0)).equals( marbleLocation )) tmpLocation= Point.parsePoint((String)nameValuePair.elementAt(1)); if ( ((String)nameValuePair.elementAt(0)).equals( marbleVelocity )) velocity= Point.parsePoint((String)nameValuePair.elementAt(1)); } i++; } //re-initialize the images GameImages gameImage = new GameImages(); if(imageId>=0) image =gameImage.createSprite(imageId, tmpLocation); } }
package com.sneaker.mall.api.util; import com.google.common.base.Strings; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * 将汉字转换为拼音工具类 */ public class PingYinUtil { /** * 将字符串中的中文转化为拼音,其他字符不变 * * @param inputString * @return */ public static String getPingYin(String inputString) { HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); format.setCaseType(HanyuPinyinCaseType.LOWERCASE); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); format.setVCharType(HanyuPinyinVCharType.WITH_V); char[] input = inputString.trim().toCharArray(); String output = ""; try { for (int i = 0; i < input.length; i++) { if (java.lang.Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) { String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format); output += temp[0]; } else output += java.lang.Character.toString(input[i]); } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } return output; } /** * 获取汉字串,第一个 * * @param chinese 汉字串 * @return 拼音首字母 */ public static String getFirstSpellForSentence(String chinese) { String res = "X"; if (!Strings.isNullOrEmpty(chinese)) { String charster = chinese.substring(0, 1); res = getFirstSpell(charster); } return res; } /** * 获取汉字串拼音首字母,英文字符不变 * * @param chinese 汉字串 * @return 汉语拼音首字母 */ public static String getFirstSpell(String chinese) { StringBuffer pybf = new StringBuffer(); char[] arr = chinese.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < arr.length; i++) { if (arr[i] > 128) { try { String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat); if (temp != null) { pybf.append(temp[0].charAt(0)); } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pybf.append(arr[i]); } } return pybf.toString().replaceAll("\\W", "").trim(); } /** * 获取汉字串拼音,英文字符不变 * * @param chinese 汉字串 * @return 汉语拼音 */ public static String getFullSpell(String chinese) { StringBuffer pybf = new StringBuffer(); char[] arr = chinese.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < arr.length; i++) { if (arr[i] > 128) { try { pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pybf.append(arr[i]); } } return pybf.toString(); } }
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.*; public class V1LoginCheck { WebDriver driver; ExcelWrite excelWrite; // @BeforeTest // public void setup() // { // System.setProperty("webdriver.chrome.driver", "/home/shijon/Downloads/chromedriver_linux64(1)/chromedriver"); // driver = new ChromeDriver(); // driver.manage().window().maximize(); // driver.get("https://gps.thinture.com"); // driver.manage().deleteAllCookies(); // // } @Test (dataProvider="getlogin") public void login(String Uname,String Passwrd) throws InterruptedException { String arr[]= new String [4]; System.setProperty("webdriver.chrome.driver", "/home/shijon/Downloads/chromedriver_linux64(1)/chromedriver"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://gps.thinture.com"); driver.manage().deleteAllCookies(); WebElement UserName = driver.findElement(By.id("UserName")); UserName.clear(); UserName.sendKeys(Uname); arr[0]=Uname; WebElement Password =driver.findElement(By.id("Password")); Password.clear(); Password.sendKeys(Passwrd); arr[1]=Passwrd; driver.findElement(By.xpath("//input[@type='submit']")).click(); try { driver.findElement(By.xpath("//li[text()='Your Account has been Disabled']")); System.out.println("Account is disable " +Uname); arr[2]="Not Active"; arr[3]="Department not available"; } catch (Exception e) { arr[2]="Active"; System.out.println("Account disabled warning message doesn't appears"); Thread.sleep(2000); try { if(driver.getTitle().contains("Home | Thinture")) { Thread.sleep(2000); WebElement menu= driver.findElement(By.id("pushmenu-button")); menu.click(); System.out.println("menu button clicked"); try { Thread.sleep(2000); WebElement Managmnt= driver.findElement(By.xpath("//a[text()='Management ']")); Managmnt.click(); System.out.println("Management button clicked"); Thread.sleep(2000); driver.findElement(By.xpath("//a[@data-original-title='Department']")).click(); System.out.println("Department button clicked"); arr[3]="Department available"; } catch (Exception ee) { arr[3]="Department not available"; System.out.println("Login performed."); } } else { arr[3]="Department not available"; } } catch (Exception er) { arr[3]="Department not available"; System.out.println("login doesn't perform"); } }finally { WriteData(arr); System.out.println(arr[3]); Thread.sleep(2000); driver.quit(); } } @DataProvider public Object[][] getlogin(){ Object data[][] = ExcelUtils.getTestData("V1Login"); return data; } public void WriteData(String err[]) { try { FileInputStream file = new FileInputStream(new File("/home/shijon/Documents/Test.xls")); HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet sheet = workbook.getSheet("Sheet1"); // sheet.createRow(0).createCell(0).setCellValue("Hiiiii"); // Cell cell = null; //Update the value of cell // for (String s :err){ // if (s!=null){ // sheet.createRow(0).createCell(1).setCellValue(s); // // } // // } int i=1+sheet.getLastRowNum(); System.out.println("last row +1 "+i); for(int j=0;j<err.length;j++) { sheet.createRow(i).createCell(j).setCellValue(err[j]); System.out.println(" read excel "+err[j]); } file.close(); FileOutputStream outFile =new FileOutputStream(new File("/home/shijon/Documents/Test.xls")); workbook.write(outFile); outFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package com.example.demo.repository; import java.util.List; import javax.websocket.server.PathParam; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.example.demo.entity.Course; import com.example.demo.entity.Student; @Repository public interface CourseRepository extends CrudRepository<Course, Long>{ // jpaRepo->pagingandsort->crud ->repository @Override List<Course> findAll(); List<Course> findByStudents(Student student); @Query(value = "SELECT course FROM Course course WHERE upper(course.name) LIKE upper(concat('%',:name,'%')) ") //build query List<Course> findByNameContainingAllIgnoreCase(@PathParam("name") String name); // Tìm kiếm %name% ko phân biệt hoa thường(tất cả trường hợp bỏ qua) //findByNameAllIgnoreCase //tìm kiếm name ko phan biệt hoa,thường //SQL : nó sử dụng upper cho value về chữ hoa và cho các value field về hoa rồi tìm kiếm }
package customer.gajamove.com.gajamove_customer.fragment; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import org.json.JSONArray; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.regex.Pattern; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import customer.gajamove.com.gajamove_customer.Create_Order_Screen; import customer.gajamove.com.gajamove_customer.CurrentJobScreen; import customer.gajamove.com.gajamove_customer.FindDriverScreen; import customer.gajamove.com.gajamove_customer.HomeScreen; import customer.gajamove.com.gajamove_customer.MyApp ; import customer.gajamove.com.gajamove_customer.OrderDetailScreen; import customer.gajamove.com.gajamove_customer.Profile_Screen; import customer.gajamove.com.gajamove_customer.R; import customer.gajamove.com.gajamove_customer.adapter.AdditionalServicesAdapter; import customer.gajamove.com.gajamove_customer.adapter.BigSidePointAdapter; import customer.gajamove.com.gajamove_customer.adapter.ScheduledJobAdapter; import customer.gajamove.com.gajamove_customer.adapter.StopInfoAdapter; import customer.gajamove.com.gajamove_customer.auth.LoginScreen; import customer.gajamove.com.gajamove_customer.models.MyOrder; import customer.gajamove.com.gajamove_customer.models.Prediction; import customer.gajamove.com.gajamove_customer.utils.Constants; import customer.gajamove.com.gajamove_customer.utils.RideDirectionPointsDB; import customer.gajamove.com.gajamove_customer.utils.ShowAdvertisement; import customer.gajamove.com.gajamove_customer.utils.UtilsManager; import cz.msebera.android.httpclient.Header; import static android.content.Context.MODE_PRIVATE; public class ActiveJobTab extends Fragment { private static final String TAG = "ActiveJobTab"; LinearLayout current_job_lay; TextView total_cost_txt,extra_km_label,pickup_location,pickup_location_header,destination_location,destination_location_header,date_text,service_name_txt; LinearLayout additional_lay,view_driver_btn; ListView services_list_view; LinearLayout drop_down_lay,proceed_lay; View home_frame; ListView side_point_list,stop_list,current_job_list; ScheduledJobAdapter scheduledJobAdapter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { home_frame = inflater.inflate(R.layout.active_tab_lay,container,false); current_job_lay = home_frame.findViewById(R.id.current_job_lay); Constants.enableSSL(asyncHttpClient); pickup_location = home_frame.findViewById(R.id.pickup_location_txt); destination_location = home_frame.findViewById(R.id.destination_location_txt); date_text = home_frame.findViewById(R.id.date_text); total_cost_txt = home_frame.findViewById(R.id.total_cost); pickup_location_header = home_frame.findViewById(R.id.pickup_header_text); destination_location_header = home_frame.findViewById(R.id.destination_header_text); service_name_txt = home_frame.findViewById(R.id.service_name); extra_km_label = home_frame.findViewById(R.id.extra_km_label); current_job_list = home_frame.findViewById(R.id.current_job_list); proceed_lay = home_frame.findViewById(R.id.proceed_lay); myOrders = new ArrayList<>(); scheduledJobAdapter = new ScheduledJobAdapter(myOrders,getActivity()); current_job_list.setAdapter(scheduledJobAdapter); proceed_lay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { view_driver_btn.performClick(); } }); side_point_list = home_frame.findViewById(R.id.side_point_list); stop_list = home_frame.findViewById(R.id.stop_list); view_driver_btn = home_frame.findViewById(R.id.view_driver_btn); drop_down_lay = home_frame.findViewById(R.id.drop_down_lay); drop_down_lay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* if (additional_lay.getVisibility()==View.VISIBLE){ additional_lay.setVisibility(View.GONE); ((ImageView)drop_down_lay.getChildAt(0)).setRotation(0); }else { additional_lay.setVisibility(View.VISIBLE); ((ImageView)drop_down_lay.getChildAt(0)).setRotation(180); }*/ Intent intent = new Intent(getActivity(), OrderDetailScreen.class); intent.putExtra("order",myOrder); startActivity(intent); } }); view_driver_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { new RideDirectionPointsDB(getActivity()).clearSavedPoints(); if (m_connected) { if (predictionArrayList.size() > 0){ startActivity(new Intent(getActivity(), CurrentJobScreen.class) .putExtra("order_id", order_id) .putExtra("customer_id", customer_id) .putExtra("stops", predictionArrayList) ); }else { startActivity(new Intent(getActivity(), CurrentJobScreen.class) .putExtra("order_id", order_id) .putExtra("customer_id", customer_id)); } } else { startActivity(new Intent(getActivity(), FindDriverScreen.class) .putExtra("order_id", order_id) .putExtra("customer_id", customer_id) ); } } catch (Exception e){ e.printStackTrace(); } } }); additional_lay = home_frame.findViewById(R.id.additionalservices_lay); services_list_view = home_frame.findViewById(R.id.services_list_view); current_job_lay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); return home_frame; } @Override public void onResume() { super.onResume(); // getCurrentOrderInformation(); getScheduledBookings(); } SharedPreferences sha_prefs; String customer_id; AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); String order_id; boolean haveCurrentJob = false; boolean m_connected = false; MyOrder myOrder; ArrayList<Prediction> predictionArrayList; StopInfoAdapter stopInfoAdapter; BigSidePointAdapter bigSidePointAdapter; ArrayList<MyOrder> myOrders; private void getCurrentOrderInformation() { sha_prefs = getActivity().getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE); customer_id = sha_prefs.getString(Constants.PREFS_CUSTOMER_ID, "0"); String accessToken = "tgs_appkey_amin";//sha_prefs.getString(Constants.PREFS_ACCESS_TOKEN, ""); if (!customer_id.equalsIgnoreCase("0")) { asyncHttpClient.setConnectTimeout(20000); Log.e("current_order", Constants.Host_Address + "customers/my_current_job/" + customer_id + "/"+accessToken+""); asyncHttpClient.get(getActivity(), Constants.Host_Address + "customers/my_current_job/" + customer_id + "/"+accessToken+"", new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { home_frame.findViewById(R.id.no_data_lay).setVisibility(View.GONE); String response = new String(responseBody); Log.e("RESPONSE", response); JSONObject object = new JSONObject(response); String message = object.getString("message"); if (message.toLowerCase().equalsIgnoreCase("invalid key")){ getActivity().getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE).edit().clear().apply(); startActivity(new Intent(getActivity(), LoginScreen.class)); getActivity().finish(); return; } String data = object.getString("data"); if (!data.equalsIgnoreCase("no")) { order_id = data; current_job_lay.setVisibility(View.VISIBLE); haveCurrentJob = true; } else { /* curent_location.setText(""); etLocation.setText(""); curent_location.setVisibility(View.GONE);*/ order_id = "0"; current_job_lay.setVisibility(View.VISIBLE); home_frame.findViewById(R.id.no_data_lay).setVisibility(View.VISIBLE); haveCurrentJob = false; } myOrder = new MyOrder(); JSONObject order_info = object.getJSONObject("order_info"); customer_id = order_info.getString("customer_id"); String meet_location = order_info.getString("meet_location"); String dest_location = order_info.getString("destination"); String order_total = order_info.getString("order_total"); String pickup_address = order_info.getString("pickup_address"); String pickup_contact = order_info.getString("pickup_contact"); String destination_address = order_info.getString("destination_address"); String destination_contact = order_info.getString("destination_contact"); String meet_lat = order_info.getString("meet_lat"); String meet_lon = order_info.getString("meet_long"); String datetime = order_info.getString("meet_datetime"); String total_distance = order_info.getString("total_distance"); String service_id = order_info.getString("service_id"); String service_type_name = order_info.getString("service_name"); String basic_service = order_info.getString("basic_service"); String fixed_cost = order_info.getString("fixed_cost"); String basic_price = order_info.getString("basic_price"); String multiple_stops = order_info.getString("multiple_stops"); if (service_type_name.equalsIgnoreCase("null")){ service_type_name=""; } //total_distance = order_info.getString("total_distance"); //job_state = object.getString("job_state"); myOrder.setOrder_id(order_id); myOrder.setPick_location(meet_location); myOrder.setDest_location(dest_location); myOrder.setTotal_distance(total_distance); myOrder.setOrder_date(datetime); myOrder.setOrder_total(order_total); myOrder.setBasic_price(basic_price); try { String driver_id = object.getJSONObject("driver_info").getString("id"); String driver_full_name = object.getJSONObject("driver_info").getString("full_name"); String driver_profile_img = object.getJSONObject("driver_info").getString("profile_img"); myOrder.setDriver_name(driver_full_name); myOrder.setDriver_id(driver_id); myOrder.setDriver_image(driver_profile_img); } catch (Exception e){ e.printStackTrace(); } try { String[] pick_header = meet_location.split("\\s+"); String[] dest_header = dest_location.split("\\s+"); pickup_location_header.setText((pick_header[0] + " " + pick_header[1]).replaceAll(",","")); destination_location_header.setText((dest_header[0] + " " + dest_header[1]).replaceAll(",","")); pickup_location.setText(meet_location); destination_location.setText(dest_location); } catch (Exception e){ e.printStackTrace(); } /* String name_vehicle="Car"; if (order_info.has("service_type_name")) name_vehicle = order_info.getString("service_type_name"); */ String service_name; try { service_name = object.getJSONObject("service_name").getString("service_name"); } catch (Exception e){ e.printStackTrace(); service_name = ""; } myOrder.setMain_service_name(service_name); myOrder.setService_name(service_name); service_name_txt.setText(service_name); date_text.setText(UtilsManager.parseDateToddMMyyyy(datetime)); total_cost_txt.setText("RM"+order_total); extra_km_label.setText(total_distance+"KM"); predictionArrayList = new ArrayList<>(); String[] pick_header = meet_location.split("\\s+"); Prediction prediction; prediction = new Prediction(); prediction.setLocation_name(meet_location); prediction.setLocation_title((pick_header[0] + " " + pick_header[1]).replaceAll(",","")); prediction.setAddress(pickup_address); prediction.setContact(pickup_contact); predictionArrayList.add(prediction); if (multiple_stops.equalsIgnoreCase("1")){ JSONArray jsonArray = object.getJSONArray("stops_details"); for (int j=0;j<jsonArray.length();j++){ prediction = new Prediction(); String[] header = jsonArray.getJSONObject(j).getString("stop_location").split("\\s+"); prediction.setLocation_title((header[0] + " " + header[1]).replaceAll(",","")); prediction.setLocation_name(jsonArray.getJSONObject(j).getString("stop_location")); prediction.setAddress(jsonArray.getJSONObject(j).getString("stop_address")); prediction.setContact(jsonArray.getJSONObject(j).getString("stop_contact")); predictionArrayList.add(prediction); } } String[] dest_header = dest_location.split("\\s+"); prediction = new Prediction(); prediction.setLocation_name(dest_location); prediction.setLocation_title((dest_header[0] + " " + dest_header[1]).replaceAll(",","")); prediction.setAddress(destination_address); prediction.setContact(destination_contact); predictionArrayList.add(prediction); myOrder.setPredictionArrayList(predictionArrayList); stopInfoAdapter = new StopInfoAdapter(getActivity(), predictionArrayList); stop_list.setAdapter(stopInfoAdapter); UtilsManager.setListViewHeightBasedOnItems(stop_list); // UtilsManager.updateListHeight(getActivity(),60,stop_list,predictionArrayList.size()); /*bigSidePointAdapter = new BigSidePointAdapter(predictionArrayList.size(), getActivity()); side_point_list.setAdapter(bigSidePointAdapter); UtilsManager.setListViewHeightBasedOnItems(side_point_list);*/ // UtilsManager.updateListHeight(getActivity(),55,side_point_list,predictionArrayList.size()); String member_connected = object.getString("is_assigned"); if (member_connected.toLowerCase().equalsIgnoreCase("y")){ m_connected = true; }else { m_connected = false; } myOrder.setIs_assigned(m_connected); /*if (job_state==1){ m_connected = false; }else { m_connected = true; }*/ SharedPreferences prefs = getActivity().getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString(Constants.MEET_LOCATION, meet_location); editor.putString(Constants.DESTINATION, dest_location); editor.putString(Constants.MEET_LAT, meet_lat); editor.putString(Constants.MEET_LONG, meet_lon); editor.putString(Constants.TOTAL, order_total); editor.putString(Constants.PREFS_TOTAL_DISTANCE, total_distance); editor.putString(Constants.ORDER_ID, order_id); editor.apply(); //getMemberSelectionStatus(); try { String[] service_type_name_list = service_type_name.split(","); String[] basic_service_list = basic_service.split(","); String[] cost_list = fixed_cost.split(","); String additional_services = "", additional_prices = ""; for (int i = 0; i < service_type_name_list.length; i++) { if (!service_type_name_list[i].toString().trim().equalsIgnoreCase("")) { additional_services = additional_services + service_type_name_list[i] + ","; additional_prices = additional_prices + cost_list[i] + ","; } } myOrder.setAdditional_prices(additional_prices); myOrder.setAdditional_services(additional_services); } catch (Exception e){ e.printStackTrace(); } /* if (additional_services.length() > 1){ String[] services = additional_services.split(Pattern.quote(",")); AdditionalServicesAdapter additionalServicesAdapter = new AdditionalServicesAdapter(services,getActivity()); services_list_view.setAdapter(additionalServicesAdapter); *//* LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) services_list_view.getLayoutParams(); int height = 60 * services.length; layoutParams.height = height; services_list_view.setLayoutParams(layoutParams);*//* // UtilsManager.setListViewHeightBasedOnChildren(services_list_view); additional_lay.setVisibility(View.GONE); }else { additional_lay.setVisibility(View.GONE); }*/ ArrayList<MyOrder> myOrders = new ArrayList<>(); myOrders.add(myOrder); scheduledJobAdapter = new ScheduledJobAdapter(myOrders,getActivity()); current_job_list.setAdapter(scheduledJobAdapter); } catch (Exception e) { e.printStackTrace(); new RideDirectionPointsDB(getActivity()).clearSavedPoints(); current_job_lay.setVisibility(View.GONE); home_frame.findViewById(R.id.no_data_lay).setVisibility(View.VISIBLE); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { try { String response = new String(responseBody); JSONObject object = new JSONObject(response); Log.e("response failed", object.toString()); current_job_lay.setVisibility(View.GONE); home_frame.findViewById(R.id.no_data_lay).setVisibility(View.VISIBLE); } catch (Exception e) { e.printStackTrace(); } } }); } } ShowAdvertisement showAdvertisement; @Override public void onAttach(@NonNull Context context) { super.onAttach(context); try { showAdvertisement = (ShowAdvertisement) context; } catch (Exception e){ e.printStackTrace(); } } private void getScheduledBookings() { String customerId = getActivity().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE).getString(Constants.PREFS_CUSTOMER_ID,""); asyncHttpClient.setConnectTimeout(20000); Log.e(TAG, "getScheduledBookings: "+ Constants.Host_Address + "orders/customer_scheduled_orders/"+UtilsManager.getApiKey(getActivity())+"/"+customerId+"/1"); asyncHttpClient.get(getActivity(), Constants.Host_Address + "orders/customer_scheduled_orders/"+UtilsManager.getApiKey(getActivity())+"/"+customerId+"/1", new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); // Sh("Loading Orders..."); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { // hideDialoge(); home_frame.findViewById(R.id.no_data_lay).setVisibility(View.GONE); String json = new String(responseBody); UtilsManager.isInvalidKey(getActivity(),json); JSONObject object = new JSONObject(json); Log.e("response",json); if (object.has("data")) { JSONArray array = object.getJSONArray("data"); myOrders = new ArrayList<>(); if (array.length() > 0) getActivity().getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE).edit().putBoolean(Constants.PROFILE_EDITABLE,false).apply(); for (int i=0;i<array.length();i++) { String order_num = array.getJSONObject(i).getString("order_id"); String order_meet = array.getJSONObject(i).getString("meet_location"); String order_destination = array.getJSONObject(i).getString("destination"); String order_datetime = array.getJSONObject(i).getString("datetime_ordered"); String meet_datetime = array.getJSONObject(i).getString("meet_datetime"); String order_total = array.getJSONObject(i).getString("order_total"); String pickup_address = array.getJSONObject(i).getString("pickup_address"); String pickup_contact = array.getJSONObject(i).getString("pickup_contact"); String destination_address = array.getJSONObject(i).getString("destination_address"); String destination_contact = array.getJSONObject(i).getString("destination_contact"); String service_name = array.getJSONObject(i).getString("service_id"); String service_type_name = array.getJSONObject(i).getString("service_name"); if (service_type_name.equalsIgnoreCase("null")) service_type_name = ""; String total_distance = array.getJSONObject(i).getString("total_distance"); String basic_service = array.getJSONObject(i).getString("basic_service"); String fixed_cost = array.getJSONObject(i).getString("fixed_cost"); String basic_price = array.getJSONObject(i).getString("basic_price"); String member_assigned = array.getJSONObject(i).getString("is_assigned"); ArrayList<Prediction> predictionArrayList = new ArrayList<>(); Prediction prediction; String[] pick_header = order_meet.split("\\s+"); prediction = new Prediction(); prediction.setLocation_name(order_meet); prediction.setLocation_title((pick_header[0] + " " + pick_header[1]).replaceAll(",","")); prediction.setAddress(pickup_address); prediction.setContact(pickup_contact); predictionArrayList.add(prediction); String isMulti = array.getJSONObject(i).getString("multiple_stops"); if (isMulti.equalsIgnoreCase("1")){ JSONArray jsonArray = array.getJSONObject(i).getJSONArray("stops_details"); for (int j=0;j<jsonArray.length();j++){ prediction = new Prediction(); prediction.setLocation_name(jsonArray.getJSONObject(j).getString("stop_location")); pick_header = jsonArray.getJSONObject(j).getString("stop_location").split("\\s+"); prediction.setLocation_title((pick_header[0] + " " + pick_header[1]).replaceAll(",","")); prediction.setAddress(jsonArray.getJSONObject(j).getString("stop_address")); prediction.setContact(jsonArray.getJSONObject(j).getString("stop_contact")); predictionArrayList.add(prediction); } } pick_header = order_destination.split("\\s+"); prediction = new Prediction(); prediction.setLocation_name(order_destination); prediction.setLocation_title((pick_header[0] + " " + pick_header[1]).replaceAll(",","")); prediction.setAddress(destination_address); prediction.setContact(destination_contact); predictionArrayList.add(prediction); String driver_id = array.getJSONObject(i).getString("driver_id"); String driver_full_name = array.getJSONObject(i).getString("driver_full_name"); String driver_profile_img = array.getJSONObject(i).getString("driver_profile_img"); String vehicle_plate_number = array.getJSONObject(i).getString("vehicle_plate_number"); MyOrder order = new MyOrder(); order.setPredictionArrayList(predictionArrayList); order.setOrder_id(order_num); order.setPick_location(order_meet); order.setDest_location(order_destination); order.setOrder_date(meet_datetime); order.setOrder_total(order_total); order.setService_name(service_name); order.setMain_service_name(service_name); order.setTotal_distance(total_distance); order.setBasic_price(basic_price); order.setDriver_id(driver_id); order.setDriver_image(driver_profile_img); order.setDriver_name(driver_full_name); order.setDriver_plate(vehicle_plate_number); if (member_assigned.equalsIgnoreCase("N")) order.setIs_assigned(false); else order.setIs_assigned(true); String additional_services = "",additional_prices=""; try { String[] service_names = service_type_name.split(","); String[] service_types = basic_service.split(","); String[] cost_list = fixed_cost.split(","); for (int j=0;j<service_names.length;j++){ if (!service_names[j].trim().toString().equalsIgnoreCase("")) { additional_services = additional_services + service_names[j] + ","; additional_prices = additional_prices + cost_list[j] + ","; } } } catch (Exception e){ e.printStackTrace(); } order.setAdditional_services(additional_services); order.setAdditional_prices(additional_prices); myOrders.add(order); } if (myOrders.size()==0) home_frame.findViewById(R.id.no_data_lay).setVisibility(View.VISIBLE); scheduledJobAdapter = new ScheduledJobAdapter(myOrders,getActivity()); current_job_list.setAdapter(scheduledJobAdapter); } else { getActivity().getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE).edit().putBoolean(Constants.PROFILE_EDITABLE,true).apply(); home_frame.findViewById(R.id.no_data_lay).setVisibility(View.VISIBLE); /* String phone = getActivity().getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE).getString(Constants.PREFS_USER_MOBILE,""); if (phone.equalsIgnoreCase("")){ startActivity(new Intent(getActivity(), Profile_Screen.class).putExtra("back",true)); Toast.makeText(getActivity(),"Add Phone Number",Toast.LENGTH_SHORT).show(); }else { boolean show_ad = getActivity().getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE).getBoolean(Constants.SHOW_AD,false); startActivity(new Intent(getActivity(), Create_Order_Screen.class).putExtra("show_ads",show_ad)); }*/ } } catch (Exception e) { getActivity().getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE).edit().putBoolean(Constants.PROFILE_EDITABLE,true).apply(); Log.e(TAG," "+e.getMessage()); home_frame.findViewById(R.id.no_data_lay).setVisibility(View.VISIBLE); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { try { getActivity().getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE).edit().putBoolean(Constants.PROFILE_EDITABLE,true).apply(); // hideDialoge(); String json = new String(responseBody); Log.e("RESPONSE",json); JSONObject object = new JSONObject(json); home_frame.findViewById(R.id.no_data_lay).setVisibility(View.VISIBLE); } catch (Exception e) { e.printStackTrace(); } } }); } }
package dng.deongeori.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.gallery.dao.GalleryBean; import com.gallery.dao.GalleryDAO; import com.mtory.action.Action; import com.mtory.action.ActionForward; import dng.deongeori.DeongeoriBean; import dng.deongeori.DeongeoriDAO; public class DeongeoriListAction implements Action { @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html; charset=UTF-8"); request.setCharacterEncoding("UTF-8"); String dng_id = request.getParameter("dng_id"); DeongeoriDAO dngdao = new DeongeoriDAO(); DeongeoriBean dngbean = dngdao.selectDeongeori(dng_id); GalleryDAO gd=new GalleryDAO(); List<GalleryBean> galleryList = gd.getGalleryList(dng_id); GalleryBean gallery = gd.getGalMostLiked(dng_id); HttpSession session = request.getSession(); session.setAttribute("dng_id", dngbean.getDng_id()); request.setAttribute("dngbean", dngbean); request.setAttribute("gd", galleryList); /*if((galleryList != null)&&(galleryList.size()>0)){ request.setAttribute("gc", galleryList.get(0)); }*/ if(gallery != null){ request.setAttribute("gc", gallery); request.setAttribute("gm", gallery); } ActionForward forward = new ActionForward(); forward.setRedirect(false); forward.setPath("./deongeori/deongeori_main_g2.jsp?dng_id="+dng_id); return forward; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mytest.iodemo; import com.mytest.common.utils.ConfigProperties; /** * @author liqingyu * @since 2020/03/06 */ public class NioDemoConfig extends ConfigProperties { static ConfigProperties singleton = new NioDemoConfig("/system.properties"); private NioDemoConfig(String fileName) { super(fileName); super.loadFromFile(); } public static final String SOCKET_SEND_FILE = singleton.getValue("socket.send.file"); public static final String SOCKET_RECEIVE_FILE = singleton.getValue("socket.receive.file"); public static final String SOCKET_RECEIVE_PATH = singleton.getValue("socket.receive.path"); public static final int SEND_BUFFER_SIZE = singleton.getIntValue("send.buffer.size"); public static final int SERVER_BUFFER_SIZE = singleton.getIntValue("server.buffer.size"); public static final String SOCKET_SERVER_IP = singleton.getValue("socket.server.ip"); public static final int SOCKET_SERVER_PORT = singleton.getIntValue("socket.server.port"); }
package com.dns.feedbox; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.integration.support.json.Jackson2JsonObjectMapper; /** * Created by dinusha on 9/12/16. */ public class FeedMapper { public static Jackson2JsonObjectMapper getMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); return new Jackson2JsonObjectMapper(mapper); } }
package com.hesoyam.pharmacy.appointment.exceptions; public class CheckupCancellationPeriodExpiredException extends Exception{ public CheckupCancellationPeriodExpiredException(Long id){ super(String.format("Checkup with ID '%s' cannot be cancelled 24h before reserved time",id)); } }
package com.skt.test; import org.junit.Test; public class Test02 { @Test public void Correctness(){ String [] S = { "123456" // 162534 ,"130" // 103 ,"100000000" // 100000000 ,"953568128" // 985231586 ,"95356812" // 92513856 } ; for(String s : S){ System.out.println(new Test02().solution(Integer.parseInt(s))); System.out.println("--"); } } // solution public int solution(int A) { String strSrc = String.valueOf(A); String strDes = ""; int strSrcLen = strSrc.length(); for(int i=0;i<strSrcLen;i++){ int fromIdx = i; int backIdx = (strSrcLen-i)-1; if(fromIdx<backIdx){ strDes += String.valueOf(strSrc.charAt(fromIdx)); strDes += String.valueOf(strSrc.charAt(backIdx)); }else if(fromIdx==backIdx){ strDes += String.valueOf(strSrc.charAt(fromIdx)); }else{ break; } } return Integer.parseInt(strDes); } }
package pattern_test.iterator; /** * Description: * * @author Baltan * @date 2019-04-03 15:32 */ public class Test1 { public static void main(String[] args) { LanguageRepository languageRepository = new LanguageRepository(); Iterator<String> iterator1 = languageRepository.iterator(); while (iterator1.hasNext()) { System.out.println(iterator1.next()); } System.out.println("------------------"); while (iterator1.hasPrevious()) { System.out.println(iterator1.previous()); } } }
package net.wrap_trap.calcite_arrow_sample; /** * Created by masayuki on 2017/12/17. */ public interface Filterable { int[][] filter(); }
import sut.OS.potoki.Set; import sut.OS.potoki.SetImpl; import java.util.ArrayList; public class jmn { public static void main(String[] args) throws InterruptedException { int threads = 10; Set set = new SetImpl(); ArrayList<Thread> threadArrayList = new ArrayList<>(); for (int i = 0; i < threads; i++) { final int index = i; Thread thread = new Thread(() -> { for (int j = 10 * index; j < 10 + 10 * index; j++) { set.add(j); System.out.println(set.contains(j) + " " + j); set.remove(j); } }); thread.start(); threadArrayList.add(thread); } for (Thread thread : threadArrayList) { thread.join(); } } }
/* * A java application to compress css code to prepare it for being uploaded to server * Since transfer of bits of data affect the speed of loading webpage * So it is necessary to compress css files to decrease its size... */ package css.compressor; import java.awt.*; import java.awt.event.*; /** * @author hitesh * Uploaded to : https://github.com/hiteshnayak305 repository=CSS Compressor */ public class CSSCompressor extends Frame implements ActionListener { //containers Panel center; Panel north; //declare Layouts BorderLayout b; GridLayout g; GridLayout g2; //declare menubar and items MenuBar mb; //Menu Menu file, edit, view, help; //Menuitems //file MenuItem nw, opn, sv, ext; //edit MenuItem cut, cpy, pst, slctAll; //view CheckboxMenuItem fullscr; CheckboxMenuItem stbarview; //help //buttons Button com,clr; //TextArea TextArea mainTxt; TextArea comTxt; //string buffer String cp; //statusbar Label stbar; /** * */ public CSSCompressor() { super("CSS Compressor"); setSize(700, 500); setBackground(new Color(250, 250, 250)); setVisible(true); cp = ""; //setting Layout b = new BorderLayout(10, 5); //hsp,vsp setLayout(b); g = new GridLayout(2,1,10,5); center = new Panel(g); g2 = new GridLayout(1,10,10,5); north = new Panel(g2); //Play background audio //AudioClip ac; //ac = getAudioClip(getDocumentBase(),"a.au"); //ac.loop(); /**** set menu bar ****/ mb = new MenuBar(); setMenuBar(mb); //set file menu file = new Menu("File"); mb.add(file); //set menu items nw = new MenuItem("New"); nw.addActionListener(this); file.add(nw); opn = new MenuItem("Open"); opn.addActionListener(this); file.add(opn); sv = new MenuItem("Save"); sv.addActionListener(this); file.add(sv); MenuItem sprtr = new MenuItem("-"); file.add(sprtr); ext = new MenuItem("Exit"); ext.addActionListener(this); file.add(ext); //set edit menu edit = new Menu("Edit"); mb.add(edit); //set menuitems cut = new MenuItem("Cut"); cut.addActionListener(this); edit.add(cut); cpy = new MenuItem("Copy"); cpy.addActionListener(this); edit.add(cpy); pst = new MenuItem("Paste"); pst.addActionListener(this); edit.add(pst); slctAll = new MenuItem("Select All"); slctAll.addActionListener(this); edit.add(slctAll); //set view menu view = new Menu("View"); mb.add(view); //set menu items fullscr = new CheckboxMenuItem("Show full screen"); view.add(fullscr); stbarview = new CheckboxMenuItem("Show Status Bar"); view.add(stbarview); //set help menu //buttons com = new Button("Compress"); com.addActionListener(this); clr = new Button("Clear"); clr.addActionListener(this); north.add(com); north.add(clr); north.add(new Label()); north.add(new Label()); north.add(new Label()); north.add(new Label()); north.add(new Label()); north.add(new Label()); north.add(new Label()); add(north,BorderLayout.NORTH); /**** main workspace ****/ String init = "class c{\n\tpublic static void main(){\n\t\tSystem.out.println(\"Hello World!\");\n\t}\n}"; //textArea mainTxt = new TextArea(init, 700, 240, TextArea.SCROLLBARS_BOTH); center.add(mainTxt); comTxt = new TextArea("", 700, 240, TextArea.SCROLLBARS_VERTICAL_ONLY); comTxt.setEditable(false); center.add(comTxt); add(center,BorderLayout.CENTER); /**** status bar ****/ stbar = new Label("Ready", Label.LEFT); add(stbar, BorderLayout.SOUTH); } /** * compress method to remove whitespace and comment lines * @param s string extracted from mainText Field * @return string without waste memory */ String compress(String s){ if(s == null || s.length() < 1){ return null; } s = s.replaceAll("/*.*?=*/", ""); s = s.replaceAll("//.*?=\n", ""); s = s.replaceAll(" ", ""); s = s.replaceAll("\t", ""); s = s.replaceAll("\n", ""); return s; } /** * to cut out selected string * @param s string extracted from mainText area * @param start start of selected text * @param end end of selected text * @return string with removed selected text */ String remove(String s,int start,int end){ StringBuilder sb = new StringBuilder(); sb.append(s.substring(0, start)); sb.append(s.substring(end,s.length())); return sb.toString(); } /** * @param args the command line arguments */ public static void main(String[] args) { CSSCompressor c; c = new CSSCompressor(); } /** * ActionListener implemented method * perform on actions of menu items and buttons * @param e */ @Override public void actionPerformed(ActionEvent e) { switch (e.getActionCommand()) { case "New": break; case "Open": break; case "Save": break; case "Exit": break; case "Cut": cp = mainTxt.getSelectedText(); int start = mainTxt.getSelectionStart(); int end = mainTxt.getSelectionEnd(); String temp1 = remove(mainTxt.getText(),start,end); mainTxt.setText(temp1); stbar.setText("Cut:\""+cp); break; case "Copy": cp = mainTxt.getSelectedText(); stbar.setText("Copied: \"" + cp + "\""); break; case "Paste": mainTxt.insert(cp, mainTxt.getCaretPosition()); break; case "Select All": mainTxt.select(0, mainTxt.getText().length()); stbar.setText("Selected All"); break; case "Compress": String temp2 = compress(mainTxt.getText()); comTxt.setText(temp2); stbar.setText("Compressed"); break; case "Clear": mainTxt.setText(""); comTxt.setText(""); stbar.setText("Ready"); break; default: //nothing } } }