text
stringlengths
10
2.72M
package cn.itcast.core.service.cart; import cn.itcast.core.pojo.cart.Cart; import cn.itcast.core.pojo.item.Item; import java.util.List; public interface CartService { /** * 获取库存对象 */ public Item findOne(Long id); /** * 填充购物车列表需要回显的数据 */ List<Cart> setAttributeForCart(List<Cart> cartList); /** * 将购物车同步到redis中 */ void mergeCartList(String username,List<Cart> cartList); /** * 从redis中取出购物车 */ List<Cart> findCartListFromRedis(String username); /* 添加到我的收藏 */ public void addGoodsToMyFavorite(String username,Long itemId); }
package com.uniinfo.cloudplat.eo; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * UserEqMain entity. @author hongzhou.yi */ @Entity @Table(name = "user_eq_main") public class UserEqMainEO implements java.io.Serializable { private static final long serialVersionUID = 1L; // Fields private String recordId; private String userId; private String isBindEq; private String eqId; private String eqType; private String iosToken; private Date recordTime; // Constructors /** default constructor */ public UserEqMainEO() { } /** minimal constructor */ public UserEqMainEO(String recordId, String userId) { this.recordId = recordId; this.userId = userId; } /** full constructor */ public UserEqMainEO(String recordId, String userId, String isBindEq, String eqId, String eqType, String iosToken, Date recordTime) { this.recordId = recordId; this.userId = userId; this.isBindEq = isBindEq; this.eqId = eqId; this.eqType = eqType; this.iosToken = iosToken; this.recordTime = recordTime; } // Property accessors @Id @Column(name = "RECORD_ID", unique = true, nullable = false) public String getRecordId() { return this.recordId; } public void setRecordId(String recordId) { this.recordId = recordId; } @Column(name = "USER_ID", nullable = false) public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } @Column(name = "IS_BIND_EQ") public String getIsBindEq() { return this.isBindEq; } public void setIsBindEq(String isBindEq) { this.isBindEq = isBindEq; } @Column(name = "EQ_ID") public String getEqId() { return this.eqId; } public void setEqId(String eqId) { this.eqId = eqId; } @Column(name = "EQ_TYPE") public String getEqType() { return this.eqType; } public void setEqType(String eqType) { this.eqType = eqType; } @Column(name = "IOS_TOKEN") public String getIosToken() { return this.iosToken; } public void setIosToken(String iosToken) { this.iosToken = iosToken; } @Column(name = "RECORD_TIME") public Date getRecordTime() { return this.recordTime; } public void setRecordTime(Date recordTime) { this.recordTime = recordTime; } }
package Problem_1780; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static int N; static int[][] arr; static int[] answers = new int[3]; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); arr = new int[N][N]; for(int i = 0; i < N; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); for(int j = 0; j<N; j++) { arr[i][j] = Integer.parseInt(st.nextToken()); } } answer(0, 0, N); for(int i = 0; i <3; i++) System.out.println(answers[i]); } static void answer(int x, int y, int N) { if(N == 1) { answers[arr[x][y] + 1]++; } else { int num = arr[x][y]; boolean flag = true; for(int i = x; i<x+N; i++) { for(int j = y; j<y+N;j++) { if(arr[i][j] != num) { flag = false; break; } } } if(flag) { answers[num+1]++; return; } else { int M = N/3; for(int i = 0; i <3 ; i++) { for(int j = 0 ; j<3; j++) { answer(x+i*M, y+j*M, M); } } } } } }
public class Triangle { public static void printTriangle(int x) { int i; int j; int k; for(i=0; i<2*x+1; i++) { k=i; if(i>x) { k=2*x-i; } for(j=0; j<2*k+1; j++) { System.out.print("*"); } if(i!=x) { System.out.print("*"); } System.out.println(""); } } public static void main(String[] args) { printTriangle(10); } }
package com.yandex.disk.client.exceptions; public class FileModifiedException extends WebdavException { public FileModifiedException(String msg) { super(msg); } }
package com.cedo.cat2shop.util; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import java.util.Map; /** * @Author chendong * @date 19-3-19 下午11:48 */ public class PageUtil { public static IPage getPage(Map<String, Object> params) { Integer current = Integer.valueOf((String)params.get("page")); Integer limit = Integer.valueOf((String)params.get("limit")); return new Page(current, limit); } }
package com.digiburo.spring.demo.mvc.web; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/hello") public class HelloController { @RequestMapping(method = RequestMethod.GET) public String printWelcome(ModelMap model) { LOGGER.info("entering printWelcome"); System.out.println("println"); model.addAttribute("message", "Hello world2!"); return "hello"; } // public static final Logger LOGGER = LoggerFactory.getLogger(HelloController.class); }
/* * Ara - Capture Species and Specimen Data * * Copyright © 2009 INBio (Instituto Nacional de Biodiversidad). * Heredia, Costa Rica. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.ara.facade.label.impl; import javax.ejb.EJB; import org.inbio.ara.dto.label.LabelDTO; import org.inbio.ara.dto.label.OriginalLabelDTO; import org.inbio.ara.facade.label.*; import javax.ejb.Stateless; import java.util.Calendar; import java.util.List; import org.inbio.ara.dto.inventory.SpecimenDTOFactory; import org.inbio.ara.dto.label.HistoryLabelDTO; import org.inbio.ara.dto.label.HistoryLabelDTOFactory; import org.inbio.ara.dto.label.LabelDTOFactory; import org.inbio.ara.dto.label.OriginalLabelDTOFactory; import org.inbio.ara.eao.label.HistoryLabelEAOLocal; import org.inbio.ara.eao.label.LabelEAOLocal; import org.inbio.ara.eao.label.OriginalLabelEAOLocal; import org.inbio.ara.eao.specimen.SpecimenEAOLocal; import org.inbio.ara.persistence.label.Label; import org.inbio.ara.persistence.label.OriginalLabel; import org.inbio.ara.persistence.label.LabelHistory; /** * Jueves 21-01-10 16:00 * @author pcorrales */ @Stateless public class LabelFacadeImpl implements LabelFacadeRemote { @EJB //inyectar interfaces local -remote private SpecimenEAOLocal specimenEAO; @EJB // private LabelEAOLocal labelEAO; @EJB // private OriginalLabelEAOLocal originalLabelEAO; @EJB // private HistoryLabelEAOLocal historylLabelEAO; /*factory of DTO */ private SpecimenDTOFactory specimenDTOFactory = new SpecimenDTOFactory(); private LabelDTOFactory labelDTOFactory = new LabelDTOFactory(); private OriginalLabelDTOFactory originalLabelDTOFactory = new OriginalLabelDTOFactory (); private HistoryLabelDTOFactory historylLabelDTOFactory = new HistoryLabelDTOFactory(); /** * @return the specimenEAO */ public SpecimenEAOLocal getSpecimenEAO() { return specimenEAO; } /** * @param specimenEAO the specimenEAO to set */ public void setSpecimenEAO(SpecimenEAOLocal specimenEAO) { this.specimenEAO = specimenEAO; } /** * @return the labelEAO */ public LabelEAOLocal getLabelEAO() { return labelEAO; } /** * @param labelEAO the labelEAO to set */ public void setLabelEAO(LabelEAOLocal labelEAO) { this.labelEAO = labelEAO; } /** * @return the originalLabelEAO */ public OriginalLabelEAOLocal getOriginalLabelEAO() { return originalLabelEAO; } /** * @param originalLabelEAO the originalLabelEAO to set */ public void setOriginalLabelEAO(OriginalLabelEAOLocal originalLabelEAO) { this.originalLabelEAO = originalLabelEAO; } /** * @return the specimenDTOFactory */ public SpecimenDTOFactory getSpecimenDTOFactory() { return specimenDTOFactory; } /** * @param specimenDTOFactory the specimenDTOFactory to set */ public void setSpecimenDTOFactory(SpecimenDTOFactory specimenDTOFactory) { this.specimenDTOFactory = specimenDTOFactory; } /** * @return the labelDTOFactory */ public LabelDTOFactory getLabelDTOFactory() { return labelDTOFactory; } /** * @param labelDTOFactory the labelDTOFactory to set */ public void setLabelDTOFactory(LabelDTOFactory labelDTOFactory) { this.labelDTOFactory = labelDTOFactory; } /** * @return the originalLabelDTOFactory */ public OriginalLabelDTOFactory getOriginalLabelDTOFactory() { return originalLabelDTOFactory; } /** * @param originalLabelDTOFactory the originalLabelDTOFactory to set */ public void setOriginalLabelDTOFactory(OriginalLabelDTOFactory originalLabelDTOFactory) { this.originalLabelDTOFactory = originalLabelDTOFactory; } /** * @param selectionListEntityId * @param collectionId * @return */ /** * @return the historylLabelDTOFactory */ public HistoryLabelDTOFactory getHistorylLabelDTOFactory() { return historylLabelDTOFactory; } /** * @param historylLabelDTOFactory the historylLabelDTOFactory to set */ public void setHistorylLabelDTOFactory(HistoryLabelDTOFactory historylLabelDTOFactory) { this.historylLabelDTOFactory = historylLabelDTOFactory; } /** * @return the historylLabelEAO */ public HistoryLabelEAOLocal getHistorylLabelEAO() { return historylLabelEAO; } /** * @param historylLabelEAO the historylLabelEAO to set */ public void setHistorylLabelEAO(HistoryLabelEAOLocal historylLabelEAO) { this.historylLabelEAO = historylLabelEAO; } /** * created tha label of specimen information * @param labelDTO */ public Long saveLabel(LabelDTO labelDTO) { Label label = this.getLabelDTOFactory().createPlainEntity(labelDTO); this.getLabelEAO().create(label); return label.getLabelId(); } /** * created tha OriginalLabel of specimen information, this label is not modificable * @param OriginalLabelDTO */ public Long saveOriginalLabel(OriginalLabelDTO originalLabelDTO) { OriginalLabel originalLabel = this.getOriginalLabelDTOFactory().createPlainEntity(originalLabelDTO); this.getOriginalLabelEAO().create(originalLabel); return originalLabel.getOriginalLabelId(); } /** * created tha OriginalLabel of specimen information, this label is not modificable * @param OriginalLabelDTO */ public void updateLabel(LabelDTO labelDTO) { Label label = this.labelEAO.findById(Label.class, labelDTO.getLabelId()); Label newLabel = this.labelDTOFactory.updateEntityWithPlainValues(labelDTO, label); this.getLabelEAO().update(newLabel); } /** * created tha OriginalLabel of specimen information, this label is not modificable * @param OriginalLabelDTO */ public void updateOriginalLabel(OriginalLabelDTO labelDTO) { OriginalLabel label = this.originalLabelEAO.findById(OriginalLabel.class, labelDTO.getOriginalLabelID()); OriginalLabel newLabel = this.originalLabelDTOFactory.updateEntityWithPlainValues(labelDTO, label); this.originalLabelEAO.update(newLabel); } /** * created tha OriginalLabel of specimen information, this label is not modificable * this labels is the result of label and label type corrector * @param HistoryLabelDTO */ public void saveHistoryLabel(HistoryLabelDTO historyLabelDTO){ //buscar los correctores LabelHistory history = this.getHistorylLabelDTOFactory().createPlainEntity(historyLabelDTO); this.getHistorylLabelEAO().create(history); } /** * counts the labels * @return */ public Long countLabels() { return this.getLabelEAO().count(Label.class); } /** * find the label * @param id * @param initialDate * @param finalDate * @return */ public List<Long> findByLabelTypeId(Long id, Calendar initialDate, Calendar finalDate) { return this.getLabelEAO().findByLabelTypeId(id, initialDate, finalDate); } /** * find the label match with the id * @param labelDTO */ public LabelDTO findByLabelId(Long labelId) { return this.getLabelDTOFactory().createDTO(this.getLabelEAO().findById(Label.class, labelId)); } /** * find tje label match with the id * @param labelDTO */ public OriginalLabelDTO findByOriginalLabelId(Long labelId) { return this.getOriginalLabelDTOFactory().createDTO(this.getOriginalLabelEAO().findById(OriginalLabel.class, labelId)); } public List<HistoryLabelDTO> getAllLabelHistoryPaginated(int first, int totalResults, Long labelId, Long collectionId) { List<LabelHistory> sList = this.getHistorylLabelEAO().findLabelHistoryPaginatedFilterAndOrderByAncestorId(labelId, first, totalResults, null, collectionId); if (sList == null) return null; List<HistoryLabelDTO> updated = this.getHistorylLabelDTOFactory().createDTOList(sList); return updated; } /** * get the list of labels associated with a current label * @param first * @param totalResults * @param labelId * @param collection * @param labelTypeId * @return */ public List<LabelDTO> getAllLabelPaginated(int first,int totalResults,Long labelId, Long collection,Long labelTypeId) { //paginated the label by id of the labels String[] campos = {"labelId"}; List<Label> sList = this.getLabelEAO().findAllPaginatedFilterAndOrderByAncestorId(labelId, first, totalResults,campos,collection,labelTypeId); if (sList == null) return null; List<LabelDTO> updated = this.getLabelDTOFactory().createDTOList(sList); return updated; } }
//package com.union.express.commons.bean.oauth2; // //import com.union.express.web.oauth.security.ClientDetailsService; //import com.union.express.web.oauth.security.CustomAuthenticationEntryPoint; //import com.union.express.web.oauth.security.CustomLogoutSuccessHandler; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.beans.factory.annotation.Qualifier; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; //import org.springframework.security.authentication.AuthenticationManager; //import org.springframework.security.config.annotation.web.builders.HttpSecurity; //import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; //import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; //import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; //import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; //import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; //import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; //import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; //import org.springframework.security.oauth2.provider.token.TokenStore; //import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; //import org.springframework.security.web.util.matcher.AntPathRequestMatcher; // //import javax.sql.DataSource; // ///** // * @author linaz // * @created 2016.08.24 15:25 // * // * Spring Security logout handler // */ //@Configuration //public class OAuth2Configuration { // // @Configuration // @EnableResourceServer // protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { // // @Autowired // private CustomAuthenticationEntryPoint customAuthenticationEntryPoint; // // @Autowired // private CustomLogoutSuccessHandler customLogoutSuccessHandler; // // @Override // public void configure(ResourceServerSecurityConfigurer resources) { // resources.resourceId("union-resource"); // } // // @Override // public void configure(HttpSecurity http) throws Exception { // // http // .exceptionHandling() // .authenticationEntryPoint(customAuthenticationEntryPoint) // .and() // .logout() // .logoutUrl("/oauth/logout") // .logoutSuccessHandler(customLogoutSuccessHandler) // .and() // .csrf() // .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")) // .and() // .authorizeRequests() // .antMatchers("/**").permitAll() //// .antMatchers("/**").authenticated() // ; // // } // // } // // @Configuration // @EnableAuthorizationServer // protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { // // @Autowired // private DataSource dataSource; // // @Bean // public TokenStore tokenStore() { // return new JdbcTokenStore(dataSource); // } // // @Bean // ClientDetailsService clientDetailsService() { // return new ClientDetailsService(dataSource); // } // // @Autowired // @Qualifier("authenticationManagerBean") // private AuthenticationManager authenticationManager; // // @Override // public void configure(AuthorizationServerEndpointsConfigurer endpoints) // throws Exception { // endpoints // .tokenStore(tokenStore()) // .authenticationManager(authenticationManager); // } // // @Override // public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // clients.withClientDetails(clientDetailsService()); // } // // } // //}
package com.baiwang.custom.web.service.axis; public class WSInvokeException extends Exception { /** * */ private static final long serialVersionUID = -4457802535842594940L; }
package com.example.ahsan.youtube.adapters; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.ahsan.youtube.R; import java.util.ArrayList; import com.example.ahsan.youtube.Models.DataModel; import com.example.ahsan.youtube.vedio_view; import com.squareup.picasso.Picasso; public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> { private ArrayList<DataModel> dataSet; Context context; public class MyViewHolder extends RecyclerView.ViewHolder { TextView textViewTitle; TextView textViewAuthor; TextView textViewViews; TextView textViewDuration; ImageView imageViewIcon; ArrayList<DataModel> dataSet; public MyViewHolder(final View itemView, final ArrayList<DataModel> dataSet) { super(itemView); this.textViewTitle = (TextView) itemView.findViewById(R.id.title); this.textViewAuthor = (TextView) itemView.findViewById(R.id.author); this.textViewViews = (TextView) itemView.findViewById(R.id.views); this.textViewDuration = (TextView) itemView.findViewById(R.id.duration); this.imageViewIcon = (ImageView) itemView.findViewById(R.id.image); this.dataSet=dataSet; itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Toast.makeText(itemView.getContext(),dataSet.get( getPosition()).getUrl(), Toast.LENGTH_SHORT).show(); String url=dataSet.get( getPosition()).getUrl(); String title =dataSet.get(getPosition()).getTitle(); Intent goToNewActivity = new Intent(itemView.getContext(),vedio_view.class); goToNewActivity.putExtra("url", url); goToNewActivity.putExtra("title",title); context.startActivity(goToNewActivity); } }); } } public CustomAdapter(ArrayList<DataModel> data) { this.dataSet = data; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.design, parent, false); context=parent.getContext(); MyViewHolder myViewHolder = new MyViewHolder(view,dataSet); return myViewHolder; } @Override public void onBindViewHolder(final MyViewHolder holder, final int listPosition) { TextView textViewTitle = holder.textViewTitle; TextView textViewAuthor = holder.textViewAuthor; TextView textViewView = holder.textViewViews; TextView textViewDuration = holder.textViewDuration; ImageView imageView = holder.imageViewIcon; textViewTitle.setText(dataSet.get(listPosition).getTitle()); textViewAuthor.setText(dataSet.get(listPosition).getAuthor()); textViewView.setText(dataSet.get(listPosition).getViews()); textViewDuration.setText(dataSet.get(listPosition).getDuration()); Picasso.with(context).load(dataSet.get(listPosition).getImage()).into(imageView); } @Override public int getItemCount() { return dataSet.size(); } }
package ua.game.pro.controller; import java.security.Principal; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import resources.creatorHTMLTag.CreatorHTMLTag; import ua.game.pro.entity.MusicFile; import ua.game.pro.entity.User; import ua.game.pro.service.MusicFileService; import ua.game.pro.service.UserService; @Controller public class HomeController { @Autowired UserService userService; CreatorHTMLTag creator = new CreatorHTMLTag(); @Autowired MusicFileService musicFileService; @RequestMapping(value = { "/", "home" }, method = RequestMethod.GET) public String home(Principal principal, Model model) { if (principal != null) { User user = userService.findOne(Integer.parseInt(principal.getName())); model.addAttribute("user", user); /* add music in model */ String fileMusic = ""; ArrayList<MusicFile> list = (ArrayList<MusicFile>) musicFileService.findAll(); for (int i = 0; i < list.size(); i++) { if (i == 0) { fileMusic += creator.li(creator.a(list.get(i).getPath(), "", "", creator.div(list.get(i).getName(), "", "container musicDiv")), ""); } else { fileMusic += creator.li(creator.a(list.get(i).getPath(), "", "", creator.div(list.get(i).getName(), "", "container musicDiv")), ""); } } model.addAttribute("music", fileMusic); /* end add music in model */ } return "views-base-home"; } @RequestMapping(value = "/home", method = RequestMethod.POST) public String anton() { return "redirect:/home"; } @RequestMapping("/loginpage") public String login() { return "views-base-loginpage"; } @RequestMapping(value = "/logout", method = RequestMethod.POST) public String logout() { return "redirect:/"; } }
package com.xpecya.xds; import java.util.Iterator; import java.util.Map; import java.util.Spliterator; import java.util.function.Consumer; /** * 邻接矩阵表示的无向图 * @param <T> 结点数据类型 */ public class AdjacencyMatrixUndirectedGraph<T> extends AbstractUndirectedGraph<T> { /** * 构造一个默认的邻接矩阵无向图 */ public AdjacencyMatrixUndirectedGraph() { } /** * 转换一个图的底层结构 * @param anotherGraph 另一个图 */ public AdjacencyMatrixUndirectedGraph(Graph<T> anotherGraph) { super(anotherGraph); } @Override public Iterator<T> iterator() { return null; } @Override public boolean contains(T vertice) { return false; } @Override public boolean contains(T start, T end) { return false; } @Override public boolean isConnect(T start, T end) { return false; } @Override public void add(T vertice) { } @Override public void add(T start, T end) { } @Override public void remove(T vertice) { } @Override public void removeEdge(T start, T end) { } @Override public Iterator<Edge<T>> edgeIterator() { return null; } }
package info.revenberg.loader.step; import java.io.File; import java.util.ArrayList; import java.util.List; import info.revenberg.loader.objects.DataObject; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.NonTransientResourceException; import org.springframework.batch.item.ParseException; import org.springframework.batch.item.UnexpectedInputException; import java.util.concurrent.TimeUnit; import info.revenberg.loader.service.BatchService; public class Reader implements ItemReader<DataObject> { @Autowired private BatchService batchService; private File folder = null; List<String> list = new ArrayList<>(); public static String location = "D:/pptx/"; public static void search(final String pattern, final File folder, List<String> result, final String pre) { Reader reader = new Reader(); Long count = reader.batchService.getLastReadCount(); System.out.println(count); for (final File f : folder.listFiles()) { if (f.isDirectory()) { search(pattern, f, result, pre + f.getName() + "/"); } if (f.isFile()) { if (f.getName().matches(pattern)) { if (pre == "") { result.add(location + f.getName()); } else { result.add(location + pre + f.getName()); } } } } } @Override public DataObject read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { if (folder == null) { folder = new File(location); search(".*", folder, list, ""); } if (!list.isEmpty()) { String element = list.get(0); list.remove(0); return new DataObject(element); } return null; } }
package org.panel; import org.panel.Panel.OnPanelListener; import easing.interpolator.BackInterpolator; import easing.interpolator.BounceInterpolator; import easing.interpolator.ElasticInterpolator; import easing.interpolator.ExpoInterpolator; import easing.interpolator.EasingType.Type; import android.app.Activity; import android.graphics.Matrix; import android.graphics.RectF; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.ImageView; public class Test extends Activity implements OnPanelListener { private Panel bottomPanel; private Panel topPanel; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Panel panel; topPanel = panel = (Panel) findViewById(R.id.topPanel); panel.setOnPanelListener(this); panel.setInterpolator(new BounceInterpolator(Type.OUT)); panel = (Panel) findViewById(R.id.leftPanel1); panel.setOnPanelListener(this); panel.setInterpolator(new BackInterpolator(Type.OUT, 2)); panel = (Panel) findViewById(R.id.leftPanel2); panel.setOnPanelListener(this); panel.setInterpolator(new BackInterpolator(Type.OUT, 2)); panel = (Panel) findViewById(R.id.rightPanel); panel.setOnPanelListener(this); panel.setInterpolator(new ExpoInterpolator(Type.OUT)); bottomPanel = panel = (Panel) findViewById(R.id.bottomPanel); panel.setOnPanelListener(this); panel.setInterpolator(new ElasticInterpolator(Type.OUT, 1.0f, 0.3f)); findViewById(R.id.smoothButton1).setOnClickListener(new OnClickListener() { public void onClick(View v) { bottomPanel.setOpen(!bottomPanel.isOpen(), true); } }); findViewById(R.id.smoothButton2).setOnClickListener(new OnClickListener() { public void onClick(View v) { topPanel.setOpen(!topPanel.isOpen(), false); } }); } public void onPanelClosed(Panel panel) { String panelName = getResources().getResourceEntryName(panel.getId()); Log.d("Test", "Panel [" + panelName + "] closed"); } public void onPanelOpened(Panel panel) { String panelName = getResources().getResourceEntryName(panel.getId()); Log.d("Test", "Panel [" + panelName + "] opened"); } }
package hu.ibm.gamax.springboot.oauth.mvc.configuration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @EnableWebMvc @ComponentScan(basePackages = "hu.ibm.gamax.springboot.oauth.mvc") public class WebMVCConfiguration { }
/* * Copyright 2013 Yu AOKI */ package com.aokyu.dev.sample.music; import java.lang.ref.WeakReference; import android.app.Activity; import android.app.Fragment; import android.app.LoaderManager; import android.content.Context; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.provider.MediaStore; public abstract class PlaylistLoaderFragment extends Fragment { public final class ColumnIndex { public static final int ID = 0; public static final int NAME = 1; private ColumnIndex() {} } protected Context mContext; private LoaderManager mLoaderManager; private PlaylistLoaderCallbacks mLoaderCallbacks; private static final int ID_PLAYLIST_LOADER = 0x00000004; protected abstract void onLoadFinished(Loader<Cursor> loader, Cursor cursor); protected abstract void onLoaderReset(Loader<Cursor> loader); public PlaylistLoaderFragment() {} @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity != null) { mContext = activity.getApplicationContext(); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLoaderManager = getLoaderManager(); mLoaderCallbacks = new PlaylistLoaderCallbacks(mContext, this); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); loadPlaylists(); } protected void loadPlaylists() { Loader<Cursor> loader = mLoaderManager.getLoader(ID_PLAYLIST_LOADER); Bundle args = new Bundle(); if (loader != null) { mLoaderManager.restartLoader(ID_PLAYLIST_LOADER, args, mLoaderCallbacks); } else { mLoaderManager.initLoader(ID_PLAYLIST_LOADER, args, mLoaderCallbacks); } } private static final class PlaylistCursorLoader extends CursorLoader { private static final String[] PROJECTION = new String[] { MediaStore.Audio.Playlists._ID, MediaStore.Audio.Playlists.NAME }; public PlaylistCursorLoader(Context context) { super(context, MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, PROJECTION, null, null, null); } } private static class PlaylistLoaderCallbacks implements LoaderManager.LoaderCallbacks<Cursor> { private WeakReference<Context> mContext; private WeakReference<PlaylistLoaderFragment> mFragment; public PlaylistLoaderCallbacks(Context context, PlaylistLoaderFragment fragment) { mContext = new WeakReference<Context>(context); mFragment = new WeakReference<PlaylistLoaderFragment>(fragment); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new PlaylistCursorLoader(mContext.get()); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { PlaylistLoaderFragment fragment = mFragment.get(); if (fragment != null) { fragment.onLoadFinished(loader, cursor); } } @Override public void onLoaderReset(Loader<Cursor> loader) { PlaylistLoaderFragment fragment = mFragment.get(); if (fragment != null) { fragment.onLoaderReset(loader); } } } }
package com.toda.consultant.model; import okhttp3.Call; /** * Created by Zhao Haibin on 2016/1/28. */ public interface ResponseListener { public void onRefresh(Call call, int tag, ResultData data); }
package com.sense.cloud.service; import com.sense.cloud.entity.ErrorCode; import java.util.List; /** * Created by Administrator on 2016/6/30. */ public interface CodeService { int add(ErrorCode errorCode); int delete(String id); int update(ErrorCode errorCode); List<ErrorCode> getListByTerminal(String terminalId); List<ErrorCode> search(String searchText); List<ErrorCode> getList(); }
/* * Copyright 2015 The RPC Project * * The RPC Project 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 io.flood.rpc; import com.google.common.collect.Maps; import io.flood.common.Resource; import io.flood.rpc.network.Connector; import io.flood.rpc.network.SocketFactory; import io.flood.rpc.registry.ResourceRegistry; import io.netty.channel.ChannelFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class FloodClient { private final FloodDispatcher dispatcher; private static final Logger LOG = LoggerFactory.getLogger(FloodServer.class); private Map<String, Connector> connectorMap = Maps.newConcurrentMap(); private ResourceRegistry resourceRegistry; public FloodClient(ResourceRegistry resourceRegistry,FloodDispatcher dispatcher) { this.resourceRegistry=resourceRegistry; this.dispatcher = dispatcher; init(); } private void init() { // resourceRegistry.subscribe(); // discovery.setServiceListener(new FloodServiceListener() { // public void onServiceChange(Collection<ServiceInstance<FloodInfo>> instanceList) { // connect(instanceList); // clear(instanceList); // } // }); // // discovery.setConnectorMap(connectorMap); } private synchronized void connect(Collection<Resource> resources) { for (final Resource inst : resources) { if (connectorMap.containsKey(inst.getId())) { continue; } final ChannelFuture channelFuture = newConnector(inst.getId(), inst.getHost(), inst.getPort()); } } private synchronized void clear(Collection<Resource> instanceList) { for (Map.Entry<String, Connector> entry : connectorMap.entrySet()) { boolean exist=false; for (Resource inst : instanceList) { if (entry.getKey().equals(inst.getId())) { exist=true; break; } } if(exist){ continue; } entry.getValue().shutdown(); connectorMap.remove(entry.getKey()); } } public ChannelFuture newConnector(String id, String ip, int port) { Connector connector = SocketFactory.connector(this.dispatcher); ChannelFuture future = connector.connect(ip, port, 30 * 1000); connectorMap.put(ip+":"+port, connector); return future; } public void getBolockingInterface(Class<?> clazz) { } }
package org.sdf4j.awt; import java.awt.BasicStroke; import java.awt.geom.Area; import java.util.Map; import org.sdf4j.core.shapes.CompositeShape; import org.sdf4j.core.shapes.IShape; import org.sdf4j.core.shapes.Operation; public final class ConversionUtil { public static java.awt.Color convertColor(org.sdf4j.core.Color c) { return new java.awt.Color(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); } public static org.sdf4j.core.Color convertColor(java.awt.Color c) { return new org.sdf4j.core.Color(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); } public static java.awt.Stroke convertStroke(org.sdf4j.core.Stroke s) { return new java.awt.BasicStroke(s.getLineWidth(), s.getEndCap(), s.getLineJoin(), s .getMiterLimit(), s.getDashArray(), s.getDashPhase()); } public static org.sdf4j.core.Stroke convertStroke(java.awt.Stroke s) { if (s instanceof BasicStroke) { BasicStroke bs = (BasicStroke) s; return new org.sdf4j.core.Stroke(bs.getLineWidth(), bs.getEndCap(), bs.getLineJoin(), bs.getMiterLimit(), bs.getDashArray(), bs.getDashPhase()); } throw new IllegalArgumentException("Only BasicStroke instance are recognized."); } public static java.awt.Font convertFont(org.sdf4j.core.Font f) { return new java.awt.Font(f.getName(), f.getStyle(), f.getSize()); } public static org.sdf4j.core.Font convertFont(java.awt.Font f) { return new org.sdf4j.core.Font(f.getName(), f.getStyle(), f.getSize()); } public static java.awt.Shape convertShape(CompositeShape shape) { Area area = new Area(); if (shape.isEmpty()) { return area; } if (shape.getShapeMap().size() == 1) { return convertShape(shape.getShapeMap().keySet().iterator().next()); } for (Map.Entry<IShape, Operation> entry : shape.getShapeMap().entrySet()) { java.awt.Shape awtShape = convertShape(entry.getKey()); if (entry.getValue() == Operation.ADD) { area.add(new Area(awtShape)); } else { area.subtract(new Area(awtShape)); } } return area; } public static java.awt.Shape convertShape(IShape shape) { if (shape instanceof org.sdf4j.core.shapes.Rectangle) { org.sdf4j.core.shapes.Rectangle rect = (org.sdf4j.core.shapes.Rectangle) shape; return new java.awt.geom.Rectangle2D.Double(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); } if (shape instanceof org.sdf4j.core.shapes.Ellipse) { org.sdf4j.core.shapes.Ellipse rect = (org.sdf4j.core.shapes.Ellipse) shape; return new java.awt.geom.Ellipse2D.Double(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); } throw new IllegalArgumentException("Could not recognize shape type: " + shape.getClass()); } public static IShape convertShape(java.awt.Shape shape) { if (shape instanceof java.awt.geom.Rectangle2D) { java.awt.geom.Rectangle2D rect = (java.awt.geom.Rectangle2D) shape; return new org.sdf4j.core.shapes.Rectangle((int) rect.getX(), (int) rect.getY(), (int) rect.getWidth(), (int) rect.getHeight()); } if (shape instanceof java.awt.geom.Ellipse2D.Double) { java.awt.geom.Ellipse2D.Double rect = (java.awt.geom.Ellipse2D.Double) shape; return new org.sdf4j.core.shapes.Ellipse((int) rect.getX(), (int) rect.getY(), (int) rect.getWidth(), (int) rect.getHeight()); } throw new IllegalArgumentException("Could not recognize shape type: " + shape.getClass()); } public static java.awt.Point convertPoint(org.sdf4j.core.Point point) { return new java.awt.Point(point.getX(), point.getY()); } // public static java.awt.geom.AffineTransform convertAffineTransform( // org.sdf4j.core.AffineTransform tx) { // return new java.awt.geom.AffineTransform(tx.getM00(), tx.getM10(), // tx.getM01(), // tx.getM11(), tx.getM02(), tx.getM12()); // } // // public static org.sdf4j.core.AffineTransform convertAffineTransform( // java.awt.geom.AffineTransform tx) { // double[] flatMatrix = new double[6]; // tx.getMatrix(flatMatrix); // return new org.sdf4j.core.AffineTransform(flatMatrix[0], flatMatrix[1], // flatMatrix[2], // flatMatrix[3], flatMatrix[4], flatMatrix[5]); // } }
package ngordnet; import edu.princeton.cs.introcs.In; import java.util.HashMap; import java.util.Collection; public class NGramMap { /* The key is the YEAR and the value is TOTAL NUMBER OF WORDS from that year. */ private TimeSeries<Long> countsMap; /* The key is the YEAR and the value is a YEARLYRECORD with all the WORDS and their COUNTS. */ private HashMap<Integer, YearlyRecord> yearMap; private HashMap<String, TimeSeries> wordsMap; private In wordsFile; private In countsFile; private static YearlyRecordProcessor wlp = new WordLengthProcessor(); /** Constructs an NGramMap from WORDSFILENAME and COUNTSFILENAME. */ public NGramMap(String wordsFilename, String countsFilename) { countsFile = new In(countsFilename); wordsFile = new In(wordsFilename); countsMap = new TimeSeries<Long>(); yearMap = new HashMap<Integer, YearlyRecord>(); wordsMap = new HashMap<String, TimeSeries>(); while (countsFile.hasNextLine()) { String row = countsFile.readLine(); String[] tokens = row.split(","); countsMap.put(Integer.parseInt(tokens[0]), Long.parseLong(tokens[1])); } while (wordsFile.hasNextLine()) { String word = wordsFile.readString(); Integer year = wordsFile.readInt(); Integer count = wordsFile.readInt(); Integer forget = wordsFile.readInt(); YearlyRecord yearMapValue = yearMap.get(year); if (yearMapValue != null) { yearMapValue.put(word, count); } else { YearlyRecord putThis = new YearlyRecord(); putThis.put(word, count); yearMap.put(year, putThis); } TimeSeries wordsMapValue = wordsMap.get(word); if (wordsMapValue != null) { wordsMapValue.put(year, count); } else { TimeSeries putThisTimeSeries = new TimeSeries(); putThisTimeSeries.put(year, count); wordsMap.put(word, putThisTimeSeries); } } } /** Returns the absolute count of WORD in the given YEAR. If the word * did not appear in the given year, return 0. */ public int countInYear(String word, int year) { try { if (yearMap.get(year).words().contains(word)) { return yearMap.get(year).count(word); } else { return 0; } } catch (NullPointerException e) { System.err.println("This year is not in our records."); return 0; } } /** Returns a defensive copy of the YearlyRecord of YEAR. */ public YearlyRecord getRecord(int year) { try { YearlyRecord result = new YearlyRecord(); for (String key: yearMap.get(year).words()) { result.put(key, yearMap.get(year).count(key)); } return result; } catch (NullPointerException e) { System.err.println("This year is not in our records."); return null; } } /** Returns the total number of words recorded in all volumes. */ public TimeSeries<Long> totalCountHistory() { TimeSeries<Long> totalCountHistory = new TimeSeries<Long>(countsMap); return totalCountHistory; } /** Provides the history of WORD between STARTYEAR and ENDYEAR. */ public TimeSeries<Integer> countHistory(String word, int startYear, int endYear) { TimeSeries<Long> countsInInterval = new TimeSeries<Long>(countsMap, startYear, endYear); TimeSeries<Integer> countHistory = new TimeSeries<Integer>(); for (Integer key: countsInInterval.keySet()) { countHistory.put(key, countInYear(word, key)); } return countHistory; } /** Provides a defensive copy of the history of WORD. */ public TimeSeries<Integer> countHistory(String word) { TimeSeries<Integer> result = new TimeSeries<Integer>(wordsMap.get(word)); return result; } /** Provides the relative frequency of WORD between STARTYEAR and ENDYEAR. */ public TimeSeries<Double> weightHistory(String word, int startYear, int endYear) { TimeSeries<Double> numerator = new TimeSeries(wordsMap.get(word), startYear, endYear); TimeSeries<Double> denominator = new TimeSeries(countsMap, startYear, endYear); TimeSeries<Double> result = numerator.dividedBy(denominator); return result; } /** Provides the relative frequency of WORD. */ public TimeSeries<Double> weightHistory(String word) { TimeSeries<Double> numerator = new TimeSeries(wordsMap.get(word)); TimeSeries<Double> denominator = new TimeSeries(countsMap); TimeSeries<Double> result = numerator.dividedBy(denominator); return result; } /** Provides the summed relative frequency of all WORDS between * STARTYEAR and ENDYEAR. */ public TimeSeries<Double> summedWeightHistory(Collection<String> words, int startYear, int endYear) { TimeSeries<Double> sum = new TimeSeries<Double>(); TimeSeries<Double> denominator = new TimeSeries(countsMap, startYear, endYear); for (String word: words) { TimeSeries<Double> check = wordsMap.get(word); if (check != null) { TimeSeries<Double> numerator = new TimeSeries(check, startYear, endYear); sum = sum.plus(numerator); } } TimeSeries<Double> result = sum.dividedBy(denominator); return result; } /** Returns the summed relative frequency of all WORDS. */ public TimeSeries<Double> summedWeightHistory(Collection<String> words) { TimeSeries<Double> result = new TimeSeries<Double>(); for (String word: words) { result = result.plus(weightHistory(word)); } return result; } /** Provides processed history of all words between STARTYEAR and ENDYEAR as processed * by YRP. */ public TimeSeries<Double> processedHistory(int startYear, int endYear, YearlyRecordProcessor yrp) { TimeSeries<Double> result = new TimeSeries<Double>(); for (int year = startYear; year <= endYear; year++) { YearlyRecord check = yearMap.get(year); if (check != null) { result.put(year, wlp.process(check)); } } return result; } /** Provides processed history of all words ever as processed by YRP. */ public TimeSeries<Double> processedHistory(YearlyRecordProcessor yrp) { TimeSeries<Double> result = new TimeSeries<Double>(); for (Integer year: yearMap.keySet()) { result.put(year, wlp.process(yearMap.get(year))); } return result; } }
package br.edu.ifrs.poa.database; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; /** * Classe respons�vel por ler e criar os arquivos de propriedades * @author Karen Borges * @version 1.0 */ @SuppressWarnings({"rawtypes","unused","unchecked"}) public class PropertiesManager { private String fileName; /** * M�todo construtor. Seta o nome do arquivo de propriedades que ser� manipulado * @param fileName Nome do arquivo de propriedades que ser� manipulado */ public PropertiesManager(String fileName){ this.fileName = fileName; } /** * M�todo respons�vel pela cria��o do arquivo de properties * @param dados Informa��es a serem armazenadas no arquivo * @throws java.io.IOException Exce��o gerada em caso de problema de cria��o do arquivo de properties */ public void createPropertiesFile( HashMap dados) throws IOException { Properties props = new Properties(); Set valores = dados.entrySet(); Iterator it = valores.iterator(); while (it.hasNext()){ Map.Entry me = (Map.Entry) it.next(); String chave = (String)me.getKey(); String valor = (String)me.getValue(); props.setProperty(chave, valor); } // Salvamos para uma proxima execussao FileOutputStream out = new FileOutputStream(fileName); props.store(out,null); out.close(); } /** * M�todo respons�vel pela leitura do arquivo de properties * @return cole��o de objetos contendo os dados do arquivo * @throws java.io.IOException Exce��o gerada em caso de problema de leitura do arquivo de properties */ public HashMap readPropertiesFile() throws IOException { Properties properties; StringTokenizer sToken; HashMap lista = new HashMap(); int count=0; InputStream is = getClass().getResourceAsStream( fileName ); properties = new Properties(); properties.load( is ); for (Enumeration list = properties.propertyNames(); list.hasMoreElements(); count++) { String entry = (String) list.nextElement(); //System.out.println("entrada = " + entry); lista.put(entry, properties.getProperty(entry)); } return lista; } }
package be.openclinic.medical; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.ScreenHelper; import be.openclinic.common.KeyValue; import be.openclinic.common.Util; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.*; public class CarePrescriptionAdministrationSchema { private Date date; private String personuid; private Vector carePrescriptionSchemas=new Vector(); //### INNER CLASS : AdministrationSchemaLine ################################################## public class AdministrationSchemaLine{ private CarePrescription careprescription; private Vector timeQuantities=new Vector(); private Hashtable timeAdministrations=new Hashtable(); public CarePrescription getCarePrescription() { return careprescription; } public void setCarePrescription(CarePrescription careprescription) { this.careprescription = careprescription; } public Hashtable getTimeAdministrations() { return timeAdministrations; } public Vector getTimeQuantities() { return timeQuantities; } public void setTimeQuantities(Vector timeQuantities) { this.timeQuantities = timeQuantities; } public void setTimeAdministrations(Hashtable timeAdministrations) { this.timeAdministrations = timeAdministrations; } public AdministrationSchemaLine(CarePrescription careprescription) { this.careprescription = careprescription; } public String getTimeAdministration(String datetime){ String quantity = (String)timeAdministrations.get(datetime); if(quantity!=null){ return quantity; } else { return ""; } } } //############################################################################################# public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getPersonuid() { return personuid; } public void setPersonuid(String personuid) { this.personuid = personuid; } public Vector getCarePrescriptionSchemas() { return carePrescriptionSchemas; } public void setCarePrescriptionSchemas(Vector vCarePrescriptionSchemas) { this.carePrescriptionSchemas = vCarePrescriptionSchemas; } //--- CONSTRUCTOR ----------------------------------------------------------------------------- public CarePrescriptionAdministrationSchema(Date date, String personuid) { this.date = date; this.personuid = personuid; SortedMap schemaTimes = new TreeMap(); Vector prescriptions= CarePrescription.find(personuid,"","",ScreenHelper.stdDateFormat.format(new Date(date.getTime()+24*3600*1000)),ScreenHelper.stdDateFormat.format(date),"","",""); //We inventariseren eerst alle noodzakelijke tijdstippen CarePrescription prescription; CarePrescriptionSchema prescriptionSchema; Vector timequantities; KeyValue keyValue; for (int n=0;n<prescriptions.size();n++){ prescription= (CarePrescription)prescriptions.elementAt(n); prescriptionSchema = CarePrescriptionSchema.getCarePrescriptionSchema(prescription.getUid()); timequantities = prescriptionSchema.getTimequantities(); for(int i=0;i<timequantities.size();i++){ keyValue = (KeyValue)timequantities.elementAt(i); schemaTimes.put(new Integer(keyValue.getKey()),""); } } //Voor elk van de voorschriften gaan we nu de eenheden invullen die bij het betreffende uur horen AdministrationSchemaLine administrationSchemaLine; Iterator iterator; Integer time; for (int n=0;n<prescriptions.size();n++){ prescription= (CarePrescription)prescriptions.elementAt(n); prescriptionSchema = CarePrescriptionSchema.getCarePrescriptionSchema(prescription.getUid()); administrationSchemaLine = new AdministrationSchemaLine(prescription); iterator = schemaTimes.keySet().iterator(); while (iterator.hasNext()){ time = (Integer)iterator.next(); administrationSchemaLine.getTimeQuantities().add(new KeyValue(time.toString(),prescriptionSchema.getQuantity(time.toString())+"")); } carePrescriptionSchemas.add(administrationSchemaLine); } } //--- CONSTRUCTOR ----------------------------------------------------------------------------- public CarePrescriptionAdministrationSchema(Date dateBegin, Date dateEnd, String personuid) { this.date = dateBegin; this.personuid = personuid; SortedMap schemaTimes = new TreeMap(); Vector prescriptions= CarePrescription.find(personuid,"","",ScreenHelper.stdDateFormat.format(dateEnd),ScreenHelper.stdDateFormat.format(dateBegin),"","",""); //We inventariseren eerst alle noodzakelijke tijdstippen CarePrescription prescription; CarePrescriptionSchema prescriptionSchema; Vector timequantities; KeyValue keyValue; for (int n=0;n<prescriptions.size();n++){ prescription= (CarePrescription)prescriptions.elementAt(n); prescriptionSchema = CarePrescriptionSchema.getCarePrescriptionSchema(prescription.getUid()); timequantities = prescriptionSchema.getTimequantities(); for(int i=0;i<timequantities.size();i++){ keyValue = (KeyValue)timequantities.elementAt(i); schemaTimes.put(new Integer(keyValue.getKey()),""); } } //Voor elk van de voorschriften gaan we nu de eenheden invullen die bij het betreffende uur horen AdministrationSchemaLine administrationSchemaLine; Iterator iterator; Integer time; Connection dbConnection= MedwanQuery.getInstance().getOpenclinicConnection(); PreparedStatement ps; ResultSet rs; for (int n=0;n<prescriptions.size();n++){ prescription= (CarePrescription)prescriptions.elementAt(n); prescriptionSchema = CarePrescriptionSchema.getCarePrescriptionSchema(prescription.getUid()); administrationSchemaLine = new AdministrationSchemaLine(prescription); iterator = schemaTimes.keySet().iterator(); while (iterator.hasNext()){ time = (Integer)iterator.next(); administrationSchemaLine.getTimeQuantities().add(new KeyValue(time.toString(),prescriptionSchema.getQuantity(time.toString())+"")); } //Nu zoeken we voor betreffende geneesmiddelen de toedieningen op try { ps = dbConnection.prepareStatement("select * from OC_CAREPRESCRIPTION_ADMINISTRATION where OC_CAREPRESCR_SERVERID=? and OC_CAREPRESCR_OBJECTID=?"); ps.setInt(1, Util.getServerid(prescription.getUid())); ps.setInt(2, Util.getObjectid(prescription.getUid())); rs = ps.executeQuery(); while (rs.next()){ administrationSchemaLine.getTimeAdministrations().put(new SimpleDateFormat("yyyyMMdd").format(rs.getDate("OC_CARESCHEMA_DATE"))+"."+rs.getString("OC_CARESCHEMA_TIME"),rs.getString("OC_CARESCHEMA_QUANTITY")); } rs.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } carePrescriptionSchemas.add(administrationSchemaLine); } try { dbConnection.close(); } catch (SQLException e) { e.printStackTrace(); } } //--- STORE ADMINISTRATION -------------------------------------------------------------------- public static void storeAdministration(String prescriptionUid,Date date,int time,int quantity){ Connection dbConnection= MedwanQuery.getInstance().getOpenclinicConnection(); try { PreparedStatement ps = dbConnection.prepareStatement("delete from OC_CAREPRESCRIPTION_ADMINISTRATION where OC_CAREPRESCR_SERVERID=? and OC_CAREPRESCR_OBJECTID=? and OC_CARESCHEMA_DATE=? and OC_CARESCHEMA_TIME=?"); ps.setInt(1,Util.getServerid(prescriptionUid)); ps.setInt(2,Util.getObjectid(prescriptionUid)); ps.setDate(3,new java.sql.Date(date.getTime())); ps.setInt(4,time); ps.execute(); ps.close(); if(quantity>0){ ps = dbConnection.prepareStatement("insert into OC_CAREPRESCRIPTION_ADMINISTRATION (OC_CAREPRESCR_SERVERID,OC_CAREPRESCR_OBJECTID,OC_CARESCHEMA_DATE,OC_CARESCHEMA_TIME,OC_CARESCHEMA_QUANTITY) values(?,?,?,?,?)"); ps.setInt(1,Util.getServerid(prescriptionUid)); ps.setInt(2,Util.getObjectid(prescriptionUid)); ps.setDate(3,new java.sql.Date(date.getTime())); ps.setInt(4,time); ps.setInt(5,quantity); ps.execute(); ps.close(); } } catch (SQLException e) { e.printStackTrace(); } try { dbConnection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
package cn.kitho.web.controller.textRecording; import cn.kitho.web.dto.base.BaseResult; import org.springframework.stereotype.Controller; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by lingkitho on 16/11/26. */ @Controller @RequestMapping("/keywords") public class KeyWordsController { @InitBinder("userInfo") public void initBinder(WebDataBinder binder) { binder.setFieldDefaultPrefix("userInfo."); } /** * 查询关键字列表 * @param request * @param response * @return */ @RequestMapping("/select") @ResponseBody public BaseResult select(HttpServletRequest request, HttpServletResponse response){ return null; } /** * 去添加 * @param request * @param response * @return */ @RequestMapping("/add") @ResponseBody public BaseResult add(HttpServletRequest request, HttpServletResponse response){ return null; } /** * 去编辑 * @param request * @param response * @return */ @RequestMapping("/modify") public BaseResult modify(HttpServletRequest request, HttpServletResponse response){ return null; } /** * 删除 * @param request * @param response * @return */ @RequestMapping("/delete") @ResponseBody public BaseResult delete(HttpServletRequest request, HttpServletResponse response){ return null; } }
package man.frechet.demo.actuator.spring; import man.frechet.demo.actuator.spring.config.AppConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {AppConfig.class}) public class ActuatorDemoApplicationTests { @Test public void contextLoads() { } }
package com.trump.auction.trade.model; import java.io.Serializable; public class ActualAuctionModel implements Serializable{ }
package com.blurack.constants; /** * @DateOfCreation : 13/04/16 * @Author : RK * @Description : description. * <p> * Copyright (c) 2016, Rakesh. All rights reserved. */ public final class LocationConstants { // Milliseconds per second private static final int MILLISECONDS_PER_SECOND = 1000; // Update frequency in seconds private static final int UPDATE_INTERVAL_IN_SECONDS = 30; // Update frequency in milliseconds public static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS; // The fastest update frequency, in seconds private static final int FASTEST_INTERVAL_IN_SECONDS = 30; // A fast frequency ceiling in milliseconds public static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS; // Stores the lat / long pairs in a text file public static final String LOCATION_FILE = "sdcard/location.txt"; // Stores the connect / disconnect data in a text file public static final String LOG_FILE = "sdcard/log.txt"; // Key to sore preferences for location logging on public static final String KEY_UPDATES_ON = "KEY_UPDATES_ON"; /** * Suppress default constructor for noninstantiability */ private LocationConstants() { throw new AssertionError(); } }
package ru.shikhovtsev; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import ru.shikhovtsev.core.model.Account; import ru.shikhovtsev.core.service.DbServiceAccountImpl; import ru.shikhovtsev.h2.DataSourceH2; import ru.shikhovtsev.jdbc.DbExecutor; import ru.shikhovtsev.jdbc.JdbcTemplate; import ru.shikhovtsev.jdbc.dao.AccountDaoJdbc; import ru.shikhovtsev.jdbc.sessionmanager.SessionManagerJdbc; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class JdbcAccountTest { private static DbServiceAccountImpl service; @BeforeAll static void createTable() throws SQLException { var dataSource = new DataSourceH2(); var jdbcTemplate = new JdbcTemplate<>(new DbExecutor<>(), Account.class); service = new DbServiceAccountImpl(new AccountDaoJdbc(new SessionManagerJdbc(dataSource), jdbcTemplate)); try (Connection connection = dataSource.getConnection(); PreparedStatement pst = connection.prepareStatement("create table account(no long auto_increment, type varchar(255), rest number)")) { pst.executeUpdate(); } System.out.println("table created"); } @Test void test() { String type = "typeKek"; BigDecimal rest = BigDecimal.valueOf(101); long id = service.saveAccount(new Account(type, rest)); assertTrue(id != 0); Optional<Account> account = service.getAccount(id); Account acc = account.orElseThrow(RuntimeException::new); assertEquals(acc.getRest(), rest); assertEquals(acc.getType(), type); } @Test void update() { String type = "typeKek"; String type2 = "type2"; BigDecimal rest = BigDecimal.valueOf(101); var account = new Account(type, rest); long id = service.saveAccount(account); account = service.getAccount(id).orElseThrow(RuntimeException::new); account.setType(type2); service.updateAccount(account); var accountFromDb = service.getAccount(id).orElseThrow(RuntimeException::new); assertEquals(type2, accountFromDb.getType()); } @Test void createOrUpdate() { var account = new Account("type", BigDecimal.valueOf(101)); Long id = service.createOrUpdate(account); account = service.getAccount(id).orElseThrow(RuntimeException::new); String type2 = "type2"; account.setType(type2); assertEquals(id, service.createOrUpdate(account)); account = service.getAccount(id).orElseThrow(RuntimeException::new); assertEquals(type2, account.getType()); } }
package info.cukes.transaction; import bitronix.tm.BitronixTransactionManager; import bitronix.tm.TransactionManagerServices; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import javax.transaction.TransactionManager; import java.lang.invoke.MethodHandles; /** * @author glick */ @SuppressWarnings("UnusedDeclaration") @ApplicationScoped public class TransactionManagerConfigurationFactory { private static final transient Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); public @Produces @Config TransactionManager getConfigurationTransactionManager(InjectionPoint injectionPoint) { BitronixTransactionManager transactionManager = TransactionManagerServices.getTransactionManager(); return transactionManager; } }
package com.alex.patterns.decorator.example; public class Main { public static void main(String[] args) { Programmer programmer = new JavaProgrammer(); /* add the current programmer the new ability */ ProgrammerWithGit programmerWithGit = new ProgrammerWithGit(programmer); programmerWithGit.writeCode(); } }
package com.mygdx.boardgame.controller; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.Shape.Type; import com.mygdx.boardgame.model.BlockTile; import java.util.ArrayList; /** * Created by jacobth on 2015-04-18. */ public class MoveController { private ArrayList<BlockTile> tileList; private ArrayList<Sprite> spriteList; private BlockTile tmp; private BlockTile tmp2; private Texture tileTexture; private Texture emptyTexture; private float x; private float y; private float x2; private float y2; private int i; private int j; private int h; private GameController gameController; public MoveController(ArrayList<BlockTile> tileList, ArrayList<Sprite> spriteList, Texture tileTexture, Texture emptyTexture) { this.tileList = tileList; this.spriteList = spriteList; this.tileTexture = tileTexture; this.emptyTexture = emptyTexture; gameController = new GameController(); } public void setSpriteList(ArrayList<Sprite> spriteList) { this.spriteList = spriteList; } public void moveUp(Camera camera) { for (int i = 0; i < tileList.size(); i++) { if (tileList.get(i).getBody().getType() != BodyDef.BodyType.KinematicBody) { int x1 = Gdx.input.getX(); int y1 = Gdx.input.getY(); Vector3 input = new Vector3(x1, y1, 0); camera.unproject(input); if (tileList.get(i).getSprite().getBoundingRectangle() .contains(input.x, input.y) && !tileList.get(i).isEmpty() && !isMoving()) { upMove(i, input.x, input.y + tileTexture.getHeight() * 2); } } } } public void moveDown(Camera camera) { for (int i = 0; i < tileList.size(); i++) { if (tileList.get(i).getBody().getType() != BodyDef.BodyType.KinematicBody) { int x1 = Gdx.input.getX(); int y1 = Gdx.input.getY(); Vector3 input = new Vector3(x1, y1, 0); camera.unproject(input); if (tileList.get(i).getSprite().getBoundingRectangle() .contains(input.x, input.y) && !tileList.get(i).isEmpty() && !isMoving()) { downMove(i, input.x, input.y - tileTexture.getHeight() * 2); } } } } public void moveLeft(Camera camera) { for (int i = 0; i < tileList.size(); i++) { if (tileList.get(i).getBody().getType() != BodyDef.BodyType.KinematicBody) { int x1 = Gdx.input.getX(); int y1 = Gdx.input.getY(); Vector3 input = new Vector3(x1, y1, 0); camera.unproject(input); if (tileList.get(i).getSprite().getBoundingRectangle() .contains(input.x, input.y) && !tileList.get(i).isEmpty() && !isMoving()) { leftMove(i, input.x - tileTexture.getWidth() * 2, input.y); } } } } public void moveRight(Camera camera) { for (int i = 0; i < tileList.size(); i++) { if (tileList.get(i).getBody().getType() != BodyDef.BodyType.KinematicBody) { int x1 = Gdx.input.getX(); int y1 = Gdx.input.getY(); Vector3 input = new Vector3(x1, y1, 0); camera.unproject(input); if (tileList.get(i).getSprite().getBoundingRectangle() .contains(input.x, input.y) && !tileList.get(i).isEmpty() && !isMoving()) { rightMove(i, input.x + tileTexture.getWidth() * 2, input.y); } } } } private void downMove(int i, float x, float y) { float posY = y; float posX = x; for (int j = 0; j < tileList.size(); j++) { this.i = i; if (tileList.get(j).getSprite().getBoundingRectangle() .contains(posX, posY) && tileList.get(j).isEmpty()) { for (int h = 0; h < tileList.size(); h++) { if (tileList.get(h).getSprite().getBoundingRectangle() .contains(posX, posY + tileTexture.getHeight()) && !tileList.get(h).isEmpty()) { tileList.get(h).getSprite().setTexture(emptyTexture); tileList.get(i).moveDown(); this.x = tileList.get(i).getBody().getPosition().x; this.y = tileList.get(i).getBody().getPosition().y; this.x2 = tileList.get(j).getBody().getPosition().x; this.y2 = tileList.get(j).getBody().getPosition().y; this.h = h; this.j = j; } } } } } private void upMove(int i, float x, float y) { float posY = y; float posX = x; for (int j = 0; j < tileList.size(); j++) { this.i = i; if (tileList.get(j).getSprite().getBoundingRectangle() .contains(posX, posY) && tileList.get(j).isEmpty()) { for (int h = 0; h < tileList.size(); h++) { if (tileList.get(h).getSprite().getBoundingRectangle() .contains(posX, posY - tileTexture.getHeight()) && !tileList.get(h).isEmpty()) { tileList.get(h).getSprite().setTexture(emptyTexture); tileList.get(i).moveUp(); this.x = tileList.get(i).getBody().getPosition().x; this.y = tileList.get(i).getBody().getPosition().y; this.x2 = tileList.get(j).getBody().getPosition().x; this.y2 = tileList.get(j).getBody().getPosition().y; this.j = j; } } } } } private void leftMove(int i, float x, float y) { float posY = y; float posX = x; for (int j = 0; j < tileList.size(); j++) { this.i = i; if (tileList.get(j).getSprite().getBoundingRectangle() .contains(posX, posY) && tileList.get(j).isEmpty()) { for (int h = 0; h < tileList.size(); h++) { if (tileList.get(h).getSprite().getBoundingRectangle() .contains(posX + tileTexture.getWidth(), posY) && !tileList.get(h).isEmpty()) { tileList.get(h).getSprite().setTexture(emptyTexture); tileList.get(i).moveLeft(); this.x = tileList.get(i).getBody().getPosition().x; this.y = tileList.get(i).getBody().getPosition().y; this.x2 = tileList.get(j).getBody().getPosition().x; this.y2 = tileList.get(j).getBody().getPosition().y; this.j = j; } } } } } private void rightMove(int i, float x, float y) { float posY = y; float posX = x; for (int j = 0; j < tileList.size(); j++) { this.i = i; if (tileList.get(j).getSprite().getBoundingRectangle() .contains(posX, posY) && tileList.get(j).isEmpty()) { for (int h = 0; h < tileList.size(); h++) { if (tileList.get(h).getSprite().getBoundingRectangle() .contains(posX - tileTexture.getWidth(), posY) && !tileList.get(h).isEmpty()) { tileList.get(h).getSprite().setTexture(emptyTexture); tileList.get(i).moveRight(); this.x = tileList.get(i).getBody().getPosition().x; this.y = tileList.get(i).getBody().getPosition().y; this.x2 = tileList.get(j).getBody().getPosition().x; this.y2 = tileList.get(j).getBody().getPosition().y; this.j = j; } } } } } public void stop() { stopDown(); stopUp(); stopLeft(); stopRight(); } private void stopUp() { if (tileList.get(j).getBody().getPosition().y - tileList.get(i).getBody().getPosition().y < 0.014 && i != j && tileList.get(i).getVelocityY() > 0) { tileList.get(i).resetVelocity(); stopMethod(); } } private void stopDown() { if (tileList.get(i).getBody().getPosition().y - tileList.get(j).getBody().getPosition().y < 0.014 && i != j && tileList.get(i).getVelocityY() < 0) { tileList.get(i).resetVelocity(); stopMethod(); } } private void stopLeft() { if (tileList.get(i).getBody().getPosition().x - tileList.get(j).getBody().getPosition().x < 0.014 && i != j && tileList.get(i).getVelocityX() < 0) { tileList.get(i).resetVelocity(); stopMethod(); } } private void stopRight() { if (tileList.get(j).getBody().getPosition().x - tileList.get(i).getBody().getPosition().x < 0.014 && i != j && tileList.get(i).getVelocityX() > 0) { tileList.get(i).resetVelocity(); stopMethod(); } } private void stopMethod() { tileList.get(i).stop(); tileList.get(j).getBody() .setTransform(x, y, tileList.get(j).getBody().getAngle()); tileList.get(i).getBody() .setTransform(x2, y2, tileList.get(i).getBody().getAngle()); tileList.get(i).getBody().setType(BodyDef.BodyType.StaticBody); } public boolean isMoving() { for(int tmp = 0; tmp<tileList.size(); i++) { return tileList.get(i).getBody().getType() == BodyDef.BodyType.KinematicBody; } return false; } }
import java.util.Scanner; public class OnTimeForTheExam { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int hoursExam = Integer.parseInt(scan.nextLine()); int minutesExam = Integer.parseInt(scan.nextLine()); int hoursArrive = Integer.parseInt(scan.nextLine()); int minutesArrive = Integer.parseInt(scan.nextLine()); int totalMinExam = hoursExam * 60 + minutesExam; int totalMinArrive = hoursArrive * 60 + minutesArrive; if (totalMinExam == totalMinArrive || (totalMinExam > totalMinArrive && totalMinExam - totalMinArrive<=30)) { System.out.println("On time"); } if (totalMinExam > totalMinArrive && totalMinExam - totalMinArrive >30) { System.out.println("Early"); } if (totalMinArrive > totalMinExam) { System.out.println("Late"); } if (Math.abs(totalMinArrive - totalMinExam)!=0) { int hours = Math.abs(totalMinArrive - totalMinExam) / 60; int mins = Math.abs(totalMinArrive - totalMinExam) % 60; if (hours >=1) { if (mins < 10) System.out.print(hours + ":0" + mins + " hours"); else System.out.print(hours + ":" + mins + " hours"); } else System.out.print(mins + " minutes"); if ((totalMinArrive - totalMinExam) < 0) System.out.println(" before the start"); else System.out.println(" after the start"); } } }
package com.agamidev.newsfeedsapp.Models; public class DrawerItemModel { int image_id; String title; Boolean isSelected; public DrawerItemModel(int image_id, String title, Boolean isSelected){ this.image_id = image_id; this.title = title; this.isSelected = isSelected; } public int getImage_id() { return image_id; } public String getTitle() { return title; } public void setSelected(Boolean selected) { isSelected = selected; } public Boolean getSelected() { return isSelected; } }
package com.bichu.dao; import com.bichu.pojo.News; import java.util.List; /** * Created by kaven on 2018/10/24. */ public interface NewsMapper { List<News> getNews(); }
package cn.tedu.store.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.tedu.store.bean.Area; import cn.tedu.store.bean.City; import cn.tedu.store.bean.Province; import cn.tedu.store.bean.ResponseResult; import cn.tedu.store.service.IDictService; @Controller @RequestMapping("/dict") public class DictController { @Resource private IDictService dictService; //获取省份信息 @RequestMapping("/getProvince.do") @ResponseBody public ResponseResult<List<Province>> getProvince(){ //1.创建rr对象,state : 1 messge: 成功 ResponseResult<List<Province>> rr = new ResponseResult<List<Province>>( 1,"成功"); //2.调用业务层的方法 getProvince();返回list集合 List<Province> list = dictService.getProvince(); //3.把list添加到rr对象的data属性中 rr.setData(list); return rr; } //异步请求,获取城市信息 @RequestMapping("/getCity.do") @ResponseBody public ResponseResult<List<City>> getCity( String provinceCode){ //1.创建rr对象,state : 1 message:成功 ResponseResult<List<City>> rr = new ResponseResult<List<City>>( 1,"成功"); //2.调用业务层方法 getCity(provinceCode);返回list List<City> list = dictService.getCity(provinceCode); //3.把list设置到rr对象中 rr.setData(list); return rr; } @RequestMapping("/getArea.do") @ResponseBody public ResponseResult<List<Area>> getArea( String cityCode){ ResponseResult<List<Area>> rr = new ResponseResult<List<Area>>(1,"成功"); List<Area> list = dictService.getArea(cityCode); rr.setData(list); return rr; } }
package mc.kurunegala.bop.model; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; public class CustomerExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public CustomerExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } protected void addCriterionForJDBCDate(String condition, Date value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } addCriterion(condition, new java.sql.Date(value.getTime()), property); } protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) { if (values == null || values.size() == 0) { throw new RuntimeException("Value list for " + property + " cannot be null or empty"); } List<java.sql.Date> dateList = new ArrayList<java.sql.Date>(); Iterator<Date> iter = values.iterator(); while (iter.hasNext()) { dateList.add(new java.sql.Date(iter.next().getTime())); } addCriterion(condition, dateList, property); } protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property); } public Criteria andIdcustomerIsNull() { addCriterion("idCustomer is null"); return (Criteria) this; } public Criteria andIdcustomerIsNotNull() { addCriterion("idCustomer is not null"); return (Criteria) this; } public Criteria andIdcustomerEqualTo(Integer value) { addCriterion("idCustomer =", value, "idcustomer"); return (Criteria) this; } public Criteria andIdcustomerNotEqualTo(Integer value) { addCriterion("idCustomer <>", value, "idcustomer"); return (Criteria) this; } public Criteria andIdcustomerGreaterThan(Integer value) { addCriterion("idCustomer >", value, "idcustomer"); return (Criteria) this; } public Criteria andIdcustomerGreaterThanOrEqualTo(Integer value) { addCriterion("idCustomer >=", value, "idcustomer"); return (Criteria) this; } public Criteria andIdcustomerLessThan(Integer value) { addCriterion("idCustomer <", value, "idcustomer"); return (Criteria) this; } public Criteria andIdcustomerLessThanOrEqualTo(Integer value) { addCriterion("idCustomer <=", value, "idcustomer"); return (Criteria) this; } public Criteria andIdcustomerIn(List<Integer> values) { addCriterion("idCustomer in", values, "idcustomer"); return (Criteria) this; } public Criteria andIdcustomerNotIn(List<Integer> values) { addCriterion("idCustomer not in", values, "idcustomer"); return (Criteria) this; } public Criteria andIdcustomerBetween(Integer value1, Integer value2) { addCriterion("idCustomer between", value1, value2, "idcustomer"); return (Criteria) this; } public Criteria andIdcustomerNotBetween(Integer value1, Integer value2) { addCriterion("idCustomer not between", value1, value2, "idcustomer"); return (Criteria) this; } public Criteria andCusNameIsNull() { addCriterion("cus_name is null"); return (Criteria) this; } public Criteria andCusNameIsNotNull() { addCriterion("cus_name is not null"); return (Criteria) this; } public Criteria andCusNameEqualTo(String value) { addCriterion("cus_name =", value, "cusName"); return (Criteria) this; } public Criteria andCusNameNotEqualTo(String value) { addCriterion("cus_name <>", value, "cusName"); return (Criteria) this; } public Criteria andCusNameGreaterThan(String value) { addCriterion("cus_name >", value, "cusName"); return (Criteria) this; } public Criteria andCusNameGreaterThanOrEqualTo(String value) { addCriterion("cus_name >=", value, "cusName"); return (Criteria) this; } public Criteria andCusNameLessThan(String value) { addCriterion("cus_name <", value, "cusName"); return (Criteria) this; } public Criteria andCusNameLessThanOrEqualTo(String value) { addCriterion("cus_name <=", value, "cusName"); return (Criteria) this; } public Criteria andCusNameLike(String value) { addCriterion("cus_name like", value, "cusName"); return (Criteria) this; } public Criteria andCusNameNotLike(String value) { addCriterion("cus_name not like", value, "cusName"); return (Criteria) this; } public Criteria andCusNameIn(List<String> values) { addCriterion("cus_name in", values, "cusName"); return (Criteria) this; } public Criteria andCusNameNotIn(List<String> values) { addCriterion("cus_name not in", values, "cusName"); return (Criteria) this; } public Criteria andCusNameBetween(String value1, String value2) { addCriterion("cus_name between", value1, value2, "cusName"); return (Criteria) this; } public Criteria andCusNameNotBetween(String value1, String value2) { addCriterion("cus_name not between", value1, value2, "cusName"); return (Criteria) this; } public Criteria andCusNicIsNull() { addCriterion("cus_nic is null"); return (Criteria) this; } public Criteria andCusNicIsNotNull() { addCriterion("cus_nic is not null"); return (Criteria) this; } public Criteria andCusNicEqualTo(String value) { addCriterion("cus_nic =", value, "cusNic"); return (Criteria) this; } public Criteria andCusNicNotEqualTo(String value) { addCriterion("cus_nic <>", value, "cusNic"); return (Criteria) this; } public Criteria andCusNicGreaterThan(String value) { addCriterion("cus_nic >", value, "cusNic"); return (Criteria) this; } public Criteria andCusNicGreaterThanOrEqualTo(String value) { addCriterion("cus_nic >=", value, "cusNic"); return (Criteria) this; } public Criteria andCusNicLessThan(String value) { addCriterion("cus_nic <", value, "cusNic"); return (Criteria) this; } public Criteria andCusNicLessThanOrEqualTo(String value) { addCriterion("cus_nic <=", value, "cusNic"); return (Criteria) this; } public Criteria andCusNicLike(String value) { addCriterion("cus_nic like", value, "cusNic"); return (Criteria) this; } public Criteria andCusNicNotLike(String value) { addCriterion("cus_nic not like", value, "cusNic"); return (Criteria) this; } public Criteria andCusNicIn(List<String> values) { addCriterion("cus_nic in", values, "cusNic"); return (Criteria) this; } public Criteria andCusNicNotIn(List<String> values) { addCriterion("cus_nic not in", values, "cusNic"); return (Criteria) this; } public Criteria andCusNicBetween(String value1, String value2) { addCriterion("cus_nic between", value1, value2, "cusNic"); return (Criteria) this; } public Criteria andCusNicNotBetween(String value1, String value2) { addCriterion("cus_nic not between", value1, value2, "cusNic"); return (Criteria) this; } public Criteria andCusMobileIsNull() { addCriterion("cus_mobile is null"); return (Criteria) this; } public Criteria andCusMobileIsNotNull() { addCriterion("cus_mobile is not null"); return (Criteria) this; } public Criteria andCusMobileEqualTo(String value) { addCriterion("cus_mobile =", value, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileNotEqualTo(String value) { addCriterion("cus_mobile <>", value, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileGreaterThan(String value) { addCriterion("cus_mobile >", value, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileGreaterThanOrEqualTo(String value) { addCriterion("cus_mobile >=", value, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileLessThan(String value) { addCriterion("cus_mobile <", value, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileLessThanOrEqualTo(String value) { addCriterion("cus_mobile <=", value, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileLike(String value) { addCriterion("cus_mobile like", value, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileNotLike(String value) { addCriterion("cus_mobile not like", value, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileIn(List<String> values) { addCriterion("cus_mobile in", values, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileNotIn(List<String> values) { addCriterion("cus_mobile not in", values, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileBetween(String value1, String value2) { addCriterion("cus_mobile between", value1, value2, "cusMobile"); return (Criteria) this; } public Criteria andCusMobileNotBetween(String value1, String value2) { addCriterion("cus_mobile not between", value1, value2, "cusMobile"); return (Criteria) this; } public Criteria andCusTelIsNull() { addCriterion("cus_tel is null"); return (Criteria) this; } public Criteria andCusTelIsNotNull() { addCriterion("cus_tel is not null"); return (Criteria) this; } public Criteria andCusTelEqualTo(String value) { addCriterion("cus_tel =", value, "cusTel"); return (Criteria) this; } public Criteria andCusTelNotEqualTo(String value) { addCriterion("cus_tel <>", value, "cusTel"); return (Criteria) this; } public Criteria andCusTelGreaterThan(String value) { addCriterion("cus_tel >", value, "cusTel"); return (Criteria) this; } public Criteria andCusTelGreaterThanOrEqualTo(String value) { addCriterion("cus_tel >=", value, "cusTel"); return (Criteria) this; } public Criteria andCusTelLessThan(String value) { addCriterion("cus_tel <", value, "cusTel"); return (Criteria) this; } public Criteria andCusTelLessThanOrEqualTo(String value) { addCriterion("cus_tel <=", value, "cusTel"); return (Criteria) this; } public Criteria andCusTelLike(String value) { addCriterion("cus_tel like", value, "cusTel"); return (Criteria) this; } public Criteria andCusTelNotLike(String value) { addCriterion("cus_tel not like", value, "cusTel"); return (Criteria) this; } public Criteria andCusTelIn(List<String> values) { addCriterion("cus_tel in", values, "cusTel"); return (Criteria) this; } public Criteria andCusTelNotIn(List<String> values) { addCriterion("cus_tel not in", values, "cusTel"); return (Criteria) this; } public Criteria andCusTelBetween(String value1, String value2) { addCriterion("cus_tel between", value1, value2, "cusTel"); return (Criteria) this; } public Criteria andCusTelNotBetween(String value1, String value2) { addCriterion("cus_tel not between", value1, value2, "cusTel"); return (Criteria) this; } public Criteria andCusAddressL1IsNull() { addCriterion("cus_address_l1 is null"); return (Criteria) this; } public Criteria andCusAddressL1IsNotNull() { addCriterion("cus_address_l1 is not null"); return (Criteria) this; } public Criteria andCusAddressL1EqualTo(String value) { addCriterion("cus_address_l1 =", value, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1NotEqualTo(String value) { addCriterion("cus_address_l1 <>", value, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1GreaterThan(String value) { addCriterion("cus_address_l1 >", value, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1GreaterThanOrEqualTo(String value) { addCriterion("cus_address_l1 >=", value, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1LessThan(String value) { addCriterion("cus_address_l1 <", value, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1LessThanOrEqualTo(String value) { addCriterion("cus_address_l1 <=", value, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1Like(String value) { addCriterion("cus_address_l1 like", value, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1NotLike(String value) { addCriterion("cus_address_l1 not like", value, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1In(List<String> values) { addCriterion("cus_address_l1 in", values, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1NotIn(List<String> values) { addCriterion("cus_address_l1 not in", values, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1Between(String value1, String value2) { addCriterion("cus_address_l1 between", value1, value2, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL1NotBetween(String value1, String value2) { addCriterion("cus_address_l1 not between", value1, value2, "cusAddressL1"); return (Criteria) this; } public Criteria andCusAddressL2IsNull() { addCriterion("cus_address_l2 is null"); return (Criteria) this; } public Criteria andCusAddressL2IsNotNull() { addCriterion("cus_address_l2 is not null"); return (Criteria) this; } public Criteria andCusAddressL2EqualTo(String value) { addCriterion("cus_address_l2 =", value, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2NotEqualTo(String value) { addCriterion("cus_address_l2 <>", value, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2GreaterThan(String value) { addCriterion("cus_address_l2 >", value, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2GreaterThanOrEqualTo(String value) { addCriterion("cus_address_l2 >=", value, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2LessThan(String value) { addCriterion("cus_address_l2 <", value, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2LessThanOrEqualTo(String value) { addCriterion("cus_address_l2 <=", value, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2Like(String value) { addCriterion("cus_address_l2 like", value, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2NotLike(String value) { addCriterion("cus_address_l2 not like", value, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2In(List<String> values) { addCriterion("cus_address_l2 in", values, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2NotIn(List<String> values) { addCriterion("cus_address_l2 not in", values, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2Between(String value1, String value2) { addCriterion("cus_address_l2 between", value1, value2, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL2NotBetween(String value1, String value2) { addCriterion("cus_address_l2 not between", value1, value2, "cusAddressL2"); return (Criteria) this; } public Criteria andCusAddressL3IsNull() { addCriterion("cus_address_l3 is null"); return (Criteria) this; } public Criteria andCusAddressL3IsNotNull() { addCriterion("cus_address_l3 is not null"); return (Criteria) this; } public Criteria andCusAddressL3EqualTo(String value) { addCriterion("cus_address_l3 =", value, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3NotEqualTo(String value) { addCriterion("cus_address_l3 <>", value, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3GreaterThan(String value) { addCriterion("cus_address_l3 >", value, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3GreaterThanOrEqualTo(String value) { addCriterion("cus_address_l3 >=", value, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3LessThan(String value) { addCriterion("cus_address_l3 <", value, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3LessThanOrEqualTo(String value) { addCriterion("cus_address_l3 <=", value, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3Like(String value) { addCriterion("cus_address_l3 like", value, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3NotLike(String value) { addCriterion("cus_address_l3 not like", value, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3In(List<String> values) { addCriterion("cus_address_l3 in", values, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3NotIn(List<String> values) { addCriterion("cus_address_l3 not in", values, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3Between(String value1, String value2) { addCriterion("cus_address_l3 between", value1, value2, "cusAddressL3"); return (Criteria) this; } public Criteria andCusAddressL3NotBetween(String value1, String value2) { addCriterion("cus_address_l3 not between", value1, value2, "cusAddressL3"); return (Criteria) this; } public Criteria andCusSityIsNull() { addCriterion("cus_sity is null"); return (Criteria) this; } public Criteria andCusSityIsNotNull() { addCriterion("cus_sity is not null"); return (Criteria) this; } public Criteria andCusSityEqualTo(String value) { addCriterion("cus_sity =", value, "cusSity"); return (Criteria) this; } public Criteria andCusSityNotEqualTo(String value) { addCriterion("cus_sity <>", value, "cusSity"); return (Criteria) this; } public Criteria andCusSityGreaterThan(String value) { addCriterion("cus_sity >", value, "cusSity"); return (Criteria) this; } public Criteria andCusSityGreaterThanOrEqualTo(String value) { addCriterion("cus_sity >=", value, "cusSity"); return (Criteria) this; } public Criteria andCusSityLessThan(String value) { addCriterion("cus_sity <", value, "cusSity"); return (Criteria) this; } public Criteria andCusSityLessThanOrEqualTo(String value) { addCriterion("cus_sity <=", value, "cusSity"); return (Criteria) this; } public Criteria andCusSityLike(String value) { addCriterion("cus_sity like", value, "cusSity"); return (Criteria) this; } public Criteria andCusSityNotLike(String value) { addCriterion("cus_sity not like", value, "cusSity"); return (Criteria) this; } public Criteria andCusSityIn(List<String> values) { addCriterion("cus_sity in", values, "cusSity"); return (Criteria) this; } public Criteria andCusSityNotIn(List<String> values) { addCriterion("cus_sity not in", values, "cusSity"); return (Criteria) this; } public Criteria andCusSityBetween(String value1, String value2) { addCriterion("cus_sity between", value1, value2, "cusSity"); return (Criteria) this; } public Criteria andCusSityNotBetween(String value1, String value2) { addCriterion("cus_sity not between", value1, value2, "cusSity"); return (Criteria) this; } public Criteria andCusStatusIsNull() { addCriterion("cus_status is null"); return (Criteria) this; } public Criteria andCusStatusIsNotNull() { addCriterion("cus_status is not null"); return (Criteria) this; } public Criteria andCusStatusEqualTo(Integer value) { addCriterion("cus_status =", value, "cusStatus"); return (Criteria) this; } public Criteria andCusStatusNotEqualTo(Integer value) { addCriterion("cus_status <>", value, "cusStatus"); return (Criteria) this; } public Criteria andCusStatusGreaterThan(Integer value) { addCriterion("cus_status >", value, "cusStatus"); return (Criteria) this; } public Criteria andCusStatusGreaterThanOrEqualTo(Integer value) { addCriterion("cus_status >=", value, "cusStatus"); return (Criteria) this; } public Criteria andCusStatusLessThan(Integer value) { addCriterion("cus_status <", value, "cusStatus"); return (Criteria) this; } public Criteria andCusStatusLessThanOrEqualTo(Integer value) { addCriterion("cus_status <=", value, "cusStatus"); return (Criteria) this; } public Criteria andCusStatusIn(List<Integer> values) { addCriterion("cus_status in", values, "cusStatus"); return (Criteria) this; } public Criteria andCusStatusNotIn(List<Integer> values) { addCriterion("cus_status not in", values, "cusStatus"); return (Criteria) this; } public Criteria andCusStatusBetween(Integer value1, Integer value2) { addCriterion("cus_status between", value1, value2, "cusStatus"); return (Criteria) this; } public Criteria andCusStatusNotBetween(Integer value1, Integer value2) { addCriterion("cus_status not between", value1, value2, "cusStatus"); return (Criteria) this; } public Criteria andCusSynIsNull() { addCriterion("cus_syn is null"); return (Criteria) this; } public Criteria andCusSynIsNotNull() { addCriterion("cus_syn is not null"); return (Criteria) this; } public Criteria andCusSynEqualTo(Integer value) { addCriterion("cus_syn =", value, "cusSyn"); return (Criteria) this; } public Criteria andCusSynNotEqualTo(Integer value) { addCriterion("cus_syn <>", value, "cusSyn"); return (Criteria) this; } public Criteria andCusSynGreaterThan(Integer value) { addCriterion("cus_syn >", value, "cusSyn"); return (Criteria) this; } public Criteria andCusSynGreaterThanOrEqualTo(Integer value) { addCriterion("cus_syn >=", value, "cusSyn"); return (Criteria) this; } public Criteria andCusSynLessThan(Integer value) { addCriterion("cus_syn <", value, "cusSyn"); return (Criteria) this; } public Criteria andCusSynLessThanOrEqualTo(Integer value) { addCriterion("cus_syn <=", value, "cusSyn"); return (Criteria) this; } public Criteria andCusSynIn(List<Integer> values) { addCriterion("cus_syn in", values, "cusSyn"); return (Criteria) this; } public Criteria andCusSynNotIn(List<Integer> values) { addCriterion("cus_syn not in", values, "cusSyn"); return (Criteria) this; } public Criteria andCusSynBetween(Integer value1, Integer value2) { addCriterion("cus_syn between", value1, value2, "cusSyn"); return (Criteria) this; } public Criteria andCusSynNotBetween(Integer value1, Integer value2) { addCriterion("cus_syn not between", value1, value2, "cusSyn"); return (Criteria) this; } public Criteria andCusRegDateIsNull() { addCriterion("cus_reg_date is null"); return (Criteria) this; } public Criteria andCusRegDateIsNotNull() { addCriterion("cus_reg_date is not null"); return (Criteria) this; } public Criteria andCusRegDateEqualTo(Date value) { addCriterionForJDBCDate("cus_reg_date =", value, "cusRegDate"); return (Criteria) this; } public Criteria andCusRegDateNotEqualTo(Date value) { addCriterionForJDBCDate("cus_reg_date <>", value, "cusRegDate"); return (Criteria) this; } public Criteria andCusRegDateGreaterThan(Date value) { addCriterionForJDBCDate("cus_reg_date >", value, "cusRegDate"); return (Criteria) this; } public Criteria andCusRegDateGreaterThanOrEqualTo(Date value) { addCriterionForJDBCDate("cus_reg_date >=", value, "cusRegDate"); return (Criteria) this; } public Criteria andCusRegDateLessThan(Date value) { addCriterionForJDBCDate("cus_reg_date <", value, "cusRegDate"); return (Criteria) this; } public Criteria andCusRegDateLessThanOrEqualTo(Date value) { addCriterionForJDBCDate("cus_reg_date <=", value, "cusRegDate"); return (Criteria) this; } public Criteria andCusRegDateIn(List<Date> values) { addCriterionForJDBCDate("cus_reg_date in", values, "cusRegDate"); return (Criteria) this; } public Criteria andCusRegDateNotIn(List<Date> values) { addCriterionForJDBCDate("cus_reg_date not in", values, "cusRegDate"); return (Criteria) this; } public Criteria andCusRegDateBetween(Date value1, Date value2) { addCriterionForJDBCDate("cus_reg_date between", value1, value2, "cusRegDate"); return (Criteria) this; } public Criteria andCusRegDateNotBetween(Date value1, Date value2) { addCriterionForJDBCDate("cus_reg_date not between", value1, value2, "cusRegDate"); return (Criteria) this; } public Criteria andCusUpdateDateIsNull() { addCriterion("cus_update_date is null"); return (Criteria) this; } public Criteria andCusUpdateDateIsNotNull() { addCriterion("cus_update_date is not null"); return (Criteria) this; } public Criteria andCusUpdateDateEqualTo(Date value) { addCriterionForJDBCDate("cus_update_date =", value, "cusUpdateDate"); return (Criteria) this; } public Criteria andCusUpdateDateNotEqualTo(Date value) { addCriterionForJDBCDate("cus_update_date <>", value, "cusUpdateDate"); return (Criteria) this; } public Criteria andCusUpdateDateGreaterThan(Date value) { addCriterionForJDBCDate("cus_update_date >", value, "cusUpdateDate"); return (Criteria) this; } public Criteria andCusUpdateDateGreaterThanOrEqualTo(Date value) { addCriterionForJDBCDate("cus_update_date >=", value, "cusUpdateDate"); return (Criteria) this; } public Criteria andCusUpdateDateLessThan(Date value) { addCriterionForJDBCDate("cus_update_date <", value, "cusUpdateDate"); return (Criteria) this; } public Criteria andCusUpdateDateLessThanOrEqualTo(Date value) { addCriterionForJDBCDate("cus_update_date <=", value, "cusUpdateDate"); return (Criteria) this; } public Criteria andCusUpdateDateIn(List<Date> values) { addCriterionForJDBCDate("cus_update_date in", values, "cusUpdateDate"); return (Criteria) this; } public Criteria andCusUpdateDateNotIn(List<Date> values) { addCriterionForJDBCDate("cus_update_date not in", values, "cusUpdateDate"); return (Criteria) this; } public Criteria andCusUpdateDateBetween(Date value1, Date value2) { addCriterionForJDBCDate("cus_update_date between", value1, value2, "cusUpdateDate"); return (Criteria) this; } public Criteria andCusUpdateDateNotBetween(Date value1, Date value2) { addCriterionForJDBCDate("cus_update_date not between", value1, value2, "cusUpdateDate"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package seleweek2day2; import java.util.List; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class FindElements { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); ChromeDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("http://leafground.com/pages/Button.html"); List<WebElement> allButton=driver.findElementsByTagName("button"); int count = allButton.size(); System.out.println(count); for(WebElement eachButton : allButton) { System.out.println(eachButton.getText()); } WebElement lastElement = allButton.get(count-1); lastElement.click(); } }
package com.example.demo.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.example.demo.model.User; import com.github.pagehelper.Page; @Mapper public interface UserMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table users * * @mbggenerated */ int deleteByPrimaryKey(Long id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table users * * @mbggenerated */ int insert(User record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table users * * @mbggenerated */ User selectByPrimaryKey(Long id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table users * * @mbggenerated */ List<User> selectAll(); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table users * * @mbggenerated */ int updateByPrimaryKey(User record); Page<User> findByPage(); }
package com.example.administrator.panda_channel_app.MVP_Framework.module.live_china; import com.example.administrator.panda_channel_app.MVP_Framework.modle.biz.Panda_channelModle; import com.example.administrator.panda_channel_app.MVP_Framework.modle.biz.Panda_channelModleImpl; import com.example.administrator.panda_channel_app.MVP_Framework.modle.entity.ChildFragmentAllBean; import com.example.administrator.panda_channel_app.MVP_Framework.network.callback.MyNetWorkCallback; /** * Created by Administrator on 2017/7/12 0012. */ public class Live_ChinaPresenter implements Live_ChinaContract.Presenter { Live_ChinaContract.View live_chinaview; private Panda_channelModle panda_channelModle; public Live_ChinaPresenter(Live_ChinaContract.View live_chinaview){ this.live_chinaview=live_chinaview; this.live_chinaview.setPresenter(this); panda_channelModle=new Panda_channelModleImpl(); } @Override public void start() {//实现业务操作 panda_channelModle.getChildFragmentData(new MyNetWorkCallback<ChildFragmentAllBean>() { @Override public void Success(ChildFragmentAllBean childFragmentAllBean) { live_chinaview.setResulst(childFragmentAllBean); } @Override public void onError(String errormsg) { live_chinaview.setError(errormsg); } }); } }
package hu.hevi.timeline.api.controller.response; import hu.hevi.timeline.api.domain.update.Update; import hu.hevi.timeline.api.model.Ticket; import lombok.Builder; import lombok.Value; import java.util.List; @Value @Builder public class TicketResponse { private List<Ticket> tickets; private Overview overview; private List<Update> recentUpdates; }
package edu.rutgers.MOST.optimization.solvers; import java.awt.HeadlessException; import java.io.File; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javassist.Modifier; import javassist.util.proxy.MethodFilter; import javassist.util.proxy.MethodHandler; import javassist.util.proxy.ProxyFactory; import javax.swing.JOptionPane; import org.apache.log4j.Logger; import edu.rutgers.MOST.config.LocalConfig; import edu.rutgers.MOST.data.Solution; import edu.rutgers.MOST.optimization.GDBB.GDBB; import edu.rutgers.MOST.presentation.GraphicalInterface; import edu.rutgers.MOST.presentation.GraphicalInterfaceConstants; public class GurobiSolver extends Solver { //static Logger log = Logger.getLogger(GurobiSolver.class); private URLClassLoader classLoader; private Class<?> grbClass; private Class<?> envClass; private Class<?> modelClass; private Object env; private Object model; private ArrayList<Object> vars = new ArrayList<Object>(); private static boolean isAbort = false; public static void main(String[] args) { //GurobiSolver gurobiSolver = new GurobiSolver("test.log"); } public static void setAbort(boolean isAbort) { GurobiSolver.isAbort = isAbort; } public GurobiSolver() { //public GurobiSolver(String logName) { try { File gurobiJARFile = new File(GraphicalInterface.getGurobiPath()); //File gurobiJARFile = new File("C:\\gurobi500\\win64\\lib\\gurobi.jar"); classLoader = URLClassLoader.newInstance(new URL[]{ gurobiJARFile.toURI().toURL() }); grbClass = classLoader.loadClass("gurobi.GRB"); //log.debug("creating Gurobi environment"); envClass = classLoader.loadClass("gurobi.GRBEnv"); // Constructor<?> envConstr = envClass.getConstructor(new Class[]{ String.class }); // env = envConstr.newInstance(new Object[]{ logName }); Constructor<?> envConstr = envClass.getConstructor(new Class[]{}); env = envConstr.newInstance(new Object[]{}); //log.debug("setting Gurobi parameters"); Class<?> grbDoubleParam = classLoader.loadClass("gurobi.GRB$DoubleParam"); Class<?> grbIntParam = classLoader.loadClass("gurobi.GRB$IntParam"); Enum[] grbDoubleParamConstants = (Enum[]) grbDoubleParam.getEnumConstants(); Enum[] grbIntParamConstants = (Enum[]) grbIntParam.getEnumConstants(); Method envSetDoubleMethod = envClass.getMethod("set", new Class[]{ grbDoubleParam, double.class }); Method envSetIntMethod = envClass.getMethod("set", new Class[]{ grbIntParam, int.class }); for (int i = 0; i < grbDoubleParamConstants.length; i++) { switch (grbDoubleParamConstants[i].name()) { case "FeasibilityTol": envSetDoubleMethod.invoke(env, new Object[]{ grbDoubleParamConstants[i], 1.0E-9 }); break; case "IntFeasTol": envSetDoubleMethod.invoke(env, new Object[]{ grbDoubleParamConstants[i], 1.0E-9 }); break; } } for (int i = 0; i < grbIntParamConstants.length; i++) { switch (grbIntParamConstants[i].name()) { case "OutputFlag": envSetIntMethod.invoke(env, new Object[]{ grbIntParamConstants[i], 0 }); break; } } //log.debug("creating Gurobi Model"); modelClass = classLoader.loadClass("gurobi.GRBModel"); Constructor<?> modelConstr = modelClass.getConstructor(new Class[]{ envClass }); model = modelConstr.newInstance(new Object[]{ env }); this.objType = ObjType.Minimize; } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | ClassNotFoundException | MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { try { Class<?> grbExceptionClass = classLoader.loadClass("gurobi.GRBException"); Method grbExceptionGetErrorCodeMethod = grbExceptionClass.getMethod("getErrorCode", null); int errorCode = (int) grbExceptionGetErrorCodeMethod.invoke(e, null); if (errorCode == grbClass.getDeclaredField("ERROR_NO_LICENSE").getInt(null)) { // GraphicalInterface.getTextInput().setVisible(false); LocalConfig.getInstance().hasValidGurobiKey = false; GraphicalInterface.outputTextArea.setText("ERROR: No validation file - run 'grbgetkey' to refresh it."); Object[] options = {" OK "}; int choice = JOptionPane.showOptionDialog(null, "ERROR: No validation file - run 'grbgetkey' to refresh it.", GraphicalInterfaceConstants.GUROBI_KEY_ERROR_TITLE, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); // if (choice == JOptionPane.YES_OPTION) { // try{ // //Process p; // //p = Runtime.getRuntime().exec("cmd /c start cmd"); // // }catch(Exception e2){} // // } /* if (choice == JOptionPane.NO_OPTION) { } */ } else { handleGurobiException(); } } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | HeadlessException | NoSuchFieldException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } public void abort() { isAbort = true; } @Override public void addConstraint(Map<Integer, Double> map, ConType con, double value) { try { Class<?> grbLinExprClass = classLoader.loadClass("gurobi.GRBLinExpr"); Class<?> grbVarClass = classLoader.loadClass("gurobi.GRBVar"); Object expr = grbLinExprClass.newInstance(); Method exprAddTermMethod = grbLinExprClass.getMethod("addTerm", new Class[]{ double.class, grbVarClass }); Set<Entry<Integer, Double>> s = map.entrySet(); Iterator<Entry<Integer, Double>> it = s.iterator(); while (it.hasNext()) { Map.Entry<Integer, Double> m = it.next(); int key = m.getKey(); Double v = m.getValue(); exprAddTermMethod.invoke(expr, new Object[]{ v, this.vars.get(key) }); } Method modelAddConstrMethod = modelClass.getMethod("addConstr", new Class[]{ grbLinExprClass, char.class, double.class, String.class}); modelAddConstrMethod.invoke(model, new Object[]{expr, getGRBConType(con), value, null}); } catch (IllegalAccessException | ClassNotFoundException | InstantiationException | NoSuchMethodException | SecurityException | IllegalArgumentException | NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { handleGurobiException(); } } @Override public void enable() { isAbort = false; } public void finalize() { // Not guaranteed to be invoked try { Method modelDisposeMethod = modelClass.getMethod("dispose", null); modelDisposeMethod.invoke(model, null); Method envDisposeMethod = envClass.getMethod("dispose", null); envDisposeMethod.invoke(model, null); } catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { handleGurobiException(); } } private char getGRBConType(ConType type) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { switch (type) { case LESS_EQUAL: return grbClass.getDeclaredField("LESS_EQUAL").getChar(null); case EQUAL: return grbClass.getDeclaredField("EQUAL").getChar(null); case GREATER_EQUAL: return grbClass.getDeclaredField("GREATER_EQUAL").getChar(null); default: return grbClass.getDeclaredField("LESS_EQUAL").getChar(null); } } private int getGRBObjType(ObjType type) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { switch (type) { case Minimize: return grbClass.getDeclaredField("MINIMIZE").getInt(null); case Maximize: return grbClass.getDeclaredField("MAXIMIZE").getInt(null); default: return grbClass.getDeclaredField("MINIMIZE").getInt(null); } } private char getGRBVarType(VarType type) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { switch (type) { case CONTINUOUS: return grbClass.getDeclaredField("CONTINUOUS").getChar(null); case BINARY: return grbClass.getDeclaredField("BINARY").getChar(null); case INTEGER: return grbClass.getDeclaredField("INTEGER").getChar(null); case SEMICONT: return grbClass.getDeclaredField("SEMICONT").getChar(null); case SEMIINT: return grbClass.getDeclaredField("SEMIINT").getChar(null); default: return grbClass.getDeclaredField("CONTINUOUS").getChar(null); } } @Override public String getName() { return "GurobiSolver"; } public ArrayList<Double> getSoln() { ArrayList<Double> soln = new ArrayList<Double>(vars.size()); try { Class<?> grbDoubleAttr = classLoader.loadClass("gurobi.GRB$DoubleAttr"); Enum[] grbDoubleAttrConstants = (Enum[]) grbDoubleAttr.getEnumConstants(); Enum xAttr = null; for (int i = 0; i < grbDoubleAttrConstants.length; i++) if (grbDoubleAttrConstants[i].name() == "X") { xAttr = grbDoubleAttrConstants[i]; break; } Class<?> varClass = classLoader.loadClass("gurobi.GRBVar"); Method varGetMethod = varClass.getMethod("get", new Class[]{ grbDoubleAttr }); if (this.vars.size() != 0) { for (int i = 0; i < this.vars.size(); i++) { soln.add((double) varGetMethod.invoke(this.vars.get(i), xAttr)); } } } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { handleGurobiException(); } return soln; } private void handleGurobiException() { Method envGetErrorMsgMethod; try { envGetErrorMsgMethod = envClass.getMethod("getErrorMsg", null); //log.error("Gurobi error: " + (String) envGetErrorMsgMethod.invoke(env, null)); } catch (NoSuchMethodException | SecurityException | IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public double optimize() { try { // Callback logic Method modelGetVarsMethod = modelClass.getMethod("getVars", null); final Object[] vars = (Object[]) modelGetVarsMethod.invoke(model, null); final Class<?> grbCallbackClass = classLoader.loadClass("gurobi.GRBCallback"); final Class<?> grbVarClass = classLoader.loadClass("gurobi.GRBVar"); ProxyFactory factory = new ProxyFactory(); factory.setSuperclass(grbCallbackClass); factory.setFilter( new MethodFilter() { @Override public boolean isHandled(Method method) { return Modifier.isAbstract(method.getModifiers()); } } ); MethodHandler handler = new MethodHandler() { @Override public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { if (thisMethod.getName() == "callback") { if (isAbort) { try { Method grbCallbackAbortMethod = grbCallbackClass.getDeclaredMethod("abort", null); grbCallbackAbortMethod.setAccessible(true); grbCallbackAbortMethod.invoke(self, null); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { handleGurobiException(); } } try { ClassLoader classLoader = grbCallbackClass.getClassLoader(); Class grbClass = classLoader.loadClass("gurobi.GRB"); Field[] asdf = grbClass.getDeclaredFields(); Field whereField = grbCallbackClass.getDeclaredField("where"); whereField.setAccessible(true); int where = whereField.getInt(self); if (where == grbClass.getDeclaredField("CB_MIPSOL").getInt(null)) { Method grbCallbackGetDoubleInfoMethod = grbCallbackClass.getDeclaredMethod("getDoubleInfo", new Class[]{ int.class }); Method grbCallbackGetSolutionMethod = grbCallbackClass.getDeclaredMethod("getSolution", new Class[]{ Array.newInstance(grbVarClass, 0).getClass() }); grbCallbackGetDoubleInfoMethod.setAccessible(true); grbCallbackGetSolutionMethod.setAccessible(true); Solution solution = new Solution((double) grbCallbackGetDoubleInfoMethod.invoke(self, new Object[]{ grbClass.getDeclaredField("CB_MIPSOL_OBJ").getInt(null) }), (double[]) grbCallbackGetSolutionMethod.invoke(self, new Object[]{ vars })); GDBB.intermediateSolution.add(solution); } } catch (ClassNotFoundException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException | NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { handleGurobiException(); } } return null; } }; Method modelSetCallbackMethod = modelClass.getMethod("setCallback", new Class[]{ grbCallbackClass }); Object callback = factory.create(new Class[0], new Object[0], handler); modelSetCallbackMethod.invoke(model, new Object[]{ callback }); Method modelOptimizeMethod = modelClass.getMethod("optimize", null); modelOptimizeMethod.invoke(model, null); // Method modelWriteMethod = modelClass.getMethod("write", new Class[]{ String.class }); // modelWriteMethod.invoke(model, new Object[]{ "model.lp" }); // modelWriteMethod.invoke(model, new Object[]{ "model.mps" }); Class<?> grbDoubleAttr = classLoader.loadClass("gurobi.GRB$DoubleAttr"); Enum[] grbDoubleAttrConstants = (Enum[]) grbDoubleAttr.getEnumConstants(); Enum objValAttr = null; for (int i = 0; i < grbDoubleAttrConstants.length; i++) if (grbDoubleAttrConstants[i].name() == "ObjVal") { objValAttr = grbDoubleAttrConstants[i]; break; } Method modelGetMethod = modelClass.getMethod("get", new Class[]{ grbDoubleAttr }); return (double) modelGetMethod.invoke(model, new Object[]{ objValAttr }); } catch (IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | ClassNotFoundException | InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { handleGurobiException(); } return Double.NaN; } public void setEnv(double timeLimit, int numThreads) { try { //log.debug("setting Gurobi parameters"); Class<?> grbDoubleParam = classLoader.loadClass("gurobi.GRB$DoubleParam"); Class<?> grbIntParam = classLoader.loadClass("gurobi.GRB$IntParam"); Enum[] grbDoubleParamConstants = (Enum[]) grbDoubleParam.getEnumConstants(); Enum[] grbIntParamConstants = (Enum[]) grbIntParam.getEnumConstants(); Method envSetDoubleMethod = envClass.getMethod("set", new Class[]{ grbDoubleParam, double.class }); Method envSetIntMethod = envClass.getMethod("set", new Class[]{ grbIntParam, int.class }); for (int i = 0; i < grbDoubleParamConstants.length; i++) { switch (grbDoubleParamConstants[i].name()) { case "Heuristics": envSetDoubleMethod.invoke(env, new Object[]{ grbDoubleParamConstants[i], 1.0 }); break; case "ImproveStartGap": envSetDoubleMethod.invoke(env, new Object[]{ grbDoubleParamConstants[i], Double.POSITIVE_INFINITY }); break; case "TimeLimit": envSetDoubleMethod.invoke(env, new Object[]{ grbDoubleParamConstants[i], timeLimit}); break; } } for (int i = 0; i < grbIntParamConstants.length; i++) { switch (grbIntParamConstants[i].name()) { case "MIPFocus": envSetIntMethod.invoke(env, new Object[]{ grbIntParamConstants[i], 1 }); break; case "Threads": envSetIntMethod.invoke(env, new Object[]{ grbIntParamConstants[i], numThreads }); break; } } } catch (IllegalAccessException | ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { handleGurobiException(); } } @Override public void setObj(Map<Integer, Double> map) { try { Class<?> grbLinExprClass = classLoader.loadClass("gurobi.GRBLinExpr"); Class<?> grbVarClass = classLoader.loadClass("gurobi.GRBVar"); Object expr = grbLinExprClass.newInstance(); Method exprAddTermMethod = grbLinExprClass.getMethod("addTerm", new Class[]{ double.class, grbVarClass }); Set<Entry<Integer, Double>> s = map.entrySet(); Iterator<Entry<Integer, Double>> it = s.iterator(); while (it.hasNext()) { Map.Entry<Integer, Double> m = it.next(); int key = m.getKey(); Double value = m.getValue(); Object var = this.vars.get(key); exprAddTermMethod.invoke(expr, new Object[]{ value, var }); //System.out.println("key = " + key + " value = " + value); //System.out.println("objType: " + this.objType); } Class<?> grbExprClass = classLoader.loadClass("gurobi.GRBExpr"); Method modelSetObjectiveMethod = modelClass.getMethod("setObjective", new Class[]{ grbExprClass, int.class }); modelSetObjectiveMethod.invoke(model, new Object[]{ expr, getGRBObjType(this.objType) }); } catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException | NoSuchMethodException | InstantiationException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { handleGurobiException(); } } @Override public void setObjType(ObjType objType) { this.objType = objType; } @Override public void setVar(String varName, VarType types, double lb, double ub) { try { if (varName != null && types != null) { Method modelAddVarMethod = modelClass.getMethod("addVar", new Class[]{ double.class, double.class, double.class, char.class, String.class }); Object var = modelAddVarMethod.invoke(this.model, new Object[]{lb, ub, 0.0, getGRBVarType(types), varName}); this.vars.add(var); Method modelUpdateMethod = modelClass.getMethod("update", null); modelUpdateMethod.invoke(this.model, null); } } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { handleGurobiException(); } } @Override public void setVars(VarType[] types, double[] lb, double[] ub) { try { Method modelAddVarMethod = modelClass.getMethod("addVar", new Class[]{ double.class, double.class, double.class, char.class, String.class }); if (types.length == lb.length && lb.length == ub.length) { for (int i = 0; i < lb.length; i++) { Object var = modelAddVarMethod.invoke(this.model, new Object[]{lb[i], ub[i], 0.0, getGRBVarType(types[i]), Integer.toString(i)}); this.vars.add(var); } Method modelUpdateMethod = modelClass.getMethod("update", null); modelUpdateMethod.invoke(this.model, null); } } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { handleGurobiException(); } } }
package com.human.ex; public class quiz0228_04 { public static void main(String[] args) { java.util.Scanner sc = new java.util.Scanner(System.in); System.out.print("두 정수 입력 : "); int a = Integer.parseInt(sc.nextLine()); int b = Integer.parseInt(sc.nextLine()); int res; if(a>=10) { res = a; }else if(b!=0) { res = a / b; }else { res = a; } System.out.println(res); sc.close(); } }
package io.github.daomephsta.mosaic; public class Size { private static final SizeConstraint DEFAULT_PREFERRED_SIZE = SizeConstraint.DEFAULT; private static final int DEFAULT_MAX_SIZE = Integer.MAX_VALUE; private static final int DEFAULT_MIN_SIZE = Integer.MIN_VALUE; private SizeConstraint preferredSize; private int minSize, maxSize; public Size() { this.preferredSize = DEFAULT_PREFERRED_SIZE; this.minSize = DEFAULT_MIN_SIZE; this.maxSize = DEFAULT_MAX_SIZE; } public int computeSize(double parentSize) { // Clamp within [minSize, maxSize] and round return (int) Math.ceil(Math.min(Math.max(preferredSize.toAbsolute(parentSize), minSize), maxSize)); } public void setPreferredSize(SizeConstraint preferred) { this.preferredSize = preferred; } public void setDefaultPreferredSize(SizeConstraint preferred) { if (this.preferredSize == DEFAULT_PREFERRED_SIZE) setPreferredSize(preferred); } public void setMinSize(int minSize) { this.minSize = minSize; } public void setDefaultMinSize(int minSize) { if (this.minSize == DEFAULT_MIN_SIZE) setMinSize(minSize); } public void setMaxSize(int maxSize) { this.maxSize = maxSize; } public void setDefaultMaxSize(int maxSize) { if (this.maxSize == DEFAULT_MAX_SIZE) setMaxSize(maxSize); } public boolean isDefault() { return preferredSize == DEFAULT_PREFERRED_SIZE && minSize == DEFAULT_MIN_SIZE && maxSize == DEFAULT_MAX_SIZE; } @Override public String toString() { return String.format("Size(preferredSize: %s, minSize: %s, maxSize: %s)", preferredSize, minSize, maxSize); } }
package com.cst.test; import java.util.HashMap; import java.util.Map; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class TestCL { public static final String CL_KEY="625051be7f610c"; public static final String CL_ACCOUNT="人帅屌遭罪"; public static final String CL_PASSWD="ran.,~~198722"; public static final String CL_EMAIL="ranbihong2015@gmail.com"; public static final String CL_URL = "http://cl.beett.pw/register.php"; public static final String[] CL_TRY = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; public static void main(String[] args) throws Exception { register("a049aba04232c85f"); // checkKey("de9f1b66b1792fd6"); // for(String t:CL_TRY){ // for(String tt:CL_TRY){ checkKey("a049aba04232c85f"); // } // } /*if(!(CL_KEY.startsWith("_") || CL_KEY.endsWith("_"))){ String[] keys = CL_KEY.split("_"); if(keys.length==2){ for(String t:CL_TRY){ checkKey(keys[0]+t+keys[1]); System.out.println(keys[0]+t+keys[1]); } }else if(keys.length==3){ for(String t:CL_TRY){ for(String tt:CL_TRY){ checkKey(keys[0]+t+keys[1]+tt+keys[2]); System.out.println(keys[0]+t+keys[1]+tt+keys[2]); } } } }else{ if(CL_KEY.startsWith("_")){ String[] keys = CL_KEY.split("_"); if(keys.length==1){ for(String t:CL_TRY){ checkKey(t+keys[0]); System.out.println(t+keys[0]); } }else if(keys.length==2){ for(String t:CL_TRY){ for(String tt:CL_TRY){ checkKey(t+keys[0]+tt+keys[1]); System.out.println(t+keys[0]+tt+keys[1]); } } } }else if(CL_KEY.endsWith("_")){ String[] keys = CL_KEY.split("_"); if(keys.length==1){ for(String t:CL_TRY){ checkKey(keys[0]+t); System.out.println(keys[0]+t); } }else if(keys.length==2){ for(String t:CL_TRY){ for(String tt:CL_TRY){ checkKey(keys[0]+t+keys[1]+tt); System.out.println(keys[0]+t+keys[1]+tt); } } } } }*/ } public static void checkKey(String code) throws Exception{ Map<String, String> map = new HashMap<>(); //检查key map.put("reginvcode", code); map.put("action", "reginvcodeck"); Document doc = Jsoup.connect(CL_URL).data(map).userAgent("Mozilla") .ignoreContentType(true).post(); if(doc.html().toString().contains(">parent.retmsg_invcode('0')")){ System.out.println("code:"+code); register(code); }else{ // System.out.println(doc.html().toString()); } } public static void register(String code) throws Exception{ Map<String, String> map = new HashMap<>(); // //检查名字 // map.put("username", CL_ACCOUNT); // map.put("action", "regnameck"); map.put("regname", CL_ACCOUNT); map.put("regpwd", CL_PASSWD); map.put("regpwdrepeat", CL_PASSWD); map.put("regemail", CL_EMAIL); map.put("invcode", code); map.put("forward", ""); map.put("step", "2"); Document doc = Jsoup.connect(CL_URL).data(map).userAgent("Mozilla") .ignoreContentType(true).post(); // System.out.println(doc.html().toString()); String linkText = new String(doc.html().getBytes(),"UTF-8"); System.out.println(linkText); } }
package Image_recognition; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; public class FileManager { public String classifierId; public FileManager() { classifierId = XML.currentClassifier; } /** * * @param newid: id of a classifier * @param classes: Key: class name, Value: zip file name */ public Map<String, String> addClassifier(String newid, Map<String, String > classes) { Map<String, List<String> > imagesclass = new HashMap<String, List<String>>(); Map<String, String> imagesZip = new HashMap<>(); // unzip each file, and compress Iterator<Map.Entry<String, String> > itr = classes.entrySet().iterator(); while(itr.hasNext()) { Map.Entry<String, String> tmp = itr.next(); List<String> images = FileManager.unZip(XML.ZipDir + tmp.getValue()); List<String> compressed = new ArrayList<>(); // compress each image in the file for(int i = 0; i < images.size(); i++) { String compressfile = FileManager.compressPictureByQality(images.get(i)); if(compressfile == null) continue; compressed.add(compressfile); } // generate new compressed file using compressed files, get the ziped name String zipname = FileManager.createZip(tmp.getKey() + "compressed", compressed); if(zipname == null || compressed.size() == 0) continue; // put the record into imagesclass imagesclass.put(tmp.getKey(), compressed); imagesZip.put(tmp.getKey(), zipname); } // record the files to XML XML.classifyRecord(newid, imagesclass); return imagesZip; } /** * Create zip file from list of images name * @param name: name of the zip files * @param images: list of images in the zip file * @return the ziped file name * @author baeldung https://www.baeldung.com/java-compress-and-uncompress */ public static String createZip(String name, List<String> images) { try { List<String> srcFiles = new ArrayList<String>(images); FileOutputStream fos = new FileOutputStream(XML.ZipDir + name + ".zip"); ZipOutputStream zipOut = new ZipOutputStream(fos); for (String srcFile : srcFiles) { File fileToZip = new File(XML.imageDir + srcFile); FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } fis.close(); } zipOut.close(); fos.close(); return name + ".zip"; }catch(IOException e) { e.printStackTrace(); } return null; } /** * Extract files from zipFile * @param fileZip: the file waiting for extracting * @return list of images name extracted * @throws IOException * @author baeldung https://www.baeldung.com/java-compress-and-uncompress */ public static List<String> unZip(String fileZip) { List<String> images = new ArrayList<String>(); File destDir = new File(XML.imageDir); byte[] buffer = new byte[1024]; try { ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip)); ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { File newFile = newFile(destDir, zipEntry); images.add(zipEntry.getName()); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); zipEntry = zis.getNextEntry(); } zis.closeEntry(); zis.close(); }catch(IOException e) { e.printStackTrace(); } return images; } /** * * @param destinationDir * @param zipEntry * @return * @throws IOException * @author baeldung https://www.baeldung.com/java-compress-and-uncompress */ public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException { File destFile = new File(destinationDir, zipEntry.getName()); String destDirPath = destinationDir.getCanonicalPath(); String destFilePath = destFile.getCanonicalPath(); if (!destFilePath.startsWith(destDirPath + File.separator)) { throw new IOException("Entry is outside of the target dir: " + zipEntry.getName()); } return destFile; } /** * * @author https://stackoverflow.com/questions/44565500/how-can-i-compress-images-using-java */ public static String compressPictureByQality(String imagename) { try { // give a new name to the compressed image System.out.println(imagename); int end = Math.max(Math.max(imagename.indexOf(".JPG"), imagename.indexOf(".jpeg")), imagename.indexOf(".jpg")); if(end == -1) return null; String compressedname = imagename.substring(0, end) + "compress.jpg"; File input = new File(XML.imageDir + imagename); BufferedImage image = ImageIO.read(input); File compressedImageFile = new File(XML.imageDir + compressedname); OutputStream os = new FileOutputStream(compressedImageFile); Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = (ImageWriter) writers.next(); ImageOutputStream ios = ImageIO.createImageOutputStream(os); writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(0.5f); // Change the quality value you prefer writer.write(null, new IIOImage(image, null, null), param); os.close(); ios.close(); writer.dispose(); return compressedname; }catch(IOException e) { e.printStackTrace(); } return null; } }
// https://www.youtube.com/watch?v=fBPS7PtPtaE class Solution { public int lastStoneWeight(int[] stones) { PriorityQueue<Integer> heap = new PriorityQueue<>(Comparator.reverseOrder()); for (int stone: stones) heap.add(stone); while (heap.size() > 1) { int stone1 = heap.remove(); int stone2 = heap.remove(); if (stone1 != stone2) heap.add(stone1 - stone2); } return heap.isEmpty() ? 0 : heap.remove(); } }
package com.vipvideo.view; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import com.vipvideo.R; /** * author: rsw * created on: 2018/10/21 下午2:40 * description: */ public class ClearEditText extends carbon.widget.EditText { private Drawable drawable; private Context context; public ClearEditText(Context context) { super(context); init(context); } public ClearEditText(Context context, AttributeSet attributeSet) { super(context, attributeSet); init(context); } public ClearEditText(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); init(context); } private void init(Context context) { this.context=context; drawable = getResources().getDrawable(R.mipmap.ai_account_register_clear); } protected void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { super.onTextChanged(charSequence, i, i2, i3); setClearIconVisible(hasFocus()&&charSequence.length() > 0); } protected void onFocusChanged(boolean z, int i, Rect rect) { super.onFocusChanged(z, i, rect); setClearIconVisible(length()>0); } public boolean onTouchEvent(MotionEvent motionEvent) { if (motionEvent.getAction() == 1) { Drawable drawable = getCompoundDrawables()[2]; if (drawable != null && motionEvent.getX() <= ((float) (getWidth() - getPaddingRight())) && motionEvent.getX() >= ((float) ((getWidth() - getPaddingRight()) - drawable.getBounds().width()))) { setText(""); } } return super.onTouchEvent(motionEvent); } private void setClearIconVisible(boolean z) { setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[0], getCompoundDrawables()[1], z ? this.drawable : null, getCompoundDrawables()[3]); } }
package dp; import java.util.Scanner; /** * @Author: qixiang.shao * @Description: 最大连续子数列和 * @Date: Created in 15:41 2019/1/4 * @Modified By: */ public class MaxSubStr { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) { int num = sc.nextInt(); nums[i] = num; } int ans = nums[0]; } }
/** * */ package com.application.beans; import android.os.Parcel; import android.os.Parcelable; /** * @author Vikalp Patel(VikalpPatelCE) * */ public class Testimonial implements Parcelable { private String mName; private String mCompany; private String mNote; private String mImageLink; private String mDate; public Testimonial() { super(); // TODO Auto-generated constructor stub } public Testimonial(String mName, String mCompany, String mNote, String mImageLink, String mDate) { super(); this.mName = mName; this.mCompany = mCompany; this.mNote = mNote; this.mImageLink = mImageLink; this.mDate = mDate; } public String getmName() { return mName; } public void setmName(String mName) { this.mName = mName; } public String getmCompany() { return mCompany; } public void setmCompany(String mCompany) { this.mCompany = mCompany; } public String getmNote() { return mNote; } public void setmNote(String mNote) { this.mNote = mNote; } public String getmImageLink() { return mImageLink; } public void setmImageLink(String mImageLink) { this.mImageLink = mImageLink; } public String getmDate() { return mDate; } public void setmDate(String mDate) { this.mDate = mDate; } protected Testimonial(Parcel in) { mName = in.readString(); mCompany = in.readString(); mNote = in.readString(); mImageLink = in.readString(); mDate = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mName); dest.writeString(mCompany); dest.writeString(mNote); dest.writeString(mImageLink); dest.writeString(mDate); } @SuppressWarnings("unused") public static final Parcelable.Creator<Testimonial> CREATOR = new Parcelable.Creator<Testimonial>() { @Override public Testimonial createFromParcel(Parcel in) { return new Testimonial(in); } @Override public Testimonial[] newArray(int size) { return new Testimonial[size]; } }; }
package dev.liambloom.softwareEngineering.chapter17.sort; import java.util.Comparator; import java.util.List; public class Tree { private TreeNode root; private final Comparator<PersonNode> cmp; public Tree(List<PersonNode> list, Comparator<PersonNode> cmp) { this.cmp = cmp; for (PersonNode node : list) add(node); } public void add(PersonNode node) { root = add(root, node); } private TreeNode add(TreeNode parent, PersonNode node) { if (parent == null) return new TreeNode(node); else if (cmp.compare(node, parent.value) <= 0) parent.left = add(parent.left, node); else parent.right = add(parent.right, node); return parent; } public void printInOrder() { System.out.println("Sorted via " + cmp.getClass().getSimpleName()); System.out.println(" Last Name | First Name | Middle Name | ID Number "); System.out.println("-------------+-------------+-------------+------------"); printInOrder(root); System.out.println(); } private static void printInOrder(final TreeNode node) { if (node != null) { printInOrder(node.left); System.out.print(' '); for (final String column : new String[]{node.value.getLastName(), node.value.getFirstName(), node.value.getMiddleName()}) { if (column.length() > 11) System.out.print(column.substring(0, 8) + "..."); else System.out.print(column + " ".repeat(11 - column.length())); System.out.print(" | "); } System.out.println(node.value.getIdNum()); printInOrder(node.right); } } }
package github.dwstanle.tickets.repository; import github.dwstanle.tickets.model.Reservation; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional public interface ReservationRepository extends JpaRepository<Reservation, Long> { List<Reservation> findByAccount(String email); List<Reservation> findByEventId(Long id); }
package com.lenovohit.hwe.mobile.core.web.rest; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.core.utils.JSONUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.hwe.mobile.core.model.Classification; import com.lenovohit.hwe.mobile.core.model.Emergency; @RestController @RequestMapping("hwe/app/emergency") public class EmergencyRestController extends MobileBaseRestController { @Autowired private GenericManager<Emergency, String> emergencyManager; @Autowired private GenericManager<Classification, String> classificationManager; //查找急救类型 @RequestMapping(value = "/listEmergencyType", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listCommonDisease(@RequestParam(value = "data", defaultValue = "") String data) { List<Classification> dicts=classificationManager.findByProp("classType", 4); return ResultUtils.renderSuccessResult(dicts); } //根据关键字搜索急救方法 @RequestMapping(value = "/listByKeyWords", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listByKeyWords(@RequestParam(value = "data", defaultValue = "") String data) { Emergency model = JSONUtils.deserialize(data, Emergency.class); List<Object> values=new ArrayList<Object>(); String jql="from Emergency where fakName like ? "; values.add("%" + model.getFakName() + "%"); List<Emergency> firstAid=(List<Emergency>) emergencyManager.findByJql(jql, values.toArray()); return ResultUtils.renderSuccessResult(firstAid); } //根据急救类型搜索急救方法 @RequestMapping(value = "/listEmergencyByType", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listEmergencyByType(@RequestParam(value = "data", defaultValue = "") String data) { Classification model = JSONUtils.deserialize(data, Classification.class); String jql="from Emergency where classificationId = ? "; List<Object> values=new ArrayList<Object>(); values.add(model.getClassificationId().trim()); //c=emergencyManager.findByProp("classificationId", model.getClassificationId()); List<Emergency> emergencys=(List<Emergency>) emergencyManager.findByJql(jql, values.toArray()); return ResultUtils.renderSuccessResult(emergencys); } }
package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { StringProcessing str_process = new StringProcessing(); StProccesingBuffer stBuffer = new StProccesingBuffer(); reStrings restr = new reStrings(); Scanner in = new Scanner(System.in); boolean run = true; while(run){ Scanner scan = new Scanner(System.in); System.out.println("1. Первое задание с применением класса String"); System.out.println("2. Второе задание с применением класса StringBuilder"); System.out.println("3. Третье задание - регулярные выражения"); int choice = scan.nextInt(); switch(choice) { case 1: System.out.println("1. Разделить текст на абзацы"); System.out.println("2. В каждом абзаце первое и последнее слово записать с CAPS LOCK"); System.out.println("3. Определите количество слов в конкретном абзаце, имеющие сочетание 'ам' "); System.out.println("4. Сформировать новую строку, содеражащую информацию о кол-ве предложений."); int choice_first = scan.nextInt(); switch (choice_first) { case 1: str_process.transform_string(); break; case 2: str_process.change_register(); break; case 3: System.out.println("Введите номер абзаца: "); int position = scan.nextInt(); str_process.search_substring(position); break; case 4: System.out.println(str_process.create_info()); break; } break; case 2: System.out.println("1. Разделить текст на абзацы"); System.out.println("2. В каждом абзаце первое и последнее слово записать с CAPS LOCK"); System.out.println("3. Добавить в текст информацию, отображающую количество предложений в тексте."); int choice_second = scan.nextInt(); switch (choice_second) { case 1: stBuffer.transform_string(); break; case 2: stBuffer.change_register(); break; case 3: stBuffer.append_info(); break; } break; case 3: System.out.println("1. Определить, что строка состоит из двух одинаковых цифр."); System.out.println("2. Ввести текст и замените все числа, удовлетворяющие условию 1, на '*'"); int choice_third = scan.nextInt(); switch (choice_third) { case 1: System.out.println("Введите строку: "); String str = in.nextLine(); String result = restr.is_string_consists_2num(str) ? "Введеная строка состоит из 2 одинаковых цифр." : "Введеная строка НЕ состоит из 2 одинаковых цифр."; System.out.println(result); break; case 2: System.out.println("Введите текст: "); String text = in.nextLine(); reStrings reStr = new reStrings(text); reStr.replace_numeric(); break; } break; } } } }
package com.wuc.libnavannotation; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * @author: wuchao * @date: 2020-01-18 22:57 * @desciption: */ @Target(ElementType.TYPE) public @interface FragmentDestination { String pageUrl(); /* 登录标志,有些页面需要登录后才能进入 */ boolean needLogin() default false; /* startDestination 是否把当前页面作为开始页面 */ boolean asStarter() default false; }
package com.thomson.dp.principle.zen.lsp.domain; /** * 士兵的实现类 * * @author Thomson Tang */ public class Solider { /** * 士兵拥有枪支, * <p>这把枪是抽象的,是枪就有shoot方法,也就可以杀人,<br> * 具体是什么枪,在上战场前通过setGun方法来确定</p> */ private AbstractGun gun; /** * 士兵可以杀敌 * <p>杀敌的方式是士兵调用枪支的shoot方法</p> */ public void killEnemy() { System.out.println("士兵开始杀敌....."); System.out.println("士兵用的枪的形状是:" + gun.getShape()); gun.shoot(); } /** * 给士兵配备一支枪 * * @param gun 枪 */ public void setGun(AbstractGun gun) { this.gun = gun; } }
package com.bupsolutions.polaritydetection.ml.sentiwordnet; import com.bupsolutions.polaritydetection.ml.ClassificationModel; import com.bupsolutions.polaritydetection.ml.SubjectivityHandler; import com.bupsolutions.polaritydetection.ml.SubjectivityModel; import com.bupsolutions.polaritydetection.model.Subjectivity; import java.io.IOException; import java.util.List; import java.util.Map; public class SentiWordNetSubjectivityModel extends SentiWordNetEnhancedModel<Subjectivity> implements SubjectivityModel { public SentiWordNetSubjectivityModel(ClassificationModel<Subjectivity> model, String sentiWordNetPath) throws IOException { super(model, sentiWordNetPath); } @Override public Subjectivity eval(String message) { Map<Subjectivity, Double> map = getProbabilities(message); return new SubjectivityHandler().getSubjectivity(map); } @Override public Map<Subjectivity, Double> getProbabilities(String message) { Map<Subjectivity, Double> map = getModel().getProbabilities(message); double subScore = map.get(Subjectivity.SUBJECTIVE); List<Double> swnScores = getScores(message); double infScore = Math.abs(infScore(swnScores)); double euclScore = Math.abs(euclScore(swnScores)); if (infScore > 0.4 || euclScore > 0.4) { infScore = (infScore + 1) / 2; subScore = 0.15 * subScore + 0.85 * infScore; } double objScore = 1 - subScore; map.put(Subjectivity.SUBJECTIVE, subScore); map.put(Subjectivity.OBJECTIVE, objScore); return map; } }
package com.newbig.im.common.constant; public class AppConstant { public static final String API_PREFIX_V1 = "/api/v1"; public static final String TOKEN_HEADER = "AppToken"; public static final String EXECUTION = "execution (* com..*.app.controller..*(..))"; public static final String PACKAGE_NAME = "com.newbig.im"; public static final String SECRET = "apptoken"; public static final String ISSUER = PACKAGE_NAME; public static final String USER_ID = "userId"; public static final String MOBILE = "mobile"; }
package com.thomsontang.dp.command.hfdp.domain; import com.thomsontang.dp.command.hfdp.Light; /** * the light in room. * * @author Thomson Tang */ public class LivingRoomLight implements Light { @Override public void on() { System.out.println("the room light is on..."); } @Override public void off() { System.out.println("the room light is off..."); } }
package screens.components; import java.awt.image.BufferedImage; import gui.components.ClickableGraphic; import gui.components.Graphic; public class EnemyRobot extends ClickableGraphic{ public EnemyRobot(int x, int y, int w, int h, String imageLocation) { super(x, y, w, h, imageLocation); // TODO Auto-generated constructor stub } public void changeLocation() { } }
package demo.kafka.connector; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.CSVWriter; import demo.kafka.config.MySinkConnectorConfig; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.connect.sink.SinkRecord; import org.apache.kafka.connect.sink.SinkTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.UUID; import com.github.jcustenborder.kafka.connect.utils.VersionUtil; public class MySinkTask extends SinkTask { /* Your connector should never use System.out for logging. All of your classes should use slf4j for logging */ private static Logger log = LoggerFactory.getLogger(MySinkTask.class); CSVWriter csvWriter; MySinkConnectorConfig config; ObjectMapper objectMapper; @Override public void start(Map<String, String> settings) { this.config = new MySinkConnectorConfig(settings); objectMapper = new ObjectMapper(); try { this.csvWriter = new CSVWriter(new FileWriter("messages_" + UUID.randomUUID().toString() + ".csv")); } catch (IOException e) { log.error(e.getMessage()); } String[] headers = {"offset", "partition_id", "topic","payload"}; csvWriter.writeNext(headers); } @Override public void put(Collection<SinkRecord> records) { records.forEach(record -> { String[] line = {String.valueOf(record.kafkaOffset()), String.valueOf(record.kafkaPartition()), record.topic(), record.value().toString()}; csvWriter.writeNext(line); csvWriter.flushQuietly(); }); } @Override public void flush(Map<TopicPartition, OffsetAndMetadata> map) { csvWriter.flushQuietly(); } @Override public void stop() { try { csvWriter.flush(); csvWriter.close(); } catch (IOException e) { log.error(e.getMessage()); } } @Override public String version() { return VersionUtil.version(this.getClass()); } }
package io.ceph.rgw.client.core.admin; import io.ceph.rgw.client.exception.RGWServerException; import org.junit.Test; import org.junit.experimental.categories.Category; /** * @author zhuangshuo * Created by zhuangshuo on 2020/7/31. */ @Category(AdminTests.class) public class GetPolicyTest extends BaseAdminClientTest { @Test(expected = RGWServerException.class) public void testNoBucket() { logResponse(adminClient.prepareGetPolicy() .withBucket("not exists") .run()); } @Test(expected = RGWServerException.class) public void testNoKey() { logResponse(adminClient.prepareGetPolicy() .withBucket("test") .withObject("not exists") .run()); } @Test public void testSync() { logResponse(adminClient.prepareGetPolicy() .withBucket(bucket) .run()); } @Test public void testCallback() throws InterruptedException { Latch latch = newLatch(); adminClient.prepareGetPolicy() .withBucket(bucket) .execute(newActionListener(latch)); latch.await(); } @Test public void testAsync() { logResponse(adminClient.prepareGetPolicy() .withBucket(bucket) .execute()); } @Override protected boolean isCreateBucket() { return true; } }
/* * ### Copyright (C) 2001-2003 Michael Fuchs ### * * 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 2, 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, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Author: Michael Fuchs * E-Mail: mfuchs@unico-consulting.com * * RCS Information: * --------------- * Id.........: $Id: ImgTests.java,v 1.1.1.1 2004/12/21 14:00:01 mfuchs Exp $ * Author.....: $Author: mfuchs $ * Date.......: $Date: 2004/12/21 14:00:01 $ * Revision...: $Revision: 1.1.1.1 $ * State......: $State: Exp $ */ package org.dbdoclet.test.transform; import junit.framework.Test; import junit.framework.TestSuite; import org.dbdoclet.log.Logger; public class ImgTests extends XmlTestCase { /** * The variable <code>logger</code>{@link org.apache.log4j.Logger (org.apache.log4j.Logger)} * can be used to print logging information via the log4j framework. */ private static Log logger = LogFactory.getLog(ImgTests.class); public static Test suite() { return new TestSuite(ImgTests.class); } public void testTransformImg2() throws Exception { String code = "<pre class=\"programlisting\">&lt;?xml version='1.0'&gt; <a name=\"xmlversion\" href=\"Version.html\"><img src=\"images/1.png\" alt=\"1\" border=\"0\"></a></pre>"; checkDocBook(code, true); } public void testTransformImg3() throws Exception { String code = "<a><img src=\"figures/img1.jpg\"></a><img src=\"figures/img2.jpg\">"; checkDocBook(code, true); } public void testTransformImg4() throws Exception { String code = "<center>" + "<img src=\"prev.gif\" alt=\"Zur�ck\">" + "<img src=\"toc.gif\" alt=\"Inhalt\">" + "<a href=\"#\" rel=\"next\"><img src=\"next.gif\" alt=\"Weiter\" border=\"0\"></a>" + "</center>"; checkDocBook(code, true); } public void testTransformImg5() throws Exception { String code = "This is an empty img tag example: <img>."; checkDocBook(code, true); } public void testTransformImg6() throws Exception { String code = "?img src=\"figures/logo.jpg\"?: <img src=\"figures/logo.jpg\">."; checkDocBook(code, true); } public void testTransformImg7() throws Exception { String code = "<p>Some Text before the img!</p>\n" + "<img src=\"figures/logo.jpg\">\n" + "<p>!Some Text after the image</p>\n"; checkDocBook(code, true); } public void testTransformImg8() throws Exception { String code = "<p>Paragraph <b><img src=\"b1.gif\"></b></p>."; checkDocBook(code, true); } } /* * $Log: ImgTests.java,v $ * Revision 1.1.1.1 2004/12/21 14:00:01 mfuchs * Reimport * * Revision 1.2 2004/10/05 13:13:18 mfuchs * Sicherung * * Revision 1.1.1.1 2004/02/17 22:49:23 mfuchs * dbdoclet * * Revision 1.1.1.1 2004/01/05 14:56:57 cvs * dbdoclet * * Revision 1.2 2003/11/30 20:43:44 cvs * Many fixes. Command line options. * * Revision 1.1.1.1 2003/08/01 13:18:08 cvs * DocBook Doclet * * Revision 1.1.1.1 2003/07/31 17:05:40 mfuchs * DocBook Doclet since 0.46 * * Revision 1.1.1.1 2003/05/30 11:09:40 mfuchs * dbdoclet * * Revision 1.2 2003/05/30 10:07:49 mfuchs * Bugfixes and improvements. * * Revision 1.1.1.1 2003/03/18 07:41:37 mfuchs * DocBook Doclet 0.40 * * Revision 1.1.1.1 2003/03/17 20:50:24 cvs * dbdoclet * */
package com.example.gamedb.adapter; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.preference.PreferenceManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.gamedb.R; import com.example.gamedb.db.entity.Game; import com.example.gamedb.ui.fragment.GameListFragment; import java.util.ArrayList; import java.util.List; public class GameListAdapter extends RecyclerView.Adapter<GameListAdapter.GameListViewHolder> { private List<Game> mGames = new ArrayList<>(); // The fragment's interaction listener is needed to perform actions from the recyclerview private GameListFragment.OnGameListFragmentInteractionListener mListener; public GameListAdapter(GameListFragment.OnGameListFragmentInteractionListener listener) { this.mListener = listener; } public void setGames(List<Game> games) { mGames = games; } @NonNull @Override public GameListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.game_list_item, parent, false); return new GameListViewHolder(view, mListener); } @Override public void onBindViewHolder(@NonNull GameListViewHolder holder, int position) { Game game = mGames.get(position); if (game.getPosterImage() != null) { Uri imageUri = Uri.parse(holder.mIgdbImageUrl).buildUpon() .appendPath("t_logo_med") .appendPath(game.getPosterImage() + ".jpg") .build(); Glide.with(holder.mContext) .load(imageUri.toString()) .centerCrop() .into(holder.mImageView); } } @Override public int getItemCount() { return mGames.size(); } public class GameListViewHolder extends RecyclerView.ViewHolder { private final Context mContext; private final ImageView mImageView; private GameListFragment.OnGameListFragmentInteractionListener mListener; private final String mIgdbImageUrl; public GameListViewHolder(@NonNull final View itemView, GameListFragment.OnGameListFragmentInteractionListener listener) { super(itemView); this.mContext = itemView.getContext(); mImageView = itemView.findViewById(R.id.image_view_game_list_item); mListener = listener; SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(mContext); mIgdbImageUrl = preference.getString(mContext.getResources().getString( R.string.igdb_image_url), ""); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Game game = mGames.get(getAdapterPosition()); mListener.onGameSelected(game.getId()); } }); } } }
package pageobject; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import base.PageBase; public class HomePage extends PageBase { // ========= ELEMENTS in the Home Page ======================== @FindBy(xpath="//a[text()='Log In']") private WebElement loginButton ; // null @FindBy(xpath="//a[text()='Sign Up']") private WebElement signUpButton; // null //Constructor public HomePage(WebDriver inputDriver) { super(inputDriver); driver.get("https://www.trello.com"); PageFactory.initElements(driver, this); } //=========== Actions we can perfomr in the Home Page ============= public String clickLoginButton() { loginButton.click(); waitfor(2); String bannerText = driver.findElement(By.tagName("h1")).getText(); return bannerText; } public String clickSignUpButton() { signUpButton.click(); waitfor(2); String bannerText = driver.findElement(By.tagName("h1")).getText(); return bannerText; } }
package so.team.bukkitlejyon.cmdBlock.api.event; import org.bukkit.block.CommandBlock; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class CommandBlockEditEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private Player player; private CommandBlock block; private String newCommand; private String oldCommand; private boolean cancel; public CommandBlockEditEvent(Player player, CommandBlock block, String oldCommand, String newCommand) { this.player = player; this.block = block; this.oldCommand = oldCommand; this.newCommand = newCommand; } public Player getPlayer() { return this.player; } public CommandBlock getBlock() { return this.block; } public String getOldCommand() { return this.oldCommand; } public String getNewCommand() { return this.newCommand; } public void setNewCommand(String command) { this.newCommand = command; } public boolean isCancelled() { return this.cancel; } public void setCancelled(boolean cancel) { this.cancel = cancel; } public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
package com.cninnovatel.ev.db; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.Property; import de.greenrobot.dao.internal.DaoConfig; import com.cninnovatel.ev.db.RestUser_; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table "REST_USER_". */ public class RestUser_Dao extends AbstractDao<RestUser_, Long> { public static final String TABLENAME = "REST_USER_"; /** * Properties of entity RestUser_.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Id = new Property(0, Long.class, "id", true, "_id"); public final static Property Name = new Property(1, String.class, "name", false, "NAME"); public final static Property DisplayName = new Property(2, String.class, "displayName", false, "DISPLAY_NAME"); public final static Property Email = new Property(3, String.class, "email", false, "EMAIL"); public final static Property Telephone = new Property(4, String.class, "telephone", false, "TELEPHONE"); public final static Property Cellphone = new Property(5, String.class, "cellphone", false, "CELLPHONE"); public final static Property UnitId = new Property(6, Integer.class, "unitId", false, "UNIT_ID"); public final static Property UnitName = new Property(7, String.class, "unitName", false, "UNIT_NAME"); public final static Property DepartmentId = new Property(8, Integer.class, "departmentId", false, "DEPARTMENT_ID"); public final static Property DepName = new Property(9, String.class, "depName", false, "DEP_NAME"); public final static Property OrgId = new Property(10, Integer.class, "orgId", false, "ORG_ID"); public final static Property OrgName = new Property(11, String.class, "orgName", false, "ORG_NAME"); public final static Property H323ConfNumber = new Property(12, String.class, "h323ConfNumber", false, "H323_CONF_NUMBER"); public final static Property SipConfNumber = new Property(13, String.class, "sipConfNumber", false, "SIP_CONF_NUMBER"); public final static Property Pstn = new Property(14, String.class, "pstn", false, "PSTN"); public final static Property Description = new Property(15, String.class, "description", false, "DESCRIPTION"); public final static Property CallNumber = new Property(16, String.class, "callNumber", false, "CALL_NUMBER"); public final static Property ImageURL = new Property(17, String.class, "imageURL", false, "IMAGE_URL"); public final static Property LastModifiedTime = new Property(18, Long.class, "lastModifiedTime", false, "LAST_MODIFIED_TIME"); }; public RestUser_Dao(DaoConfig config) { super(config); } public RestUser_Dao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(SQLiteDatabase db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"REST_USER_\" (" + // "\"_id\" INTEGER PRIMARY KEY ," + // 0: id "\"NAME\" TEXT," + // 1: name "\"DISPLAY_NAME\" TEXT," + // 2: displayName "\"EMAIL\" TEXT," + // 3: email "\"TELEPHONE\" TEXT," + // 4: telephone "\"CELLPHONE\" TEXT," + // 5: cellphone "\"UNIT_ID\" INTEGER," + // 6: unitId "\"UNIT_NAME\" TEXT," + // 7: unitName "\"DEPARTMENT_ID\" INTEGER," + // 8: departmentId "\"DEP_NAME\" TEXT," + // 9: depName "\"ORG_ID\" INTEGER," + // 10: orgId "\"ORG_NAME\" TEXT," + // 11: orgName "\"H323_CONF_NUMBER\" TEXT," + // 12: h323ConfNumber "\"SIP_CONF_NUMBER\" TEXT," + // 13: sipConfNumber "\"PSTN\" TEXT," + // 14: pstn "\"DESCRIPTION\" TEXT," + // 15: description "\"CALL_NUMBER\" TEXT," + // 16: callNumber "\"IMAGE_URL\" TEXT," + // 17: imageURL "\"LAST_MODIFIED_TIME\" INTEGER);"); // 18: lastModifiedTime } /** Drops the underlying database table. */ public static void dropTable(SQLiteDatabase db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"REST_USER_\""; db.execSQL(sql); } /** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, RestUser_ entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String name = entity.getName(); if (name != null) { stmt.bindString(2, name); } String displayName = entity.getDisplayName(); if (displayName != null) { stmt.bindString(3, displayName); } String email = entity.getEmail(); if (email != null) { stmt.bindString(4, email); } String telephone = entity.getTelephone(); if (telephone != null) { stmt.bindString(5, telephone); } String cellphone = entity.getCellphone(); if (cellphone != null) { stmt.bindString(6, cellphone); } Integer unitId = entity.getUnitId(); if (unitId != null) { stmt.bindLong(7, unitId); } String unitName = entity.getUnitName(); if (unitName != null) { stmt.bindString(8, unitName); } Integer departmentId = entity.getDepartmentId(); if (departmentId != null) { stmt.bindLong(9, departmentId); } String depName = entity.getDepName(); if (depName != null) { stmt.bindString(10, depName); } Integer orgId = entity.getOrgId(); if (orgId != null) { stmt.bindLong(11, orgId); } String orgName = entity.getOrgName(); if (orgName != null) { stmt.bindString(12, orgName); } String h323ConfNumber = entity.getH323ConfNumber(); if (h323ConfNumber != null) { stmt.bindString(13, h323ConfNumber); } String sipConfNumber = entity.getSipConfNumber(); if (sipConfNumber != null) { stmt.bindString(14, sipConfNumber); } String pstn = entity.getPstn(); if (pstn != null) { stmt.bindString(15, pstn); } String description = entity.getDescription(); if (description != null) { stmt.bindString(16, description); } String callNumber = entity.getCallNumber(); if (callNumber != null) { stmt.bindString(17, callNumber); } String imageURL = entity.getImageURL(); if (imageURL != null) { stmt.bindString(18, imageURL); } Long lastModifiedTime = entity.getLastModifiedTime(); if (lastModifiedTime != null) { stmt.bindLong(19, lastModifiedTime); } } /** @inheritdoc */ @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } /** @inheritdoc */ @Override public RestUser_ readEntity(Cursor cursor, int offset) { RestUser_ entity = new RestUser_( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // displayName cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // email cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // telephone cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // cellphone cursor.isNull(offset + 6) ? null : cursor.getInt(offset + 6), // unitId cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7), // unitName cursor.isNull(offset + 8) ? null : cursor.getInt(offset + 8), // departmentId cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9), // depName cursor.isNull(offset + 10) ? null : cursor.getInt(offset + 10), // orgId cursor.isNull(offset + 11) ? null : cursor.getString(offset + 11), // orgName cursor.isNull(offset + 12) ? null : cursor.getString(offset + 12), // h323ConfNumber cursor.isNull(offset + 13) ? null : cursor.getString(offset + 13), // sipConfNumber cursor.isNull(offset + 14) ? null : cursor.getString(offset + 14), // pstn cursor.isNull(offset + 15) ? null : cursor.getString(offset + 15), // description cursor.isNull(offset + 16) ? null : cursor.getString(offset + 16), // callNumber cursor.isNull(offset + 17) ? null : cursor.getString(offset + 17), // imageURL cursor.isNull(offset + 18) ? null : cursor.getLong(offset + 18) // lastModifiedTime ); return entity; } /** @inheritdoc */ @Override public void readEntity(Cursor cursor, RestUser_ entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setDisplayName(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); entity.setEmail(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3)); entity.setTelephone(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4)); entity.setCellphone(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5)); entity.setUnitId(cursor.isNull(offset + 6) ? null : cursor.getInt(offset + 6)); entity.setUnitName(cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7)); entity.setDepartmentId(cursor.isNull(offset + 8) ? null : cursor.getInt(offset + 8)); entity.setDepName(cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9)); entity.setOrgId(cursor.isNull(offset + 10) ? null : cursor.getInt(offset + 10)); entity.setOrgName(cursor.isNull(offset + 11) ? null : cursor.getString(offset + 11)); entity.setH323ConfNumber(cursor.isNull(offset + 12) ? null : cursor.getString(offset + 12)); entity.setSipConfNumber(cursor.isNull(offset + 13) ? null : cursor.getString(offset + 13)); entity.setPstn(cursor.isNull(offset + 14) ? null : cursor.getString(offset + 14)); entity.setDescription(cursor.isNull(offset + 15) ? null : cursor.getString(offset + 15)); entity.setCallNumber(cursor.isNull(offset + 16) ? null : cursor.getString(offset + 16)); entity.setImageURL(cursor.isNull(offset + 17) ? null : cursor.getString(offset + 17)); entity.setLastModifiedTime(cursor.isNull(offset + 18) ? null : cursor.getLong(offset + 18)); } /** @inheritdoc */ @Override protected Long updateKeyAfterInsert(RestUser_ entity, long rowId) { entity.setId(rowId); return rowId; } /** @inheritdoc */ @Override public Long getKey(RestUser_ entity) { if(entity != null) { return entity.getId(); } else { return null; } } /** @inheritdoc */ @Override protected boolean isEntityUpdateable() { return true; } }
package com.company.Devices.State; import com.company.Devices.SmartDevice; import com.company.Net.TCPConnection; public class SwitchOffState extends State { public SwitchOffState(SmartDevice sender, TCPConnection connection) { super(sender, connection); } @Override public void turnOn() { System.out.println(sender.getName() + "turnOn device from SwitchOffState"); } @Override public void turnOff() { System.out.println(sender.getName() + "already turnOff"); } @Override public void reset() { System.out.println(sender.getName() + "reset device from SwitchOffState"); } @Override public void block() { System.out.println(sender.getName() + "block device from SwitchOffState"); } }
package cc.mzou.idea; /** * Created by cheng on 18/12/16. */ public class DemoOne { public void showName(){ System.out.println("this is class DemoTwo"); } }
package codePlus.AGBasic2.BruteForce; import java.util.*; public class No_3085 { static int n; static int max; static char [][] arr; public static void main(String[] args) { Scanner scn = new Scanner(System.in); n = scn.nextInt(); arr = new char [n][n]; max = 0; //먹을 수 있는 사탕의 최대 개수 for(int i=0; i<n; i++) { String str = scn.next(); //for문 안에 있어야 하는 이유? 한 줄 씩 읽고, 문자열을 쪼개야 하므로 //for문 밖에 있으면? n줄 중 첫 줄의 데이터만 배열에 반복적으로 입력됨 for(int j=0; j<arr[i].length; j++) { arr[i][j]=str.charAt(j); // System.out.print(arr[i]); } // System.out.println(); } //오른쪽 칸의 사탕과 차례로 교환해보고 원위치로 되돌리기 for(int i=0; i<n;i++) { for(int j=0; j<n-1;j++) { char temp = arr[i][j]; arr[i][j] = arr[i][j+1]; arr[i][j+1] = temp; maxCandies(); //오른쪽,아래쪽으로 쭉 훑으면서 사탕의 최대 갯수 구하기 } } //왼쪽 칸의 사탕과 차례로 교환해보고 원위치로 되돌리기 for(int i=0; i<n; i++) { for(int j=0; j<n-1; j++) { maxCandies(); //오른쪽,아래쪽으로 쭉 훑으면서 사탕의 최대갯수 구하기 } } } public static int maxCandies() { int count = 1; //같은 색상의 사탕이 나오는 가장 긴 연속 부분 행/열의 "초기값" //오른쪽 칸과 비교하면서 먹을 수 있는 사탕의 최대 개수 구하기 (색상이 같다고 해서 사탕을 교환하진 x) for(int i=0; i<n; i++) { for(int j=0; j<n-1; j++) { //arr[i][j] : 왼쪽칸, arr[i][j+1] : 오른쪽칸 if(arr[i][j]==arr[i][j+1]) { // 오른쪽칸과 같은 색상의 사탕인 경우 -> 냠냠 count++; } else { // 오른쪽칸과 다른 색상의 사탕인 경우 count = 1; } max = Math.max(max, count); //먹을 수 있는 사탕의 최대개수를 저장 } } count = 1; //아래 칸과 비교하면서 먹을 수 있는 사탕의 최대 개수 구하기 (색상이 같다고 해서 사탕을 교환하진 x) for(int i=0; i<n; i++) { for(int j=0; j<n-1; j++) { //arr[i][j] : 윗칸, arr[i+1][j] : 아래칸 if(arr[i][j]==arr[i+1][j]) { count++; } else count = 1; max = Math.max(max, count); } } return max; } }
package com.arthur.leetcode; import com.sun.org.apache.xpath.internal.WhitespaceStrippingElementMatcher; import java.util.List; /** * @title: No61 * @Author ArthurJi * @Date: 2021/3/27 9:36 * @Version 1.0 */ public class No61 { public static void main(String[] args) { } public class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public ListNode rotateRight(ListNode head, int k) { if(head == null || head.next == null || k == 0) { return head; } ListNode fast = head; ListNode slow = head; int len = 0; ListNode temp = head; while (temp!= null){ len++; temp = temp.next; } int n = k % len; if(n == 0) { return head; } while (fast != null && n-- != 0) { fast = fast.next; } while (fast.next != null ) { slow = slow.next; fast = fast.next; } ListNode newHead = slow.next; slow.next = null; fast.next = head; return newHead; } } /* 61. 旋转链表 给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。 示例 1: 输入:head = [1,2,3,4,5], k = 2 输出:[4,5,1,2,3] 示例 2: 输入:head = [0,1,2], k = 4 输出:[2,0,1]*/
package com.clicky.semarnat.data; import com.parse.ParseClassName; import com.parse.ParseObject; import com.parse.ParseQuery; /** * * Created by Clicky on 4/2/15. * */ @ParseClassName("Materia_Prima") public class MateriaPrima extends ParseObject { public String getTipo() { return getString("Tipo"); } public Number getCantidad() { return getNumber("numer_cantidad"); } public String getDescripcion() { return getString("descripcion"); } public String getVolumen() { return getString("volumen_peso_amp"); } public String getUnidad() { return getString("unidad_medida"); } public Number getSaldoDisponible() { return getNumber("saldo_disp"); } public Number getSaldoRestante() { return getNumber("saldo_rest"); } public Documentos getDocumento() { return (Documentos)getParseObject("Documentos"); } public static ParseQuery<MateriaPrima> getQuery() { return ParseQuery.getQuery(MateriaPrima.class); } }
package com.doterob.transparencia.connector.contract.extractor.xunta; import com.doterob.transparencia.connector.HttpService; import com.doterob.transparencia.model.ContractComplex; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * Created by dotero on 14/05/2016. */ public class XuntaConnectorExecutor extends HttpService implements XuntaConnector { private static final Logger LOG = LogManager.getLogger(XuntaConnectorExecutor.class); @Override public List<ContractComplex> extract(Date start, Date end) { final List<ContractComplex> result = new ArrayList<>(); try { client.execute(XuntaRequestBuilder.session()); final List<String> codes = new ArrayList<>(); XuntaContractPage page = client.execute(XuntaRequestBuilder.search(start,end), new XuntaContractPageResponseHandler()); do { codes.addAll(page.getCodes()); page = page.getNext() != null ? client.execute(XuntaRequestBuilder.next(page.getNext()), new XuntaContractPageResponseHandler()) : page; } while (page.getNext() != null); return get(codes); } catch (IOException e){ LOG.error("Error obteniendo contratos", e); } return result; } public List<ContractComplex> get(final List<String> codes){ final List<ContractComplex> result = new ArrayList<>(); for(Map.Entry<String, List<ContractComplex>> entry : requestAll(XuntaRequestBuilder.findAll(codes), new ContractResponseHandler()).entrySet()){ result.addAll(entry.getValue()); } return result; } }
/* * Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms. */ package com.yahoo.cubed.service.bullet.query; /** * Bullet query failed exception. */ public class BulletQueryFailException extends Exception { private static final long serialVersionUID = 1L; /** * Create Bullet fail query exception. */ public BulletQueryFailException(Exception e) { super(e); } }
/* * 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 de.kaojo.persistence.entities; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; /** * * @author jwinter */ @Entity @Table(name = "CHAT_MESSAGE") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public abstract class MessageEntity extends AbstractEntity<Long> { @ManyToOne @JoinColumn(name = "account_id") private AccountEntity author; @ManyToOne @JoinColumn(name = "room_id") private ChatRoomEntity chatRoom; @Column @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date creationDate; public AccountEntity getAuthor() { return author; } public void setAuthor(AccountEntity author) { this.author = author; } public abstract String getContent(); public abstract void setContent(String content); public ChatRoomEntity getChatRoom() { return chatRoom; } public void setChatRoom(ChatRoomEntity chatRoom) { this.chatRoom = chatRoom; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } }
package by.orion.onlinertasks.common.account; import android.app.Service; import android.content.Intent; import android.os.IBinder; import javax.inject.Inject; import by.orion.onlinertasks.App; import by.orion.onlinertasks.data.repository.credentials.CredentialsRepository; public class AuthenticatorService extends Service { @Inject CredentialsRepository credentialsRepository; private UserAuthenticator userAuthenticator; @Override public void onCreate() { super.onCreate(); App.getComponent().inject(this); userAuthenticator = new UserAuthenticator(getApplicationContext(), credentialsRepository); } @Override public IBinder onBind(Intent intent) { return userAuthenticator.getIBinder(); } }
/** * */ package solo; import it.unimi.dsi.fastutil.objects.ObjectList; import java.awt.BasicStroke; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import com.graphbuilder.curve.ControlPath; import com.graphbuilder.geom.Geom; /** * @author kokichi3000 * */ public final class EdgeDetector { // public static ObjectArrayList<Vector2D> newLeft = ObjectArrayList.wrap(new Vector2D[20], 0); // public static ObjectArrayList<Vector2D> newRight = ObjectArrayList.wrap(new Vector2D[20], 0); // private static IntArrayList lIndx = IntArrayList.wrap(new int[20], 0); // private static IntArrayList rIndx = IntArrayList.wrap(new int[20], 0); public final static int TURNLEFT = -1; public final static int TURNRIGHT = 1; public final static int STRAIGHT = 0; public final static int UNKNOWN = 2; public static boolean isNoisy = false; public static boolean isConfirmedTW = false; private static final int[] out = new int[]{0,0}; private static final int UPPER_LIM = 16; private static final int LOWER_LIM = 6; private static final double E = 0.1*TrackSegment.EPSILON; private final Vector2D tmpHighestPoint = new Vector2D(); final static double steerLock=0.785398; public static final double CERTAIN_DIST = 0.05; private static final double SMALL_MARGIN = 0.002; public static final double MAX_DISTANCE = 99.95; private static final double DELTA = 0.001; private static final double PRECISION = 1000000.0d; private static final double PI_2 = Math.PI/2; final static double EPS = 0.02; private static int avgNum = 0; private static double avgTotal = 0; public int whichE = 0;//highest point belong to which edge,0 = unknown public int whichEdgeAhead = 0; private static final int[] twMap = new int[100]; final static double[] SIN_LK = new double[]{0.0d, 0.17364817766693041,0.3420201433256688,0.5d,0.6427876096865394, 0.766044443118978,0.8660254037844386,0.9396926207859083,0.984807753012208,1.0, 0.984807753012208,0.9396926207859083,0.8660254037844387,0.766044443118978, 0.6427876096865395,0.5,0.3420201433256688,0.17364817766693064, 0.0d}; final static double[] COS_LK = new double[]{-1.0,-0.984807753012208, -0.9396926207859083,-0.8660254037844387,-0.766044443118978,-0.6427876096865393, -0.5,-0.34202014332566877,-0.17364817766693036,0.0,0.17364817766693036, 0.34202014332566877,0.5,0.6427876096865394,0.7660444431189779, 0.8660254037844387,0.9396926207859083,0.984807753012208,1.0}; final static double[] ANGLE_LK = new double[]{0.0,0.17453292519943295,0.3490658503988659,0.5235987755982988,0.6981317007977318, 0.8726646259971648,1.0471975511965976,1.2217304763960306,1.3962634015954636,1.5707963267948966,1.7453292519943295, 1.9198621771937623,2.0943951023931953,2.2689280275926285,2.443460952792061,2.617993877991494,2.792526803190927, 2.9670597283903604,3.141592653589793}; // private static final double UNKNOWN_ANGLE = -2; private static final double DELTATIME = 0.002; private static final double MAXSTEERSPEED = Math.PI*2/3; // private static final double ANGLEACCURACY =100.0d; public static final double MINDIST = 1; public static final int[] closePoint = new int[256]; public static final Vector2D[] closePointV = new Vector2D[256]; private static final int[] tmpIndx = new int[256]; public static int numClosePoints = 0; static { for (int i = closePointV.length-1;i>=0;--i) closePointV[i] = new Vector2D(); } // private static final Comparator<Vector2D> Vector2DComparator = new Comparator<Vector2D>(){ // public final int compare(Vector2D a, Vector2D b) { // // TODO Auto-generated method stub // return (Math.abs(a.y-b.y)<=0.00001) ? 0 : (a.y>b.y) ? 1 : -1; // }}; // private static final Swapper swapper = new Swapper(){ // @Override // public void swap(int i, int j) { // // TODO Auto-generated method stub // double tmp = angles[i]; // angles[i] = angles[j]; // angles[j] = tmp; // Vector2D v = backP[i]; // backP[i] = backP[j]; // backP[j] = v; // } // }; // private static class Swap implements Swapper{ // Object[] backP; // // public Swap(Object[] b) { // // TODO Auto-generated constructor stub // backP = b; // } // // @Override // public void swap(int i, int j) { // // TODO Auto-generated method stub // Object v = backP[i]; // backP[i] = backP[j]; // backP[j] = v; // // } // } Vector2D currentPointAhead = new Vector2D(); Vector2D originalHighest = new Vector2D(); ControlPath cp=null; private static double[] tracks; public double trackWidth=0; double curPos=0; double distRaced; private static final int NUM_POINTS=500; double curAngle; double maxY; int pointAheadIndx = -1; public final Vector2D[] left = new Vector2D[NUM_POINTS]; public final Vector2D[] right = new Vector2D[NUM_POINTS]; public final static Vector2D[] nleft = new Vector2D[20]; public final static Vector2D[] nright = new Vector2D[20]; static { for (int i = nleft.length-1;i>=0;--i){ nleft[i] = new Vector2D(); nright[i] = new Vector2D(); } } public int nLsz = 0; public int nRsz = 0; public int lSize = 0; public int rSize = 0; // public final ObjectArrayList<Vector2D> allPoints = ObjectArrayList.wrap(backP,0); // private static ObjectArrayList<Vector2D> allPointsR = null; // private static double[] angles = new double[NUM_POINTS]; // DoubleArrayList x = null; // DoubleArrayList y = null; int numpoint = 0; // int firstIndexMax = -1,lastIndexMax = -1; double maxDistance=-1; public double leftStraight = -1; public double rightStraight = -1; public double straightDist =-1; Vector2D highestPoint = null; int turn; Vector2D center = null; double radiusL = -1; double radiusR = -1; // private static double[] tmpX = new double[NUM_POINTS];//x is axis along track axis // private static double[] tmpY = new double[NUM_POINTS]; // private static double[] tmpRx = new double[NUM_POINTS];//x is axis along track axis // private static double[] tmpRy = new double[NUM_POINTS]; /** * Copy Constructor * * @param edgeDetector a <code>EdgeDetector</code> object */ public final int removeElems(Vector2D[] sortedArr,int indx,int num,int[] selected){ int k = 0; Vector2D v = sortedArr[indx]; Vector2D vvv = v; int j = 0; for (k = indx-1;k>=0;--k){ Vector2D vv = sortedArr[k]; if (v.y-vv.y>trackWidth && vvv.y-vv.y>trackWidth) break; if (vv.distance(vvv)<trackWidth) { vvv = vv; selected[j++] = k; } } if (j>0){ System.arraycopy(selected, 0, selected, j, j); k = j; for (int i=j-1;i>=0;--i){ selected[i] = selected[k++]; } } selected[j++] = indx; vvv = v; for (k = indx+1;k<num;++k){ Vector2D vv = sortedArr[k]; if (vv.y-v.y>trackWidth && vv.y-vvv.y>trackWidth) break; if (vv.distance(vvv)<trackWidth) { vvv = vv; selected[j++] = k; } } // k++; // for (;k<num;++k){ // Vector2D vv = sortedArr[k]; // if (vv.distance(v)<trackWidth || k<num-1 && vv.distance(sortedArr[k+1])<trackWidth) selected[j++] = k; // } return j; } public final int removeFromRightEdge(int i,Segment[] trArr,int trSz,int[] trIndx,int[] occupied){ int n = removeElems(right, i, rSize, tmpIndx); if (n==0 || rSize>5 && n>rSize-5 ) { i = n>0 && rSize>5 && n>rSize-5 ? tmpIndx[0] : i; return i; } int count = 0; for (int j = 0;j<n;++j){ if (right[ tmpIndx[j]].certain ) count++; if (count>1) break; } if (count>1) return tmpIndx[0]; int firstIndx = tmpIndx[0]; for (int j = 0;j<trSz;++j){ int indx = trIndx[j]; Segment t = trArr[ indx ].rightSeg; if (t.startIndex>=firstIndx || t.endIndex>=firstIndx){ int start = t.startIndex; int end = t.endIndex; for (int k = 0;k<n;++k){ int idx = tmpIndx[k]; if (idx<start) t.startIndex--; if (idx<=end) t.endIndex--; if (idx>end) break; } t.num = t.endIndex - t.startIndex+1; if (t.num<3 && t.opp.num<3){ occupied[indx] = 0; if (trSz>j+1) System.arraycopy(trIndx, j+1, trIndx, j, trSz-j-1); trSz--; j--; } } } int lastIndx = tmpIndx[n-1]; int indx = lastIndx; for (int j = n-1;j>=0;--j){ int idx = tmpIndx[j]; if (idx<i) i--; lSize = EdgeDetector.join(right[idx], left, lSize, trArr, trIndx, trSz, -1); if (indx-- == idx) continue; indx = tmpIndx[j+1]; if (rSize>lastIndx+1) { for (int ii = 0,nn = rSize-lastIndx-1;ii<nn;++ii){ right[indx+ii].copy(right[lastIndx+1+ii]); } // System.arraycopy(right, lastIndx+1, right, indx, rSize-lastIndx-1); } rSize -= lastIndx-indx+1; lastIndx = idx; indx = lastIndx; } indx = tmpIndx[0]; if (rSize>lastIndx+1) { for (int ii = 0,nn = rSize-lastIndx-1;ii<nn;++ii){ right[indx+ii].copy(right[lastIndx+1+ii]); } // System.arraycopy(right, lastIndx+1, right, indx, rSize-lastIndx-1); } rSize -= lastIndx-indx+1; CircleDriver2.trSz = trSz; return tmpIndx[0]; } public final int removeFromLeftEdge(int i,Segment[] trArr,int trSz,int[] trIndx,int[] occupied){ int n = removeElems(left, i, lSize, tmpIndx); if (n==0 || lSize>5 && n>lSize-5) { i = n>0 && n>lSize-5 ? tmpIndx[0] : i; return i; } int count = 0; for (int j = 0;j<n;++j){ if (left[ tmpIndx[j]].certain ) count++; if (count>1) break; } if (count>1) return tmpIndx[0]; int firstIndx = tmpIndx[0]; for (int j = 0;j<trSz;++j){ int indx = trIndx[j]; Segment t = trArr[ indx ].leftSeg; if (t.startIndex>=firstIndx || t.endIndex>=firstIndx){ int start = t.startIndex; int end = t.endIndex; for (int k = 0;k<n;++k){ int idx = tmpIndx[k]; if (idx<start) t.startIndex--; if (idx<=end) t.endIndex--; if (idx>end) break; } t.num = t.endIndex - t.startIndex+1; if (t.num<3 && t.opp.num<3){ occupied[indx] = 0; if (trSz>j+1) System.arraycopy(trIndx, j+1, trIndx, j, trSz-j-1); trSz--; j--; } } } int lastIndx = tmpIndx[n-1]; int indx = lastIndx; for (int j = n-1;j>=0;--j){ int idx = tmpIndx[j]; if (idx<i) i--; rSize = EdgeDetector.join(left[idx], right, rSize, trArr, trIndx, trSz, 1); if (indx-- == idx) continue; indx = tmpIndx[j+1]; if (lSize>lastIndx+1) { for (int ii = 0,nn = lSize-lastIndx-1;ii<nn;++ii){ left[indx+ii].copy(left[lastIndx+1+ii]); } // System.arraycopy(left, lastIndx+1, left, indx, lSize-lastIndx-1); } lSize -= lastIndx-indx+1; lastIndx = idx; indx = lastIndx; } indx = tmpIndx[0]; if (lSize>lastIndx+1) { for (int ii = 0,nn = lSize-lastIndx-1;ii<nn;++ii){ left[indx+ii].copy(left[lastIndx+1+ii]); } // System.arraycopy(left, lastIndx+1, left, indx, lSize-lastIndx-1); } lSize -= lastIndx-indx+1; CircleDriver2.trSz = trSz; return tmpIndx[0]; } public final void copy(EdgeDetector edgeDetector) { this.cp = edgeDetector.cp; this.trackWidth = edgeDetector.trackWidth; this.curPos = edgeDetector.curPos; this.distRaced = edgeDetector.distRaced; this.curAngle = edgeDetector.curAngle; this.maxY = edgeDetector.maxY; this.pointAheadIndx = edgeDetector.pointAheadIndx; if (edgeDetector.center==null) this.center = null; else if (this.center==null) this.center = new Vector2D(edgeDetector.center); else { this.center.x = edgeDetector.center.x; this.center.y = edgeDetector.center.y; } this.radiusL = edgeDetector.radiusL; this.radiusR = edgeDetector.radiusR; // this.left = edgeDetector.left; // this.right = edgeDetector.right; // this.firstIndexMax = edgeDetector.firstIndexMax; // this.lastIndexMax = edgeDetector.lastIndexMax; this.maxDistance = edgeDetector.maxDistance; this.leftStraight = edgeDetector.leftStraight; this.rightStraight = edgeDetector.rightStraight; this.straightDist = edgeDetector.straightDist; // this.highestPoint = edgeDetector.highestPoint; if (edgeDetector.highestPoint==null){ this.highestPoint = null; } else { this.highestPoint = tmpHighestPoint; this.highestPoint.copy(edgeDetector.highestPoint); } // this.x = new DoubleArrayList(edgeDetector.x); // this.y = new DoubleArrayList(edgeDetector.y); this.numpoint = edgeDetector.numpoint; this.turn = edgeDetector.turn; this.currentPointAhead = edgeDetector.currentPointAhead; this.whichE = edgeDetector.whichE; int sL = lSize = edgeDetector.lSize; int sR = rSize = edgeDetector.rSize; if (sL>0) for (int i = sL-1;i>=0;--i){ Vector2D v = edgeDetector.left[i]; left[i].x = v.x; left[i].y = v.y; } if (sR>0) for (int i = sR-1;i>=0;--i){ Vector2D v = edgeDetector.right[i]; right[i].x = v.x; right[i].y = v.y; } // int sA = allPoints.size(); // edgeDetector.allPoints.getElements(0, this.allPoints.elements(), 0, sA); } public EdgeDetector() { for (int i = left.length-1;i>=0;--i){ left[i] = new Vector2D(); right[i] = new Vector2D(); } } private static final int compare(Vector2D a,Vector2D b){ double d = a.y-b.y; return (-SMALL_MARGIN<=d && d<=SMALL_MARGIN) ? 0 : (d<0) ? -1 : 1; } private static int partition(Vector2D[] a, int left, int right) { int i = left - 1; int j = right; while (true) { while (compare(a[++i],a[right])<0) // find item on left to swap ; // a[right] acts as sentinel while (compare(a[right],a[--j])<0) // find item on right to swap if (j == left) break; // don't go out-of-bounds if (i >= j) break; // check if pointers cross Vector2D tmp = a[i]; a[i] = a[j]; a[j] =tmp; } Vector2D tmp = a[i]; a[i] = a[right]; a[right] =tmp; return i; } public static void quicksort(Vector2D[] a, int left, int right) { if (right <= left) return; int i = partition(a, left, right); quicksort(a, left, i-1); quicksort(a, i+1, right); } public final void init(CarState cs,double trkWidth) { // TODO Auto-generated constructor stub long ti = System.currentTimeMillis(); tracks = cs.track; Vector2D[] left = this.left; Vector2D[] right = this.right; whichE = 0; curPos = -Math.round(cs.trackPos*PRECISION)/PRECISION; // curPos = -cs.getTrackPos(); curAngle = Math.round(cs.angle*PRECISION)/PRECISION; maxDistance=-1; int firstIndexMax = -1; int lastIndexMax = -1; maxY = -1000; distRaced = Math.round(cs.distRaced*PRECISION)/PRECISION; int startIndex = 0; int endIndex = 19; if (Math.abs(curAngle)<0.01 && !isConfirmedTW){ avgNum++; trackWidth = Math.round((tracks[0]+tracks[18])*Math.cos(curAngle)); avgTotal += trackWidth; trackWidth = Math.round(avgTotal/avgNum); // if (trackWidth>0 && trkWidth>0 && trackWidth!=trkWidth) { // trackWidth = trkWidth; // startIndex = 1; // } twMap[(int)trackWidth]++; if (twMap[(int)trackWidth]>100 && trackWidth==trkWidth) isConfirmedTW = true; if (trackWidth>0 && trackWidth!=trkWidth) { if (trkWidth<0) trkWidth = trackWidth; else if (twMap[(int)trackWidth]>twMap[(int)trkWidth]){ trkWidth = trackWidth; isNoisy = true; } else trackWidth = trkWidth; } // if (trackWidth!=15) // System.out.println(); } if (trackWidth<=0) trackWidth = trkWidth; leftStraight=-1; rightStraight=-1; int j = 0; double angle = Math.PI-ANGLE_LK[9]-curAngle; // double xx = tracks[i]* Math.cos(angle); // double yy = tracks[i]* Math.sin(angle); double yy =Math.round(tracks[9]* Math.sin(angle)*PRECISION)/PRECISION; int sign = (yy<0) ? -1 : 1; // sign *= (curAngle<-PI_2) ? -1 : 1; if (sign<0){ angle = Math.PI-ANGLE_LK[startIndex]-curAngle; yy =Math.round(tracks[startIndex]* Math.sin(angle)*PRECISION)/PRECISION; angle = Math.PI-ANGLE_LK[1+startIndex]-curAngle; double yy1 =Math.round(tracks[1+startIndex]* Math.sin(angle)*PRECISION)/PRECISION; if (yy<yy1){ angle = Math.PI-ANGLE_LK[2+startIndex]-curAngle; double yy2 =Math.round(tracks[2+startIndex]* Math.sin(angle)*PRECISION)/PRECISION; if (yy2<yy1) sign = 1; } // else { // angle = Math.PI-ANGLE_LK[2]-curAngle; // double yy2 =Math.round(tracks[2]* Math.sin(angle)*PRECISION)/PRECISION; // if (yy2>yy1) sign = 1; // } } Vector2D[] edge = (sign<0) ? right : left; // int startIndex = (curAngle>PI_2) ? 1 : 0; // int endIndex = (curAngle<-PI_2) ? 18 : 19; whichEdgeAhead = 0; pointAheadIndx = -1; currentPointAhead.x = 0; currentPointAhead.y = 0; firstIndexMax = -1; double ll = 0; /*if (CircleDriver2.time>=CircleDriver2.BREAK_TIME){ double[] px = new double[19]; double[] py = new double[19]; for (int i =0 ; i<19;++i){ double l = tracks[i]; angle = Math.PI-ANGLE_LK[i]; px[i] = l* Math.cos(angle); py[i] = l* Math.sin(angle); } drawEdge(px, py, "Track sensor"); }//*/ for (int i=startIndex;i<endIndex;++i){ angle = Math.PI-ANGLE_LK[i]-curAngle; // double xx = tracks[i]* Math.cos(angle); // double yy = tracks[i]* Math.sin(angle); double l = tracks[i]; if (l<=0) continue; double xx =Math.round(l* Math.cos(angle)*PRECISION)/PRECISION; yy =Math.round(l* Math.sin(angle)*PRECISION)/PRECISION; if (i==9) currentPointAhead.copy(xx,yy); if ((i==0 || i==endIndex-1 || Math.abs(yy)<trackWidth) && (xx<-2*trackWidth || xx>2*trackWidth)) continue; // angle=Math.round((Math.PI-angle)*ANGLEACCURACY)/ANGLEACCURACY; // angle = Math.PI - angle; // angle = (xx==0) ? PI_2 : (yy>=0) ? Math.PI-Math.atan2(yy,xx) : Math.PI - angle; // angle = Math.round(angle*PRECISION)/PRECISION; if (maxDistance<l) maxDistance = l; double absXX = Math.abs(xx); if (absXX>=40 || (absXX>trackWidth*2 && absXX>Math.abs(yy))){ if (CircleDriver2.debug) System.out.println("Vo no roi"); continue; } if (yy<-5 || (j>0 && Math.abs(yy-edge[j-1].y)<=0.15)) continue; double absYY = yy*sign; if (maxY<absYY || l>MAX_DISTANCE){ if (maxY<absYY) maxY = absYY; if (l<=MAX_DISTANCE){ firstIndexMax = j; lastIndexMax = firstIndexMax; ll = l; } else { if (ll<=MAX_DISTANCE){ firstIndexMax = j; ll = l; } else if (ll<l) ll = l; lastIndexMax = j; } } else if (maxY==absYY && lastIndexMax>=0){ lastIndexMax =j; if (ll<l) ll = l; } else if (l>MAX_DISTANCE){ if (maxY<absYY && firstIndexMax>=0 && ll<=MAX_DISTANCE){ maxY = absYY; firstIndexMax =j; lastIndexMax =j; ll = l; } else if (maxY==absYY && lastIndexMax>=0){ lastIndexMax = j; if (ll<l) ll = l; } else { continue; } } if (yy<-5) continue; // Vector2D v = edge[j]; if (j<=0 || Math.abs(yy-edge[j-1].y)>0.15){ edge[j++].copy(xx, yy,true); // j++; // v.x = xx; // v.y = yy; // v.certain = true; if (i==9) pointAheadIndx = j-1; } } Vector2D[] other = (sign<0) ? left : right; for (int i=j-1;i>=0;--i){ // Vector2D v = edge[j-1-i]; // Vector2D s = other[i]; // s.x = v.x; // s.y = v.y; other[i].copy(edge[j-1-i]); } numpoint = j; int lsz = (firstIndexMax>=0 && firstIndexMax<numpoint) ? firstIndexMax : 0; int rsz = (lastIndexMax<numpoint-1 && lastIndexMax>=0) ? numpoint-1-lastIndexMax : 0; if (numpoint==0){ if (highestPoint!=null){ highestPoint.x = 0; highestPoint.y = 0; } lSize = 0; rSize = 0; nLsz = 0; nRsz = 0; whichE = 0; whichEdgeAhead = 0; currentPointAhead.x = 0; currentPointAhead.y = 0; return; } if (sign<0){ yy = edge[0].y; int oldIndx = firstIndexMax; firstIndexMax = 0; Vector2D p; for (int i=1;i<numpoint;++i){ p = edge[i]; if (p.y>yy){ yy = p.y; firstIndexMax = i; } } if (firstIndexMax>=0 && firstIndexMax<oldIndx){ sign = 1; lastIndexMax = firstIndexMax; lsz = (firstIndexMax>=0 && firstIndexMax<numpoint) ? firstIndexMax : 0; rsz = (lastIndexMax<oldIndx-1 && lastIndexMax>=0) ? oldIndx-lastIndexMax-1 : 0; int oldLsz = numpoint-1-oldIndx; // Vector2D[] tmp = new Vector2D[lsz+1 + oldLsz]; // if (oldLsz>0) System.arraycopy(edge, oldIndx+1, tmp, 0, oldLsz); // System.arraycopy(edge, 0, tmp, oldLsz, lsz+1); //Use nleft as temporary buffer for (int i = 0;i<oldLsz;++i) nleft[i].copy(edge[oldIndx+1+i]); for (int i = 0;i<lsz+1;++i) nleft[i+oldLsz].copy(edge[i]); lsz+=oldLsz; if (rsz>0) { for (int i = rsz-1;i>=0;--i){ right[i].copy(other[oldLsz+1+i]); // Vector2D s = other[oldLsz+1+i]; // Vector2D d = right[i]; // d.x = s.x; // d.y = s.y; } // System.arraycopy(other, oldLsz+1, right, 0, rsz); } // System.arraycopy(tmp, 0, left, 0, lsz+1); for (int i = lsz;i>=0;--i){ left[i].copy(nleft[i]); // Vector2D s = tmp[i]; // Vector2D d = left[i]; // d.x = s.x; // d.y = s.y; } firstIndexMax = lsz; } else if (firstIndexMax>oldIndx){ sign = 1; int oldRsz = oldIndx; lsz = firstIndexMax - oldIndx-1; rsz = (firstIndexMax<numpoint-1 && firstIndexMax>=0) ? numpoint-1-firstIndexMax : 0; // Vector2D[] tmp = (rsz+oldRsz>0) ? new Vector2D[Math.max(rsz+oldRsz,lsz)] : null; // if (tmp!=null) for (int i = tmp.length-1;i>=0;--i) tmp[i] = new Vector2D(); if (oldRsz>0) { /*if (tmp==null || numpoint-oldRsz>tmp.length){ tmp = new Vector2D[numpoint-oldRsz]; for (int i = tmp.length-1;i>=0;--i) tmp[i] = new Vector2D(); }//*/ int startIndx = numpoint-1; for (int i = oldRsz-1;i>=0;--i){ nleft[i].copy(other[startIndx--]); // Vector2D s = other[startIndx--]; // Vector2D d = tmp[i]; // d.x = s.x; // d.y = s.y; } // System.arraycopy(other, numpoint-oldRsz, tmp, 0, oldRsz); } if (rsz>0) { int startIndx = oldRsz+rsz-1; for (int i = rsz-1;i>=0;--i){ nleft[startIndx--].copy(other[i]); // Vector2D s = other[i]; // Vector2D d = tmp[startIndx--]; // d.x = s.x; // d.y = s.y; } //System.arraycopy(other, 0, tmp, oldRsz, rsz); } rsz += oldRsz; for (int i = rsz-1;i>=0;--i){ right[i].copy(nleft[i]); // Vector2D s = tmp[i]; // Vector2D d = right[i]; // d.x = s.x; // d.y = s.y; } // System.arraycopy(tmp, 0, right, 0, rsz); if (lsz>0) { int startIndx = firstIndexMax-1; for (int i = 0;i<lsz;++i){ nleft[i].copy(other[startIndx--]); // Vector2D s = other[startIndx--]; // Vector2D d = tmp[i]; // d.x = s.x; // d.y = s.y; } for (int i = 0;i<lsz;++i){ // Vector2D s = tmp[i]; // Vector2D d = left[i]; // d.x = s.x; // d.y = s.y; left[i].copy(nleft[i]); } // System.arraycopy(edge, oldIndx+1, left, 0, lsz+1); } firstIndexMax = lsz; } } if (firstIndexMax>=0 && numpoint>0 && sign<0){ highestPoint = (firstIndexMax>=0 && firstIndexMax<numpoint && edge[firstIndexMax].y>=0) ? new Vector2D(edge[firstIndexMax]) : null; whichE = 0; firstIndexMax = j-1-firstIndexMax; lastIndexMax = j-1-lastIndexMax; lsz = (firstIndexMax>0 && firstIndexMax<numpoint) ? firstIndexMax : 0; rsz = (lastIndexMax<numpoint-1 && lastIndexMax>=0) ? numpoint-1-lastIndexMax : 0; if (lsz>0) quicksort(left, 0, lsz-1); if (rsz>0) quicksort(right, 0, rsz-1); // int hIndx = (startIndex==1) ? 0 : 18; // angle = Math.PI-ANGLE_LK[hIndx]-curAngle; // double xx = tracks[i]* Math.cos(angle); // double yy = tracks[i]* Math.sin(angle); // double xx =Math.round(tracks[hIndx]* Math.cos(angle)*PRECISION)/PRECISION; // yy =Math.round(tracks[hIndx]* Math.sin(angle)*PRECISION)/PRECISION; // highestPoint = (yy>0) ? new Vector2D(xx,yy) : null; } else { if (pointAheadIndx>=0){ if (lsz>pointAheadIndx){ whichEdgeAhead = -1; } else if (firstIndexMax<pointAheadIndx) whichEdgeAhead = 1; } highestPoint = (firstIndexMax>=0 && firstIndexMax<numpoint && left[firstIndexMax].y>=0) ? new Vector2D(left[firstIndexMax]) : null; if (highestPoint!=null && CircleDriver2.debug) System.out.println("New Highest point : "+highestPoint+" "+highestPoint.length()); } double dx =(highestPoint==null) ? 0: highestPoint.x; double dy = (highestPoint==null) ? 0 :highestPoint.y; double d = (highestPoint==null) ? 100 : Math.sqrt(dx*dx+dy*dy); double ldv = 0; if (firstIndexMax>0 && left!=null && lsz>0 && d<MAX_DISTANCE){ Vector2D v = (sign>0) ? left[lsz-1] : left[0]; double dvx = dx - v.x; double dvy = dy - v.y; ldv = Math.sqrt(dvx*dvx+dvy*dvy); ldv = Math.round(ldv*1000.0d)/1000.0d; double absDvx = Math.abs(dvx); double absDvy = Math.abs(dvy); if (absDvx>trackWidth && absDvx<=UPPER_LIM && absDvx>=absDvy && absDvy<=LOWER_LIM ) whichE = 1; } double rdv = 0; if (whichE==0 && right!=null && rsz>0 && d<MAX_DISTANCE){ Vector2D v = (sign>0) ? right[rsz-1] : right[0]; double dvx = dx - v.x; double dvy = dy - v.y; rdv = Math.sqrt(dvx*dvx+dvy*dvy); rdv = Math.round(rdv*1000.0d)/1000.0d; double absDvx = Math.abs(dvx); double absDvy = Math.abs(dvy); if (absDvx>trackWidth && absDvx<=UPPER_LIM && absDvx>=absDvy && absDvy<=LOWER_LIM ) whichE = -1; } if (whichE==0 && d<MAX_DISTANCE){ if (lsz>0 && rsz>0){ if (ldv<trackWidth-EPS && ldv<rdv) whichE = -1; else if (rdv<trackWidth-EPS && rdv<ldv) whichE = 1; else if (ldv<trackWidth-EPS) whichE = -1; else if (rdv<trackWidth-EPS) whichE = 1; } else if (lsz>0 && ldv<trackWidth-EPS){ whichE = -1; } else if (rsz>0 && rdv<trackWidth-EPS){ whichE = 1; } } if (whichE==1){ if (sign>0) { Vector2D dest = right[rsz++]; dest.x = dx; dest.y = dy; } else { // System.arraycopy(right, 0, right, 1, rsz++); for (int i = rsz++;i>=0;--i){ right[i+1].copy(right[i]); // Vector2D s = right[i]; // Vector2D dest = right[i+1]; // dest.x = s.x; // dest.y = s.y; } Vector2D dest = right[0]; dest.x = dx; dest.y = dy; } } else if (whichE==-1){ if (sign>0) { Vector2D dest = left[lsz++]; dest.x = dx; dest.y = dy; }else { // System.arraycopy(left, 0, left, 1, lsz++); for (int i = lsz++;i>=0;--i){ left[i+1].copy(left[i]); // Vector2D s = left[i]; // Vector2D dest = left[i+1]; // dest.x = s.x; // dest.y = s.y; } Vector2D dest = left[0]; dest.x = dx; dest.y = dy; } } if (highestPoint!=null) originalHighest.copy(highestPoint); if (whichEdgeAhead==0 && pointAheadIndx>=0){ if (lsz>0 && binarySearchFromTo(left, currentPointAhead, 0, lsz-1)>=0) whichEdgeAhead = -1; else if (rsz>0 && binarySearchFromTo(right, currentPointAhead, 0, rsz-1)>=0) whichEdgeAhead = 1; } lSize = lsz; rSize = rsz; nLsz = lsz; nRsz = rsz; if (lsz>0) { for (int i = lsz-1;i>=0;--i){ // Vector2D s = left[i]; // Vector2D dest = nleft[i]; // dest.x = s.x; // dest.y = s.y; nleft[i].copy(left[i]); } // System.arraycopy(left, 0, nleft, 0, lsz); } if (rsz>0) { for (int i = rsz-1;i>=0;--i){ nright[i].copy(right[i]); // Vector2D s = right[i]; // Vector2D dest = nright[i]; // dest.x = s.x; // dest.y = s.y; } // System.arraycopy(right, 0, nright, 0, rsz); } // newLeft.size(lsz); // if (left!=null && lsz>0) System.arraycopy(left.elements(), 0, newLeft.elements(), 0, lsz); // newRight.size(rsz); // if (right!=null && rsz>0) System.arraycopy(right.elements(), 0, newRight.elements(), 0, rsz); // lIndx.size(lsz); // int[] ar = lIndx.elements(); // for (int i=0;i<lsz;++i)ar[i] = i; // rIndx.size(rsz); // ar = rIndx.elements(); // for (int i=0;i<rsz;++i) ar[i] = i; double l0 = (left!=null && lsz>0) ? left[0].x : -10000; double l1 = (left!=null && lsz>0) ? left[lsz-1].x : -10000; double r0 = (right!=null && rsz>0) ? right[0].x : -10000; double r1 = (right!=null && rsz>0) ? right[rsz-1].x : -10000; boolean straight = (highestPoint!=null && d>=MAX_DISTANCE); boolean nlS = (l1>l0 ? l1 : l0)>TrackSegment.EPSILON; boolean nrS = (r1>r0?r1:r0)>TrackSegment.EPSILON; if (straight && ((l1>=l0 ? l1-l0 : l0-l1)<=0.1*TrackSegment.EPSILON || (r1>=r0 ? r1-r0 : r0-r1)<=TrackSegment.EPSILON*0.1)) turn = STRAIGHT; else if ((nlS && l1>l0+TrackSegment.EPSILON) || (nrS && r1>r0+TrackSegment.EPSILON)) turn = 1; else if ((nlS && l1+TrackSegment.EPSILON<l0) || (nrS && r1+TrackSegment.EPSILON<r0)) turn = -1; else turn = 2; double dL = getStraightDist(left,lsz); double dR = getStraightDist(right,rsz); if (CircleDriver2.debug) System.out.println("EdgeInit : "+(System.currentTimeMillis()-ti)); straightDist = (dL< dR) ? dR : dL; } private static final double getStraightDist(Vector2D[] left,int sL){ double val = 0; if (left!=null && sL>0){ double l0 = -10000; boolean ok = false; int i = 0; int j = 0; for (i=0;i<sL;++i){ Vector2D v = left[i]; if (!ok && v.y>=0) { l0 = v.x; j = i; ok = true; continue; } if (ok && Math.abs(v.x-l0)>E) break; } if (ok){ if (i==sL || i>j+1) val = left[i-1].y; } } return val; } // private static final int compare(Segment s,Vector2D key){ // if (key.y<=s.end.y && key.y>=s.start.y) return 0; // if (key.y>s.end.y) return -1; // return 1; // } /*private static final int binarySearchFromTo(Segment[] list, double key, int from, int to) { if (from>to) return -from-1; Segment val = list[from]; int cmp = (key<=val.end.y+SMALL_MARGIN && key>=val.start.y-SMALL_MARGIN) ? 0 : (key>val.end.y) ? -1 : 1; if (cmp==0) return from; else if (cmp>0) return -from-1; val = list[to]; cmp = (key<=val.end.y+SMALL_MARGIN && key>=val.start.y-SMALL_MARGIN) ? 0 : (key>val.end.y) ? -1 : 1; if (cmp==0) return to; else if (cmp<0) return -(to+2); while (from <= to) { int mid =(from + to)/2; val = list[mid]; cmp = (key<=val.end.y+SMALL_MARGIN && key>=val.start.y-SMALL_MARGIN) ? 0 : (key>val.end.y) ? -1 : 1; if (cmp < 0) from = mid + 1; else if (cmp > 0) to = mid - 1; else return mid; // key found } return -(from + 1); // key not found. }//*/ private static final int binarySearchFromTo(Vector2D[] list, Vector2D key, int from, int to) { if (from>to) return -from-1; Vector2D midVal = list[from]; double d = midVal.y-key.y; if (d<0) d = -d; int cmp = (d<=SMALL_MARGIN) ? 0 : (midVal.y>key.y) ? 1 : -1; if (cmp==0){ if (from<to){ midVal = list[from+1]; double de = midVal.y-key.y; if (de<0) de = -de; if (de<d) return from+1; } return from; } else if (cmp>0) return -from-1; midVal = list[to]; d = midVal.y-key.y; if (d<0) d = -d; cmp = (d<=SMALL_MARGIN) ? 0 : (midVal.y>key.y) ? 1 : -1; if (cmp==0) { if (from<to){ midVal = list[to-1]; double de = midVal.y-key.y; if (de<0) de = -de; if (de<d) return to-1; } return to; } else if (cmp<0) return -(to+2); while (from <= to) { int mid =(from + to)/2; midVal = list[mid]; d = midVal.y-key.y; if (d<0) d = -d; cmp = (d<=SMALL_MARGIN) ? 0 : (midVal.y>key.y) ? 1 : -1; if (cmp < 0) from = mid + 1; else if (cmp > 0) to = mid - 1; else { if (midVal.y>key.y){ if (mid>from){ midVal = list[mid-1]; double de = midVal.y-key.y; if (de<0) de = -de; if (de<d) return mid-1; } } else if (midVal.y<key.y){ midVal = list[mid+1]; double de = midVal.y-key.y; if (de<0) de = -de; if (de<d) return mid+1; } return mid; // key found } } return -(from + 1); // key not found. } // @SuppressWarnings("unchecked") // private static final int binarySearchFromTo(Object[] list, Object key, int from, int to, java.util.Comparator comparator) { // Object midVal; // int cmp = comparator.compare(list[from], key); // if (cmp==0) // return from; // else if (cmp>0) return -from-1; // cmp = comparator.compare(list[to], key); // if (cmp==0) // return to; // else if (cmp<0) return -(to+2); // while (from <= to) { // int mid =(from + to)/2; // midVal = list[mid]; // cmp = comparator.compare(midVal,key); // // if (cmp < 0) from = mid + 1; // else if (cmp > 0) to = mid - 1; // else return mid; // key found // } // return -(from + 1); // key not found. // } /*private static final void shift(int offset,IntArrayList s,IntArrayList e){ int[] sr = s.elements(); int[] se = e.elements(); for (int i = 0;i<s.size();++i) { sr[i]+=offset; se[i]+=offset; if (sr[i]<0) sr[i] = 0; if (se[i]<0) se[i] = -1; } }//*/ // private static final void shift(int offset,IntArrayList s,IntArrayList e,int from){ // int[] sr = s.elements(); // int[] se = e.elements(); // for (int i = from;i<s.size();++i) { // if (sr[i]>se[i] || se[i]<0) { // if (i>0) se[i] = se[i-1]; // sr[i] = se[i]+1; // continue; // } // sr[i]+=offset; // se[i]+=offset; // } // } /*private static final void addPoint(int segmentIndex,ObjectArrayList<Segment> ss){ Segment[] ssArr = ss.elements(); Segment s = ssArr[segmentIndex]; s.endIndex++; int sz = ss.size(); for (int i = segmentIndex+1;i<sz;++i){ s = ssArr[i]; Segment prev = ssArr[i-1]; if (s.startIndex>s.endIndex || s.endIndex<0){ s.startIndex = prev.endIndex+1; s.endIndex = s.startIndex-1; continue; } if (s.startIndex<0) s.startIndex = 0; if (s.startIndex>=0 && s.startIndex<=prev.endIndex){ do { s.startIndex++; s.endIndex++; } while (s.startIndex<=prev.endIndex); } else if (s.startIndex<=s.endIndex && i>0 && s.startIndex>prev.endIndex+1) break; } }//*/ private static final boolean insertPoint(Vector2D[] elems,int sz,Vector2D v,int from,int to,Segment s){ int indx = (to<=from) ? -from-1: binarySearchFromTo(elems, v, from, to-1); if (indx>=0){ Vector2D old = elems[indx]; if (old.x==s.start.x && old.y==s.start.y) { s.start.copy(v); } if (old.x==s.end.x && old.y==s.end.y) { s.end.copy(v); } old.copy(v); // elems[indx].certain = true; return false; } if (indx<0) indx = -indx-1; boolean ok1 = false; boolean ok2 = false; Vector2D p1 = null; Vector2D p2 = null; double d1 = 0; double d2 = 0; boolean isStart = false; boolean isEnd = false; if (indx>from){ p1 = elems[indx-1]; double dx = p1.x-v.x; double dy = p1.y - v.y; d1 = Math.sqrt(dx*dx+dy*dy); if (d1<MINDIST && !p1.certain){ isStart = (p1.x==s.start.x && p1.y==s.start.y); ok1 = true; } } if (indx<to){ p2 = elems[indx]; double dx = p2.x-v.x; double dy = p2.y - v.y; d2 = Math.sqrt(dx*dx+dy*dy); if (d2<MINDIST && !p2.certain) { isStart = !isStart && (p2.x==s.start.x && p2.y==s.start.y); isEnd = p2.x==s.end.x && p2.y==s.end.y; ok2 = true; } } if (ok1 && ok2){ if (d1<=d2){ p1.copy(v); if (isStart) { // s.start.x = v.x; // s.start.y = v.y; s.start.copy(v); } } else { // p2.x = v.x; // p2.y = v.y; p2.copy(v); if (isStart) { // s.start.x = v.x; // s.start.y = v.y; s.start.copy(v); } if (isEnd) { // s.end.x = v.x; // s.end.y = v.y; s.end.copy(v); } } return false; } else if (ok1){ // p1.x = v.x; // p1.y = v.y; p1.copy(v); if (isStart) { // s.start.x = v.x; // s.start.y = v.y; s.start.copy(v); } return false; } else if (ok2) { // p2.x = v.x; // p2.y = v.y; p2.copy(v); if (isStart) { // s.start.x = v.x; // s.start.y = v.y; s.start.copy(v); } if (isEnd) { // s.end.x = v.x; // s.end.y = v.y; s.end.copy(v); } return false; } if ((sz-indx)>0) { for (int ii = sz-indx-1;ii>=0;--ii){ elems[indx+1+ii].copy(elems[indx+ii]); // Vector2D src = elems[indx+ii]; // Vector2D dest = elems[indx+1+ii]; // dest.x = src.x; // dest.y = src.y; } // System.arraycopy(elems, indx, elems, indx+1, sz); } sz++; p2 = elems[indx]; // p2.x = v.x; // p2.y = v.y; p2.copy(v); return true; } public static final int join(Vector2D v,Vector2D[] elems,int sz,Segment[] trArr,int[] trIndx,int trSz,int which){ // boolean ok1 =false; // boolean ok2 = false; // double d1 = 0; // double d2 = 0; // Vector2D p = null; // boolean changed = false; int index = 0; double vy = v.y; // int lastIndex = (trSz==0) ? 0 : (which==-1) ? trArr[trSz-1].leftSeg.endIndex : trArr[trSz-1].rightSeg.endIndex; Segment s = null; Vector2D p = null; Vector2D p1 = null; Vector2D p2 = null; for (int i = 0;i<trSz;++i){ s = (which==-1) ? trArr[ trIndx[i] ].leftSeg : trArr[ trIndx[i] ].rightSeg; if (s==null) continue; if (s.start.y-SMALL_MARGIN<=vy && vy<=s.end.y+SMALL_MARGIN){ index = i; break; } if (s.start.y>vy){ index = -i-1; break; } if (i==trSz-1 && s.end.y+SMALL_MARGIN<vy){ index = -trSz-1; } } if (index>=0 && s!=null){ int start = s.startIndex; int end = s.endIndex; if (start<0) { start = 0; s.startIndex = 0; } if (end<0 || end<start) { end = start; s.endIndex = end; if (sz-start>0) { for (int ii = sz-start-1;ii>=0;--ii) elems[start+1+ii].copy(elems[start+ii]); // System.arraycopy(elems, start, elems, start+1, sz); } sz++; p = elems[start]; p.x = v.x; p.y = v.y; p.certain = v.certain; // elems[start] = v; for (int ii=index+1;ii<trSz;++ii){ Segment ss = (which==-1) ? trArr[ trIndx[ii] ].leftSeg : trArr[ trIndx[ii] ].rightSeg; ss.startIndex++; ss.endIndex++; } s.num++; s.updated = true; return sz; } boolean inserted = (insertPoint(elems,sz, v, start, end+1,s)); if (inserted) { sz++; s.updated = true; s.endIndex++; s.num++; for (int ii=index+1;ii<trSz;++ii){ Segment ss = (which==-1) ? trArr[ trIndx[ii] ].leftSeg : trArr[ trIndx[ii] ].rightSeg; ss.startIndex++; ss.endIndex++; } } } else if (s!=null){//if index<0 index = -index-1; Segment prev = (index>0) ? (which==-1) ? trArr[ trIndx[index-1] ].leftSeg : trArr[ trIndx[index-1] ].rightSeg : null; Segment next = (index<trSz) ? (which==-1) ? trArr[ trIndx[index] ].leftSeg : trArr[ trIndx[index] ].rightSeg : null; int start = (prev==null || prev.endIndex<0) ? 0 : prev.endIndex+1; int end = (index<0 || index>=trSz) ? sz : (which==-1) ? trArr[ trIndx[index] ].leftSeg.startIndex : trArr[trIndx[index] ].rightSeg.startIndex; // int insertionIndx = binarySearchFromTo(elems, v, start, sz-1, Vector2DComparator); // boolean inserted = insertPoint(oldEdge, v, start, end); // if (inserted) sz++; int indx = binarySearchFromTo(elems, v, start, end-1); if (indx>=0){ p = elems[indx]; p.x = v.x; p.y = v.y; p.certain = v.certain; // elems[indx] = v; return sz; } if (indx<0) indx = -indx-1; boolean ok1 = false; boolean ok2 = false; double d1 = 0; double d2 = 0; if (indx>start){ p1 = elems[indx-1]; double dx = p1.x-v.x; double dy = p1.y - v.y; d1 = Math.sqrt(dx*dx+dy*dy); if (d1<MINDIST && !p1.certain && (prev==null || indx-1!=prev.endIndex)) ok1 = true; } if (indx<end){ p2 = elems[indx]; double dx = p2.x-v.x; double dy = p2.y - v.y; d2 = Math.sqrt(dx*dx+dy*dy); if (d2<MINDIST && !p2.certain && (next==null || indx!=next.startIndex)) ok2 = true; } if (ok1 && ok2){ if (d1<=d2){ p1.x = v.x; p1.y = v.y; p1.certain = v.certain; } else { p2.x = v.x; p2.y = v.y; p2.certain = v.certain; } } else if (ok1){ p1.x = v.x; p1.y = v.y; p1.certain = v.certain; } else if (ok2) { p2.x = v.x; p2.y = v.y; p2.certain = v.certain; } else if (v.certain && prev!=null && prev.num>2 && !elems[prev.endIndex].certain && elems[prev.endIndex].y>v.y-1){ prev.num--; elems[prev.endIndex].copy(v); prev.endIndex--; // } else if (v.certain && next!=null && next.num>2 && !elems[next.startIndex].certain && elems[next.startIndex].y<v.y+1){ // next.num--; // elems[next.startIndex].copy(v); // next.startIndex++; } else { if ((sz-indx)>0) { for (int ii = sz-indx-1;ii>=0;--ii) elems[indx+1+ii].copy(elems[indx+ii]); // System.arraycopy(elems, indx, elems, indx+1, sz); } sz++; p = elems[indx]; p.x = v.x; p.y = v.y; p.certain = v.certain; // elems[indx] = v; for (int ii=index;ii<trSz;++ii){ Segment ss = (which==-1) ? trArr[ trIndx[ii] ].leftSeg : trArr[ trIndx[ii] ].rightSeg; ss.startIndex++; ss.endIndex++; } } }//end of if // if (changed && edge!=null && edge.size()>0) // Arrays.quicksort(edge.elements(), 0,edge.size()-1,new Swap(edge.elements()), Vector2DComparator); return sz; } /*private static final int add(Vector2D[] elems,int sz,int index,Vector2D point){ if (index<0 || index>sz)throw new ArrayIndexOutOfBoundsException( "Array index "+index+" out of bound" ); if (index==sz) { elems[sz++] = point; return sz; } System.arraycopy(elems, index, elems, index+1, sz++ -index); elems[index] = new Vector2D(point); return sz; }//*/ /*private static final int remove(Vector2D[] elems,int sz,int index){ if (index<0 || index>=sz)throw new ArrayIndexOutOfBoundsException( "Array index "+index+" out of bound" ); if (index==sz-1) { elems[--sz] = null; return sz; } System.arraycopy(elems, index+1, elems, index, --sz-index); return sz; }//*/ /*private static final int insert(Vector2D[] right,int sz,int index,Vector2D lower){ if (lower.certain){ sz = add(right,sz,index,new Vector2D(lower)); Vector2D p = null; if (index>0){ p = right[index-1]; if (p!=null && !p.certain && Math.hypot(p.x-lower.x,p.y-lower.y)<MINDIST){ sz = remove(right,sz,--index); } } if (index<sz-1){ p = right[index+1]; if (p!=null && !p.certain && Math.hypot(p.x-lower.x,p.y-lower.y)<MINDIST) sz = remove(right,sz,index+1); } } else { sz = add(right,sz,index,new Vector2D(lower)); Vector2D p = null; boolean ok = true; if (index>0){ p = right[index-1]; if (p!=null && p.certain && Math.hypot(p.x-lower.x,p.y-lower.y)<MINDIST){ sz = remove(right,sz,index); ok = false; } } if (ok && index<sz-1){ p = right[index+1]; if (p!=null && p.certain && Math.hypot(p.x-lower.x,p.y-lower.y)<MINDIST) sz = remove(right,sz,index+1); } } return sz; }//*/ public static final void guessHighestPointEdge(Vector2D lower,int whichL,Vector2D higher,int whichH,Vector2D[] left,int sL,Vector2D[] right,int sR,double trackWidth,int[] out){ long ti = System.currentTimeMillis(); if (whichL!=0 && whichH!=0) return; double lx = (lower==null) ? 0 :lower.x; double ly = (lower==null) ? 0 :lower.y; double hx = (higher==null) ? 0 :higher.x; double hy = (higher==null) ? 0 :higher.y; double ll = (lower==null) ? 100 : Math.sqrt(lx*lx+ly*ly); double hl = Math.sqrt(hx*hx+hy*hy); double dx = hx-lx; double dy = hy-ly; double ldh = (lower==null) ? 100 : Math.sqrt(dx*dx+dy*dy); ldh = Math.round(ldh*1000)/1000.0d; if (lower!=null && higher!=null && ldh>0){ if (whichL==0 && lower!=null && ll<MAX_DISTANCE){ if (whichH!=0 && hl<MAX_DISTANCE && ldh<trackWidth-CERTAIN_DIST){ whichL = whichH; } else { double ldv = 100; if (sL>0){ Vector2D v = left[sL-1]; if (v.y<=lower.y){ double dvx = lx - v.x; double dvy = ly - v.y; ldv = Math.sqrt(dvx*dvx+dvy*dvy); ldv = Math.round(ldv*1000.0d)/1000.0d; double absDvx = Math.abs(dvx); double absDvy = Math.abs(dvy); if (absDvx>trackWidth && absDvx<=UPPER_LIM && absDvx>=absDvy && absDvy<=LOWER_LIM ) whichL = 1; } else { v = new Vector2D(); findNearestPoint(lower, left,sL, v); double dvx = lx - v.x; double dvy = ly - v.y; ldv = Math.sqrt(dvx*dvx+dvy*dvy); ldv = Math.round(ldv*1000.0d)/1000.0d; double absDvx = Math.abs(dvx); double absDvy = Math.abs(dvy); if (absDvx>trackWidth && absDvx<=UPPER_LIM && absDvx>=absDvy && absDvy<=LOWER_LIM ) whichL = 1; } } double rdv = 100; if (sR>0 && whichL==0){ Vector2D v = right[sR-1]; if (v.y<=lower.y){ double dvx = lx - v.x; double dvy = ly - v.y; rdv = Math.sqrt(dvx*dvx+dvy*dvy); rdv = Math.round(rdv*1000.0d)/1000.0d; double absDvx = Math.abs(dvx); double absDvy = Math.abs(dvy); if (absDvx>trackWidth && absDvx<=UPPER_LIM && absDvx>=absDvy && absDvy<=LOWER_LIM ) whichL = -1; } else { v = new Vector2D(); findNearestPoint(lower, right,sR, v); double dvx = lx - v.x; double dvy = ly - v.y; rdv = Math.sqrt(dvx*dvx+dvy*dvy); rdv = Math.round(rdv*1000.0d)/1000.0d; double absDvx = Math.abs(dvx); double absDvy = Math.abs(dvy); if (absDvx>trackWidth && absDvx<=UPPER_LIM && absDvx>=absDvy && absDvy<=LOWER_LIM ) whichL = -1; } } if (whichL==0){ if (sL>0 && sR>0){ if (ldv<trackWidth-EPS && ldv<rdv) whichL = -1; else if (rdv<trackWidth-EPS && rdv<ldv) whichL = 1; else if (ldv<trackWidth-EPS) whichL = -1; else if (rdv<trackWidth-EPS) whichL = 1; } else if (sL>0 && ldv<trackWidth-EPS){ whichL = -1; } else if (sR>0 && rdv<trackWidth-EPS){ whichL = 1; } } } if (hl<MAX_DISTANCE && ldh<trackWidth) whichH = whichL; } } if (whichH==0 && higher!=null && hl<MAX_DISTANCE){ if (whichL!=0 && ll<MAX_DISTANCE && ldh<trackWidth-CERTAIN_DIST){ whichH = whichL; } else { double ldv = 100; if (sL>0){ Vector2D v = left[sL-1]; if (v.y<=higher.y){ double dvx = hx - v.x; double dvy = hy - v.y; ldv = Math.sqrt(dvx*dvx+dvy*dvy); ldv = Math.round(ldv*1000.0d)/1000.0d; double absDvx = Math.abs(dvx); double absDvy = Math.abs(dvy); if (absDvx>trackWidth && absDvx<=UPPER_LIM && absDvx>=absDvy && absDvy<=LOWER_LIM ) whichH = 1; } } double rdv = 100; if (sR>0 && whichH==0){ Vector2D v = right[sR-1]; if (v.y<=higher.y){ double dvx = hx - v.x; double dvy = hy - v.y; rdv = Math.sqrt(dvx*dvx+dvy*dvy); rdv = Math.round(rdv*1000.0d)/1000.0d; double absDvx = Math.abs(dvx); double absDvy = Math.abs(dvy); if (absDvx>trackWidth && absDvx<=UPPER_LIM && absDvx>=absDvy && absDvy<=LOWER_LIM ) whichH = -1; } } if (whichH==0){ if (sL>0 && sR>0){ if (ldv<trackWidth-EPS && ldv<rdv) whichH = -1; else if (rdv<trackWidth-EPS && rdv<ldv) whichH = 1; else if (ldv<trackWidth-EPS) whichH = -1; else if (rdv<trackWidth-EPS) whichH = 1; } else if (sL>0 && ldv<trackWidth-EPS){ whichH = -1; } else if (sR>0 && rdv<trackWidth-EPS){ whichH = 1; } } } if (whichH!=0 && whichL==0 && ldh<trackWidth-EPS) whichL = whichH; } Segment[] trArr = CircleDriver2.trArr; int trSz = CircleDriver2.trSz; int[] trIndx = CircleDriver2.trIndx; if (whichL==0 && ll<MAX_DISTANCE){ double tx = 0; double ty = 0; double dl = 0; double dr = 0; for (int i = trSz-1;i>=0;--i){ Segment t = trArr[ trIndx[i] ]; if (t.type==Segment.UNKNOWN) continue; Segment lSeg = t.leftSeg; Segment rSeg = t.rightSeg; int tp = t.type; if (ly>=lSeg.start.y || ly>=rSeg.start.y){ tx = lx - lSeg.end.x; ty = ly - lSeg.end.y; dl = Math.sqrt(tx*tx+ty*ty); tx = lx - rSeg.end.x; ty = ly - rSeg.end.y; dr = Math.sqrt(tx*tx+ty*ty); if (dl<trackWidth && dr<trackWidth){ whichL = (dl<dr) ? -1 : 1; break; } else if (dl<trackWidth-EPS) { whichL = -1; break; } else if (dr<trackWidth-EPS) { whichL = 1; break; } } if (ly<=lSeg.end.y || ly<=rSeg.end.y){ tx = lx - lSeg.start.x; ty = ly - lSeg.start.y; dl = Math.sqrt(tx*tx+ty*ty); tx = lx - rSeg.start.x; ty = ly - rSeg.start.y; dr = Math.sqrt(tx*tx+ty*ty); if (dl<trackWidth && dr<trackWidth){ whichL = (dl<dr) ? -1 : 1; break; } else if (dl<trackWidth-EPS) { whichL = -1; break; } else if (dr<trackWidth-EPS) { whichL = 1; break; } } if (i==trSz-1 && ly>lSeg.end.y && ly>rSeg.end.y){ int turnLeft = 0; int turnRight = 0; int numL = sL - lSeg.endIndex-1; int numR = sR - rSeg.endIndex-1; if (numL>=1){ Vector2D v = left[lSeg.endIndex+1]; turnLeft = (lSeg.type==0 && CircleDriver2.isFirstSeg(lSeg) && Math.abs(lSeg.end.x-v.x)<E) ? 0 : (v.x>lSeg.end.x) ? 1 : -1; } if (numR>=1){ Vector2D v = right[rSeg.endIndex+1]; turnRight = (rSeg.type==0 && CircleDriver2.isFirstSeg(rSeg) && Math.abs(rSeg.end.x-v.x)<E) ? 0 : (v.x>rSeg.end.x) ? 1 : -1; } if (turnLeft!=0 && turnRight!=0 && turnLeft!=turnRight) if (CircleDriver2.debug) System.out.println("Check immediately"); else if (turnLeft!=0 && turnRight!=0 && turnLeft==turnRight) whichL = turnLeft; } if (tp!=0 && (ly>=lSeg.end.y || ly>=rSeg.end.y)){ tx = lx-lSeg.center.x; ty = ly-lSeg.center.y; dl = Math.sqrt(tx*tx+ty*ty) - lSeg.radius; tx = lx-rSeg.center.x; ty = ly-rSeg.center.y; dr = Math.sqrt(tx*tx+ty*ty) - rSeg.radius; if (dl<0) dl = -dl; if (dr<0) dr = -dr; if (dl<trackWidth && dr<trackWidth){ whichL = (dl<dr) ? -1 : 1; } else if (dl<=trackWidth-EPS){ whichL = -1; } else if (dr<=trackWidth-EPS) whichL = 1; } else if (tp==0){ dl = Math.sqrt(Geom.ptSegDistSq(lSeg.start.x, lSeg.start.y, lSeg.end.x, lSeg.end.y, lx, ly, null)); dr = Math.sqrt(Geom.ptSegDistSq(rSeg.start.x, rSeg.start.y, rSeg.end.x, rSeg.end.y, lx, ly, null)); if (dl<trackWidth && dr<trackWidth){ whichL = (dl<dr) ? -1 : 1; } else if (dl<=trackWidth-EPS){ whichL = -1; } else if (dr<=trackWidth-EPS) whichL = 1; } if (whichL!=0) break; if (ly>lSeg.end.y && ly>rSeg.end.y || ly>lSeg.start.y && ly>rSeg.start.y) break; }//end of for }//end of if if (whichL!=0 && hl<MAX_DISTANCE && ll<MAX_DISTANCE && ldh<trackWidth-CERTAIN_DIST){ whichH = whichL; } else if (whichH==0 && hl<MAX_DISTANCE){ double tx = 0; double ty = 0; double dl = 0; double dr = 0; for (int i = trSz-1;i>=0;--i){ Segment t = trArr[ trIndx[i] ]; if (t.type==Segment.UNKNOWN) continue; Segment lSeg = t.leftSeg; Segment rSeg = t.rightSeg; int tp = t.type; if (hy>=lSeg.start.y || hy>=rSeg.start.y){ tx = hx - lSeg.end.x; ty = hy - lSeg.end.y; dl = Math.sqrt(tx*tx+ty*ty); tx = hx - rSeg.end.x; ty = hy - rSeg.end.y; dr = Math.sqrt(tx*tx+ty*ty); if (dl<trackWidth && dr<trackWidth){ whichH = (dl<dr) ? -1 : 1; break; } else if (dl<trackWidth-EPS) { whichH = -1; break; } else if (dr<trackWidth-EPS) { whichH = 1; break; } } if (hy<=lSeg.end.y || hy<=rSeg.end.y){ tx = hx - lSeg.start.x; ty = hy - lSeg.start.y; dl = Math.sqrt(tx*tx+ty*ty); tx = hx - rSeg.start.x; ty = hy - rSeg.start.y; dr = Math.sqrt(tx*tx+ty*ty); if (dl<trackWidth && dr<trackWidth){ whichH = (dl<dr) ? -1 : 1; break; } else if (dl<trackWidth-EPS) { whichH = -1; break; } else if (dr<trackWidth-EPS) { whichH = 1; break; } } if (i==trSz-1 && hy>lSeg.end.y && hy>rSeg.end.y){ int turnLeft = 0; int turnRight = 0; int numL = sL - lSeg.endIndex-1; int numR = sR - rSeg.endIndex-1; if (numL>=1){ Vector2D v = left[lSeg.endIndex+1]; turnLeft = (lSeg.type==0 && CircleDriver2.isFirstSeg(lSeg) && Math.abs(lSeg.end.x-v.x)<E) ? 0 : (v.x>lSeg.end.x) ? 1 : -1; } if (numR>=1){ Vector2D v = right[rSeg.endIndex+1]; turnRight = (rSeg.type==0 && CircleDriver2.isFirstSeg(rSeg) && Math.abs(rSeg.end.x-v.x)<E) ? 0 : (v.x>rSeg.end.x) ? 1 : -1; } if (turnLeft!=0 && turnRight!=0 && turnLeft!=turnRight) if (CircleDriver2.debug) System.out.println("Check immediately"); else if (turnLeft!=0 && turnRight!=0 && turnLeft==turnRight) whichH = turnLeft; } if (tp!=0 && (hy>=lSeg.end.y || hy>=rSeg.end.y)){ tx = hx-lSeg.center.x; ty = hy-lSeg.center.y; dl = Math.sqrt(tx*tx+ty*ty) - lSeg.radius; tx = hx-rSeg.center.x; ty = hy-rSeg.center.y; dr = Math.sqrt(tx*tx+ty*ty) - rSeg.radius; if (dl<0) dl = -dl; if (dr<0) dr = -dr; if (dl<trackWidth && dr<trackWidth){ whichH = (dl<dr) ? -1 : 1; } else if (dl<=trackWidth-EPS){ whichH = -1; } else if (dr<=trackWidth-EPS) whichH = 1; } else if (tp==0){ dl = Math.sqrt(Geom.ptSegDistSq(lSeg.start.x, lSeg.start.y, lSeg.end.x, lSeg.end.y, hx, hy, null)); dr = Math.sqrt(Geom.ptSegDistSq(rSeg.start.x, rSeg.start.y, rSeg.end.x, rSeg.end.y, hx, hy, null)); if (dl<trackWidth && dr<trackWidth){ whichH = (dl<dr) ? -1 : 1; } else if (dl<=trackWidth-EPS){ whichH = -1; } else if (dr<=trackWidth-EPS) whichH = 1; } if (whichH!=0) break; if (hy>lSeg.end.y && hy>rSeg.end.y || hy>lSeg.start.y && hy>rSeg.start.y) break; }//end of for }//end of if if (whichL==0 && whichH==0 && hl<MAX_DISTANCE && ll<MAX_DISTANCE && ldh<trackWidth && ldh>=MINDIST){ double angleH = (higher.x==0) ? PI_2 : Math.PI-Math.atan2(higher.y,higher.x); angleH=Math.round(angleH*PRECISION)/PRECISION; double angleL = (lower.x==0) ? PI_2 : Math.PI-Math.atan2(lower.y,lower.x); angleL=Math.round(angleL*PRECISION)/PRECISION; if (angleL<angleH && left!=null && higher!=null && hl<MAX_DISTANCE) { whichL = -1; } else if (angleL>angleH && right!=null && higher!=null && hl<MAX_DISTANCE){ whichL = 1; } } if (CircleDriver2.debug) System.out.println("End of guess Highest Point "+(System.currentTimeMillis()-ti)+" ms."); if (out!=null){ out[0] = whichL; out[1] = whichH; } } public static final int findNearestPoint(final Vector2D point, final Vector2D[] elems, int sz,Vector2D nearest){ int index = binarySearchFromTo(elems, point, 0, sz-1); if (index<0) index = -index-1; Vector2D p1 = (index>0) ? elems[index-1] : null; Vector2D p; if (p1==null) { if (sz>=0) { p = elems[0]; nearest.x = p.x; nearest.y = p.y; } return 0; } Vector2D p2 = (index<sz) ? elems[index] : null; if (p2==null) { if (sz>=0) { p = elems[sz-1]; nearest.x = p.x; nearest.y = p.y; } return index; } double dx1 = point.x - p1.x; double dy1 = point.y - p1.y; double dx2 = point.x - p2.x; double dy2 = point.y - p2.x; p = (dx1*dx1+dy1*dy1<dx2*dx2+dy2*dy2) ? p1 : p2; nearest.x = p.x; nearest.y = p.y; return index; } private static final int join(double scale,double tx,double ty,Vector2D[] oldElems,int os,Vector2D[] elems,int sz,Segment[] trArr,int[] trIndx,int trSz,int which){ int i = os-1; int[] occupied = CircleDriver2.occupied; for (;i>=0;--i) { Vector2D v = oldElems[i]; if (scale!=1) v.x *= scale; v.x+=tx; v.y+=ty; v.certain = false; } for (i=trSz-1;i>=0;--i){ Segment s = (which==-1) ? trArr[ trIndx[i] ].leftSeg : trArr[ trIndx[i] ].rightSeg; if (scale!=1.0) s.scale(scale); s.translate(tx, ty); } if (sz==0){ for (i = os-1;i>=0;--i){ // Vector2D src = oldElems[i]; // Vector2D dest = elems[i]; // dest.x = src.x; // dest.y = src.y; elems[i].copy(oldElems[i]); } // System.arraycopy(oldElems, 0, elems, 0, os); return os; } Segment s = null; Segment prev = null; int prevIndex = -1; Vector2D key = null; int j = 0; Vector2D p1 = null; Vector2D p2 = null; int oldEndIndx = (trSz==0) ? 0 : (which==-1) ? trArr[ trIndx[trSz-1] ].leftSeg.endIndex+1 : trArr[ trIndx[trSz-1] ].rightSeg.endIndex+1; int k = sz; boolean done = false; for (i = 0;i<trSz;++i){ if (j>=sz){ done = true; break; } s = (which==-1) ? trArr[ trIndx[i] ].leftSeg : trArr[ trIndx[i] ].rightSeg; Segment next = (i>=trSz-1) ? null : (which==-1) ? trArr[ trIndx[i+1] ].leftSeg : trArr[ trIndx[i+1] ].rightSeg; if (s.type==Segment.UNKNOWN){ occupied[ trIndx[i] ] = 0; int idx = i+1; if (trSz-idx>0) System.arraycopy(trIndx, idx, trIndx, i, trSz-idx); trSz--; continue; } key = s.start; int index = binarySearchFromTo(elems, key, j, sz-1); if (index<0) index = -index-1; if (prev==null){ if (index>0){ for (int ii = index-1;ii>=0;--ii){ // Vector2D src = elems[ii]; // Vector2D dest = elems[k+ii]; // dest.x = src.x; // dest.y = src.y; elems[k+ii].copy(elems[ii]); } // System.arraycopy(elems, 0, elems, k, index); k += index; j = index; } } else { int size = 0; int start = prevIndex+1; int end = s.startIndex; size = end - start; if (size>0) { for (int ii = size-1;ii>=0;--ii){ // Vector2D src = oldElems[start+ii]; // Vector2D dest = elems[k+ii]; // dest.x = src.x; // dest.y = src.y; elems[k+ii].copy(oldElems[start+ii]); } // System.arraycopy(oldElems, start, elems, k,size); } for (int t=j;t<index;++t){ Vector2D point = elems[t]; int pos = (size>0) ? binarySearchFromTo(elems, point, k, k+size-1) : -(k+1); if (pos>=0){ p2 = elems[pos]; p2.x = point.x; p2.y = point.y; p2.certain = point.certain; } else { pos = -pos - 1; boolean ok1 = false; boolean ok2 = false; double d1 = 0; double d2 = 0; if (pos>k){ p1 = elems[pos-1]; double dx = p1.x-point.x; double dy = p1.y-point.y; d1 = Math.sqrt(dx*dx+dy*dy); if (d1<MINDIST && !p1.certain) ok1 = true; } if (pos<k+size){ p2 = elems[pos]; double dx = p2.x-point.x; double dy = p2.y-point.y; d2 = Math.sqrt(dx*dx+dy*dy); if (d2<MINDIST && !p2.certain) ok2 = true; } if (ok1 && ok2){ if (d1<=d2){ p1.x = point.x; p1.y = point.y; p1.certain = point.certain; } else { p2.x = point.x; p2.y = point.y; p2.certain = point.certain; } } else if (ok1){ p1.x = point.x; p1.y = point.y; p1.certain = point.certain; } else if (ok2) { p2.x = point.x; p2.y = point.y; p2.certain = point.certain; } else { if (k+size-pos>0) { for (int ii = k+size-pos-1;ii>=0;--ii){ elems[pos+1+ii].copy(elems[pos+ii]); // Vector2D src = elems[pos+ii]; // Vector2D dest = elems[pos+1+ii]; // dest.x = src.x; // dest.y = src.y; } // System.arraycopy(elems, pos, elems, pos+1, k+size-pos); } // elems[pos]= new Vector2D(point); p2 = elems[pos]; p2.x = point.x; p2.y = point.y; p2.certain = point.certain; size++; } }//end of else }//end of for if (size>0){ k+=size; } j = index; }//end of gap int start = s.startIndex; int end = s.endIndex+1; int size = end-start; prevIndex = s.endIndex; if (size>0 && start>=0) { if (size>2 && s.type==0 && s.end.x==s.start.x){ size = 2; p2 = elems[k]; p1 = oldElems[start]; p2.copy(p1); // elems[k] = new Vector2D(oldElems[start]); p2 = elems[k+1]; p1 = oldElems[end-1]; p2.copy(p1); // p2.x = p1.x; // p2.y = p1.y; // elems[k+1] = new Vector2D(oldElems[end-1]); } else { for (int ii = size-1;ii>=0;--ii){ elems[k+ii].copy(oldElems[start+ii]); // Vector2D src = oldElems[start+ii]; // Vector2D dest = elems[k+ii]; // dest.x = src.x; // dest.y = src.y; } // System.arraycopy(oldElems, start, elems, k, size); } } key = s.end; int endIndex = binarySearchFromTo(elems, key, j, sz-1); if (endIndex<0) endIndex = -endIndex-1; else endIndex++; j = endIndex; for (int t=index;t<endIndex;++t){ Vector2D point = elems[t]; int pos = (size>0) ? binarySearchFromTo(elems, point, k, k+size-1) : -(k+1); if (pos>=0){ p2 = elems[pos]; p2.x = point.x; p2.y = point.y; p2.certain = point.certain; } else { pos = -pos - 1; boolean ok1 = false; boolean ok2 = false; double d1 = 0; double d2 = 0; if (pos>k){ p1 = elems[pos-1]; double dx = p1.x-point.x; double dy = p1.y-point.y; d1 = Math.sqrt(dx*dx+dy*dy); if (d1<MINDIST && !p1.certain) ok1 = true; } if (pos<k+size){ p2 = elems[pos]; double dx = p2.x-point.x; double dy = p2.y-point.y; d2 = Math.sqrt(dx*dx+dy*dy); if (d2<MINDIST && !p2.certain) ok2 = true; } if (ok1 && ok2){ if (d1<=d2){ p1.x = point.x; p1.y = point.y; p1.certain = point.certain; } else { p2.x = point.x; p2.y = point.y; p2.certain = point.certain; } } else if (ok1){ p1.x = point.x; p1.y = point.y; p1.certain = point.certain; } else if (ok2) { p2.x = point.x; p2.y = point.y; p2.certain = point.certain; } else if (point.certain && prev!=null && prev.num>2 && !elems[prev.endIndex].certain && elems[prev.endIndex].y>point.y-1){ prev.num--; elems[prev.endIndex].copy(point); prev.endIndex--; } else { if (k+size-pos>0) { for (int ii = k+size-pos-1;ii>=0;--ii){ elems[pos+1+ii].copy( elems[pos+ii]); // Vector2D src = elems[pos+ii]; // Vector2D dest = elems[pos+1+ii]; // dest.x = src.x; // dest.y = src.y; } // System.arraycopy(elems, pos, elems, pos+1, k+size-pos); } // elems[pos]= new Vector2D(point); p2 = elems[pos]; p2.x = point.x; p2.y = point.y; p2.certain = point.certain; size++; } }//end of else }//end of for // segs[newIndex++] = s; s.num = size; s.updated = (index<endIndex); int sI = k - sz; s.startIndex = sI; s.endIndex = sI+size-1; k+=size; prev = s; } if (!done){ //Do the last bit int size = 0; if (oldEndIndx<os){ size = os - oldEndIndx; if (size>0) { Vector2D point = elems[k]; p1 = (oldEndIndx>0) ? oldElems[oldEndIndx-1] : null; if (p1!=null && !p1.certain && point.distance(p1)<MINDIST){ // oldEndIndx--; p1.copy(point); if (s!=null) { s.endIndex--; s.num = s.endIndex-s.startIndex+1; } } for (int ii = size-1;ii>=0;--ii){ elems[k+ii].copy(oldElems[oldEndIndx+ii]); // Vector2D src = oldElems[oldEndIndx+ii]; // Vector2D dest = elems[k+ii]; // dest.x = src.x; // dest.y = src.y; } // System.arraycopy(oldElems, oldEndIndx, elems, k,size); } } for (int t=j;t<sz;++t){ Vector2D point = elems[t]; int pos = (size>0) ? binarySearchFromTo(elems, point, k, k+size-1) : -(k+1); if (pos>=0){ p2 = elems[pos]; p2.x = point.x; p2.y = point.y; p2.certain = point.certain; } else { pos = -pos - 1; boolean ok1 = false; boolean ok2 = false; double d1 = 0; double d2 = 0; if (pos>k){ p1 = elems[pos-1]; double dx = p1.x-point.x; double dy = p1.y-point.y; d1 = Math.sqrt(dx*dx+dy*dy); if (d1<MINDIST && !p1.certain) ok1 = true; } if (pos<k+size){ p2 = elems[pos]; double dx = p2.x-point.x; double dy = p2.y-point.y; d2 = Math.sqrt(dx*dx+dy*dy); if (d2<MINDIST && !p2.certain) ok2 = true; } if (ok1 && ok2){ if (d1<=d2){ p1.x = point.x; p1.y = point.y; p1.certain = point.certain; } else { p2.x = point.x; p2.y = point.y; p2.certain = point.certain; } } else if (ok1){ p1.x = point.x; p1.y = point.y; p1.certain = point.certain; } else if (ok2) { p2.x = point.x; p2.y = point.y; p2.certain = point.certain; } else if (point.certain && prev!=null && prev.num>2 && !elems[prev.endIndex].certain && elems[prev.endIndex].y>point.y-1){ prev.num--; elems[prev.endIndex].copy(point); prev.endIndex--; } else { if (k+size-pos>0) { for (int ii = k+size-pos-1;ii>=0;--ii){ elems[pos+1+ii].copy(elems[pos+ii]); // Vector2D src = elems[pos+ii]; // Vector2D dest = elems[pos+1+ii]; // dest.x = src.x; // dest.y = src.y; } // System.arraycopy(elems, pos, elems, pos+1, k+size-pos); } // elems[pos]= new Vector2D(point); p2 = elems[pos]; p2.x = point.x; p2.y = point.y; p2.certain = point.certain; size++; } }//end of else }//end of for if (size>0){ k+=size; } } k -= sz; for (int ii = 0;ii<k;++ii){ // Vector2D src = elems[sz+ii]; // Vector2D dest = elems[ii]; // dest.x = src.x; // dest.y = src.y; elems[ii].copy(elems[sz+ii]); } if (done){ prevIndex++; int diff = k-prevIndex; int size = os - prevIndex; if (size>0) { for (int ii = size-1;ii>=0;--ii){ // Vector2D src = oldElems[prevIndex+ii]; // Vector2D dest = elems[k+ii]; // dest.x = src.x; // dest.y = src.y; elems[k+ii].copy(oldElems[prevIndex+ii]); } // System.arraycopy(oldElems, oldEndIndx, elems, k,size); k+=size; } for (;i<trSz;++i){ s = (which==-1) ? trArr[ trIndx[i] ].leftSeg : trArr[ trIndx[i] ].rightSeg; if (s.type==Segment.UNKNOWN){ occupied[ trIndx[i] ] = 0; int idx = i+1; if (trSz-idx>0) System.arraycopy(trIndx, idx, trIndx, i, trSz-idx); trSz--; continue; } s.startIndex+=diff; for (;s.startIndex<k;++s.startIndex) if (elems[s.startIndex].y>=s.start.y-SMALL_MARGIN) break; s.endIndex = s.startIndex+s.num-1; } } // System.arraycopy(elems, sz, elems, 0, k-sz); CircleDriver2.trSz = trSz; return k; } public void reset(){ lSize = nLsz; for (int ii = lSize-1;ii>=0;--ii) left[ii].copy(nleft[ii]); rSize = nRsz; for (int ii = rSize-1;ii>=0;--ii) right[ii].copy(nright[ii]); CircleDriver2.inTurn = true; // for (int ii = CircleDriver2.trSz-1;ii>=0;--ii) // CircleDriver2.occupied[CircleDriver2.trIndx[ii]] = 0; // CircleDriver2.trSz = 0; int i = 0; int trSz = CircleDriver2.trSz; int[] trIndx = CircleDriver2.trIndx; Segment[] trArr = CircleDriver2.trArr; for (;i<trSz;++i) { int idx = trIndx[i]; Segment t = trArr[idx]; if (t.type==0 || t.type==Segment.UNKNOWN) { CircleDriver2.occupied[idx] = 0; } else break; } if (i>0) { System.arraycopy(trIndx, i,trIndx, 0, trSz-i); trSz -= i; CircleDriver2.trSz = trSz; int jL = 0; int jR = 0; int sL= lSize; int sR = rSize; for (i = 0;i<trSz;++i){ Segment t = trArr[ trIndx[i] ]; Segment l = t.leftSeg; Segment r = t.rightSeg; double my = l.start.y; if (sL>0){ for (;jL<sL;++jL){ Vector2D p = left[jL]; if (p.y>=my-SMALL_MARGIN) break; } l.startIndex = jL; my = l.end.y; for (;jL<sL;++jL){ Vector2D p = left[jL]; if (p.y>my+SMALL_MARGIN) break; } l.endIndex = jL-1; l.num = jL-l.startIndex; } else { l.startIndex = 0; l.endIndex = -1; l.num = 0; } my = r.start.y; if (sR>0){ for (;jR<sR;++jR){ Vector2D p = right[jR]; if (p.y>=my-SMALL_MARGIN) break; } r.startIndex = jR; my = r.end.y; for (;jR<sR;++jR){ Vector2D p = right[jR]; if (p.y>my+SMALL_MARGIN) break; } r.endIndex = jR-1; r.num = jR-r.startIndex; } else { r.startIndex = 0; r.endIndex = -1; r.num = 0; } } } } public void double_check(Vector2D highest){ Segment[] trArr = CircleDriver2.trArr; int[] trIndx = CircleDriver2.trIndx; int trSz = CircleDriver2.trSz; int isL = 0; numClosePoints = 0; for (int i = lSize-1;i>=0;--i){ Vector2D v = left[i]; if (v.y<=0) break; double angle = Vector2D.angle(highest.x, highest.y, v.x, v.y); double dv = v.distance(highest); if (highest.length() > MAX_DISTANCE ||dv>trackWidth+EPS){ if (angle>=0){ i = removeFromLeftEdge(i, trArr, trSz, trIndx, CircleDriver2.occupied); trSz = CircleDriver2.trSz; } } } for (int i = lSize-1;i>=0;--i){ Vector2D v = left[i]; if (v.y<=0) break; double angle = Vector2D.angle(highest.x, highest.y, v.x, v.y); double dv = v.distance(highest); if (highest.length() < MAX_DISTANCE && dv<=trackWidth-EPS){ isL = 1; closePointV[numClosePoints].copy(v); closePoint[numClosePoints++] = dv<0.1 || angle<=0 ? -1 : 1; } } int isR = 0; for (int i = rSize-1;i>=0;--i){ Vector2D v = right[i]; if (v.y<=0) break; double angle = Vector2D.angle(highest.x, highest.y, v.x, v.y); double dv = v.distance(highest); if (highest.length() > MAX_DISTANCE || dv>trackWidth+EPS){ if (angle<0){ i = removeFromRightEdge(i, trArr, trSz, trIndx, CircleDriver2.occupied); trSz = CircleDriver2.trSz; } } } for (int i = rSize-1;i>=0;--i){ Vector2D v = right[i]; if (v.y<=0) break; double angle = Vector2D.angle(highest.x, highest.y, v.x, v.y); double dv = v.distance(highest); if (highest.length() < MAX_DISTANCE && dv<=trackWidth-EPS){ isR = 1; closePointV[numClosePoints].copy(v); closePoint[numClosePoints++] = dv>0.1 && angle<0 ? -1 : 1; } } if (isL==1 || isR==1){ //sort vector of closepoints for (int i = numClosePoints-1;i>=1;--i){ for (int j = i-1;j>=0;--j){ if (closePointV[j].y>closePointV[i].y){ Vector2D tmp = closePointV[i]; closePointV[i] = closePointV[j]; closePointV[j] = tmp; int tmpI = closePoint[i]; closePoint[i] = closePoint[j]; closePoint[j] = tmpI; } } } int firstGuess = closePoint[0]; int n = removeElems(closePointV, 0, numClosePoints, tmpIndx); if (n!=numClosePoints || !(firstGuess==1 && isL==0 || firstGuess==-1 && isR==0)){ for (int i = n-1;i>=0;--i){ Vector2D v = closePointV[ tmpIndx[i] ]; int j = binarySearchFromTo(left, v, 0, lSize-1); if (j>=0 && firstGuess==1){ removeFromLeftEdge(j, trArr, trSz, trIndx, CircleDriver2.occupied); trSz = CircleDriver2.trSz; } else if (j<0 && firstGuess==-1){ j = binarySearchFromTo(right, v, 0, rSize-1); if (j>=0){ removeFromRightEdge(j, trArr, trSz, trIndx, CircleDriver2.occupied); trSz = CircleDriver2.trSz; } } } } } CircleDriver2.trSz = trSz; CircleDriver2.edgeDetector.lSize = lSize; CircleDriver2.edgeDetector.rSize = rSize; } public final void combine(EdgeDetector ed,double distRaced,Segment[] trArr,int[] trIndx,int trSz){ long ti = System.currentTimeMillis(); // if (distRaced>ed.straightDist) // return null; if (trackWidth<=0) { trackWidth = ed.trackWidth; } double tW = Math.round(trackWidth)*0.5d; double prevTW = Math.round(ed.trackWidth)*0.5d; double toMiddle = Math.round((-tW*curPos)*PRECISION)/PRECISION; double prevToMiddle = Math.round((-prevTW*ed.curPos)*PRECISION)/PRECISION; double ax = toMiddle-prevToMiddle; double scale = tW/prevTW; if (straightDist<ed.straightDist -distRaced) straightDist = ed.straightDist -distRaced; // Segment[] rArr = r.elements(); // Segment[] lArr = l.elements(); Vector2D[] left = this.left; Vector2D[] right = this.right; // int len=ed.numpoint; // // int j = 0; if (lSize<0) lSize = 0; if (left!=null){ lSize = join(scale,ax,-distRaced, ed.left,ed.lSize,left,lSize,trArr,trIndx,trSz,-1); trSz= CircleDriver2.trSz; for (int i = 0;i<trSz;++i){ Segment lSeg = trArr[ trIndx[i] ].leftSeg; if (lSeg.num==0) continue; if (lSeg.startIndex>=0 && lSeg.start.y>lSeg.points[lSeg.startIndex].y+SMALL_MARGIN || lSeg.endIndex>=0 && lSeg.end.y<lSeg.points[lSeg.endIndex].y-SMALL_MARGIN){ CircleDriver2.inTurn = true; if (CircleDriver2.debug) System.out.println(); } if (lSeg.endIndex<lSize-1 && lSeg.end.y>lSeg.points[lSeg.endIndex+1].y+SMALL_MARGIN){ if (CircleDriver2.debug) System.out.println(); CircleDriver2.inTurn = true; } if (lSeg.startIndex>0 && lSeg.start.y<lSeg.points[lSeg.startIndex-1].y-SMALL_MARGIN ){ if (CircleDriver2.debug) System.out.println(); CircleDriver2.inTurn = true; } } for (int i=1;i<lSize;++i){ if (CircleDriver2.debug && left[i].y-left[i-1].y==0) System.out.println(); if (left[i].y<left[i-1].y){ if (CircleDriver2.debug) System.out.println(); turn = Segment.UNKNOWN; reset(); return; } } } if (rSize<0) rSize = 0; if (right!=null){ rSize = join(scale,ax,-distRaced,ed.right,ed.rSize, right,rSize, trArr,trIndx,trSz,1); trSz= CircleDriver2.trSz; for (int i = 0;i<trSz;++i){ Segment rSeg = trArr[ trIndx[i] ].rightSeg; if (rSeg.num==0) continue; if (rSeg.startIndex>=0 && rSeg.start.y>rSeg.points[rSeg.startIndex].y+SMALL_MARGIN || rSeg.endIndex>=0 && rSeg.end.y<rSeg.points[rSeg.endIndex].y-SMALL_MARGIN){ if (CircleDriver2.debug) System.out.println(); CircleDriver2.inTurn = true; } } for (int i=1;i<rSize;++i){ if (CircleDriver2.debug && right[i].y-right[i-1].y==0) System.out.println(); if (right[i].y<right[i-1].y){ if (CircleDriver2.debug) System.out.println(); reset(); return; } } } Segment first = (trSz>0) ? trArr[ trIndx[0] ] : null; if (left!=null && right!=null && rSize>0 && lSize>0 && first.type==0 && Math.abs(first.start.x-first.end.x)<=TrackSegment.EPSILON*0.1){ for (int j = 0;j<trSz;++j){ Segment t = trArr[ trIndx[j] ]; if (t.type!=0 || Math.abs(t.start.x-t.end.x)>=TrackSegment.EPSILON) break; Segment r0 = t.rightSeg; Segment l0 = t.leftSeg; double x0 = r0.start.x; double xx = l0.start.x; int end = l0.endIndex+1; boolean notGood = false; int li = -1; int ri= -1; for (int i = l0.startIndex;i<end;++i){ double x = left[i].x; if (CircleDriver2.debug && Math.abs(x-x0)<trackWidth-1) System.out.println(); if (left[i].certain && Math.abs(x-xx)>=TrackSegment.EPSILON){ notGood = true; if (i<end-1){ reset(); return; } li = i; break; } } x0 = l0.start.x; xx = r0.start.x; end = r0.endIndex+1; if (r0.startIndex>=0){ for (int i = r0.startIndex;i<end;++i){ double x = right[i].x; if (CircleDriver2.debug && Math.abs(x-x0)<trackWidth-1) System.out.println(); if (right[i].certain && Math.abs(x-xx)>=TrackSegment.EPSILON){ notGood = true; if (i<end-1){ reset(); return; } ri = i; break; } } } if (notGood){ double mm = -1; if (li!=-1 && li>0) mm = Math.max(mm, left[li-1].y); if (ri!=-1 && ri>0) mm = Math.max(mm, right[ri-1].y); if (li!=-1 && ri!=-1 || mm-l0.start.y<2){ reset(); return; } else { if (li!=-1){ if (r0.num>0) { mm = Math.max(right[r0.endIndex].y, mm); if (mm>=left[li].y){ reset(); return; } } l0.endIndex = li-1; l0.num = li-l0.startIndex; while (r0.endIndex>=r0.startIndex && right[r0.endIndex].y>mm) r0.endIndex--; r0.num = r0.endIndex+1-r0.startIndex; } else { if (l0.num>0) { mm = Math.max(left[l0.endIndex].y, mm); if (mm>=right[ri].y){ reset(); return; } } r0.endIndex = ri-1; r0.num = ri-r0.startIndex; while (l0.endIndex>=l0.startIndex && left[l0.endIndex].y>mm) l0.endIndex--; l0.num = l0.endIndex+1-l0.startIndex; } l0.end.y = mm; r0.end.y = mm; t.end.y = mm; } } } } Vector2D edH = ed.highestPoint; if (ed!=null && edH!=null && edH.length()<MAX_DISTANCE){ if (scale!=1.0) edH.x*=scale; edH.x+=ax; edH.y+=-distRaced; // at.transform(edH, edH); edH.certain = false; } Vector2D lower = (highestPoint !=null && edH!=null && highestPoint.y<edH.y) ? highestPoint : (highestPoint==null || edH==null) ? null : edH; int whichL = (highestPoint !=null && edH!=null && highestPoint.y<edH.y) ? whichE : (lower==null) ? 0 : ed.whichE; Vector2D higher = (highestPoint !=null && edH!=null && highestPoint.y<edH.y) ? edH : (highestPoint==null) ? edH : highestPoint; int whichH = (highestPoint !=null && edH!=null && highestPoint.y<edH.y) ? ed.whichE : (highestPoint==null) ? ed.whichE : whichE; if (whichH==0 || whichL==0){ if (lower!=null && higher!=null ) guessHighestPointEdge(lower, whichL, higher, whichH, left, lSize, right, rSize, trackWidth,out); int newWhichL = out[0]; int newWhichH = out[1]; double dd = edH!=null && highestPoint!=null ? edH.distance(highestPoint) : 0; if (newWhichL==0 && newWhichH==0 && edH!=null && highestPoint!=null && edH.length()<99 && highestPoint.length()<99 && dd<trackWidth-EdgeDetector.CERTAIN_DIST && dd>0.5) { // if (relativeAngleMovement>0) { // if (highestPoint.y>ph.y) { // whichH = whichL = (highestPoint.x-ph.x)*turn<0 ? -turn : 0; // } else whichH = whichL = (highestPoint.x-ph.x)*turn>0 ? turn : 0; // } else if (highestPoint.y<ph.y) { // whichH = whichL = (highestPoint.x-ph.x)*turn>0 ? turn : 0; // } else whichH = whichL = (highestPoint.x-ph.x)*turn<0 ? -turn : 0; if ((highestPoint.y-edH.y)*(highestPoint.x-edH.x)<0) newWhichH = newWhichL = 1; else newWhichH = newWhichL = -1; if (whichH!=0) turn = -newWhichH; CircleDriver2.edgeDetector.turn = turn; CircleDriver2.guessTurn = false; } if (whichL==0 && newWhichL!=0 && lower!=null){ double dx = lower.x - higher.x; double dy = lower.y - higher.y; if (newWhichH!=newWhichL || (higher!=null && Math.sqrt(dx*dx+dy*dy)>MINDIST) || higher==null){ switch (newWhichL){ case 1: rSize = join(lower, right, rSize, trArr,trIndx,trSz,1); break; default: lSize = join(lower,left,lSize, trArr,trIndx,trSz,-1); break; } } } if (whichH==0 && newWhichH!=0 && higher!=null){ switch (newWhichH){ case 1: rSize = join(higher, right, rSize, trArr,trIndx,trSz,1); break; default: lSize = join(higher,left,lSize, trArr,trIndx,trSz,-1); break; } } if (CircleDriver2.debug)System.out.println("Left num : "+lSize); if (CircleDriver2.debug)System.out.println("Right num : "+rSize); whichL = newWhichL; whichH = newWhichH; if (whichEdgeAhead==0){ if (whichL!=0 && lower!=null && currentPointAhead.x==lower.x && currentPointAhead.y==lower.y) whichEdgeAhead = whichL; else if (whichH!=0 && higher!=null && currentPointAhead.x==higher.x && currentPointAhead.y==higher.y) whichEdgeAhead = whichH; else if (currentPointAhead.y!=0 || currentPointAhead.x!=0){ if (lSize>0 && binarySearchFromTo(left, currentPointAhead, 0, lSize-1)>=0) whichEdgeAhead = -1; else if (rSize>0 && binarySearchFromTo(right, currentPointAhead, 0, rSize-1)>=0) whichEdgeAhead = 1; } } double dx = (higher==null) ? 0 : higher.x; double dy = (higher==null) ? 0 : higher.y; if (higher!=null && Math.sqrt(dx*dx+dy*dy)<MAX_DISTANCE){ highestPoint = higher; whichE = whichH; } else if (lower!=null && lower.length()<MAX_DISTANCE){ highestPoint = lower; whichE = whichL; } } Vector2D highest = (lSize>0) ? left[lSize-1] : null; if (rSize>0){ if (highest==null || highest.y<right[rSize-1].y) highest = right[rSize-1]; } if (highestPoint!=null && highest.y<highestPoint.y) highest = highestPoint; else if (highestPoint==null && ed.highestPoint!=null && highest.y<ed.highestPoint.y) highest = ed.highestPoint; /*if (trSz>0){ Segment lSeg = trArr[trIndx[trSz-1]].leftSeg; if (lSeg.end.y>highest.y) highest = lSeg.end; lSeg = trArr[trIndx[trSz-1]].rightSeg; if (lSeg.end.y>highest.y) highest = lSeg.end; }//*/ double_check(highest); if (CircleDriver2.debug && highestPoint!=null)System.out.println("Highest Point : "+highestPoint+" "+highestPoint.length()); int nlS = lSize; int nrS = rSize; numpoint = (whichE==0 && highestPoint!=null && highestPoint.length()<MAX_DISTANCE) ? nlS+nrS+1 : nlS+nrS; // Vector2D[] newArr = new Vector2D[numpoint]; // j = nlS; // if (left!=null) // System.arraycopy(left.elements(), 0, newArr, 0, j); // if (whichE==0 && highestPoint!=null && highestPoint.length()<MAX_DISTANCE) // newArr[j++] = highestPoint; // // if (right!=null) // System.arraycopy(right.elements(), 0, newArr, j, nrS); // allPoints = ObjectArrayList.wrap(newArr, numpoint); // double l0 = (left!=null && left.size()>0) ? left.get(0).x : -10000; // double l1 = (left!=null && left.size()>0) ? left.get(left.size()-1).x : -10000; // double r0 = (right!=null && right.size()>0) ? right.get(0).x : -10000; // double r1 = (right!=null && right.size()>0) ? right.get(right.size()-1).x : -10000; // boolean straight = (highestPoint!=null && highestPoint.length()>=MAX_DISTANCE); // boolean nlS = Math.abs(l1-l0)>TrackSegment.EPSILON; // boolean nrS = Math.abs(r1-r0)>TrackSegment.EPSILON; // if (straight && (Math.abs(l1-l0)<=TrackSegment.EPSILON || Math.abs(r1-r0)<=TrackSegment.EPSILON)) // turn = MyDriver.STRAIGHT; // else if ((nlS && l1>l0) || (nrS && r1>r0)) // turn = 1; // else if ((nlS && l1<l0) || (nrS && r1<r0)) // turn = -1; // else turn = 2; double dL = getStraightDist(left,lSize); double dR = getStraightDist(right,rSize); straightDist = Math.max(dL, dR); if (CircleDriver2.debug) System.out.println("K : "+(System.currentTimeMillis()-ti)); // AffineTransform at = new AffineTransform(); // at.scale(scale, 1); // at.translate(ax, -distRaced); // combine(scale,ax,-distRaced,ed,distRaced,trArr,trIndx,trSz); } public final int estimateTurn(){ boolean all=true; double toRight = toRightEdge(); Vector2D[] lArr = left; Vector2D[] rArr = right; int sL = lSize; int sR= rSize; double sum=0; for (int i=sL-1;i>=0;--i){ Vector2D v = lArr[i]; sum += v.x; double r = v.x+toRight; if (!(Math.abs(r)<=DELTA || Math.abs(r-trackWidth)<=DELTA)){ all = false; } else if (r>0){ return TURNRIGHT; } else if (r<-trackWidth) return TURNLEFT; } double meanL = Math.round(sum/sL*10000)/10000.0d; sum = 0; for (int i=sR-1;i>=0;--i){ Vector2D v = rArr[i]; sum+=v.x; double r = v.x+toRight; if (!(Math.abs(r)<=DELTA || Math.abs(r-trackWidth)<=DELTA)){ all = false; } else if (r>0){ return TURNRIGHT; } else if (r<-trackWidth) return TURNLEFT; } double meanR = Math.round(sum/sR*10000.0)/10000.0d; if (all) // if (maxDistance>=99) return STRAIGHT; // else return MyDriver.UNKNOWN; if (sL<=0 || sR<=0) return UNKNOWN; double rl = lArr[sL-1].x; double rr = rArr[sR-1].x; if (Math.abs(rl-meanL)<=DELTA && Math.abs(rr-meanR)<=DELTA){ if (maxDistance>=99) { return STRAIGHT; } return UNKNOWN; } if (meanR<=0 || rl<meanL-DELTA || meanR>rr+DELTA) return TURNLEFT; return TURNRIGHT; } public double toMiddle(){ // if (trackWidth<=0 || curPos<-1 || curPos>1) return Double.NaN; return Math.round(trackWidth/2*curPos*10000.0d)/10000.0d; } public double toLeftEdge(){ // if (trackWidth<=0 || curPos<-1 || curPos>1) return Double.NaN; return Math.round(trackWidth/2*(1+curPos)*10000.0d)/10000.0d; } public double toRightEdge(){ // if (trackWidth<=0 || curPos<-1 || curPos>1) return Double.NaN; return -Math.round(trackWidth/2*(1-curPos)*10000.0d)/10000.0d; } /** * @return the trackWidth */ public double getTrackWidth() { return trackWidth; } /** * @param trackWidth the trackWidth to set */ public void setTrackWidth(double trackWidth) { this.trackWidth = trackWidth; } /** * @return the maxDistance */ public double getMaxDistance() { return maxDistance; } /** * @param maxDistance the maxDistance to set */ public void setMaxDistance(double maxDistance) { this.maxDistance = maxDistance; } double SimSteerUpdate(double oldSteer,double steer){ /* input control */ steer *= steerLock; double stdelta = steer - oldSteer; double sign = (stdelta<0) ?-1:1; if ( Math.abs(stdelta/DELTATIME) > MAXSTEERSPEED ){ steer = sign * MAXSTEERSPEED * DELTATIME + oldSteer; }; return steer; } public void drawEdge(double[] x,double[] y,final String title){ XYSeries series = new XYSeries("Curve",false,true); // for (int i=0;i<numPointLeft;++i){ // series.add(leftEgdeX[i], leftEgdeY[i]); // } for (int i=0;i<x.length;++i){ series.add(x[i],y[i]); if (i<x.length-1) series.add(0,0); } // for (int i=0;i<numPointRight;++i){ // series.add(rightEgdeX[i], rightEgdeY[i]); // } XYDataset xyDataset = new XYSeriesCollection(series); // Create plot and show it final JFreeChart chart = ChartFactory.createXYLineChart("", "x", "y", xyDataset, PlotOrientation.VERTICAL, false, false, false ); // Shape[] shapes = new Shape[x.length]; // for (int i = 0;i<shapes.length;++i){ // shapes[i] = new Line2D.Double(0, 0, x[i], y[i]); // } // final DrawingSupplier supplier = new DefaultDrawingSupplier( // DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE, // DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE, // DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE, // DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE, // shapes // ); XYPlot xyPlot = chart.getXYPlot(); xyPlot.getDomainAxis().setRange(-60.0,60.0); xyPlot.getRangeAxis().setRange(-10.0,110.0); // xyPlot.setDrawingSupplier(supplier); final XYLineAndShapeRenderer renderer= (XYLineAndShapeRenderer)xyPlot.getRenderer(); // renderer.setDrawSeriesLineAsPath(true); renderer.setSeriesStroke( 0, new BasicStroke( 2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] {2.0f, 10.0f}, 0.0f )); renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled (true); // customise the renderer... // renderer.setDrawShapes(true); // renderer.setLabelGenerator(new StandardCategoryLabelGenerator()); Thread p = new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try{ BufferedImage image = chart.createBufferedImage(500, 500); ImageIO.write(image, "png", new File(title+".png")); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }); p.start(); // ChartPanel chartPanel = new ChartPanel(chart); // jf.setContentPane(chartPanel); // jf.setPreferredSize(new Dimension(600,400)); // jf.setMinimumSize(new Dimension(600,400)); // jf.setVisible(true); } public static void drawEdge(ObjectList<Vector2D> vs,final String title){ XYSeries series = new XYSeries("Curve"); for (Vector2D v:vs){ if (v!=null) series.add(v.x,v.y); } XYDataset xyDataset = new XYSeriesCollection(series); // Create plot and show it final JFreeChart chart = ChartFactory.createScatterPlot(title, "x", "y", xyDataset, PlotOrientation.VERTICAL, false, true, false ); // chart.getXYPlot().getDomainAxis().setRange(-50.0,50.0); // chart.getXYPlot().getRangeAxis().setRange(-20.0,100.0); chart.getXYPlot().getDomainAxis().setRange(-60.0,60.0); chart.getXYPlot().getRangeAxis().setRange(-10.0,110.0); Thread p = new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try{ BufferedImage image = chart.createBufferedImage(500, 500); ImageIO.write(image, "png", new File(title+".png")); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }); p.start(); } public static void drawEdge(Vector2D[] vs,final String title){ XYSeries series = new XYSeries("Curve"); for (int i=0;i<vs.length;++i){ series.add(vs[i].x,vs[i].y); } XYDataset xyDataset = new XYSeriesCollection(series); // Create plot and show it final JFreeChart chart = ChartFactory.createScatterPlot(title, "x", "y", xyDataset, PlotOrientation.VERTICAL, false, true, false ); // chart.getXYPlot().getDomainAxis().setRange(-50.0,50.0); // chart.getXYPlot().getRangeAxis().setRange(-20.0,100.0); chart.getXYPlot().getDomainAxis().setRange(-60.0,60.0); chart.getXYPlot().getRangeAxis().setRange(-10.0,110.0); Thread p = new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try{ BufferedImage image = chart.createBufferedImage(600, 400); ImageIO.write(image, "png", new File(title+".png")); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }); p.start(); } public static void drawEdge(EdgeDetector ed,final String title){ XYSeries series = new XYSeries("Curve"); Vector2D[] lArr = ed.left; Vector2D[] rArr = ed.right; int sL = ed.lSize; int sR= ed.rSize; for (int i=sL-1;i>=0;--i){ Vector2D v = lArr[i]; series.add(v.x,v.y); } if (ed.whichE==0) series.add(ed.highestPoint.x,ed.highestPoint.y); for (int i=sR-1;i>=0;--i){ Vector2D v = rArr[i]; series.add(v.x,v.y); } XYDataset xyDataset = new XYSeriesCollection(series); // Create plot and show it final JFreeChart chart = ChartFactory.createScatterPlot(title, "x", "y", xyDataset, PlotOrientation.VERTICAL, false, true, false ); chart.getXYPlot().getDomainAxis().setRange(-50.0,50.0); chart.getXYPlot().getRangeAxis().setRange(-20.0,100.0); Thread p = new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try{ BufferedImage image = chart.createBufferedImage(600, 400); ImageIO.write(image, "png", new File(title+".png")); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }); p.start(); } public static void drawEdge(XYSeries series,final String title){ XYDataset xyDataset = new XYSeriesCollection(series); // Create plot and show it final JFreeChart chart = ChartFactory.createScatterPlot(title, "x", "y", xyDataset, PlotOrientation.VERTICAL, false, true, false ); // chart.getXYPlot().getDomainAxis().setRange(-200.0,200.0); // chart.getXYPlot().getRangeAxis().setRange(-200.0,200.0); chart.getXYPlot().getDomainAxis().setRange(-60.0,60.0); chart.getXYPlot().getRangeAxis().setRange(-10.0,110.0); // chart.getXYPlot().getDomainAxis().setRange(-5.0,5.0); // chart.getXYPlot().getRangeAxis().setRange(-5.0,5.0); Thread p = new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try{ BufferedImage image = chart.createBufferedImage(500, 500); ImageIO.write(image, "png", new File(title+".png")); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }); p.start(); } // public ObjectArrayList<Vector2D> getLeftEdge(){ // return left; // } // // public ObjectArrayList<Vector2D> getRightEdge(){ // return right; // } /** * Constructs a <code>String</code> with all attributes * in name = value format. * * @return a <code>String</code> representation * of this object. */ public String toString() { final String TAB = " "; String retValue = ""; retValue = "EdgeDetector ( " + super.toString() + TAB + "whichE = " + this.whichE + TAB + "currentPointAhead = " + this.currentPointAhead + TAB + "cp = " + this.cp + TAB + "trackWidth = " + this.trackWidth + TAB + "curPos = " + this.curPos + TAB + "distRaced = " + this.distRaced + TAB + "curAngle = " + this.curAngle + TAB + "maxY = " + this.maxY + TAB + "left = " + this.left + TAB + "right = " + this.right + TAB + "numpoint = " + this.numpoint + TAB + "maxDistance = " + this.maxDistance + TAB + "leftStraight = " + this.leftStraight + TAB + "rightStraight = " + this.rightStraight + TAB + "straightDist = " + this.straightDist + TAB + "highestPoint = " + this.highestPoint + TAB + "turn = " + this.turn + TAB + "center = " + this.center + TAB + "radiusL = " + this.radiusL + TAB + "radiusR = " + this.radiusR + TAB + " )"; return retValue; } }
package go4Code.Restaurante.dto; import go4Code.Restaurante.model.Menu; public class MenuDTO { private Long id; private String name; private String category; private Double price; public MenuDTO() { super(); } public MenuDTO(Long id, String name, String category, Double price) { super(); this.id = id; this.name = name; this.category = category; this.price = price; } public MenuDTO(Menu menu) { this.id = menu.getId(); this.name = menu.getName(); this.category = menu.getCategory(); this.price = menu.getPrice(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Override public String toString() { return "MenuDTO [name=" + name + ", category=" + category + ", price=" + price + "]"; } }
package com.example.words; import java.util.ArrayList; import java.util.List; import java.io.Serializable; import java.util.Vector; import db.*; public class MessagePack implements Serializable { private static final long serialVersionUID = 1L; public String orderType; public User user; public Boolean isChanged = false; public Vector<String> strPack = new Vector<String>(); public Vector<Boolean> booleanResult = new Vector<Boolean>(); public List<Wordbook> wordbookList = new ArrayList<Wordbook>(); public String taskType; public MessagePack(){} public MessagePack(String ot) { this.orderType = ot; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Boolean getChanged() { return isChanged; } public void setChanged(Boolean changed) { isChanged = changed; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public void booleanAdd(Boolean b){ this.booleanResult.add(b); } public void setListwordbook(List<Wordbook> wb){ this.wordbookList = wb; } public List<Wordbook> getListwordbook(){ return wordbookList; } public Vector<String> getStrPack() { return strPack; } public void setStrPack(Vector<String> strPack) { this.strPack = strPack; } public void addString(String str){ this.strPack.add(str); } public Vector<Boolean> getBooleanResult() { return booleanResult; } public void setBooleanResult(Vector<Boolean> booleanResult) { this.booleanResult = booleanResult; } public String getTaskType() { return taskType; } public void setTaskType(String taskType) { this.taskType = taskType; } public List<Wordbook> getWordbookList() { return wordbookList; } public void setWordbookList(List<Wordbook> wordbookList) { this.wordbookList = wordbookList; } }
package edu.uiowa.icts.util; /** * @author rrlorent */ public class DataTableColumn { private String name = null; private String value = null; private String title = null; private boolean selected = true; public DataTableColumn( String name, String value, String title, boolean selected ){ this.name = name; this.title = title; this.value = value; this.selected = selected; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean getSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } }
package cn.com.onlinetool.fastpay.pay.wxpay.response; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author choice * @description: 微信 转换短链接 响应对象 * @date 2019-06-11 14:42 * */ @NoArgsConstructor @AllArgsConstructor @Data public class WXPayShortUrlResponse extends WXPayBaseResponse { /** * URL链接 必填 * 转换后的URL */ private String shortUrl; }
package org.shiro.demo.vo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.shiro.demo.dao.util.Pagination; import org.shiro.demo.entity.DBPlan; public class UDBPlanVO { private Long id; private Integer block;//分区(1:一元区,2:十元区,3:百元区,4:千元区) private Long split;//单次竞标价 private Long startTime;//竞标开始时间 private Long endTime;//竞标结束 private Integer number;//数量 private Double money;//价位 private Long goodsid; public Integer getBlock() { return block; } public void setBlock(Integer block) { this.block = block; } public Long getSplit() { return split; } public void setSplit(Long split) { this.split = split; } public Long getStartTime() { return startTime; } public void setStartTime(Long startTime) { this.startTime = startTime; } public Long getEndTime() { return endTime; } public void setEndTime(Long endTime) { this.endTime = endTime; } public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } public UDBPlanVO() { super(); } public UDBPlanVO(DBPlan dbPlan) { super(); this.id = dbPlan.getDbplanid(); this.block = dbPlan.getBlock(); this.split = dbPlan.getSplit(); this.startTime = dbPlan.getStartTime(); this.endTime = dbPlan.getEndTime(); this.number = dbPlan.getNumber(); this.money = dbPlan.getMoney(); this.goodsid = dbPlan.getGoods().getGoodsid(); } /** * 将实体类转换成显示层实体类 * @param pagination 分页数据 * @return */ public static Map<String, Object> changeDBPlan2DBPlanVO(Pagination<DBPlan> pagination){ List<DBPlan> recordList = pagination.getRecordList(); List<UDBPlanVO> VOList = new ArrayList<UDBPlanVO>(); Map<String, Object> map = new HashMap<String, Object>(); for(DBPlan item : recordList){ VOList.add(new UDBPlanVO(item)); } map.put("rows", VOList); map.put("total", pagination.getRecordCount()); return map; } /** * 将实体类转换成显示层实体类 * @param pagination 分页数据 * @return */ public static List<UDBPlanVO> changeDBPlan2DBPlanVO(List<DBPlan> recordList){ List<UDBPlanVO> roleVOList = new ArrayList<UDBPlanVO>(); Map<String, Object> map = new HashMap<String, Object>(); for(DBPlan item : recordList){ roleVOList.add(new UDBPlanVO(item)); } return roleVOList; } public UDBPlanVO(Long id, Integer block, Long split, Long startTime, Long endTime, Integer number, Double money, Long goodsid) { super(); this.id = id; this.block = block; this.split = split; this.startTime = startTime; this.endTime = endTime; this.number = number; this.money = money; this.goodsid = goodsid; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getGoodsid() { return goodsid; } public void setGoodsid(Long goodsid) { this.goodsid = goodsid; } }
package com.njit.card.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.njit.card.dao.LoginDAO; import com.njit.card.entity.Login; import com.njit.card.utils.DBUtil; public class LoginDAOImpl implements LoginDAO { public Login findById(long id) { Connection conn=null; Login login=null; try { conn=DBUtil.getConnection(); String sql="select * from login where id=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1, id); ResultSet rst=prep.executeQuery(); while(rst.next()){ login=new Login(); login.setId(id); login.setMm(rst.getString("mm")); login.setType(rst.getInt("type")); } } catch (Exception e) { e.printStackTrace(); }finally{ DBUtil.close(conn); } return login; } @Override public void updataById(long id, String pasword) throws Exception{ // TODO 自动生成的方法存根 Connection conn=null; conn=DBUtil.getConnection(); System.out.println(id+" "+ pasword); String sql="update login set mm=? where id=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setString(1,pasword); prep.setDouble(2,id); prep.execute(); DBUtil.close(conn); } @Override public void addLogin(Login newLogin) throws Exception { // TODO 自动生成的方法存根 Connection conn=null; conn=DBUtil.getConnection(); String sql="insert into login(id,mm,type) values(?,?,?)"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,newLogin.getId()); prep.setString(2,newLogin.getMm()); prep.setInt(3, newLogin.getType()); prep.execute(); DBUtil.close(conn); } @Override public void delById(long loginId) throws Exception { // TODO 自动生成的方法存根 Connection conn=null; conn=DBUtil.getConnection(); String sql="delete from login where id=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,loginId); prep.execute(); DBUtil.close(conn); } }
package malp.Entities; import malp.SantaDash.GameEngine; import malp.SantaDash.ResourceManager; public class Explosion extends Entity{ public Explosion(int x, int y) { super(ResourceManager.getExplosion(), x, y, true); ResourceManager.getExplosionSound().play(); } @Override public void update() { if(ResourceManager.getExplosion().getFrame() == ResourceManager.getExplosion().getFrameCount() - 1) { this.x = GameEngine.CLEANUP_X; } } @Override public void collisionEvent() { } }
package ru.job4j.task4; /** * Интерфэйс Shape реализует сущность "геометрическая фигура". * * @author Goureev Ilya (mailto:ill-jah@yandex.ru) * @version 1 * @since 2017-04-22 */ interface Shape { /** * Возвращает фигуру в виде строки. * @return фигура в виде строки. */ String pic(); }
package jire.packet.parse; import jire.packet.Packet; import jire.packet.PacketParser; import jire.packet.PacketRepresentation; import jire.packet.reflective.ParsesPacket; import jire.packet.represent.IdleLogoutPacket; @ParsesPacket(202) public final class IdleLogoutPacketParser implements PacketParser { @Override public PacketRepresentation parse(Packet packet) { return IdleLogoutPacket.get(); } }
/* * Copyright (c) 2017 Anwar. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Anwar - initial API and implementation and/or initial documentation */ package NQTD; /** * The following class is store an intent(a command, the category it belongs to * and the response that should be appended to the result) * @author Anwar */ public class Intents { private final String command; private final String category; private final String response; private static int id; /** * Constructor for Intents class * @param command * @param category * @param response */ public Intents(String command, String category, String response) { super(); this.command = command; this.category = category; this.response=response; } /** * Copy constructor * @param intent */ public Intents(Intents intent) { this(intent.getCommand(), intent.getCategory(), intent.getResponse()); } /** * Returns the command of an intent * @return command */ public String getCommand() { return command; } /** * Returns the category of an intent * @return category */ public String getCategory() { return category; } /** * Returns the response of an intent * @return response */ public String getResponse(){ return this.response; } /** * Returns the id of an intent * @return id */ public static int getId() { return id; } /** * Sets the id of an intent * @param id */ public static void setId(int id) { Intents.id = id; } } /////////////////////// END OF SOURCE FILE /////////////////
package com.proyecto.common.util; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class ApplicationContextProvider implements ApplicationContextAware { /** * The application context. */ private static ApplicationContext ctx; /** * Get context. * @return ctx */ public static ApplicationContext getContext() { return ctx; } /** * Set context. * @param ctx */ public static void setContext(ApplicationContext ctx) { ApplicationContextProvider.ctx = ctx; } /** * Set application context. * @param ctx */ public void setApplicationContext(ApplicationContext ctx){ setContext(ctx); } /** * Get bean. * @param beanName * @return the bean by name */ public static <E extends Object> E getBean(Class<E> beanName) { return getContext().getBean(beanName); } /** * Get bean. * @param beanName * @return the bean by name */ public static Object getBean(String beanName) { return getContext().getBean(beanName); } }
package net; import commands.Command; public interface Channel { /** * Send command to server / client * * @param command : the command to be sent */ public void send(Command<?, ? extends Connection> command); }
package com.example.objectbox.adapter; import android.app.Activity; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.example.objectbox.App; import com.example.objectbox.R; import com.example.objectbox.bean.Customer; import java.util.ArrayList; import java.util.List; public class OneToManyAdapter extends RecyclerView.Adapter<CommonHolder> { private List<Customer> list = new ArrayList<>(); @NonNull @Override public CommonHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(App.getInstance().getApplicationContext()).inflate(R.layout.adapter_one_to_many, viewGroup, false); return new CommonHolder(view); } @Override public void onBindViewHolder(@NonNull final CommonHolder holder, final int i) { holder.id.setText(String.valueOf(list.get(i).getId())); holder.name.setText(list.get(i).getName()); holder.num.setText(String.valueOf(list.get(i).getOrders().size())); holder.ll_one_to_many.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onItemClick(v,list.get(i)); } }); } @Override public int getItemCount() { return list.size(); } public void setData(List<Customer> list){ this.list = list; notifyDataSetChanged(); } public void setOnItemClick(OnItemClickListener onItemClickListener){ listener = onItemClickListener; } public OnItemClickListener listener; public interface OnItemClickListener{ void onItemClick(View v,Customer customer); } }
package org.yoqu.fish.common.codec.compress; /** * @author yoqu * @date 2018/2/5 - 下午2:53 */ public interface Compress { byte[] compress(byte[] bytes); byte[] unCompress(byte[] bytes); }
package com.willian.Estoque.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor @Builder @Entity public class Produto implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String descricao; private String numSerie; @JsonIgnore @ManyToMany @JoinTable(name = "PRODUTO_CATEGORIA", joinColumns = @JoinColumn(name = "produto_id"), inverseJoinColumns = @JoinColumn(name = "categoria_id")) private List<Categoria> categorias = new ArrayList<>(); @ManyToOne @JoinColumn(name = "marca_id") private Marca marca; @JsonIgnore @OneToMany(mappedBy = "item.produto") private List<ItemPedido> itens = new ArrayList<>(); @JsonIgnore public List<Pedido> getPedidos(){ List<Pedido> lista = new ArrayList<>(); for (ItemPedido itemPedido : itens ) { lista.add(itemPedido.getPedido()); } return lista; } }
package calculator; public class ExpressionCalculator{ //ctor public ExpressionCalculator(){ } //hitung public void Hitung(){ System.out.println("Hitung!"); } }
package Locacao.view; import javax.swing.JFrame; import javax.swing.SwingConstants; public class LocacaoJF extends javax.swing.JFrame { public LocacaoJF() { initComponents(); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); btnListaLocacoes = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); btnAddOuRemLocacao = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(255, 204, 102)); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); btnListaLocacoes.setText("Lista de locações"); btnListaLocacoes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnListaLocacoesActionPerformed(evt); } }); jPanel2.setBackground(new java.awt.Color(51, 204, 255)); jLabel1.setFont(new java.awt.Font("Tunga", 0, 36)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Locadora de filmes"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(179, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(158, 158, 158)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(jLabel1) .addContainerGap(19, Short.MAX_VALUE)) ); btnAddOuRemLocacao.setText("Adicionar"); btnAddOuRemLocacao.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLocacaoActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(0, 51, 204)); jLabel2.setText("Opções locação:"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(54, 54, 54) .addComponent(btnListaLocacoes, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnAddOuRemLocacao, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(78, 78, 78)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(245, 245, 245) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(52, 52, 52) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(34, 34, 34) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnListaLocacoes, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnAddOuRemLocacao, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(174, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnListaLocacoesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListaLocacoesActionPerformed ListaDeLocacoesJF telaListaLocacoes = new ListaDeLocacoesJF(); telaListaLocacoes.setVisible(true); }//GEN-LAST:event_btnListaLocacoesActionPerformed private void btnLocacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLocacaoActionPerformed CadastrarLocacao telaLocacao = new CadastrarLocacao(); telaLocacao.setVisible(true); }//GEN-LAST:event_btnLocacaoActionPerformed public static void main(String args[]) { /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new LocacaoJF().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAddOuRemLocacao; private javax.swing.JButton btnListaLocacoes; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; // End of variables declaration//GEN-END:variables }
package com.ak.texasholdem.tests; import com.ak.texasholdem.board.Board; import com.ak.texasholdem.cards.Deck; import com.ak.texasholdem.player.Player; import com.ak.texasholdem.player.Players; public class SessionTest { public static void main(String[] args) { System.out.println("game setup"); Board board = new Board(); Players players = new Players(); players.addPlayerToTheBoard(new Player("AAA", "", "", 5000)); players.addPlayerToTheBoard(new Player("BBB", "", "", 5000)); players.addPlayerToTheBoard(new Player("CCC", "", "", 5000)); players.addPlayerToTheBoard(new Player("DDD", "", "", 5000)); Deck deck = new Deck(); System.out.println("game over"); } }
package io.robusta.fora.swing; import io.robusta.fora.domain.Comment; public class CommentController { Comment model; CommentView view; public CommentController(Comment model, CommentView view) { this.model = model; this.view = view; } public Comment getModel() { return model; } public void setModel(Comment model) { this.model = model; } public CommentView getView() { return view; } public void setView(CommentView view) { this.view = view; } public int like(){ this.model.setScore(this.model.getScore() + 1); return this.model.getScore(); } public int dislike(){ this.model.setScore(this.model.getScore() - 1); return this.model.getScore(); } public void flag(){ } }
public class Service2Proxy extends Service2 { public void print2(){ new Aspect().beforeCalled(); super.print2(); } }
package eu.hradio.timeshiftsample; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.IBinder; import android.support.v4.app.Fragment; import android.util.Log; import org.omri.radio.Radio; import org.omri.radioservice.RadioService; import org.omri.radioservice.RadioServiceType; import org.omri.radioservice.metadata.Textual; import org.omri.radioservice.metadata.TextualDabDynamicLabel; import org.omri.radioservice.metadata.TextualDabDynamicLabelPlusItem; import org.omri.radioservice.metadata.TextualType; import org.omri.radioservice.metadata.Visual; import org.omri.tuner.ReceptionQuality; import org.omri.tuner.Tuner; import org.omri.tuner.TunerListener; import org.omri.tuner.TunerStatus; import java.io.IOException; import eu.hradio.core.audiotrackservice.AudiotrackService; import eu.hradio.timeshiftplayer.SkipItem; import eu.hradio.timeshiftplayer.TimeshiftListener; import eu.hradio.timeshiftplayer.TimeshiftPlayer; import eu.hradio.timeshiftplayer.TimeshiftPlayerFactory; import static eu.hradio.timeshiftsample.BuildConfig.DEBUG; public class RetainedFragment extends Fragment implements TunerListener, TimeshiftListener { private static final String TAG = "RetainedFragment"; private TimeshiftPlayer mTimeshiftPlayer = null; private RadioService mRunningSrv = null; private boolean mAudiotrackServiceBound = false; private transient AudiotrackService.AudioTrackBinder mAudiotrackService = null; private PendingIntent mNotificationIntent = null; private ServiceConnection mSrvCon = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { if(BuildConfig.DEBUG)Log.d(TAG, "onServiceConnected AudioTrackService"); if(service instanceof AudiotrackService.AudioTrackBinder) { mAudiotrackServiceBound = true; mAudiotrackService = (AudiotrackService.AudioTrackBinder) service; if(mNotificationIntent != null) { mAudiotrackService.getNotification().setContentIntent(mNotificationIntent); } } } @Override public void onServiceDisconnected(ComponentName name) { if(BuildConfig.DEBUG)Log.d(TAG, "onServiceDisconnected AudioTrackService"); mAudiotrackServiceBound = false; mAudiotrackService = null; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(BuildConfig.DEBUG) Log.d(TAG, "onCreate"); setRetainInstance(true); Bundle argsbundle = getArguments(); if(argsbundle != null) { mNotificationIntent = argsbundle.getParcelable(MainActivity.NOTIFICATION_INTENT_ID); } } private RetainedStateCallback mRetCb = null; @Override public void onAttach(Context context) { super.onAttach(context); if(BuildConfig.DEBUG) Log.d(TAG, "onAttach"); mRetCb = (RetainedStateCallback)context; if(mTimeshiftPlayer != null) { mRetCb.onNewTimeshiftPlayer(mTimeshiftPlayer); } if(getActivity() != null) { Intent aTrackIntent = new Intent(getActivity(), eu.hradio.core.audiotrackservice.AudiotrackService.class); getActivity().startService(aTrackIntent); getActivity().bindService(aTrackIntent, mSrvCon, 0); } } @Override public void onDetach() { super.onDetach(); if(BuildConfig.DEBUG) Log.d(TAG, "onDetach, isRemoving: " + isRemoving() + " : isStateSaved: " + isStateSaved()); if(mAudiotrackServiceBound && mAudiotrackService != null) { if(getActivity() != null) { getActivity().unbindService(mSrvCon); } } } @Override public void onDestroy() { super.onDestroy(); if(BuildConfig.DEBUG) Log.d(TAG, "onDestroy, isRemoving: " + isRemoving() + ", isStateSaved: " + isStateSaved() + ", Activity: " + (getActivity() != null ? "okay" : "null")); if(mTimeshiftPlayer != null) { mTimeshiftPlayer.stop(true); mTimeshiftPlayer.removeAudioDataListener(mAudiotrackService.getAudioDataListener()); } if(mAudiotrackServiceBound && mAudiotrackService != null) { if(BuildConfig.DEBUG)Log.d(TAG, "Dismissing notification, Activity: " + (getActivity() != null ? "okay" : "null")); mAudiotrackService.getNotification().dismissNotification(); if(getActivity() != null) { getActivity().unbindService(mSrvCon); getActivity().stopService(new Intent(getActivity(), eu.hradio.core.audiotrackservice.AudiotrackService.class)); //set here because onDetach will be called before onServiceDisconnected() from ServiceConnection mAudiotrackServiceBound = false; } } } TimeshiftPlayer getTimeshiftPlayer() { return mTimeshiftPlayer; } void setNotificationIntent(PendingIntent intent) { if(mAudiotrackServiceBound && mAudiotrackService != null) { mAudiotrackService.getNotification().setContentIntent(intent); } } void setNotificatinLargeIcon(Bitmap largeIcon) { if(mAudiotrackServiceBound && mAudiotrackService != null) { mAudiotrackService.getNotification().setLargeIcon(largeIcon); } } void shutdown() { if(BuildConfig.DEBUG)Log.d(TAG, "Shutting down"); if(mTimeshiftPlayer != null) { mTimeshiftPlayer.stop(true); mTimeshiftPlayer.removeAudioDataListener(mAudiotrackService.getAudioDataListener()); } if(BuildConfig.DEBUG)Log.d(TAG, "Dismissing notification, Activity: " + (getActivity() != null ? "okay" : "null")); mAudiotrackService.getNotification().dismissNotification(); if(getActivity() != null) { getActivity().unbindService(mSrvCon); getActivity().stopService(new Intent(getActivity(), eu.hradio.core.audiotrackservice.AudiotrackService.class)); } } /**/ @Override public void radioServiceStarted(Tuner tuner, RadioService radioService) { if(BuildConfig.DEBUG) Log.d(TAG, "radioServiceStarted: " + radioService.getServiceLabel()); if(mRunningSrv != null) { /* if(mRunningSrv.equalsRadioService(radioService)) { if(DEBUG)Log.d(TAG, "Same service started, switching Service: " + mRunningSrv.getServiceLabel() + " from " + mRunningSrv.getRadioServiceType().toString() + " to " + radioService.getRadioServiceType().toString()); if(mTimeshiftPlayer != null) { if(DEBUG)Log.d(TAG, "TimeshiftPlayer already running...."); ((TimeshiftPlayerPcmAu)mTimeshiftPlayer).setNewService(radioService); Radio.getInstance().stopRadioService(mRunningSrv); mRunningSrv = radioService; return; } } */ Radio.getInstance().stopRadioService(mRunningSrv); } mRunningSrv = radioService; if(mTimeshiftPlayer != null) { mTimeshiftPlayer.removeListener(this); mTimeshiftPlayer.stop(true); if(mAudiotrackServiceBound) { if(mAudiotrackService != null) { mTimeshiftPlayer.removeAudioDataListener(mAudiotrackService.getAudioDataListener()); } } mTimeshiftPlayer = null; } try { //For ShoutCast IP services a PCM TimeshiftPlayer is needed if(radioService.getRadioServiceType() == RadioServiceType.RADIOSERVICE_TYPE_IP) { mTimeshiftPlayer = TimeshiftPlayerFactory.createPcmPlayer(getActivity(), radioService); } else { mTimeshiftPlayer = TimeshiftPlayerFactory.create(getActivity(), radioService); } if(mTimeshiftPlayer != null) { mTimeshiftPlayer.addListener(this); mRetCb.onNewTimeshiftPlayer(mTimeshiftPlayer); mTimeshiftPlayer.setPlayWhenReady(); if(mAudiotrackServiceBound && mAudiotrackService != null) { mTimeshiftPlayer.addAudioDataListener(mAudiotrackService.getAudioDataListener()); Bitmap logoBmp = null; if(!radioService.getLogos().isEmpty()) { for(Visual logo : radioService.getLogos()) { if(logo.getVisualHeight() > 32 && logo.getVisualHeight() == logo.getVisualHeight()) { if(DEBUG)Log.d(TAG, "Setting NotificationIcon with: " + logo.getVisualWidth() + "x" + logo.getVisualHeight()); logoBmp = BitmapFactory.decodeByteArray(logo.getVisualData(), 0, logo.getVisualData().length); break; } } } mAudiotrackService.getNotification().setLargeIcon(logoBmp); mAudiotrackService.getNotification().setNotificationText(""); mAudiotrackService.getNotification().setNotificationTitle(radioService.getServiceLabel()); } } } catch(IOException ioE) { ioE.printStackTrace(); } } @Override public void radioServiceStopped(Tuner tuner, RadioService radioService) { if(BuildConfig.DEBUG) Log.d(TAG, "radioServiceStopped: " + radioService.getServiceLabel()); if(mAudiotrackServiceBound && mAudiotrackService != null) { // } } @Override public void tunerStatusChanged(Tuner tuner, TunerStatus tunerStatus) { } @Override public void tunerScanStarted(Tuner tuner) { } @Override public void tunerScanProgress(Tuner tuner, int i) { } @Override public void tunerScanFinished(Tuner tuner) { } @Override public void tunerScanServiceFound(Tuner tuner, RadioService radioService) { } @Override public void tunerReceptionStatistics(Tuner tuner, boolean b, ReceptionQuality receptionQuality) { } @Override public void tunerRawData(Tuner tuner, byte[] bytes) { } /* TimeshiftListener impl*/ @Override public void progress(long l, long l1) { } @Override public void sbtRealTime(long l, long l1, long l2, long l3) { } @Override public void started() { } @Override public void paused() { } @Override public void stopped() { } @Override public void textual(Textual textual) { if(textual.getType() == TextualType.METADATA_TEXTUAL_TYPE_DAB_DLS && ((TextualDabDynamicLabel)textual).hasTags()) { TextualDabDynamicLabel dl = (TextualDabDynamicLabel)textual; String itemArtist = null; String itemTitle = null; for(TextualDabDynamicLabelPlusItem dlItem : dl.getDlPlusItems()) { switch (dlItem.getDynamicLabelPlusContentType()) { case ITEM_TITLE: itemTitle = dlItem.getDlPlusContentText(); break; case ITEM_ARTIST: itemArtist = dlItem.getDlPlusContentText(); break; } } if(itemArtist != null && itemTitle != null) { mAudiotrackService.getNotification().setNotificationText(itemArtist + "\n" + itemTitle); } } } @Override public void visual(Visual visual) { } @Override public void skipItemAdded(SkipItem skipItem) { } @Override public void skipItemRemoved(SkipItem skipItem) { } /**/ public interface RetainedStateCallback { void onNewTimeshiftPlayer(TimeshiftPlayer player); } }
/* * 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 edu.cpp.iipl.util; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Map Utility to provide some basic but frequently used operations * @author Xing */ public class MapUtil { /** * Sort the Map entities according to the values in descendant order. * Refer to http://stackoverflow.com/questions/2864840/treemap-sort-by-value * It is not able to sort HashMap * @param map Map to be sorted * @param <K> Key of map entry * @param <V> Value of map entry, could be integer or float * @return Sorted map */ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) { List<Map.Entry<K, V>> list = new LinkedList<>( map.entrySet() ); Collections.sort( list, (o1, o2) -> (o2.getValue()).compareTo( o1.getValue() )); Map<K, V> result = new LinkedHashMap<>(); for (Map.Entry<K, V> entry : list) { result.put( entry.getKey(), entry.getValue() ); } return result; } /** * Update +1 to the count of word in the HashMap. * @param map HashMap to be updated * @param word String type word */ public static void updateMap(Map<String, Integer> map, String word) throws NullPointerException{ if (map.containsKey(word)) map.put(word, map.get(word)+1); // add one else map.put(word, 1); // init as one } /** * Update +n to the count of word in the HashMap. * @param map HashMap to be updated * @param word String type word * @param n Count to be added */ public static void updateMap(Map<String, Integer> map, String word, Integer n) throws NullPointerException{ if (map.containsKey(word)) map.put(word, map.get(word)+n); // add n else map.put(word, n); // init as n } /** * Calculate the sum of values in the HashMap * @param map HashMap to be calculated * @return Sum of values of the HashMap */ public static int sumMap(Map<String, Integer> map) throws NullPointerException{ int sum = 0; for (Integer value : map.values()) sum += value; return sum; } }
package com.demo.pojo; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Table(name="t_item") @Entity public class Item { private Integer id; private String itemName; private Set<Category> categories = new HashSet<>(); @GeneratedValue @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } @JoinTable(name="item_category", joinColumns={@JoinColumn(name="item_id",referencedColumnName="id")}, inverseJoinColumns={@JoinColumn(name="category_id",referencedColumnName="id")}) @ManyToMany(cascade={CascadeType.REMOVE}) public Set<Category> getCategories() { return categories; } public void setCategories(Set<Category> categories) { this.categories = categories; } }